• 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 <cstddef>
23 #include <cstdint>
24 #include <cstdio>
25 #include <cstdlib>
26 #include <limits>
27 #include <string>
28 
29 #include "absl/base/config.h"
30 #include "absl/debugging/internal/demangle_rust.h"
31 
32 #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
33 #include <cxxabi.h>
34 #endif
35 
36 namespace absl {
37 ABSL_NAMESPACE_BEGIN
38 namespace debugging_internal {
39 
40 typedef struct {
41   const char *abbrev;
42   const char *real_name;
43   // Number of arguments in <expression> context, or 0 if disallowed.
44   int arity;
45 } AbbrevPair;
46 
47 // List of operators from Itanium C++ ABI.
48 static const AbbrevPair kOperatorList[] = {
49     // New has special syntax (not currently supported).
50     {"nw", "new", 0},
51     {"na", "new[]", 0},
52 
53     // Works except that the 'gs' prefix is not supported.
54     {"dl", "delete", 1},
55     {"da", "delete[]", 1},
56 
57     {"ps", "+", 1},  // "positive"
58     {"ng", "-", 1},  // "negative"
59     {"ad", "&", 1},  // "address-of"
60     {"de", "*", 1},  // "dereference"
61     {"co", "~", 1},
62 
63     {"pl", "+", 2},
64     {"mi", "-", 2},
65     {"ml", "*", 2},
66     {"dv", "/", 2},
67     {"rm", "%", 2},
68     {"an", "&", 2},
69     {"or", "|", 2},
70     {"eo", "^", 2},
71     {"aS", "=", 2},
72     {"pL", "+=", 2},
73     {"mI", "-=", 2},
74     {"mL", "*=", 2},
75     {"dV", "/=", 2},
76     {"rM", "%=", 2},
77     {"aN", "&=", 2},
78     {"oR", "|=", 2},
79     {"eO", "^=", 2},
80     {"ls", "<<", 2},
81     {"rs", ">>", 2},
82     {"lS", "<<=", 2},
83     {"rS", ">>=", 2},
84     {"ss", "<=>", 2},
85     {"eq", "==", 2},
86     {"ne", "!=", 2},
87     {"lt", "<", 2},
88     {"gt", ">", 2},
89     {"le", "<=", 2},
90     {"ge", ">=", 2},
91     {"nt", "!", 1},
92     {"aa", "&&", 2},
93     {"oo", "||", 2},
94     {"pp", "++", 1},
95     {"mm", "--", 1},
96     {"cm", ",", 2},
97     {"pm", "->*", 2},
98     {"pt", "->", 0},  // Special syntax
99     {"cl", "()", 0},  // Special syntax
100     {"ix", "[]", 2},
101     {"qu", "?", 3},
102     {"st", "sizeof", 0},  // Special syntax
103     {"sz", "sizeof", 1},  // Not a real operator name, but used in expressions.
104     {"sZ", "sizeof...", 0},  // Special syntax
105     {nullptr, nullptr, 0},
106 };
107 
108 // List of builtin types from Itanium C++ ABI.
109 //
110 // Invariant: only one- or two-character type abbreviations here.
111 static const AbbrevPair kBuiltinTypeList[] = {
112     {"v", "void", 0},
113     {"w", "wchar_t", 0},
114     {"b", "bool", 0},
115     {"c", "char", 0},
116     {"a", "signed char", 0},
117     {"h", "unsigned char", 0},
118     {"s", "short", 0},
119     {"t", "unsigned short", 0},
120     {"i", "int", 0},
121     {"j", "unsigned int", 0},
122     {"l", "long", 0},
123     {"m", "unsigned long", 0},
124     {"x", "long long", 0},
125     {"y", "unsigned long long", 0},
126     {"n", "__int128", 0},
127     {"o", "unsigned __int128", 0},
128     {"f", "float", 0},
129     {"d", "double", 0},
130     {"e", "long double", 0},
131     {"g", "__float128", 0},
132     {"z", "ellipsis", 0},
133 
134     {"De", "decimal128", 0},      // IEEE 754r decimal floating point (128 bits)
135     {"Dd", "decimal64", 0},       // IEEE 754r decimal floating point (64 bits)
136     {"Dc", "decltype(auto)", 0},
137     {"Da", "auto", 0},
138     {"Dn", "std::nullptr_t", 0},  // i.e., decltype(nullptr)
139     {"Df", "decimal32", 0},       // IEEE 754r decimal floating point (32 bits)
140     {"Di", "char32_t", 0},
141     {"Du", "char8_t", 0},
142     {"Ds", "char16_t", 0},
143     {"Dh", "float16", 0},         // IEEE 754r half-precision float (16 bits)
144     {nullptr, nullptr, 0},
145 };
146 
147 // List of substitutions Itanium C++ ABI.
148 static const AbbrevPair kSubstitutionList[] = {
149     {"St", "", 0},
150     {"Sa", "allocator", 0},
151     {"Sb", "basic_string", 0},
152     // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
153     {"Ss", "string", 0},
154     // std::basic_istream<char, std::char_traits<char> >
155     {"Si", "istream", 0},
156     // std::basic_ostream<char, std::char_traits<char> >
157     {"So", "ostream", 0},
158     // std::basic_iostream<char, std::char_traits<char> >
159     {"Sd", "iostream", 0},
160     {nullptr, nullptr, 0},
161 };
162 
163 // State needed for demangling.  This struct is copied in almost every stack
164 // frame, so every byte counts.
165 typedef struct {
166   int mangled_idx;                     // Cursor of mangled name.
167   int out_cur_idx;                     // Cursor of output string.
168   int prev_name_idx;                   // For constructors/destructors.
169   unsigned int prev_name_length : 16;  // For constructors/destructors.
170   signed int nest_level : 15;          // For nested names.
171   unsigned int append : 1;             // Append flag.
172   // Note: for some reason MSVC can't pack "bool append : 1" into the same int
173   // with the above two fields, so we use an int instead.  Amusingly it can pack
174   // "signed bool" as expected, but relying on that to continue to be a legal
175   // type seems ill-advised (as it's illegal in at least clang).
176 } ParseState;
177 
178 static_assert(sizeof(ParseState) == 4 * sizeof(int),
179               "unexpected size of ParseState");
180 
181 // One-off state for demangling that's not subject to backtracking -- either
182 // constant data, data that's intentionally immune to backtracking (steps), or
183 // data that would never be changed by backtracking anyway (recursion_depth).
184 //
185 // Only one copy of this exists for each call to Demangle, so the size of this
186 // struct is nearly inconsequential.
187 typedef struct {
188   const char *mangled_begin;  // Beginning of input string.
189   char *out;                  // Beginning of output string.
190   int out_end_idx;            // One past last allowed output character.
191   int recursion_depth;        // For stack exhaustion prevention.
192   int steps;               // Cap how much work we'll do, regardless of depth.
193   ParseState parse_state;  // Backtrackable state copied for most frames.
194 } State;
195 
196 namespace {
197 // Prevent deep recursion / stack exhaustion.
198 // Also prevent unbounded handling of complex inputs.
199 class ComplexityGuard {
200  public:
ComplexityGuard(State * state)201   explicit ComplexityGuard(State *state) : state_(state) {
202     ++state->recursion_depth;
203     ++state->steps;
204   }
~ComplexityGuard()205   ~ComplexityGuard() { --state_->recursion_depth; }
206 
207   // 256 levels of recursion seems like a reasonable upper limit on depth.
208   // 128 is not enough to demagle synthetic tests from demangle_unittest.txt:
209   // "_ZaaZZZZ..." and "_ZaaZcvZcvZ..."
210   static constexpr int kRecursionDepthLimit = 256;
211 
212   // We're trying to pick a charitable upper-limit on how many parse steps are
213   // necessary to handle something that a human could actually make use of.
214   // This is mostly in place as a bound on how much work we'll do if we are
215   // asked to demangle an mangled name from an untrusted source, so it should be
216   // much larger than the largest expected symbol, but much smaller than the
217   // amount of work we can do in, e.g., a second.
218   //
219   // Some real-world symbols from an arbitrary binary started failing between
220   // 2^12 and 2^13, so we multiply the latter by an extra factor of 16 to set
221   // the limit.
222   //
223   // Spending one second on 2^17 parse steps would require each step to take
224   // 7.6us, or ~30000 clock cycles, so it's safe to say this can be done in
225   // under a second.
226   static constexpr int kParseStepsLimit = 1 << 17;
227 
IsTooComplex() const228   bool IsTooComplex() const {
229     return state_->recursion_depth > kRecursionDepthLimit ||
230            state_->steps > kParseStepsLimit;
231   }
232 
233  private:
234   State *state_;
235 };
236 }  // namespace
237 
238 // We don't use strlen() in libc since it's not guaranteed to be async
239 // signal safe.
StrLen(const char * str)240 static size_t StrLen(const char *str) {
241   size_t len = 0;
242   while (*str != '\0') {
243     ++str;
244     ++len;
245   }
246   return len;
247 }
248 
249 // Returns true if "str" has at least "n" characters remaining.
AtLeastNumCharsRemaining(const char * str,size_t n)250 static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
251   for (size_t i = 0; i < n; ++i) {
252     if (str[i] == '\0') {
253       return false;
254     }
255   }
256   return true;
257 }
258 
259 // Returns true if "str" has "prefix" as a prefix.
StrPrefix(const char * str,const char * prefix)260 static bool StrPrefix(const char *str, const char *prefix) {
261   size_t i = 0;
262   while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
263     ++i;
264   }
265   return prefix[i] == '\0';  // Consumed everything in "prefix".
266 }
267 
InitState(State * state,const char * mangled,char * out,size_t out_size)268 static void InitState(State* state,
269                       const char* mangled,
270                       char* out,
271                       size_t out_size) {
272   state->mangled_begin = mangled;
273   state->out = out;
274   state->out_end_idx = static_cast<int>(out_size);
275   state->recursion_depth = 0;
276   state->steps = 0;
277 
278   state->parse_state.mangled_idx = 0;
279   state->parse_state.out_cur_idx = 0;
280   state->parse_state.prev_name_idx = 0;
281   state->parse_state.prev_name_length = 0;
282   state->parse_state.nest_level = -1;
283   state->parse_state.append = true;
284 }
285 
RemainingInput(State * state)286 static inline const char *RemainingInput(State *state) {
287   return &state->mangled_begin[state->parse_state.mangled_idx];
288 }
289 
290 // Returns true and advances "mangled_idx" if we find "one_char_token"
291 // at "mangled_idx" position.  It is assumed that "one_char_token" does
292 // not contain '\0'.
ParseOneCharToken(State * state,const char one_char_token)293 static bool ParseOneCharToken(State *state, const char one_char_token) {
294   ComplexityGuard guard(state);
295   if (guard.IsTooComplex()) return false;
296   if (RemainingInput(state)[0] == one_char_token) {
297     ++state->parse_state.mangled_idx;
298     return true;
299   }
300   return false;
301 }
302 
303 // Returns true and advances "mangled_idx" if we find "two_char_token"
304 // at "mangled_idx" position.  It is assumed that "two_char_token" does
305 // not contain '\0'.
ParseTwoCharToken(State * state,const char * two_char_token)306 static bool ParseTwoCharToken(State *state, const char *two_char_token) {
307   ComplexityGuard guard(state);
308   if (guard.IsTooComplex()) return false;
309   if (RemainingInput(state)[0] == two_char_token[0] &&
310       RemainingInput(state)[1] == two_char_token[1]) {
311     state->parse_state.mangled_idx += 2;
312     return true;
313   }
314   return false;
315 }
316 
317 // Returns true and advances "mangled_idx" if we find "three_char_token"
318 // at "mangled_idx" position.  It is assumed that "three_char_token" does
319 // not contain '\0'.
ParseThreeCharToken(State * state,const char * three_char_token)320 static bool ParseThreeCharToken(State *state, const char *three_char_token) {
321   ComplexityGuard guard(state);
322   if (guard.IsTooComplex()) return false;
323   if (RemainingInput(state)[0] == three_char_token[0] &&
324       RemainingInput(state)[1] == three_char_token[1] &&
325       RemainingInput(state)[2] == three_char_token[2]) {
326     state->parse_state.mangled_idx += 3;
327     return true;
328   }
329   return false;
330 }
331 
332 // Returns true and advances "mangled_idx" if we find a copy of the
333 // NUL-terminated string "long_token" at "mangled_idx" position.
ParseLongToken(State * state,const char * long_token)334 static bool ParseLongToken(State *state, const char *long_token) {
335   ComplexityGuard guard(state);
336   if (guard.IsTooComplex()) return false;
337   int i = 0;
338   for (; long_token[i] != '\0'; ++i) {
339     // Note that we cannot run off the end of the NUL-terminated input here.
340     // Inside the loop body, long_token[i] is known to be different from NUL.
341     // So if we read the NUL on the end of the input here, we return at once.
342     if (RemainingInput(state)[i] != long_token[i]) return false;
343   }
344   state->parse_state.mangled_idx += i;
345   return true;
346 }
347 
348 // Returns true and advances "mangled_cur" if we find any character in
349 // "char_class" at "mangled_cur" position.
ParseCharClass(State * state,const char * char_class)350 static bool ParseCharClass(State *state, const char *char_class) {
351   ComplexityGuard guard(state);
352   if (guard.IsTooComplex()) return false;
353   if (RemainingInput(state)[0] == '\0') {
354     return false;
355   }
356   const char *p = char_class;
357   for (; *p != '\0'; ++p) {
358     if (RemainingInput(state)[0] == *p) {
359       ++state->parse_state.mangled_idx;
360       return true;
361     }
362   }
363   return false;
364 }
365 
ParseDigit(State * state,int * digit)366 static bool ParseDigit(State *state, int *digit) {
367   char c = RemainingInput(state)[0];
368   if (ParseCharClass(state, "0123456789")) {
369     if (digit != nullptr) {
370       *digit = c - '0';
371     }
372     return true;
373   }
374   return false;
375 }
376 
377 // This function is used for handling an optional non-terminal.
Optional(bool)378 static bool Optional(bool /*status*/) { return true; }
379 
380 // This function is used for handling <non-terminal>+ syntax.
381 typedef bool (*ParseFunc)(State *);
OneOrMore(ParseFunc parse_func,State * state)382 static bool OneOrMore(ParseFunc parse_func, State *state) {
383   if (parse_func(state)) {
384     while (parse_func(state)) {
385     }
386     return true;
387   }
388   return false;
389 }
390 
391 // This function is used for handling <non-terminal>* syntax. The function
392 // always returns true and must be followed by a termination token or a
393 // terminating sequence not handled by parse_func (e.g.
394 // ParseOneCharToken(state, 'E')).
ZeroOrMore(ParseFunc parse_func,State * state)395 static bool ZeroOrMore(ParseFunc parse_func, State *state) {
396   while (parse_func(state)) {
397   }
398   return true;
399 }
400 
401 // Append "str" at "out_cur_idx".  If there is an overflow, out_cur_idx is
402 // set to out_end_idx+1.  The output string is ensured to
403 // always terminate with '\0' as long as there is no overflow.
Append(State * state,const char * const str,const size_t length)404 static void Append(State *state, const char *const str, const size_t length) {
405   for (size_t i = 0; i < length; ++i) {
406     if (state->parse_state.out_cur_idx + 1 <
407         state->out_end_idx) {  // +1 for '\0'
408       state->out[state->parse_state.out_cur_idx++] = str[i];
409     } else {
410       // signal overflow
411       state->parse_state.out_cur_idx = state->out_end_idx + 1;
412       break;
413     }
414   }
415   if (state->parse_state.out_cur_idx < state->out_end_idx) {
416     state->out[state->parse_state.out_cur_idx] =
417         '\0';  // Terminate it with '\0'
418   }
419 }
420 
421 // We don't use equivalents in libc to avoid locale issues.
IsLower(char c)422 static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
423 
IsAlpha(char c)424 static bool IsAlpha(char c) {
425   return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
426 }
427 
IsDigit(char c)428 static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
429 
430 // Returns true if "str" is a function clone suffix.  These suffixes are used
431 // by GCC 4.5.x and later versions (and our locally-modified version of GCC
432 // 4.4.x) to indicate functions which have been cloned during optimization.
433 // We treat any sequence (.<alpha>+.<digit>+)+ as a function clone suffix.
434 // Additionally, '_' is allowed along with the alphanumeric sequence.
IsFunctionCloneSuffix(const char * str)435 static bool IsFunctionCloneSuffix(const char *str) {
436   size_t i = 0;
437   while (str[i] != '\0') {
438     bool parsed = false;
439     // Consume a single [.<alpha> | _]*[.<digit>]* sequence.
440     if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
441       parsed = true;
442       i += 2;
443       while (IsAlpha(str[i]) || str[i] == '_') {
444         ++i;
445       }
446     }
447     if (str[i] == '.' && IsDigit(str[i + 1])) {
448       parsed = true;
449       i += 2;
450       while (IsDigit(str[i])) {
451         ++i;
452       }
453     }
454     if (!parsed)
455       return false;
456   }
457   return true;  // Consumed everything in "str".
458 }
459 
EndsWith(State * state,const char chr)460 static bool EndsWith(State *state, const char chr) {
461   return state->parse_state.out_cur_idx > 0 &&
462          state->parse_state.out_cur_idx < state->out_end_idx &&
463          chr == state->out[state->parse_state.out_cur_idx - 1];
464 }
465 
466 // Append "str" with some tweaks, iff "append" state is true.
MaybeAppendWithLength(State * state,const char * const str,const size_t length)467 static void MaybeAppendWithLength(State *state, const char *const str,
468                                   const size_t length) {
469   if (state->parse_state.append && length > 0) {
470     // Append a space if the output buffer ends with '<' and "str"
471     // starts with '<' to avoid <<<.
472     if (str[0] == '<' && EndsWith(state, '<')) {
473       Append(state, " ", 1);
474     }
475     // Remember the last identifier name for ctors/dtors,
476     // but only if we haven't yet overflown the buffer.
477     if (state->parse_state.out_cur_idx < state->out_end_idx &&
478         (IsAlpha(str[0]) || str[0] == '_')) {
479       state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
480       state->parse_state.prev_name_length = static_cast<unsigned int>(length);
481     }
482     Append(state, str, length);
483   }
484 }
485 
486 // Appends a positive decimal number to the output if appending is enabled.
MaybeAppendDecimal(State * state,int val)487 static bool MaybeAppendDecimal(State *state, int val) {
488   // Max {32-64}-bit unsigned int is 20 digits.
489   constexpr size_t kMaxLength = 20;
490   char buf[kMaxLength];
491 
492   // We can't use itoa or sprintf as neither is specified to be
493   // async-signal-safe.
494   if (state->parse_state.append) {
495     // We can't have a one-before-the-beginning pointer, so instead start with
496     // one-past-the-end and manipulate one character before the pointer.
497     char *p = &buf[kMaxLength];
498     do {  // val=0 is the only input that should write a leading zero digit.
499       *--p = static_cast<char>((val % 10) + '0');
500       val /= 10;
501     } while (p > buf && val != 0);
502 
503     // 'p' landed on the last character we set.  How convenient.
504     Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
505   }
506 
507   return true;
508 }
509 
510 // A convenient wrapper around MaybeAppendWithLength().
511 // Returns true so that it can be placed in "if" conditions.
MaybeAppend(State * state,const char * const str)512 static bool MaybeAppend(State *state, const char *const str) {
513   if (state->parse_state.append) {
514     size_t length = StrLen(str);
515     MaybeAppendWithLength(state, str, length);
516   }
517   return true;
518 }
519 
520 // This function is used for handling nested names.
EnterNestedName(State * state)521 static bool EnterNestedName(State *state) {
522   state->parse_state.nest_level = 0;
523   return true;
524 }
525 
526 // This function is used for handling nested names.
LeaveNestedName(State * state,int16_t prev_value)527 static bool LeaveNestedName(State *state, int16_t prev_value) {
528   state->parse_state.nest_level = prev_value;
529   return true;
530 }
531 
532 // Disable the append mode not to print function parameters, etc.
DisableAppend(State * state)533 static bool DisableAppend(State *state) {
534   state->parse_state.append = false;
535   return true;
536 }
537 
538 // Restore the append mode to the previous state.
RestoreAppend(State * state,bool prev_value)539 static bool RestoreAppend(State *state, bool prev_value) {
540   state->parse_state.append = prev_value;
541   return true;
542 }
543 
544 // Increase the nest level for nested names.
MaybeIncreaseNestLevel(State * state)545 static void MaybeIncreaseNestLevel(State *state) {
546   if (state->parse_state.nest_level > -1) {
547     ++state->parse_state.nest_level;
548   }
549 }
550 
551 // Appends :: for nested names if necessary.
MaybeAppendSeparator(State * state)552 static void MaybeAppendSeparator(State *state) {
553   if (state->parse_state.nest_level >= 1) {
554     MaybeAppend(state, "::");
555   }
556 }
557 
558 // Cancel the last separator if necessary.
MaybeCancelLastSeparator(State * state)559 static void MaybeCancelLastSeparator(State *state) {
560   if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
561       state->parse_state.out_cur_idx >= 2) {
562     state->parse_state.out_cur_idx -= 2;
563     state->out[state->parse_state.out_cur_idx] = '\0';
564   }
565 }
566 
567 // Returns true if the identifier of the given length pointed to by
568 // "mangled_cur" is anonymous namespace.
IdentifierIsAnonymousNamespace(State * state,size_t length)569 static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
570   // Returns true if "anon_prefix" is a proper prefix of "mangled_cur".
571   static const char anon_prefix[] = "_GLOBAL__N_";
572   return (length > (sizeof(anon_prefix) - 1) &&
573           StrPrefix(RemainingInput(state), anon_prefix));
574 }
575 
576 // Forward declarations of our parsing functions.
577 static bool ParseMangledName(State *state);
578 static bool ParseEncoding(State *state);
579 static bool ParseName(State *state);
580 static bool ParseUnscopedName(State *state);
581 static bool ParseNestedName(State *state);
582 static bool ParsePrefix(State *state);
583 static bool ParseUnqualifiedName(State *state);
584 static bool ParseSourceName(State *state);
585 static bool ParseLocalSourceName(State *state);
586 static bool ParseUnnamedTypeName(State *state);
587 static bool ParseNumber(State *state, int *number_out);
588 static bool ParseFloatNumber(State *state);
589 static bool ParseSeqId(State *state);
590 static bool ParseIdentifier(State *state, size_t length);
591 static bool ParseOperatorName(State *state, int *arity);
592 static bool ParseSpecialName(State *state);
593 static bool ParseCallOffset(State *state);
594 static bool ParseNVOffset(State *state);
595 static bool ParseVOffset(State *state);
596 static bool ParseAbiTags(State *state);
597 static bool ParseCtorDtorName(State *state);
598 static bool ParseDecltype(State *state);
599 static bool ParseType(State *state);
600 static bool ParseCVQualifiers(State *state);
601 static bool ParseBuiltinType(State *state);
602 static bool ParseVendorExtendedType(State *state);
603 static bool ParseFunctionType(State *state);
604 static bool ParseBareFunctionType(State *state);
605 static bool ParseOverloadAttribute(State *state);
606 static bool ParseClassEnumType(State *state);
607 static bool ParseArrayType(State *state);
608 static bool ParsePointerToMemberType(State *state);
609 static bool ParseTemplateParam(State *state);
610 static bool ParseTemplateParamDecl(State *state);
611 static bool ParseTemplateTemplateParam(State *state);
612 static bool ParseTemplateArgs(State *state);
613 static bool ParseTemplateArg(State *state);
614 static bool ParseBaseUnresolvedName(State *state);
615 static bool ParseUnresolvedName(State *state);
616 static bool ParseUnresolvedQualifierLevel(State *state);
617 static bool ParseUnionSelector(State* state);
618 static bool ParseFunctionParam(State* state);
619 static bool ParseBracedExpression(State *state);
620 static bool ParseExpression(State *state);
621 static bool ParseExprPrimary(State *state);
622 static bool ParseExprCastValueAndTrailingE(State *state);
623 static bool ParseQRequiresClauseExpr(State *state);
624 static bool ParseRequirement(State *state);
625 static bool ParseTypeConstraint(State *state);
626 static bool ParseLocalName(State *state);
627 static bool ParseLocalNameSuffix(State *state);
628 static bool ParseDiscriminator(State *state);
629 static bool ParseSubstitution(State *state, bool accept_std);
630 
631 // Implementation note: the following code is a straightforward
632 // translation of the Itanium C++ ABI defined in BNF with a couple of
633 // exceptions.
634 //
635 // - Support GNU extensions not defined in the Itanium C++ ABI
636 // - <prefix> and <template-prefix> are combined to avoid infinite loop
637 // - Reorder patterns to shorten the code
638 // - Reorder patterns to give greedier functions precedence
639 //   We'll mark "Less greedy than" for these cases in the code
640 //
641 // Each parsing function changes the parse state and returns true on
642 // success, or returns false and doesn't change the parse state (note:
643 // the parse-steps counter increases regardless of success or failure).
644 // To ensure that the parse state isn't changed in the latter case, we
645 // save the original state before we call multiple parsing functions
646 // consecutively with &&, and restore it if unsuccessful.  See
647 // ParseEncoding() as an example of this convention.  We follow the
648 // convention throughout the code.
649 //
650 // Originally we tried to do demangling without following the full ABI
651 // syntax but it turned out we needed to follow the full syntax to
652 // parse complicated cases like nested template arguments.  Note that
653 // implementing a full-fledged demangler isn't trivial (libiberty's
654 // cp-demangle.c has +4300 lines).
655 //
656 // Note that (foo) in <(foo) ...> is a modifier to be ignored.
657 //
658 // Reference:
659 // - Itanium C++ ABI
660 //   <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
661 
662 // <mangled-name> ::= _Z <encoding>
ParseMangledName(State * state)663 static bool ParseMangledName(State *state) {
664   ComplexityGuard guard(state);
665   if (guard.IsTooComplex()) return false;
666   return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
667 }
668 
669 // <encoding> ::= <(function) name> <bare-function-type>
670 //                [`Q` <requires-clause expr>]
671 //            ::= <(data) name>
672 //            ::= <special-name>
673 //
674 // NOTE: Based on http://shortn/_Hoq9qG83rx
ParseEncoding(State * state)675 static bool ParseEncoding(State *state) {
676   ComplexityGuard guard(state);
677   if (guard.IsTooComplex()) return false;
678   // Since the first two productions both start with <name>, attempt
679   // to parse it only once to avoid exponential blowup of backtracking.
680   //
681   // We're careful about exponential blowup because <encoding> recursively
682   // appears in other productions downstream of its first two productions,
683   // which means that every call to `ParseName` would possibly indirectly
684   // result in two calls to `ParseName` etc.
685   if (ParseName(state)) {
686     if (!ParseBareFunctionType(state)) {
687       return true;  // <(data) name>
688     }
689 
690     // Parsed: <(function) name> <bare-function-type>
691     // Pending: [`Q` <requires-clause expr>]
692     ParseQRequiresClauseExpr(state);  // restores state on failure
693     return true;
694   }
695 
696   if (ParseSpecialName(state)) {
697     return true;  // <special-name>
698   }
699   return false;
700 }
701 
702 // <name> ::= <nested-name>
703 //        ::= <unscoped-template-name> <template-args>
704 //        ::= <unscoped-name>
705 //        ::= <local-name>
ParseName(State * state)706 static bool ParseName(State *state) {
707   ComplexityGuard guard(state);
708   if (guard.IsTooComplex()) return false;
709   if (ParseNestedName(state) || ParseLocalName(state)) {
710     return true;
711   }
712 
713   // We reorganize the productions to avoid re-parsing unscoped names.
714   // - Inline <unscoped-template-name> productions:
715   //   <name> ::= <substitution> <template-args>
716   //          ::= <unscoped-name> <template-args>
717   //          ::= <unscoped-name>
718   // - Merge the two productions that start with unscoped-name:
719   //   <name> ::= <unscoped-name> [<template-args>]
720 
721   ParseState copy = state->parse_state;
722   // "std<...>" isn't a valid name.
723   if (ParseSubstitution(state, /*accept_std=*/false) &&
724       ParseTemplateArgs(state)) {
725     return true;
726   }
727   state->parse_state = copy;
728 
729   // Note there's no need to restore state after this since only the first
730   // subparser can fail.
731   return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
732 }
733 
734 // <unscoped-name> ::= <unqualified-name>
735 //                 ::= St <unqualified-name>
ParseUnscopedName(State * state)736 static bool ParseUnscopedName(State *state) {
737   ComplexityGuard guard(state);
738   if (guard.IsTooComplex()) return false;
739   if (ParseUnqualifiedName(state)) {
740     return true;
741   }
742 
743   ParseState copy = state->parse_state;
744   if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
745       ParseUnqualifiedName(state)) {
746     return true;
747   }
748   state->parse_state = copy;
749   return false;
750 }
751 
752 // <ref-qualifer> ::= R // lvalue method reference qualifier
753 //                ::= O // rvalue method reference qualifier
ParseRefQualifier(State * state)754 static inline bool ParseRefQualifier(State *state) {
755   return ParseCharClass(state, "OR");
756 }
757 
758 // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix>
759 //                   <unqualified-name> E
760 //               ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
761 //                   <template-args> E
ParseNestedName(State * state)762 static bool ParseNestedName(State *state) {
763   ComplexityGuard guard(state);
764   if (guard.IsTooComplex()) return false;
765   ParseState copy = state->parse_state;
766   if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
767       Optional(ParseCVQualifiers(state)) &&
768       Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
769       LeaveNestedName(state, copy.nest_level) &&
770       ParseOneCharToken(state, 'E')) {
771     return true;
772   }
773   state->parse_state = copy;
774   return false;
775 }
776 
777 // This part is tricky.  If we literally translate them to code, we'll
778 // end up infinite loop.  Hence we merge them to avoid the case.
779 //
780 // <prefix> ::= <prefix> <unqualified-name>
781 //          ::= <template-prefix> <template-args>
782 //          ::= <template-param>
783 //          ::= <decltype>
784 //          ::= <substitution>
785 //          ::= # empty
786 // <template-prefix> ::= <prefix> <(template) unqualified-name>
787 //                   ::= <template-param>
788 //                   ::= <substitution>
789 //                   ::= <vendor-extended-type>
ParsePrefix(State * state)790 static bool ParsePrefix(State *state) {
791   ComplexityGuard guard(state);
792   if (guard.IsTooComplex()) return false;
793   bool has_something = false;
794   while (true) {
795     MaybeAppendSeparator(state);
796     if (ParseTemplateParam(state) || ParseDecltype(state) ||
797         ParseSubstitution(state, /*accept_std=*/true) ||
798         // Although the official grammar does not mention it, nested-names
799         // shaped like Nu14__some_builtinIiE6memberE occur in practice, and it
800         // is not clear what else a compiler is supposed to do when a
801         // vendor-extended type has named members.
802         ParseVendorExtendedType(state) ||
803         ParseUnscopedName(state) ||
804         (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) {
805       has_something = true;
806       MaybeIncreaseNestLevel(state);
807       continue;
808     }
809     MaybeCancelLastSeparator(state);
810     if (has_something && ParseTemplateArgs(state)) {
811       return ParsePrefix(state);
812     } else {
813       break;
814     }
815   }
816   return true;
817 }
818 
819 // <unqualified-name> ::= <operator-name> [<abi-tags>]
820 //                    ::= <ctor-dtor-name> [<abi-tags>]
821 //                    ::= <source-name> [<abi-tags>]
822 //                    ::= <local-source-name> [<abi-tags>]
823 //                    ::= <unnamed-type-name> [<abi-tags>]
824 //
825 // <local-source-name> is a GCC extension; see below.
ParseUnqualifiedName(State * state)826 static bool ParseUnqualifiedName(State *state) {
827   ComplexityGuard guard(state);
828   if (guard.IsTooComplex()) return false;
829   if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) ||
830       ParseSourceName(state) || ParseLocalSourceName(state) ||
831       ParseUnnamedTypeName(state)) {
832     return ParseAbiTags(state);
833   }
834   return false;
835 }
836 
837 // <abi-tags> ::= <abi-tag> [<abi-tags>]
838 // <abi-tag>  ::= B <source-name>
ParseAbiTags(State * state)839 static bool ParseAbiTags(State *state) {
840   ComplexityGuard guard(state);
841   if (guard.IsTooComplex()) return false;
842 
843   while (ParseOneCharToken(state, 'B')) {
844     ParseState copy = state->parse_state;
845     MaybeAppend(state, "[abi:");
846 
847     if (!ParseSourceName(state)) {
848       state->parse_state = copy;
849       return false;
850     }
851     MaybeAppend(state, "]");
852   }
853 
854   return true;
855 }
856 
857 // <source-name> ::= <positive length number> <identifier>
ParseSourceName(State * state)858 static bool ParseSourceName(State *state) {
859   ComplexityGuard guard(state);
860   if (guard.IsTooComplex()) return false;
861   ParseState copy = state->parse_state;
862   int length = -1;
863   if (ParseNumber(state, &length) &&
864       ParseIdentifier(state, static_cast<size_t>(length))) {
865     return true;
866   }
867   state->parse_state = copy;
868   return false;
869 }
870 
871 // <local-source-name> ::= L <source-name> [<discriminator>]
872 //
873 // References:
874 //   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
875 //   https://gcc.gnu.org/viewcvs?view=rev&revision=124467
ParseLocalSourceName(State * state)876 static bool ParseLocalSourceName(State *state) {
877   ComplexityGuard guard(state);
878   if (guard.IsTooComplex()) return false;
879   ParseState copy = state->parse_state;
880   if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
881       Optional(ParseDiscriminator(state))) {
882     return true;
883   }
884   state->parse_state = copy;
885   return false;
886 }
887 
888 // <unnamed-type-name> ::= Ut [<(nonnegative) number>] _
889 //                     ::= <closure-type-name>
890 // <closure-type-name> ::= Ul <lambda-sig> E [<(nonnegative) number>] _
891 // <lambda-sig>        ::= <template-param-decl>* <(parameter) type>+
892 //
893 // For <template-param-decl>* in <lambda-sig> see:
894 //
895 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31
ParseUnnamedTypeName(State * state)896 static bool ParseUnnamedTypeName(State *state) {
897   ComplexityGuard guard(state);
898   if (guard.IsTooComplex()) return false;
899   ParseState copy = state->parse_state;
900   // Type's 1-based index n is encoded as { "", n == 1; itoa(n-2), otherwise }.
901   // Optionally parse the encoded value into 'which' and add 2 to get the index.
902   int which = -1;
903 
904   // Unnamed type local to function or class.
905   if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) &&
906       which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
907       ParseOneCharToken(state, '_')) {
908     MaybeAppend(state, "{unnamed type#");
909     MaybeAppendDecimal(state, 2 + which);
910     MaybeAppend(state, "}");
911     return true;
912   }
913   state->parse_state = copy;
914 
915   // Closure type.
916   which = -1;
917   if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
918       ZeroOrMore(ParseTemplateParamDecl, state) &&
919       OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
920       ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
921       which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
922       ParseOneCharToken(state, '_')) {
923     MaybeAppend(state, "{lambda()#");
924     MaybeAppendDecimal(state, 2 + which);
925     MaybeAppend(state, "}");
926     return true;
927   }
928   state->parse_state = copy;
929 
930   return false;
931 }
932 
933 // <number> ::= [n] <non-negative decimal integer>
934 // If "number_out" is non-null, then *number_out is set to the value of the
935 // parsed number on success.
ParseNumber(State * state,int * number_out)936 static bool ParseNumber(State *state, int *number_out) {
937   ComplexityGuard guard(state);
938   if (guard.IsTooComplex()) return false;
939   bool negative = false;
940   if (ParseOneCharToken(state, 'n')) {
941     negative = true;
942   }
943   const char *p = RemainingInput(state);
944   uint64_t number = 0;
945   for (; *p != '\0'; ++p) {
946     if (IsDigit(*p)) {
947       number = number * 10 + static_cast<uint64_t>(*p - '0');
948     } else {
949       break;
950     }
951   }
952   // Apply the sign with uint64_t arithmetic so overflows aren't UB.  Gives
953   // "incorrect" results for out-of-range inputs, but negative values only
954   // appear for literals, which aren't printed.
955   if (negative) {
956     number = ~number + 1;
957   }
958   if (p != RemainingInput(state)) {  // Conversion succeeded.
959     state->parse_state.mangled_idx += p - RemainingInput(state);
960     if (number_out != nullptr) {
961       // Note: possibly truncate "number".
962       *number_out = static_cast<int>(number);
963     }
964     return true;
965   }
966   return false;
967 }
968 
969 // Floating-point literals are encoded using a fixed-length lowercase
970 // hexadecimal string.
ParseFloatNumber(State * state)971 static bool ParseFloatNumber(State *state) {
972   ComplexityGuard guard(state);
973   if (guard.IsTooComplex()) return false;
974   const char *p = RemainingInput(state);
975   for (; *p != '\0'; ++p) {
976     if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
977       break;
978     }
979   }
980   if (p != RemainingInput(state)) {  // Conversion succeeded.
981     state->parse_state.mangled_idx += p - RemainingInput(state);
982     return true;
983   }
984   return false;
985 }
986 
987 // The <seq-id> is a sequence number in base 36,
988 // using digits and upper case letters
ParseSeqId(State * state)989 static bool ParseSeqId(State *state) {
990   ComplexityGuard guard(state);
991   if (guard.IsTooComplex()) return false;
992   const char *p = RemainingInput(state);
993   for (; *p != '\0'; ++p) {
994     if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
995       break;
996     }
997   }
998   if (p != RemainingInput(state)) {  // Conversion succeeded.
999     state->parse_state.mangled_idx += p - RemainingInput(state);
1000     return true;
1001   }
1002   return false;
1003 }
1004 
1005 // <identifier> ::= <unqualified source code identifier> (of given length)
ParseIdentifier(State * state,size_t length)1006 static bool ParseIdentifier(State *state, size_t length) {
1007   ComplexityGuard guard(state);
1008   if (guard.IsTooComplex()) return false;
1009   if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
1010     return false;
1011   }
1012   if (IdentifierIsAnonymousNamespace(state, length)) {
1013     MaybeAppend(state, "(anonymous namespace)");
1014   } else {
1015     MaybeAppendWithLength(state, RemainingInput(state), length);
1016   }
1017   state->parse_state.mangled_idx += length;
1018   return true;
1019 }
1020 
1021 // <operator-name> ::= nw, and other two letters cases
1022 //                 ::= cv <type>  # (cast)
1023 //                 ::= v  <digit> <source-name> # vendor extended operator
ParseOperatorName(State * state,int * arity)1024 static bool ParseOperatorName(State *state, int *arity) {
1025   ComplexityGuard guard(state);
1026   if (guard.IsTooComplex()) return false;
1027   if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
1028     return false;
1029   }
1030   // First check with "cv" (cast) case.
1031   ParseState copy = state->parse_state;
1032   if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
1033       EnterNestedName(state) && ParseType(state) &&
1034       LeaveNestedName(state, copy.nest_level)) {
1035     if (arity != nullptr) {
1036       *arity = 1;
1037     }
1038     return true;
1039   }
1040   state->parse_state = copy;
1041 
1042   // Then vendor extended operators.
1043   if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
1044       ParseSourceName(state)) {
1045     return true;
1046   }
1047   state->parse_state = copy;
1048 
1049   // Other operator names should start with a lower alphabet followed
1050   // by a lower/upper alphabet.
1051   if (!(IsLower(RemainingInput(state)[0]) &&
1052         IsAlpha(RemainingInput(state)[1]))) {
1053     return false;
1054   }
1055   // We may want to perform a binary search if we really need speed.
1056   const AbbrevPair *p;
1057   for (p = kOperatorList; p->abbrev != nullptr; ++p) {
1058     if (RemainingInput(state)[0] == p->abbrev[0] &&
1059         RemainingInput(state)[1] == p->abbrev[1]) {
1060       if (arity != nullptr) {
1061         *arity = p->arity;
1062       }
1063       MaybeAppend(state, "operator");
1064       if (IsLower(*p->real_name)) {  // new, delete, etc.
1065         MaybeAppend(state, " ");
1066       }
1067       MaybeAppend(state, p->real_name);
1068       state->parse_state.mangled_idx += 2;
1069       return true;
1070     }
1071   }
1072   return false;
1073 }
1074 
1075 // <special-name> ::= TV <type>
1076 //                ::= TT <type>
1077 //                ::= TI <type>
1078 //                ::= TS <type>
1079 //                ::= TW <name>  # thread-local wrapper
1080 //                ::= TH <name>  # thread-local initialization
1081 //                ::= Tc <call-offset> <call-offset> <(base) encoding>
1082 //                ::= GV <(object) name>
1083 //                ::= T <call-offset> <(base) encoding>
1084 // G++ extensions:
1085 //                ::= TC <type> <(offset) number> _ <(base) type>
1086 //                ::= TF <type>
1087 //                ::= TJ <type>
1088 //                ::= GR <name>
1089 //                ::= GA <encoding>
1090 //                ::= Th <call-offset> <(base) encoding>
1091 //                ::= Tv <call-offset> <(base) encoding>
1092 //
1093 // Note: Most of these are special data, not functions that occur in stack
1094 // traces.  Exceptions are TW and TH, which denote functions supporting the
1095 // thread_local feature.  For these see:
1096 //
1097 // https://maskray.me/blog/2021-02-14-all-about-thread-local-storage
ParseSpecialName(State * state)1098 static bool ParseSpecialName(State *state) {
1099   ComplexityGuard guard(state);
1100   if (guard.IsTooComplex()) return false;
1101   ParseState copy = state->parse_state;
1102 
1103   if (ParseTwoCharToken(state, "TW")) {
1104     MaybeAppend(state, "thread-local wrapper routine for ");
1105     if (ParseName(state)) return true;
1106     state->parse_state = copy;
1107     return false;
1108   }
1109 
1110   if (ParseTwoCharToken(state, "TH")) {
1111     MaybeAppend(state, "thread-local initialization routine for ");
1112     if (ParseName(state)) return true;
1113     state->parse_state = copy;
1114     return false;
1115   }
1116 
1117   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") &&
1118       ParseType(state)) {
1119     return true;
1120   }
1121   state->parse_state = copy;
1122 
1123   if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
1124       ParseCallOffset(state) && ParseEncoding(state)) {
1125     return true;
1126   }
1127   state->parse_state = copy;
1128 
1129   if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
1130     return true;
1131   }
1132   state->parse_state = copy;
1133 
1134   if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
1135       ParseEncoding(state)) {
1136     return true;
1137   }
1138   state->parse_state = copy;
1139 
1140   // G++ extensions
1141   if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
1142       ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1143       DisableAppend(state) && ParseType(state)) {
1144     RestoreAppend(state, copy.append);
1145     return true;
1146   }
1147   state->parse_state = copy;
1148 
1149   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
1150       ParseType(state)) {
1151     return true;
1152   }
1153   state->parse_state = copy;
1154 
1155   if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
1156     return true;
1157   }
1158   state->parse_state = copy;
1159 
1160   if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
1161     return true;
1162   }
1163   state->parse_state = copy;
1164 
1165   if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
1166       ParseCallOffset(state) && ParseEncoding(state)) {
1167     return true;
1168   }
1169   state->parse_state = copy;
1170   return false;
1171 }
1172 
1173 // <call-offset> ::= h <nv-offset> _
1174 //               ::= v <v-offset> _
ParseCallOffset(State * state)1175 static bool ParseCallOffset(State *state) {
1176   ComplexityGuard guard(state);
1177   if (guard.IsTooComplex()) return false;
1178   ParseState copy = state->parse_state;
1179   if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
1180       ParseOneCharToken(state, '_')) {
1181     return true;
1182   }
1183   state->parse_state = copy;
1184 
1185   if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
1186       ParseOneCharToken(state, '_')) {
1187     return true;
1188   }
1189   state->parse_state = copy;
1190 
1191   return false;
1192 }
1193 
1194 // <nv-offset> ::= <(offset) number>
ParseNVOffset(State * state)1195 static bool ParseNVOffset(State *state) {
1196   ComplexityGuard guard(state);
1197   if (guard.IsTooComplex()) return false;
1198   return ParseNumber(state, nullptr);
1199 }
1200 
1201 // <v-offset>  ::= <(offset) number> _ <(virtual offset) number>
ParseVOffset(State * state)1202 static bool ParseVOffset(State *state) {
1203   ComplexityGuard guard(state);
1204   if (guard.IsTooComplex()) return false;
1205   ParseState copy = state->parse_state;
1206   if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1207       ParseNumber(state, nullptr)) {
1208     return true;
1209   }
1210   state->parse_state = copy;
1211   return false;
1212 }
1213 
1214 // <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
1215 // <base-class-type>
1216 //                  ::= D0 | D1 | D2
1217 // # GCC extensions: "unified" constructor/destructor.  See
1218 // #
1219 // https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
1220 //                  ::= C4 | D4
ParseCtorDtorName(State * state)1221 static bool ParseCtorDtorName(State *state) {
1222   ComplexityGuard guard(state);
1223   if (guard.IsTooComplex()) return false;
1224   ParseState copy = state->parse_state;
1225   if (ParseOneCharToken(state, 'C')) {
1226     if (ParseCharClass(state, "1234")) {
1227       const char *const prev_name =
1228           state->out + state->parse_state.prev_name_idx;
1229       MaybeAppendWithLength(state, prev_name,
1230                             state->parse_state.prev_name_length);
1231       return true;
1232     } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
1233                ParseClassEnumType(state)) {
1234       return true;
1235     }
1236   }
1237   state->parse_state = copy;
1238 
1239   if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
1240     const char *const prev_name = state->out + state->parse_state.prev_name_idx;
1241     MaybeAppend(state, "~");
1242     MaybeAppendWithLength(state, prev_name,
1243                           state->parse_state.prev_name_length);
1244     return true;
1245   }
1246   state->parse_state = copy;
1247   return false;
1248 }
1249 
1250 // <decltype> ::= Dt <expression> E  # decltype of an id-expression or class
1251 //                                   # member access (C++0x)
1252 //            ::= DT <expression> E  # decltype of an expression (C++0x)
ParseDecltype(State * state)1253 static bool ParseDecltype(State *state) {
1254   ComplexityGuard guard(state);
1255   if (guard.IsTooComplex()) return false;
1256 
1257   ParseState copy = state->parse_state;
1258   if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
1259       ParseExpression(state) && ParseOneCharToken(state, 'E')) {
1260     return true;
1261   }
1262   state->parse_state = copy;
1263 
1264   return false;
1265 }
1266 
1267 // <type> ::= <CV-qualifiers> <type>
1268 //        ::= P <type>   # pointer-to
1269 //        ::= R <type>   # reference-to
1270 //        ::= O <type>   # rvalue reference-to (C++0x)
1271 //        ::= C <type>   # complex pair (C 2000)
1272 //        ::= G <type>   # imaginary (C 2000)
1273 //        ::= U <source-name> <type>  # vendor extended type qualifier
1274 //        ::= <builtin-type>
1275 //        ::= <function-type>
1276 //        ::= <class-enum-type>  # note: just an alias for <name>
1277 //        ::= <array-type>
1278 //        ::= <pointer-to-member-type>
1279 //        ::= <template-template-param> <template-args>
1280 //        ::= <template-param>
1281 //        ::= <decltype>
1282 //        ::= <substitution>
1283 //        ::= Dp <type>          # pack expansion of (C++0x)
1284 //        ::= Dv <num-elems> _   # GNU vector extension
1285 //        ::= Dk <type-constraint>  # constrained auto
1286 //
ParseType(State * state)1287 static bool ParseType(State *state) {
1288   ComplexityGuard guard(state);
1289   if (guard.IsTooComplex()) return false;
1290   ParseState copy = state->parse_state;
1291 
1292   // We should check CV-qualifers, and PRGC things first.
1293   //
1294   // CV-qualifiers overlap with some operator names, but an operator name is not
1295   // valid as a type.  To avoid an ambiguity that can lead to exponential time
1296   // complexity, refuse to backtrack the CV-qualifiers.
1297   //
1298   // _Z4aoeuIrMvvE
1299   //  => _Z 4aoeuI        rM  v     v   E
1300   //         aoeu<operator%=, void, void>
1301   //  => _Z 4aoeuI r Mv v              E
1302   //         aoeu<void void::* restrict>
1303   //
1304   // By consuming the CV-qualifiers first, the former parse is disabled.
1305   if (ParseCVQualifiers(state)) {
1306     const bool result = ParseType(state);
1307     if (!result) state->parse_state = copy;
1308     return result;
1309   }
1310   state->parse_state = copy;
1311 
1312   // Similarly, these tag characters can overlap with other <name>s resulting in
1313   // two different parse prefixes that land on <template-args> in the same
1314   // place, such as "C3r1xI...".  So, disable the "ctor-name = C3" parse by
1315   // refusing to backtrack the tag characters.
1316   if (ParseCharClass(state, "OPRCG")) {
1317     const bool result = ParseType(state);
1318     if (!result) state->parse_state = copy;
1319     return result;
1320   }
1321   state->parse_state = copy;
1322 
1323   if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
1324     return true;
1325   }
1326   state->parse_state = copy;
1327 
1328   if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
1329       ParseType(state)) {
1330     return true;
1331   }
1332   state->parse_state = copy;
1333 
1334   if (ParseBuiltinType(state) || ParseFunctionType(state) ||
1335       ParseClassEnumType(state) || ParseArrayType(state) ||
1336       ParsePointerToMemberType(state) || ParseDecltype(state) ||
1337       // "std" on its own isn't a type.
1338       ParseSubstitution(state, /*accept_std=*/false)) {
1339     return true;
1340   }
1341 
1342   if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
1343     return true;
1344   }
1345   state->parse_state = copy;
1346 
1347   // Less greedy than <template-template-param> <template-args>.
1348   if (ParseTemplateParam(state)) {
1349     return true;
1350   }
1351 
1352   if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
1353       ParseOneCharToken(state, '_')) {
1354     return true;
1355   }
1356   state->parse_state = copy;
1357 
1358   if (ParseTwoCharToken(state, "Dk") && ParseTypeConstraint(state)) {
1359     return true;
1360   }
1361   state->parse_state = copy;
1362 
1363   // For this notation see CXXNameMangler::mangleType in Clang's source code.
1364   // The relevant logic and its comment "not clear how to mangle this!" date
1365   // from 2011, so it may be with us awhile.
1366   return ParseLongToken(state, "_SUBSTPACK_");
1367 }
1368 
1369 // <CV-qualifiers> ::= [r] [V] [K]
1370 // We don't allow empty <CV-qualifiers> to avoid infinite loop in
1371 // ParseType().
ParseCVQualifiers(State * state)1372 static bool ParseCVQualifiers(State *state) {
1373   ComplexityGuard guard(state);
1374   if (guard.IsTooComplex()) return false;
1375   int num_cv_qualifiers = 0;
1376   num_cv_qualifiers += ParseOneCharToken(state, 'r');
1377   num_cv_qualifiers += ParseOneCharToken(state, 'V');
1378   num_cv_qualifiers += ParseOneCharToken(state, 'K');
1379   return num_cv_qualifiers > 0;
1380 }
1381 
1382 // <builtin-type> ::= v, etc.  # single-character builtin types
1383 //                ::= <vendor-extended-type>
1384 //                ::= Dd, etc.  # two-character builtin types
1385 //
1386 // Not supported:
1387 //                ::= DF <number> _ # _FloatN (N bits)
1388 //
1389 // NOTE: [I <type> E] is a vendor extension (http://shortn/_FrINpH1XC5).
ParseBuiltinType(State * state)1390 static bool ParseBuiltinType(State *state) {
1391   ComplexityGuard guard(state);
1392   if (guard.IsTooComplex()) return false;
1393 
1394   for (const AbbrevPair *p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
1395     // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
1396     if (p->abbrev[1] == '\0') {
1397       if (ParseOneCharToken(state, p->abbrev[0])) {
1398         MaybeAppend(state, p->real_name);
1399         return true;  // ::= v, etc.  # single-character builtin types
1400       }
1401     } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
1402       MaybeAppend(state, p->real_name);
1403       return true;  // ::= Dd, etc.  # two-character builtin types
1404     }
1405   }
1406 
1407   return ParseVendorExtendedType(state);
1408 }
1409 
1410 // <vendor-extended-type> ::= u <source-name> [I <type> E]
1411 //
1412 // NOTE: [I <type> E] is a vendor extension (http://shortn/_FrINpH1XC5).
ParseVendorExtendedType(State * state)1413 static bool ParseVendorExtendedType(State *state) {
1414   ComplexityGuard guard(state);
1415   if (guard.IsTooComplex()) return false;
1416 
1417   ParseState copy = state->parse_state;
1418   if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
1419     copy = state->parse_state;
1420     if (ParseOneCharToken(state, 'I') && ParseType(state) &&
1421         ParseOneCharToken(state, 'E')) {
1422       return true;  // ::= u <source-name> I <type> E
1423     }
1424     state->parse_state = copy;
1425     return true;  // ::= u <source-name>
1426   }
1427   state->parse_state = copy;
1428   return false;
1429 }
1430 
1431 //  <exception-spec> ::= Do                # non-throwing
1432 //                                           exception-specification (e.g.,
1433 //                                           noexcept, throw())
1434 //                   ::= DO <expression> E # computed (instantiation-dependent)
1435 //                                           noexcept
1436 //                   ::= Dw <type>+ E      # dynamic exception specification
1437 //                                           with instantiation-dependent types
ParseExceptionSpec(State * state)1438 static bool ParseExceptionSpec(State *state) {
1439   ComplexityGuard guard(state);
1440   if (guard.IsTooComplex()) return false;
1441 
1442   if (ParseTwoCharToken(state, "Do")) return true;
1443 
1444   ParseState copy = state->parse_state;
1445   if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
1446       ParseOneCharToken(state, 'E')) {
1447     return true;
1448   }
1449   state->parse_state = copy;
1450   if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
1451       ParseOneCharToken(state, 'E')) {
1452     return true;
1453   }
1454   state->parse_state = copy;
1455 
1456   return false;
1457 }
1458 
1459 // <function-type> ::=
1460 //     [exception-spec] F [Y] <bare-function-type> [<ref-qualifier>] E
1461 //
1462 // <ref-qualifier> ::= R | O
ParseFunctionType(State * state)1463 static bool ParseFunctionType(State *state) {
1464   ComplexityGuard guard(state);
1465   if (guard.IsTooComplex()) return false;
1466   ParseState copy = state->parse_state;
1467   Optional(ParseExceptionSpec(state));
1468   if (!ParseOneCharToken(state, 'F')) {
1469     state->parse_state = copy;
1470     return false;
1471   }
1472   Optional(ParseOneCharToken(state, 'Y'));
1473   if (!ParseBareFunctionType(state)) {
1474     state->parse_state = copy;
1475     return false;
1476   }
1477   Optional(ParseCharClass(state, "RO"));
1478   if (!ParseOneCharToken(state, 'E')) {
1479     state->parse_state = copy;
1480     return false;
1481   }
1482   return true;
1483 }
1484 
1485 // <bare-function-type> ::= <overload-attribute>* <(signature) type>+
1486 //
1487 // The <overload-attribute>* prefix is nonstandard; see the comment on
1488 // ParseOverloadAttribute.
ParseBareFunctionType(State * state)1489 static bool ParseBareFunctionType(State *state) {
1490   ComplexityGuard guard(state);
1491   if (guard.IsTooComplex()) return false;
1492   ParseState copy = state->parse_state;
1493   DisableAppend(state);
1494   if (ZeroOrMore(ParseOverloadAttribute, state) &&
1495       OneOrMore(ParseType, state)) {
1496     RestoreAppend(state, copy.append);
1497     MaybeAppend(state, "()");
1498     return true;
1499   }
1500   state->parse_state = copy;
1501   return false;
1502 }
1503 
1504 // <overload-attribute> ::= Ua <name>
1505 //
1506 // The nonstandard <overload-attribute> production is sufficient to accept the
1507 // current implementation of __attribute__((enable_if(condition, "message")))
1508 // and future attributes of a similar shape.  See
1509 // https://clang.llvm.org/docs/AttributeReference.html#enable-if and the
1510 // definition of CXXNameMangler::mangleFunctionEncodingBareType in Clang's
1511 // source code.
ParseOverloadAttribute(State * state)1512 static bool ParseOverloadAttribute(State *state) {
1513   ComplexityGuard guard(state);
1514   if (guard.IsTooComplex()) return false;
1515   ParseState copy = state->parse_state;
1516   if (ParseTwoCharToken(state, "Ua") && ParseName(state)) {
1517     return true;
1518   }
1519   state->parse_state = copy;
1520   return false;
1521 }
1522 
1523 // <class-enum-type> ::= <name>
ParseClassEnumType(State * state)1524 static bool ParseClassEnumType(State *state) {
1525   ComplexityGuard guard(state);
1526   if (guard.IsTooComplex()) return false;
1527   return ParseName(state);
1528 }
1529 
1530 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
1531 //              ::= A [<(dimension) expression>] _ <(element) type>
ParseArrayType(State * state)1532 static bool ParseArrayType(State *state) {
1533   ComplexityGuard guard(state);
1534   if (guard.IsTooComplex()) return false;
1535   ParseState copy = state->parse_state;
1536   if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
1537       ParseOneCharToken(state, '_') && ParseType(state)) {
1538     return true;
1539   }
1540   state->parse_state = copy;
1541 
1542   if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
1543       ParseOneCharToken(state, '_') && ParseType(state)) {
1544     return true;
1545   }
1546   state->parse_state = copy;
1547   return false;
1548 }
1549 
1550 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
ParsePointerToMemberType(State * state)1551 static bool ParsePointerToMemberType(State *state) {
1552   ComplexityGuard guard(state);
1553   if (guard.IsTooComplex()) return false;
1554   ParseState copy = state->parse_state;
1555   if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
1556     return true;
1557   }
1558   state->parse_state = copy;
1559   return false;
1560 }
1561 
1562 // <template-param> ::= T_
1563 //                  ::= T <parameter-2 non-negative number> _
1564 //                  ::= TL <level-1> __
1565 //                  ::= TL <level-1> _ <parameter-2 non-negative number> _
ParseTemplateParam(State * state)1566 static bool ParseTemplateParam(State *state) {
1567   ComplexityGuard guard(state);
1568   if (guard.IsTooComplex()) return false;
1569   if (ParseTwoCharToken(state, "T_")) {
1570     MaybeAppend(state, "?");  // We don't support template substitutions.
1571     return true;              // ::= T_
1572   }
1573 
1574   ParseState copy = state->parse_state;
1575   if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
1576       ParseOneCharToken(state, '_')) {
1577     MaybeAppend(state, "?");  // We don't support template substitutions.
1578     return true;              // ::= T <parameter-2 non-negative number> _
1579   }
1580   state->parse_state = copy;
1581 
1582   if (ParseTwoCharToken(state, "TL") && ParseNumber(state, nullptr)) {
1583     if (ParseTwoCharToken(state, "__")) {
1584       MaybeAppend(state, "?");  // We don't support template substitutions.
1585       return true;              // ::= TL <level-1> __
1586     }
1587 
1588     if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
1589         ParseOneCharToken(state, '_')) {
1590       MaybeAppend(state, "?");  // We don't support template substitutions.
1591       return true;  // ::= TL <level-1> _ <parameter-2 non-negative number> _
1592     }
1593   }
1594   state->parse_state = copy;
1595   return false;
1596 }
1597 
1598 // <template-param-decl>
1599 //   ::= Ty                                  # template type parameter
1600 //   ::= Tk <concept name> [<template-args>] # constrained type parameter
1601 //   ::= Tn <type>                           # template non-type parameter
1602 //   ::= Tt <template-param-decl>* E         # template template parameter
1603 //   ::= Tp <template-param-decl>            # template parameter pack
1604 //
1605 // NOTE: <concept name> is just a <name>: http://shortn/_MqJVyr0fc1
1606 // TODO(b/324066279): Implement optional suffix for `Tt`:
1607 // [Q <requires-clause expr>]
ParseTemplateParamDecl(State * state)1608 static bool ParseTemplateParamDecl(State *state) {
1609   ComplexityGuard guard(state);
1610   if (guard.IsTooComplex()) return false;
1611   ParseState copy = state->parse_state;
1612 
1613   if (ParseTwoCharToken(state, "Ty")) {
1614     return true;
1615   }
1616   state->parse_state = copy;
1617 
1618   if (ParseTwoCharToken(state, "Tk") && ParseName(state) &&
1619       Optional(ParseTemplateArgs(state))) {
1620     return true;
1621   }
1622   state->parse_state = copy;
1623 
1624   if (ParseTwoCharToken(state, "Tn") && ParseType(state)) {
1625     return true;
1626   }
1627   state->parse_state = copy;
1628 
1629   if (ParseTwoCharToken(state, "Tt") &&
1630       ZeroOrMore(ParseTemplateParamDecl, state) &&
1631       ParseOneCharToken(state, 'E')) {
1632     return true;
1633   }
1634   state->parse_state = copy;
1635 
1636   if (ParseTwoCharToken(state, "Tp") && ParseTemplateParamDecl(state)) {
1637     return true;
1638   }
1639   state->parse_state = copy;
1640 
1641   return false;
1642 }
1643 
1644 // <template-template-param> ::= <template-param>
1645 //                           ::= <substitution>
ParseTemplateTemplateParam(State * state)1646 static bool ParseTemplateTemplateParam(State *state) {
1647   ComplexityGuard guard(state);
1648   if (guard.IsTooComplex()) return false;
1649   return (ParseTemplateParam(state) ||
1650           // "std" on its own isn't a template.
1651           ParseSubstitution(state, /*accept_std=*/false));
1652 }
1653 
1654 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
ParseTemplateArgs(State * state)1655 static bool ParseTemplateArgs(State *state) {
1656   ComplexityGuard guard(state);
1657   if (guard.IsTooComplex()) return false;
1658   ParseState copy = state->parse_state;
1659   DisableAppend(state);
1660   if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
1661       Optional(ParseQRequiresClauseExpr(state)) &&
1662       ParseOneCharToken(state, 'E')) {
1663     RestoreAppend(state, copy.append);
1664     MaybeAppend(state, "<>");
1665     return true;
1666   }
1667   state->parse_state = copy;
1668   return false;
1669 }
1670 
1671 // <template-arg>  ::= <template-param-decl> <template-arg>
1672 //                 ::= <type>
1673 //                 ::= <expr-primary>
1674 //                 ::= J <template-arg>* E        # argument pack
1675 //                 ::= X <expression> E
ParseTemplateArg(State * state)1676 static bool ParseTemplateArg(State *state) {
1677   ComplexityGuard guard(state);
1678   if (guard.IsTooComplex()) return false;
1679   ParseState copy = state->parse_state;
1680   if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
1681       ParseOneCharToken(state, 'E')) {
1682     return true;
1683   }
1684   state->parse_state = copy;
1685 
1686   // There can be significant overlap between the following leading to
1687   // exponential backtracking:
1688   //
1689   //   <expr-primary> ::= L <type> <expr-cast-value> E
1690   //                 e.g. L 2xxIvE 1                 E
1691   //   <type>         ==> <local-source-name> <template-args>
1692   //                 e.g. L 2xx               IvE
1693   //
1694   // This means parsing an entire <type> twice, and <type> can contain
1695   // <template-arg>, so this can generate exponential backtracking.  There is
1696   // only overlap when the remaining input starts with "L <source-name>", so
1697   // parse all cases that can start this way jointly to share the common prefix.
1698   //
1699   // We have:
1700   //
1701   //   <template-arg> ::= <type>
1702   //                  ::= <expr-primary>
1703   //
1704   // First, drop all the productions of <type> that must start with something
1705   // other than 'L'.  All that's left is <class-enum-type>; inline it.
1706   //
1707   //   <type> ::= <nested-name> # starts with 'N'
1708   //          ::= <unscoped-name>
1709   //          ::= <unscoped-template-name> <template-args>
1710   //          ::= <local-name> # starts with 'Z'
1711   //
1712   // Drop and inline again:
1713   //
1714   //   <type> ::= <unscoped-name>
1715   //          ::= <unscoped-name> <template-args>
1716   //          ::= <substitution> <template-args> # starts with 'S'
1717   //
1718   // Merge the first two, inline <unscoped-name>, drop last:
1719   //
1720   //   <type> ::= <unqualified-name> [<template-args>]
1721   //          ::= St <unqualified-name> [<template-args>] # starts with 'S'
1722   //
1723   // Drop and inline:
1724   //
1725   //   <type> ::= <operator-name> [<template-args>] # starts with lowercase
1726   //          ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
1727   //          ::= <source-name> [<template-args>] # starts with digit
1728   //          ::= <local-source-name> [<template-args>]
1729   //          ::= <unnamed-type-name> [<template-args>] # starts with 'U'
1730   //
1731   // One more time:
1732   //
1733   //   <type> ::= L <source-name> [<template-args>]
1734   //
1735   // Likewise with <expr-primary>:
1736   //
1737   //   <expr-primary> ::= L <type> <expr-cast-value> E
1738   //                  ::= LZ <encoding> E # cannot overlap; drop
1739   //                  ::= L <mangled_name> E # cannot overlap; drop
1740   //
1741   // By similar reasoning as shown above, the only <type>s starting with
1742   // <source-name> are "<source-name> [<template-args>]".  Inline this.
1743   //
1744   //   <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
1745   //
1746   // Now inline both of these into <template-arg>:
1747   //
1748   //   <template-arg> ::= L <source-name> [<template-args>]
1749   //                  ::= L <source-name> [<template-args>] <expr-cast-value> E
1750   //
1751   // Merge them and we're done:
1752   //   <template-arg>
1753   //     ::= L <source-name> [<template-args>] [<expr-cast-value> E]
1754   if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
1755     copy = state->parse_state;
1756     if (ParseExprCastValueAndTrailingE(state)) {
1757       return true;
1758     }
1759     state->parse_state = copy;
1760     return true;
1761   }
1762 
1763   // Now that the overlapping cases can't reach this code, we can safely call
1764   // both of these.
1765   if (ParseType(state) || ParseExprPrimary(state)) {
1766     return true;
1767   }
1768   state->parse_state = copy;
1769 
1770   if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
1771       ParseOneCharToken(state, 'E')) {
1772     return true;
1773   }
1774   state->parse_state = copy;
1775 
1776   if (ParseTemplateParamDecl(state) && ParseTemplateArg(state)) {
1777     return true;
1778   }
1779   state->parse_state = copy;
1780 
1781   return false;
1782 }
1783 
1784 // <unresolved-type> ::= <template-param> [<template-args>]
1785 //                   ::= <decltype>
1786 //                   ::= <substitution>
ParseUnresolvedType(State * state)1787 static inline bool ParseUnresolvedType(State *state) {
1788   // No ComplexityGuard because we don't copy the state in this stack frame.
1789   return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
1790          ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
1791 }
1792 
1793 // <simple-id> ::= <source-name> [<template-args>]
ParseSimpleId(State * state)1794 static inline bool ParseSimpleId(State *state) {
1795   // No ComplexityGuard because we don't copy the state in this stack frame.
1796 
1797   // Note: <simple-id> cannot be followed by a parameter pack; see comment in
1798   // ParseUnresolvedType.
1799   return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
1800 }
1801 
1802 // <base-unresolved-name> ::= <source-name> [<template-args>]
1803 //                        ::= on <operator-name> [<template-args>]
1804 //                        ::= dn <destructor-name>
ParseBaseUnresolvedName(State * state)1805 static bool ParseBaseUnresolvedName(State *state) {
1806   ComplexityGuard guard(state);
1807   if (guard.IsTooComplex()) return false;
1808 
1809   if (ParseSimpleId(state)) {
1810     return true;
1811   }
1812 
1813   ParseState copy = state->parse_state;
1814   if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
1815       Optional(ParseTemplateArgs(state))) {
1816     return true;
1817   }
1818   state->parse_state = copy;
1819 
1820   if (ParseTwoCharToken(state, "dn") &&
1821       (ParseUnresolvedType(state) || ParseSimpleId(state))) {
1822     return true;
1823   }
1824   state->parse_state = copy;
1825 
1826   return false;
1827 }
1828 
1829 // <unresolved-name> ::= [gs] <base-unresolved-name>
1830 //                   ::= sr <unresolved-type> <base-unresolved-name>
1831 //                   ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1832 //                         <base-unresolved-name>
1833 //                   ::= [gs] sr <unresolved-qualifier-level>+ E
1834 //                         <base-unresolved-name>
ParseUnresolvedName(State * state)1835 static bool ParseUnresolvedName(State *state) {
1836   ComplexityGuard guard(state);
1837   if (guard.IsTooComplex()) return false;
1838 
1839   ParseState copy = state->parse_state;
1840   if (Optional(ParseTwoCharToken(state, "gs")) &&
1841       ParseBaseUnresolvedName(state)) {
1842     return true;
1843   }
1844   state->parse_state = copy;
1845 
1846   if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
1847       ParseBaseUnresolvedName(state)) {
1848     return true;
1849   }
1850   state->parse_state = copy;
1851 
1852   if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
1853       ParseUnresolvedType(state) &&
1854       OneOrMore(ParseUnresolvedQualifierLevel, state) &&
1855       ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
1856     return true;
1857   }
1858   state->parse_state = copy;
1859 
1860   if (Optional(ParseTwoCharToken(state, "gs")) &&
1861       ParseTwoCharToken(state, "sr") &&
1862       OneOrMore(ParseUnresolvedQualifierLevel, state) &&
1863       ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
1864     return true;
1865   }
1866   state->parse_state = copy;
1867 
1868   return false;
1869 }
1870 
1871 // <unresolved-qualifier-level> ::= <simple-id>
1872 //                              ::= <substitution> <template-args>
1873 //
1874 // The production <substitution> <template-args> is nonstandard but is observed
1875 // in practice.  An upstream discussion on the best shape of <unresolved-name>
1876 // has not converged:
1877 //
1878 // https://github.com/itanium-cxx-abi/cxx-abi/issues/38
ParseUnresolvedQualifierLevel(State * state)1879 static bool ParseUnresolvedQualifierLevel(State *state) {
1880   ComplexityGuard guard(state);
1881   if (guard.IsTooComplex()) return false;
1882 
1883   if (ParseSimpleId(state)) return true;
1884 
1885   ParseState copy = state->parse_state;
1886   if (ParseSubstitution(state, /*accept_std=*/false) &&
1887       ParseTemplateArgs(state)) {
1888     return true;
1889   }
1890   state->parse_state = copy;
1891   return false;
1892 }
1893 
1894 // <union-selector> ::= _ [<number>]
1895 //
1896 // https://github.com/itanium-cxx-abi/cxx-abi/issues/47
ParseUnionSelector(State * state)1897 static bool ParseUnionSelector(State *state) {
1898   return ParseOneCharToken(state, '_') && Optional(ParseNumber(state, nullptr));
1899 }
1900 
1901 // <function-param> ::= fp <(top-level) CV-qualifiers> _
1902 //                  ::= fp <(top-level) CV-qualifiers> <number> _
1903 //                  ::= fL <number> p <(top-level) CV-qualifiers> _
1904 //                  ::= fL <number> p <(top-level) CV-qualifiers> <number> _
1905 //                  ::= fpT  # this
ParseFunctionParam(State * state)1906 static bool ParseFunctionParam(State *state) {
1907   ComplexityGuard guard(state);
1908   if (guard.IsTooComplex()) return false;
1909 
1910   ParseState copy = state->parse_state;
1911 
1912   // Function-param expression (level 0).
1913   if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
1914       Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
1915     return true;
1916   }
1917   state->parse_state = copy;
1918 
1919   // Function-param expression (level 1+).
1920   if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
1921       ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
1922       Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
1923     return true;
1924   }
1925   state->parse_state = copy;
1926 
1927   return ParseThreeCharToken(state, "fpT");
1928 }
1929 
1930 // <braced-expression> ::= <expression>
1931 //                     ::= di <field source-name> <braced-expression>
1932 //                     ::= dx <index expression> <braced-expression>
1933 //                     ::= dX <expression> <expression> <braced-expression>
ParseBracedExpression(State * state)1934 static bool ParseBracedExpression(State *state) {
1935   ComplexityGuard guard(state);
1936   if (guard.IsTooComplex()) return false;
1937 
1938   ParseState copy = state->parse_state;
1939 
1940   if (ParseTwoCharToken(state, "di") && ParseSourceName(state) &&
1941       ParseBracedExpression(state)) {
1942     return true;
1943   }
1944   state->parse_state = copy;
1945 
1946   if (ParseTwoCharToken(state, "dx") && ParseExpression(state) &&
1947       ParseBracedExpression(state)) {
1948     return true;
1949   }
1950   state->parse_state = copy;
1951 
1952   if (ParseTwoCharToken(state, "dX") &&
1953       ParseExpression(state) && ParseExpression(state) &&
1954       ParseBracedExpression(state)) {
1955     return true;
1956   }
1957   state->parse_state = copy;
1958 
1959   return ParseExpression(state);
1960 }
1961 
1962 // <expression> ::= <1-ary operator-name> <expression>
1963 //              ::= <2-ary operator-name> <expression> <expression>
1964 //              ::= <3-ary operator-name> <expression> <expression> <expression>
1965 //              ::= cl <expression>+ E
1966 //              ::= cp <simple-id> <expression>* E # Clang-specific.
1967 //              ::= so <type> <expression> [<number>] <union-selector>* [p] E
1968 //              ::= cv <type> <expression>      # type (expression)
1969 //              ::= cv <type> _ <expression>* E # type (expr-list)
1970 //              ::= tl <type> <braced-expression>* E
1971 //              ::= il <braced-expression>* E
1972 //              ::= dc <type> <expression>
1973 //              ::= sc <type> <expression>
1974 //              ::= cc <type> <expression>
1975 //              ::= rc <type> <expression>
1976 //              ::= st <type>
1977 //              ::= <template-param>
1978 //              ::= <function-param>
1979 //              ::= sZ <template-param>
1980 //              ::= sZ <function-param>
1981 //              ::= sP <template-arg>* E
1982 //              ::= <expr-primary>
1983 //              ::= dt <expression> <unresolved-name> # expr.name
1984 //              ::= pt <expression> <unresolved-name> # expr->name
1985 //              ::= sp <expression>         # argument pack expansion
1986 //              ::= fl <binary operator-name> <expression>
1987 //              ::= fr <binary operator-name> <expression>
1988 //              ::= fL <binary operator-name> <expression> <expression>
1989 //              ::= fR <binary operator-name> <expression> <expression>
1990 //              ::= sr <type> <unqualified-name> <template-args>
1991 //              ::= sr <type> <unqualified-name>
1992 //              ::= u <source-name> <template-arg>* E  # vendor extension
1993 //              ::= rq <requirement>+ E
1994 //              ::= rQ <bare-function-type> _ <requirement>+ E
ParseExpression(State * state)1995 static bool ParseExpression(State *state) {
1996   ComplexityGuard guard(state);
1997   if (guard.IsTooComplex()) return false;
1998   if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
1999     return true;
2000   }
2001 
2002   ParseState copy = state->parse_state;
2003 
2004   // Object/function call expression.
2005   if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
2006       ParseOneCharToken(state, 'E')) {
2007     return true;
2008   }
2009   state->parse_state = copy;
2010 
2011   // Clang-specific "cp <simple-id> <expression>* E"
2012   //   https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
2013   if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
2014       ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
2015     return true;
2016   }
2017   state->parse_state = copy;
2018 
2019   // <expression> ::= so <type> <expression> [<number>] <union-selector>* [p] E
2020   //
2021   // https://github.com/itanium-cxx-abi/cxx-abi/issues/47
2022   if (ParseTwoCharToken(state, "so") && ParseType(state) &&
2023       ParseExpression(state) && Optional(ParseNumber(state, nullptr)) &&
2024       ZeroOrMore(ParseUnionSelector, state) &&
2025       Optional(ParseOneCharToken(state, 'p')) &&
2026       ParseOneCharToken(state, 'E')) {
2027     return true;
2028   }
2029   state->parse_state = copy;
2030 
2031   // <expression> ::= <function-param>
2032   if (ParseFunctionParam(state)) return true;
2033   state->parse_state = copy;
2034 
2035   // <expression> ::= tl <type> <braced-expression>* E
2036   if (ParseTwoCharToken(state, "tl") && ParseType(state) &&
2037       ZeroOrMore(ParseBracedExpression, state) &&
2038       ParseOneCharToken(state, 'E')) {
2039     return true;
2040   }
2041   state->parse_state = copy;
2042 
2043   // <expression> ::= il <braced-expression>* E
2044   if (ParseTwoCharToken(state, "il") &&
2045       ZeroOrMore(ParseBracedExpression, state) &&
2046       ParseOneCharToken(state, 'E')) {
2047     return true;
2048   }
2049   state->parse_state = copy;
2050 
2051   // dynamic_cast, static_cast, const_cast, reinterpret_cast.
2052   //
2053   // <expression> ::= (dc | sc | cc | rc) <type> <expression>
2054   if (ParseCharClass(state, "dscr") && ParseOneCharToken(state, 'c') &&
2055       ParseType(state) && ParseExpression(state)) {
2056     return true;
2057   }
2058   state->parse_state = copy;
2059 
2060   // Parse the conversion expressions jointly to avoid re-parsing the <type> in
2061   // their common prefix.  Parsed as:
2062   // <expression> ::= cv <type> <conversion-args>
2063   // <conversion-args> ::= _ <expression>* E
2064   //                   ::= <expression>
2065   //
2066   // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
2067   // also needs to accept "cv <type>" in other contexts.
2068   if (ParseTwoCharToken(state, "cv")) {
2069     if (ParseType(state)) {
2070       ParseState copy2 = state->parse_state;
2071       if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
2072           ParseOneCharToken(state, 'E')) {
2073         return true;
2074       }
2075       state->parse_state = copy2;
2076       if (ParseExpression(state)) {
2077         return true;
2078       }
2079     }
2080   } else {
2081     // Parse unary, binary, and ternary operator expressions jointly, taking
2082     // care not to re-parse subexpressions repeatedly. Parse like:
2083     //   <expression> ::= <operator-name> <expression>
2084     //                    [<one-to-two-expressions>]
2085     //   <one-to-two-expressions> ::= <expression> [<expression>]
2086     int arity = -1;
2087     if (ParseOperatorName(state, &arity) &&
2088         arity > 0 &&  // 0 arity => disabled.
2089         (arity < 3 || ParseExpression(state)) &&
2090         (arity < 2 || ParseExpression(state)) &&
2091         (arity < 1 || ParseExpression(state))) {
2092       return true;
2093     }
2094   }
2095   state->parse_state = copy;
2096 
2097   // sizeof type
2098   if (ParseTwoCharToken(state, "st") && ParseType(state)) {
2099     return true;
2100   }
2101   state->parse_state = copy;
2102 
2103   // sizeof...(pack)
2104   //
2105   // <expression> ::= sZ <template-param>
2106   //              ::= sZ <function-param>
2107   if (ParseTwoCharToken(state, "sZ") &&
2108       (ParseFunctionParam(state) || ParseTemplateParam(state))) {
2109     return true;
2110   }
2111   state->parse_state = copy;
2112 
2113   // sizeof...(pack) captured from an alias template
2114   //
2115   // <expression> ::= sP <template-arg>* E
2116   if (ParseTwoCharToken(state, "sP") && ZeroOrMore(ParseTemplateArg, state) &&
2117       ParseOneCharToken(state, 'E')) {
2118     return true;
2119   }
2120   state->parse_state = copy;
2121 
2122   // Unary folds (... op pack) and (pack op ...).
2123   //
2124   // <expression> ::= fl <binary operator-name> <expression>
2125   //              ::= fr <binary operator-name> <expression>
2126   if ((ParseTwoCharToken(state, "fl") || ParseTwoCharToken(state, "fr")) &&
2127       ParseOperatorName(state, nullptr) && ParseExpression(state)) {
2128     return true;
2129   }
2130   state->parse_state = copy;
2131 
2132   // Binary folds (init op ... op pack) and (pack op ... op init).
2133   //
2134   // <expression> ::= fL <binary operator-name> <expression> <expression>
2135   //              ::= fR <binary operator-name> <expression> <expression>
2136   if ((ParseTwoCharToken(state, "fL") || ParseTwoCharToken(state, "fR")) &&
2137       ParseOperatorName(state, nullptr) && ParseExpression(state) &&
2138       ParseExpression(state)) {
2139     return true;
2140   }
2141   state->parse_state = copy;
2142 
2143   // Object and pointer member access expressions.
2144   //
2145   // <expression> ::= (dt | pt) <expression> <unresolved-name>
2146   if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
2147       ParseExpression(state) && ParseUnresolvedName(state)) {
2148     return true;
2149   }
2150   state->parse_state = copy;
2151 
2152   // Pointer-to-member access expressions.  This parses the same as a binary
2153   // operator, but it's implemented separately because "ds" shouldn't be
2154   // accepted in other contexts that parse an operator name.
2155   if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
2156       ParseExpression(state)) {
2157     return true;
2158   }
2159   state->parse_state = copy;
2160 
2161   // Parameter pack expansion
2162   if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
2163     return true;
2164   }
2165   state->parse_state = copy;
2166 
2167   // Vendor extended expressions
2168   if (ParseOneCharToken(state, 'u') && ParseSourceName(state) &&
2169       ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) {
2170     return true;
2171   }
2172   state->parse_state = copy;
2173 
2174   // <expression> ::= rq <requirement>+ E
2175   //
2176   // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
2177   if (ParseTwoCharToken(state, "rq") && OneOrMore(ParseRequirement, state) &&
2178       ParseOneCharToken(state, 'E')) {
2179     return true;
2180   }
2181   state->parse_state = copy;
2182 
2183   // <expression> ::= rQ <bare-function-type> _ <requirement>+ E
2184   //
2185   // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
2186   if (ParseTwoCharToken(state, "rQ") && ParseBareFunctionType(state) &&
2187       ParseOneCharToken(state, '_') && OneOrMore(ParseRequirement, state) &&
2188       ParseOneCharToken(state, 'E')) {
2189     return true;
2190   }
2191   state->parse_state = copy;
2192 
2193   return ParseUnresolvedName(state);
2194 }
2195 
2196 // <expr-primary> ::= L <type> <(value) number> E
2197 //                ::= L <type> <(value) float> E
2198 //                ::= L <mangled-name> E
2199 //                // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
2200 //                ::= LZ <encoding> E
2201 //
2202 // Warning, subtle: the "bug" LZ production above is ambiguous with the first
2203 // production where <type> starts with <local-name>, which can lead to
2204 // exponential backtracking in two scenarios:
2205 //
2206 // - When whatever follows the E in the <local-name> in the first production is
2207 //   not a name, we backtrack the whole <encoding> and re-parse the whole thing.
2208 //
2209 // - When whatever follows the <local-name> in the first production is not a
2210 //   number and this <expr-primary> may be followed by a name, we backtrack the
2211 //   <name> and re-parse it.
2212 //
2213 // Moreover this ambiguity isn't always resolved -- for example, the following
2214 // has two different parses:
2215 //
2216 //   _ZaaILZ4aoeuE1x1EvE
2217 //   => operator&&<aoeu, x, E, void>
2218 //   => operator&&<(aoeu::x)(1), void>
2219 //
2220 // To resolve this, we just do what GCC's demangler does, and refuse to parse
2221 // casts to <local-name> types.
ParseExprPrimary(State * state)2222 static bool ParseExprPrimary(State *state) {
2223   ComplexityGuard guard(state);
2224   if (guard.IsTooComplex()) return false;
2225   ParseState copy = state->parse_state;
2226 
2227   // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
2228   // or fail, no backtracking.
2229   if (ParseTwoCharToken(state, "LZ")) {
2230     if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
2231       return true;
2232     }
2233 
2234     state->parse_state = copy;
2235     return false;
2236   }
2237 
2238   if (ParseOneCharToken(state, 'L')) {
2239     // There are two special cases in which a literal may or must contain a type
2240     // without a value.  The first is that both LDnE and LDn0E are valid
2241     // encodings of nullptr, used in different situations.  Recognize LDnE here,
2242     // leaving LDn0E to be recognized by the general logic afterward.
2243     if (ParseThreeCharToken(state, "DnE")) return true;
2244 
2245     // The second special case is a string literal, currently mangled in C++98
2246     // style as LA<length + 1>_KcE.  This is inadequate to support C++11 and
2247     // later versions, and the discussion of this problem has not converged.
2248     //
2249     // https://github.com/itanium-cxx-abi/cxx-abi/issues/64
2250     //
2251     // For now the bare-type mangling is what's used in practice, so we
2252     // recognize this form and only this form if an array type appears here.
2253     // Someday we'll probably have to accept a new form of value mangling in
2254     // LA...E constructs.  (Note also that C++20 allows a wide range of
2255     // class-type objects as template arguments, so someday their values will be
2256     // mangled and we'll have to recognize them here too.)
2257     if (RemainingInput(state)[0] == 'A' /* an array type follows */) {
2258       if (ParseType(state) && ParseOneCharToken(state, 'E')) return true;
2259       state->parse_state = copy;
2260       return false;
2261     }
2262 
2263     // The merged cast production.
2264     if (ParseType(state) && ParseExprCastValueAndTrailingE(state)) {
2265       return true;
2266     }
2267   }
2268   state->parse_state = copy;
2269 
2270   if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
2271       ParseOneCharToken(state, 'E')) {
2272     return true;
2273   }
2274   state->parse_state = copy;
2275 
2276   return false;
2277 }
2278 
2279 // <number> or <float>, followed by 'E', as described above ParseExprPrimary.
ParseExprCastValueAndTrailingE(State * state)2280 static bool ParseExprCastValueAndTrailingE(State *state) {
2281   ComplexityGuard guard(state);
2282   if (guard.IsTooComplex()) return false;
2283   // We have to be able to backtrack after accepting a number because we could
2284   // have e.g. "7fffE", which will accept "7" as a number but then fail to find
2285   // the 'E'.
2286   ParseState copy = state->parse_state;
2287   if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
2288     return true;
2289   }
2290   state->parse_state = copy;
2291 
2292   if (ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) {
2293     return true;
2294   }
2295   state->parse_state = copy;
2296 
2297   return false;
2298 }
2299 
2300 // Parses `Q <requires-clause expr>`.
2301 // If parsing fails, applies backtracking to `state`.
2302 //
2303 // This function covers two symbols instead of one for convenience,
2304 // because in LLVM's Itanium ABI mangling grammar, <requires-clause expr>
2305 // always appears after Q.
2306 //
2307 // Does not emit the parsed `requires` clause to simplify the implementation.
2308 // In other words, these two functions' mangled names will demangle identically:
2309 //
2310 // template <typename T>
2311 // int foo(T) requires IsIntegral<T>;
2312 //
2313 // vs.
2314 //
2315 // template <typename T>
2316 // int foo(T);
ParseQRequiresClauseExpr(State * state)2317 static bool ParseQRequiresClauseExpr(State *state) {
2318   ComplexityGuard guard(state);
2319   if (guard.IsTooComplex()) return false;
2320   ParseState copy = state->parse_state;
2321   DisableAppend(state);
2322 
2323   // <requires-clause expr> is just an <expression>: http://shortn/_9E1Ul0rIM8
2324   if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) {
2325     RestoreAppend(state, copy.append);
2326     return true;
2327   }
2328 
2329   // also restores append
2330   state->parse_state = copy;
2331   return false;
2332 }
2333 
2334 // <requirement> ::= X <expression> [N] [R <type-constraint>]
2335 // <requirement> ::= T <type>
2336 // <requirement> ::= Q <constraint-expression>
2337 //
2338 // <constraint-expression> ::= <expression>
2339 //
2340 // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
ParseRequirement(State * state)2341 static bool ParseRequirement(State *state) {
2342   ComplexityGuard guard(state);
2343   if (guard.IsTooComplex()) return false;
2344 
2345   ParseState copy = state->parse_state;
2346 
2347   if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
2348       Optional(ParseOneCharToken(state, 'N')) &&
2349       // This logic backtracks cleanly if we eat an R but a valid type doesn't
2350       // follow it.
2351       (!ParseOneCharToken(state, 'R') || ParseTypeConstraint(state))) {
2352     return true;
2353   }
2354   state->parse_state = copy;
2355 
2356   if (ParseOneCharToken(state, 'T') && ParseType(state)) return true;
2357   state->parse_state = copy;
2358 
2359   if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) return true;
2360   state->parse_state = copy;
2361 
2362   return false;
2363 }
2364 
2365 // <type-constraint> ::= <name>
ParseTypeConstraint(State * state)2366 static bool ParseTypeConstraint(State *state) {
2367   return ParseName(state);
2368 }
2369 
2370 // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2371 //              ::= Z <(function) encoding> E s [<discriminator>]
2372 //              ::= Z <(function) encoding> E d [<(parameter) number>] _ <name>
2373 //
2374 // Parsing a common prefix of these two productions together avoids an
2375 // exponential blowup of backtracking.  Parse like:
2376 //   <local-name> := Z <encoding> E <local-name-suffix>
2377 //   <local-name-suffix> ::= s [<discriminator>]
2378 //                       ::= d [<(parameter) number>] _ <name>
2379 //                       ::= <name> [<discriminator>]
2380 
ParseLocalNameSuffix(State * state)2381 static bool ParseLocalNameSuffix(State *state) {
2382   ComplexityGuard guard(state);
2383   if (guard.IsTooComplex()) return false;
2384   ParseState copy = state->parse_state;
2385 
2386   // <local-name-suffix> ::= d [<(parameter) number>] _ <name>
2387   if (ParseOneCharToken(state, 'd') &&
2388       (IsDigit(RemainingInput(state)[0]) || RemainingInput(state)[0] == '_')) {
2389     int number = -1;
2390     Optional(ParseNumber(state, &number));
2391     if (number < -1 || number > 2147483645) {
2392       // Work around overflow cases.  We do not expect these outside of a fuzzer
2393       // or other source of adversarial input.  If we do detect overflow here,
2394       // we'll print {default arg#1}.
2395       number = -1;
2396     }
2397     number += 2;
2398 
2399     // The ::{default arg#1}:: infix must be rendered before the lambda itself,
2400     // so print this before parsing the rest of the <local-name-suffix>.
2401     MaybeAppend(state, "::{default arg#");
2402     MaybeAppendDecimal(state, number);
2403     MaybeAppend(state, "}::");
2404     if (ParseOneCharToken(state, '_') && ParseName(state)) return true;
2405 
2406     // On late parse failure, roll back not only the input but also the output,
2407     // whose trailing NUL was overwritten.
2408     state->parse_state = copy;
2409     if (state->parse_state.append) {
2410       state->out[state->parse_state.out_cur_idx] = '\0';
2411     }
2412     return false;
2413   }
2414   state->parse_state = copy;
2415 
2416   // <local-name-suffix> ::= <name> [<discriminator>]
2417   if (MaybeAppend(state, "::") && ParseName(state) &&
2418       Optional(ParseDiscriminator(state))) {
2419     return true;
2420   }
2421   state->parse_state = copy;
2422   if (state->parse_state.append) {
2423     state->out[state->parse_state.out_cur_idx] = '\0';
2424   }
2425 
2426   // <local-name-suffix> ::= s [<discriminator>]
2427   return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
2428 }
2429 
ParseLocalName(State * state)2430 static bool ParseLocalName(State *state) {
2431   ComplexityGuard guard(state);
2432   if (guard.IsTooComplex()) return false;
2433   ParseState copy = state->parse_state;
2434   if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
2435       ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
2436     return true;
2437   }
2438   state->parse_state = copy;
2439   return false;
2440 }
2441 
2442 // <discriminator> := _ <digit>
2443 //                 := __ <number (>= 10)> _
ParseDiscriminator(State * state)2444 static bool ParseDiscriminator(State *state) {
2445   ComplexityGuard guard(state);
2446   if (guard.IsTooComplex()) return false;
2447   ParseState copy = state->parse_state;
2448 
2449   // Both forms start with _ so parse that first.
2450   if (!ParseOneCharToken(state, '_')) return false;
2451 
2452   // <digit>
2453   if (ParseDigit(state, nullptr)) return true;
2454 
2455   // _ <number> _
2456   if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
2457       ParseOneCharToken(state, '_')) {
2458     return true;
2459   }
2460   state->parse_state = copy;
2461   return false;
2462 }
2463 
2464 // <substitution> ::= S_
2465 //                ::= S <seq-id> _
2466 //                ::= St, etc.
2467 //
2468 // "St" is special in that it's not valid as a standalone name, and it *is*
2469 // allowed to precede a name without being wrapped in "N...E".  This means that
2470 // if we accept it on its own, we can accept "St1a" and try to parse
2471 // template-args, then fail and backtrack, accept "St" on its own, then "1a" as
2472 // an unqualified name and re-parse the same template-args.  To block this
2473 // exponential backtracking, we disable it with 'accept_std=false' in
2474 // problematic contexts.
ParseSubstitution(State * state,bool accept_std)2475 static bool ParseSubstitution(State *state, bool accept_std) {
2476   ComplexityGuard guard(state);
2477   if (guard.IsTooComplex()) return false;
2478   if (ParseTwoCharToken(state, "S_")) {
2479     MaybeAppend(state, "?");  // We don't support substitutions.
2480     return true;
2481   }
2482 
2483   ParseState copy = state->parse_state;
2484   if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
2485       ParseOneCharToken(state, '_')) {
2486     MaybeAppend(state, "?");  // We don't support substitutions.
2487     return true;
2488   }
2489   state->parse_state = copy;
2490 
2491   // Expand abbreviations like "St" => "std".
2492   if (ParseOneCharToken(state, 'S')) {
2493     const AbbrevPair *p;
2494     for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
2495       if (RemainingInput(state)[0] == p->abbrev[1] &&
2496           (accept_std || p->abbrev[1] != 't')) {
2497         MaybeAppend(state, "std");
2498         if (p->real_name[0] != '\0') {
2499           MaybeAppend(state, "::");
2500           MaybeAppend(state, p->real_name);
2501         }
2502         ++state->parse_state.mangled_idx;
2503         return true;
2504       }
2505     }
2506   }
2507   state->parse_state = copy;
2508   return false;
2509 }
2510 
2511 // Parse <mangled-name>, optionally followed by either a function-clone suffix
2512 // or version suffix.  Returns true only if all of "mangled_cur" was consumed.
ParseTopLevelMangledName(State * state)2513 static bool ParseTopLevelMangledName(State *state) {
2514   ComplexityGuard guard(state);
2515   if (guard.IsTooComplex()) return false;
2516   if (ParseMangledName(state)) {
2517     if (RemainingInput(state)[0] != '\0') {
2518       // Drop trailing function clone suffix, if any.
2519       if (IsFunctionCloneSuffix(RemainingInput(state))) {
2520         return true;
2521       }
2522       // Append trailing version suffix if any.
2523       // ex. _Z3foo@@GLIBCXX_3.4
2524       if (RemainingInput(state)[0] == '@') {
2525         MaybeAppend(state, RemainingInput(state));
2526         return true;
2527       }
2528       return false;  // Unconsumed suffix.
2529     }
2530     return true;
2531   }
2532   return false;
2533 }
2534 
Overflowed(const State * state)2535 static bool Overflowed(const State *state) {
2536   return state->parse_state.out_cur_idx >= state->out_end_idx;
2537 }
2538 
2539 // The demangler entry point.
Demangle(const char * mangled,char * out,size_t out_size)2540 bool Demangle(const char* mangled, char* out, size_t out_size) {
2541   if (mangled[0] == '_' && mangled[1] == 'R') {
2542     return DemangleRustSymbolEncoding(mangled, out, out_size);
2543   }
2544 
2545   State state;
2546   InitState(&state, mangled, out, out_size);
2547   return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
2548          state.parse_state.out_cur_idx > 0;
2549 }
2550 
DemangleString(const char * mangled)2551 std::string DemangleString(const char* mangled) {
2552   std::string out;
2553   int status = 0;
2554   char* demangled = nullptr;
2555 #if ABSL_INTERNAL_HAS_CXA_DEMANGLE
2556   demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status);
2557 #endif
2558   if (status == 0 && demangled != nullptr) {
2559     out.append(demangled);
2560     free(demangled);
2561   } else {
2562     out.append(mangled);
2563   }
2564   return out;
2565 }
2566 
2567 }  // namespace debugging_internal
2568 ABSL_NAMESPACE_END
2569 }  // namespace absl
2570