Coverage Report

Created: 2026-08-13 07:15

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 >= -1 &&                                   // Don't print garbage.
977
0
      which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
978
0
      ParseOneCharToken(state, '_')) {
979
0
    MaybeAppend(state, "{unnamed type#");
980
0
    MaybeAppendDecimal(state, 2 + which);
981
0
    MaybeAppend(state, "}");
982
0
    return true;
983
0
  }
984
0
  state->parse_state = copy;
985
986
  // Closure type.
987
0
  which = -1;
988
0
  if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
989
0
      ZeroOrMore(ParseTemplateParamDecl, state) &&
990
0
      OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
991
0
      ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
992
0
      which >= -1 &&                                   // Don't print garbage.
993
0
      which <= std::numeric_limits<int>::max() - 2 &&  // Don't overflow.
994
0
      ParseOneCharToken(state, '_')) {
995
0
    MaybeAppend(state, "{lambda()#");
996
0
    MaybeAppendDecimal(state, 2 + which);
997
0
    MaybeAppend(state, "}");
998
0
    return true;
999
0
  }
1000
0
  state->parse_state = copy;
1001
1002
0
  return false;
1003
0
}
1004
1005
// <number> ::= [n] <non-negative decimal integer>
1006
// If "number_out" is non-null, then *number_out is set to the value of the
1007
// parsed number on success.
1008
0
static bool ParseNumber(State *state, int *number_out) {
1009
0
  ComplexityGuard guard(state);
1010
0
  if (guard.IsTooComplex()) return false;
1011
0
  bool negative = false;
1012
0
  if (ParseOneCharToken(state, 'n')) {
1013
0
    negative = true;
1014
0
  }
1015
0
  const char *p = RemainingInput(state);
1016
0
  uint64_t number = 0;
1017
0
  for (; *p != '\0'; ++p) {
1018
0
    if (IsDigit(*p)) {
1019
0
      number = number * 10 + static_cast<uint64_t>(*p - '0');
1020
0
    } else {
1021
0
      break;
1022
0
    }
1023
0
  }
1024
  // Apply the sign with uint64_t arithmetic so overflows aren't UB.  Gives
1025
  // "incorrect" results for out-of-range inputs, but negative values only
1026
  // appear for literals, which aren't printed.
1027
0
  if (negative) {
1028
0
    number = ~number + 1;
1029
0
  }
1030
0
  if (p != RemainingInput(state)) {  // Conversion succeeded.
1031
0
    state->parse_state.mangled_idx +=
1032
0
        static_cast<int>(p - RemainingInput(state));
1033
0
    UpdateHighWaterMark(state);
1034
0
    if (number_out != nullptr) {
1035
      // Note: possibly truncate "number".
1036
0
      *number_out = static_cast<int>(number);
1037
0
    }
1038
0
    return true;
1039
0
  }
1040
0
  return false;
1041
0
}
1042
1043
// Floating-point literals are encoded using a fixed-length lowercase
1044
// hexadecimal string.
1045
0
static bool ParseFloatNumber(State *state) {
1046
0
  ComplexityGuard guard(state);
1047
0
  if (guard.IsTooComplex()) return false;
1048
0
  const char *p = RemainingInput(state);
1049
0
  for (; *p != '\0'; ++p) {
1050
0
    if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
1051
0
      break;
1052
0
    }
1053
0
  }
1054
0
  if (p != RemainingInput(state)) {  // Conversion succeeded.
1055
0
    state->parse_state.mangled_idx +=
1056
0
        static_cast<int>(p - RemainingInput(state));
1057
0
    UpdateHighWaterMark(state);
1058
0
    return true;
1059
0
  }
1060
0
  return false;
1061
0
}
1062
1063
// The <seq-id> is a sequence number in base 36,
1064
// using digits and upper case letters
1065
0
static bool ParseSeqId(State *state) {
1066
0
  ComplexityGuard guard(state);
1067
0
  if (guard.IsTooComplex()) return false;
1068
0
  const char *p = RemainingInput(state);
1069
0
  for (; *p != '\0'; ++p) {
1070
0
    if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
1071
0
      break;
1072
0
    }
1073
0
  }
1074
0
  if (p != RemainingInput(state)) {  // Conversion succeeded.
1075
0
    state->parse_state.mangled_idx +=
1076
0
        static_cast<int>(p - RemainingInput(state));
1077
0
    UpdateHighWaterMark(state);
1078
0
    return true;
1079
0
  }
1080
0
  return false;
1081
0
}
1082
1083
// <identifier> ::= <unqualified source code identifier> (of given length)
1084
0
static bool ParseIdentifier(State *state, size_t length) {
1085
0
  ComplexityGuard guard(state);
1086
0
  if (guard.IsTooComplex()) return false;
1087
0
  if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
1088
0
    return false;
1089
0
  }
1090
0
  if (IdentifierIsAnonymousNamespace(state, length)) {
1091
0
    MaybeAppend(state, "(anonymous namespace)");
1092
0
  } else {
1093
0
    MaybeAppendWithLength(state, RemainingInput(state), length);
1094
0
  }
1095
0
  state->parse_state.mangled_idx += static_cast<int>(length);
1096
0
  UpdateHighWaterMark(state);
1097
0
  return true;
1098
0
}
1099
1100
// <operator-name> ::= nw, and other two letters cases
1101
//                 ::= cv <type>  # (cast)
1102
//                 ::= li <source-name>  # C++11 user-defined literal
1103
//                 ::= v  <digit> <source-name> # vendor extended operator
1104
0
static bool ParseOperatorName(State *state, int *arity) {
1105
0
  ComplexityGuard guard(state);
1106
0
  if (guard.IsTooComplex()) return false;
1107
0
  if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
1108
0
    return false;
1109
0
  }
1110
  // First check with "cv" (cast) case.
1111
0
  ParseState copy = state->parse_state;
1112
0
  if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
1113
0
      EnterNestedName(state) && ParseConversionOperatorType(state) &&
1114
0
      LeaveNestedName(state, copy.nest_level)) {
1115
0
    if (arity != nullptr) {
1116
0
      *arity = 1;
1117
0
    }
1118
0
    return true;
1119
0
  }
1120
0
  state->parse_state = copy;
1121
1122
  // Then user-defined literals.
1123
0
  if (ParseTwoCharToken(state, "li") && MaybeAppend(state, "operator\"\" ") &&
1124
0
      ParseSourceName(state)) {
1125
0
    return true;
1126
0
  }
1127
0
  state->parse_state = copy;
1128
1129
  // Then vendor extended operators.
1130
0
  if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
1131
0
      ParseSourceName(state)) {
1132
0
    return true;
1133
0
  }
1134
0
  state->parse_state = copy;
1135
1136
  // Other operator names should start with a lower alphabet followed
1137
  // by a lower/upper alphabet.
1138
0
  if (!(IsLower(RemainingInput(state)[0]) &&
1139
0
        IsAlpha(RemainingInput(state)[1]))) {
1140
0
    return false;
1141
0
  }
1142
  // We may want to perform a binary search if we really need speed.
1143
0
  const AbbrevPair *p;
1144
0
  for (p = kOperatorList; p->abbrev != nullptr; ++p) {
1145
0
    if (RemainingInput(state)[0] == p->abbrev[0] &&
1146
0
        RemainingInput(state)[1] == p->abbrev[1]) {
1147
0
      if (arity != nullptr) {
1148
0
        *arity = p->arity;
1149
0
      }
1150
0
      MaybeAppend(state, "operator");
1151
0
      if (IsLower(*p->real_name)) {  // new, delete, etc.
1152
0
        MaybeAppend(state, " ");
1153
0
      }
1154
0
      MaybeAppend(state, p->real_name);
1155
0
      state->parse_state.mangled_idx += 2;
1156
0
      UpdateHighWaterMark(state);
1157
0
      return true;
1158
0
    }
1159
0
  }
1160
0
  return false;
1161
0
}
1162
1163
// <operator-name> ::= cv <type>  # (cast)
1164
//
1165
// The name of a conversion operator is the one place where cv-qualifiers, *, &,
1166
// and other simple type combinators are expected to appear in our stripped-down
1167
// demangling (elsewhere they appear in function signatures or template
1168
// arguments, which we omit from the output).  We make reasonable efforts to
1169
// render simple cases accurately.
1170
0
static bool ParseConversionOperatorType(State *state) {
1171
0
  ComplexityGuard guard(state);
1172
0
  if (guard.IsTooComplex()) return false;
1173
0
  ParseState copy = state->parse_state;
1174
1175
  // Scan pointers, const, and other easy mangling prefixes with postfix
1176
  // demanglings.  Remember the range of input for later rescanning.
1177
  //
1178
  // See `ParseType` and the `switch` below for the meaning of each char.
1179
0
  const char* begin_simple_prefixes = RemainingInput(state);
1180
0
  while (ParseCharClass(state, "OPRCGrVK")) {}
1181
0
  const char* end_simple_prefixes = RemainingInput(state);
1182
1183
  // Emit the base type first.
1184
0
  if (!ParseType(state)) {
1185
0
    state->parse_state = copy;
1186
0
    return false;
1187
0
  }
1188
1189
  // Then rescan the easy type combinators in reverse order to emit their
1190
  // demanglings in the expected output order.
1191
0
  while (begin_simple_prefixes != end_simple_prefixes) {
1192
0
    switch (*--end_simple_prefixes) {
1193
0
      case 'P':
1194
0
        MaybeAppend(state, "*");
1195
0
        break;
1196
0
      case 'R':
1197
0
        MaybeAppend(state, "&");
1198
0
        break;
1199
0
      case 'O':
1200
0
        MaybeAppend(state, "&&");
1201
0
        break;
1202
0
      case 'C':
1203
0
        MaybeAppend(state, " _Complex");
1204
0
        break;
1205
0
      case 'G':
1206
0
        MaybeAppend(state, " _Imaginary");
1207
0
        break;
1208
0
      case 'r':
1209
0
        MaybeAppend(state, " restrict");
1210
0
        break;
1211
0
      case 'V':
1212
0
        MaybeAppend(state, " volatile");
1213
0
        break;
1214
0
      case 'K':
1215
0
        MaybeAppend(state, " const");
1216
0
        break;
1217
0
    }
1218
0
  }
1219
0
  return true;
1220
0
}
1221
1222
// <special-name> ::= TV <type>
1223
//                ::= TT <type>
1224
//                ::= TI <type>
1225
//                ::= TS <type>
1226
//                ::= TW <name>  # thread-local wrapper
1227
//                ::= TH <name>  # thread-local initialization
1228
//                ::= Tc <call-offset> <call-offset> <(base) encoding>
1229
//                ::= GV <(object) name>
1230
//                ::= GR <(object) name> [<seq-id>] _
1231
//                ::= T <call-offset> <(base) encoding>
1232
//                ::= GTt <encoding>  # transaction-safe entry point
1233
//                ::= TA <template-arg>  # nontype template parameter object
1234
// G++ extensions:
1235
//                ::= TC <type> <(offset) number> _ <(base) type>
1236
//                ::= TF <type>
1237
//                ::= TJ <type>
1238
//                ::= GR <name>  # without final _, perhaps an earlier form?
1239
//                ::= GA <encoding>
1240
//                ::= Th <call-offset> <(base) encoding>
1241
//                ::= Tv <call-offset> <(base) encoding>
1242
//
1243
// Note: Most of these are special data, not functions that occur in stack
1244
// traces.  Exceptions are TW and TH, which denote functions supporting the
1245
// thread_local feature.  For these see:
1246
//
1247
// https://maskray.me/blog/2021-02-14-all-about-thread-local-storage
1248
//
1249
// For TA see https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1250
0
static bool ParseSpecialName(State *state) {
1251
0
  ComplexityGuard guard(state);
1252
0
  if (guard.IsTooComplex()) return false;
1253
0
  ParseState copy = state->parse_state;
1254
1255
0
  if (ParseTwoCharToken(state, "TW")) {
1256
0
    MaybeAppend(state, "thread-local wrapper routine for ");
1257
0
    if (ParseName(state)) return true;
1258
0
    state->parse_state = copy;
1259
0
    return false;
1260
0
  }
1261
1262
0
  if (ParseTwoCharToken(state, "TH")) {
1263
0
    MaybeAppend(state, "thread-local initialization routine for ");
1264
0
    if (ParseName(state)) return true;
1265
0
    state->parse_state = copy;
1266
0
    return false;
1267
0
  }
1268
1269
0
  if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") &&
1270
0
      ParseType(state)) {
1271
0
    return true;
1272
0
  }
