std/sys/personality/dwarf/
mod.rs

1//! Utilities for parsing DWARF-encoded data streams.
2//! See <http://www.dwarfstd.org>,
3//! DWARF-4 standard, Section 7 - "Data Representation"
4
5// This module is used only by x86_64-pc-windows-gnu for now, but we
6// are compiling it everywhere to avoid regressions.
7#![allow(unused)]
8#![forbid(unsafe_op_in_unsafe_fn)]
9
10#[cfg(test)]
11mod tests;
12
13pub mod eh;
14
15use core::mem;
16
17pub struct DwarfReader {
18    pub ptr: *const u8,
19}
20
21impl DwarfReader {
22    pub fn new(ptr: *const u8) -> DwarfReader {
23        DwarfReader { ptr }
24    }
25
26    /// Read a type T and then bump the pointer by that amount.
27    ///
28    /// DWARF streams are "packed", so all types must be read at align 1.
29    pub unsafe fn read<T: Copy>(&mut self) -> T {
30        unsafe {
31            let result = self.ptr.cast::<T>().read_unaligned();
32            self.ptr = self.ptr.byte_add(mem::size_of::<T>());
33            result
34        }
35    }
36
37    /// ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable Length Data".
38    pub unsafe fn read_uleb128(&mut self) -> u64 {
39        let mut shift: usize = 0;
40        let mut result: u64 = 0;
41        let mut byte: u8;
42        loop {
43            byte = unsafe { self.read::<u8>() };
44            result |= ((byte & 0x7F) as u64) << shift;
45            shift += 7;
46            if byte & 0x80 == 0 {
47                break;
48            }
49        }
50        result
51    }
52
53    pub unsafe fn read_sleb128(&mut self) -> i64 {
54        let mut shift: u32 = 0;
55        let mut result: u64 = 0;
56        let mut byte: u8;
57        loop {
58            byte = unsafe { self.read::<u8>() };
59            result |= ((byte & 0x7F) as u64) << shift;
60            shift += 7;
61            if byte & 0x80 == 0 {
62                break;
63            }
64        }
65        // sign-extend
66        if shift < u64::BITS && (byte & 0x40) != 0 {
67            result |= (!0 as u64) << shift;
68        }
69        result as i64
70    }
71}