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