1273
0
  state->parse_state = copy;
1274
1275
0
  if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
1276
0
      ParseCallOffset(state) && ParseEncoding(state)) {
1277
0
    return true;
1278
0
  }
1279
0
  state->parse_state = copy;
1280
1281
0
  if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
1282
0
    return true;
1283
0
  }
1284
0
  state->parse_state = copy;
1285
1286
0
  if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
1287
0
      ParseEncoding(state)) {
1288
0
    return true;
1289
0
  }
1290
0
  state->parse_state = copy;
1291
1292
  // G++ extensions
1293
0
  if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
1294
0
      ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1295
0
      DisableAppend(state) && ParseType(state)) {
1296
0
    RestoreAppend(state, copy.append);
1297
0
    return true;
1298
0
  }
1299
0
  state->parse_state = copy;
1300
1301
0
  if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
1302
0
      ParseType(state)) {
1303
0
    return true;
1304
0
  }
1305
0
  state->parse_state = copy;
1306
1307
  // <special-name> ::= GR <(object) name> [<seq-id>] _  # modern standard
1308
  //                ::= GR <(object) name>  # also recognized
1309
0
  if (ParseTwoCharToken(state, "GR")) {
1310
0
    MaybeAppend(state, "reference temporary for ");
1311
0
    if (!ParseName(state)) {
1312
0
      state->parse_state = copy;
1313
0
      return false;
1314
0
    }
1315
0
    const bool has_seq_id = ParseSeqId(state);
1316
0
    const bool has_underscore = ParseOneCharToken(state, '_');
1317
0
    if (has_seq_id && !has_underscore) {
1318
0
      state->parse_state = copy;
1319
0
      return false;
1320
0
    }
1321
0
    return true;
1322
0
  }
1323
1324
0
  if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
1325
0
    return true;
1326
0
  }
1327
0
  state->parse_state = copy;
1328
1329
0
  if (ParseThreeCharToken(state, "GTt") &&
1330
0
      MaybeAppend(state, "transaction clone for ") && ParseEncoding(state)) {
1331
0
    return true;
1332
0
  }
1333
0
  state->parse_state = copy;
1334
1335
0
  if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
1336
0
      ParseCallOffset(state) && ParseEncoding(state)) {
1337
0
    return true;
1338
0
  }
1339
0
  state->parse_state = copy;
1340
1341
0
  if (ParseTwoCharToken(state, "TA")) {
1342
0
    bool append = state->parse_state.append;
1343
0
    DisableAppend(state);
1344
0
    if (ParseTemplateArg(state)) {
1345
0
      RestoreAppend(state, append);
1346
0
      MaybeAppend(state, "template parameter object");
1347
0
      return true;
1348
0
    }
1349
0
  }
1350
0
  state->parse_state = copy;
1351
1352
0
  return false;
1353
0
}
1354
1355
// <call-offset> ::= h <nv-offset> _
1356
//               ::= v <v-offset> _
1357
0
static bool ParseCallOffset(State *state) {
1358
0
  ComplexityGuard guard(state);
1359
0
  if (guard.IsTooComplex()) return false;
1360
0
  ParseState copy = state->parse_state;
1361
0
  if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
1362
0
      ParseOneCharToken(state, '_')) {
1363
0
    return true;
1364
0
  }
1365
0
  state->parse_state = copy;
1366
1367
0
  if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
1368
0
      ParseOneCharToken(state, '_')) {
1369
0
    return true;
1370
0
  }
1371
0
  state->parse_state = copy;
1372
1373
0
  return false;
1374
0
}
1375
1376
// <nv-offset> ::= <(offset) number>
1377
0
static bool ParseNVOffset(State *state) {
1378
0
  ComplexityGuard guard(state);
1379
0
  if (guard.IsTooComplex()) return false;
1380
0
  return ParseNumber(state, nullptr);
1381
0
}
1382
1383
// <v-offset>  ::= <(offset) number> _ <(virtual offset) number>
1384
0
static bool ParseVOffset(State *state) {
1385
0
  ComplexityGuard guard(state);
1386
0
  if (guard.IsTooComplex()) return false;
1387
0
  ParseState copy = state->parse_state;
1388
0
  if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
1389
0
      ParseNumber(state, nullptr)) {
1390
0
    return true;
1391
0
  }
1392
0
  state->parse_state = copy;
1393
0
  return false;
1394
0
}
1395
1396
// <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
1397
// <base-class-type>
1398
//                  ::= D0 | D1 | D2
1399
// # GCC extensions: "unified" constructor/destructor.  See
1400
// #
1401
// https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
1402
//                  ::= C4 | D4
1403
0
static bool ParseCtorDtorName(State *state) {
1404
0
  ComplexityGuard guard(state);
1405
0
  if (guard.IsTooComplex()) return false;
1406
0
  ParseState copy = state->parse_state;
1407
0
  if (ParseOneCharToken(state, 'C')) {
1408
0
    if (ParseCharClass(state, "1234")) {
1409
0
      const char *const prev_name =
1410
0
          state->out + state->parse_state.prev_name_idx;
1411
0
      MaybeAppendWithLength(state, prev_name,
1412
0
                            state->parse_state.prev_name_length);
1413
0
      return true;
1414
0
    } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
1415
0
               ParseClassEnumType(state)) {
1416
0
      return true;
1417
0
    }
1418
0
  }
1419
0
  state->parse_state = copy;
1420
1421
0
  if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
1422
0
    const char *const prev_name = state->out + state->parse_state.prev_name_idx;
1423
0
    MaybeAppend(state, "~");
1424
0
    MaybeAppendWithLength(state, prev_name,
1425
0
                          state->parse_state.prev_name_length);
1426
0
    return true;
1427
0
  }
1428
0
  state->parse_state = copy;
1429
0
  return false;
1430
0
}
1431
1432
// <decltype> ::= Dt <expression> E  # decltype of an id-expression or class
1433
//                                   # member access (C++0x)
1434
//            ::= DT <expression> E  # decltype of an expression (C++0x)
1435
0
static bool ParseDecltype(State *state) {
1436
0
  ComplexityGuard guard(state);
1437
0
  if (guard.IsTooComplex()) return false;
1438
1439
0
  ParseState copy = state->parse_state;
1440
0
  if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
1441
0
      ParseExpression(state) && ParseOneCharToken(state, 'E')) {
1442
0
    return true;
1443
0
  }
1444
0
  state->parse_state = copy;
1445
1446
0
  return false;
1447
0
}
1448
1449
// <type> ::= <CV-qualifiers> <type>
1450
//        ::= P <type>   # pointer-to
1451
//        ::= R <type>   # reference-to
1452
//        ::= O <type>   # rvalue reference-to (C++0x)
1453
//        ::= C <type>   # complex pair (C 2000)
1454
//        ::= G <type>   # imaginary (C 2000)
1455
//        ::= <builtin-type>
1456
//        ::= <function-type>
1457
//        ::= <class-enum-type>  # note: just an alias for <name>
1458
//        ::= <array-type>
1459
//        ::= <pointer-to-member-type>
1460
//        ::= <template-template-param> <template-args>
1461
//        ::= <template-param>
1462
//        ::= <decltype>
1463
//        ::= <substitution>
1464
//        ::= Dp <type>          # pack expansion of (C++0x)
1465
//        ::= Dv <(elements) number> _ <type>  # GNU vector extension
1466
//        ::= Dv <(bytes) expression> _ <type>
1467
//        ::= Dk <type-constraint>  # constrained auto
1468
//
1469
0
static bool ParseType(State *state) {
1470
0
  ComplexityGuard guard(state);
1471
0
  if (guard.IsTooComplex()) return false;
1472
0
  ParseState copy = state->parse_state;
1473
1474
  // We should check CV-qualifers, and PRGC things first.
1475
  //
1476
  // CV-qualifiers overlap with some operator names, but an operator name is not
1477
  // valid as a type.  To avoid an ambiguity that can lead to exponential time
1478
  // complexity, refuse to backtrack the CV-qualifiers.
1479
  //
1480
  // _Z4aoeuIrMvvE
1481
  //  => _Z 4aoeuI        rM  v     v   E
1482
  //         aoeu<operator%=, void, void>
1483
  //  => _Z 4aoeuI r Mv v              E
1484
  //         aoeu<void void::* restrict>
1485
  //
1486
  // By consuming the CV-qualifiers first, the former parse is disabled.
1487
0
  if (ParseCVQualifiers(state)) {
1488
0
    const bool result = ParseType(state);
1489
0
    if (!result) state->parse_state = copy;
1490
0
    return result;
1491
0
  }
1492
0
  state->parse_state = copy;
1493
1494
  // Similarly, these tag characters can overlap with other <name>s resulting in
1495
  // two different parse prefixes that land on <template-args> in the same
1496
  // place, such as "C3r1xI...".  So, disable the "ctor-name = C3" parse by
1497
  // refusing to backtrack the tag characters.
1498
0
  if (ParseCharClass(state, "OPRCG")) {
1499
0
    const bool result = ParseType(state);
1500
0
    if (!result) state->parse_state = copy;
1501
0
    return result;
1502
0
  }
1503
0
  state->parse_state = copy;
1504
1505
0
  if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
1506
0
    return true;
1507
0
  }
