1#![allow(warnings)]
3use std::collections::HashMap;
4use std::hash::{BuildHasher, Hasher};
5use std::panic::Location;
6use std::sync::{Arc, LazyLock, OnceLock};
7use std::{cell::RefCell, ffi::c_void, fmt, fmt::Write, os, path, ptr};
8
9use backtrace::{BacktraceFmt, BytesOrWideString, Frame, SymbolName};
10
11thread_local! {
12 static FRAMES: RefCell<HashMap<usize, Arc<ResolvedFrame>>> = RefCell::new(HashMap::default());
13 static REPRS: RefCell<HashMap<u64, Arc<str>>> = RefCell::new(HashMap::default());
14 static DEFAULT: Arc<str> = Arc::from("Unresolved backtrace");
15}
16
17type StartLoc = (&'static str, u32);
18
19const START_ALT_SLOTS: usize = 8;
20
21static START: OnceLock<StartLoc> = OnceLock::new();
22static START_ALT: [OnceLock<StartLoc>; START_ALT_SLOTS] =
23 [const { OnceLock::new() }; START_ALT_SLOTS];
24
25pub fn set_backtrace_start(file: &'static str, line: u32) {
31 let _ = START.set((file, line));
32}
33
34#[doc(hidden)]
39pub fn set_backtrace_start_alt(file: &'static str, line: u32) {
40 let loc = (file, line);
41 for slot in &START_ALT {
42 if slot.set(loc).is_ok() || slot.get() == Some(&loc) {
45 return;
46 }
47 }
48}
49
50#[derive(Clone)]
51pub struct Backtrace(Arc<BacktraceRaw>);
57
58#[derive(Debug)]
59pub struct BacktraceResolver {
68 bt: Arc<BacktraceRaw>,
69 repr: Option<Arc<str>>,
70 resolved: bool,
71 frames: HashMap<usize, Arc<ResolvedFrame>>,
72}
73
74#[derive(Debug)]
75pub struct BacktraceRaw {
77 id: u64,
78 frames: [Option<RawFrame>; 80],
79 location: &'static str,
80}
81
82#[derive(Debug, Clone)]
83enum RawFrame {
84 Frame(Frame),
85 Ip(usize),
86}
87
88impl RawFrame {
89 fn ip(&self) -> usize {
90 match self {
91 RawFrame::Frame(frm) => frm.ip() as usize,
92 RawFrame::Ip(ip) => *ip,
93 }
94 }
95}
96
97#[derive(Debug)]
98struct ResolvedFrame {
99 ip: usize,
100 symbols: Vec<ResolvedSymbol>,
101}
102
103#[derive(Debug)]
104struct ResolvedSymbol {
105 name: Option<Vec<u8>>,
106 filename: Option<path::PathBuf>,
107 lineno: Option<u32>,
108 colno: Option<u32>,
109}
110
111impl ResolvedFrame {
112 fn resolve(frm: &RawFrame) -> Self {
113 let mut symbols = Vec::new();
114 let mut cb = |sym: &backtrace::Symbol| {
115 symbols.push(ResolvedSymbol {
116 name: sym.name().map(|n| n.as_bytes().to_vec()),
117 filename: sym.filename().map(path::Path::to_path_buf),
118 lineno: sym.lineno(),
119 colno: sym.colno(),
120 });
121 };
122 match frm {
123 RawFrame::Frame(f) => backtrace::resolve_frame(f, &mut cb),
124 RawFrame::Ip(ip) => backtrace::resolve(*ip as *mut c_void, &mut cb),
125 }
126 ResolvedFrame {
127 ip: frm.ip(),
128 symbols,
129 }
130 }
131}
132
133impl BacktraceRaw {
134 pub fn new(location: &'static Location<'static>) -> Self {
136 Self::with_filename(location.file())
137 }
138
139 #[track_caller]
140 pub fn with_current() -> Self {
142 Self::new(Location::caller())
143 }
144
145 pub fn with_filename(location: &'static str) -> Self {
147 Self::capture(location, |cb| backtrace::trace(cb))
148 }
149
150 #[doc(hidden)]
151 pub unsafe fn with_filename_unsynchronized(location: &'static str) -> Self {
160 Self::capture(location, |cb| {
161 unsafe { backtrace::trace_unsynchronized(cb) };
163 })
164 }
165
166 #[doc(hidden)]
167 pub fn from_ips(ips: &[usize], location: &'static str) -> Self {
172 let mut st = foldhash::fast::FixedState::default().build_hasher();
173 let mut frames: [Option<RawFrame>; 80] = [const { None }; 80];
174
175 for (frm, ip) in frames.iter_mut().zip(ips) {
176 st.write_usize(*ip);
177 *frm = Some(RawFrame::Ip(*ip));
178 }
179 let id = st.finish();
180
181 BacktraceRaw {
182 id,
183 frames,
184 location,
185 }
186 }
187
188 fn capture<F>(location: &'static str, trace: F) -> Self
189 where
190 F: FnOnce(&mut dyn FnMut(&Frame) -> bool),
191 {
192 let mut st = foldhash::fast::FixedState::default().build_hasher();
193 let mut idx = 0;
194 let mut frames: [Option<RawFrame>; 80] = [const { None }; 80];
195
196 trace(&mut |frm| {
197 let ip = frm.ip();
198 st.write_usize(ip as usize);
199 frames[idx] = Some(RawFrame::Frame(frm.clone()));
200 idx += 1;
201 idx < 80
202 });
203 let id = st.finish();
204
205 BacktraceRaw {
206 id,
207 frames,
208 location,
209 }
210 }
211}
212
213impl From<BacktraceRaw> for Backtrace {
214 fn from(bt: BacktraceRaw) -> Backtrace {
215 Backtrace(Arc::new(bt))
216 }
217}
218
219impl Backtrace {
220 pub fn new(location: &'static Location<'static>) -> Self {
222 Self(Arc::new(BacktraceRaw::new(location)))
223 }
224
225 #[track_caller]
226 pub fn with_current() -> Self {
228 Self(Arc::new(BacktraceRaw::new(Location::caller())))
229 }
230
231 pub fn with_filename(location: &'static str) -> Self {
233 Self(Arc::new(BacktraceRaw::with_filename(location)))
234 }
235
236 pub fn repr(&self) -> Option<Arc<str>> {
238 REPRS.with(|r| r.borrow_mut().get(&self.0.id).cloned())
239 }
240
241 pub fn is_resolved(&self) -> bool {
244 REPRS.with(|r| r.borrow_mut().contains_key(&self.0.id))
245 }
246
247 #[must_use]
249 pub fn resolve(self) -> Self {
250 self.resolver().resolve();
251 self
252 }
253
254 pub fn resolver(&self) -> BacktraceResolver {
258 REPRS.with(|r| {
259 let mut reprs = r.borrow_mut();
260 if let Some(repr) = reprs.get(&self.0.id) {
261 BacktraceResolver {
262 repr: None,
263 resolved: true,
264 bt: self.0.clone(),
265 frames: HashMap::default(),
266 }
267 } else {
268 DEFAULT.with(|s| {
269 reprs.insert(self.0.id, s.clone());
270 });
271
272 let mut frames = HashMap::default();
273
274 FRAMES.with(|c| {
275 let mut cache = c.borrow();
276
277 for frm in &self.0.frames {
278 if let Some(frm) = frm {
279 let ip = frm.ip();
280 if let Some(frame) = cache.get(&ip) {
281 frames.insert(ip, frame.clone());
282 }
283 }
284 }
285 });
286
287 BacktraceResolver {
288 frames,
289 resolved: false,
290 repr: None,
291 bt: self.0.clone(),
292 }
293 }
294 })
295 }
296}
297
298impl BacktraceResolver {
299 #[allow(clippy::return_self_not_must_use)]
303 pub fn resolve(mut self) -> Self {
304 if self.resolved {
305 return self;
306 }
307
308 for frm in &self.bt.frames {
309 if let Some(frm) = frm {
310 let ip = frm.ip();
311 if self.frames.contains_key(&ip) {
312 continue;
313 }
314 self.frames
315 .insert(ip, Arc::new(ResolvedFrame::resolve(frm)));
316 }
317 }
318
319 let mut idx = 0;
320 let mut frames: [Option<&ResolvedFrame>; 80] = [None; 80];
321 for frm in &self.bt.frames {
322 if let Some(frm) = frm {
323 let ip = frm.ip();
324 frames[idx] = Some(self.frames[&ip].as_ref());
325 idx += 1;
326 }
327 }
328
329 find_loc(self.bt.location, &mut frames);
330
331 if let Some(start) = START.get() {
332 find_loc_start(*start, &mut frames);
333 }
334 for start in START_ALT.iter().map_while(OnceLock::get) {
335 find_loc_start(*start, &mut frames);
336 }
337 PATHS2.with(|paths| {
338 for s in paths {
339 find_loc_start((s.as_str(), 0), &mut frames);
340 }
341 });
342
343 let mut idx = 0;
344 for frm in &mut frames {
345 if frm.is_some() {
346 if idx > 10 {
347 *frm = None;
348 } else {
349 idx += 1;
350 }
351 }
352 }
353
354 let bt = Bt(&frames[..]);
355 let mut buf = String::new();
356 let _ = write!(&mut buf, "\n{bt:?}");
357 self.repr = Some(Arc::from(buf));
358
359 self
360 }
361}
362
363impl Drop for BacktraceResolver {
364 fn drop(&mut self) {
365 if !self.resolved {
366 if let Some(repr) = self.repr.take() {
367 REPRS.with(|r| {
368 r.borrow_mut().insert(self.bt.id, repr);
369 });
370 }
371
372 FRAMES.with(|c| {
373 let mut cache = c.borrow_mut();
374
375 for (ip, frm) in &self.frames {
376 let ip = frm.ip;
377 if !cache.contains_key(&ip) {
378 cache.insert(ip, frm.clone());
379 }
380 }
381 });
382 }
383 }
384}
385
386fn find_loc(loc: &str, frames: &mut [Option<&ResolvedFrame>]) {
387 let mut idx = 0;
388
389 'outer: for (i, frm) in frames.iter().enumerate() {
390 if let Some(f) = frm {
391 for sym in &f.symbols {
392 if let Some(fname) = &sym.filename
393 && fname.ends_with(loc)
394 {
395 idx = i;
396 break 'outer;
397 }
398 }
399 } else {
400 break;
401 }
402 }
403
404 for f in frames.iter_mut().take(idx) {
405 *f = None;
406 }
407
408 PATHS.with(|paths| {
409 'outer: for frm in &mut frames[idx..] {
410 if let Some(f) = frm {
411 for sym in &f.symbols {
412 if let Some(fname) = &sym.filename {
413 for p in paths {
414 if fname.ends_with(p) {
415 *frm = None;
416 continue 'outer;
417 }
418 }
419 }
420 }
421 }
422 }
423 });
424}
425
426thread_local! {
427 static PATHS: Vec<String> = {
428 let mut paths = Vec::new();
429 for item in [
430 &["src", "ctx.rs"][..],
431 &["src", "map_err.rs"][..],
432 &["src", "and_then.rs"][..],
433 &["src", "fn_service.rs"][..],
434 &["src", "pipeline.rs"][..],
435 &["src", "net", "factory.rs"][..],
436 &["src", "future", "future.rs"][..],
437 &["src", "net", "service.rs"][..],
438 &["src", "boxed.rs"][..],
439 &["src", "error.rs"][..],
440 &["src", "wrk.rs"][..],
441 &["src", "future.rs"][..],
442 &["std", "src", "thread", "local.rs"][..],
443 ] {
444 paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
445 }
446 paths
447 };
448
449 static PATHS2: Vec<String> = {
450 let mut paths = Vec::new();
451 for item in [
452 &["src", "driver.rs"][..],
453 &["src", "rt_compio.rs"][..],
454 &["core", "src", "panic", "unwind_safe.rs"][..],
455 &["src", "runtime", "task", "core.rs"][..]
456 ] {
457 paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
458 }
459 paths
460 }
461}
462
463fn find_loc_start(loc: (&str, u32), frames: &mut [Option<&ResolvedFrame>]) {
464 let mut idx = 0;
465 while idx < frames.len() {
466 if let Some(frm) = &frames[idx] {
467 for sym in &frm.symbols {
468 if let Some(fname) = &sym.filename
469 && let Some(lineno) = sym.lineno
470 && fname.ends_with(loc.0)
471 && (loc.1 == 0 || lineno == loc.1)
472 {
473 for f in frames.iter_mut().skip(idx) {
474 if f.is_some() {
475 *f = None;
476 }
477 }
478 return;
479 }
480 }
481 }
482 idx += 1;
483 }
484}
485
486struct Bt<'a>(&'a [Option<&'a ResolvedFrame>]);
487
488impl fmt::Debug for Bt<'_> {
489 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
490 let cwd = std::env::current_dir();
491 let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
492 let path = crate::utils::module_path_fs(path.to_str_lossy().as_ref());
493 fmt::Display::fmt(&path, fmt)
494 };
495
496 let mut f = BacktraceFmt::new(fmt, backtrace::PrintFmt::Short, &mut print_path);
497 f.add_context()?;
498 for frm in self.0.iter().flatten() {
499 let ip = frm.ip as *mut c_void;
500 let mut ff = f.frame();
501 for sym in &frm.symbols {
502 ff.print_raw_with_column(
503 ip,
504 sym.name.as_deref().map(SymbolName::new),
505 sym.filename
506 .as_deref()
507 .and_then(|p| Some(BytesOrWideString::Bytes(p.to_str()?.as_bytes()))),
508 sym.lineno,
509 sym.colno,
510 )?;
511 }
512 if frm.symbols.is_empty() {
513 ff.print_raw(ip, None, None, None)?;
514 }
515 }
516 f.finish()?;
517 Ok(())
518 }
519}
520
521impl fmt::Debug for Backtrace {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 if let Some(repr) = self.repr() {
524 fmt::Display::fmt(repr.as_ref(), f)
525 } else {
526 Ok(())
527 }
528 }
529}
530
531impl fmt::Display for Backtrace {
532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533 if let Some(repr) = self.repr() {
534 fmt::Display::fmt(repr.as_ref(), f)
535 } else {
536 Ok(())
537 }
538 }
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544
545 #[test]
556 fn miri_backtrace_start_concurrent_set() {
557 set_backtrace_start("first.rs", 1);
558 set_backtrace_start_alt("alt-a.rs", 0);
559 set_backtrace_start_alt("alt-b.rs", 0);
560
561 let threads: Vec<_> = (0..4)
562 .map(|_| {
563 std::thread::spawn(|| {
564 for _ in 0..4 {
565 set_backtrace_start("second.rs", 2);
566 set_backtrace_start_alt("alt-b.rs", 0);
567 set_backtrace_start_alt("alt-c.rs", 0);
568 set_backtrace_start_alt("alt-a.rs", 0);
569 assert_eq!(START.get(), Some(&("first.rs", 1)));
570 assert!(START_ALT.iter().map_while(OnceLock::get).count() >= 2);
571 }
572 })
573 })
574 .collect();
575 for t in threads {
576 t.join().unwrap();
577 }
578
579 assert_eq!(START.get(), Some(&("first.rs", 1)));
580 let alts: Vec<_> = START_ALT.iter().map_while(OnceLock::get).copied().collect();
581 assert_eq!(alts, [("alt-a.rs", 0), ("alt-b.rs", 0), ("alt-c.rs", 0)]);
582 }
583}