Files
adler32
ahash
aho_corasick
ansi_term
antidote
anyhow
arc_swap
arrayvec
async_speed_limit
async_stream
async_stream_impl
async_trait
atty
aws
backtrace
backtrace_sys
backup
base64
batch_system
bitfield
bitflags
block_buffer
boolinator
bstr
byteorder
bytes
bzip2_sys
cargo_metadata
cdc
cfg_if
chrono
chrono_tz
clap
cloud
codec
collections
concurrency_manager
configuration
configuration_derive
const_fn
const_random
const_random_macro
coprocessor_plugin_api
cpuid_bool
crc32fast
crc64fast
crossbeam
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_skiplist
crossbeam_utils
crypto_mac
darling
darling_core
darling_macro
dashmap
debugid
derive_more
digest
dirs
dirs_sys
doc_comment
dtoa
either
encoding_rs
encryption
encryption_export
engine_panic
engine_rocks
engine_test
engine_traits
engine_traits_tests
error_code
error_code_gen
example_plugin
external_storage
external_storage_export
fail
failure
failure_derive
farmhash
file_system
filetime
flate2
fnv
foreign_types
foreign_types_shared
fs2
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_timer
futures_util
async_await
compat
future
io
lock
sink
stream
task
fuzz
fxhash
gcp
generic_array
getrandom
getset
grpcio
grpcio_health
grpcio_sys
h2
heck
hex
hmac
http
http_body
httparse
httpdate
hyper
hyper_openssl
hyper_tls
ident_case
idna
indexmap
inferno
inotify
inotify_sys
instant
into_other
iovec
ipnet
ipnetwork
itertools
itoa
keys
kvproto
lazy_static
lazycell
libc
libflate
libflate_lz77
libloading
librocksdb_sys
libtitan_sys
libz_sys
linked_hash_map
linked_hash_set
lock_api
log
log_wrappers
lz4_sys
match_template
matches
md5
memchr
memmap
memoffset
memory_trace_macros
mime
mime_guess
mio
mio_extras
mio_uds
more_asserts
murmur3
native_tls
net2
nix
nodrop
nom
notify
num
num_complex
num_cpus
num_derive
num_format
num_integer
num_iter
num_rational
num_traits
once_cell
opaque_debug
openssl
openssl_probe
openssl_sys
ordered_float
panic_hook
parking_lot
parking_lot_core
paste
paste_impl
pd_client
percent_encoding
pest
pin_project
pin_project_lite
pin_utils
pnet_base
pnet_datalink
pnet_sys
pprof
ppv_lite86
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
procfs
procinfo
profiler
prometheus
prometheus_static_metric
promptly
prost
prost_derive
protobuf
quick_xml
quote
raft
raft_engine
raft_log_engine
raft_proto
raftstore
rand
rand_chacha
rand_core
rand_isaac
rayon
rayon_core
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
resolved_ts
rev_lines
rgb
ring
rle_decode_fast
rocksdb
rusoto_core
rusoto_credential
rusoto_kms
rusoto_s3
rusoto_signature
rusoto_sts
rustc_demangle
rustyline
ryu
safemem
same_file
scopeguard
security
semver
semver_parser
serde
serde_derive
serde_ignored
serde_json
serde_urlencoded
serde_with
serde_with_macros
server
sha2
shlex
signal
signal_hook_registry
slab
slog
slog_async
slog_derive
slog_global
slog_json
slog_term
smallvec
snappy_sys
socket2
spin
sst_importer
stable_deref_trait
standback
static_assertions
str_stack
strsim
structopt
structopt_derive
strum
strum_macros
subtle
symbolic_common
symbolic_demangle
syn
syn_mid
synstructure
sysinfo
take_mut
tame_gcs
tame_oauth
tempfile
term
test_backup
test_coprocessor
test_pd
test_raftstore
test_sst_importer
test_storage
test_util
textwrap
thiserror
thiserror_impl
thread_local
tidb_query_aggr
tidb_query_codegen
tidb_query_common
tidb_query_datatype
tidb_query_executors
tidb_query_expr
tikv
coprocessor
coprocessor_v2
import
server
storage
tikv_alloc
tikv_ctl
tikv_jemalloc_ctl
tikv_jemalloc_sys
tikv_jemallocator
tikv_kv
tikv_server
tikv_util
time
time_macros
time_macros_impl
tipb
tipb_helper
tokio
fs
future
io
loom
macros
net
park
process
runtime
signal
stream
sync
task
time
util
tokio_executor
tokio_macros
tokio_openssl
tokio_timer
tokio_tls
tokio_util
toml
tower_service
tracing
tracing_core
try_lock
twoway
twox_hash
txn_types
typenum
ucd_trie
unchecked_index
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
untrusted
url
utf8parse
uuid
vec_map
vlog
walkdir
want
xml
yatp
zeroize
zstd_sys
  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
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Symbolication strategy using the DWARF-parsing code in libbacktrace.
//!
//! The libbacktrace C library, typically distributed with gcc, supports not
//! only generating a backtrace (which we don't actually use) but also
//! symbolicating the backtrace and handling dwarf debug information about
//! things like inlined frames and whatnot.
//!
//! This is relatively complicated due to lots of various concerns here, but the
//! basic idea is:
//!
//! * First we call `backtrace_syminfo`. This gets symbol information from the
//!   dynamic symbol table if we can.
//! * Next we call `backtrace_pcinfo`. This will parse debuginfo tables if
//!   they're available and allow us to recover information about inline frames,
//!   filenames, line numbers, etc.
//!
//! There's lots of trickery about getting the dwarf tables into libbacktrace,
//! but hopefully it's not the end of the world and is clear enough when reading
//! below.
//!
//! This is the default symbolication strategy for non-MSVC and non-OSX
//! platforms. In libstd though this is the default strategy for OSX.