1508
0
  state->parse_state = copy;
1509
1510
0
  if (ParseBuiltinType(state) || ParseFunctionType(state) ||
1511
0
      ParseClassEnumType(state) || ParseArrayType(state) ||
1512
0
      ParsePointerToMemberType(state) || ParseDecltype(state) ||
1513
      // "std" on its own isn't a type.
1514
0
      ParseSubstitution(state, /*accept_std=*/false)) {
1515
0
    return true;
1516
0
  }
1517
1518
0
  if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
1519
0
    return true;
1520
0
  }
1521
0
  state->parse_state = copy;
1522
1523
  // Less greedy than <template-template-param> <template-args>.
1524
0
  if (ParseTemplateParam(state)) {
1525
0
    return true;
1526
0
  }
1527
1528
  // GNU vector extension Dv <number> _ <type>
1529
0
  if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
1530
0
      ParseOneCharToken(state, '_') && ParseType(state)) {
1531
0
    return true;
1532
0
  }
1533
0
  state->parse_state = copy;
1534
1535
  // GNU vector extension Dv <expression> _ <type>
1536
0
  if (ParseTwoCharToken(state, "Dv") && ParseExpression(state) &&
1537
0
      ParseOneCharToken(state, '_') && ParseType(state)) {
1538
0
    return true;
1539
0
  }
1540
0
  state->parse_state = copy;
1541
1542
0
  if (ParseTwoCharToken(state, "Dk") && ParseTypeConstraint(state)) {
1543
0
    return true;
1544
0
  }
1545
0
  state->parse_state = copy;
1546
1547
  // For this notation see CXXNameMangler::mangleType in Clang's source code.
1548
  // The relevant logic and its comment "not clear how to mangle this!" date
1549
  // from 2011, so it may be with us awhile.
1550
0
  return ParseLongToken(state, "_SUBSTPACK_");
1551
0
}
1552
1553
// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
1554
// <CV-qualifiers> ::= [r] [V] [K]
1555
//
1556
// We don't allow empty <CV-qualifiers> to avoid infinite loop in
1557
// ParseType().
1558
0
static bool ParseCVQualifiers(State *state) {
1559
0
  ComplexityGuard guard(state);
1560
0
  if (guard.IsTooComplex()) return false;
1561
0
  int num_cv_qualifiers = 0;
1562
0
  while (ParseExtendedQualifier(state)) ++num_cv_qualifiers;
1563
0
  num_cv_qualifiers += ParseOneCharToken(state, 'r');
1564
0
  num_cv_qualifiers += ParseOneCharToken(state, 'V');
1565
0
  num_cv_qualifiers += ParseOneCharToken(state, 'K');
1566
0
  return num_cv_qualifiers > 0;
1567
0
}
1568
1569
// <extended-qualifier> ::= U <source-name> [<template-args>]
1570
0
static bool ParseExtendedQualifier(State *state) {
1571
0
  ComplexityGuard guard(state);
1572
0
  if (guard.IsTooComplex()) return false;
1573
0
  ParseState copy = state->parse_state;
1574
1575
0
  if (!ParseOneCharToken(state, 'U')) return false;
1576
1577
0
  bool append = state->parse_state.append;
1578
0
  DisableAppend(state);
1579
0
  if (!ParseSourceName(state)) {
1580
0
    state->parse_state = copy;
1581
0
    return false;
1582
0
  }
1583
0
  Optional(ParseTemplateArgs(state));
1584
0
  RestoreAppend(state, append);
1585
0
  return true;
1586
0
}
1587
1588
// <builtin-type> ::= v, etc.  # single-character builtin types
1589
//                ::= <vendor-extended-type>
1590
//                ::= Dd, etc.  # two-character builtin types
1591
//                ::= DB (<number> | <expression>) _  # _BitInt(N)
1592
//                ::= DU (<number> | <expression>) _  # unsigned _BitInt(N)
1593
//                ::= DF <number> _  # _FloatN (N bits)
1594
//                ::= DF <number> x  # _FloatNx
1595
//                ::= DF16b  # std::bfloat16_t
1596
//
1597
// Not supported:
1598
//                ::= [DS] DA <fixed-point-size>
1599
//                ::= [DS] DR <fixed-point-size>
1600
// because real implementations of N1169 fixed-point are scant.
1601
0
static bool ParseBuiltinType(State *state) {
1602
0
  ComplexityGuard guard(state);
1603
0
  if (guard.IsTooComplex()) return false;
1604
0
  ParseState copy = state->parse_state;
1605
1606
  // DB (<number> | <expression>) _  # _BitInt(N)
1607
  // DU (<number> | <expression>) _  # unsigned _BitInt(N)
1608
0
  if (ParseTwoCharToken(state, "DB") ||
1609
0
      (ParseTwoCharToken(state, "DU") && MaybeAppend(state, "unsigned "))) {
1610
0
    bool append = state->parse_state.append;
1611
0
    DisableAppend(state);
1612
0
    int number = -1;
1613
0
    if (!ParseNumber(state, &number) && !ParseExpression(state)) {
1614
0
      state->parse_state = copy;
1615
0
      return false;
1616
0
    }
1617
0
    RestoreAppend(state, append);
1618
1619
0
    if (!ParseOneCharToken(state, '_')) {
1620
0
      state->parse_state = copy;
1621
0
      return false;
1622
0
    }
1623
1624
0
    MaybeAppend(state, "_BitInt(");
1625
0
    if (number >= 0) {
1626
0
      MaybeAppendDecimal(state, number);
1627
0
    } else {
1628
0
      MaybeAppend(state, "?");  // the best we can do for dependent sizes
1629
0
    }
1630
0
    MaybeAppend(state, ")");
1631
0
    return true;
1632
0
  }
1633
1634
  // DF <number> _  # _FloatN
1635
  // DF <number> x  # _FloatNx
1636
  // DF16b  # std::bfloat16_t
1637
0
  if (ParseTwoCharToken(state, "DF")) {
1638
0
    if (ParseThreeCharToken(state, "16b")) {
1639
0
      MaybeAppend(state, "std::bfloat16_t");
1640
0
      return true;
1641
0
    }
1642
0
    int number = 0;
1643
0
    if (!ParseNumber(state, &number)) {
1644
0
      state->parse_state = copy;
1645
0
      return false;
1646
0
    }
1647
0
    MaybeAppend(state, "_Float");
1648
0
    MaybeAppendDecimal(state, number);
1649
0
    if (ParseOneCharToken(state, 'x')) {
1650
0
      MaybeAppend(state, "x");
1651
0
      return true;
1652
0
    }
1653
0
    if (ParseOneCharToken(state, '_')) return true;
1654
0
    state->parse_state = copy;
1655
0
    return false;
1656
0
  }
1657
1658
0
  for (const AbbrevPair *p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
1659
    // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
1660
0
    if (p->abbrev[1] == '\0') {
1661
0
      if (ParseOneCharToken(state, p->abbrev[0])) {
1662
0
        MaybeAppend(state, p->real_name);
1663
0
        return true;  // ::= v, etc.  # single-character builtin types
1664
0
      }
1665
0
    } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
1666
0
      MaybeAppend(state, p->real_name);
1667
0
      return true;  // ::= Dd, etc.  # two-character builtin types
1668
0
    }
1669
0
  }
1670
1671
0
  return ParseVendorExtendedType(state);
1672
0
}
1673
1674
// <vendor-extended-type> ::= u <source-name> [<template-args>]
1675
0
static bool ParseVendorExtendedType(State *state) {
1676
0
  ComplexityGuard guard(state);
1677
0
  if (guard.IsTooComplex()) return false;
1678
1679
0
  ParseState copy = state->parse_state;
1680
0
  if (ParseOneCharToken(state, 'u') && ParseSourceName(state) &&
1681
0
      Optional(ParseTemplateArgs(state))) {
1682
0
    return true;
1683
0
  }
1684
0
  state->parse_state = copy;
1685
0
  return false;
1686
0
}
1687
1688
//  <exception-spec> ::= Do                # non-throwing
1689
//                                           exception-specification (e.g.,
1690
//                                           noexcept, throw())
1691
//                   ::= DO <expression> E # computed (instantiation-dependent)
1692
//                                           noexcept
1693
//                   ::= Dw <type>+ E      # dynamic exception specification
1694
//                                           with instantiation-dependent types
1695
0
static bool ParseExceptionSpec(State *state) {
1696
0
  ComplexityGuard guard(state);
1697
0
  if (guard.IsTooComplex()) return false;
1698
1699
0
  if (ParseTwoCharToken(state, "Do")) return true;
1700
1701
0
  ParseState copy = state->parse_state;
1702
0
  if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
1703
0
      ParseOneCharToken(state, 'E')) {
1704
0
    return true;
1705
0
  }
1706
0
  state->parse_state = copy;
1707
0
  if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
1708
0
      ParseOneCharToken(state, 'E')) {
1709
0
    return true;
1710
0
  }
1711
0
  state->parse_state = copy;
1712
1713
0
  return false;
