• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // For reference check out:
16 // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
17 //
18 // Note that we only have partial C++11 support yet.
19 
20 #include "absl/debugging/internal/demangle.h"
21 
22 #include <cstdint>
23 #include <cstdio>
24 #include <cstdlib>
25 #include <limits>
26 #include <string>
27 
28 #include "absl/base/config.h"
29 
30 #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
31 #include <cxxabi.h>
32 #endif
33 
34 namespace absl {
35 ABSL_NAMESPACE_BEGIN
36 namespace debugging_internal {
37 
38 typedef struct {
39   const char *abbrev;
40   const char *real_name;
41   // Number of arguments in <expression> context, or 0 if disallowed.
42   int arity;
43 } AbbrevPair;
44 
45 // List of operators from Itanium C++ ABI.
46 static const AbbrevPair kOperatorList[] = {
47     // New has special syntax (not currently supported).
48     {"nw", "new", 0},
49     {"na", "new[]", 0},
50 
51     // Works except that the 'gs' prefix is not supported.
52     {"dl", "delete", 1},
53     {"da", "delete[]", 1},
54 
55     {"ps", "+", 1},  // "positive"
56     {"ng", "-", 1},  // "negative"
57     {"ad", "&", 1},  // "address-of"
58     {"de", "*", 1},  // "dereference"
59     {"co", "~", 1},
60 
61     {"pl", "+", 2},
62     {"mi", "-", 2},
63     {"ml", "*", 2},
64     {"dv", "/", 2},
65     {"rm", "%", 2},
66     {"an", "&", 2},
67     {"or", "|", 2},
68     {"eo", "^", 2},
69     {"aS", "=", 2},
70     {"pL", "+=", 2},
71     {"mI", "-=", 2},
72     {"mL", "*=", 2},
73     {"dV", "/=", 2},
74     {"rM", "%=", 2},
75     {"aN", "&=", 2},
76     {"oR", "|=", 2},
77     {"eO", "^=", 2},
78     {"ls", "<<", 2},
79     {"rs", ">>", 2},
80     {"lS", "<<=", 2},
81     {"rS", ">>=", 2},
82     {"eq", "==", 2},
83     {"ne", "!=", 2},
84     {"lt", "<", 2},
85     {"gt", ">", 2},
86     {"le", "<=", 2},
87     {"ge", ">=", 2},
88     {"nt", "!", 1},
89     {"aa", "&&", 2},
90     {"oo", "||", 2},
91     {"pp", "++", 1},
92     {"mm", "--", 1},
93     {"cm", ",", 2},
94     {"pm", "->*", 2},
95     {"pt", "->", 0},  // Special syntax
96     {"cl", "()", 0},  // Special syntax
97     {"ix", "[]", 2},
98     {"qu", "?", 3},
99     {"st", "sizeof", 0},  // Special syntax
100     {"sz", "sizeof", 1},  // Not a real operator name, but used in expressions.
101     {nullptr, nullptr, 0},
102 };
103 
104 // List of builtin types from Itanium C++ ABI.
105 //
106 // Invariant: only one- or two-character type abbreviations here.
107 static const AbbrevPair kBuiltinTypeList[] = {
108     {"v", "void", 0},
109     {"w", "wchar_t", 0},
110     {"b", "bool", 0},
111     {"c", "char", 0},
112     {"a", "signed char", 0},
113     {"h", "unsigned char", 0},
114     {"s", "short", 0},
115     {"t", "unsigned short", 0},
116     {"i", "int", 0},
117     {"j", "unsigned int", 0},
118     {"l", "long", 0},
119     {"m", "unsigned long", 0},
120     {"x", "long long", 0},
121     {"y", "unsigned long long", 0},
122     {"n", "__int128", 0},
123     {"o", "unsigned __int128", 0},
124     {"f", "float", 0},
125     {"d", "double", 0},
126     {"e", "long double", 0},
127     {"g", "__float128", 0},
128     {"z", "ellipsis", 0},
129 
130     {"De", "decimal128", 0},      // IEEE 754r decimal floating point (128 bits)
131     {"Dd", "decimal64", 0},       // IEEE 754r decimal floating point (64 bits)
132     {"Dc", "decltype(auto)", 0},
133     {"Da", "auto", 0},
134     {"Dn", "std::nullptr_t", 0},  // i.e., decltype(nullptr)
135     {"Df", "decimal32", 0},       // IEEE 754r decimal floating point (32 bits)
136     {"Di", "char32_t", 0},
137     {"Du", "char8_t", 0},
138     {"Ds", "char16_t", 0},
139     {"Dh", "float16", 0},         // IEEE 754r half-precision float (16 bits)
140     {nullptr, nullptr, 0},
141 };
142 
143 // List of substitutions Itanium C++ ABI.
144 static const AbbrevPair kSubstitutionList[] = {
145     {"St", "", 0},
146     {"Sa", "allocator", 0},
147     {"Sb", "basic_string", 0},
148     // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
149     {"Ss", "string", 0},
150     // std::basic_istream<char, std::char_traits<char> >
151     {"Si", "istream", 0},
152     // std::basic_ostream<char, std::char_traits<char> >
153     {"So", "ostream", 0},
154     // std::basic_iostream<char, std::char_traits<char> >
155     {"Sd", "iostream", 0},
156     {nullptr, nullptr, 0},
157 };
158 
159 // State needed for demangling.  This struct is copied in almost every stack
160 // frame, so every byte counts.
161 typedef struct {
162   int mangled_idx;                     // Cursor of mangled name.
163   int out_cur_idx;                     // Cursor of output string.
164   int prev_name_idx;                   // For constructors/destructors.
165   unsigned int prev_name_length : 16;  // For constructors/destructors.
166   signed int nest_level : 15;          // For nested names.
167   unsigned int append : 1;             // Append flag.
168   // Note: for some reason MSVC can't pack "bool append : 1" into the same int
169   // with the above two fields, so we use an int instead.  Amusingly it can pack
170   // "signed bool" as expected, but relying on that to continue to be a legal
171   // type seems ill-advised (as it's illegal in at least clang).
172 } ParseState;
173 
174 static_assert(sizeof(ParseState) == 4 * sizeof(int),
175               "unexpected size of ParseState");
176 
177 // One-off state for demangling that's not subject to backtracking -- either
178 // constant data, data that's intentionally immune to backtracking (steps), or
179 // data that would never be changed by backtracking anyway (recursion_depth).
180 //
181 // Only one copy of this exists for each call to Demangle, so the size of this
182 // struct is nearly inconsequential.
183 typedef struct {
184   const char *mangled_begin;  // Beginning of input string.
185   char *out;                  // Beginning of output string.
186   int out_end_idx;            // One past last allowed output character.
187   int recursion_depth;        // For stack exhaustion prevention.
188   int steps;               // Cap how much work we'll do, regardless of depth.
189   ParseState parse_state;  // Backtrackable state copied for most frames.
190 } State;
191 
192 namespace {
193 // Prevent deep recursion / stack exhaustion.
194 // Also prevent unbounded handling of complex inputs.
195 class ComplexityGuard {
196  public:
ComplexityGuard(State * state)197   explicit ComplexityGuard(State *state) : state_(state) {
198     ++state->recursion_depth;
199     ++state->steps;
200   }
~ComplexityGuard()201   ~ComplexityGuard() { --state_->recursion_depth; }
202 
203   // 256 levels of recursion seems like a reasonable upper limit on depth.
204   // 128 is not enough to demagle synthetic tests from demangle_unittest.txt:
205   // "_ZaaZZZZ..." and "_ZaaZcvZcvZ..."
206   static constexpr int kRecursionDepthLimit = 256;
207 
208   // We're trying to pick a charitable upper-limit on how many parse steps are
209   // necessary to handle something that a human could actually make use of.
210   // This is mostly in place as a bound on how much work we'll do if we are
211   // asked to demangle an mangled name from an untrusted source, so it should be
212   // much larger than the largest expected symbol, but much smaller than the
213   // amount of work we can do in, e.g., a second.
214   //
215   // Some real-world symbols from an arbitrary binary started failing between
216   // 2^12 and 2^13, so we multiply the latter by an extra factor of 16 to set
217   // the limit.
218   //
219   // Spending one second on 2^17 parse steps would require each step to take
220   // 7.6us, or ~30000 clock cycles, so it's safe to say this can be done in
221   // under a second.
222   static constexpr int kParseStepsLimit = 1 << 17;
223 
IsTooComplex() const224   bool IsTooComplex() const {
225     return state_->recursion_depth > kRecursionDepthLimit ||
226            state_->steps > kParseStepsLimit;
227   }
228 
229  private:
230   State *state_;
231 };
232 }  // namespace
233 
234 // We don't use strlen() in libc since it's not guaranteed to be async
235 // signal safe.
StrLen(const char * str)236 static size_t StrLen(const char *str) {
237   size_t len = 0;
238   while (*str != '\0') {
239     ++str;
240     ++len;
241   }
242   return len;
243 }
244 
245 // Returns true if "str" has at least "n" characters remaining.
AtLeastNumCharsRemaining(const char * str,size_t n)246 static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
247   for (size_t i = 0; i < n; ++i) {
248     if (str[i] == '\0') {
249       return false;
250     }
251   }
252   return true;
253 }
254 
255 // Returns true if "str" has "prefix" as a prefix.
StrPrefix(const char * str,const char * prefix)256 static bool StrPrefix(const char *str, const char *prefix) {
257   size_t i = 0;
258   while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
259     ++i;
260   }
261   return prefix[i] == '\0';  // Consumed everything in "prefix".
262 }
263 
InitState(State * state,const char * mangled,char * out,size_t out_size)264 static void InitState(State* state,
265                       const char* mangled,
266                       char* out,
267                       size_t out_size) {
268   state->mangled_begin = mangled;
269   state->out = out;
270   state->out_end_idx = static_cast<int>(out_size);
271   state->recursion_depth = 0;
272   state->steps = 0;
273 
274   state->parse_state.mangled_idx = 0;
275   state->parse_state.out_cur_idx = 0;
276   state->parse_state.prev_name_idx = 0;
277   state->parse_state.prev_name_length = 0;
278   state->parse_state.nest_level = -1;
279   state->parse_state.append = true;
280 }
281 
RemainingInput(State * state)282 static inline const char *RemainingInput(State *state) {
283   return &state->mangled_begin[state->parse_state.mangled_idx];
284 }
285 
286 // Returns true and advances "mangled_idx" if we find "one_char_token"
287 // at "mangled_idx" position.  It is assumed that "one_char_token" does
288 // not contain '\0'.
ParseOneCharToken(State * state,const char one_char_token)289 static bool ParseOneCharToken(State *state, const char one_char_token) {
290   ComplexityGuard guard(state);
291   if (guard.IsTooComplex()) return false;
292   if (RemainingInput(state)[0] == one_char_token) {
293     ++state->parse_state.mangled_idx;
294     return true;
295   }
296   return false;
297 }
298 
299 // Returns true and advances "mangled_cur" if we find "two_char_token"
300 // at "mangled_cur" position.  It is assumed that "two_char_token" does
301 // not contain '\0'.
ParseTwoCharToken(State * state,const char * two_char_token)302 static bool ParseTwoCharToken(State *state, const char *two_char_token) {
303   ComplexityGuard guard(state);
304   if (guard.IsTooComplex()) return false;
305   if (RemainingInput(state)[0] == two_char_token[0] &&
306       RemainingInput(state)[1] == two_char_token[1]) {
307     state->parse_state.mangled_idx += 2;
308     return true;
309   }
310   return false;
311 }
312 
313 // Returns true and advances "mangled_cur" if we find any character in
314 // "char_class" at "mangled_cur" position.
ParseCharClass(State * state,const char * char_class)315 static bool ParseCharClass(State *state, const char *char_class) {
316   ComplexityGuard guard(state);
317   if (guard.IsTooComplex()) return false;
318   if (RemainingInput(state)[0] == '\0') {
319     return false;
320   }
321   const char *p = char_class;
322   for (; *p != '\0'; ++p) {
323     if (RemainingInput(state)[0] == *p) {
324       ++state->parse_state.mangled_idx;
325       return true;
326     }
327   }
328   return false;
329 }
330 
ParseDigit(State * state,int * digit)331 static bool ParseDigit(State *state, int *digit) {
332   char c = RemainingInput(state)[0];
333   if (ParseCharClass(state, "0123456789")) {
334     if (digit != nullptr) {
335       *digit = c - '0';
336     }
337     return true;
338   }
339   return false;
340 }
341 
342 // This function is used for handling an optional non-terminal.
Optional(bool)343 static bool Optional(bool /*status*/) { return true; }
344 
345 // This function is used for handling <non-terminal>+ syntax.
346 typedef bool (*ParseFunc)(State *);
OneOrMore(ParseFunc parse_func,State * state)347 static bool OneOrMore(ParseFunc parse_func, State *state) {
348   if (parse_func(state)) {
349     while (parse_func(state)) {
350     }
351     return true;
352   }
353   return false;
354 }
355 
356 // This function is used for handling <non-terminal>* syntax. The function
357 // always returns true and must be followed by a termination token or a
358 // terminating sequence not handled by parse_func (e.g.
359 // ParseOneCharToken(state, 'E')).
ZeroOrMore(ParseFunc parse_func,State * state)360 static bool ZeroOrMore(ParseFunc parse_func, State *state) {
361   while (parse_func(state)) {
362   }
363   return true;
364 }
365 
366 // Append "str" at "out_cur_idx".  If there is an overflow, out_cur_idx is
367 // set to out_end_idx+1.  The output string is ensured to
368 // always terminate with '\0' as long as there is no overflow.
Append(State * state,const char * const str,const size_t length)369 static void Append(State *state, const char *const str, const size_t length) {
370   for (size_t i = 0; i < length; ++i) {
371     if (state->parse_state.out_cur_idx + 1 <
372         state->out_end_idx) {  // +1 for '\0'
373       state->out[state->parse_state.out_cur_idx++] = str[i];
374     } else {
375       // signal overflow
376       state->parse_state.out_cur_idx = state->out_end_idx + 1;
377       break;
378     }
379   }
380   if (state->parse_state.out_cur_idx < state->out_end_idx) {
381     state->out[state->parse_state.out_cur_idx] =
382         '\0';  // Terminate it with '\0'
383   }
384 }
385 
386 // We don't use equivalents in libc to avoid locale issues.
IsLower(char c)387 static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
388 
IsAlpha(char c)389 static bool IsAlpha(char c) {
390   return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
391 }
392 
IsDigit(char c)393 static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
394 
395 // Returns true if "str" is a function clone suffix.  These suffixes are used
396 // by GCC 4.5.x and later versions (and our locally-modified version of GCC
397 // 4.4.x) to indicate functions which have been cloned during optimization.
398 // We treat any sequence (.<alpha>+.<digit>+)+ as a function clone suffix.
399 // Additionally, '_' is allowed along with the alphanumeric sequence.
IsFunctionCloneSuffix(const char * str)400 static bool IsFunctionCloneSuffix(const char *str) {
401   size_t i = 0;
402   while (str[i] != '\0') {
403     bool parsed = false;
404     // Consume a single [.<alpha> | _]*[.<digit>]* sequence.
405     if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
406       parsed = true;
407       i += 2;
408       while (IsAlpha(str[i]) || str[i] == '_') {
409         ++i;
410       }
411     }
412     if (str[i] == '.' && IsDigit(str[i + 1])) {
413       parsed = true;
414       i += 2;
415       while (IsDigit(str[i])) {
416         ++i;
417       }
418     }
419     if (!parsed)
420       return false;
421   }
422   return true;  // Consumed everything in "str".
423 }
424 
EndsWith(State * state,const char chr)425 static bool EndsWith(State *state, const char chr) {
426   return state->parse_state.out_cur_idx > 0 &&
427          state->parse_state.out_cur_idx < state->out_end_idx &&
428          chr == state->out[state->parse_state.out_cur_idx - 1];
429 }
430 
431 // Append "str" with some tweaks, iff "append" state is true.
MaybeAppendWithLength(State * state,const char * const str,const size_t length)432 static void MaybeAppendWithLength(State *state, const char *const str,
433                                   const size_t length) {
434   if (state->parse_state.append && length > 0) {
435     // Append a space if the output buffer ends with '<' and "str"
436     // starts with '<' to avoid <<<.
437     if (str[0] == '<' && EndsWith(state, '<')) {
438       Append(state, " ", 1);
439     }
440     // Remember the last identifier name for ctors/dtors,
441     // but only if we haven't yet overflown the buffer.
442     if (state->parse_state.out_cur_idx < state->out_end_idx &&
443         (IsAlpha(str[0]) || str[0] == '_')) {
444       state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
445       state->parse_state.prev_name_length = static_cast<unsigned int>(length);
446     }
447     Append(state, str, length);
448   }
449 }
450 
451 // Appends a positive decimal number to the output if appending is enabled.
MaybeAppendDecimal(State * state,int val)452 static bool MaybeAppendDecimal(State *state, int val) {
453   // Max {32-64}-bit unsigned int is 20 digits.
454   constexpr size_t kMaxLength = 20;
455   char buf[kMaxLength];
456 
457   // We can't use itoa or sprintf as neither is specified to be
458   // async-signal-safe.
459   if (state->parse_state.append) {
460     // We can't have a one-before-the-beginning pointer, so instead start with
461     // one-past-the-end and manipulate one character before the pointer.
462     char *p = &buf[kMaxLength];
463     do {  // val=0 is the only input that should write a leading zero digit.
464       *--p = static_cast<char>((val % 10) + '0');
465       val /= 10;
466     } while (p > buf && val != 0);
467 
468     // 'p' landed on the last character we set.  How convenient.
469     Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
470   }
471 
472   return true;
473 }
474 
475 // A convenient wrapper around MaybeAppendWithLength().
476 // Returns true so that it can be placed in "if" conditions.
MaybeAppend(State * state,const char * const str)477 static bool MaybeAppend(State *state, const char *const str) {
478   if (state->parse_state.append) {
479     size_t length = StrLen(str);
480     MaybeAppendWithLength(state, str, length);
481   }
482   return true;
483 }
484 
485 // This function is used for handling nested names.
EnterNestedName(State * state)486 static bool EnterNestedName(State *state) {
487   state->parse_state.nest_level = 0;
488   return true;
489 }
490 
491 // This function is used for handling nested names.
LeaveNestedName(State * state,int16_t prev_value)492 static bool LeaveNestedName(State *state, int16_t prev_value) {
493   state->parse_state.nest_level = prev_value;
494   return true;
495 }
496 
497 // Disable the append mode not to print function parameters, etc.
DisableAppend(State * state)498 static bool DisableAppend(State *state) {
499   state->parse_state.append = false;
500   return true;
501 }
502 
503 // Restore the append mode to the previous state.
RestoreAppend(State * state,bool prev_value)504 static bool RestoreAppend(State *state, bool prev_value) {
505   state->parse_state.append = prev_value;
506   return true;
507 }
508 
509 // Increase the nest level for nested names.
MaybeIncreaseNestLevel(State * state)510 static void MaybeIncreaseNestLevel(State *state) {
511   if (state->parse_state.nest_level > -1) {
512     ++state->parse_state.nest_level;
513   }
514 }
515 
516 // Appends :: for nested names if necessary.
MaybeAppendSeparator(State * state)517 static void MaybeAppendSeparator(State *state) {
518   if (state->parse_state.nest_level >= 1) {
519     MaybeAppend(state, "::");
520   }
521 }
522 
523 // Cancel the last separator if necessary.
MaybeCancelLastSeparator(State * state)524 static void MaybeCancelLastSeparator(State *state) {
525   if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
526       state->parse_state.out_cur_idx >= 2) {
527     state->parse_state.out_cur_idx -= 2;
528     state->out[state->parse_state.out_cur_idx] = '\0';
529   }
530 }
531 
532 // Returns true if the identifier of the given length pointed to by
533 // "mangled_cur" is anonymous namespace.
IdentifierIsAnonymousNamespace(State * state,size_t length)534 static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
535   // Returns true if "anon_prefix" is a proper prefix of "mangled_cur".
536   static const char anon_prefix[] = "_GLOBAL__N_";
537   return (length > (sizeof(anon_prefix) - 1) &&
538           StrPrefix(RemainingInput(state), anon_prefix));
539 }
540 
541 // Forward declarations of our parsing functions.
542 static bool ParseMangledName(State *state);
543 static bool ParseEncoding(State *state);
544 static bool ParseName(State *state);
545 static bool ParseUnscopedName(State *state);
546 static bool ParseNestedName(State *state);
547 static bool ParsePrefix(State *state);
548 static bool ParseUnqualifiedName(State *state);
549 static bool ParseSourceName(State *state);
550 static bool ParseLocalSourceName(State *state);
551 static bool ParseUnnamedTypeName(State *state);
552 static bool ParseNumber(State *state, int *number_out);
553 static bool ParseFloatNumber(State *state);
554 static bool ParseSeqId(State *state);
555 static bool ParseIdentifier(State *state, size_t length);
556 static bool ParseOperatorName(State *state, int *arity);
557 static bool ParseSpecialName(State *state);
558 static bool ParseCallOffset(State *state);
559 static bool ParseNVOffset(State *state);
560 static bool ParseVOffset(State *state);
561 static bool ParseAbiTags(State *state);
562 static bool ParseCtorDtorName(State *state);
563 static bool ParseDecltype(State *state);
564 static bool ParseType(State *state);
565 static bool ParseCVQualifiers(State *state);
566 static bool ParseBuiltinType(State *state);
567 static bool ParseFunctionType(State *state);
568 static bool ParseBareFunctionType(State *state);
569 static bool ParseClassEnumType(State *state);
570 static bool ParseArrayType(State *state);
571 static bool ParsePointerToMemberType(State *state);
572 static bool ParseTemplateParam(State *state);
573 static bool ParseTemplateTemplateParam(State *state);
574 static bool ParseTemplateArgs(State *state);
575 static bool ParseTemplateArg(State *state);
576 static bool ParseBaseUnresolvedName(State *state);
577 static bool ParseUnresolvedName(State *state);
578 static bool ParseExpression(State *state);
579 static bool ParseExprPrimary(State *state);
580 static bool ParseExprCastValue(State *state);
581 static bool ParseLocalName(State *state);
582 static bool ParseLocalNameSuffix(State *state);
583 static bool ParseDiscriminator(State *state);
584 static bool ParseSubstitution(State *state, bool accept_std);
585 
586 // Implementation note: the following code is a straightforward
587 // translation of the Itanium C++ ABI defined in BNF with a couple of
588 // exceptions.
589 //
590 // - Support GNU extensions not defined in the Itanium C++ ABI
591 // - <prefix> and <template-prefix> are combined to avoid infinite loop
592 // - Reorder patterns to shorten the code
593 // - Reorder patterns to give greedier functions precedence
594 //   We'll mark "Less greedy than" for these cases in the code
595 //
596 // Each parsing function changes the parse state and returns true on
597 // success, or returns false and doesn't change the parse state (note:
598 // the parse-steps counter increases regardless of success or failure).
599 // To ensure that the parse state isn't changed in the latter case, we
600 // save the original state before we call multiple parsing functions
601 // consecutively with &&, and restore it if unsuccessful.  See
602 // ParseEncoding() as an example of this convention.  We follow the
603 // convention throughout the code.
604 //
605 // Originally we tried to do demangling without following the full ABI
606 // syntax but it turned out we needed to follow the full syntax to
607 // parse complicated cases like nested template arguments.  Note that
608 // implementing a full-fledged demangler isn't trivial (libiberty's
609 // cp-demangle.c has +4300 lines).
610 //
611 // Note that (foo) in <(foo) ...> is a modifier to be ignored.
612 //
613 // Reference:
614 // - Itanium C++ ABI
615 //   <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
616 
617 // <mangled-name> ::= _Z <encoding>
ParseMangledName(State * state)618 static bool ParseMangledName(State *state) {
619   ComplexityGuard guard(state);
620   if (guard.IsTooComplex()) return false;
621   return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
622 }
623 
624 // <encoding> ::= <(function) name> <bare-function-type>
625 //            ::= <(data) name>
626 //            ::= <special-name>
ParseEncoding(State * state)627 static bool ParseEncoding(State *state) {
628   ComplexityGuard guard(state);
629   if (guard.IsTooComplex()) return false;
630   // Implementing the first two productions together as <name>
631   // [<bare-function-type>] avoids exponential blowup of backtracking.
632   //
633   // Since Optional(...) can't fail, there's no need to copy the state for
634   // backtracking.
635   if (ParseName(state) && Optional(ParseBareFunctionType(state))) {
636     return true;
637   }
638 
639   if (ParseSpecialName(state)) {
640     return true;
641   }
642   return false;
643 }
644 
645 // <name> ::= <nested-name>
646 //        ::= <unscoped-template-name> <template-args>
647 //        ::= <unscoped-name>
648 //        ::= <local-name>
ParseName(State * state)649 static bool ParseName(State *state) {
650   ComplexityGuard guard(state);
651   if (guard.IsTooComplex()) return false;
652   if (ParseNestedName(state) || ParseLocalName(state)) {
653     return true;
654   }
655 
656   // We reorganize the productions to avoid re-parsing unscoped names.
657   // - Inline <unscoped-template-name> productions:
658   //   <name> ::= <substitution> <template-args>
659   //          ::= <unscoped-name> <template-args>
660   //          ::= <unscoped-name>
661   // - Merge the two productions that start with unscoped-name:
662   //   <name> ::= <unscoped-name> [<template-args>]
663 
664   ParseState copy = state->parse_state;
665   // "std<...>" isn't a valid name.
666   if (ParseSubstitution(state, /*accept_std=*/false) &&
667       ParseTemplateArgs(state)) {
668     return true;
669   }
670   state->parse_state = copy;
671 
672   // Note there's no need to restore state after this since only the first
673   // subparser can fail.
674   return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
675 }
676 
677 // <unscoped-name> ::= <unqualified-name>
678 //                 ::= St <unqualified-name>
ParseUnscopedName(State * state)679 static bool ParseUnscopedName(State *state) {
680   ComplexityGuard guard(state);
681   if (guard.IsTooComplex()) return false;
682   if (ParseUnqualifiedName(state)) {
683     return true;
684   }
685 
686   ParseState copy = state->parse_state;
687   if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
688       ParseUnqualifiedName(state)) {
689     return true;
690   }
691   state->parse_state = copy;
692   return false;
693 }
694 
695 // <ref-qualifer> ::= R // lvalue method reference qualifier
696 //                ::= O // rvalue method reference qualifier
ParseRefQualifier(State * state)697 static inline bool ParseRefQualifier(State *state) {
698   return ParseCharClass(state, "OR");
699 }
700 
701 // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix>
702 //                   <unqualified-name> E
703 //               ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
704 //                   <template-args> E
ParseNestedName(State * state)705 static bool ParseNestedName(State *state) {
706   ComplexityGuard guard(state);
707   if (guard.IsTooComplex()) return false;
708   ParseState copy = state->parse_state;
709   if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
710       Optional(ParseCVQualifiers(state)) &&
711       Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
712       LeaveNestedName(state, copy.nest_level) &&
713       ParseOneCharToken(state, 'E')) {
714     return true;
715   }
716   state->parse_state = copy;
717   return false;
718 }
719 
720 // This part is tricky.  If we literally translate them to code, we'll
721 // end up infinite loop.  Hence we merge them to avoid the case.
722 //
723 // <prefix> ::= <prefix> <unqualified-name>
724 //          ::= <template-prefix> <template-args>
725 //          ::= <template-param>
726 //          ::= <substitution>
727 //          ::= # empty
728 // <template-prefix> ::= <prefix> <(template) unqualified-name>
729 //                   ::= <template-param>
730 //                   ::= <substitution>
ParsePrefix(State * state)731 static bool ParsePrefix(State *state) {
732   ComplexityGuard guard(state);
733   if (guard.IsTooComplex()) return false;
734   bool has_something = false;
735   while (true) {
736     MaybeAppendSeparator(state);
737     if (ParseTemplateParam(state) ||
738         ParseSubstitution(state, /*accept_std=*/true) ||
739         ParseUnscopedName(state) ||
740         (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) {
741       has_something = true;
742       MaybeIncreaseNestLevel(state);
743       continue;
744     }
745     MaybeCancelLastSeparator(state);
746     if (has_something && ParseTemplateArgs(state)) {
747       return ParsePrefix(state);
748     } else {
749       break;
750     }
751   }
752   return true;
753 }
754 
755 // <unqualified-name> ::= <operator-name> [<abi-tags>]
756 //                    ::= <ctor-dtor-name> [<abi-tags>]
757 //                    ::= <source-name> [<abi-tags>]
758 //                    ::= <local-source-name> [<abi-tags>]
759 //                    ::= <unnamed-type-name> [<abi-tags>]
760 //
761 // <local-source-name> is a GCC extension; see below.
ParseUnqualifiedName(State * state)762 static bool ParseUnqualifiedName(State *state) {
763   ComplexityGuard guard(state);
764   if (guard.IsTooComplex()) return false;
765   if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) ||
766       ParseSourceName(state) || ParseLocalSourceName(state) ||
767       ParseUnnamedTypeName(state)) {
768     return ParseAbiTags(state);
769   }
770   return false;
771 }
772 
773 // <abi-tags> ::= <abi-tag> [<abi-tags>]
774 // <abi-tag>  ::= B <source-name>
ParseAbiTags(State * state)775 static bool ParseAbiTags(State *state) {
776   ComplexityGuard guard(state);
777   if (guard.IsTooComplex()) return false;
778 
779   while (ParseOneCharToken(state, 'B')) {
780     ParseState copy = state->parse_state;
781     MaybeAppend(state, "[abi:");
782 
783     if (!ParseSourceName(state)) {
784       state->parse_state = copy;
785       return false;
786     }
787     MaybeAppend(state, "]");
788   }
789 
790   return true;
791 }
792 
793 // <source-name> ::= <positive length number> <identifier>
ParseSourceName(State * state)794 static bool ParseSourceName(State *state) {
795   ComplexityGuard guard(state);
796   if (guard.IsTooComplex()) return false;
797   ParseState copy = state->parse_state;
798   int length = -1;
799   if (ParseNumber(state, &length) &&
800       ParseIdentifier(state, static_cast<size_t>(length))) {
801     return true;
802   }
803   state->parse_state = copy;
804   return false;
805 }
806 
807 // <local-source-name> ::= L <source-name> [<discriminator>]
808 //
809 // References:
810 //   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
811 //   https://gcc.gnu.org/viewcvs?view=rev&revision=124467
ParseLocalSourceName(State * state)812 static bool ParseLocalSourceName(State *state) {
813   ComplexityGuard guard(state);
814   if (guard.IsTooComplex()) return false;
815   ParseState copy = state->parse_state;
816   if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
817       Optional(ParseDiscriminator(state))) {
818     return true;
819   }
820   state->parse_state = copy;
821   return false;
822 }
823 
824 // <unnamed-type-name> ::= Ut [<(nonnegative) number>] _
825 //                     ::= <closure-type-name>
826 // <closure-type-name> ::= Ul <lambda-sig> E [<(nonnegative) number>] _
827 // <lambda-sig>        ::= <(parameter) type>+
ParseUnnamedTypeName(State * state)828 static bool ParseUnnamedTypeName(State *state) {
829   ComplexityGuard guard(state);
830   if (guard.IsTooComplex()) return false;
831   ParseState copy = state->parse_state;
832   // Type's 1-based index n is encoded as { "", n == 1; itoa(n-2), otherwise }.
833   // Optionally parse the encoded value into 'which' and add 2 to get the index.
834   int which = -1;
835 
836   // Unnamed type local to function or class.
837   if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) &&
838       which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
839       ParseOneCharToken(state, '_')) {
840     MaybeAppend(state, "{unnamed type#");
841     MaybeAppendDecimal(state, 2 + which);
842     MaybeAppend(state, "}");
843     return true;
844   }
845   state->parse_state = copy;
846 
847   // Closure type.
848   which = -1;
849   if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
850       OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
851       ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
852       which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
853       ParseOneCharToken(state, '_')) {
854     MaybeAppend(state, "{lambda()#");
855     MaybeAppendDecimal(state, 2 + which);
856     MaybeAppend(state, "}");
857     return true;
858   }
859   state->parse_state = copy;
860 
861   return false;
862 }
863 
864 // <number> ::= [n] <non-negative decimal integer>
865 // If "number_out" is non-null, then *number_out is set to the value of the
866 // parsed number on success.
ParseNumber(State * state,int * number_out)867 static bool ParseNumber(State *state, int *number_out) {
868   ComplexityGuard guard(state);
869   if (guard.IsTooComplex()) return false;
870   bool negative = false;
871   if (ParseOneCharToken(state, 'n')) {
872     negative = true;
873   }
874   const char *p = RemainingInput(state);
875   uint64_t number = 0;
876   for (; *p != '\0'; ++p) {
877     if (IsDigit(*p)) {
878       number = number * 10 + static_cast<uint64_t>(*p - '0');
879     } else {
880       break;
881     }
882   }
883   // Apply the sign with uint64_t arithmetic so overflows aren't UB.  Gives
884   // "incorrect" results for out-of-range inputs, but negative values only
885   // appear for literals, which aren't printed.
886   if (negative) {
887     number = ~number + 1;
888   }
889   if (p != RemainingInput(state)) {  // Conversion succeeded.
890     state->parse_state.mangled_idx += p - RemainingInput(state);
891     if (number_out != nullptr) {
892       // Note: possibly truncate "number".
893       *number_out = static_cast<int>(number);
894     }
895     return true;
896   }
897   return false;
898 }
899 
900 // Floating-point literals are encoded using a fixed-length lowercase
901 // hexadecimal string.
ParseFloatNumber(State * state)902 static bool ParseFloatNumber(State *state) {
903   ComplexityGuard guard(state);
904   if (guard.IsTooComplex()) return false;
905   const char *p = RemainingInput(state);
906   for (; *p != '\0'; ++p) {
907     if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
908       break;
909     }
910   }
911   if (p != RemainingInput(state)) {  // Conversion succeeded.
912     state->parse_state.mangled_idx += p - RemainingInput(state);
913     return true;
914   }
915   return false;
916 }
917 
918 // The <seq-id> is a sequence number in base 36,
919 // using digits and upper case letters
ParseSeqId(State * state)920 static bool ParseSeqId(State *state) {
921   ComplexityGuard guard(state);
922   if (guard.IsTooComplex()) return false;
923   const char *p = RemainingInput(state);
924   for (; *p != '\0'; ++p) {
925     if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
926       break;
927     }
928   }
929   if (p != RemainingInput(state)) {  // Conversion succeeded.
930     state->parse_state.mangled_idx += p - RemainingInput(state);
931     return true;
932   }
933   return false;
934 }
935 
936 // <identifier> ::= <unqualified source code identifier> (of given length)
ParseIdentifier(State * state,size_t length)937 static bool ParseIdentifier(State *state, size_t length) {
938   ComplexityGuard guard(state);
939   if (guard.IsTooComplex()) return false;
940   if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
941     return false;
942   }
943   if (IdentifierIsAnonymousNamespace(state, length)) {
944     MaybeAppend(state, "(anonymous namespace)");
945   } else {
946     MaybeAppendWithLength(state, RemainingInput(state), length);
947   }
948   state->parse_state.mangled_idx += length;
949   return true;
950 }
951 
952 // <operator-name> ::= nw, and other two letters cases
953 //                 ::= cv <type>  # (cast)
954 //                 ::= v  <digit> <source-name> # vendor extended operator
ParseOperatorName(State * state,int * arity)955 static bool ParseOperatorName(State *state, int *arity) {
956   ComplexityGuard guard(state);
957   if (guard.IsTooComplex()) return false;
958   if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
959     return false;
960   }
961   // First check with "cv" (cast) case.
962   ParseState copy = state->parse_state;
963   if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
964       EnterNestedName(state) && ParseType(state) &&
965       LeaveNestedName(state, copy.nest_level)) {
966     if (arity != nullptr) {
967       *arity = 1;
968     }
969     return true;
970   }
971   state->parse_state = copy;
972 
973   // Then vendor extended operators.
974   if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
975       ParseSourceName(state)) {
976     return true;
977   }
978   state->parse_state = copy;
979 
980   // Other operator names should start with a lower alphabet followed
981   // by a lower/upper alphabet.
982   if (!(IsLower(RemainingInput(state)[0]) &&
983         IsAlpha(RemainingInput(state)[1]))) {
984     return false;
985   }
986   // We may want to perform a binary search if we really need speed.
987   const AbbrevPair *p;
988   for (p = kOperatorList; p->abbrev != nullptr; ++p) {
989     if (RemainingInput(state)[0] == p->abbrev[0] &&
990         RemainingInput(state)[1] == p->abbrev[1]) {
991       if (arity != nullptr) {
992         *arity = p->arity;
993       }
994       MaybeAppend(state, "operator");
995       if (IsLower(*p->real_name)) {  // new, delete, etc.
996         MaybeAppend(state, " ");
997       }
998       MaybeAppend(state, p->real_name);
999       state->parse_state.mangled_idx += 2;
1000       return true;
1001     }
1002   }
1003   return false;
1004 }
1005 
1006 // <special-name> ::= TV <type>
1007 //                ::= TT <type>
1008 //                ::= TI <type>
1009 //                ::= TS <type>
1010 //                ::= TH <type>  # thread-local
1011 //                ::= Tc <call-offset> <call-offset> <(base) encoding>
1012 //                ::= GV <(object) name>
1013 //                ::= T <call-offset> <(base) encoding>
1014 // G++ extensions:
1015 //                ::= TC <type> <(offset) number> _ <(base) type>
1016 //                ::= TF <type>
1017 //                ::= TJ <type>
1018 //                ::= GR <name>
1019 //                ::= GA <encoding>
1020 //                ::= Th <call-offset> <(base) encoding>
1021 //                ::= Tv <call-offset> <(base) encoding>
1022 //
1023 // Note: we don't care much about them since they don't appear in
1024 // stack traces.  The are special data.
ParseSpecialName(State * state)1025 static bool ParseSpecialName(State *state) {
1026   ComplexityGuard guard(state);
1027   if (guard.IsTooComplex()) return false;
1028   ParseState copy = state->parse_state;
1029   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTISH") &&
1030       ParseType(state)) {
1031     return true;
1032   }
1033   state->parse_state = copy;
1034 
1035   if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
1036       ParseCallOffset(state) && ParseEncoding(state)) {
1037     return true;
1038   }
1039   state->parse_state = copy;
1040 
1041   if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
1042     return true;
1043   }
1044   state->parse_state = copy;
1045 
1046   if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
1047       ParseEncoding(state)) {
1048     return true;
1049   }
1050   state->parse_state = copy;
1051 
1052   // G++ extensions
1053   if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
1054       ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1055       DisableAppend(state) && ParseType(state)) {
1056     RestoreAppend(state, copy.append);
1057     return true;
1058   }
1059   state->parse_state = copy;
1060 
1061   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
1062       ParseType(state)) {
1063     return true;
1064   }
1065   state->parse_state = copy;
1066 
1067   if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
1068     return true;
1069   }
1070   state->parse_state = copy;
1071 
1072   if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
1073     return true;
1074   }
1075   state->parse_state = copy;
1076 
1077   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
1078       ParseCallOffset(state) && ParseEncoding(state)) {
1079     return true;
1080   }
1081   state->parse_state = copy;
1082   return false;
1083 }
1084 
1085 // <call-offset> ::= h <nv-offset> _
1086 //               ::= v <v-offset> _
ParseCallOffset(State * state)1087 static bool ParseCallOffset(State *state) {
1088   ComplexityGuard guard(state);
1089   if (guard.IsTooComplex()) return false;
1090   ParseState copy = state->parse_state;
1091   if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
1092       ParseOneCharToken(state, '_')) {
1093     return true;
1094   }
1095   state->parse_state = copy;
1096 
1097   if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
1098       ParseOneCharToken(state, '_')) {
1099     return true;
1100   }
1101   state->parse_state = copy;
1102 
1103   return false;
1104 }
1105 
1106 // <nv-offset> ::= <(offset) number>
ParseNVOffset(State * state)1107 static bool ParseNVOffset(State *state) {
1108   ComplexityGuard guard(state);
1109   if (guard.IsTooComplex()) return false;
1110   return ParseNumber(state, nullptr);
1111 }
1112 
1113 // <v-offset>  ::= <(offset) number> _ <(virtual offset) number>
ParseVOffset(State * state)1114 static bool ParseVOffset(State *state) {
1115   ComplexityGuard guard(state);
1116   if (guard.IsTooComplex()) return false;
1117   ParseState copy = state->parse_state;
1118   if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1119       ParseNumber(state, nullptr)) {
1120     return true;
1121   }
1122   state->parse_state = copy;
1123   return false;
1124 }
1125 
1126 // <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
1127 // <base-class-type>
1128 //                  ::= D0 | D1 | D2
1129 // # GCC extensions: "unified" constructor/destructor.  See
1130 // #
1131 // https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
1132 //                  ::= C4 | D4
ParseCtorDtorName(State * state)1133 static bool ParseCtorDtorName(State *state) {
1134   ComplexityGuard guard(state);
1135   if (guard.IsTooComplex()) return false;
1136   ParseState copy = state->parse_state;
1137   if (ParseOneCharToken(state, 'C')) {
1138     if (ParseCharClass(state, "1234")) {
1139       const char *const prev_name =
1140           state->out + state->parse_state.prev_name_idx;
1141       MaybeAppendWithLength(state, prev_name,
1142                             state->parse_state.prev_name_length);
1143       return true;
1144     } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
1145                ParseClassEnumType(state)) {
1146       return true;
1147     }
1148   }
1149   state->parse_state = copy;
1150 
1151   if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
1152     const char *const prev_name = state->out + state->parse_state.prev_name_idx;
1153     MaybeAppend(state, "~");
1154     MaybeAppendWithLength(state, prev_name,
1155                           state->parse_state.prev_name_length);
1156     return true;
1157   }
1158   state->parse_state = copy;
1159   return false;
1160 }
1161 
1162 // <decltype> ::= Dt <expression> E  # decltype of an id-expression or class
1163 //                                   # member access (C++0x)
1164 //            ::= DT <expression> E  # decltype of an expression (C++0x)
ParseDecltype(State * state)1165 static bool ParseDecltype(State *state) {
1166   ComplexityGuard guard(state);
1167   if (guard.IsTooComplex()) return false;
1168 
1169   ParseState copy = state->parse_state;
1170   if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
1171       ParseExpression(state) && ParseOneCharToken(state, 'E')) {
1172     return true;
1173   }
1174   state->parse_state = copy;
1175 
1176   return false;
1177 }
1178 
1179 // <type> ::= <CV-qualifiers> <type>
1180 //        ::= P <type>   # pointer-to
1181 //        ::= R <type>   # reference-to
1182 //        ::= O <type>   # rvalue reference-to (C++0x)
1183 //        ::= C <type>   # complex pair (C 2000)
1184 //        ::= G <type>   # imaginary (C 2000)
1185 //        ::= U <source-name> <type>  # vendor extended type qualifier
1186 //        ::= <builtin-type>
1187 //        ::= <function-type>
1188 //        ::= <class-enum-type>  # note: just an alias for <name>
1189 //        ::= <array-type>
1190 //        ::= <pointer-to-member-type>
1191 //        ::= <template-template-param> <template-args>
1192 //        ::= <template-param>
1193 //        ::= <decltype>
1194 //        ::= <substitution>
1195 //        ::= Dp <type>          # pack expansion of (C++0x)
1196 //        ::= Dv <num-elems> _   # GNU vector extension
1197 //
ParseType(State * state)1198 static bool ParseType(State *state) {
1199   ComplexityGuard guard(state);
1200   if (guard.IsTooComplex()) return false;
1201   ParseState copy = state->parse_state;
1202 
1203   // We should check CV-qualifers, and PRGC things first.
1204   //
1205   // CV-qualifiers overlap with some operator names, but an operator name is not
1206   // valid as a type.  To avoid an ambiguity that can lead to exponential time
1207   // complexity, refuse to backtrack the CV-qualifiers.
1208   //
1209   // _Z4aoeuIrMvvE
1210   //  => _Z 4aoeuI        rM  v     v   E
1211   //         aoeu<operator%=, void, void>
1212   //  => _Z 4aoeuI r Mv v              E
1213   //         aoeu<void void::* restrict>
1214   //
1215   // By consuming the CV-qualifiers first, the former parse is disabled.
1216   if (ParseCVQualifiers(state)) {
1217     const bool result = ParseType(state);
1218     if (!result) state->parse_state = copy;
1219     return result;
1220   }
1221   state->parse_state = copy;
1222 
1223   // Similarly, these tag characters can overlap with other <name>s resulting in
1224   // two different parse prefixes that land on <template-args> in the same
1225   // place, such as "C3r1xI...".  So, disable the "ctor-name = C3" parse by
1226   // refusing to backtrack the tag characters.
1227   if (ParseCharClass(state, "OPRCG")) {
1228     const bool result = ParseType(state);
1229     if (!result) state->parse_state = copy;
1230     return result;
1231   }
1232   state->parse_state = copy;
1233 
1234   if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
1235     return true;
1236   }
1237   state->parse_state = copy;
1238 
1239   if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
1240       ParseType(state)) {
1241     return true;
1242   }
1243   state->parse_state = copy;
1244 
1245   if (ParseBuiltinType(state) || ParseFunctionType(state) ||
1246       ParseClassEnumType(state) || ParseArrayType(state) ||
1247       ParsePointerToMemberType(state) || ParseDecltype(state) ||
1248       // "std" on its own isn't a type.
1249       ParseSubstitution(state, /*accept_std=*/false)) {
1250     return true;
1251   }
1252 
1253   if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
1254     return true;
1255   }
1256   state->parse_state = copy;
1257 
1258   // Less greedy than <template-template-param> <template-args>.
1259   if (ParseTemplateParam(state)) {
1260     return true;
1261   }
1262 
1263   if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
1264       ParseOneCharToken(state, '_')) {
1265     return true;
1266   }
1267   state->parse_state = copy;
1268 
1269   return false;
1270 }
1271 
1272 // <CV-qualifiers> ::= [r] [V] [K]
1273 // We don't allow empty <CV-qualifiers> to avoid infinite loop in
1274 // ParseType().
ParseCVQualifiers(State * state)1275 static bool ParseCVQualifiers(State *state) {
1276   ComplexityGuard guard(state);
1277   if (guard.IsTooComplex()) return false;
1278   int num_cv_qualifiers = 0;
1279   num_cv_qualifiers += ParseOneCharToken(state, 'r');
1280   num_cv_qualifiers += ParseOneCharToken(state, 'V');
1281   num_cv_qualifiers += ParseOneCharToken(state, 'K');
1282   return num_cv_qualifiers > 0;
1283 }
1284 
1285 // <builtin-type> ::= v, etc.  # single-character builtin types
1286 //                ::= u <source-name>
1287 //                ::= Dd, etc.  # two-character builtin types
1288 //
1289 // Not supported:
1290 //                ::= DF <number> _ # _FloatN (N bits)
1291 //
ParseBuiltinType(State * state)1292 static bool ParseBuiltinType(State *state) {
1293   ComplexityGuard guard(state);
1294   if (guard.IsTooComplex()) return false;
1295   const AbbrevPair *p;
1296   for (p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
1297     // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
1298     if (p->abbrev[1] == '\0') {
1299       if (ParseOneCharToken(state, p->abbrev[0])) {
1300         MaybeAppend(state, p->real_name);
1301         return true;
1302       }
1303     } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
1304       MaybeAppend(state, p->real_name);
1305       return true;
1306     }
1307   }
1308 
1309   ParseState copy = state->parse_state;
1310   if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
1311     return true;
1312   }
1313   state->parse_state = copy;
1314   return false;
1315 }
1316 
1317 //  <exception-spec> ::= Do                # non-throwing
1318 //                                           exception-specification (e.g.,
1319 //                                           noexcept, throw())
1320 //                   ::= DO <expression> E # computed (instantiation-dependent)
1321 //                                           noexcept
1322 //                   ::= Dw <type>+ E      # dynamic exception specification
1323 //                                           with instantiation-dependent types
ParseExceptionSpec(State * state)1324 static bool ParseExceptionSpec(State *state) {
1325   ComplexityGuard guard(state);
1326   if (guard.IsTooComplex()) return false;
1327 
1328   if (ParseTwoCharToken(state, "Do")) return true;
1329 
1330   ParseState copy = state->parse_state;
1331   if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
1332       ParseOneCharToken(state, 'E')) {
1333     return true;
1334   }
1335   state->parse_state = copy;
1336   if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
1337       ParseOneCharToken(state, 'E')) {
1338     return true;
1339   }
1340   state->parse_state = copy;
1341 
1342   return false;
1343 }
1344 
1345 // <function-type> ::= [exception-spec] F [Y] <bare-function-type> [O] E
ParseFunctionType(State * state)1346 static bool ParseFunctionType(State *state) {
1347   ComplexityGuard guard(state);
1348   if (guard.IsTooComplex()) return false;
1349   ParseState copy = state->parse_state;
1350   if (Optional(ParseExceptionSpec(state)) && ParseOneCharToken(state, 'F') &&
1351       Optional(ParseOneCharToken(state, 'Y')) && ParseBareFunctionType(state) &&
1352       Optional(ParseOneCharToken(state, 'O')) &&
1353       ParseOneCharToken(state, 'E')) {
1354     return true;
1355   }
1356   state->parse_state = copy;
1357   return false;
1358 }
1359 
1360 // <bare-function-type> ::= <(signature) type>+
ParseBareFunctionType(State * state)1361 static bool ParseBareFunctionType(State *state) {
1362   ComplexityGuard guard(state);
1363   if (guard.IsTooComplex()) return false;
1364   ParseState copy = state->parse_state;
1365   DisableAppend(state);
1366   if (OneOrMore(ParseType, state)) {
1367     RestoreAppend(state, copy.append);
1368     MaybeAppend(state, "()");
1369     return true;
1370   }
1371   state->parse_state = copy;
1372   return false;
1373 }
1374 
1375 // <class-enum-type> ::= <name>
ParseClassEnumType(State * state)1376 static bool ParseClassEnumType(State *state) {
1377   ComplexityGuard guard(state);
1378   if (guard.IsTooComplex()) return false;
1379   return ParseName(state);
1380 }
1381 
1382 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
1383 //              ::= A [<(dimension) expression>] _ <(element) type>
ParseArrayType(State * state)1384 static bool ParseArrayType(State *state) {
1385   ComplexityGuard guard(state);
1386   if (guard.IsTooComplex()) return false;
1387   ParseState copy = state->parse_state;
1388   if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
1389       ParseOneCharToken(state, '_') && ParseType(state)) {
1390     return true;
1391   }
1392   state->parse_state = copy;
1393 
1394   if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
1395       ParseOneCharToken(state, '_') && ParseType(state)) {
1396     return true;
1397   }
1398   state->parse_state = copy;
1399   return false;
1400 }
1401 
1402 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
ParsePointerToMemberType(State * state)1403 static bool ParsePointerToMemberType(State *state) {
1404   ComplexityGuard guard(state);
1405   if (guard.IsTooComplex()) return false;
1406   ParseState copy = state->parse_state;
1407   if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
1408     return true;
1409   }
1410   state->parse_state = copy;
1411   return false;
1412 }
1413 
1414 // <template-param> ::= T_
1415 //                  ::= T <parameter-2 non-negative number> _
ParseTemplateParam(State * state)1416 static bool ParseTemplateParam(State *state) {
1417   ComplexityGuard guard(state);
1418   if (guard.IsTooComplex()) return false;
1419   if (ParseTwoCharToken(state, "T_")) {
1420     MaybeAppend(state, "?");  // We don't support template substitutions.
1421     return true;
1422   }
1423 
1424   ParseState copy = state->parse_state;
1425   if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
1426       ParseOneCharToken(state, '_')) {
1427     MaybeAppend(state, "?");  // We don't support template substitutions.
1428     return true;
1429   }
1430   state->parse_state = copy;
1431   return false;
1432 }
1433 
1434 // <template-template-param> ::= <template-param>
1435 //                           ::= <substitution>
ParseTemplateTemplateParam(State * state)1436 static bool ParseTemplateTemplateParam(State *state) {
1437   ComplexityGuard guard(state);
1438   if (guard.IsTooComplex()) return false;
1439   return (ParseTemplateParam(state) ||
1440           // "std" on its own isn't a template.
1441           ParseSubstitution(state, /*accept_std=*/false));
1442 }
1443 
1444 // <template-args> ::= I <template-arg>+ E
ParseTemplateArgs(State * state)1445 static bool ParseTemplateArgs(State *state) {
1446   ComplexityGuard guard(state);
1447   if (guard.IsTooComplex()) return false;
1448   ParseState copy = state->parse_state;
1449   DisableAppend(state);
1450   if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
1451       ParseOneCharToken(state, 'E')) {
1452     RestoreAppend(state, copy.append);
1453     MaybeAppend(state, "<>");
1454     return true;
1455   }
1456   state->parse_state = copy;
1457   return false;
1458 }
1459 
1460 // <template-arg>  ::= <type>
1461 //                 ::= <expr-primary>
1462 //                 ::= J <template-arg>* E        # argument pack
1463 //                 ::= X <expression> E
ParseTemplateArg(State * state)1464 static bool ParseTemplateArg(State *state) {
1465   ComplexityGuard guard(state);
1466   if (guard.IsTooComplex()) return false;
1467   ParseState copy = state->parse_state;
1468   if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
1469       ParseOneCharToken(state, 'E')) {
1470     return true;
1471   }
1472   state->parse_state = copy;
1473 
1474   // There can be significant overlap between the following leading to
1475   // exponential backtracking:
1476   //
1477   //   <expr-primary> ::= L <type> <expr-cast-value> E
1478   //                 e.g. L 2xxIvE 1                 E
1479   //   <type>         ==> <local-source-name> <template-args>
1480   //                 e.g. L 2xx               IvE
1481   //
1482   // This means parsing an entire <type> twice, and <type> can contain
1483   // <template-arg>, so this can generate exponential backtracking.  There is
1484   // only overlap when the remaining input starts with "L <source-name>", so
1485   // parse all cases that can start this way jointly to share the common prefix.
1486   //
1487   // We have:
1488   //
1489   //   <template-arg> ::= <type>
1490   //                  ::= <expr-primary>
1491   //
1492   // First, drop all the productions of <type> that must start with something
1493   // other than 'L'.  All that's left is <class-enum-type>; inline it.
1494   //
1495   //   <type> ::= <nested-name> # starts with 'N'
1496   //          ::= <unscoped-name>
1497   //          ::= <unscoped-template-name> <template-args>
1498   //          ::= <local-name> # starts with 'Z'
1499   //
1500   // Drop and inline again:
1501   //
1502   //   <type> ::= <unscoped-name>
1503   //          ::= <unscoped-name> <template-args>
1504   //          ::= <substitution> <template-args> # starts with 'S'
1505   //
1506   // Merge the first two, inline <unscoped-name>, drop last:
1507   //
1508   //   <type> ::= <unqualified-name> [<template-args>]
1509   //          ::= St <unqualified-name> [<template-args>] # starts with 'S'
1510   //
1511   // Drop and inline:
1512   //
1513   //   <type> ::= <operator-name> [<template-args>] # starts with lowercase
1514   //          ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
1515   //          ::= <source-name> [<template-args>] # starts with digit
1516   //          ::= <local-source-name> [<template-args>]
1517   //          ::= <unnamed-type-name> [<template-args>] # starts with 'U'
1518   //
1519   // One more time:
1520   //
1521   //   <type> ::= L <source-name> [<template-args>]
1522   //
1523   // Likewise with <expr-primary>:
1524   //
1525   //   <expr-primary> ::= L <type> <expr-cast-value> E
1526   //                  ::= LZ <encoding> E # cannot overlap; drop
1527   //                  ::= L <mangled_name> E # cannot overlap; drop
1528   //
1529   // By similar reasoning as shown above, the only <type>s starting with
1530   // <source-name> are "<source-name> [<template-args>]".  Inline this.
1531   //
1532   //   <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
1533   //
1534   // Now inline both of these into <template-arg>:
1535   //
1536   //   <template-arg> ::= L <source-name> [<template-args>]
1537   //                  ::= L <source-name> [<template-args>] <expr-cast-value> E
1538   //
1539   // Merge them and we're done:
1540   //   <template-arg>
1541   //     ::= L <source-name> [<template-args>] [<expr-cast-value> E]
1542   if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
1543     copy = state->parse_state;
1544     if (ParseExprCastValue(state) && ParseOneCharToken(state, 'E')) {
1545       return true;
1546     }
1547     state->parse_state = copy;
1548     return true;
1549   }
1550 
1551   // Now that the overlapping cases can't reach this code, we can safely call
1552   // both of these.
1553   if (ParseType(state) || ParseExprPrimary(state)) {
1554     return true;
1555   }
1556   state->parse_state = copy;
1557 
1558   if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
1559       ParseOneCharToken(state, 'E')) {
1560     return true;
1561   }
1562   state->parse_state = copy;
1563   return false;
1564 }
1565 
1566 // <unresolved-type> ::= <template-param> [<template-args>]
1567 //                   ::= <decltype>
1568 //                   ::= <substitution>
ParseUnresolvedType(State * state)1569 static inline bool ParseUnresolvedType(State *state) {
1570   // No ComplexityGuard because we don't copy the state in this stack frame.
1571   return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
1572          ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
1573 }
1574 
1575 // <simple-id> ::= <source-name> [<template-args>]
ParseSimpleId(State * state)1576 static inline bool ParseSimpleId(State *state) {
1577   // No ComplexityGuard because we don't copy the state in this stack frame.
1578 
1579   // Note: <simple-id> cannot be followed by a parameter pack; see comment in
1580   // ParseUnresolvedType.
1581   return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
1582 }
1583 
1584 // <base-unresolved-name> ::= <source-name> [<template-args>]
1585 //                        ::= on <operator-name> [<template-args>]
1586 //                        ::= dn <destructor-name>
ParseBaseUnresolvedName(State * state)1587 static bool ParseBaseUnresolvedName(State *state) {
1588   ComplexityGuard guard(state);
1589   if (guard.IsTooComplex()) return false;
1590 
1591   if (ParseSimpleId(state)) {
1592     return true;
1593   }
1594 
1595   ParseState copy = state->parse_state;
1596   if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
1597       Optional(ParseTemplateArgs(state))) {
1598     return true;
1599   }
1600   state->parse_state = copy;
1601 
1602   if (ParseTwoCharToken(state, "dn") &&
1603       (ParseUnresolvedType(state) || ParseSimpleId(state))) {
1604     return true;
1605   }
1606   state->parse_state = copy;
1607 
1608   return false;
1609 }
1610 
1611 // <unresolved-name> ::= [gs] <base-unresolved-name>
1612 //                   ::= sr <unresolved-type> <base-unresolved-name>
1613 //                   ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1614 //                         <base-unresolved-name>
1615 //                   ::= [gs] sr <unresolved-qualifier-level>+ E
1616 //                         <base-unresolved-name>
ParseUnresolvedName(State * state)1617 static bool ParseUnresolvedName(State *state) {
1618   ComplexityGuard guard(state);
1619   if (guard.IsTooComplex()) return false;
1620 
1621   ParseState copy = state->parse_state;
1622   if (Optional(ParseTwoCharToken(state, "gs")) &&
1623       ParseBaseUnresolvedName(state)) {
1624     return true;
1625   }
1626   state->parse_state = copy;
1627 
1628   if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
1629       ParseBaseUnresolvedName(state)) {
1630     return true;
1631   }
1632   state->parse_state = copy;
1633 
1634   if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
1635       ParseUnresolvedType(state) &&
1636       OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
1637       ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
1638     return true;
1639   }
1640   state->parse_state = copy;
1641 
1642   if (Optional(ParseTwoCharToken(state, "gs")) &&
1643       ParseTwoCharToken(state, "sr") &&
1644       OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
1645       ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
1646     return true;
1647   }
1648   state->parse_state = copy;
1649 
1650   return false;
1651 }
1652 
1653 // <expression> ::= <1-ary operator-name> <expression>
1654 //              ::= <2-ary operator-name> <expression> <expression>
1655 //              ::= <3-ary operator-name> <expression> <expression> <expression>
1656 //              ::= cl <expression>+ E
1657 //              ::= cp <simple-id> <expression>* E # Clang-specific.
1658 //              ::= cv <type> <expression>      # type (expression)
1659 //              ::= cv <type> _ <expression>* E # type (expr-list)
1660 //              ::= st <type>
1661 //              ::= <template-param>
1662 //              ::= <function-param>
1663 //              ::= <expr-primary>
1664 //              ::= dt <expression> <unresolved-name> # expr.name
1665 //              ::= pt <expression> <unresolved-name> # expr->name
1666 //              ::= sp <expression>         # argument pack expansion
1667 //              ::= sr <type> <unqualified-name> <template-args>
1668 //              ::= sr <type> <unqualified-name>
1669 // <function-param> ::= fp <(top-level) CV-qualifiers> _
1670 //                  ::= fp <(top-level) CV-qualifiers> <number> _
1671 //                  ::= fL <number> p <(top-level) CV-qualifiers> _
1672 //                  ::= fL <number> p <(top-level) CV-qualifiers> <number> _
ParseExpression(State * state)1673 static bool ParseExpression(State *state) {
1674   ComplexityGuard guard(state);
1675   if (guard.IsTooComplex()) return false;
1676   if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
1677     return true;
1678   }
1679 
1680   ParseState copy = state->parse_state;
1681 
1682   // Object/function call expression.
1683   if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
1684       ParseOneCharToken(state, 'E')) {
1685     return true;
1686   }
1687   state->parse_state = copy;
1688 
1689   // Clang-specific "cp <simple-id> <expression>* E"
1690   //   https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
1691   if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
1692       ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
1693     return true;
1694   }
1695   state->parse_state = copy;
1696 
1697   // Function-param expression (level 0).
1698   if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
1699       Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
1700     return true;
1701   }
1702   state->parse_state = copy;
1703 
1704   // Function-param expression (level 1+).
1705   if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
1706       ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
1707       Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
1708     return true;
1709   }
1710   state->parse_state = copy;
1711 
1712   // Parse the conversion expressions jointly to avoid re-parsing the <type> in
1713   // their common prefix.  Parsed as:
1714   // <expression> ::= cv <type> <conversion-args>
1715   // <conversion-args> ::= _ <expression>* E
1716   //                   ::= <expression>
1717   //
1718   // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
1719   // also needs to accept "cv <type>" in other contexts.
1720   if (ParseTwoCharToken(state, "cv")) {
1721     if (ParseType(state)) {
1722       ParseState copy2 = state->parse_state;
1723       if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
1724           ParseOneCharToken(state, 'E')) {
1725         return true;
1726       }
1727       state->parse_state = copy2;
1728       if (ParseExpression(state)) {
1729         return true;
1730       }
1731     }
1732   } else {
1733     // Parse unary, binary, and ternary operator expressions jointly, taking
1734     // care not to re-parse subexpressions repeatedly. Parse like:
1735     //   <expression> ::= <operator-name> <expression>
1736     //                    [<one-to-two-expressions>]
1737     //   <one-to-two-expressions> ::= <expression> [<expression>]
1738     int arity = -1;
1739     if (ParseOperatorName(state, &arity) &&
1740         arity > 0 &&  // 0 arity => disabled.
1741         (arity < 3 || ParseExpression(state)) &&
1742         (arity < 2 || ParseExpression(state)) &&
1743         (arity < 1 || ParseExpression(state))) {
1744       return true;
1745     }
1746   }
1747   state->parse_state = copy;
1748 
1749   // sizeof type
1750   if (ParseTwoCharToken(state, "st") && ParseType(state)) {
1751     return true;
1752   }
1753   state->parse_state = copy;
1754 
1755   // Object and pointer member access expressions.
1756   if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
1757       ParseExpression(state) && ParseType(state)) {
1758     return true;
1759   }
1760   state->parse_state = copy;
1761 
1762   // Pointer-to-member access expressions.  This parses the same as a binary
1763   // operator, but it's implemented separately because "ds" shouldn't be
1764   // accepted in other contexts that parse an operator name.
1765   if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
1766       ParseExpression(state)) {
1767     return true;
1768   }
1769   state->parse_state = copy;
1770 
1771   // Parameter pack expansion
1772   if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
1773     return true;
1774   }
1775   state->parse_state = copy;
1776 
1777   return ParseUnresolvedName(state);
1778 }
1779 
1780 // <expr-primary> ::= L <type> <(value) number> E
1781 //                ::= L <type> <(value) float> E
1782 //                ::= L <mangled-name> E
1783 //                // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
1784 //                ::= LZ <encoding> E
1785 //
1786 // Warning, subtle: the "bug" LZ production above is ambiguous with the first
1787 // production where <type> starts with <local-name>, which can lead to
1788 // exponential backtracking in two scenarios:
1789 //
1790 // - When whatever follows the E in the <local-name> in the first production is
1791 //   not a name, we backtrack the whole <encoding> and re-parse the whole thing.
1792 //
1793 // - When whatever follows the <local-name> in the first production is not a
1794 //   number and this <expr-primary> may be followed by a name, we backtrack the
1795 //   <name> and re-parse it.
1796 //
1797 // Moreover this ambiguity isn't always resolved -- for example, the following
1798 // has two different parses:
1799 //
1800 //   _ZaaILZ4aoeuE1x1EvE
1801 //   => operator&&<aoeu, x, E, void>
1802 //   => operator&&<(aoeu::x)(1), void>
1803 //
1804 // To resolve this, we just do what GCC's demangler does, and refuse to parse
1805 // casts to <local-name> types.
ParseExprPrimary(State * state)1806 static bool ParseExprPrimary(State *state) {
1807   ComplexityGuard guard(state);
1808   if (guard.IsTooComplex()) return false;
1809   ParseState copy = state->parse_state;
1810 
1811   // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
1812   // or fail, no backtracking.
1813   if (ParseTwoCharToken(state, "LZ")) {
1814     if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
1815       return true;
1816     }
1817 
1818     state->parse_state = copy;
1819     return false;
1820   }
1821 
1822   // The merged cast production.
1823   if (ParseOneCharToken(state, 'L') && ParseType(state) &&
1824       ParseExprCastValue(state)) {
1825     return true;
1826   }
1827   state->parse_state = copy;
1828 
1829   if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
1830       ParseOneCharToken(state, 'E')) {
1831     return true;
1832   }
1833   state->parse_state = copy;
1834 
1835   return false;
1836 }
1837 
1838 // <number> or <float>, followed by 'E', as described above ParseExprPrimary.
ParseExprCastValue(State * state)1839 static bool ParseExprCastValue(State *state) {
1840   ComplexityGuard guard(state);
1841   if (guard.IsTooComplex()) return false;
1842   // We have to be able to backtrack after accepting a number because we could
1843   // have e.g. "7fffE", which will accept "7" as a number but then fail to find
1844   // the 'E'.
1845   ParseState copy = state->parse_state;
1846   if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
1847     return true;
1848   }
1849   state->parse_state = copy;
1850 
1851   if (ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) {
1852     return true;
1853   }
1854   state->parse_state = copy;
1855 
1856   return false;
1857 }
1858 
1859 // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
1860 //              ::= Z <(function) encoding> E s [<discriminator>]
1861 //
1862 // Parsing a common prefix of these two productions together avoids an
1863 // exponential blowup of backtracking.  Parse like:
1864 //   <local-name> := Z <encoding> E <local-name-suffix>
1865 //   <local-name-suffix> ::= s [<discriminator>]
1866 //                       ::= <name> [<discriminator>]
1867 
ParseLocalNameSuffix(State * state)1868 static bool ParseLocalNameSuffix(State *state) {
1869   ComplexityGuard guard(state);
1870   if (guard.IsTooComplex()) return false;
1871 
1872   if (MaybeAppend(state, "::") && ParseName(state) &&
1873       Optional(ParseDiscriminator(state))) {
1874     return true;
1875   }
1876 
1877   // Since we're not going to overwrite the above "::" by re-parsing the
1878   // <encoding> (whose trailing '\0' byte was in the byte now holding the
1879   // first ':'), we have to rollback the "::" if the <name> parse failed.
1880   if (state->parse_state.append) {
1881     state->out[state->parse_state.out_cur_idx - 2] = '\0';
1882   }
1883 
1884   return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
1885 }
1886 
ParseLocalName(State * state)1887 static bool ParseLocalName(State *state) {
1888   ComplexityGuard guard(state);
1889   if (guard.IsTooComplex()) return false;
1890   ParseState copy = state->parse_state;
1891   if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
1892       ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
1893     return true;
1894   }
1895   state->parse_state = copy;
1896   return false;
1897 }
1898 
1899 // <discriminator> := _ <(non-negative) number>
ParseDiscriminator(State * state)1900 static bool ParseDiscriminator(State *state) {
1901   ComplexityGuard guard(state);
1902   if (guard.IsTooComplex()) return false;
1903   ParseState copy = state->parse_state;
1904   if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr)) {
1905     return true;
1906   }
1907   state->parse_state = copy;
1908   return false;
1909 }
1910 
1911 // <substitution> ::= S_
1912 //                ::= S <seq-id> _
1913 //                ::= St, etc.
1914 //
1915 // "St" is special in that it's not valid as a standalone name, and it *is*
1916 // allowed to precede a name without being wrapped in "N...E".  This means that
1917 // if we accept it on its own, we can accept "St1a" and try to parse
1918 // template-args, then fail and backtrack, accept "St" on its own, then "1a" as
1919 // an unqualified name and re-parse the same template-args.  To block this
1920 // exponential backtracking, we disable it with 'accept_std=false' in
1921 // problematic contexts.
ParseSubstitution(State * state,bool accept_std)1922 static bool ParseSubstitution(State *state, bool accept_std) {
1923   ComplexityGuard guard(state);
1924   if (guard.IsTooComplex()) return false;
1925   if (ParseTwoCharToken(state, "S_")) {
1926     MaybeAppend(state, "?");  // We don't support substitutions.
1927     return true;
1928   }
1929 
1930   ParseState copy = state->parse_state;
1931   if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
1932       ParseOneCharToken(state, '_')) {
1933     MaybeAppend(state, "?");  // We don't support substitutions.
1934     return true;
1935   }
1936   state->parse_state = copy;
1937 
1938   // Expand abbreviations like "St" => "std".
1939   if (ParseOneCharToken(state, 'S')) {
1940     const AbbrevPair *p;
1941     for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
1942       if (RemainingInput(state)[0] == p->abbrev[1] &&
1943           (accept_std || p->abbrev[1] != 't')) {
1944         MaybeAppend(state, "std");
1945         if (p->real_name[0] != '\0') {
1946           MaybeAppend(state, "::");
1947           MaybeAppend(state, p->real_name);
1948         }
1949         ++state->parse_state.mangled_idx;
1950         return true;
1951       }
1952     }
1953   }
1954   state->parse_state = copy;
1955   return false;
1956 }
1957 
1958 // Parse <mangled-name>, optionally followed by either a function-clone suffix
1959 // or version suffix.  Returns true only if all of "mangled_cur" was consumed.
ParseTopLevelMangledName(State * state)1960 static bool ParseTopLevelMangledName(State *state) {
1961   ComplexityGuard guard(state);
1962   if (guard.IsTooComplex()) return false;
1963   if (ParseMangledName(state)) {
1964     if (RemainingInput(state)[0] != '\0') {
1965       // Drop trailing function clone suffix, if any.
1966       if (IsFunctionCloneSuffix(RemainingInput(state))) {
1967         return true;
1968       }
1969       // Append trailing version suffix if any.
1970       // ex. _Z3foo@@GLIBCXX_3.4
1971       if (RemainingInput(state)[0] == '@') {
1972         MaybeAppend(state, RemainingInput(state));
1973         return true;
1974       }
1975       return false;  // Unconsumed suffix.
1976     }
1977     return true;
1978   }
1979   return false;
1980 }
1981 
Overflowed(const State * state)1982 static bool Overflowed(const State *state) {
1983   return state->parse_state.out_cur_idx >= state->out_end_idx;
1984 }
1985 
1986 // The demangler entry point.
Demangle(const char * mangled,char * out,size_t out_size)1987 bool Demangle(const char* mangled, char* out, size_t out_size) {
1988   State state;
1989   InitState(&state, mangled, out, out_size);
1990   return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
1991          state.parse_state.out_cur_idx > 0;
1992 }
1993 
DemangleString(const char * mangled)1994 std::string DemangleString(const char* mangled) {
1995   std::string out;
1996   int status = 0;
1997   char* demangled = nullptr;
1998 #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
1999   demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status);
2000 #endif
2001   if (status == 0 && demangled != nullptr) {
2002     out.append(demangled);
2003     free(demangled);
2004   } else {
2005     out.append(mangled);
2006   }
2007   return out;
2008 }
2009 
2010 }  // namespace debugging_internal
2011 ABSL_NAMESPACE_END
2012 }  // namespace absl
2013