#![allow(bad_style)]

extern crate backtrace_sys as bt;

use core::{ptr, slice};
use libc::{self, c_char, c_int, c_void, uintptr_t};

use crate::symbolize::{ResolveWhat, SymbolName};
use crate::symbolize::dladdr;
use crate::types::BytesOrWideString;

pub enum Symbol<'a> {
    Syminfo {
        pc: uintptr_t,
        symname: *const c_char,
    },
    Pcinfo {
        pc: uintptr_t,
        filename: *const c_char,
        lineno: c_int,
        function: *const c_char,
        symname: *const c_char,
    },
    Dladdr(dladdr::Symbol<'a>),
}

impl Symbol<'_> {
    pub fn name(&self) -> Option<SymbolName> {
        let symbol = |ptr: *const c_char| {
            unsafe {
                if ptr.is_null() {
                    None
                } else {
                    let len = libc::strlen(ptr);
                    Some(SymbolName::new(slice::from_raw_parts(
                        ptr as *const u8,
                        len,
                    )))
                }
            }
        };
        match *self {
            Symbol::Syminfo { symname, .. } => symbol(symname),
            Symbol::Pcinfo { function, symname, .. } => {
                // If possible prefer the `function` name which comes from
                // debuginfo and can typically be more accurate for inline
                // frames for example. If that's not present though fall back to
                // the symbol table name specified in `symname`.
                //
                // Note that sometimes `function` can feel somewhat less
                // accurate, for example being listed as `try<i32,closure>`
                // isntead of `std::panicking::try::do_call`. It's not really
                // clear why, but overall the `function` name seems more accurate.
                if let Some(sym) = symbol(function) {
                    return Some(sym)
                }
                symbol(symname)
            }
            Symbol::Dladdr(ref s) => s.name(),
        }
    }

    pub fn addr(&self) -> Option<*mut c_void> {
        let pc = match *self {
            Symbol::Syminfo { pc, .. } => pc,
            Symbol::Pcinfo { pc, .. } => pc,
            Symbol::Dladdr(ref s) => return s.addr(),
        };
        if pc == 0 {
            None
        } else {
            Some(pc as *mut _)
        }
    }

    fn filename_bytes(&self) -> Option<&[u8]> {
        match *self {
            Symbol::Syminfo { .. } => None,
            Symbol::Pcinfo { filename, .. } => {
                let ptr = filename as *const u8;
                unsafe {
                    let len = libc::strlen(filename);
                    Some(slice::from_raw_parts(ptr, len))
                }
            }
            Symbol::Dladdr(_) => None,
        }
    }

    pub fn filename_raw(&self) -> Option<BytesOrWideString> {
        self.filename_bytes().map(BytesOrWideString::Bytes)
    }

    #[cfg(feature = "std")]
    pub fn filename(&self) -> Option<&::std::path::Path> {
        use std::path::Path;

        #[cfg(unix)]
        fn bytes2path(bytes: &[u8]) -> Option<&Path> {
            use std::ffi::OsStr;
            use std::os::unix::prelude::*;
            Some(Path::new(OsStr::from_bytes(bytes)))
        }

        #[cfg(windows)]
        fn bytes2path(bytes: &[u8]) -> Option<&Path> {
            use std::str;
            str::from_utf8(bytes).ok().map(Path::new)
        }

        self.filename_bytes().and_then(bytes2path)
    }

    pub fn lineno(&self) -> Option<u32> {
        match *self {
            Symbol::Syminfo { .. } => None,
            Symbol::Pcinfo { lineno, .. } => Some(lineno as u32),
            Symbol::Dladdr(ref s) => s.lineno(),
        }
    }
}