1714
0
}
1715
1716
// <function-type> ::=
1717
//     [exception-spec] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
1718
//
1719
// <ref-qualifier> ::= R | O
1720
0
static bool ParseFunctionType(State *state) {
1721
0
  ComplexityGuard guard(state);
1722
0
  if (guard.IsTooComplex()) return false;
1723
0
  ParseState copy = state->parse_state;
1724
0
  Optional(ParseExceptionSpec(state));
1725
0
  Optional(ParseTwoCharToken(state, "Dx"));
1726
0
  if (!ParseOneCharToken(state, 'F')) {
1727
0
    state->parse_state = copy;
1728
0
    return false;
1729
0
  }
1730
0
  Optional(ParseOneCharToken(state, 'Y'));
1731
0
  if (!ParseBareFunctionType(state)) {
1732
0
    state->parse_state = copy;
1733
0
    return false;
1734
0
  }
1735
0
  Optional(ParseCharClass(state, "RO"));
1736
0
  if (!ParseOneCharToken(state, 'E')) {
1737
0
    state->parse_state = copy;
1738
0
    return false;
1739
0
  }
1740
0
  return true;
1741
0
}
1742
1743
// <bare-function-type> ::= <overload-attribute>* <(signature) type>+
1744
//
1745
// The <overload-attribute>* prefix is nonstandard; see the comment on
1746
// ParseOverloadAttribute.
1747
0
static bool ParseBareFunctionType(State *state) {
1748
0
  ComplexityGuard guard(state);
1749
0
  if (guard.IsTooComplex()) return false;
1750
0
  ParseState copy = state->parse_state;
1751
0
  DisableAppend(state);
1752
0
  if (ZeroOrMore(ParseOverloadAttribute, state) &&
1753
0
      OneOrMore(ParseType, state)) {
1754
0
    RestoreAppend(state, copy.append);
1755
0
    MaybeAppend(state, "()");
1756
0
    return true;
1757
0
  }
1758
0
  state->parse_state = copy;
1759
0
  return false;
1760
0
}
1761
1762
// <overload-attribute> ::= Ua <name>
1763
//
1764
// The nonstandard <overload-attribute> production is sufficient to accept the
1765
// current implementation of __attribute__((enable_if(condition, "message")))
1766
// and future attributes of a similar shape.  See
1767
// https://clang.llvm.org/docs/AttributeReference.html#enable-if and the
1768
// definition of CXXNameMangler::mangleFunctionEncodingBareType in Clang's
1769
// source code.
1770
0
static bool ParseOverloadAttribute(State *state) {
1771
0
  ComplexityGuard guard(state);
1772
0
  if (guard.IsTooComplex()) return false;
1773
0
  ParseState copy = state->parse_state;
1774
0
  if (ParseTwoCharToken(state, "Ua") && ParseName(state)) {
1775
0
    return true;
1776
0
  }
1777
0
  state->parse_state = copy;
1778
0
  return false;
1779
0
}
1780
1781
// <class-enum-type> ::= <name>
1782
//                   ::= Ts <name>  # struct Name or class Name
1783
//                   ::= Tu <name>  # union Name
1784
//                   ::= Te <name>  # enum Name
1785
//
1786
// See http://shortn/_W3YrltiEd0.
1787
0
static bool ParseClassEnumType(State *state) {
1788
0
  ComplexityGuard guard(state);
1789
0
  if (guard.IsTooComplex()) return false;
1790
0
  ParseState copy = state->parse_state;
1791
0
  if (Optional(ParseTwoCharToken(state, "Ts") ||
1792
0
               ParseTwoCharToken(state, "Tu") ||
1793
0
               ParseTwoCharToken(state, "Te")) &&
1794
0
      ParseName(state)) {
1795
0
    return true;
1796
0
  }
1797
0
  state->parse_state = copy;
1798
0
  return false;
1799
0
}
1800
1801
// <array-type> ::= A <(positive dimension) number> _ <(element) type>
1802
//              ::= A [<(dimension) expression>] _ <(element) type>
1803
0
static bool ParseArrayType(State *state) {
1804
0
  ComplexityGuard guard(state);
1805
0
  if (guard.IsTooComplex()) return false;
1806
0
  ParseState copy = state->parse_state;
1807
0
  if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
1808
0
      ParseOneCharToken(state, '_') && ParseType(state)) {
1809
0
    return true;
1810
0
  }
1811
0
  state->parse_state = copy;
1812
1813
0
  if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
1814
0
      ParseOneCharToken(state, '_') && ParseType(state)) {
1815
0
    return true;
1816
0
  }
1817
0
  state->parse_state = copy;
1818
0
  return false;
1819
0
}
1820
1821
// <pointer-to-member-type> ::= M <(class) type> <(member) type>
1822
0
static bool ParsePointerToMemberType(State *state) {
1823
0
  ComplexityGuard guard(state);
1824
0
  if (guard.IsTooComplex()) return false;
1825
0
  ParseState copy = state->parse_state;
1826
0
  if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
1827
0
    return true;
1828
0
  }
1829
0
  state->parse_state = copy;
1830
0
  return false;
1831
0
}
1832
1833
// <template-param> ::= T_
1834
//                  ::= T <parameter-2 non-negative number> _
1835
//                  ::= TL <level-1> __
1836
//                  ::= TL <level-1> _ <parameter-2 non-negative number> _
1837
0
static bool ParseTemplateParam(State *state) {
1838
0
  ComplexityGuard guard(state);
1839
0
  if (guard.IsTooComplex()) return false;
1840
0
  if (ParseTwoCharToken(state, "T_")) {
1841
0
    MaybeAppend(state, "?");  // We don't support template substitutions.
1842
0
    return true;              // ::= T_
1843
0
  }
1844
1845
0
  ParseState copy = state->parse_state;
1846
0
  if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
1847
0
      ParseOneCharToken(state, '_')) {
1848
0
    MaybeAppend(state, "?");  // We don't support template substitutions.
1849
0
    return true;              // ::= T <parameter-2 non-negative number> _
1850
0
  }
1851
0
  state->parse_state = copy;
1852
1853
0
  if (ParseTwoCharToken(state, "TL") && ParseNumber(state, nullptr)) {
1854
0
    if (ParseTwoCharToken(state, "__")) {
1855
0
      MaybeAppend(state, "?");  // We don't support template substitutions.
1856
0
      return true;              // ::= TL <level-1> __
1857
0
    }
1858
1859
0
    if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
1860
0
        ParseOneCharToken(state, '_')) {
1861
0
      MaybeAppend(state, "?");  // We don't support template substitutions.
1862
0
      return true;  // ::= TL <level-1> _ <parameter-2 non-negative number> _
1863
0
    }
1864
0
  }
1865
0
  state->parse_state = copy;
1866
0
  return false;
1867
0
}
1868
1869
// <template-param-decl>
1870
//   ::= Ty                                  # template type parameter
1871
//   ::= Tk <concept name> [<template-args>] # constrained type parameter
1872
//   ::= Tn <type>                           # template non-type parameter
1873
//   ::= Tt <template-param-decl>* E         # template template parameter
1874
//   ::= Tp <template-param-decl>            # template parameter pack
1875
//
1876
// NOTE: <concept name> is just a <name>: http://shortn/_MqJVyr0fc1
1877
// TODO(b/324066279): Implement optional suffix for `Tt`:
1878
// [Q <requires-clause expr>]
1879
0
static bool ParseTemplateParamDecl(State *state) {
1880
0
  ComplexityGuard guard(state);
1881
0
  if (guard.IsTooComplex()) return false;
1882
0
  ParseState copy = state->parse_state;
1883
1884
0
  if (ParseTwoCharToken(state, "Ty")) {
1885
0
    return true;
1886
0
  }
1887
0
  state->parse_state = copy;
1888
1889
0
  if (ParseTwoCharToken(state, "Tk") && ParseName(state) &&
1890
0
      Optional(ParseTemplateArgs(state))) {
1891
0
    return true;
1892
0
  }
1893
0
  state->parse_state = copy;
1894
1895
0
  if (ParseTwoCharToken(state, "Tn") && ParseType(state)) {
1896
0
    return true;
1897
0
  }
1898
0
  state->parse_state = copy;
1899
1900
0
  if (ParseTwoCharToken(state, "Tt") &&
1901
0
      ZeroOrMore(ParseTemplateParamDecl, state) &&
1902
0
      ParseOneCharToken(state, 'E')) {
1903
0
    return true;
1904
0
  }
1905
0
  state->parse_state = copy;
1906
1907
0
  if (ParseTwoCharToken(state, "Tp") && ParseTemplateParamDecl(state)) {
1908
0
    return true;
1909
0
  }
1910
0
  state->parse_state = copy;
1911
1912
0
  return false;
1913
0
}
1914
1915
// <template-template-param> ::= <template-param>
1916
//                           ::= <substitution>
1917
0
static bool ParseTemplateTemplateParam(State *state) {
1918
0
  ComplexityGuard guard(state);
1919
0
  if (guard.IsTooComplex()) return false;
1920
0
  return (ParseTemplateParam(state) ||
1921
          // "std" on its own isn't a template.
1922
0
          ParseSubstitution(state, /*accept_std=*/false));
1923
0
}
1924
1925
// <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
1926
0
static bool ParseTemplateArgs(State *state) {
1927
0
  ComplexityGuard guard(state);
1928
0
  if (guard.IsTooComplex()) return false;
1929
0
  ParseState copy = state->parse_state;
1930
0
  DisableAppend(state);
1931
0
  if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
1932
0
      Optional(ParseQRequiresClauseExpr(state)) &&
1933
0
      ParseOneCharToken(state, 'E')) {
1934
0
    RestoreAppend(state, copy.append);
1935
0
    MaybeAppend(state, "<>");
1936
0
    return true;
1937
0
  }
1938
0
  state->parse_state = copy;
1939
0
  return false;
1940
0
}
1941
1942
// <template-arg>  ::= <template-param-decl> <template-arg>
1943
//                 ::= <type>
1944
//                 ::= <expr-primary>
1945
//                 ::= J <template-arg>* E        # argument pack
1946
//                 ::= X <expression> E
1947
0
static bool ParseTemplateArg(State *state) {
1948
0
  ComplexityGuard guard(state);
1949
0
  if (guard.IsTooComplex()) return false;
1950
0
  ParseState copy = state->parse_state;
1951
0
  if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
1952
0
      ParseOneCharToken(state, 'E')) {
1953
0
    return true;
1954
0
  }
1955
0
  state->parse_state = copy;
1956
1957
  // There can be significant overlap between the following leading to
1958
  // exponential backtracking:
1959
  //
1960
  //   <expr-primary> ::= L <type> <expr-cast-value> E
1961
  //                 e.g. L 2xxIvE 1                 E
1962
  //   <type>         ==> <local-source-name> <template-args>
1963
  //                 e.g. L 2xx               IvE
1964
  //
1965
  // This means parsing an entire <type> twice, and <type> can contain
1966
  // <template-arg>, so this can generate exponential backtracking.  There is
1967
  // only overlap when the remaining input starts with "L <source-name>", so
1968
  // parse all cases that can start this way jointly to share the common prefix.
1969
  //
1970
  // We have:
1971
  //
1972
  //   <template-arg> ::= <type>
1973
  //                  ::= <expr-primary>
1974
  //
1975
  // First, drop all the productions of <type> that must start with something
1976
  // other than 'L'.  All that's left is <class-enum-type>; inline it.
1977
  //
1978
  //   <type> ::= <nested-name> # starts with 'N'
1979
  //          ::= <unscoped-name>
