Debian Codegraph @

src/main.rs

raw symbols SCIP
1 // Based on the gimli 0.16.1 dwarfdump.rs example
2 use anyhow::{anyhow, bail, Error, Result};
3 use fallible_iterator::{convert, FallibleIterator};
4 use gimli::{AttributeValue, Endianity, Reader};
5 use object::{Object, ObjectSection};
6 use serde::ser::SerializeMap;
7 use serde::{Serialize, Serializer};
8 use std::borrow::{Borrow, Cow};
9 use std::collections::BTreeSet;
10 use std::fs;
11 use std::path::PathBuf;
12 use structopt::StructOpt;
13 use typed_arena::Arena;
14
15 #[derive(Debug, Serialize)]
16 struct Unit {
17 comp_dir: String,
18 comp_name: String,
19 }
20
21 #[derive(Debug, Default, Serialize)]
22 struct ObjectInfo {
23 units: Vec<Unit>,
24 // Note that we use a BTreeSet so that the output order is consistent across
25 // runs.
26 external_files: BTreeSet<String>,
27 }
28
29 fn list_file<E: Endianity>(file: &object::File, endian: E) -> Result<ObjectInfo> {
30 let arena = Arena::new();
31
32 fn load_section<'a, 'file, 'input, S, E>(
33 arena: &'a Arena<Cow<'file, [u8]>>,
34 file: &'file object::File<'input>,
35 endian: E,
36 ) -> S
37 where
38 S: gimli::Section<gimli::EndianSlice<'a, E>>,
39 E: gimli::Endianity,
40 'file: 'input,
41 'a: 'file,
42 {
43 let data = file
44 .section_by_name(S::section_name())
45 .and_then(|section| section.uncompressed_data().ok())
46 .unwrap_or(Cow::Borrowed(&[]));
47 let data_ref = (*arena.alloc(data)).borrow();
48 S::from(gimli::EndianSlice::new(data_ref, endian))
49 }
50
51 // Variables representing sections of the file. The type of each is inferred from its use in the
52 // functions below.
53 let debug_abbrev = &load_section(&arena, file, endian);
54 let debug_info = &load_section(&arena, file, endian);
55 let debug_str = &load_section(&arena, file, endian);
56 let debug_line_str = &load_section(&arena, file, endian);
57 let debug_line = &load_section(&arena, file, endian);
58
59 list_info(
60 debug_info,
61 debug_abbrev,
62 debug_str,
63 debug_line_str,
64 debug_line,
65 )
66 }
67
68 fn list_info<R: Reader>(
69 debug_info: &gimli::DebugInfo<R>,
70 debug_abbrev: &gimli::DebugAbbrev<R>,
71 debug_str: &gimli::DebugStr<R>,
72 debug_line: &gimli::DebugLine<R>,
73 debug_line_str: &gimli::DebugLineStr<R>,
74 ) -> Result<ObjectInfo> {
75 let mut info = ObjectInfo::default();
76 let dw_units = debug_info.units().collect::<Vec<_>>().unwrap();
77 for u in dw_units {
78 let abbrevs = u.abbreviations(debug_abbrev)?;
79 info.units.append(&mut list_entries(
80 &mut info.external_files,
81 u.entries(&abbrevs),
82 u.address_size(),
83 debug_str,
84 debug_line_str,
85 debug_line,
86 )?);
87 }
88 Ok(info)
89 }
90
91 fn get_attr_string<R: Reader>(
92 dw_attr_value: &gimli::AttributeValue<R>,
93 debug_str: &gimli::DebugStr<R>,
94 debug_line_str: &gimli::DebugLineStr<R>,
95 ) -> Result<(R, String)> {
96 let reader = if let Some(r) = dw_attr_value.string_value(debug_str) {
97 r
98 } else {
99 match dw_attr_value {
100 AttributeValue::DebugLineStrRef(offset) => debug_line_str
101 .get_str(*offset)
102 .expect("attribute value should be set"),
103 AttributeValue::DebugStrRefSup(_) => {
104 bail!("attribute in supplemental file");
105 }
106 _ => bail!("attribute with unexpected type"),
107 }
108 };
109
110 let string = reader.to_string()?.into_owned();
111 Ok((reader, string))
112 }
113
114 fn entry_attr_value<R: Reader>(
115 entry: &gimli::DebuggingInformationEntry<R>,
116 attr_name: gimli::constants::DwAt,
117 debug_str: &gimli::DebugStr<R>,
118 debug_line_str: &gimli::DebugLineStr<R>,
119 ) -> Result<Option<(R, String)>> {
120 let dw_attr = if let Some(it) = entry.attr(attr_name)? {
121 it
122 } else {
123 return Ok(None);
124 };
125
126 get_attr_string(&dw_attr.value(), debug_str, debug_line_str).map(Some)
127 }
128
129 fn collect_external_files<R: Reader>(
130 external_files: &mut BTreeSet<String>,
131 entry: &gimli::DebuggingInformationEntry<R>,
132 address_size: u8,
133 debug_str: &gimli::DebugStr<R>,
134 debug_line_str: &gimli::DebugLineStr<R>,
135 debug_line: &gimli::DebugLine<R>,
136 comp_dir_reader: R,
137 comp_name_reader: R,
138 ) -> Result<()> {
139 let program = if let Some(gimli::AttributeValue::DebugLineRef(offs)) =
140 entry.attr_value(gimli::DW_AT_stmt_list)?
141 {
142 debug_line.program(
143 offs,
144 address_size,
145 Some(comp_dir_reader),
146 Some(comp_name_reader),
147 )?
148 } else {
149 return Ok(());
150 };
151
152 let header = program.header();
153 for file_entry in header.file_names() {
154 if file_entry.directory_index() == 0 {
155 // Directory index of 0 means it's from the current CU's directory,
156 // so skip it.
157 continue;
158 }
159
160 let mut name =
161 PathBuf::from(get_attr_string(&file_entry.path_name(), debug_str, debug_line_str)?.1);
162
163 if let Some(dir_attr) = file_entry.directory(header) {
164 let (_, dir) = get_attr_string(&dir_attr, debug_str, debug_line_str)?;
165 name = PathBuf::from(dir).join(name);
166 }
167
168 if name.is_absolute() {
169 // This shouldn't be invalid UTF-8, because it just came from some
170 // String instances already.
171 external_files.insert(name.into_os_string().into_string().unwrap());
172 }
173 }
174
175 Ok(())
176 }
177
178 fn list_entries<R: Reader>(
179 external_files: &mut BTreeSet<String>,
180 mut entries: gimli::EntriesCursor<R>,
181 address_size: u8,
182 debug_str: &gimli::DebugStr<R>,
183 debug_line_str: &gimli::DebugLineStr<R>,
184 debug_line: &gimli::DebugLine<R>,
185 ) -> Result<Vec<Unit>> {
186 let mut depth = 0;
187 let mut v = Vec::new();
188 while let Some((delta_depth, entry)) = entries.next_dfs()? {
189 depth += delta_depth;
190 assert!(depth >= 0);
191 if depth > 0 {
192 continue;
193 }
194
195 if entry.tag() == gimli::DW_TAG_compile_unit || entry.tag() == gimli::DW_TAG_type_unit {
196 let (comp_dir_reader, comp_dir) =
197 entry_attr_value(entry, gimli::DW_AT_comp_dir, debug_str, debug_line_str)?
198 .ok_or_else(|| anyhow!("Unable to parse or missing DW_AT_comp_dir"))?;
199
200 let at_name = entry_attr_value(entry, gimli::DW_AT_name, debug_str, debug_line_str);
201 let (comp_name_reader, comp_name) = match at_name {
202 Ok(Some(result)) => result,
203 Ok(None) => {
204 eprintln!("Warning: unit without name, skipping it");
205 continue;
206 }
207 Err(err) => {
208 eprintln!("Warning: {}", err);
209 continue;
210 }
211 };
212
213 if comp_name == "<artificial>" {
214 eprintln!("Warning: Artificial name in compile unit, probably DWARF debug information has been generated with LTO")
215 } else {
216 v.push(Unit {
217 comp_dir,
218 comp_name,
219 });
220 }
221
222 if let Err(err) = collect_external_files(
223 external_files,
224 entry,
225 address_size,
226 debug_str,
227 debug_line_str,
228 debug_line,
229 comp_dir_reader,
230 comp_name_reader,
231 ) {
232 eprintln!("Warning: collecting external files: {}", err);
233 }
234 }
235 }
236 Ok(v)
237 }
238
239 #[derive(StructOpt, Debug)]
240 struct Opt {
241 #[structopt(short, long, parse(from_os_str))]
242 /// File to write json output to
243 output: Option<PathBuf>,
244 #[structopt(long = "strip-prefix", short, long)]
245 /// Strip given prefix from comp_dir paths
246 strip_prefix: Option<String>,
247 file: Vec<String>,
248 }
249
250 fn process_file<E: Endianity>(
251 file: &object::File,
252 endian: E,
253 strip_prefix: Option<&String>,
254 ) -> Result<ObjectInfo> {
255 let mut info = list_file(file, endian)?;
256 if let Some(strip) = strip_prefix {
257 for u in info.units.iter_mut() {
258 if u.comp_dir.starts_with(strip) {
259 u.comp_dir = (&u.comp_dir[strip.len()..]).to_string();
260 }
261 }
262 }
263
264 Ok(info)
265 }
266
267 fn serialize<S, K, V, I>(s: S, mut iter: I, len: Option<usize>) -> Result<()>
268 where
269 S: Serializer,
270 S::Error: 'static + Send + Sync,
271 K: Serialize,
272 V: Serialize,
273 I: FallibleIterator<Item = (K, V), Error = Error>,
274 {
275 let mut map = s.serialize_map(len)?;
276 while let Some((k, v)) = iter.next()? {
277 map.serialize_entry(&k, &v)?;
278 }
279 map.end()?;
280 Ok(())
281 }
282
283 fn main() -> Result<()> {
284 let opt = Opt::from_args();
285
286 let data = convert(opt.file.iter().map(|f| -> Result<_> {
287 let file = fs::File::open(&f)?;
288 let file = unsafe { memmap2::Mmap::map(&file) }?;
289 let file = object::File::parse(&*file).map_err(|e| anyhow!(e))?;
290
291 let endian = if file.is_little_endian() {
292 gimli::RunTimeEndian::Little
293 } else {
294 gimli::RunTimeEndian::Big
295 };
296
297 let info = process_file(&file, endian, opt.strip_prefix.as_ref())?;
298 Ok((f.clone(), info))
299 }));
300
301 if let Some(output) = &opt.output {
302 let file = fs::OpenOptions::new()
303 .write(true)
304 .create_new(true)
305 .open(output)?;
306 let mut s = serde_json::Serializer::new(&file);
307 if let Err(e) = serialize(&mut s, data, Some(opt.file.len())) {
308 fs::remove_file(output)?;
309 return Err(e);
310 }
311 } else {
312 let mut s = serde_json::Serializer::pretty(std::io::stdout());
313 serialize(&mut s, data, Some(opt.file.len()))?;
314 }
315
316 Ok(())
317 }