Coverage Report

Created: 2026-07-16 06:43

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