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
//! This crate can parse a C++ “mangled” linker symbol name into a Rust value
//! describing what the name refers to: a variable, a function, a virtual table,
//! etc. The description type implements `Display`, producing human-readable
//! text describing the mangled name. Debuggers and profilers can use this crate
//! to provide more meaningful output.
//!
//! C++ requires the compiler to choose names for linker symbols consistently
//! across compilation units, so that two compilation units that have seen the
//! same declarations can pair up definitions in one unit with references in
//! another.  Almost all platforms other than Microsoft Windows follow the
//! [Itanium C++ ABI][itanium]'s rules for this.
//!
//! [itanium]: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
//!
//! For example, suppose a C++ compilation unit has the definition:
//!
//! ```c++
//! namespace space {
//!   int foo(int x, int y) { return x+y; }
//! }
//! ```
//!
//! The Itanium C++ ABI specifies that the linker symbol for that function must
//! be named `_ZN5space3fooEii`. This crate can parse that name into a Rust
//! value representing its structure. Formatting the value with the `format!`
//! macro or the `std::string::ToString::to_string` trait method yields the
//! string `space::foo(int, int)`, which is more meaningful to the C++
//! developer.

#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(unsafe_code)]
// Clippy stuff.
#![allow(unknown_lints)]
#![allow(clippy::inline_always)]
#![allow(clippy::redundant_field_names)]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;

#[cfg(not(feature = "alloc"))]
compile_error!("`alloc` or `std` feature is required for this crate");

#[macro_use]
mod logging;

pub mod ast;
pub mod error;
mod index_str;
mod subs;

use alloc::string::String;
use alloc::vec::Vec;
use ast::{Demangle, Parse, ParseContext};
use core::fmt;
use core::num::NonZeroU32;
use error::{Error, Result};
use index_str::IndexStr;

/// Options to control the parsing process.
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct ParseOptions {
    recursion_limit: Option<NonZeroU32>,
}

impl ParseOptions {
    /// Set the limit on recursion depth during the parsing phase. A low
    /// limit will cause valid symbols to be rejected, but a high limit may
    /// allow pathological symbols to overflow the stack during parsing.
    /// The default value is 96, which will not overflow the stack even in
    /// a debug build.
    pub fn recursion_limit(mut self, limit: u32) -> Self {
        self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0"));
        self
    }
}

/// Options to control the demangling process.
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct DemangleOptions {
    no_params: bool,
    no_return_type: bool,
    hide_expression_literal_types: bool,
    recursion_limit: Option<NonZeroU32>,
}

impl DemangleOptions {
    /// Construct a new `DemangleOptions` with the default values.
    pub fn new() -> Self {
        Default::default()
    }

    /// Do not display function arguments.
    pub fn no_params(mut self) -> Self {
        self.no_params = true;
        self
    }

    /// Do not display the function return type.
    pub fn no_return_type(mut self) -> Self {
        self.no_return_type = true;
        self
    }

    /// Hide type annotations in template value parameters.
    /// These are not needed to distinguish template instances
    /// so this can make it easier to match user-provided
    /// template instance names.
    pub fn hide_expression_literal_types(mut self) -> Self {
        self.hide_expression_literal_types = true;
        self
    }

    /// Set the limit on recursion depth during the demangling phase. A low
    /// limit will cause valid symbols to be rejected, but a high limit may
    /// allow pathological symbols to overflow the stack during demangling.
    /// The default value is 128.
    pub fn recursion_limit(mut self, limit: u32) -> Self {
        self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0"));
        self
    }
}

/// A `Symbol` which owns the underlying storage for the mangled name.
pub type OwnedSymbol = Symbol<Vec<u8>>;

/// A `Symbol` which borrows the underlying storage for the mangled name.
pub type BorrowedSymbol<'a> = Symbol<&'a [u8]>;

/// A mangled symbol that has been parsed into an AST.
///
/// This is generic over some storage type `T` which can be either owned or
/// borrowed. See the `OwnedSymbol` and `BorrowedSymbol` type aliases.
#[derive(Clone, Debug, PartialEq)]
pub struct Symbol<T> {
    raw: T,
    substitutions: subs::SubstitutionTable,
    parsed: ast::MangledName,
}