1980
  //          ::= <unscoped-template-name> <template-args>
1981
  //          ::= <local-name> # starts with 'Z'
1982
  //
1983
  // Drop and inline again:
1984
  //
1985
  //   <type> ::= <unscoped-name>
1986
  //          ::= <unscoped-name> <template-args>
1987
  //          ::= <substitution> <template-args> # starts with 'S'
1988
  //
1989
  // Merge the first two, inline <unscoped-name>, drop last:
1990
  //
1991
  //   <type> ::= <unqualified-name> [<template-args>]
1992
  //          ::= St <unqualified-name> [<template-args>] # starts with 'S'
1993
  //
1994
  // Drop and inline:
1995
  //
1996
  //   <type> ::= <operator-name> [<template-args>] # starts with lowercase
1997
  //          ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
1998
  //          ::= <source-name> [<template-args>] # starts with digit
1999
  //          ::= <local-source-name> [<template-args>]
2000
  //          ::= <unnamed-type-name> [<template-args>] # starts with 'U'
2001
  //
2002
  // One more time:
2003
  //
2004
  //   <type> ::= L <source-name> [<template-args>]
2005
  //
2006
  // Likewise with <expr-primary>:
2007
  //
2008
  //   <expr-primary> ::= L <type> <expr-cast-value> E
2009
  //                  ::= LZ <encoding> E # cannot overlap; drop
2010
  //                  ::= L <mangled_name> E # cannot overlap; drop
2011
  //
2012
  // By similar reasoning as shown above, the only <type>s starting with
2013
  // <source-name> are "<source-name> [<template-args>]".  Inline this.
2014
  //
2015
  //   <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
2016
  //
2017
  // Now inline both of these into <template-arg>:
2018
  //
2019
  //   <template-arg> ::= L <source-name> [<template-args>]
2020
  //                  ::= L <source-name> [<template-args>] <expr-cast-value> E
2021
  //
2022
  // Merge them and we're done:
2023
  //   <template-arg>
2024
  //     ::= L <source-name> [<template-args>] [<expr-cast-value> E]
2025
0
  if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
2026
0
    copy = state->parse_state;
2027
0
    if (ParseExprCastValueAndTrailingE(state)) {
2028
0
      return true;
2029
0
    }
2030
0
    state->parse_state = copy;
2031
0
    return true;
2032
0
  }
2033
2034
  // Now that the overlapping cases can't reach this code, we can safely call
2035
  // both of these.
2036
0
  if (ParseType(state) || ParseExprPrimary(state)) {
2037
0
    return true;
2038
0
  }
2039
0
  state->parse_state = copy;
2040
2041
0
  if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
2042
0
      ParseOneCharToken(state, 'E')) {
2043
0
    return true;
2044
0
  }
2045
0
  state->parse_state = copy;
2046
2047
0
  if (ParseTemplateParamDecl(state) && ParseTemplateArg(state)) {
2048
0
    return true;
2049
0
  }
2050
0
  state->parse_state = copy;
2051
2052
0
  return false;
2053
0
}
2054
2055
// <unresolved-type> ::= <template-param> [<template-args>]
2056
//                   ::= <decltype>
2057
//                   ::= <substitution>
2058
0
static inline bool ParseUnresolvedType(State *state) {
2059
  // No ComplexityGuard because we don't copy the state in this stack frame.
2060
0
  return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
2061
0
         ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
2062
0
}
2063
2064
// <simple-id> ::= <source-name> [<template-args>]
2065
0
static inline bool ParseSimpleId(State *state) {
2066
  // No ComplexityGuard because we don't copy the state in this stack frame.
2067
2068
  // Note: <simple-id> cannot be followed by a parameter pack; see comment in
2069
  // ParseUnresolvedType.
2070
0
  return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
2071
0
}
2072
2073
// <base-unresolved-name> ::= <source-name> [<template-args>]
2074
//                        ::= on <operator-name> [<template-args>]
2075
//                        ::= dn <destructor-name>
2076
0
static bool ParseBaseUnresolvedName(State *state) {
2077
0
  ComplexityGuard guard(state);
2078
0
  if (guard.IsTooComplex()) return false;
2079
2080
0
  if (ParseSimpleId(state)) {
2081
0
    return true;
2082
0
  }
2083
2084
0
  ParseState copy = state->parse_state;
2085
0
  if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
2086
0
      Optional(ParseTemplateArgs(state))) {
2087
0
    return true;
2088
0
  }
2089
0
  state->parse_state = copy;
2090
2091
0
  if (ParseTwoCharToken(state, "dn") &&
2092
0
      (ParseUnresolvedType(state) || ParseSimpleId(state))) {
2093
0
    return true;
2094
0
  }
2095
0
  state->parse_state = copy;
2096
2097
0
  return false;
2098
0
}
2099
2100
// <unresolved-name> ::= [gs] <base-unresolved-name>
2101
//                   ::= sr <unresolved-type> <base-unresolved-name>
2102
//                   ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
2103
//                         <base-unresolved-name>
2104
//                   ::= [gs] sr <unresolved-qualifier-level>+ E
2105
//                         <base-unresolved-name>
2106
//                   ::= sr St <simple-id> <simple-id>  # nonstandard
2107
//
2108
// The last case is not part of the official grammar but has been observed in
2109
// real-world examples that the GNU demangler (but not the LLVM demangler) is
2110
// able to decode; see demangle_test.cc for one such symbol name.  The shape
2111
// sr St <simple-id> <simple-id> was inferred by closed-box testing of the GNU
2112
// demangler.
2113
0
static bool ParseUnresolvedName(State *state) {
2114
0
  ComplexityGuard guard(state);
2115
0
  if (guard.IsTooComplex()) return false;
2116
2117
0
  ParseState copy = state->parse_state;
2118
0
  if (Optional(ParseTwoCharToken(state, "gs")) &&
2119
0
      ParseBaseUnresolvedName(state)) {
2120
0
    return true;
2121
0
  }
2122
0
  state->parse_state = copy;
2123
2124
0
  if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
2125
0
      ParseBaseUnresolvedName(state)) {
2126
0
    return true;
2127
0
  }
2128
0
  state->parse_state = copy;
2129
2130
0
  if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
2131
0
      ParseUnresolvedType(state) &&
2132
0
      OneOrMore(ParseUnresolvedQualifierLevel, state) &&
2133
0
      ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
2134
0
    return true;
2135
0
  }
2136
0
  state->parse_state = copy;
2137
2138
0
  if (Optional(ParseTwoCharToken(state, "gs")) &&
2139
0
      ParseTwoCharToken(state, "sr") &&
2140
0
      OneOrMore(ParseUnresolvedQualifierLevel, state) &&
2141
0
      ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
2142
0
    return true;
2143
0
  }
2144
0
  state->parse_state = copy;
2145
2146
0
  if (ParseTwoCharToken(state, "sr") && ParseTwoCharToken(state, "St") &&
2147
0
      ParseSimpleId(state) && ParseSimpleId(state)) {
2148
0
    return true;
2149
0
  }
2150
0
  state->parse_state = copy;
2151
2152
0
  return false;
2153
0
}
2154
2155
// <unresolved-qualifier-level> ::= <simple-id>
2156
//                              ::= <substitution> <template-args>
2157
//
2158
// The production <substitution> <template-args> is nonstandard but is observed
2159
// in practice.  An upstream discussion on the best shape of <unresolved-name>
2160
// has not converged:
2161
//
2162
// https://github.com/itanium-cxx-abi/cxx-abi/issues/38
2163
0
static bool ParseUnresolvedQualifierLevel(State *state) {
2164
0
  ComplexityGuard guard(state);
2165
0
  if (guard.IsTooComplex()) return false;
2166
2167
0
  if (ParseSimpleId(state)) return true;
2168
2169
0
  ParseState copy = state->parse_state;
2170
0
  if (ParseSubstitution(state, /*accept_std=*/false) &&
2171
0
      ParseTemplateArgs(state)) {
2172
0
    return true;
2173
0
  }
2174
0
  state->parse_state = copy;
2175
0
  return false;
2176
0
}
2177
2178
// <union-selector> ::= _ [<number>]
2179
//
2180
// https://github.com/itanium-cxx-abi/cxx-abi/issues/47
2181
0
static bool ParseUnionSelector(State *state) {
2182
0
  return ParseOneCharToken(state, '_') && Optional(ParseNumber(state, nullptr));
2183
0
}
2184
2185
// <function-param> ::= fp <(top-level) CV-qualifiers> _
2186
//                  ::= fp <(top-level) CV-qualifiers> <number> _
2187
//                  ::= fL <number> p <(top-level) CV-qualifiers> _
2188
//                  ::= fL <number> p <(top-level) CV-qualifiers> <number> _
2189
//                  ::= fpT  # this
2190
0
static bool ParseFunctionParam(State *state) {
2191
0
  ComplexityGuard guard(state);
2192
0
  if (guard.IsTooComplex()) return false;
2193
2194
0
  ParseState copy = state->parse_state;
2195
2196
  // Function-param expression (level 0).
2197
0
  if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
2198
0
      Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
2199
0
    return true;
2200
0
  }
2201
0
  state->parse_state = copy;
2202
2203
  // Function-param expression (level 1+).
2204
0
  if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
2205
0
      ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
2206
0
      Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
2207
0
    return true;
2208
0
  }
2209
0
  state->parse_state = copy;
2210
2211
0
  return ParseThreeCharToken(state, "fpT");