extern "C" fn error_cb(_data: *mut c_void, _msg: *const c_char, _errnum: c_int) {
    // do nothing for now
}

/// Type of the `data` pointer passed into `syminfo_cb`
struct SyminfoState<'a> {
    cb: &'a mut (FnMut(&super::Symbol) + 'a),
    pc: usize,
}

extern "C" fn syminfo_cb(
    data: *mut c_void,
    pc: uintptr_t,
    symname: *const c_char,
    _symval: uintptr_t,
    _symsize: uintptr_t,
) {
    let mut bomb = crate::Bomb { enabled: true };

    // Once this callback is invoked from `backtrace_syminfo` when we start
    // resolving we go further to call `backtrace_pcinfo`. The
    // `backtrace_pcinfo` function will consult debug information and attemp tto
    // do things like recover file/line information as well as inlined frames.
    // Note though that `backtrace_pcinfo` can fail or not do much if there's
    // not debug info, so if that happens we're sure to call the callback with
    // at least one symbol from the `syminfo_cb`.
    unsafe {
        let syminfo_state = &mut *(data as *mut SyminfoState);
        let mut pcinfo_state = PcinfoState {
            symname,
            called: false,
            cb: syminfo_state.cb,
        };
        bt::backtrace_pcinfo(
            init_state(),
            syminfo_state.pc as uintptr_t,
            pcinfo_cb,
            error_cb,
            &mut pcinfo_state as *mut _ as *mut _,
        );
        if !pcinfo_state.called {
            (pcinfo_state.cb)(&super::Symbol {
                inner: Symbol::Syminfo {
                    pc: pc,
                    symname: symname,
                },
            });
        }
    }

    bomb.enabled = false;
}

/// Type of the `data` pointer passed into `pcinfo_cb`
struct PcinfoState<'a> {
    cb: &'a mut (FnMut(&super::Symbol) + 'a),
    symname: *const c_char,
    called: bool,
}

extern "C" fn pcinfo_cb(
    data: *mut c_void,
    pc: uintptr_t,
    filename: *const c_char,
    lineno: c_int,
    function: *const c_char,
) -> c_int {
    if filename.is_null() || function.is_null() {
        return -1;
    }
    let mut bomb = crate::Bomb { enabled: true };

    unsafe {
        let state = &mut *(data as *mut PcinfoState);
        state.called = true;
        (state.cb)(&super::Symbol {
            inner: Symbol::Pcinfo {
                pc: pc,
                filename: filename,
                lineno: lineno,
                symname: state.symname,
                function,
            },
        });
    }

    bomb.enabled = false;
    return 0;
}

// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// Note the lack of synchronization here is due to the requirement that
// `resolve` is externally synchronized.
unsafe fn init_state() -> *mut bt::backtrace_state {
    static mut STATE: *mut bt::backtrace_state = 0 as *mut _;

    if !STATE.is_null() {
        return STATE;
    }

    STATE = bt::backtrace_create_state(
        load_filename(),
        // Don't exercise threadsafe capabilities of libbacktrace since
        // we're always calling it in a synchronized fashion.
        0,
        error_cb,
        ptr::null_mut(), // no extra data
    );

    return STATE;

    // Note that for libbacktrace to operate at all it needs to find the DWARF
    // debug info for the current executable. It typically does that via a
    // number of mechanisms including, but not limited to:
    //
    // * /proc/self/exe on supported platforms
    // * The filename passed in explicitly when creating state
    //
    // The libbacktrace library is a big wad of C code. This naturally means
    // it's got memory safety vulnerabilities, especially when handling
    // malformed debuginfo. Libstd has run into plenty of these historically.
    //
    // If /proc/self/exe is used then we can typically ignore these as we
    // assume that libbacktrace is "mostly correct" and otherwise doesn't do
    // weird things with "attempted to be correct" dwarf debug info.
    //
    // If we pass in a filename, however, then it's possible on some platforms
    // (like BSDs) where a malicious actor can cause an arbitrary file to be
    // placed at that location. This means that if we tell libbacktrace about a
    // filename it may be using an arbitrary file, possibly causing segfaults.
    // If we don't tell libbacktrace anything though then it won't do anything
    // on platforms that don't support paths like /proc/self/exe!
    //
    // Given all that we try as hard as possible to *not* pass in a filename,
    // but we must on platforms that don't support /proc/self/exe at all.
    cfg_if::cfg_if! {
        if #[cfg(any(target_os = "macos", target_os = "ios"))] {
            // Note that ideally we'd use `std::env::current_exe`, but we can't
            // require `std` here.
            //
            // Use `_NSGetExecutablePath` to load the current executable path
            // into a static area (which if it's too small just give up).
            //
            // Note that we're seriously trusting libbacktrace here to not die
            // on corrupt executables, but it surely does...
            unsafe fn load_filename() -> *const libc::c_char {
                const N: usize = 256;
                static mut BUF: [u8; N] = [0; N];
                extern {
                    fn _NSGetExecutablePath(
                        buf: *mut libc::c_char,
                        bufsize: *mut u32,
                    ) -> libc::c_int;
                }
                let mut sz: u32 = BUF.len() as u32;
                let ptr = BUF.as_mut_ptr() as *mut libc::c_char;
                if _NSGetExecutablePath(ptr, &mut sz) == 0 {
                    ptr
                } else {
                    ptr::null()
                }
            }
        } else if #[cfg(windows)] {
            use crate::windows::*;

            // Windows has a mode of opening files where after it's opened it
            // can't be deleted. That's in general what we want here because we
            // want to ensure that our executable isn't changing out from under
            // us after we hand it off to libbacktrace, hopefully mitigating the
            // ability to pass in arbitrary data into libbacktrace (which may be
            // mishandled).
            //
            // Given that we do a bit of a dance here to attempt to get a sort
            // of lock on our own image:
            //
            // * Get a handle to the current process, load its filename.
            // * Open a file to that filename with the right flags.
            // * Reload the current process's filename, making sure it's the same
            //
            // If that all passes we in theory have indeed opened our process's
            // file and we're guaranteed it won't change. FWIW a bunch of this
            // is copied from libstd historically, so this is my best
            // interpretation of what was happening.
            unsafe fn load_filename() -> *const libc::c_char {
                load_filename_opt().unwrap_or(ptr::null())
            }

            unsafe fn load_filename_opt() -> Result<*const libc::c_char, ()> {
                const N: usize = 256;
                // This lives in static memory so we can return it..
                static mut BUF: [i8; N] = [0; N];
                // ... and this lives on the stack since it's temporary
                let mut stack_buf = [0; N];
                let name1 = query_full_name(&mut BUF)?;

                let handle = CreateFileA(
                    name1.as_ptr(),
                    GENERIC_READ,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                    ptr::null_mut(),
                    OPEN_EXISTING,
                    0,
                    ptr::null_mut(),
                );
                if handle.is_null() {
                    return Err(());
                }

                let name2 = query_full_name(&mut stack_buf)?;
                if name1 != name2 {
                    CloseHandle(handle);
                    return Err(())
                }
                // intentionally leak `handle` here because having that open
                // should preserve our lock on this file name.
                Ok(name1.as_ptr())
            }

            unsafe fn query_full_name(buf: &mut [i8]) -> Result<&[i8], ()> {
                let p1 = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
                let mut len = buf.len() as u32;
                let rc = QueryFullProcessImageNameA(p1, 0, buf.as_mut_ptr(), &mut len);
                CloseHandle(p1);

                // We want to return a slice that is nul-terminated, so if
                // everything was filled in and it equals the total length
                // then equate that to failure.
                //
                // Otherwise when returning success make sure the nul byte is
                // included in the slice.
                if rc == 0 || len == buf.len() as u32 {
                    Err(())
                } else {
                    assert_eq!(buf[len as usize], 0);
                    Ok(&buf[..(len + 1) as usize])
                }
            }


        } else {
            unsafe fn load_filename() -> *const libc::c_char {
                ptr::null()
            }
        }
    }
}

pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) {
    let symaddr = what.address_or_ip() as usize;

    // backtrace errors are currently swept under the rug
    let state = init_state();
    if state.is_null() {
        return dladdr_fallback(what.address_or_ip(), cb);
    }

    // Call the `backtrace_syminfo` API first. This is (from reading the code)
    // guaranteed to call `syminfo_cb` exactly once (or fail with an error
    // presumably). We then handle more within the `syminfo_cb`.
    //
    // Note that we do this since `syminfo` will consult the symbol table,
    // finding symbol names even if there's no debug information in the binary.
    let mut called = false;
    {
        let mut syminfo_state = SyminfoState {
            pc: symaddr,
            cb: &mut |sym| {
                called = true;
                cb(sym);
            },
        };
        bt::backtrace_syminfo(
            state,
            symaddr as uintptr_t,
            syminfo_cb,
            error_cb,
            &mut syminfo_state as *mut _ as *mut _,
        );
    }

    if !called {
        dladdr_fallback(what.address_or_ip(), cb);
    }
}

unsafe fn dladdr_fallback(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) {
    dladdr::resolve(addr, &mut |sym| {
        cb(&super::Symbol {
            inner: Symbol::Dladdr(sym),
        })
    });
}