1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: Satoru Takabayashi
32 // For reference check out:
33 // http://www.codesourcery.com/public/cxx-abi/abi.html#mangling
35 // Note that we only have partial C++0x support yet.
37 #include <stdio.h> // for NULL
38 #include "utilities.h"
41 #if defined(OS_WINDOWS)
45 _START_GOOGLE_NAMESPACE_
47 #if !defined(OS_WINDOWS)
50 const char *real_name;
53 // List of operators from Itanium C++ ABI.
54 static const AbbrevPair kOperatorList[] = {
107 // List of builtin types from Itanium C++ ABI.
108 static const AbbrevPair kBuiltinTypeList[] = {
113 { "a", "signed char" },
114 { "h", "unsigned char" },
116 { "t", "unsigned short" },
118 { "j", "unsigned int" },
120 { "m", "unsigned long" },
121 { "x", "long long" },
122 { "y", "unsigned long long" },
124 { "o", "unsigned __int128" },
127 { "e", "long double" },
128 { "g", "__float128" },
133 // List of substitutions Itanium C++ ABI.
134 static const AbbrevPair kSubstitutionList[] = {
136 { "Sa", "allocator" },
137 { "Sb", "basic_string" },
138 // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
140 // std::basic_istream<char, std::char_traits<char> >
142 // std::basic_ostream<char, std::char_traits<char> >
144 // std::basic_iostream<char, std::char_traits<char> >
145 { "Sd", "iostream" },
149 // State needed for demangling.
151 const char *mangled_cur; // Cursor of mangled name.
152 char *out_cur; // Cursor of output string.
153 const char *out_begin; // Beginning of output string.
154 const char *out_end; // End of output string.
155 const char *prev_name; // For constructors/destructors.
156 int prev_name_length; // For constructors/destructors.
157 short nest_level; // For nested names.
158 bool append; // Append flag.
159 bool overflowed; // True if output gets overflowed.
162 // We don't use strlen() in libc since it's not guaranteed to be async
164 static size_t StrLen(const char *str) {
166 while (*str != '\0') {
173 // Returns true if "str" has at least "n" characters remaining.
174 static bool AtLeastNumCharsRemaining(const char *str, int n) {
175 for (int i = 0; i < n; ++i) {
176 if (str[i] == '\0') {
183 // Returns true if "str" has "prefix" as a prefix.
184 static bool StrPrefix(const char *str, const char *prefix) {
186 while (str[i] != '\0' && prefix[i] != '\0' &&
187 str[i] == prefix[i]) {
190 return prefix[i] == '\0'; // Consumed everything in "prefix".
193 static void InitState(State *state, const char *mangled,
194 char *out, int out_size) {
195 state->mangled_cur = mangled;
196 state->out_cur = out;
197 state->out_begin = out;
198 state->out_end = out + out_size;
199 state->prev_name = NULL;
200 state->prev_name_length = -1;
201 state->nest_level = -1;
202 state->append = true;
203 state->overflowed = false;
206 // Returns true and advances "mangled_cur" if we find "one_char_token"
207 // at "mangled_cur" position. It is assumed that "one_char_token" does
209 static bool ParseOneCharToken(State *state, const char one_char_token) {
210 if (state->mangled_cur[0] == one_char_token) {
211 ++state->mangled_cur;
217 // Returns true and advances "mangled_cur" if we find "two_char_token"
218 // at "mangled_cur" position. It is assumed that "two_char_token" does
220 static bool ParseTwoCharToken(State *state, const char *two_char_token) {
221 if (state->mangled_cur[0] == two_char_token[0] &&
222 state->mangled_cur[1] == two_char_token[1]) {
223 state->mangled_cur += 2;
229 // Returns true and advances "mangled_cur" if we find any character in
230 // "char_class" at "mangled_cur" position.
231 static bool ParseCharClass(State *state, const char *char_class) {
232 const char *p = char_class;
233 for (; *p != '\0'; ++p) {
234 if (state->mangled_cur[0] == *p) {
235 ++state->mangled_cur;
242 // This function is used for handling an optional non-terminal.
243 static bool Optional(bool) {
247 // This function is used for handling <non-terminal>+ syntax.
248 typedef bool (*ParseFunc)(State *);
249 static bool OneOrMore(ParseFunc parse_func, State *state) {
250 if (parse_func(state)) {
251 while (parse_func(state)) {
258 // This function is used for handling <non-terminal>* syntax. The function
259 // always returns true and must be followed by a termination token or a
260 // terminating sequence not handled by parse_func (e.g.
261 // ParseOneCharToken(state, 'E')).
262 static bool ZeroOrMore(ParseFunc parse_func, State *state) {
263 while (parse_func(state)) {
268 // Append "str" at "out_cur". If there is an overflow, "overflowed"
269 // is set to true for later use. The output string is ensured to
270 // always terminate with '\0' as long as there is no overflow.
271 static void Append(State *state, const char * const str, const int length) {
273 for (i = 0; i < length; ++i) {
274 if (state->out_cur + 1 < state->out_end) { // +1 for '\0'
275 *state->out_cur = str[i];
278 state->overflowed = true;
282 if (!state->overflowed) {
283 *state->out_cur = '\0'; // Terminate it with '\0'
287 // We don't use equivalents in libc to avoid locale issues.
288 static bool IsLower(char c) {
289 return c >= 'a' && c <= 'z';
292 static bool IsAlpha(char c) {
293 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
296 static bool IsDigit(char c) {
297 return c >= '0' && c <= '9';
300 // Returns true if "str" is a function clone suffix. These suffixes are used
301 // by GCC 4.5.x and later versions to indicate functions which have been
302 // cloned during optimization. We treat any sequence (.<alpha>+.<digit>+)+ as
303 // a function clone suffix.
304 static bool IsFunctionCloneSuffix(const char *str) {
306 while (str[i] != '\0') {
307 // Consume a single .<alpha>+.<digit>+ sequence.
308 if (str[i] != '.' || !IsAlpha(str[i + 1])) {
312 while (IsAlpha(str[i])) {
315 if (str[i] != '.' || !IsDigit(str[i + 1])) {
319 while (IsDigit(str[i])) {
323 return true; // Consumed everything in "str".
326 // Append "str" with some tweaks, iff "append" state is true.
327 // Returns true so that it can be placed in "if" conditions.
328 static void MaybeAppendWithLength(State *state, const char * const str,
330 if (state->append && length > 0) {
331 // Append a space if the output buffer ends with '<' and "str"
332 // starts with '<' to avoid <<<.
333 if (str[0] == '<' && state->out_begin < state->out_cur &&
334 state->out_cur[-1] == '<') {
335 Append(state, " ", 1);
337 // Remember the last identifier name for ctors/dtors.
338 if (IsAlpha(str[0]) || str[0] == '_') {
339 state->prev_name = state->out_cur;
340 state->prev_name_length = length;
342 Append(state, str, length);
346 // A convenient wrapper arount MaybeAppendWithLength().
347 static bool MaybeAppend(State *state, const char * const str) {
349 int length = StrLen(str);
350 MaybeAppendWithLength(state, str, length);
355 // This function is used for handling nested names.
356 static bool EnterNestedName(State *state) {
357 state->nest_level = 0;
361 // This function is used for handling nested names.
362 static bool LeaveNestedName(State *state, short prev_value) {
363 state->nest_level = prev_value;
367 // Disable the append mode not to print function parameters, etc.
368 static bool DisableAppend(State *state) {
369 state->append = false;
373 // Restore the append mode to the previous state.
374 static bool RestoreAppend(State *state, bool prev_value) {
375 state->append = prev_value;
379 // Increase the nest level for nested names.
380 static void MaybeIncreaseNestLevel(State *state) {
381 if (state->nest_level > -1) {
386 // Appends :: for nested names if necessary.
387 static void MaybeAppendSeparator(State *state) {
388 if (state->nest_level >= 1) {
389 MaybeAppend(state, "::");
393 // Cancel the last separator if necessary.
394 static void MaybeCancelLastSeparator(State *state) {
395 if (state->nest_level >= 1 && state->append &&
396 state->out_begin <= state->out_cur - 2) {
398 *state->out_cur = '\0';
402 // Returns true if the identifier of the given length pointed to by
403 // "mangled_cur" is anonymous namespace.
404 static bool IdentifierIsAnonymousNamespace(State *state, int length) {
405 static const char anon_prefix[] = "_GLOBAL__N_";
406 return (length > (int)sizeof(anon_prefix) - 1 && // Should be longer.
407 StrPrefix(state->mangled_cur, anon_prefix));
410 // Forward declarations of our parsing functions.
411 static bool ParseMangledName(State *state);
412 static bool ParseEncoding(State *state);
413 static bool ParseName(State *state);
414 static bool ParseUnscopedName(State *state);
415 static bool ParseUnscopedTemplateName(State *state);
416 static bool ParseNestedName(State *state);
417 static bool ParsePrefix(State *state);
418 static bool ParseUnqualifiedName(State *state);
419 static bool ParseSourceName(State *state);
420 static bool ParseLocalSourceName(State *state);
421 static bool ParseNumber(State *state, int *number_out);
422 static bool ParseFloatNumber(State *state);
423 static bool ParseSeqId(State *state);
424 static bool ParseIdentifier(State *state, int length);
425 static bool ParseOperatorName(State *state);
426 static bool ParseSpecialName(State *state);
427 static bool ParseCallOffset(State *state);
428 static bool ParseNVOffset(State *state);
429 static bool ParseVOffset(State *state);
430 static bool ParseCtorDtorName(State *state);
431 static bool ParseType(State *state);
432 static bool ParseCVQualifiers(State *state);
433 static bool ParseBuiltinType(State *state);
434 static bool ParseFunctionType(State *state);
435 static bool ParseBareFunctionType(State *state);
436 static bool ParseClassEnumType(State *state);
437 static bool ParseArrayType(State *state);
438 static bool ParsePointerToMemberType(State *state);
439 static bool ParseTemplateParam(State *state);
440 static bool ParseTemplateTemplateParam(State *state);
441 static bool ParseTemplateArgs(State *state);
442 static bool ParseTemplateArg(State *state);
443 static bool ParseExpression(State *state);
444 static bool ParseExprPrimary(State *state);
445 static bool ParseLocalName(State *state);
446 static bool ParseDiscriminator(State *state);
447 static bool ParseSubstitution(State *state);
449 // Implementation note: the following code is a straightforward
450 // translation of the Itanium C++ ABI defined in BNF with a couple of
453 // - Support GNU extensions not defined in the Itanium C++ ABI
454 // - <prefix> and <template-prefix> are combined to avoid infinite loop
455 // - Reorder patterns to shorten the code
456 // - Reorder patterns to give greedier functions precedence
457 // We'll mark "Less greedy than" for these cases in the code
459 // Each parsing function changes the state and returns true on
460 // success. Otherwise, don't change the state and returns false. To
461 // ensure that the state isn't changed in the latter case, we save the
462 // original state before we call more than one parsing functions
463 // consecutively with &&, and restore the state if unsuccessful. See
464 // ParseEncoding() as an example of this convention. We follow the
465 // convention throughout the code.
467 // Originally we tried to do demangling without following the full ABI
468 // syntax but it turned out we needed to follow the full syntax to
469 // parse complicated cases like nested template arguments. Note that
470 // implementing a full-fledged demangler isn't trivial (libiberty's
471 // cp-demangle.c has +4300 lines).
473 // Note that (foo) in <(foo) ...> is a modifier to be ignored.
477 // <http://www.codesourcery.com/cxx-abi/abi.html#mangling>
479 // <mangled-name> ::= _Z <encoding>
480 static bool ParseMangledName(State *state) {
481 return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
484 // <encoding> ::= <(function) name> <bare-function-type>
486 // ::= <special-name>
487 static bool ParseEncoding(State *state) {
489 if (ParseName(state) && ParseBareFunctionType(state)) {
494 if (ParseName(state) || ParseSpecialName(state)) {
500 // <name> ::= <nested-name>
501 // ::= <unscoped-template-name> <template-args>
502 // ::= <unscoped-name>
504 static bool ParseName(State *state) {
505 if (ParseNestedName(state) || ParseLocalName(state)) {
510 if (ParseUnscopedTemplateName(state) &&
511 ParseTemplateArgs(state)) {
516 // Less greedy than <unscoped-template-name> <template-args>.
517 if (ParseUnscopedName(state)) {
523 // <unscoped-name> ::= <unqualified-name>
524 // ::= St <unqualified-name>
525 static bool ParseUnscopedName(State *state) {
526 if (ParseUnqualifiedName(state)) {
531 if (ParseTwoCharToken(state, "St") &&
532 MaybeAppend(state, "std::") &&
533 ParseUnqualifiedName(state)) {
540 // <unscoped-template-name> ::= <unscoped-name>
541 // ::= <substitution>
542 static bool ParseUnscopedTemplateName(State *state) {
543 return ParseUnscopedName(state) || ParseSubstitution(state);
546 // <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
547 // ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
548 static bool ParseNestedName(State *state) {
550 if (ParseOneCharToken(state, 'N') &&
551 EnterNestedName(state) &&
552 Optional(ParseCVQualifiers(state)) &&
553 ParsePrefix(state) &&
554 LeaveNestedName(state, copy.nest_level) &&
555 ParseOneCharToken(state, 'E')) {
562 // This part is tricky. If we literally translate them to code, we'll
563 // end up infinite loop. Hence we merge them to avoid the case.
565 // <prefix> ::= <prefix> <unqualified-name>
566 // ::= <template-prefix> <template-args>
567 // ::= <template-param>
568 // ::= <substitution>
570 // <template-prefix> ::= <prefix> <(template) unqualified-name>
571 // ::= <template-param>
572 // ::= <substitution>
573 static bool ParsePrefix(State *state) {
574 bool has_something = false;
576 MaybeAppendSeparator(state);
577 if (ParseTemplateParam(state) ||
578 ParseSubstitution(state) ||
579 ParseUnscopedName(state)) {
580 has_something = true;
581 MaybeIncreaseNestLevel(state);
584 MaybeCancelLastSeparator(state);
585 if (has_something && ParseTemplateArgs(state)) {
586 return ParsePrefix(state);
594 // <unqualified-name> ::= <operator-name>
595 // ::= <ctor-dtor-name>
597 // ::= <local-source-name>
598 static bool ParseUnqualifiedName(State *state) {
599 return (ParseOperatorName(state) ||
600 ParseCtorDtorName(state) ||
601 ParseSourceName(state) ||
602 ParseLocalSourceName(state));
605 // <source-name> ::= <positive length number> <identifier>
606 static bool ParseSourceName(State *state) {
609 if (ParseNumber(state, &length) && ParseIdentifier(state, length)) {
616 // <local-source-name> ::= L <source-name> [<discriminator>]
619 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
620 // http://gcc.gnu.org/viewcvs?view=rev&revision=124467
621 static bool ParseLocalSourceName(State *state) {
623 if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
624 Optional(ParseDiscriminator(state))) {
631 // <number> ::= [n] <non-negative decimal integer>
632 // If "number_out" is non-null, then *number_out is set to the value of the
633 // parsed number on success.
634 static bool ParseNumber(State *state, int *number_out) {
636 if (ParseOneCharToken(state, 'n')) {
639 const char *p = state->mangled_cur;
641 for (;*p != '\0'; ++p) {
643 number = number * 10 + (*p - '0');
648 if (p != state->mangled_cur) { // Conversion succeeded.
649 state->mangled_cur = p;
650 if (number_out != NULL) {
651 *number_out = number * sign;
658 // Floating-point literals are encoded using a fixed-length lowercase
659 // hexadecimal string.
660 static bool ParseFloatNumber(State *state) {
661 const char *p = state->mangled_cur;
662 for (;*p != '\0'; ++p) {
663 if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
667 if (p != state->mangled_cur) { // Conversion succeeded.
668 state->mangled_cur = p;
674 // The <seq-id> is a sequence number in base 36,
675 // using digits and upper case letters
676 static bool ParseSeqId(State *state) {
677 const char *p = state->mangled_cur;
678 for (;*p != '\0'; ++p) {
679 if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
683 if (p != state->mangled_cur) { // Conversion succeeded.
684 state->mangled_cur = p;
690 // <identifier> ::= <unqualified source code identifier> (of given length)
691 static bool ParseIdentifier(State *state, int length) {
693 !AtLeastNumCharsRemaining(state->mangled_cur, length)) {
696 if (IdentifierIsAnonymousNamespace(state, length)) {
697 MaybeAppend(state, "(anonymous namespace)");
699 MaybeAppendWithLength(state, state->mangled_cur, length);
701 state->mangled_cur += length;
705 // <operator-name> ::= nw, and other two letters cases
706 // ::= cv <type> # (cast)
707 // ::= v <digit> <source-name> # vendor extended operator
708 static bool ParseOperatorName(State *state) {
709 if (!AtLeastNumCharsRemaining(state->mangled_cur, 2)) {
712 // First check with "cv" (cast) case.
714 if (ParseTwoCharToken(state, "cv") &&
715 MaybeAppend(state, "operator ") &&
716 EnterNestedName(state) &&
718 LeaveNestedName(state, copy.nest_level)) {
723 // Then vendor extended operators.
724 if (ParseOneCharToken(state, 'v') && ParseCharClass(state, "0123456789") &&
725 ParseSourceName(state)) {
730 // Other operator names should start with a lower alphabet followed
731 // by a lower/upper alphabet.
732 if (!(IsLower(state->mangled_cur[0]) &&
733 IsAlpha(state->mangled_cur[1]))) {
736 // We may want to perform a binary search if we really need speed.
738 for (p = kOperatorList; p->abbrev != NULL; ++p) {
739 if (state->mangled_cur[0] == p->abbrev[0] &&
740 state->mangled_cur[1] == p->abbrev[1]) {
741 MaybeAppend(state, "operator");
742 if (IsLower(*p->real_name)) { // new, delete, etc.
743 MaybeAppend(state, " ");
745 MaybeAppend(state, p->real_name);
746 state->mangled_cur += 2;
753 // <special-name> ::= TV <type>
757 // ::= Tc <call-offset> <call-offset> <(base) encoding>
758 // ::= GV <(object) name>
759 // ::= T <call-offset> <(base) encoding>
761 // ::= TC <type> <(offset) number> _ <(base) type>
766 // ::= Th <call-offset> <(base) encoding>
767 // ::= Tv <call-offset> <(base) encoding>
769 // Note: we don't care much about them since they don't appear in
770 // stack traces. The are special data.
771 static bool ParseSpecialName(State *state) {
773 if (ParseOneCharToken(state, 'T') &&
774 ParseCharClass(state, "VTIS") &&
780 if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
781 ParseCallOffset(state) && ParseEncoding(state)) {
786 if (ParseTwoCharToken(state, "GV") &&
792 if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
793 ParseEncoding(state)) {
799 if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
800 ParseNumber(state, NULL) && ParseOneCharToken(state, '_') &&
801 DisableAppend(state) &&
803 RestoreAppend(state, copy.append);
808 if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
814 if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
819 if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
824 if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
825 ParseCallOffset(state) && ParseEncoding(state)) {
832 // <call-offset> ::= h <nv-offset> _
833 // ::= v <v-offset> _
834 static bool ParseCallOffset(State *state) {
836 if (ParseOneCharToken(state, 'h') &&
837 ParseNVOffset(state) && ParseOneCharToken(state, '_')) {
842 if (ParseOneCharToken(state, 'v') &&
843 ParseVOffset(state) && ParseOneCharToken(state, '_')) {
851 // <nv-offset> ::= <(offset) number>
852 static bool ParseNVOffset(State *state) {
853 return ParseNumber(state, NULL);
856 // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
857 static bool ParseVOffset(State *state) {
859 if (ParseNumber(state, NULL) && ParseOneCharToken(state, '_') &&
860 ParseNumber(state, NULL)) {
867 // <ctor-dtor-name> ::= C1 | C2 | C3
869 static bool ParseCtorDtorName(State *state) {
871 if (ParseOneCharToken(state, 'C') &&
872 ParseCharClass(state, "123")) {
873 const char * const prev_name = state->prev_name;
874 const int prev_name_length = state->prev_name_length;
875 MaybeAppendWithLength(state, prev_name, prev_name_length);
880 if (ParseOneCharToken(state, 'D') &&
881 ParseCharClass(state, "012")) {
882 const char * const prev_name = state->prev_name;
883 const int prev_name_length = state->prev_name_length;
884 MaybeAppend(state, "~");
885 MaybeAppendWithLength(state, prev_name, prev_name_length);
892 // <type> ::= <CV-qualifiers> <type>
893 // ::= P <type> # pointer-to
894 // ::= R <type> # reference-to
895 // ::= O <type> # rvalue reference-to (C++0x)
896 // ::= C <type> # complex pair (C 2000)
897 // ::= G <type> # imaginary (C 2000)
898 // ::= U <source-name> <type> # vendor extended type qualifier
899 // ::= <builtin-type>
900 // ::= <function-type>
901 // ::= <class-enum-type>
903 // ::= <pointer-to-member-type>
904 // ::= <template-template-param> <template-args>
905 // ::= <template-param>
906 // ::= <substitution>
907 // ::= Dp <type> # pack expansion of (C++0x)
908 // ::= Dt <expression> E # decltype of an id-expression or class
909 // # member access (C++0x)
910 // ::= DT <expression> E # decltype of an expression (C++0x)
912 static bool ParseType(State *state) {
913 // We should check CV-qualifers, and PRGC things first.
915 if (ParseCVQualifiers(state) && ParseType(state)) {
920 if (ParseCharClass(state, "OPRCG") && ParseType(state)) {
925 if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
930 if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
931 ParseExpression(state) && ParseOneCharToken(state, 'E')) {
936 if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
942 if (ParseBuiltinType(state) ||
943 ParseFunctionType(state) ||
944 ParseClassEnumType(state) ||
945 ParseArrayType(state) ||
946 ParsePointerToMemberType(state) ||
947 ParseSubstitution(state)) {
951 if (ParseTemplateTemplateParam(state) &&
952 ParseTemplateArgs(state)) {
957 // Less greedy than <template-template-param> <template-args>.
958 if (ParseTemplateParam(state)) {
965 // <CV-qualifiers> ::= [r] [V] [K]
966 // We don't allow empty <CV-qualifiers> to avoid infinite loop in
968 static bool ParseCVQualifiers(State *state) {
969 int num_cv_qualifiers = 0;
970 num_cv_qualifiers += ParseOneCharToken(state, 'r');
971 num_cv_qualifiers += ParseOneCharToken(state, 'V');
972 num_cv_qualifiers += ParseOneCharToken(state, 'K');
973 return num_cv_qualifiers > 0;
976 // <builtin-type> ::= v, etc.
977 // ::= u <source-name>
978 static bool ParseBuiltinType(State *state) {
980 for (p = kBuiltinTypeList; p->abbrev != NULL; ++p) {
981 if (state->mangled_cur[0] == p->abbrev[0]) {
982 MaybeAppend(state, p->real_name);
983 ++state->mangled_cur;
989 if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
996 // <function-type> ::= F [Y] <bare-function-type> E
997 static bool ParseFunctionType(State *state) {
999 if (ParseOneCharToken(state, 'F') &&
1000 Optional(ParseOneCharToken(state, 'Y')) &&
1001 ParseBareFunctionType(state) && ParseOneCharToken(state, 'E')) {
1008 // <bare-function-type> ::= <(signature) type>+
1009 static bool ParseBareFunctionType(State *state) {
1010 State copy = *state;
1011 DisableAppend(state);
1012 if (OneOrMore(ParseType, state)) {
1013 RestoreAppend(state, copy.append);
1014 MaybeAppend(state, "()");
1021 // <class-enum-type> ::= <name>
1022 static bool ParseClassEnumType(State *state) {
1023 return ParseName(state);
1026 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
1027 // ::= A [<(dimension) expression>] _ <(element) type>
1028 static bool ParseArrayType(State *state) {
1029 State copy = *state;
1030 if (ParseOneCharToken(state, 'A') && ParseNumber(state, NULL) &&
1031 ParseOneCharToken(state, '_') && ParseType(state)) {
1036 if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
1037 ParseOneCharToken(state, '_') && ParseType(state)) {
1044 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
1045 static bool ParsePointerToMemberType(State *state) {
1046 State copy = *state;
1047 if (ParseOneCharToken(state, 'M') && ParseType(state) &&
1055 // <template-param> ::= T_
1056 // ::= T <parameter-2 non-negative number> _
1057 static bool ParseTemplateParam(State *state) {
1058 if (ParseTwoCharToken(state, "T_")) {
1059 MaybeAppend(state, "?"); // We don't support template substitutions.
1063 State copy = *state;
1064 if (ParseOneCharToken(state, 'T') && ParseNumber(state, NULL) &&
1065 ParseOneCharToken(state, '_')) {
1066 MaybeAppend(state, "?"); // We don't support template substitutions.
1074 // <template-template-param> ::= <template-param>
1075 // ::= <substitution>
1076 static bool ParseTemplateTemplateParam(State *state) {
1077 return (ParseTemplateParam(state) ||
1078 ParseSubstitution(state));
1081 // <template-args> ::= I <template-arg>+ E
1082 static bool ParseTemplateArgs(State *state) {
1083 State copy = *state;
1084 DisableAppend(state);
1085 if (ParseOneCharToken(state, 'I') &&
1086 OneOrMore(ParseTemplateArg, state) &&
1087 ParseOneCharToken(state, 'E')) {
1088 RestoreAppend(state, copy.append);
1089 MaybeAppend(state, "<>");
1096 // <template-arg> ::= <type>
1097 // ::= <expr-primary>
1098 // ::= I <template-arg>* E # argument pack
1099 // ::= X <expression> E
1100 static bool ParseTemplateArg(State *state) {
1101 State copy = *state;
1102 if (ParseOneCharToken(state, 'I') &&
1103 ZeroOrMore(ParseTemplateArg, state) &&
1104 ParseOneCharToken(state, 'E')) {
1109 if (ParseType(state) ||
1110 ParseExprPrimary(state)) {
1115 if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
1116 ParseOneCharToken(state, 'E')) {
1123 // <expression> ::= <template-param>
1124 // ::= <expr-primary>
1125 // ::= <unary operator-name> <expression>
1126 // ::= <binary operator-name> <expression> <expression>
1127 // ::= <trinary operator-name> <expression> <expression>
1130 // ::= sr <type> <unqualified-name> <template-args>
1131 // ::= sr <type> <unqualified-name>
1132 static bool ParseExpression(State *state) {
1133 if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
1137 State copy = *state;
1138 if (ParseOperatorName(state) &&
1139 ParseExpression(state) &&
1140 ParseExpression(state) &&
1141 ParseExpression(state)) {
1146 if (ParseOperatorName(state) &&
1147 ParseExpression(state) &&
1148 ParseExpression(state)) {
1153 if (ParseOperatorName(state) &&
1154 ParseExpression(state)) {
1159 if (ParseTwoCharToken(state, "st") && ParseType(state)) {
1164 if (ParseTwoCharToken(state, "sr") && ParseType(state) &&
1165 ParseUnqualifiedName(state) &&
1166 ParseTemplateArgs(state)) {
1171 if (ParseTwoCharToken(state, "sr") && ParseType(state) &&
1172 ParseUnqualifiedName(state)) {
1179 // <expr-primary> ::= L <type> <(value) number> E
1180 // ::= L <type> <(value) float> E
1181 // ::= L <mangled-name> E
1182 // // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
1183 // ::= LZ <encoding> E
1184 static bool ParseExprPrimary(State *state) {
1185 State copy = *state;
1186 if (ParseOneCharToken(state, 'L') && ParseType(state) &&
1187 ParseNumber(state, NULL) &&
1188 ParseOneCharToken(state, 'E')) {
1193 if (ParseOneCharToken(state, 'L') && ParseType(state) &&
1194 ParseFloatNumber(state) &&
1195 ParseOneCharToken(state, 'E')) {
1200 if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
1201 ParseOneCharToken(state, 'E')) {
1206 if (ParseTwoCharToken(state, "LZ") && ParseEncoding(state) &&
1207 ParseOneCharToken(state, 'E')) {
1215 // <local-name> := Z <(function) encoding> E <(entity) name>
1216 // [<discriminator>]
1217 // := Z <(function) encoding> E s [<discriminator>]
1218 static bool ParseLocalName(State *state) {
1219 State copy = *state;
1220 if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
1221 ParseOneCharToken(state, 'E') && MaybeAppend(state, "::") &&
1222 ParseName(state) && Optional(ParseDiscriminator(state))) {
1227 if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
1228 ParseTwoCharToken(state, "Es") && Optional(ParseDiscriminator(state))) {
1235 // <discriminator> := _ <(non-negative) number>
1236 static bool ParseDiscriminator(State *state) {
1237 State copy = *state;
1238 if (ParseOneCharToken(state, '_') && ParseNumber(state, NULL)) {
1245 // <substitution> ::= S_
1248 static bool ParseSubstitution(State *state) {
1249 if (ParseTwoCharToken(state, "S_")) {
1250 MaybeAppend(state, "?"); // We don't support substitutions.
1254 State copy = *state;
1255 if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
1256 ParseOneCharToken(state, '_')) {
1257 MaybeAppend(state, "?"); // We don't support substitutions.
1262 // Expand abbreviations like "St" => "std".
1263 if (ParseOneCharToken(state, 'S')) {
1264 const AbbrevPair *p;
1265 for (p = kSubstitutionList; p->abbrev != NULL; ++p) {
1266 if (state->mangled_cur[0] == p->abbrev[1]) {
1267 MaybeAppend(state, "std");
1268 if (p->real_name[0] != '\0') {
1269 MaybeAppend(state, "::");
1270 MaybeAppend(state, p->real_name);
1272 ++state->mangled_cur;
1281 // Parse <mangled-name>, optionally followed by either a function-clone suffix
1282 // or version suffix. Returns true only if all of "mangled_cur" was consumed.
1283 static bool ParseTopLevelMangledName(State *state) {
1284 if (ParseMangledName(state)) {
1285 if (state->mangled_cur[0] != '\0') {
1286 // Drop trailing function clone suffix, if any.
1287 if (IsFunctionCloneSuffix(state->mangled_cur)) {
1290 // Append trailing version suffix if any.
1291 // ex. _Z3foo@@GLIBCXX_3.4
1292 if (state->mangled_cur[0] == '@') {
1293 MaybeAppend(state, state->mangled_cur);
1296 return false; // Unconsumed suffix.
1304 // The demangler entry point.
1305 bool Demangle(const char *mangled, char *out, int out_size) {
1306 #if defined(OS_WINDOWS)
1307 // When built with incremental linking, the Windows debugger
1308 // library provides a more complicated `Symbol->Name` with the
1309 // Incremental Linking Table offset, which looks like
1310 // `@ILT+1105(?func@Foo@@SAXH@Z)`. However, the demangler expects
1311 // only the mangled symbol, `?func@Foo@@SAXH@Z`. Fortunately, the
1312 // mangled symbol is guaranteed not to have parentheses,
1313 // so we search for `(` and extract up to `)`.
1315 // Since we may be in a signal handler here, we cannot use `std::string`.
1316 char buffer[1024]; // Big enough for a sane symbol.
1317 const char *lparen = strchr(mangled, '(');
1319 // Extract the string `(?...)`
1320 const char *rparen = strchr(lparen, ')');
1321 size_t length = rparen - lparen - 1;
1322 strncpy(buffer, lparen + 1, length);
1323 buffer[length] = '\0';
1325 } // Else the symbol wasn't inside a set of parentheses
1326 // We use the ANSI version to ensure the string type is always `char *`.
1327 return UnDecorateSymbolName(mangled, out, out_size, UNDNAME_COMPLETE);
1330 InitState(&state, mangled, out, out_size);
1331 return ParseTopLevelMangledName(&state) && !state.overflowed;
1335 _END_GOOGLE_NAMESPACE_