ntex-error 3.1.0

ntex error management
Documentation
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Backtrace
#![allow(warnings)]
use std::collections::HashMap;
use std::hash::{BuildHasher, Hasher};
use std::panic::Location;
use std::{cell::RefCell, ffi::c_void, fmt, fmt::Write, os, path, ptr, sync::Arc, sync::LazyLock};

use backtrace::{BacktraceFmt, BytesOrWideString, Frame, SymbolName};

thread_local! {
    static FRAMES: RefCell<HashMap<usize, Arc<ResolvedFrame>>> = RefCell::new(HashMap::default());
    static REPRS: RefCell<HashMap<u64, Arc<str>>> = RefCell::new(HashMap::default());
    static DEFAULT: Arc<str> = Arc::from("Unresolved backtrace");
}

static mut START: Option<(&'static str, u32)> = None;
static mut START_ALT: Option<(&'static str, u32)> = None;

/// Sets the source location where rendered backtraces are cut off.
///
/// The frame matching `file` (a path suffix) and `line` (`0` matches any line),
/// and all of its callers, are omitted from the rendered backtrace.
/// Must be called once during initialization, before any backtrace is resolved.
pub fn set_backtrace_start(file: &'static str, line: u32) {
    unsafe {
        START = Some((file, line));
    }
}

#[doc(hidden)]
pub fn set_backtrace_start_alt(file: &'static str, line: u32) {
    unsafe {
        START_ALT = Some((file, line));
    }
}

#[derive(Clone)]
/// Representation of a 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.
pub struct Backtrace(Arc<BacktraceRaw>);

#[derive(Debug)]
/// Backtrace resolver.
///
/// Symbol resolution may require filesystem access and can be blocking.
/// In asynchronous contexts, this work should be offloaded to a thread
/// pool.
///
/// **Note:** Once resolution is complete, control must return to the
/// originating thread to ensure caching is performed correctly.
pub struct BacktraceResolver {
    bt: Arc<BacktraceRaw>,
    repr: Option<Arc<str>>,
    resolved: bool,
    frames: HashMap<usize, Arc<ResolvedFrame>>,
}

#[derive(Debug)]
/// Representation of a backtrace.
pub struct BacktraceRaw {
    id: u64,
    frames: [Option<RawFrame>; 80],
    location: &'static str,
}

#[derive(Debug, Clone)]
enum RawFrame {
    Frame(Frame),
    Ip(usize),
}

impl RawFrame {
    fn ip(&self) -> usize {
        match self {
            RawFrame::Frame(frm) => frm.ip() as usize,
            RawFrame::Ip(ip) => *ip,
        }
    }
}

#[derive(Debug)]
struct ResolvedFrame {
    ip: usize,
    symbols: Vec<ResolvedSymbol>,
}

#[derive(Debug)]
struct ResolvedSymbol {
    name: Option<Vec<u8>>,
    filename: Option<path::PathBuf>,
    lineno: Option<u32>,
    colno: Option<u32>,
}

impl ResolvedFrame {
    fn resolve(frm: &RawFrame) -> Self {
        let mut symbols = Vec::new();
        let mut cb = |sym: &backtrace::Symbol| {
            symbols.push(ResolvedSymbol {
                name: sym.name().map(|n| n.as_bytes().to_vec()),
                filename: sym.filename().map(path::Path::to_path_buf),
                lineno: sym.lineno(),
                colno: sym.colno(),
            });
        };
        match frm {
            RawFrame::Frame(f) => backtrace::resolve_frame(f, &mut cb),
            RawFrame::Ip(ip) => backtrace::resolve(*ip as *mut c_void, &mut cb),
        }
        ResolvedFrame {
            ip: frm.ip(),
            symbols,
        }
    }
}

impl BacktraceRaw {
    /// Create new backtrace
    pub fn new(location: &'static Location<'static>) -> Self {
        Self::with_filename(location.file())
    }

    #[track_caller]
    /// Create new backtrace with current location
    pub fn with_current() -> Self {
        Self::new(Location::caller())
    }

    /// Create new backtrace with filename location
    pub fn with_filename(location: &'static str) -> Self {
        Self::capture(location, |cb| backtrace::trace(cb))
    }

    #[doc(hidden)]
    /// Create new backtrace without acquiring the global backtrace lock.
    ///
    /// Does not allocate or lock, so it can be used from a signal handler
    /// (subject to the platform unwinder being signal-safe).
    ///
    /// # Safety
    ///
    /// Same requirements as [`backtrace::trace_unsynchronized`].
    pub unsafe fn with_filename_unsynchronized(location: &'static str) -> Self {
        Self::capture(location, |cb| unsafe {
            backtrace::trace_unsynchronized(cb);
        })
    }

    #[doc(hidden)]
    /// Create new backtrace from instruction pointers, innermost frame first.
    ///
    /// Used for stacks walked outside of the `backtrace` crate, for example
    /// of another suspended thread. Does not allocate or lock.
    pub fn from_ips(ips: &[usize], location: &'static str) -> Self {
        let mut st = foldhash::fast::FixedState::default().build_hasher();
        let mut frames: [Option<RawFrame>; 80] = [const { None }; 80];

        for (frm, ip) in frames.iter_mut().zip(ips) {
            st.write_usize(*ip);
            *frm = Some(RawFrame::Ip(*ip));
        }
        let id = st.finish();

        BacktraceRaw {
            id,
            frames,
            location,
        }
    }

    fn capture<F>(location: &'static str, trace: F) -> Self
    where
        F: FnOnce(&mut dyn FnMut(&Frame) -> bool),
    {
        let mut st = foldhash::fast::FixedState::default().build_hasher();
        let mut idx = 0;
        let mut frames: [Option<RawFrame>; 80] = [const { None }; 80];

        trace(&mut |frm| {
            let ip = frm.ip();
            st.write_usize(ip as usize);
            frames[idx] = Some(RawFrame::Frame(frm.clone()));
            idx += 1;
            idx < 80
        });
        let id = st.finish();

        BacktraceRaw {
            id,
            frames,
            location,
        }
    }
}

impl From<BacktraceRaw> for Backtrace {
    fn from(bt: BacktraceRaw) -> Backtrace {
        Backtrace(Arc::new(bt))
    }
}

impl Backtrace {
    /// Create new backtrace
    pub fn new(location: &'static Location<'static>) -> Self {
        Self(Arc::new(BacktraceRaw::new(location)))
    }

    #[track_caller]
    /// Create new backtrace with current location
    pub fn with_current() -> Self {
        Self(Arc::new(BacktraceRaw::new(Location::caller())))
    }

    /// Create new backtrace with filename location
    pub fn with_filename(location: &'static str) -> Self {
        Self(Arc::new(BacktraceRaw::with_filename(location)))
    }

    /// Returns the rendered backtrace, if it has been resolved on the current thread.
    pub fn repr(&self) -> Option<Arc<str>> {
        REPRS.with(|r| r.borrow_mut().get(&self.0.id).cloned())
    }

    /// Returns `true` if this backtrace has been resolved (or resolution
    /// has started) on the current thread.
    pub fn is_resolved(&self) -> bool {
        REPRS.with(|r| r.borrow_mut().contains_key(&self.0.id))
    }

    /// Resolves the backtrace symbols on the current thread and caches the result.
    #[must_use]
    pub fn resolve(self) -> Self {
        self.resolver().resolve();
        self
    }

    /// Returns a resolver that can resolve symbols outside the current thread.
    ///
    /// See [`BacktraceResolver`] for details.
    pub fn resolver(&self) -> BacktraceResolver {
        REPRS.with(|r| {
            let mut reprs = r.borrow_mut();
            if let Some(repr) = reprs.get(&self.0.id) {
                BacktraceResolver {
                    repr: None,
                    resolved: true,
                    bt: self.0.clone(),
                    frames: HashMap::default(),
                }
            } else {
                DEFAULT.with(|s| {
                    reprs.insert(self.0.id, s.clone());
                });

                let mut frames = HashMap::default();

                FRAMES.with(|c| {
                    let mut cache = c.borrow();

                    for frm in &self.0.frames {
                        if let Some(frm) = frm {
                            let ip = frm.ip();
                            if let Some(frame) = cache.get(&ip) {
                                frames.insert(ip, frame.clone());
                            }
                        }
                    }
                });

                BacktraceResolver {
                    frames,
                    resolved: false,
                    repr: None,
                    bt: self.0.clone(),
                }
            }
        })
    }
}

impl BacktraceResolver {
    /// Resolves backtrace symbols and renders the representation.
    ///
    /// The result is cached when the resolver is dropped.
    #[allow(clippy::return_self_not_must_use)]
    pub fn resolve(mut self) -> Self {
        if self.resolved {
            return self;
        }

        for frm in &self.bt.frames {
            if let Some(frm) = frm {
                let ip = frm.ip();
                if self.frames.contains_key(&ip) {
                    continue;
                }
                self.frames
                    .insert(ip, Arc::new(ResolvedFrame::resolve(frm)));
            }
        }

        let mut idx = 0;
        let mut frames: [Option<&ResolvedFrame>; 80] = [None; 80];
        for frm in &self.bt.frames {
            if let Some(frm) = frm {
                let ip = frm.ip();
                frames[idx] = Some(self.frames[&ip].as_ref());
                idx += 1;
            }
        }

        find_loc(self.bt.location, &mut frames);

        #[allow(static_mut_refs)]
        {
            if let Some(start) = unsafe { START } {
                find_loc_start(start, &mut frames);
            }
            if let Some(start) = unsafe { START_ALT } {
                find_loc_start(start, &mut frames);
            }
            PATHS2.with(|paths| {
                for s in paths {
                    find_loc_start((s.as_str(), 0), &mut frames);
                }
            });
        }

        let mut idx = 0;
        for frm in &mut frames {
            if frm.is_some() {
                if idx > 10 {
                    *frm = None;
                } else {
                    idx += 1;
                }
            }
        }

        let bt = Bt(&frames[..]);
        let mut buf = String::new();
        let _ = write!(&mut buf, "\n{bt:?}");
        self.repr = Some(Arc::from(buf));

        self
    }
}

impl Drop for BacktraceResolver {
    fn drop(&mut self) {
        if !self.resolved {
            if let Some(repr) = self.repr.take() {
                REPRS.with(|r| {
                    r.borrow_mut().insert(self.bt.id, repr);
                });
            }

            FRAMES.with(|c| {
                let mut cache = c.borrow_mut();

                for (ip, frm) in &self.frames {
                    let ip = frm.ip;
                    if !cache.contains_key(&ip) {
                        cache.insert(ip, frm.clone());
                    }
                }
            });
        }
    }
}

fn find_loc(loc: &str, frames: &mut [Option<&ResolvedFrame>]) {
    let mut idx = 0;

    'outter: for (i, frm) in frames.iter().enumerate() {
        if let Some(f) = frm {
            for sym in &f.symbols {
                if let Some(fname) = &sym.filename
                    && fname.ends_with(loc)
                {
                    idx = i;
                    break 'outter;
                }
            }
        } else {
            break;
        }
    }

    for f in frames.iter_mut().take(idx) {
        *f = None;
    }

    PATHS.with(|paths| {
        'outter: for frm in &mut frames[idx..] {
            if let Some(f) = frm {
                for sym in &f.symbols {
                    if let Some(fname) = &sym.filename {
                        for p in paths {
                            if fname.ends_with(p) {
                                *frm = None;
                                continue 'outter;
                            }
                        }
                    }
                }
            }
        }
    });
}

thread_local! {
    static PATHS: Vec<String> = {
        let mut paths = Vec::new();
        for item in [
            &["src", "ctx.rs"][..],
            &["src", "map_err.rs"][..],
            &["src", "and_then.rs"][..],
            &["src", "fn_service.rs"][..],
            &["src", "pipeline.rs"][..],
            &["src", "net", "factory.rs"][..],
            &["src", "future", "future.rs"][..],
            &["src", "net", "service.rs"][..],
            &["src", "boxed.rs"][..],
            &["src", "error.rs"][..],
            &["src", "wrk.rs"][..],
            &["src", "future.rs"][..],
            &["std", "src", "thread", "local.rs"][..],
        ] {
            paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
        }
        paths
    };

    static PATHS2: Vec<String> = {
        let mut paths = Vec::new();
        for item in [
            &["src", "driver.rs"][..],
            &["src", "rt_compio.rs"][..],
            &["core", "src", "panic", "unwind_safe.rs"][..],
            &["src", "runtime", "task", "core.rs"][..]
        ] {
            paths.push(item.iter().collect::<path::PathBuf>().to_string_lossy().into_owned());
        }
        paths
    }
}

fn find_loc_start(loc: (&str, u32), frames: &mut [Option<&ResolvedFrame>]) {
    let mut idx = 0;
    while idx < frames.len() {
        if let Some(frm) = &frames[idx] {
            for sym in &frm.symbols {
                if let Some(fname) = &sym.filename
                    && let Some(lineno) = sym.lineno
                    && fname.ends_with(loc.0)
                    && (loc.1 == 0 || lineno == loc.1)
                {
                    for f in frames.iter_mut().skip(idx) {
                        if f.is_some() {
                            *f = None;
                        }
                    }
                    return;
                }
            }
        }
        idx += 1;
    }
}

struct Bt<'a>(&'a [Option<&'a ResolvedFrame>]);

impl fmt::Debug for Bt<'_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cwd = std::env::current_dir();
        let mut print_path = move |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
            let path = crate::utils::module_path_fs(path.to_str_lossy().as_ref());
            fmt::Display::fmt(&path, fmt)
        };

        let mut f = BacktraceFmt::new(fmt, backtrace::PrintFmt::Short, &mut print_path);
        f.add_context()?;
        for frm in self.0.iter().flatten() {
            let ip = frm.ip as *mut c_void;
            let mut ff = f.frame();
            for sym in &frm.symbols {
                ff.print_raw_with_column(
                    ip,
                    sym.name.as_deref().map(SymbolName::new),
                    sym.filename
                        .as_deref()
                        .and_then(|p| Some(BytesOrWideString::Bytes(p.to_str()?.as_bytes()))),
                    sym.lineno,
                    sym.colno,
                )?;
            }
            if frm.symbols.is_empty() {
                ff.print_raw(ip, None, None, None)?;
            }
        }
        f.finish()?;
        Ok(())
    }
}

impl fmt::Debug for Backtrace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(repr) = self.repr() {
            fmt::Display::fmt(repr.as_ref(), f)
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for Backtrace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(repr) = self.repr() {
            fmt::Display::fmt(repr.as_ref(), f)
        } else {
            Ok(())
        }
    }
}