sys-rs 0.1.1

ptrace-based Linux system tool reimplementations: strace, gcov, addr2line, debugger
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use gimli;
use goblin::elf::header::{ELFDATA2LSB, ELFDATA2MSB};
use nix::errno::Errno;
use std::{
    collections::HashMap,
    fmt,
    fs::File,
    io::{BufRead, BufReader},
    path::PathBuf,
};

use crate::{
    diag::{Error, Result},
    process,
};

const FIRST_UNSUPPORTED_DWARF_VERSION: u16 = 5;

/// Information about a source line mapped from an address.
///
/// `LineInfo` contains the instruction address, the source file path, and
/// the 1-based line number. It provides helpers for retrieving the line's
/// text and formatting it for display.
pub struct LineInfo {
    addr: u64,
    path: PathBuf,
    line: usize,
}

impl LineInfo {
    /// Create a new `LineInfo` from an address, path and 1-based line number.
    ///
    /// # Arguments
    ///
    /// * `addr` - The instruction address associated with the source line.
    /// * `path` - The path to the source file.
    /// * `line` - The 1-based line number in the file.
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `line` cannot be converted to a
    /// `usize`.
    ///
    /// # Returns
    ///
    /// Returns `Ok(LineInfo)` on success with the provided address, path,
    /// and converted line number. Returns `Err` if the `line` argument
    /// cannot be converted to `usize`.
    pub fn new(addr: u64, path: PathBuf, line: u64) -> Result<Self> {
        Ok(Self {
            addr,
            path,
            line: usize::try_from(line)?,
        })
    }

    #[must_use]
    /// Return the source path as a displayable `String`.
    ///
    /// # Returns
    ///
    /// A `String` containing the display representation of the stored path.
    pub fn path(&self) -> String {
        self.path.display().to_string()
    }

    #[must_use]
    /// Return the 1-based source line number.
    ///
    /// # Returns
    ///
    /// The 1-based source line number stored in this `LineInfo`.
    pub fn line(&self) -> usize {
        self.line
    }

    fn read(&self) -> Result<String> {
        let file = File::open(&self.path)?;
        let reader = BufReader::new(file);

        let mut lines = reader.lines();

        let line = lines
            .nth(self.line - 1)
            .ok_or_else(|| Error::from(Errno::ENODATA))??;
        Ok(line)
    }
}

impl fmt::Display for LineInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let line = self.read().map_err(|_| fmt::Error)?;
        write!(
            f,
            "{:#x}: {}:{} | {}",
            self.addr,
            self.path.display(),
            self.line,
            line
        )
    }
}

type AddressRange = Vec<(u64, u64)>;
type DebugArangesMap = HashMap<gimli::DebugInfoOffset, AddressRange>;
type SectionData<'a> = gimli::EndianSlice<'a, gimli::RunTimeEndian>;

/// DWARF debugging information parsed from an ELF image.
///
/// `Dwarf` encapsulates parsed DWARF sections and a mapping from compile
/// unit offsets to address ranges. It provides helpers to build the DWARF
/// representation from an executable and resolve addresses to source
/// locations.
pub struct Dwarf<'a> {
    data: gimli::Dwarf<SectionData<'a>>,
    aranges: DebugArangesMap,
    offset: u64,
}

impl<'a> Dwarf<'a> {
    /// Builds a `Dwarf` struct from the given process information.
    ///
    /// # Arguments
    ///
    /// * `process` - The process information.
    ///
    /// # Errors
    ///
    /// Returns an `Err` upon any failure to retrieve ELF sections or parse DWARF format.
    ///
    /// # Returns
    ///
    /// Returns a `Dwarf` struct on success, wrapped in an `Ok` variant. Returns an error on failure, wrapped in an `Err` variant.
    pub fn build(process: &'a process::Info) -> Result<Self> {
        let endianness = match process.endianness() {
            ELFDATA2LSB => Ok(gimli::RunTimeEndian::Little),
            ELFDATA2MSB => Ok(gimli::RunTimeEndian::Big),
            _ => Err(Error::from(Errno::ENOEXEC)),
        }?;

        let debug_ranges = gimli::DebugRanges::new(
            Self::get_section(".debug_ranges", process).unwrap_or(&[]),
            endianness,
        );
        let debug_rnglists = gimli::DebugRngLists::new(
            Self::get_section(".debug_rnglists", process).unwrap_or(&[]),
            endianness,
        );
        let ranges = gimli::RangeLists::new(debug_ranges, debug_rnglists);
        let data = gimli::Dwarf {
            debug_abbrev: gimli::DebugAbbrev::new(
                Self::get_section(".debug_abbrev", process)?,
                endianness,
            ),
            debug_info: gimli::DebugInfo::new(
                Self::get_section(".debug_info", process)?,
                endianness,
            ),
            debug_line: gimli::DebugLine::new(
                Self::get_section(".debug_line", process)?,
                endianness,
            ),
            debug_str: gimli::DebugStr::new(
                Self::get_section(".debug_str", process)?,
                endianness,
            ),
            ranges,
            ..Default::default()
        };

        let aranges = Self::build_aranges(&data)?;
        let offset = process.offset();

        Ok(Self {
            data,
            aranges,
            offset,
        })
    }