2212
0
}
2213
2214
// <braced-expression> ::= <expression>
2215
//                     ::= di <field source-name> <braced-expression>
2216
//                     ::= dx <index expression> <braced-expression>
2217
//                     ::= dX <expression> <expression> <braced-expression>
2218
0
static bool ParseBracedExpression(State *state) {
2219
0
  ComplexityGuard guard(state);
2220
0
  if (guard.IsTooComplex()) return false;
2221
2222
0
  ParseState copy = state->parse_state;
2223
2224
0
  if (ParseTwoCharToken(state, "di") && ParseSourceName(state) &&
2225
0
      ParseBracedExpression(state)) {
2226
0
    return true;
2227
0
  }
2228
0
  state->parse_state = copy;
2229
2230
0
  if (ParseTwoCharToken(state, "dx") && ParseExpression(state) &&
2231
0
      ParseBracedExpression(state)) {
2232
0
    return true;
2233
0
  }
2234
0
  state->parse_state = copy;
2235
2236
0
  if (ParseTwoCharToken(state, "dX") &&
2237
0
      ParseExpression(state) && ParseExpression(state) &&
2238
0
      ParseBracedExpression(state)) {
2239
0
    return true;
2240
0
  }
2241
0
  state->parse_state = copy;
2242
2243
0
  return ParseExpression(state);
2244
0
}
2245
2246
// <expression> ::= <1-ary operator-name> <expression>
2247
//              ::= <2-ary operator-name> <expression> <expression>
2248
//              ::= <3-ary operator-name> <expression> <expression> <expression>
2249
//              ::= pp_ <expression>  # ++e; pp <expression> is e++
2250
//              ::= mm_ <expression>  # --e; mm <expression> is e--
2251
//              ::= cl <expression>+ E
2252
//              ::= cp <simple-id> <expression>* E # Clang-specific.
2253
//              ::= so <type> <expression> [<number>] <union-selector>* [p] E
2254
//              ::= cv <type> <expression>      # type (expression)
2255
//              ::= cv <type> _ <expression>* E # type (expr-list)
2256
//              ::= tl <type> <braced-expression>* E
2257
//              ::= il <braced-expression>* E
2258
//              ::= [gs] nw <expression>* _ <type> E
2259
//              ::= [gs] nw <expression>* _ <type> <initializer>
2260
//              ::= [gs] na <expression>* _ <type> E
2261
//              ::= [gs] na <expression>* _ <type> <initializer>
2262
//              ::= [gs] dl <expression>
2263
//              ::= [gs] da <expression>
2264
//              ::= dc <type> <expression>
2265
//              ::= sc <type> <expression>
2266
//              ::= cc <type> <expression>
2267
//              ::= rc <type> <expression>
2268
//              ::= ti <type>
2269
//              ::= te <expression>
2270
//              ::= st <type>
2271
//              ::= at <type>
2272
//              ::= az <expression>
2273
//              ::= nx <expression>
2274
//              ::= <template-param>
2275
//              ::= <function-param>
2276
//              ::= sZ <template-param>
2277
//              ::= sZ <function-param>
2278
//              ::= sP <template-arg>* E
2279
//              ::= <expr-primary>
2280
//              ::= dt <expression> <unresolved-name> # expr.name
2281
//              ::= pt <expression> <unresolved-name> # expr->name
2282
//              ::= sp <expression>         # argument pack expansion
2283
//              ::= fl <binary operator-name> <expression>
2284
//              ::= fr <binary operator-name> <expression>
2285
//              ::= fL <binary operator-name> <expression> <expression>
2286
//              ::= fR <binary operator-name> <expression> <expression>
2287
//              ::= tw <expression>
2288
//              ::= tr
2289
//              ::= sr <type> <unqualified-name> <template-args>
2290
//              ::= sr <type> <unqualified-name>
2291
//              ::= u <source-name> <template-arg>* E  # vendor extension
2292
//              ::= rq <requirement>+ E
2293
//              ::= rQ <bare-function-type> _ <requirement>+ E
2294
0
static bool ParseExpression(State *state) {
2295
0
  ComplexityGuard guard(state);
2296
0
  if (guard.IsTooComplex()) return false;
2297
0
  if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
2298
0
    return true;
2299
0
  }
2300
2301
0
  ParseState copy = state->parse_state;
2302
2303
  // Object/function call expression.
2304
0
  if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
2305
0
      ParseOneCharToken(state, 'E')) {
2306
0
    return true;
2307
0
  }
2308
0
  state->parse_state = copy;
2309
2310
  // Preincrement and predecrement.  Postincrement and postdecrement are handled
2311
  // by the operator-name logic later on.
2312
0
  if ((ParseThreeCharToken(state, "pp_") ||
2313
0
       ParseThreeCharToken(state, "mm_")) &&
2314
0
      ParseExpression(state)) {
2315
0
    return true;
2316
0
  }
2317
0
  state->parse_state = copy;
2318
2319
  // Clang-specific "cp <simple-id> <expression>* E"
2320
  //   https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
2321
0
  if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
2322
0
      ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
2323
0
    return true;
2324
0
  }
2325
0
  state->parse_state = copy;
2326
2327
  // <expression> ::= so <type> <expression> [<number>] <union-selector>* [p] E
2328
  //
2329
  // https://github.com/itanium-cxx-abi/cxx-abi/issues/47
2330
0
  if (ParseTwoCharToken(state, "so") && ParseType(state) &&
2331
0
      ParseExpression(state) && Optional(ParseNumber(state, nullptr)) &&
2332
0
      ZeroOrMore(ParseUnionSelector, state) &&
2333
0
      Optional(ParseOneCharToken(state, 'p')) &&
2334
0
      ParseOneCharToken(state, 'E')) {
2335
0
    return true;
2336
0
  }
2337
0
  state->parse_state = copy;
2338
2339
  // <expression> ::= <function-param>
2340
0
  if (ParseFunctionParam(state)) return true;
2341
0
  state->parse_state = copy;
2342
2343
  // <expression> ::= tl <type> <braced-expression>* E
2344
0
  if (ParseTwoCharToken(state, "tl") && ParseType(state) &&
2345
0
      ZeroOrMore(ParseBracedExpression, state) &&
2346
0
      ParseOneCharToken(state, 'E')) {
2347
0
    return true;
2348
0
  }
2349
0
  state->parse_state = copy;
2350
2351
  // <expression> ::= il <braced-expression>* E
2352
0
  if (ParseTwoCharToken(state, "il") &&
2353
0
      ZeroOrMore(ParseBracedExpression, state) &&
2354
0
      ParseOneCharToken(state, 'E')) {
2355
0
    return true;
2356
0
  }
2357
0
  state->parse_state = copy;
2358
2359
  // <expression> ::= [gs] nw <expression>* _ <type> E
2360
  //              ::= [gs] nw <expression>* _ <type> <initializer>
2361
  //              ::= [gs] na <expression>* _ <type> E
2362
  //              ::= [gs] na <expression>* _ <type> <initializer>
2363
0
  if (Optional(ParseTwoCharToken(state, "gs")) &&
2364
0
      (ParseTwoCharToken(state, "nw") || ParseTwoCharToken(state, "na")) &&
2365
0
      ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, '_') &&
2366
0
      ParseType(state) &&
2367
0
      (ParseOneCharToken(state, 'E') || ParseInitializer(state))) {
2368
0
    return true;
2369
0
  }
2370
0
  state->parse_state = copy;
2371
2372
  // <expression> ::= [gs] dl <expression>
2373
  //              ::= [gs] da <expression>
2374
0
  if (Optional(ParseTwoCharToken(state, "gs")) &&
2375
0
      (ParseTwoCharToken(state, "dl") || ParseTwoCharToken(state, "da")) &&
2376
0
      ParseExpression(state)) {
2377
0
    return true;
2378
0
  }
2379
0
  state->parse_state = copy;
2380
2381
  // dynamic_cast, static_cast, const_cast, reinterpret_cast.
2382
  //
2383
  // <expression> ::= (dc | sc | cc | rc) <type> <expression>
2384
0
  if (ParseCharClass(state, "dscr") && ParseOneCharToken(state, 'c') &&
2385
0
      ParseType(state) && ParseExpression(state)) {
2386
0
    return true;
2387
0
  }
2388
0
  state->parse_state = copy;
2389
2390
  // Parse the conversion expressions jointly to avoid re-parsing the <type> in
2391
  // their common prefix.  Parsed as:
2392
  // <expression> ::= cv <type> <conversion-args>
2393
  // <conversion-args> ::= _ <expression>* E
2394
  //                   ::= <expression>
2395
  //
2396
  // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
2397
  // also needs to accept "cv <type>" in other contexts.
2398
0
  if (ParseTwoCharToken(state, "cv")) {
2399
0
    if (ParseType(state)) {
2400
0
      ParseState copy2 = state->parse_state;
2401
0
      if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
2402
0
          ParseOneCharToken(state, 'E')) {
2403
0
        return true;
2404
0
      }
2405
0
      state->parse_state = copy2;
2406
0
      if (ParseExpression(state)) {
2407
0
        return true;
2408
0
      }
2409
0
    }
2410
0
  } else {
2411
    // Parse unary, binary, and ternary operator expressions jointly, taking
2412
    // care not to re-parse subexpressions repeatedly. Parse like:
2413
    //   <expression> ::= <operator-name> <expression>
2414
    //                    [<one-to-two-expressions>]
2415
    //   <one-to-two-expressions> ::= <expression> [<expression>]
2416
0
    int arity = -1;
2417
0
    if (ParseOperatorName(state, &arity) &&
2418
0
        arity > 0 &&  // 0 arity => disabled.
2419
0
        (arity < 3 || ParseExpression(state)) &&
2420
0
        (arity < 2 || ParseExpression(state)) &&
2421
0
        (arity < 1 || ParseExpression(state))) {
2422
0
      return true;
2423
0
    }
2424
0
  }
2425
0
  state->parse_state = copy;
2426
2427
  // typeid(type)
2428
0
  if (ParseTwoCharToken(state, "ti") && ParseType(state)) {
2429
0
    return true;
2430
0
  }
2431
0
  state->parse_state = copy;
2432
2433
  // typeid(expression)
2434
0
  if (ParseTwoCharToken(state, "te") && ParseExpression(state)) {
2435
0
    return true;
2436
0
  }
2437
0
  state->parse_state = copy;
2438
2439
  // sizeof type
2440
0
  if (ParseTwoCharToken(state, "st") && ParseType(state)) {
2441
0
    return true;
2442
0
  }
2443
0
  state->parse_state = copy;
2444
2445
  // alignof(type)
2446
0
  if (ParseTwoCharToken(state, "at") && ParseType(state)) {
2447
0
    return true;
2448
0
  }
2449
0
  state->parse_state = copy;
2450
2451
  // alignof(expression), a GNU extension
2452
0
  if (ParseTwoCharToken(state, "az") && ParseExpression(state)) {
2453
0
    return true;
2454
0
  }
2455
0
  state->parse_state = copy;
2456
2457
  // noexcept(expression) appearing as an expression in a dependent signature
2458
0
  if (ParseTwoCharToken(state, "nx") && ParseExpression(state)) {
2459
0
    return true;
2460
0
  }
2461
0
  state->parse_state = copy;
2462
2463
  // sizeof...(pack)
2464
  //
2465
  // <expression> ::= sZ <template-param>
2466
  //              ::= sZ <function-param>
2467
0
  if (ParseTwoCharToken(state, "sZ") &&
2468
0
      (ParseFunctionParam(state) || ParseTemplateParam(state))) {
2469
0
    return true;
2470
0
  }
2471
0
  state->parse_state = copy;
2472
2473
  // sizeof...(pack) captured from an alias template
2474
  //
