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
//! Provides demangling support.
//!
//! Currently supported languages:
//!
//! * C++ (without windows)
//! * Rust
//! * Swift
//! * ObjC (only symbol detection)
//!
//! As the demangling schemes for different languages are different the
//! feature set is also inconsistent.  In particular Rust for instance has
//! no overloading so argument types are generally not expected to be
//! encoded into the function name whereas they are in Swift and C++.
//!
//! ## Examples
//!
//! ```rust
//! # extern crate symbolic_demangle;
//! # extern crate symbolic_common;
//! # use symbolic_common::{Language, Name};
//! # use symbolic_demangle::Demangle;
//! # fn main() {
//! let name = Name::new("__ZN3std2io4Read11read_to_end17hb85a0f6802e14499E");
//! assert_eq!(name.detect_language(), Some(Language::Rust));
//! assert_eq!(&name.try_demangle(Default::default()), "std::io::Read::read_to_end");
//! # }
//! ```
extern crate symbolic_common;
extern crate rustc_demangle;

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};
use std::ptr;

use symbolic_common::{ErrorKind, Language, Name, Result};

extern "C" {
    fn symbolic_demangle_swift(
        sym: *const c_char,
        buf: *mut c_char,
        buf_len: usize,
        simplified: c_int,
    ) -> c_int;

    fn symbolic_demangle_is_swift_symbol(sym: *const c_char) -> c_int;

    fn symbolic_demangle_cpp(
        sym: *const c_char,
        buf_out: *mut *mut c_char,
    ) -> c_int;

    fn symbolic_demangle_cpp_free(buf: *mut c_char);
}

/// Defines the output format of the demangler
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
pub enum DemangleFormat {
    Short,
    Full,
}

/// Options for the demangling
#[derive(Debug, Copy, Clone)]
pub struct DemangleOptions {
    /// Format to use for the output
    pub format: DemangleFormat,

    /// Should arguments be returned
    ///
    /// The default behavior is that arguments are not included in the
    /// demangled output, however they are if you convert the symbol
    /// into a string.
    pub with_arguments: bool,
}

impl Default for DemangleOptions {
    fn default() -> DemangleOptions {
        DemangleOptions {
            format: DemangleFormat::Short,
            with_arguments: false,
        }
    }
}

fn is_maybe_objc(ident: &str) -> bool {
    (ident.starts_with("-[") || ident.starts_with("+[")) &&
        ident.ends_with("]")
}

fn is_maybe_cpp(ident: &str) -> bool {
    ident.starts_with("_Z") || ident.starts_with("__Z")
}


fn try_demangle_cpp(ident: &str, opts: DemangleOptions) -> Result<Option<String>> {
    let ident = unsafe {
        let mut buf_out = ptr::null_mut();
        let sym = CString::new(ident.replace("\x00", "")).unwrap();
        let rv = symbolic_demangle_cpp(sym.as_ptr(), &mut buf_out);
        if rv == 0 {
            return Err(ErrorKind::BadSymbol("not a valid C++ identifier".into()).into());
        }
        let rv = CStr::from_ptr(buf_out).to_string_lossy().into_owned();
        symbolic_demangle_cpp_free(buf_out);
        rv
    };

    if opts.with_arguments {
        Ok(Some(ident))
    } else {
        Ok(ident.split('(').next().map(|x| x.to_string()))
    }
}

fn try_demangle_rust(ident: &str, _opts: DemangleOptions) -> Result<Option<String>> {
    if let Ok(dm) = rustc_demangle::try_demangle(ident) {
        Ok(Some(format!("{:#}", dm)))
    } else {
        Err(
            ErrorKind::BadSymbol("Not a valid Rust symbol".into()).into(),
        )
    }
}

fn try_demangle_swift(ident: &str, opts: DemangleOptions) -> Result<Option<String>> {
    let mut buf = vec![0i8; 4096];
    let sym = match CString::new(ident) {
        Ok(sym) => sym,
        Err(_) => {
            return Err(ErrorKind::Internal("embedded null byte").into());
        }
    };

    let simplified = match opts.format {
        DemangleFormat::Short => if opts.with_arguments {
            1
        } else {
            2
        },
        DemangleFormat::Full => 0,
    };

    unsafe {
        let rv = symbolic_demangle_swift(sym.as_ptr(), buf.as_mut_ptr(), buf.len(), simplified);
        if rv == 0 {
            return Ok(None);
        }

        let s = CStr::from_ptr(buf.as_ptr()).to_string_lossy();
        return Ok(Some(s.to_string()));
    }
}

fn try_demangle_objc(ident: &str, _opts: DemangleOptions) -> Result<Option<String>> {
    Ok(Some(ident.to_string()))
}

fn try_demangle_objcpp(ident: &str, opts: DemangleOptions) -> Result<Option<String>> {
    if is_maybe_objc(ident) {
        try_demangle_objc(ident, opts)
    } else if is_maybe_cpp(ident) {
        try_demangle_cpp(ident, opts)
    } else {
        Ok(None)
    }
}

/// Allows to demangle potentially mangled names. Non-mangled names are largely
/// ignored and language detection will not return a language.
///
/// Upon formatting the symbol is automatically demangled (without
/// arguments).
pub trait Demangle {
    /// Infers the language of a mangled name
    ///
    /// In case the symbol is not mangled or not one of the supported languages
    /// the return value will be `None`. If the language of the symbol was
    /// specified explicitly, this is returned instead.
    fn detect_language(&self) -> Option<Language>;

    /// Demangles the name with the given options
    fn demangle(&self, opts: DemangleOptions) -> Result<Option<String>>;

    /// Tries to demangle the name and falls back to the original name
    fn try_demangle(&self, opts: DemangleOptions) -> String;
}

impl<'a> Demangle for Name<'a> {
    fn detect_language(&self) -> Option<Language> {
        if let Some(lang) = self.language() {
            return Some(lang);
        }

        if is_maybe_objc(self.as_str()) {
            return Some(Language::ObjC);
        }

        if rustc_demangle::try_demangle(self.as_str()).is_ok() {
            return Some(Language::Rust);
        }

        if is_maybe_cpp(self.as_str()) {
            return Some(Language::Cpp);
        }

        // swift?
        if let Ok(sym) = CString::new(self.as_str()) {
            unsafe {
                if symbolic_demangle_is_swift_symbol(sym.as_ptr()) != 0 {
                    return Some(Language::Swift);
                }
            }
        }

        None
    }

    fn demangle(&self, opts: DemangleOptions) -> Result<Option<String>> {
        use Language::*;
        match self.detect_language() {
            Some(ObjC) => try_demangle_objc(self.as_str(), opts),
            Some(ObjCpp) => try_demangle_objcpp(self.as_str(), opts),
            Some(Rust) => try_demangle_rust(self.as_str(), opts),
            Some(Cpp) => try_demangle_cpp(self.as_str(), opts),
            Some(Swift) => try_demangle_swift(self.as_str(), opts),
            _ => Ok(None),
        }
    }

    fn try_demangle(&self, opts: DemangleOptions) -> String {
        match self.demangle(opts) {
            Ok(Some(demangled)) => demangled,
            _ => self.as_str().into(),
        }
    }
}

/// Demangles an identifier and falls back to the original symbol.
///
/// This is a shortcut for using ``Name::try_demangle``.
///
/// ```
/// # use symbolic_demangle::*;
/// let rv = demangle("_ZN3foo3barE");
/// assert_eq!(&rv, "foo::bar");
/// ```
pub fn demangle(ident: &str) -> String {
    Name::new(ident).try_demangle(Default::default())
}