impl<T> Symbol<T>
where
    T: AsRef<[u8]>,
{
    /// Given some raw storage, parse the mangled symbol from it with the default
    /// options.
    ///
    /// ```
    /// use cpp_demangle::Symbol;
    /// use std::string::ToString;
    ///
    /// // First, something easy :)
    ///
    /// let mangled = b"_ZN5space3fooEibc";
    ///
    /// let sym = Symbol::new(&mangled[..])
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(demangled, "space::foo(int, bool, char)");
    ///
    /// // Now let's try something a little more complicated!
    ///
    /// let mangled =
    ///     b"__Z28JS_GetPropertyDescriptorByIdP9JSContextN2JS6HandleIP8JSObjectEENS2_I4jsidEENS1_13MutableHandleINS1_18PropertyDescriptorEEE";
    ///
    /// let sym = Symbol::new(&mangled[..])
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(
    ///     demangled,
    ///     "JS_GetPropertyDescriptorById(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::PropertyDescriptor>)"
    /// );
    /// ```
    #[inline]
    pub fn new(raw: T) -> Result<Symbol<T>> {
        Self::new_with_options(raw, &Default::default())
    }

    /// Given some raw storage, parse the mangled symbol from it.
    ///
    /// ```
    /// use cpp_demangle::{ParseOptions, Symbol};
    /// use std::string::ToString;
    ///
    /// // First, something easy :)
    ///
    /// let mangled = b"_ZN5space3fooEibc";
    ///
    /// let parse_options = ParseOptions::default()
    ///     .recursion_limit(1024);
    ///
    /// let sym = Symbol::new_with_options(&mangled[..], &parse_options)
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(demangled, "space::foo(int, bool, char)");
    ///
    /// // Now let's try something a little more complicated!
    ///
    /// let mangled =
    ///     b"__Z28JS_GetPropertyDescriptorByIdP9JSContextN2JS6HandleIP8JSObjectEENS2_I4jsidEENS1_13MutableHandleINS1_18PropertyDescriptorEEE";
    ///
    /// let sym = Symbol::new(&mangled[..])
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(
    ///     demangled,
    ///     "JS_GetPropertyDescriptorById(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::PropertyDescriptor>)"
    /// );
    /// ```
    pub fn new_with_options(raw: T, options: &ParseOptions) -> Result<Symbol<T>> {
        let mut substitutions = subs::SubstitutionTable::new();

        let parsed = {
            let ctx = ParseContext::new(*options);
            let input = IndexStr::new(raw.as_ref());

            let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, input)?;
            debug_assert!(ctx.recursion_level() == 0);

            if tail.is_empty() {
                parsed
            } else {
                return Err(Error::UnexpectedText);
            }
        };

        let symbol = Symbol {
            raw: raw,
            substitutions: substitutions,
            parsed: parsed,
        };

        log!(
            "Successfully parsed '{}' as

AST = {:#?}

substitutions = {:#?}",
            String::from_utf8_lossy(symbol.raw.as_ref()),
            symbol.parsed,
            symbol.substitutions
        );

        Ok(symbol)
    }

    /// Demangle the symbol and return it as a String.
    ///
    /// Unlike the `ToString` implementation, this function allows options to
    /// be specified.
    ///
    /// ```
    /// use cpp_demangle::{DemangleOptions, Symbol};
    /// use std::string::ToString;
    ///
    /// let mangled = b"_ZN5space3fooEibc";
    ///
    /// let sym = Symbol::new(&mangled[..])
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// let demangled = sym.to_string();
    /// let options = DemangleOptions::default();
    /// let demangled_again = sym.demangle(&options).unwrap();
    /// assert_eq!(demangled_again, demangled);
    /// ```
    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub fn demangle(
        &self,
        options: &DemangleOptions,
    ) -> ::core::result::Result<String, fmt::Error> {
        let mut out = String::new();
        {
            let mut ctx = ast::DemangleContext::new(
                &self.substitutions,
                self.raw.as_ref(),
                *options,
                &mut out,
            );
            self.parsed.demangle(&mut ctx, None)?;
        }

        Ok(out)
    }

    /// Demangle the symbol to a DemangleWrite, which lets the consumer be informed about
    /// syntactic structure.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub fn structured_demangle<W: DemangleWrite>(
        &self,
        out: &mut W,
        options: &DemangleOptions,
    ) -> fmt::Result {
        let mut ctx =
            ast::DemangleContext::new(&self.substitutions, self.raw.as_ref(), *options, out);
        self.parsed.demangle(&mut ctx, None)
    }
}

/// The type of a demangled AST node.
/// This is only partial, not all nodes are represented.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum DemangleNodeType {
    /// Entering a <prefix> production
    Prefix,
    /// Entering a <template-prefix> production
    TemplatePrefix,
    /// Entering a <template-args> production
    TemplateArgs,
    /// Entering a <unqualified-name> production
    UnqualifiedName,
    /// Entering a <template-param> production
    TemplateParam,
    /// Entering a <decltype> production
    Decltype,
    /// Entering a <data-member-prefix> production
    DataMemberPrefix,
    /// Entering a <nested-name> production
    NestedName,
    /// Entering a <special-name> production that is a vtable.
    VirtualTable,
    /// Additional values may be added in the future. Use a
    /// _ pattern for compatibility.
    __NonExhaustive,
}

/// Sink for demangled text that reports syntactic structure.
pub trait DemangleWrite {
    /// Called when we are entering the scope of some AST node.
    fn push_demangle_node(&mut self, _: DemangleNodeType) {}
    /// Same as `fmt::Write::write_str`.
    fn write_string(&mut self, s: &str) -> fmt::Result;
    /// Called when we are exiting the scope of some AST node for
    /// which `push_demangle_node` was called.
    fn pop_demangle_node(&mut self) {}
}

impl<W: fmt::Write> DemangleWrite for W {
    fn write_string(&mut self, s: &str) -> fmt::Result {
        fmt::Write::write_str(self, s)
    }
}

impl<'a, T> Symbol<&'a T>
where
    T: AsRef<[u8]> + ?Sized,
{
    /// Parse a mangled symbol from input and return it and the trailing tail of
    /// bytes that come after the symbol, with the default options.
    ///
    /// While `Symbol::new` will return an error if there is unexpected trailing
    /// bytes, `with_tail` simply returns the trailing bytes along with the
    /// parsed symbol.
    ///
    /// ```
    /// use cpp_demangle::BorrowedSymbol;
    /// use std::string::ToString;
    ///
    /// let mangled = b"_ZN5space3fooEibc and some trailing junk";
    ///
    /// let (sym, tail) = BorrowedSymbol::with_tail(&mangled[..])
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// assert_eq!(tail, b" and some trailing junk");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(demangled, "space::foo(int, bool, char)");
    /// ```
    #[inline]
    pub fn with_tail(input: &'a T) -> Result<(BorrowedSymbol<'a>, &'a [u8])> {
        Self::with_tail_and_options(input, &Default::default())
    }

    /// Parse a mangled symbol from input and return it and the trailing tail of
    /// bytes that come after the symbol.
    ///
    /// While `Symbol::new_with_options` will return an error if there is
    /// unexpected trailing bytes, `with_tail_and_options` simply returns the
    /// trailing bytes along with the parsed symbol.
    ///
    /// ```
    /// use cpp_demangle::{BorrowedSymbol, ParseOptions};
    /// use std::string::ToString;
    ///
    /// let mangled = b"_ZN5space3fooEibc and some trailing junk";
    ///
    /// let parse_options = ParseOptions::default()
    ///     .recursion_limit(1024);
    ///
    /// let (sym, tail) = BorrowedSymbol::with_tail_and_options(&mangled[..], &parse_options)
    ///     .expect("Could not parse mangled symbol!");
    ///
    /// assert_eq!(tail, b" and some trailing junk");
    ///
    /// let demangled = sym.to_string();
    /// assert_eq!(demangled, "space::foo(int, bool, char)");
    /// ```
    pub fn with_tail_and_options(
        input: &'a T,
        options: &ParseOptions,
    ) -> Result<(BorrowedSymbol<'a>, &'a [u8])> {
        let mut substitutions = subs::SubstitutionTable::new();

        let ctx = ParseContext::new(*options);
        let idx_str = IndexStr::new(input.as_ref());
        let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, idx_str)?;
        debug_assert!(ctx.recursion_level() == 0);

        let symbol = Symbol {
            raw: input.as_ref(),
            substitutions: substitutions,
            parsed: parsed,
        };

        log!(
            "Successfully parsed '{}' as

AST = {:#?}

substitutions = {:#?}",
            String::from_utf8_lossy(symbol.raw),
            symbol.parsed,
            symbol.substitutions
        );

        Ok((symbol, tail.into()))
    }
}

impl<T> fmt::Display for Symbol<T>
where
    T: AsRef<[u8]>,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut out = String::new();
        {
            let options = DemangleOptions::default();
            let mut ctx = ast::DemangleContext::new(
                &self.substitutions,
                self.raw.as_ref(),
                options,
                &mut out,
            );
            self.parsed.demangle(&mut ctx, None).map_err(|err| {
                log!("Demangling error: {:#?}", err);
                fmt::Error
            })?;
        }
        write!(f, "{}", &out)
    }
}