2475
  // <expression> ::= sP <template-arg>* E
2476
0
  if (ParseTwoCharToken(state, "sP") && ZeroOrMore(ParseTemplateArg, state) &&
2477
0
      ParseOneCharToken(state, 'E')) {
2478
0
    return true;
2479
0
  }
2480
0
  state->parse_state = copy;
2481
2482
  // Unary folds (... op pack) and (pack op ...).
2483
  //
2484
  // <expression> ::= fl <binary operator-name> <expression>
2485
  //              ::= fr <binary operator-name> <expression>
2486
0
  if ((ParseTwoCharToken(state, "fl") || ParseTwoCharToken(state, "fr")) &&
2487
0
      ParseOperatorName(state, nullptr) && ParseExpression(state)) {
2488
0
    return true;
2489
0
  }
2490
0
  state->parse_state = copy;
2491
2492
  // Binary folds (init op ... op pack) and (pack op ... op init).
2493
  //
2494
  // <expression> ::= fL <binary operator-name> <expression> <expression>
2495
  //              ::= fR <binary operator-name> <expression> <expression>
2496
0
  if ((ParseTwoCharToken(state, "fL") || ParseTwoCharToken(state, "fR")) &&
2497
0
      ParseOperatorName(state, nullptr) && ParseExpression(state) &&
2498
0
      ParseExpression(state)) {
2499
0
    return true;
2500
0
  }
2501
0
  state->parse_state = copy;
2502
2503
  // tw <expression>: throw e
2504
0
  if (ParseTwoCharToken(state, "tw") && ParseExpression(state)) {
2505
0
    return true;
2506
0
  }
2507
0
  state->parse_state = copy;
2508
2509
  // tr: throw (rethrows an exception from the handler that caught it)
2510
0
  if (ParseTwoCharToken(state, "tr")) return true;
2511
2512
  // Object and pointer member access expressions.
2513
  //
2514
  // <expression> ::= (dt | pt) <expression> <unresolved-name>
2515
0
  if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
2516
0
      ParseExpression(state) && ParseUnresolvedName(state)) {
2517
0
    return true;
2518
0
  }
2519
0
  state->parse_state = copy;
2520
2521
  // Pointer-to-member access expressions.  This parses the same as a binary
2522
  // operator, but it's implemented separately because "ds" shouldn't be
2523
  // accepted in other contexts that parse an operator name.
2524
0
  if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
2525
0
      ParseExpression(state)) {
2526
0
    return true;
2527
0
  }
2528
0
  state->parse_state = copy;
2529
2530
  // Parameter pack expansion
2531
0
  if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
2532
0
    return true;
2533
0
  }
2534
0
  state->parse_state = copy;
2535
2536
  // Vendor extended expressions
2537
0
  if (ParseOneCharToken(state, 'u') && ParseSourceName(state) &&
2538
0
      ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) {
2539
0
    return true;
2540
0
  }
2541
0
  state->parse_state = copy;
2542
2543
  // <expression> ::= rq <requirement>+ E
2544
  //
2545
  // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
2546
0
  if (ParseTwoCharToken(state, "rq") && OneOrMore(ParseRequirement, state) &&
2547
0
      ParseOneCharToken(state, 'E')) {
2548
0
    return true;
2549
0
  }
2550
0
  state->parse_state = copy;
2551
2552
  // <expression> ::= rQ <bare-function-type> _ <requirement>+ E
2553
  //
2554
  // https://github.com/itanium-cxx-abi/cxx-abi/issues/24
2555
0
  if (ParseTwoCharToken(state, "rQ") && ParseBareFunctionType(state) &&
2556
0
      ParseOneCharToken(state, '_') && OneOrMore(ParseRequirement, state) &&
2557
0
      ParseOneCharToken(state, 'E')) {
2558
0
    return true;
2559
0
  }
2560
0
  state->parse_state = copy;
2561
2562
0
  return ParseUnresolvedName(state);
2563
0
}
2564
2565
// <initializer> ::= pi <expression>* E
2566
//               ::= il <braced-expression>* E
2567
//
2568
// The il ... E form is not in the ABI spec but is seen in practice for
2569
// braced-init-lists in new-expressions, which are standard syntax from C++11
2570
// on.
2571
0
static bool ParseInitializer(State *state) {
2572
0
  ComplexityGuard guard(state);
2573
0
  if (guard.IsTooComplex()) return false;
2574
0
  ParseState copy = state->parse_state;
2575
2576
0
  if (ParseTwoCharToken(state, "pi") && ZeroOrMore(ParseExpression, state) &&
2577
0
      ParseOneCharToken(state, 'E')) {
2578
0
    return true;
2579
0
  }
2580
0
  state->parse_state = copy;
2581
2582
0
  if (ParseTwoCharToken(state, "il") &&
2583
0
      ZeroOrMore(ParseBracedExpression, state) &&
2584
0
      ParseOneCharToken(state, 'E')) {
2585
0
    return true;
2586
0
  }
2587
0
  state->parse_state = copy;
2588
0
  return false;
2589
0
}
2590
2591
// <expr-primary> ::= L <type> <(value) number> E
2592
//                ::= L <type> <(value) float> E
2593
//                ::= L <mangled-name> E
2594
//                // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
2595
//                ::= LZ <encoding> E
2596
//
2597
// Warning, subtle: the "bug" LZ production above is ambiguous with the first
2598
// production where <type> starts with <local-name>, which can lead to
2599
// exponential backtracking in two scenarios:
2600
//
2601
// - When whatever follows the E in the <local-name> in the first production is
2602
//   not a name, we backtrack the whole <encoding> and re-parse the whole thing.
2603
//
2604
// - When whatever follows the <local-name> in the first production is not a
2605
//   number and this <expr-primary> may be followed by a name, we backtrack the
2606
//   <name> and re-parse it.
2607
//
2608
// Moreover this ambiguity isn't always resolved -- for example, the following
2609
// has two different parses:
2610
//
2611
//   _ZaaILZ4aoeuE1x1EvE
2612
//   => operator&&<aoeu, x, E, void>
2613
//   => operator&&<(aoeu::x)(1), void>
2614
//
2615
// To resolve this, we just do what GCC's demangler does, and refuse to parse
2616
// casts to <local-name> types.
2617
0
static bool ParseExprPrimary(State *state) {
2618
0
  ComplexityGuard guard(state);
2619
0
  if (guard.IsTooComplex()) return false;
2620
0
  ParseState copy = state->parse_state;
2621
2622
  // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
2623
  // or fail, no backtracking.
2624
0
  if (ParseTwoCharToken(state, "LZ")) {
2625
0
    if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
2626
0
      return true;
2627
0
    }
2628
2629
0
    state->parse_state = copy;
2630
0
    return false;
2631
0
  }
2632
2633
0
  if (ParseOneCharToken(state, 'L')) {
2634
    // There are two special cases in which a literal may or must contain a type
2635
    // without a value.  The first is that both LDnE and LDn0E are valid
2636
    // encodings of nullptr, used in different situations.  Recognize LDnE here,
2637
    // leaving LDn0E to be recognized by the general logic afterward.
2638
0
    if (ParseThreeCharToken(state, "DnE")) return true;
2639
2640
    // The second special case is a string literal, currently mangled in C++98
2641
    // style as LA<length + 1>_KcE.  This is inadequate to support C++11 and
2642
    // later versions, and the discussion of this problem has not converged.
2643
    //
2644
    // https://github.com/itanium-cxx-abi/cxx-abi/issues/64
2645
    //
2646
    // For now the bare-type mangling is what's used in practice, so we
2647
    // recognize this form and only this form if an array type appears here.
2648
    // Someday we'll probably have to accept a new form of value mangling in
2649
    // LA...E constructs.  (Note also that C++20 allows a wide range of
2650
    // class-type objects as template arguments, so someday their values will be
2651
    // mangled and we'll have to recognize them here too.)
2652
0
    if (RemainingInput(state)[0] == 'A' /* an array type follows */) {
2653
0
      if (ParseType(state) && ParseOneCharToken(state, 'E')) return true;
2654
0
      state->parse_state = copy;
2655
0
      return false;
2656
0
    }
2657
2658
    // The merged cast production.
2659
0
    if (ParseType(state) && ParseExprCastValueAndTrailingE(state)) {
2660
0
      return true;
2661
0
    }
2662
0
  }
2663
0
  state->parse_state = copy;
2664
2665
0
  if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
2666
0
      ParseOneCharToken(state, 'E')) {
2667
0
    return true;
2668
0
  }
2669
0
  state->parse_state = copy;
2670
2671
0
  return false;
2672
0
}
2673
2674
// <number> or <float>, followed by 'E', as described above ParseExprPrimary.
2675
0
static bool ParseExprCastValueAndTrailingE(State *state) {
2676
0
  ComplexityGuard guard(state);
2677
0
  if (guard.IsTooComplex()) return false;
2678
  // We have to be able to backtrack after accepting a number because we could
2679
  // have e.g. "7fffE", which will accept "7" as a number but then fail to find
2680
  // the 'E'.
2681
0
  ParseState copy = state->parse_state;
2682
0
  if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
2683
0
    return true;
2684
0
  }
2685
0
  state->parse_state = copy;
2686
2687
0
  if (ParseFloatNumber(state)) {
2688
    // <float> for ordinary floating-point types
2689
0
    if (ParseOneCharToken(state, 'E')) return true;
2690
2691
    // <float> _ <float> for complex floating-point types
2692
0
    if (ParseOneCharToken(state, '_') && ParseFloatNumber(state) &&
2693
0
        ParseOneCharToken(state, 'E')) {
2694
0
      return true;
2695
0
    }
2696
0
  }
2697
0
  state->parse_state = copy;
2698
2699
0
  return false;
2700
0
}
2701
2702
// Parses `Q <requires-clause expr>`.
2703
// If parsing fails, applies backtracking to `state`.
2704
//
2705
// This function covers two symbols instead of one for convenience,
2706
// because in LLVM's Itanium ABI mangling grammar, <requires-clause expr>
2707
// always appears after Q.
2708
//
2709
// Does not emit the parsed `requires` clause to simplify the implementation.
2710
// In other words, these two functions' mangled names will demangle identically:
2711
//
2712
// template <typename T>
2713
// int foo(T) requires IsIntegral<T>;
2714
//
2715
// vs.
2716
//
2717
// template <typename T>
2718
// int foo(T);
2719
0
static bool ParseQRequiresClauseExpr(State *state) {
2720
0
  ComplexityGuard guard(state);
2721
0
  if (guard.IsTooComplex()) return false;
2722
0
  ParseState copy = state->parse_state;
2723
0
  DisableAppend(state);
2724
2725
  // <requires-clause expr> is just an <expression>: http://shortn/_9E1Ul0rIM8
2726
0
  if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) {
2727
0
    RestoreAppend(state, copy.append);
2728
0
    return true;
2729
0
  }
