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
use crate::env;
use crate::io;
use crate::io::prelude::*;
use crate::mem;
use crate::path::{self, Path};
use crate::ptr;
use crate::sync::atomic::{self, Ordering};
use crate::sys::mutex::Mutex;
use backtrace::{BytesOrWideString, Frame, Symbol};
pub const HEX_WIDTH: usize = 2 + 2 * mem::size_of::<usize>();
const MAX_NB_FRAMES: usize = 100;
pub fn print(w: &mut dyn Write, format: PrintFormat) -> io::Result<()> {
static LOCK: Mutex = Mutex::new();
if cfg!(test) {
return Ok(());
}
unsafe {
LOCK.lock();
let res = _print(w, format);
LOCK.unlock();
res
}
}
fn _print(w: &mut dyn Write, format: PrintFormat) -> io::Result<()> {
writeln!(w, "stack backtrace:")?;
let mut printer = Printer::new(format, w);
unsafe {
backtrace::trace_unsynchronized(|frame| {
let mut hit = false;
backtrace::resolve_frame_unsynchronized(frame, |symbol| {
hit = true;
printer.output(frame, Some(symbol));
});
if !hit {
printer.output(frame, None);
}
!printer.done
});
}
if printer.skipped {
writeln!(
w,
"note: Some details are omitted, \
run with `RUST_BACKTRACE=full` for a verbose backtrace."
)?;
}
Ok(())
}
#[inline(never)]
pub fn __rust_begin_short_backtrace<F, T>(f: F) -> T
where
F: FnOnce() -> T,
F: Send,
T: Send,
{
f()
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum PrintFormat {
Short = 2,
Full = 3,
}
pub fn log_enabled() -> Option<PrintFormat> {
static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0);
match ENABLED.load(Ordering::SeqCst) {
0 => {}
1 => return None,
2 => return Some(PrintFormat::Short),
_ => return Some(PrintFormat::Full),
}
let val = env::var_os("RUST_BACKTRACE").and_then(|x| {
if &x == "0" {
None
} else if &x == "full" {
Some(PrintFormat::Full)
} else {
Some(PrintFormat::Short)
}
});
ENABLED.store(
match val {
Some(v) => v as isize,
None => 1,
},
Ordering::SeqCst,
);
val
}
struct Printer<'a, 'b> {
format: PrintFormat,
done: bool,
skipped: bool,
idx: usize,
out: &'a mut (dyn Write + 'b),
}
impl<'a, 'b> Printer<'a, 'b> {
fn new(format: PrintFormat, out: &'a mut (dyn Write + 'b)) -> Printer<'a, 'b> {
Printer { format, done: false, skipped: false, idx: 0, out }
}
fn output(&mut self, frame: &Frame, symbol: Option<&Symbol>) {
if self.idx > MAX_NB_FRAMES {
self.done = true;
self.skipped = true;
return;
}
if self._output(frame, symbol).is_err() {
self.done = true;
}
self.idx += 1;
}
fn _output(&mut self, frame: &Frame, symbol: Option<&Symbol>) -> io::Result<()> {
if self.format == PrintFormat::Short {
if let Some(sym) = symbol.and_then(|s| s.name()).and_then(|s| s.as_str()) {
if sym.contains("__rust_begin_short_backtrace") {
self.skipped = true;
self.done = true;
return Ok(());
}
}
if self.format == PrintFormat::Short && frame.ip() == ptr::null_mut() {
self.skipped = true;
return Ok(());
}
}
match self.format {
PrintFormat::Full => {
write!(self.out, " {:2}: {:2$?} - ", self.idx, frame.ip(), HEX_WIDTH)?
}
PrintFormat::Short => write!(self.out, " {:2}: ", self.idx)?,
}
match symbol.and_then(|s| s.name()) {
Some(symbol) => {
match self.format {
PrintFormat::Full => write!(self.out, "{}", symbol)?,
PrintFormat::Short => write!(self.out, "{:#}", symbol)?,
}
}
None => self.out.write_all(b"<unknown>")?,
}
self.out.write_all(b"\n")?;
if let Some(sym) = symbol {
self.output_fileline(sym)?;
}
Ok(())
}
fn output_fileline(&mut self, symbol: &Symbol) -> io::Result<()> {
#[cfg(windows)]
let path_buf;
let file = match symbol.filename_raw() {
#[cfg(unix)]
Some(BytesOrWideString::Bytes(bytes)) => {
use crate::os::unix::prelude::*;
Path::new(crate::ffi::OsStr::from_bytes(bytes))
}
#[cfg(not(unix))]
Some(BytesOrWideString::Bytes(bytes)) => {
Path::new(crate::str::from_utf8(bytes).unwrap_or("<unknown>"))
}
#[cfg(windows)]
Some(BytesOrWideString::Wide(wide)) => {
use crate::os::windows::prelude::*;
path_buf = crate::ffi::OsString::from_wide(wide);
Path::new(&path_buf)
}
#[cfg(not(windows))]
Some(BytesOrWideString::Wide(_wide)) => {
Path::new("<unknown>")
}
None => return Ok(()),
};
let line = match symbol.lineno() {
Some(line) => line,
None => return Ok(()),
};
self.out.write_all(b"")?;
match self.format {
PrintFormat::Full => write!(self.out, " {:1$}", "", HEX_WIDTH)?,
PrintFormat::Short => write!(self.out, " ")?,
}
let mut already_printed = false;
if self.format == PrintFormat::Short && file.is_absolute() {
if let Ok(cwd) = env::current_dir() {
if let Ok(stripped) = file.strip_prefix(&cwd) {
if let Some(s) = stripped.to_str() {
write!(self.out, " at .{}{}:{}", path::MAIN_SEPARATOR, s, line)?;
already_printed = true;
}
}
}
}
if !already_printed {
write!(self.out, " at {}:{}", file.display(), line)?;
}
self.out.write_all(b"\n")
}
}