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
use std::fmt;
use std::mem;
use std::os::raw::c_void;
use std::path::{Path, PathBuf};

use {trace, resolve, Frame, Symbol, SymbolName};

// Ok so the `//~ HACK` directives here are, well, hacks. Right now we want to
// compile on stable for serde support, but we also want to use
// #[derive(Serialize, Deserialize)] macros *along* with the
// `#[derive(RustcEncodable, RustcDecodable)]` macros. In theory both of these
// can be behind a #[cfg_attr], but that unfortunately doesn't work for two
// reasons:
//
// 1. rust-lang/rust#32957 - means the include! of this module doesn't expand
//    the RustcDecodable/RustcEncodable blocks.
// 2. serde-rs/serde#148 - means that Serialize/Deserialize won't get expanded.
//
// We just hack around it by doing #[cfg_attr] manually essentially. Our build
// script will just strip the `//~ HACKn` prefixes here if the corresponding
// feature is enabled.

/// Representation of an owned and self-contained backtrace.
///
/// This structure can be used to capture a backtrace at various points in a
/// program and later used to inspect what the backtrace was at that time.
#[derive(Clone)]
//~ HACK1 #[derive(RustcDecodable, RustcEncodable)]
//~ HACK2 #[derive(Deserialize, Serialize)]
pub struct Backtrace {
    frames: Vec<BacktraceFrame>,
}

/// Captured version of a frame in a backtrace.
///
/// This type is returned as a list from `Backtrace::frames` and represents one
/// stack frame in a captured backtrace.
#[derive(Clone)]
//~ HACK1 #[derive(RustcDecodable, RustcEncodable)]
//~ HACK2 #[derive(Deserialize, Serialize)]
pub struct BacktraceFrame {
    ip: usize,
    symbol_address: usize,
    symbols: Vec<BacktraceSymbol>,
}

/// Captured version of a symbol in a backtrace.
///
/// This type is returned as a list from `BacktraceFrame::symbols` and
/// represents the metadata for a symbol in a backtrace.
#[derive(Clone)]
//~ HACK1 #[derive(RustcDecodable, RustcEncodable)]
//~ HACK2 #[derive(Deserialize, Serialize)]
pub struct BacktraceSymbol {
    name: Option<Vec<u8>>,
    addr: Option<usize>,
    filename: Option<PathBuf>,
    lineno: Option<u32>,
}

impl Backtrace {
    /// Captures a backtrace at the callsite of this function, returning an
    /// owned representation.
    ///
    /// This function is useful for representing a backtrace as an object in
    /// Rust. This returned value can be sent across threads and printed
    /// elsewhere, and thie purpose of this value is to be entirely self
    /// contained.
    ///
    /// # Examples
    ///
    /// ```
    /// use backtrace::Backtrace;
    ///
    /// let current_backtrace = Backtrace::new();
    /// ```
    pub fn new() -> Backtrace {
        let mut frames = Vec::new();
        trace(|frame| {
            let mut symbols = Vec::new();
            resolve(frame.ip(), |symbol| {
                symbols.push(BacktraceSymbol {
                    name: symbol.name().map(|m| m.as_bytes().to_vec()),
                    addr: symbol.addr().map(|a| a as usize),
                    filename: symbol.filename().map(|m| m.to_path_buf()),
                    lineno: symbol.lineno(),
                });
            });
            frames.push(BacktraceFrame {
                ip: frame.ip() as usize,
                symbol_address: frame.symbol_address() as usize,
                symbols: symbols,
            });
            true
        });

        Backtrace { frames: frames }
    }

    /// Returns the frames from when this backtrace was captured.
    ///
    /// The first entry of this slice is likely the function `Backtrace::new`,
    /// and the last frame is likely something about how this thread or the main
    /// function started.
    pub fn frames(&self) -> &[BacktraceFrame] {
        &self.frames
    }
}

impl Frame for BacktraceFrame {
    fn ip(&self) -> *mut c_void {
        self.ip as *mut c_void
    }

    fn symbol_address(&self) -> *mut c_void {
        self.symbol_address as *mut c_void
    }
}

impl BacktraceFrame {
    /// Returns the list of symbols that this frame corresponds to.
    ///
    /// Normally there is only one symbol per frame, but sometimes if a number
    /// of functions are inlined into one frame then multiple symbols will be
    /// returned. The first symbol listed is the "innermost function", whereas
    /// the last symbol is the outermost (last caller).
    pub fn symbols(&self) -> &[BacktraceSymbol] {
        &self.symbols
    }
}

impl Symbol for BacktraceSymbol {
    fn name(&self) -> Option<SymbolName> {
        self.name.as_ref().map(|s| SymbolName::new(s))
    }

    fn addr(&self) -> Option<*mut c_void> {
        self.addr.map(|s| s as *mut c_void)
    }

    fn filename(&self) -> Option<&Path> {
        self.filename.as_ref().map(|p| &**p)
    }

    fn lineno(&self) -> Option<u32> {
        self.lineno
    }
}

impl fmt::Debug for Backtrace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let hex_width = mem::size_of::<usize>() * 2 + 2;

        for (i, frame) in self.frames().iter().enumerate() {
            let ip = frame.ip();
            try!(write!(f, "frame #{:<2} - {:#02$x}", i, ip as usize, hex_width));

            if frame.symbols().len() == 0 {
                try!(writeln!(f, " - <no info>"));
                continue
            }

            for (j, symbol) in frame.symbols().iter().enumerate() {
                if j != 0 {
                    for _ in 0..7 + 2 + 3 + hex_width {
                        try!(write!(f, " "));
                    }
                }

                if let Some(name) = symbol.name() {
                    try!(write!(f, " - {}", name));
                } else {
                    try!(write!(f, " - <unknown>"));
                }
                if let Some(file) = symbol.filename() {
                    if let Some(l) = symbol.lineno() {
                        try!(write!(f, "\n{:13}{:4$}@ {}:{}", "", "",
                                    file.display(), l, hex_width));
                    }
                }
                try!(writeln!(f, ""));
            }
        }

        Ok(())
    }
}