2730
2731
  // also restores append
2732
0
  state->parse_state = copy;
2733
0
  return false;
2734
0
}
2735
2736
// <requirement> ::= X <expression> [N] [R <type-constraint>]
2737
// <requirement> ::= T <type>
2738
// <requirement> ::= Q <constraint-expression>
2739
//
2740
// <constraint-expression> ::= <expression>
2741
//
2742
// https://github.com/itanium-cxx-abi/cxx-abi/issues/24
2743
0
static bool ParseRequirement(State *state) {
2744
0
  ComplexityGuard guard(state);
2745
0
  if (guard.IsTooComplex()) return false;
2746
2747
0
  ParseState copy = state->parse_state;
2748
2749
0
  if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
2750
0
      Optional(ParseOneCharToken(state, 'N')) &&
2751
      // This logic backtracks cleanly if we eat an R but a valid type doesn't
2752
      // follow it.
2753
0
      (!ParseOneCharToken(state, 'R') || ParseTypeConstraint(state))) {
2754
0
    return true;
2755
0
  }
2756
0
  state->parse_state = copy;
2757
2758
0
  if (ParseOneCharToken(state, 'T') && ParseType(state)) return true;
2759
0
  state->parse_state = copy;
2760
2761
0
  if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) return true;
2762
0
  state->parse_state = copy;
2763
2764
0
  return false;
2765
0
}
2766
2767
// <type-constraint> ::= <name>
2768
0
static bool ParseTypeConstraint(State *state) {
2769
0
  return ParseName(state);
2770
0
}
2771
2772
// <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2773
//              ::= Z <(function) encoding> E s [<discriminator>]
2774
//              ::= Z <(function) encoding> E d [<(parameter) number>] _ <name>
2775
//
2776
// Parsing a common prefix of these two productions together avoids an
2777
// exponential blowup of backtracking.  Parse like:
2778
//   <local-name> := Z <encoding> E <local-name-suffix>
2779
//   <local-name-suffix> ::= s [<discriminator>]
2780
//                       ::= d [<(parameter) number>] _ <name>
2781
//                       ::= <name> [<discriminator>]
2782
2783
0
static bool ParseLocalNameSuffix(State *state) {
2784
0
  ComplexityGuard guard(state);
2785
0
  if (guard.IsTooComplex()) return false;
2786
0
  ParseState copy = state->parse_state;
2787
2788
  // <local-name-suffix> ::= d [<(parameter) number>] _ <name>
2789
0
  if (ParseOneCharToken(state, 'd') &&
2790
0
      (IsDigit(RemainingInput(state)[0]) || RemainingInput(state)[0] == '_')) {
2791
0
    int number = -1;
2792
0
    Optional(ParseNumber(state, &number));
2793
0
    if (number < -1 || number > 2147483645) {
2794
      // Work around overflow cases.  We do not expect these outside of a fuzzer
2795
      // or other source of adversarial input.  If we do detect overflow here,
2796
      // we'll print {default arg#1}.
2797
0
      number = -1;
2798
0
    }
2799
0
    number += 2;
2800
2801
    // The ::{default arg#1}:: infix must be rendered before the lambda itself,
2802
    // so print this before parsing the rest of the <local-name-suffix>.
2803
0
    MaybeAppend(state, "::{default arg#");
2804
0
    MaybeAppendDecimal(state, number);
2805
0
    MaybeAppend(state, "}::");
2806
0
    if (ParseOneCharToken(state, '_') && ParseName(state)) return true;
2807
2808
    // On late parse failure, roll back not only the input but also the output,
2809
    // whose trailing NUL was overwritten.
2810
0
    state->parse_state = copy;
2811
0
    if (state->parse_state.append &&
2812
0
        state->parse_state.out_cur_idx < state->out_end_idx) {
2813
0
      state->out[state->parse_state.out_cur_idx] = '\0';
2814
0
    }
2815
0
    return false;
2816
0
  }
2817
0
  state->parse_state = copy;
2818
2819
  // <local-name-suffix> ::= <name> [<discriminator>]
2820
0
  if (MaybeAppend(state, "::") && ParseName(state) &&
2821
0
      Optional(ParseDiscriminator(state))) {
2822
0
    return true;
2823
0
  }
2824
0
  state->parse_state = copy;
2825
0
  if (state->parse_state.append &&
2826
0
      state->parse_state.out_cur_idx < state->out_end_idx) {
2827
0
    state->out[state->parse_state.out_cur_idx] = '\0';
2828
0
  }
2829
2830
  // <local-name-suffix> ::= s [<discriminator>]
2831
0
  return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
2832
0
}
2833
2834
0
static bool ParseLocalName(State *state) {
2835
0
  ComplexityGuard guard(state);
2836
0
  if (guard.IsTooComplex()) return false;
2837
0
  ParseState copy = state->parse_state;
2838
0
  if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
2839
0
      ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
2840
0
    return true;
2841
0
  }
2842
0
  state->parse_state = copy;
2843
0
  return false;
2844
0
}
2845
2846
// <discriminator> := _ <digit>
2847
//                 := __ <number (>= 10)> _
2848
0
static bool ParseDiscriminator(State *state) {
2849
0
  ComplexityGuard guard(state);
2850
0
  if (guard.IsTooComplex()) return false;
2851
0
  ParseState copy = state->parse_state;
2852
2853
  // Both forms start with _ so parse that first.
2854
0
  if (!ParseOneCharToken(state, '_')) return false;
2855
2856
  // <digit>
2857
0
  if (ParseDigit(state, nullptr)) return true;
2858
2859
  // _ <number> _
2860
0
  if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) &&
2861
0
      ParseOneCharToken(state, '_')) {
2862
0
    return true;
2863
0
  }
2864
0
  state->parse_state = copy;
2865
0
  return false;
2866
0
}
2867
2868
// <substitution> ::= S_
2869
//                ::= S <seq-id> _
2870
//                ::= St, etc.
2871
//
2872
// "St" is special in that it's not valid as a standalone name, and it *is*
2873
// allowed to precede a name without being wrapped in "N...E".  This means that
2874
// if we accept it on its own, we can accept "St1a" and try to parse
2875
// template-args, then fail and backtrack, accept "St" on its own, then "1a" as
2876
// an unqualified name and re-parse the same template-args.  To block this
2877
// exponential backtracking, we disable it with 'accept_std=false' in
2878
// problematic contexts.
2879
0
static bool ParseSubstitution(State *state, bool accept_std) {
2880
0
  ComplexityGuard guard(state);
2881
0
  if (guard.IsTooComplex()) return false;
2882
0
  if (ParseTwoCharToken(state, "S_")) {
2883
0
    MaybeAppend(state, "?");  // We don't support substitutions.
2884
0
    return true;
2885
0
  }
2886
2887
0
  ParseState copy = state->parse_state;
2888
0
  if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
2889
0
      ParseOneCharToken(state, '_')) {
2890
0
    MaybeAppend(state, "?");  // We don't support substitutions.
2891
0
    return true;
2892
0
  }
2893
0
  state->parse_state = copy;
2894
2895
  // Expand abbreviations like "St" => "std".
2896
0
  if (ParseOneCharToken(state, 'S')) {
2897
0
    const AbbrevPair *p;
2898
0
    for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
2899
0
      if (RemainingInput(state)[0] == p->abbrev[1] &&
2900
0
          (accept_std || p->abbrev[1] != 't')) {
2901
0
        MaybeAppend(state, "std");
2902
0
        if (p->real_name[0] != '\0') {
2903
0
          MaybeAppend(state, "::");
2904
0
          MaybeAppend(state, p->real_name);
2905
0
        }
2906
0
        ++state->parse_state.mangled_idx;
2907
0
        UpdateHighWaterMark(state);
2908
0
        return true;
2909
0
      }
2910
0
    }
2911
0
  }
2912
0
  state->parse_state = copy;
2913
0
  return false;
2914
0
}
2915
2916
// Parse <mangled-name>, optionally followed by either a function-clone suffix
2917
// or version suffix.  Returns true only if all of "mangled_cur" was consumed.
2918
0
static bool ParseTopLevelMangledName(State *state) {
2919
0
  ComplexityGuard guard(state);
2920
0
  if (guard.IsTooComplex()) return false;
2921
0
  if (ParseMangledName(state)) {
2922
0
    if (RemainingInput(state)[0] != '\0') {
2923
      // Drop trailing function clone suffix, if any.
2924
0
      if (RemainingInput(state)[0] == '.') {
2925
0
        return true;
2926
0
      }
2927
      // Append trailing version suffix if any.
2928
      // ex. _Z3foo@@GLIBCXX_3.4
2929
0
      if (RemainingInput(state)[0] == '@') {
2930
0
        MaybeAppend(state, RemainingInput(state));
2931
0
        return true;
2932
0
      }
2933
0
      ReportHighWaterMark(state);
2934
0
      return false;  // Unconsumed suffix.
2935
0
    }
2936
0
    return true;
2937
0
  }
2938
2939
0
  ReportHighWaterMark(state);
2940
0
  return false;
2941
0
}
2942
2943
0
static bool Overflowed(const State *state) {
2944
0
  return state->parse_state.out_cur_idx >= state->out_end_idx;
2945
0
}
2946
2947
// The demangler entry point.
2948
0
bool Demangle(const char* mangled, char* out, size_t out_size) {
2949
0
  if (mangled[0] == '_' && mangled[1] == 'R') {
2950
0
    return DemangleRustSymbolEncoding(mangled, out, out_size);
2951
0
  }
2952
2953
0
  State state;
2954
0
  InitState(&state, mangled, out, out_size);
2955
0
  return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
2956
0
         state.parse_state.out_cur_idx > 0;
2957
0
}
2958
2959
0
std::string DemangleString(const char* mangled) {
2960
0
  std::string out;
2961
0
  int status = 0;
2962
0
  char* demangled = nullptr;
2963
0
#ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE
2964
0
  demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status);
2965
0
#endif
2966
0
  if (status == 0 && demangled != nullptr) {
2967
0
    out.append(demangled);
2968
0
    free(demangled);
2969
0
  } else {
2970
0
    out.append(mangled);
2971
0
  }
2972
0
  return out;
2973
0
}
2974
2975
}  // namespace debugging_internal
2976
ABSL_NAMESPACE_END
2977
}  // namespace absl