Coverage Report

Created: 2025-07-11 06:37

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