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