    fn get_section(
        section_name: &'a str,
        process: &'a process::Info,
    ) -> Result<&'a [u8]> {
        process
            .get_section_data(section_name)?
            .ok_or_else(|| Error::from(Errno::ENODATA))
    }

    fn build_aranges(
        dwarf: &gimli::Dwarf<gimli::EndianSlice<gimli::RunTimeEndian>>,
    ) -> Result<HashMap<gimli::DebugInfoOffset, Vec<(u64, u64)>>> {
        let mut aranges = HashMap::new();
        let mut iter = dwarf.units();
        while let Some(unit_header) = iter.next()? {
            if unit_header.version() >= FIRST_UNSUPPORTED_DWARF_VERSION {
                Err(Errno::ENOEXEC)?;
            }

            let mut unit_ranges = Vec::new();
            let unit = dwarf.unit(unit_header)?;
            let mut entries = unit.entries();
            while let Some((_, entry)) = entries.next_dfs()? {
                let mut attrs = entry.attrs();
                let mut low_pc = None;
                let mut high_pc = None;
                let mut high_pc_offset = None;
                let mut ranges_offset = None;
                while let Some(attr) = attrs.next()? {
                    match attr.name() {
                        gimli::DW_AT_low_pc => {
                            if let gimli::AttributeValue::Addr(addr) = attr.value() {
                                low_pc = Some(addr);
                            }
                        }
                        gimli::DW_AT_high_pc => match attr.value() {
                            gimli::AttributeValue::Addr(val) => high_pc = Some(val),
                            gimli::AttributeValue::Udata(val) => {
                                high_pc_offset = Some(val);
                            }
                            _ => Err(Error::from(Errno::ENODATA))?,
                        },
                        gimli::DW_AT_ranges => {
                            if let gimli::AttributeValue::RangeListsRef(val) =
                                attr.value()
                            {
                                ranges_offset = Some(val);
                            }
                        }
                        _ => {}
                    }
                }

                if let (Some(low_pc), Some(high_pc)) = (low_pc, high_pc) {
                    unit_ranges.push((low_pc, high_pc));
                } else if let (Some(low_pc), Some(high_pc_offset)) =
                    (low_pc, high_pc_offset)
                {
                    unit_ranges.push((low_pc, (low_pc + high_pc_offset)));
                } else if let Some(ranges_offset) = ranges_offset {
                    let offset = dwarf.ranges_offset_from_raw(&unit, ranges_offset);
                    let mut iter = dwarf.ranges(&unit, offset)?;
                    while let Some(range) = iter.next()? {
                        unit_ranges.push((range.begin, range.end));
                    }
                }
            }

            let offset = unit_header
                .offset()
                .as_debug_info_offset()
                .ok_or_else(|| Error::from(Errno::ENODATA))?;
            aranges.insert(offset, unit_ranges);
        }

        Ok(aranges)
    }

    fn is_addr_in_unit<R: gimli::Reader<Offset = usize>>(
        &self,
        addr: u64,
        unit_header: &gimli::UnitHeader<R>,
    ) -> Result<bool> {
        let offset = unit_header
            .offset()
            .as_debug_info_offset()
            .ok_or_else(|| Error::from(Errno::ENODATA))?;

        self.aranges
            .get(&offset)
            .map(|ranges| {
                ranges
                    .iter()
                    .any(|(start, end)| (*start..*end).contains(&addr))
            })
            .ok_or_else(|| Error::from(Errno::ENODATA))
    }

    fn path_from_row(
        &self,
        unit_header: &gimli::UnitHeader<SectionData<'_>>,
        program_header: &gimli::LineProgramHeader<SectionData<'_>>,
        row: &gimli::LineRow,
    ) -> Result<PathBuf> {
        let mut path = PathBuf::new();

        let unit = self.data.unit(*unit_header)?;
        if let Some(dir) = unit.comp_dir {
            path.push(dir.to_string_lossy().into_owned());
        }

        let file = row
            .file(program_header)
            .ok_or_else(|| Error::from(Errno::ENODATA))?;
        if file.directory_index() != 0 {
            if let Some(dir) = file.directory(program_header) {
                let dir_path = self
                    .data
                    .attr_string(&unit, dir)?
                    .to_string_lossy()
                    .into_owned();
                path.push(dir_path);
            }
        }

        let file_path = self
            .data
            .attr_string(&unit, file.path_name())?
            .to_string_lossy()
            .into_owned();
        path.push(file_path);

        Ok(path)
    }

    fn info_from_row(
        &self,
        unit_header: &gimli::UnitHeader<SectionData<'_>>,
        program_header: &gimli::LineProgramHeader<SectionData<'_>>,
        row: &gimli::LineRow,
    ) -> Result<LineInfo> {
        let line = row.line().ok_or_else(|| Error::from(Errno::ENODATA))?;

        let line = line.get();
        let path = self.path_from_row(unit_header, program_header, row)?;
        LineInfo::new(row.address() + self.offset, path, line)
    }

    fn info_from_unit(
        &self,
        addr: u64,
        unit_header: &gimli::UnitHeader<SectionData<'_>>,
    ) -> Result<Option<LineInfo>> {
        let mut info = None;

        let unit = self.data.unit(*unit_header)?;
        if let Some(program) = unit.line_program {
            let mut rows = program.rows();
            while let Some((program_header, row)) = rows.next_row()? {
                if !row.is_stmt() {
                    continue;
                }

                if addr != row.address() {
                    continue;
                }

                info = Some(self.info_from_row(unit_header, program_header, row)?);
                break;
            }
        }

        Ok(info)
    }

    /// Resolves the source file name and line number for a given address in the binary.
    ///
    /// # Arguments
    ///
    /// * `addr`: The address in the binary's address space.
    ///
    /// # Errors
    ///
    /// Returns an error if there's any failure in reading or parsing the DWARF debug information.
    ///
    /// # Returns
    ///
    /// - `Ok(Some(LineInfo))`: The resolved source file name and line number.
    /// - `Ok(None)`: The address does not correspond to any source line information.
    /// - `Err`: Error reading or parsing the DWARF information.
    pub fn addr2line(&self, addr: u64) -> Result<Option<LineInfo>> {
        let addr = addr - self.offset;

        let mut info: Option<LineInfo> = None;
        let mut iter = self.data.units();
        while let Some(unit_header) = iter.next()? {
            if !self.is_addr_in_unit(addr, &unit_header)? {
                continue;
            }

            info = self.info_from_unit(addr, &unit_header)?;
            if info.is_some() {
                break;
            }
        }

        Ok(info)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use gimli::{
        DebugAbbrev, DebugInfo, DebugLine, DebugRanges, DebugRngLists, DebugStr,
        RangeLists, RunTimeEndian,
    };
    use std::{collections::HashMap, io::Write};

    use crate::diag::Result;

    #[test]
    fn test_line_info_new() {
        let path = PathBuf::from("/path/to/file.rs");
        let line_info = LineInfo::new(0x1234, path.clone(), 42)
            .expect("Failed to create LineInfo");
        assert_eq!(line_info.addr, 0x1234);
        assert_eq!(line_info.path, path);
        assert_eq!(line_info.line, 42);
    }

    #[test]
    fn test_line_info_path() {
        let path = PathBuf::from("/path/to/file.rs");
        let line_info = LineInfo::new(0x1234, path.clone(), 42)
            .expect("Failed to create LineInfo");
        assert_eq!(line_info.path(), "/path/to/file.rs");
    }

    #[test]
    fn test_line_info_line() {
        let path = PathBuf::from("/path/to/file.rs");
        let line_info =
            LineInfo::new(0x1234, path, 42).expect("Failed to create LineInfo");
        assert_eq!(line_info.line(), 42);
    }

    #[test]
    fn test_line_info_display() {
        let mut tmpfile =
            tempfile::NamedTempFile::new().expect("Failed to create temp file");
        for i in 1..100 {
            writeln!(tmpfile, "line {}", i).expect("Failed to write to temp file");
        }
        let path = tmpfile.path().to_path_buf();
        let line_info = LineInfo::new(0x1234, path.clone(), 42)
            .expect("Failed to create LineInfo");
        let display = format!("{}", line_info);
        assert!(display.contains("0x1234"));
        assert!(
            display.contains(path.to_str().expect("Failed to convert path to str"))
        );
        assert!(display.contains("42"));
    }

    #[test]
    fn test_build_aranges_empty() -> Result<()> {
        let endian = RunTimeEndian::Little;
        let data = gimli::Dwarf {
            debug_abbrev: DebugAbbrev::new(&[], endian),
            debug_info: DebugInfo::new(&[], endian),
            debug_line: DebugLine::new(&[], endian),
            debug_str: DebugStr::new(&[], endian),
            ranges: RangeLists::new(
                DebugRanges::new(&[], endian),
                DebugRngLists::new(&[], endian),
            ),
            ..Default::default()
        };

        let map = Dwarf::build_aranges(&data)?;
        assert!(map.is_empty());
        Ok(())
    }

    #[test]
    fn test_addr2line_empty_returns_none() -> Result<()> {
        let endian = RunTimeEndian::Little;
        let data = gimli::Dwarf {
            debug_abbrev: DebugAbbrev::new(&[], endian),
            debug_info: DebugInfo::new(&[], endian),
            debug_line: DebugLine::new(&[], endian),
            debug_str: DebugStr::new(&[], endian),
            ranges: RangeLists::new(
                DebugRanges::new(&[], endian),
                DebugRngLists::new(&[], endian),
            ),
            ..Default::default()
        };

        let dwarf = Dwarf {
            data,
            aranges: HashMap::new(),
            offset: 0,
        };
        let res = dwarf.addr2line(0x1000)?;
        assert!(res.is_none());
        Ok(())
    }
}