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)
43 #pragma comment(lib, "DbgHelp")
46 _START_GOOGLE_NAMESPACE_
48 #if !defined(OS_WINDOWS)
51 const char *real_name;
54 // List of operators from Itanium C++ ABI.
55 static const AbbrevPair kOperatorList[] = {
108 // List of builtin types from Itanium C++ ABI.
109 static const AbbrevPair kBuiltinTypeList[] = {
114 { "a", "signed char" },
115 { "h", "unsigned char" },
117 { "t", "unsigned short" },
119 { "j", "unsigned int" },
121 { "m", "unsigned long" },
122 { "x", "long long" },
123 { "y", "unsigned long long" },
125 { "o", "unsigned __int128" },
128 { "e", "long double" },
129 { "g", "__float128" },
134 // List of substitutions Itanium C++ ABI.
135 static const AbbrevPair kSubstitutionList[] = {
137 { "Sa", "allocator" },
138 { "Sb", "basic_string" },
139 // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
141 // std::basic_istream<char, std::char_traits<char> >
143 // std::basic_ostream<char, std::char_traits<char> >
145 // std::basic_iostream<char, std::char_traits<char> >
146 { "Sd", "iostream" },
150 // State needed for demangling.
152 const char *mangled_cur; // Cursor of mangled name.
153 char *out_cur; // Cursor of output string.
154 const char *out_begin; // Beginning of output string.
155 const char *out_end; // End of output string.
156 const char *prev_name; // For constructors/destructors.
157 int prev_name_length; // For constructors/destructors.
158 short nest_level; // For nested names.
159 bool append; // Append flag.
160 bool overflowed; // True if output gets overflowed.
163 // We don't use strlen() in libc since it's not guaranteed to be async
165 static size_t StrLen(const char *str) {
167 while (*str != '\0') {
174 // Returns true if "str" has at least "n" characters remaining.
175 static bool AtLeastNumCharsRemaining(const char *str, int n) {
176 for (int i = 0; i < n; ++i) {
177 if (str[i] == '\0') {
184 // Returns true if "str" has "prefix" as a prefix.
185 static bool StrPrefix(const char *str, const char *prefix) {
187 while (str[i] != '\0' && prefix[i] != '\0' &&
188 str[i] == prefix[i]) {
191 return prefix[i] == '\0'; // Consumed everything in "prefix".
194 static void InitState(State *state, const char *mangled,
195 char *out, int out_size) {
196 state->mangled_cur = mangled;
197 state->out_cur = out;
198 state->out_begin = out;
199 state->out_end = out + out_size;
200 state->prev_name = NULL;
201 state->prev_name_length = -1;
202 state->nest_level = -1;
203 state->append = true;
204 state->overflowed = false;
207 // Returns true and advances "mangled_cur" if we find "one_char_token"
208 // at "mangled_cur" position. It is assumed that "one_char_token" does
210 static bool ParseOneCharToken(State *state, const char one_char_token) {
211 if (state->mangled_cur[0] == one_char_token) {
212 ++state->mangled_cur;
218 // Returns true and advances "mangled_cur" if we find "two_char_token"
219 // at "mangled_cur" position. It is assumed that "two_char_token" does
221 static bool ParseTwoCharToken(State *state, const char *two_char_token) {
222 if (state->mangled_cur[0] == two_char_token[0] &&
223 state->mangled_cur[1] == two_char_token[1]) {
224 state->mangled_cur += 2;
230 // Returns true and advances "mangled_cur" if we find any character in
231 // "char_class" at "mangled_cur" position.
232 static bool ParseCharClass(State *state, const char *char_class) {
233 const char *p = char_class;
234 for (; *p != '\0'; ++p) {
235 if (state->mangled_cur[0] == *p) {
236 ++state->mangled_cur;
243 // This function is used for handling an optional non-terminal.
244 static bool Optional(bool) {
248 // This function is used for handling <non-terminal>+ syntax.
249 typedef bool (*ParseFunc)(State *);
250 static bool OneOrMore(ParseFunc parse_func, State *state) {
251 if (parse_func(state)) {
252 while (parse_func(state)) {
259 // This function is used for handling <non-terminal>* syntax. The function
260 // always returns true and must be followed by a termination token or a
261 // terminating sequence not handled by parse_func (e.g.
262 // ParseOneCharToken(state, 'E')).
263 static bool ZeroOrMore(ParseFunc parse_func, State *state) {
264 while (parse_func(state)) {
269 // Append "str" at "out_cur". If there is an overflow, "overflowed"
270 // is set to true for later use. The output string is ensured to
271 // always terminate with '\0' as long as there is no overflow.
272 static void Append(State *state, const char * const str, const int length) {
274 for (i = 0; i < length; ++i) {
275 if (state->out_cur + 1 < state->out_end) { // +1 for '\0'
276 *state->out_cur = str[i];
279 state->overflowed = true;
283 if (!state->overflowed) {
284 *state->out_cur = '\0'; // Terminate it with '\0'
288 // We don't use equivalents in libc to avoid locale issues.
289 static bool IsLower(char c) {
290 return c >= 'a' && c <= 'z';
293 static bool IsAlpha(char c) {
294 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
297 static bool IsDigit(char c) {
298 return c >= '0' && c <= '9';
301 // Returns true if "str" is a function clone suffix. These suffixes are used
302 // by GCC 4.5.x and later versions to indicate functions which have been
303 // cloned during optimization. We treat any sequence (.<alpha>+.<digit>+)+ as
304 // a function clone suffix.
305 static bool IsFunctionCloneSuffix(const char *str) {
307 while (str[i] != '\0') {
308 // Consume a single .<alpha>+.<digit>+ sequence.
309 if (str[i] != '.' || !IsAlpha(str[i + 1])) {
313 while (IsAlpha(str[i])) {
316 if (str[i] != '.' || !IsDigit(str[i + 1])) {
320 while (IsDigit(str[i])) {
324 return true; // Consumed everything in "str".
327 // Append "str" with some tweaks, iff "append" state is true.
328 // Returns true so that it can be placed in "if" conditions.
329 static void MaybeAppendWithLength(State *state, const char * const str,
331 if (state->append && length > 0) {
332 // Append a space if the output buffer ends with '<' and "str"
333 // starts with '<' to avoid <<<.
334 if (str[0] == '<' && state->out_begin < state->out_cur &&
335 state->out_cur[-1] == '<') {
336 Append(state, " ", 1);
338 // Remember the last identifier name for ctors/dtors.
339 if (IsAlpha(str[0]) || str[0] == '_') {
340 state->prev_name = state->out_cur;
341 state->prev_name_length = length;
343 Append(state, str, length);
347 // A convenient wrapper arount MaybeAppendWithLength().
348 static bool MaybeAppend(State *state, const char * const str) {
350 int length = StrLen(str);
351 MaybeAppendWithLength(state, str, length);
356 // This function is used for handling nested names.
357 static bool EnterNestedName(State *state) {
358 state->nest_level = 0;
362 // This function is used for handling nested names.
363 static bool LeaveNestedName(State *state, short prev_value) {
364 state->nest_level = prev_value;
368 // Disable the append mode not to print function parameters, etc.
369 static bool DisableAppend(State *state) {
370 state->append = false;
374 // Restore the append mode to the previous state.
375 static bool RestoreAppend(State *state, bool prev_value) {
376 state->append = prev_value;
380 // Increase the nest level for nested names.
381 static void MaybeIncreaseNestLevel(State *state) {
382 if (state->nest_level > -1) {
387 // Appends :: for nested names if necessary.
388 static void MaybeAppendSeparator(State *state) {
389 if (state->nest_level >= 1) {
390 MaybeAppend(state, "::");
394 // Cancel the last separator if necessary.
395 static void MaybeCancelLastSeparator(State *state) {
396 if (state->nest_level >= 1 && state->append &&
397 state->out_begin <= state->out_cur - 2) {
399 *state->out_cur = '\0';
403 // Returns true if the identifier of the given length pointed to by
404 // "mangled_cur" is anonymous namespace.
405 static bool IdentifierIsAnonymousNamespace(State *state, int length) {
406 static const char anon_prefix[] = "_GLOBAL__N_";
407 return (length > (int)sizeof(anon_prefix) - 1 && // Should be longer.
408 StrPrefix(state->mangled_cur, anon_prefix));
411 // Forward declarations of our parsing functions.
412 static bool ParseMangledName(State *state);
413 static bool ParseEncoding(State *state);
414 static bool ParseName(State *state);
415 static bool ParseUnscopedName(State *state);
416 static bool ParseUnscopedTemplateName(State *state);
417 static bool ParseNestedName(State *state);
418 static bool ParsePrefix(State *state);
419 static bool ParseUnqualifiedName(State *state);
420 static bool ParseSourceName(State *state);
421 static bool ParseLocalSourceName(State *state);
422 static bool ParseNumber(State *state, int *number_out);
423 static bool ParseFloatNumber(State *state);
424 static bool ParseSeqId(State *state);
425 static bool ParseIdentifier(State *state, int length);
426 static bool ParseOperatorName(State *state);
427 static bool ParseSpecialName(State *state);
428 static bool ParseCallOffset(State *state);
429 static bool ParseNVOffset(State *state);
430 static bool ParseVOffset(State *state);
431 static bool ParseCtorDtorName(State *state);
432 static bool ParseType(State *state);
433 static bool ParseCVQualifiers(State *state);
434 static bool ParseBuiltinType(State *state);
435 static bool ParseFunctionType(State *state);
436 static bool ParseBareFunctionType(State *state);
437 static bool ParseClassEnumType(State *state);
438 static bool ParseArrayType(State *state);
439 static bool ParsePointerToMemberType(State *state);
440 static bool ParseTemplateParam(State *state);
441 static bool ParseTemplateTemplateParam(State *state);
442 static bool ParseTemplateArgs(State *state);
443 static bool ParseTemplateArg(State *state);
444 static bool ParseExpression(State *state);
445 static bool ParseExprPrimary(State *state);
446 static bool ParseLocalName(State *state);
447 static bool ParseDiscriminator(State *state);
448 static bool ParseSubstitution(State *state);
450 // Implementation note: the following code is a straightforward
451 // translation of the Itanium C++ ABI defined in BNF with a couple of
454 // - Support GNU extensions not defined in the Itanium C++ ABI
455 // - <prefix> and <template-prefix> are combined to avoid infinite loop
456 // - Reorder patterns to shorten the code
457 // - Reorder patterns to give greedier functions precedence
458 // We'll mark "Less greedy than" for these cases in the code
460 // Each parsing function changes the state and returns true on
461 // success. Otherwise, don't change the state and returns false. To
462 // ensure that the state isn't changed in the latter case, we save the
463 // original state before we call more than one parsing functions
464 // consecutively with &&, and restore the state if unsuccessful. See
465 // ParseEncoding() as an example of this convention. We follow the
466 // convention throughout the code.
468 // Originally we tried to do demangling without following the full ABI
469 // syntax but it turned out we needed to follow the full syntax to
470 // parse complicated cases like nested template arguments. Note that
471 // implementing a full-fledged demangler isn't trivial (libiberty's
472 // cp-demangle.c has +4300 lines).
474 // Note that (foo) in <(foo) ...> is a modifier to be ignored.
478 // <http://www.codesourcery.com/cxx-abi/abi.html#mangling>
480 // <mangled-name> ::= _Z <encoding>
481 static bool ParseMangledName(State *state) {
482 return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
485 // <encoding> ::= <(function) name> <bare-function-type>
487 // ::= <special-name>
488 static bool ParseEncoding(State *state) {
490 if (ParseName(state) && ParseBareFunctionType(state)) {
495 if (ParseName(state) || ParseSpecialName(state)) {
501 // <name> ::= <nested-name>
502 // ::= <unscoped-template-name> <template-args>
503 // ::= <unscoped-name>
505 static bool ParseName(State *state) {
506 if (ParseNestedName(state) || ParseLocalName(state)) {
511 if (ParseUnscopedTemplateName(state) &&
512 ParseTemplateArgs(state)) {
517 // Less greedy than <unscoped-template-name> <template-args>.
518 if (ParseUnscopedName(state)) {
524 // <unscoped-name> ::= <unqualified-name>
525 // ::= St <unqualified-name>
526 static bool ParseUnscopedName(State *state) {
527 if (ParseUnqualifiedName(state)) {
532 if (ParseTwoCharToken(state, "St") &&
533 MaybeAppend(state, "std::") &&
534 ParseUnqualifiedName(state)) {
541 // <unscoped-template-name> ::= <unscoped-name>
542 // ::= <substitution>
543 static bool ParseUnscopedTemplateName(State *state) {
544 return ParseUnscopedName(state) || ParseSubstitution(state);
547 // <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
548 // ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
549 static bool ParseNestedName(State *state) {
551 if (ParseOneCharToken(state, 'N') &&
552 EnterNestedName(state) &&
553 Optional(ParseCVQualifiers(state)) &&
554 ParsePrefix(state) &&
555 LeaveNestedName(state, copy.nest_level) &&
556 ParseOneCharToken(state, 'E')) {
563 // This part is tricky. If we literally translate them to code, we'll
564 // end up infinite loop. Hence we merge them to avoid the case.
566 // <prefix> ::= <prefix> <unqualified-name>
567 // ::= <template-prefix> <template-args>
568 // ::= <template-param>
569 // ::= <substitution>
571 // <template-prefix> ::= <prefix> <(template) unqualified-name>
572 // ::= <template-param>
573 // ::= <substitution>
574 static bool ParsePrefix(State *state) {
575 bool has_something = false;
577 MaybeAppendSeparator(state);
578 if (ParseTemplateParam(state) ||
579 ParseSubstitution(state) ||
580 ParseUnscopedName(state)) {
581 has_something = true;
582 MaybeIncreaseNestLevel(state);
585 MaybeCancelLastSeparator(state);
586 if (has_something && ParseTemplateArgs(state)) {
587 return ParsePrefix(state);
595 // <unqualified-name> ::= <operator-name>
596 // ::= <ctor-dtor-name>
598 // ::= <local-source-name>
599 static bool ParseUnqualifiedName(State *state) {
600 return (ParseOperatorName(state) ||
601 ParseCtorDtorName(state) ||
602 ParseSourceName(state) ||
603 ParseLocalSourceName(state));
606 // <source-name> ::= <positive length number> <identifier>
607 static bool ParseSourceName(State *state) {
610 if (ParseNumber(state, &length) && ParseIdentifier(state, length)) {
617 // <local-source-name> ::= L <source-name> [<discriminator>]
620 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
621 // http://gcc.gnu.org/viewcvs?view=rev&revision=124467
622 static bool ParseLocalSourceName(State *state) {
624 if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
625 Optional(ParseDiscriminator(state))) {
632 // <number> ::= [n] <non-negative decimal integer>
633 // If "number_out" is non-null, then *number_out is set to the value of the
634 // parsed number on success.
635 static bool ParseNumber(State *state, int *number_out) {
637 if (ParseOneCharToken(state, 'n')) {
640 const char *p = state->mangled_cur;
642 for (;*p != '\0'; ++p) {
644 number = number * 10 + (*p - '0');
649 if (p != state->mangled_cur) { // Conversion succeeded.
650 state->mangled_cur = p;
651 if (number_out != NULL) {
652 *number_out = number * sign;
659 // Floating-point literals are encoded using a fixed-length lowercase
660 // hexadecimal string.
661 static bool ParseFloatNumber(State *state) {
662 const char *p = state->mangled_cur;
663 for (;*p != '\0'; ++p) {
664 if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
668 if (p != state->mangled_cur) { // Conversion succeeded.
669 state->mangled_cur = p;
675 // The <seq-id> is a sequence number in base 36,
676 // using digits and upper case letters
677 static bool ParseSeqId(State *state) {
678 const char *p = state->mangled_cur;
679 for (;*p != '\0'; ++p) {
680 if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
684 if (p != state->mangled_cur) { // Conversion succeeded.
685 state->mangled_cur = p;
691 // <identifier> ::= <unqualified source code identifier> (of given length)
692 static bool ParseIdentifier(State *state, int length) {
694 !AtLeastNumCharsRemaining(state->mangled_cur, length)) {
697 if (IdentifierIsAnonymousNamespace(state, length)) {
698 MaybeAppend(state, "(anonymous namespace)");
700 MaybeAppendWithLength(state, state->mangled_cur, length);
702 state->mangled_cur += length;
706 // <operator-name> ::= nw, and other two letters cases
707 // ::= cv <type> # (cast)
708 // ::= v <digit> <source-name> # vendor extended operator
709 static bool ParseOperatorName(State *state) {
710 if (!AtLeastNumCharsRemaining(state->mangled_cur, 2)) {
713 // First check with "cv" (cast) case.
715 if (ParseTwoCharToken(state, "cv") &&
716 MaybeAppend(state, "operator ") &&
717 EnterNestedName(state) &&
719 LeaveNestedName(state, copy.nest_level)) {
724 // Then vendor extended operators.
725 if (ParseOneCharToken(state, 'v') && ParseCharClass(state, "0123456789") &&
726 ParseSourceName(state)) {
731 // Other operator names should start with a lower alphabet followed
732 // by a lower/upper alphabet.
733 if (!(IsLower(state->mangled_cur[0]) &&
734 IsAlpha(state->mangled_cur[1]))) {
737 // We may want to perform a binary search if we really need speed.
739 for (p = kOperatorList; p->abbrev != NULL; ++p) {
740 if (state->mangled_cur[0] == p->abbrev[0] &&
741 state->mangled_cur[1] == p->abbrev[1]) {
742 MaybeAppend(state, "operator");
743 if (IsLower(*p->real_name)) { // new, delete, etc.
744 MaybeAppend(state, " ");
746 MaybeAppend(state, p->real_name);
747 state->mangled_cur += 2;
754 // <special-name> ::= TV <type>
758 // ::= Tc <call-offset> <call-offset> <(base) encoding>
759 // ::= GV <(object) name>
760 // ::= T <call-offset> <(base) encoding>
762 // ::= TC <type> <(offset) number> _ <(base) type>
767 // ::= Th <call-offset> <(base) encoding>
768 // ::= Tv <call-offset> <(base) encoding>
770 // Note: we don't care much about them since they don't appear in
771 // stack traces. The are special data.
772 static bool ParseSpecialName(State *state) {
774 if (ParseOneCharToken(state, 'T') &&
775 ParseCharClass(state, "VTIS") &&
781 if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
782 ParseCallOffset(state) && ParseEncoding(state)) {
787 if (ParseTwoCharToken(state, "GV") &&
793 if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
794 ParseEncoding(state)) {
800 if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
801 ParseNumber(state, NULL) && ParseOneCharToken(state, '_') &&
802 DisableAppend(state) &&
804 RestoreAppend(state, copy.append);
809 if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
815 if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
820 if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
825 if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
826 ParseCallOffset(state) && ParseEncoding(state)) {
833 // <call-offset> ::= h <nv-offset> _
834 // ::= v <v-offset> _
835 static bool ParseCallOffset(State *state) {
837 if (ParseOneCharToken(state, 'h') &&
838 ParseNVOffset(state) && ParseOneCharToken(state, '_')) {
843 if (ParseOneCharToken(state, 'v') &&
844 ParseVOffset(state) && ParseOneCharToken(state, '_')) {
852 // <nv-offset> ::= <(offset) number>
853 static bool ParseNVOffset(State *state) {
854 return ParseNumber(state, NULL);
857 // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
858 static bool ParseVOffset(State *state) {
860 if (ParseNumber(state, NULL) && ParseOneCharToken(state, '_') &&
861 ParseNumber(state, NULL)) {
868 // <ctor-dtor-name> ::= C1 | C2 | C3
870 static bool ParseCtorDtorName(State *state) {
872 if (ParseOneCharToken(state, 'C') &&
873 ParseCharClass(state, "123")) {
874 const char * const prev_name = state->prev_name;
875 const int prev_name_length = state->prev_name_length;
876 MaybeAppendWithLength(state, prev_name, prev_name_length);
881 if (ParseOneCharToken(state, 'D') &&
882 ParseCharClass(state, "012")) {
883 const char * const prev_name = state->prev_name;
884 const int prev_name_length = state->prev_name_length;
885 MaybeAppend(state, "~");
886 MaybeAppendWithLength(state, prev_name, prev_name_length);
893 // <type> ::= <CV-qualifiers> <type>
894 // ::= P <type> # pointer-to
895 // ::= R <type> # reference-to
896 // ::= O <type> # rvalue reference-to (C++0x)
897 // ::= C <type> # complex pair (C 2000)
898 // ::= G <type> # imaginary (C 2000)
899 // ::= U <source-name> <type> # vendor extended type qualifier
900 // ::= <builtin-type>
901 // ::= <function-type>
902 // ::= <class-enum-type>
904 // ::= <pointer-to-member-type>
905 // ::= <template-template-param> <template-args>
906 // ::= <template-param>
907 // ::= <substitution>
908 // ::= Dp <type> # pack expansion of (C++0x)
909 // ::= Dt <expression> E # decltype of an id-expression or class
910 // # member access (C++0x)
911 // ::= DT <expression> E # decltype of an expression (C++0x)
913 static bool ParseType(State *state) {
914 // We should check CV-qualifers, and PRGC things first.
916 if (ParseCVQualifiers(state) && ParseType(state)) {
921 if (ParseCharClass(state, "OPRCG") && ParseType(state)) {
926 if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
931 if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
932 ParseExpression(state) && ParseOneCharToken(state, 'E')) {
937 if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
943 if (ParseBuiltinType(state) ||
944 ParseFunctionType(state) ||
945 ParseClassEnumType(state) ||
946 ParseArrayType(state) ||
947 ParsePointerToMemberType(state) ||
948 ParseSubstitution(state)) {
952 if (ParseTemplateTemplateParam(state) &&
953 ParseTemplateArgs(state)) {
958 // Less greedy than <template-template-param> <template-args>.
959 if (ParseTemplateParam(state)) {
966 // <CV-qualifiers> ::= [r] [V] [K]
967 // We don't allow empty <CV-qualifiers> to avoid infinite loop in
969 static bool ParseCVQualifiers(State *state) {
970 int num_cv_qualifiers = 0;
971 num_cv_qualifiers += ParseOneCharToken(state, 'r');
972 num_cv_qualifiers += ParseOneCharToken(state, 'V');
973 num_cv_qualifiers += ParseOneCharToken(state, 'K');
974 return num_cv_qualifiers > 0;
977 // <builtin-type> ::= v, etc.
978 // ::= u <source-name>
979 static bool ParseBuiltinType(State *state) {
981 for (p = kBuiltinTypeList; p->abbrev != NULL; ++p) {
982 if (state->mangled_cur[0] == p->abbrev[0]) {
983 MaybeAppend(state, p->real_name);
984 ++state->mangled_cur;
990 if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
997 // <function-type> ::= F [Y] <bare-function-type> E
998 static bool ParseFunctionType(State *state) {
1000 if (ParseOneCharToken(state, 'F') &&
1001 Optional(ParseOneCharToken(state, 'Y')) &&
1002 ParseBareFunctionType(state) && ParseOneCharToken(state, 'E')) {
1009 // <bare-function-type> ::= <(signature) type>+
1010 static bool ParseBareFunctionType(State *state) {
1011 State copy = *state;
1012 DisableAppend(state);
1013 if (OneOrMore(ParseType, state)) {
1014 RestoreAppend(state, copy.append);
1015 MaybeAppend(state, "()");
1022 // <class-enum-type> ::= <name>
1023 static bool ParseClassEnumType(State *state) {
1024 return ParseName(state);
1027 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
1028 // ::= A [<(dimension) expression>] _ <(element) type>
1029 static bool ParseArrayType(State *state) {
1030 State copy = *state;
1031 if (ParseOneCharToken(state, 'A') && ParseNumber(state, NULL) &&
1032 ParseOneCharToken(state, '_') && ParseType(state)) {
1037 if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
1038 ParseOneCharToken(state, '_') && ParseType(state)) {
1045 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
1046 static bool ParsePointerToMemberType(State *state) {
1047 State copy = *state;
1048 if (ParseOneCharToken(state, 'M') && ParseType(state) &&
1056 // <template-param> ::= T_
1057 // ::= T <parameter-2 non-negative number> _
1058 static bool ParseTemplateParam(State *state) {
1059 if (ParseTwoCharToken(state, "T_")) {
1060 MaybeAppend(state, "?"); // We don't support template substitutions.
1064 State copy = *state;
1065 if (ParseOneCharToken(state, 'T') && ParseNumber(state, NULL) &&
1066 ParseOneCharToken(state, '_')) {
1067 MaybeAppend(state, "?"); // We don't support template substitutions.
1075 // <template-template-param> ::= <template-param>
1076 // ::= <substitution>
1077 static bool ParseTemplateTemplateParam(State *state) {
1078 return (ParseTemplateParam(state) ||
1079 ParseSubstitution(state));
1082 // <template-args> ::= I <template-arg>+ E
1083 static bool ParseTemplateArgs(State *state) {
1084 State copy = *state;
1085 DisableAppend(state);
1086 if (ParseOneCharToken(state, 'I') &&
1087 OneOrMore(ParseTemplateArg, state) &&
1088 ParseOneCharToken(state, 'E')) {
1089 RestoreAppend(state, copy.append);
1090 MaybeAppend(state, "<>");
1097 // <template-arg> ::= <type>
1098 // ::= <expr-primary>
1099 // ::= I <template-arg>* E # argument pack
1100 // ::= X <expression> E
1101 static bool ParseTemplateArg(State *state) {
1102 State copy = *state;
1103 if (ParseOneCharToken(state, 'I') &&
1104 ZeroOrMore(ParseTemplateArg, state) &&
1105 ParseOneCharToken(state, 'E')) {
1110 if (ParseType(state) ||
1111 ParseExprPrimary(state)) {
1116 if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
1117 ParseOneCharToken(state, 'E')) {
1124 // <expression> ::= <template-param>
1125 // ::= <expr-primary>
1126 // ::= <unary operator-name> <expression>
1127 // ::= <binary operator-name> <expression> <expression>
1128 // ::= <trinary operator-name> <expression> <expression>
1131 // ::= sr <type> <unqualified-name> <template-args>
1132 // ::= sr <type> <unqualified-name>
1133 static bool ParseExpression(State *state) {
1134 if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
1138 State copy = *state;
1139 if (ParseOperatorName(state) &&
1140 ParseExpression(state) &&
1141 ParseExpression(state) &&
1142 ParseExpression(state)) {
1147 if (ParseOperatorName(state) &&
1148 ParseExpression(state) &&
1149 ParseExpression(state)) {
1154 if (ParseOperatorName(state) &&
1155 ParseExpression(state)) {
1160 if (ParseTwoCharToken(state, "st") && ParseType(state)) {
1165 if (ParseTwoCharToken(state, "sr") && ParseType(state) &&
1166 ParseUnqualifiedName(state) &&
1167 ParseTemplateArgs(state)) {
1172 if (ParseTwoCharToken(state, "sr") && ParseType(state) &&
1173 ParseUnqualifiedName(state)) {
1180 // <expr-primary> ::= L <type> <(value) number> E
1181 // ::= L <type> <(value) float> E
1182 // ::= L <mangled-name> E
1183 // // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
1184 // ::= LZ <encoding> E
1185 static bool ParseExprPrimary(State *state) {
1186 State copy = *state;
1187 if (ParseOneCharToken(state, 'L') && ParseType(state) &&
1188 ParseNumber(state, NULL) &&
1189 ParseOneCharToken(state, 'E')) {
1194 if (ParseOneCharToken(state, 'L') && ParseType(state) &&
1195 ParseFloatNumber(state) &&
1196 ParseOneCharToken(state, 'E')) {
1201 if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
1202 ParseOneCharToken(state, 'E')) {
1207 if (ParseTwoCharToken(state, "LZ") && ParseEncoding(state) &&
1208 ParseOneCharToken(state, 'E')) {
1216 // <local-name> := Z <(function) encoding> E <(entity) name>
1217 // [<discriminator>]
1218 // := Z <(function) encoding> E s [<discriminator>]
1219 static bool ParseLocalName(State *state) {
1220 State copy = *state;
1221 if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
1222 ParseOneCharToken(state, 'E') && MaybeAppend(state, "::") &&
1223 ParseName(state) && Optional(ParseDiscriminator(state))) {
1228 if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
1229 ParseTwoCharToken(state, "Es") && Optional(ParseDiscriminator(state))) {
1236 // <discriminator> := _ <(non-negative) number>
1237 static bool ParseDiscriminator(State *state) {
1238 State copy = *state;
1239 if (ParseOneCharToken(state, '_') && ParseNumber(state, NULL)) {
1246 // <substitution> ::= S_
1249 static bool ParseSubstitution(State *state) {
1250 if (ParseTwoCharToken(state, "S_")) {
1251 MaybeAppend(state, "?"); // We don't support substitutions.
1255 State copy = *state;
1256 if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
1257 ParseOneCharToken(state, '_')) {
1258 MaybeAppend(state, "?"); // We don't support substitutions.
1263 // Expand abbreviations like "St" => "std".
1264 if (ParseOneCharToken(state, 'S')) {
1265 const AbbrevPair *p;
1266 for (p = kSubstitutionList; p->abbrev != NULL; ++p) {
1267 if (state->mangled_cur[0] == p->abbrev[1]) {
1268 MaybeAppend(state, "std");
1269 if (p->real_name[0] != '\0') {
1270 MaybeAppend(state, "::");
1271 MaybeAppend(state, p->real_name);
1273 ++state->mangled_cur;
1282 // Parse <mangled-name>, optionally followed by either a function-clone suffix
1283 // or version suffix. Returns true only if all of "mangled_cur" was consumed.
1284 static bool ParseTopLevelMangledName(State *state) {
1285 if (ParseMangledName(state)) {
1286 if (state->mangled_cur[0] != '\0') {
1287 // Drop trailing function clone suffix, if any.
1288 if (IsFunctionCloneSuffix(state->mangled_cur)) {
1291 // Append trailing version suffix if any.
1292 // ex. _Z3foo@@GLIBCXX_3.4
1293 if (state->mangled_cur[0] == '@') {
1294 MaybeAppend(state, state->mangled_cur);
1297 return false; // Unconsumed suffix.
1305 // The demangler entry point.
1306 bool Demangle(const char *mangled, char *out, int out_size) {
1307 #if defined(OS_WINDOWS)
1308 // When built with incremental linking, the Windows debugger
1309 // library provides a more complicated `Symbol->Name` with the
1310 // Incremental Linking Table offset, which looks like
1311 // `@ILT+1105(?func@Foo@@SAXH@Z)`. However, the demangler expects
1312 // only the mangled symbol, `?func@Foo@@SAXH@Z`. Fortunately, the
1313 // mangled symbol is guaranteed not to have parentheses,
1314 // so we search for `(` and extract up to `)`.
1316 // Since we may be in a signal handler here, we cannot use `std::string`.
1317 char buffer[1024]; // Big enough for a sane symbol.
1318 const char *lparen = strchr(mangled, '(');
1320 // Extract the string `(?...)`
1321 const char *rparen = strchr(lparen, ')');
1322 size_t length = rparen - lparen - 1;
1323 strncpy(buffer, lparen + 1, length);
1324 buffer[length] = '\0';
1326 } // Else the symbol wasn't inside a set of parentheses
1327 // We use the ANSI version to ensure the string type is always `char *`.
1328 return UnDecorateSymbolName(mangled, out, out_size, UNDNAME_COMPLETE);
1331 InitState(&state, mangled, out, out_size);
1332 return ParseTopLevelMangledName(&state) && !state.overflowed;
1336 _END_GOOGLE_NAMESPACE_