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
use regex::Regex;
use std::hash::{Hash, Hasher};

use crate::error;
use crate::mappings::{MappedFiles, MappedFilesExt};

/// `StacktraceEntry` struct represents the information about one line of the stack trace.
#[derive(Clone, Debug, Default)]
pub struct StacktraceEntry {
    /// Function address
    pub address: u64,
    /// Function name
    pub function: String,
    /// Module name
    pub module: String,
    /// Offset in module
    pub offset: u64,
    /// Debug information
    pub debug: DebugInfo,
}

/// `FrameDebug` struct represents the debug information of one frame in stack trace.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct DebugInfo {
    /// Source file.
    pub file: String,
    /// Source line.
    pub line: u64,
    /// Source column.
    pub column: u64,
}

impl PartialEq for StacktraceEntry {
    fn eq(&self, other: &Self) -> bool {
        if !self.debug.file.is_empty() && !other.debug.file.is_empty() {
            return self.debug == other.debug;
        }
        if !self.module.is_empty()
            && !other.module.is_empty()
            && self.offset != 0
            && other.offset != 0
        {
            return self.module == other.module && self.offset == other.offset;
        }

        self.address == other.address
    }
}

impl Eq for StacktraceEntry {}

impl Hash for StacktraceEntry {
    fn hash<H: Hasher>(&self, state: &mut H) {
        if !self.debug.file.is_empty() {
            self.debug.file.hash(state);
            self.debug.line.hash(state);
            self.debug.column.hash(state);
            return;
        }
        if !self.module.is_empty() && self.offset != 0 {
            self.module.hash(state);
            self.offset.hash(state);
            return;
        }

        self.address.hash(state);
    }
}

impl StacktraceEntry {
    /// Returns 'StacktraceEntry' struct
    ///
    /// # Arguments
    ///
    /// * 'entry' - one line of stacktrace from gdb
    pub fn new<T: AsRef<str>>(entry: T) -> error::Result<StacktraceEntry> {
        let mut stentry = StacktraceEntry::default();

        // NOTE: the order of applying regexps is important.
        // 1. GDB source+line+column
        let re =
            Regex::new(r"^ *#[0-9]+ *(?:0x([0-9a-f]+) +in)? *(.+) +at +(.+):(\d+):(\d+)").unwrap();
        if let Some(caps) = re.captures(entry.as_ref()) {
            // Get address (optional).
            if let Some(address) = caps.get(1) {
                stentry.address = u64::from_str_radix(address.as_str(), 16)?;
            }
            // Get function name.
            stentry.function = caps.get(2).unwrap().as_str().trim().to_string();
            // Get source file.
            stentry.debug.file = caps.get(3).unwrap().as_str().trim().to_string();
            // Get source line.
            stentry.debug.line = caps.get(4).unwrap().as_str().parse::<u64>()?;
            // Get source column.
            stentry.debug.column = caps.get(5).unwrap().as_str().parse::<u64>()?;

            return Ok(stentry);
        }

        // 2. GDB source+line
        let re = Regex::new(r"^ *#[0-9]+ *(?:0x([0-9a-f]+) +in)? *(.+) +at +(.+):(\d+)").unwrap();
        if let Some(caps) = re.captures(entry.as_ref()) {
            // Get address (optional).
            if let Some(address) = caps.get(1) {
                stentry.address = u64::from_str_radix(address.as_str(), 16)?;
            }
            // Get function name.
            stentry.function = caps.get(2).unwrap().as_str().trim().to_string();
            // Get source file.
            stentry.debug.file = caps.get(3).unwrap().as_str().trim().to_string();
            // Get source line.
            stentry.debug.line = caps.get(4).unwrap().as_str().parse::<u64>()?;

            return Ok(stentry);
        }

        // 3. GDB source
        let re = Regex::new(r"^ *#[0-9]+ *(?:0x([0-9a-f]+) +in)? *(.+) +at +(.+)").unwrap();
        if let Some(caps) = re.captures(entry.as_ref()) {
            // Get address (optional).
            if let Some(address) = caps.get(1) {
                stentry.address = u64::from_str_radix(address.as_str(), 16)?;
            }
            // Get function name.
            stentry.function = caps.get(2).unwrap().as_str().trim().to_string();
            // Get source file.
            stentry.debug.file = caps.get(3).unwrap().as_str().trim().to_string();

            return Ok(stentry);
        }

        // 4. GDB from library (address is optional)
        let re = Regex::new(r"^ *#[0-9]+ *(?:0x([0-9a-f]+) +in)? *(.+) +from +(.+)").unwrap();
        if let Some(caps) = re.captures(entry.as_ref()) {
            // Get address (optional).
            if let Some(address) = caps.get(1) {
                stentry.address = u64::from_str_radix(address.as_str(), 16)?;
            }
            // Get function name.
            stentry.function = caps.get(2).unwrap().as_str().trim().to_string();
            // Get module name.
            stentry.module = caps.get(3).unwrap().as_str().trim().to_string();

            return Ok(stentry);
        }

        // 5. GDB no source (address is optional)
        let re = Regex::new(r"^ *#[0-9]+ *(?:0x([0-9a-f]+) +in)? *(.+)").unwrap();
        if let Some(caps) = re.captures(entry.as_ref()) {
            // Get address (optional).
            if let Some(address) = caps.get(1) {
                stentry.address = u64::from_str_radix(address.as_str(), 16)?;
            }
            // Get function name.
            stentry.function = caps.get(2).unwrap().as_str().trim().to_string();

            return Ok(stentry);
        }

        return Err(error::Error::StacktraceParse(
            format!("Couldn't parse stack trace entry: {}", entry.as_ref()).to_string(),
        ));
    }
}

/// Represents the information about stack trace
pub type Stacktrace = Vec<StacktraceEntry>;

pub trait StacktraceExt {
    /// Get stack trace as a string and converts it into 'Stacktrace'
    ///
    /// # Arguments
    ///
    /// * 'trace' - stack trace from gdb
    ///
    /// # Return value
    ///
    /// The return value is a 'Stacktrace' struct
    fn from_gdb<T: AsRef<str>>(trace: T) -> error::Result<Stacktrace>;

    /// Compute module offsets for stack trace entries based on mapped files.
    /// Gdb doesn't print module and offset in stack trace.
    ///
    /// # Arguments
    ///
    /// * 'mappings' - information about mapped files
    fn compute_module_offsets(&mut self, mappings: &MappedFiles);
}

impl StacktraceExt for Stacktrace {
    fn from_gdb<T: AsRef<str>>(trace: T) -> error::Result<Stacktrace> {
        let mut stacktrace = Stacktrace::new();
        let mut entries = trace
            .as_ref()
            .lines()
            .map(|s| s.trim().to_string())
            .collect::<Vec<String>>();
        entries.retain(|trace| !trace.is_empty());

        for x in entries.iter() {
            stacktrace.push(StacktraceEntry::new(&x.clone())?);
        }
        Ok(stacktrace)
    }

    fn compute_module_offsets(&mut self, mappings: &MappedFiles) {
        self.iter_mut().for_each(|x| {
            if let Some(y) = mappings.find(x.address) {
                x.offset = x.address - y.start + y.offset;
                if !y.name.is_empty() {
                    x.module = y.name;
                }
            }
        });
    }
}