xref: /netbsd-src/external/gpl3/binutils.old/dist/libiberty/cp-demangle.c (revision e992f068c547fd6e84b3f104dc2340adcc955732)
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003-2022 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor <ian@wasabisystems.com>.
4 
5    This file is part of the libiberty library, which is part of GCC.
6 
7    This file is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11 
12    In addition to the permissions in the GNU General Public License, the
13    Free Software Foundation gives you unlimited permission to link the
14    compiled version of this file into combinations with other programs,
15    and to distribute those combinations without any restriction coming
16    from the use of this file.  (The General Public License restrictions
17    do apply in other respects; for example, they cover modification of
18    the file, and distribution when not linked into a combined
19    executable.)
20 
21    This program is distributed in the hope that it will be useful,
22    but WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24    GNU General Public License for more details.
25 
26    You should have received a copy of the GNU General Public License
27    along with this program; if not, write to the Free Software
28    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
29 */
30 
31 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
32    described on this web page:
33        https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
34 
35    This code was written while looking at the demangler written by
36    Alex Samuel <samuel@codesourcery.com>.
37 
38    This code first pulls the mangled name apart into a list of
39    components, and then walks the list generating the demangled
40    name.
41 
42    This file will normally define the following functions, q.v.:
43       char *cplus_demangle_v3(const char *mangled, int options)
44       char *java_demangle_v3(const char *mangled)
45       int cplus_demangle_v3_callback(const char *mangled, int options,
46                                      demangle_callbackref callback)
47       int java_demangle_v3_callback(const char *mangled,
48                                     demangle_callbackref callback)
49       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
50       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
51 
52    Also, the interface to the component list is public, and defined in
53    demangle.h.  The interface consists of these types, which are
54    defined in demangle.h:
55       enum demangle_component_type
56       struct demangle_component
57       demangle_callbackref
58    and these functions defined in this file:
59       cplus_demangle_fill_name
60       cplus_demangle_fill_extended_operator
61       cplus_demangle_fill_ctor
62       cplus_demangle_fill_dtor
63       cplus_demangle_print
64       cplus_demangle_print_callback
65    and other functions defined in the file cp-demint.c.
66 
67    This file also defines some other functions and variables which are
68    only to be used by the file cp-demint.c.
69 
70    Preprocessor macros you can define while compiling this file:
71 
72    IN_LIBGCC2
73       If defined, this file defines the following functions, q.v.:
74          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
75                                int *status)
76          int __gcclibcxx_demangle_callback (const char *,
77                                             void (*)
78                                               (const char *, size_t, void *),
79                                             void *)
80       instead of cplus_demangle_v3[_callback]() and
81       java_demangle_v3[_callback]().
82 
83    IN_GLIBCPP_V3
84       If defined, this file defines only __cxa_demangle() and
85       __gcclibcxx_demangle_callback(), and no other publically visible
86       functions or variables.
87 
88    STANDALONE_DEMANGLER
89       If defined, this file defines a main() function which demangles
90       any arguments, or, if none, demangles stdin.
91 
92    CP_DEMANGLE_DEBUG
93       If defined, turns on debugging mode, which prints information on
94       stdout about the mangled string.  This is not generally useful.
95 
96    CHECK_DEMANGLER
97       If defined, additional sanity checks will be performed.  It will
98       cause some slowdown, but will allow to catch out-of-bound access
99       errors earlier.  This macro is intended for testing and debugging.  */
100 
101 #if defined (_AIX) && !defined (__GNUC__)
102  #pragma alloca
103 #endif
104 
105 #ifdef HAVE_CONFIG_H
106 #include "config.h"
107 #endif
108 
109 #include <stdio.h>
110 
111 #ifdef HAVE_STDLIB_H
112 #include <stdlib.h>
113 #endif
114 #ifdef HAVE_STRING_H
115 #include <string.h>
116 #endif
117 
118 #ifdef HAVE_ALLOCA_H
119 # include <alloca.h>
120 #else
121 # ifndef alloca
122 #  ifdef __GNUC__
123 #   define alloca __builtin_alloca
124 #  else
125 extern char *alloca ();
126 #  endif /* __GNUC__ */
127 # endif /* alloca */
128 #endif /* HAVE_ALLOCA_H */
129 
130 #ifdef HAVE_LIMITS_H
131 #include <limits.h>
132 #endif
133 #ifndef INT_MAX
134 # define INT_MAX       (int)(((unsigned int) ~0) >> 1)          /* 0x7FFFFFFF */
135 #endif
136 
137 #include "ansidecl.h"
138 #include "libiberty.h"
139 #include "demangle.h"
140 #include "cp-demangle.h"
141 
142 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
143    also rename them via #define to avoid compiler errors when the
144    static definition conflicts with the extern declaration in a header
145    file.  */
146 #ifdef IN_GLIBCPP_V3
147 
148 #define CP_STATIC_IF_GLIBCPP_V3 static
149 
150 #define cplus_demangle_fill_name d_fill_name
151 static int d_fill_name (struct demangle_component *, const char *, int);
152 
153 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
154 static int
155 d_fill_extended_operator (struct demangle_component *, int,
156                           struct demangle_component *);
157 
158 #define cplus_demangle_fill_ctor d_fill_ctor
159 static int
160 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
161              struct demangle_component *);
162 
163 #define cplus_demangle_fill_dtor d_fill_dtor
164 static int
165 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
166              struct demangle_component *);
167 
168 #define cplus_demangle_mangled_name d_mangled_name
169 static struct demangle_component *d_mangled_name (struct d_info *, int);
170 
171 #define cplus_demangle_type d_type
172 static struct demangle_component *d_type (struct d_info *);
173 
174 #define cplus_demangle_print d_print
175 static char *d_print (int, struct demangle_component *, int, size_t *);
176 
177 #define cplus_demangle_print_callback d_print_callback
178 static int d_print_callback (int, struct demangle_component *,
179                              demangle_callbackref, void *);
180 
181 #define cplus_demangle_init_info d_init_info
182 static void d_init_info (const char *, int, size_t, struct d_info *);
183 
184 #else /* ! defined(IN_GLIBCPP_V3) */
185 #define CP_STATIC_IF_GLIBCPP_V3
186 #endif /* ! defined(IN_GLIBCPP_V3) */
187 
188 /* See if the compiler supports dynamic arrays.  */
189 
190 #ifdef __GNUC__
191 #define CP_DYNAMIC_ARRAYS
192 #else
193 #ifdef __STDC__
194 #ifdef __STDC_VERSION__
195 #if __STDC_VERSION__ >= 199901L && !__STDC_NO_VLA__
196 #define CP_DYNAMIC_ARRAYS
197 #endif /* __STDC_VERSION__ >= 199901L && !__STDC_NO_VLA__ */
198 #endif /* defined (__STDC_VERSION__) */
199 #endif /* defined (__STDC__) */
200 #endif /* ! defined (__GNUC__) */
201 
202 /* We avoid pulling in the ctype tables, to prevent pulling in
203    additional unresolved symbols when this code is used in a library.
204    FIXME: Is this really a valid reason?  This comes from the original
205    V3 demangler code.
206 
207    As of this writing this file has the following undefined references
208    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
209    strcat, strlen.  */
210 
211 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
212 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
213 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
214 
215 /* The prefix prepended by GCC to an identifier represnting the
216    anonymous namespace.  */
217 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
218 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
219   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
220 
221 /* Information we keep for the standard substitutions.  */
222 
223 struct d_standard_sub_info
224 {
225   /* The code for this substitution.  */
226   char code;
227   /* The simple string it expands to.  */
228   const char *simple_expansion;
229   /* The length of the simple expansion.  */
230   int simple_len;
231   /* The results of a full, verbose, expansion.  This is used when
232      qualifying a constructor/destructor, or when in verbose mode.  */
233   const char *full_expansion;
234   /* The length of the full expansion.  */
235   int full_len;
236   /* What to set the last_name field of d_info to; NULL if we should
237      not set it.  This is only relevant when qualifying a
238      constructor/destructor.  */
239   const char *set_last_name;
240   /* The length of set_last_name.  */
241   int set_last_name_len;
242 };
243 
244 /* Accessors for subtrees of struct demangle_component.  */
245 
246 #define d_left(dc) ((dc)->u.s_binary.left)
247 #define d_right(dc) ((dc)->u.s_binary.right)
248 
249 /* A list of templates.  This is used while printing.  */
250 
251 struct d_print_template
252 {
253   /* Next template on the list.  */
254   struct d_print_template *next;
255   /* This template.  */
256   const struct demangle_component *template_decl;
257 };
258 
259 /* A list of type modifiers.  This is used while printing.  */
260 
261 struct d_print_mod
262 {
263   /* Next modifier on the list.  These are in the reverse of the order
264      in which they appeared in the mangled string.  */
265   struct d_print_mod *next;
266   /* The modifier.  */
267   struct demangle_component *mod;
268   /* Whether this modifier was printed.  */
269   int printed;
270   /* The list of templates which applies to this modifier.  */
271   struct d_print_template *templates;
272 };
273 
274 /* We use these structures to hold information during printing.  */
275 
276 struct d_growable_string
277 {
278   /* Buffer holding the result.  */
279   char *buf;
280   /* Current length of data in buffer.  */
281   size_t len;
282   /* Allocated size of buffer.  */
283   size_t alc;
284   /* Set to 1 if we had a memory allocation failure.  */
285   int allocation_failure;
286 };
287 
288 /* Stack of components, innermost first, used to avoid loops.  */
289 
290 struct d_component_stack
291 {
292   /* This component.  */
293   const struct demangle_component *dc;
294   /* This component's parent.  */
295   const struct d_component_stack *parent;
296 };
297 
298 /* A demangle component and some scope captured when it was first
299    traversed.  */
300 
301 struct d_saved_scope
302 {
303   /* The component whose scope this is.  */
304   const struct demangle_component *container;
305   /* The list of templates, if any, that was current when this
306      scope was captured.  */
307   struct d_print_template *templates;
308 };
309 
310 /* Checkpoint structure to allow backtracking.  This holds copies
311    of the fields of struct d_info that need to be restored
312    if a trial parse needs to be backtracked over.  */
313 
314 struct d_info_checkpoint
315 {
316   const char *n;
317   int next_comp;
318   int next_sub;
319   int expansion;
320 };
321 
322 /* Maximum number of times d_print_comp may be called recursively.  */
323 #define MAX_RECURSION_COUNT 1024
324 
325 enum { D_PRINT_BUFFER_LENGTH = 256 };
326 struct d_print_info
327 {
328   /* Fixed-length allocated buffer for demangled data, flushed to the
329      callback with a NUL termination once full.  */
330   char buf[D_PRINT_BUFFER_LENGTH];
331   /* Current length of data in buffer.  */
332   size_t len;
333   /* The last character printed, saved individually so that it survives
334      any buffer flush.  */
335   char last_char;
336   /* Callback function to handle demangled buffer flush.  */
337   demangle_callbackref callback;
338   /* Opaque callback argument.  */
339   void *opaque;
340   /* The current list of templates, if any.  */
341   struct d_print_template *templates;
342   /* The current list of modifiers (e.g., pointer, reference, etc.),
343      if any.  */
344   struct d_print_mod *modifiers;
345   /* Set to 1 if we saw a demangling error.  */
346   int demangle_failure;
347   /* Number of times d_print_comp was recursively called.  Should not
348      be bigger than MAX_RECURSION_COUNT.  */
349   int recursion;
350   /* Non-zero if we're printing a lambda argument.  A template
351      parameter reference actually means 'auto'.  */
352   int is_lambda_arg;
353   /* The current index into any template argument packs we are using
354      for printing, or -1 to print the whole pack.  */
355   int pack_index;
356   /* Number of d_print_flush calls so far.  */
357   unsigned long int flush_count;
358   /* Stack of components, innermost first, used to avoid loops.  */
359   const struct d_component_stack *component_stack;
360   /* Array of saved scopes for evaluating substitutions.  */
361   struct d_saved_scope *saved_scopes;
362   /* Index of the next unused saved scope in the above array.  */
363   int next_saved_scope;
364   /* Number of saved scopes in the above array.  */
365   int num_saved_scopes;
366   /* Array of templates for saving into scopes.  */
367   struct d_print_template *copy_templates;
368   /* Index of the next unused copy template in the above array.  */
369   int next_copy_template;
370   /* Number of copy templates in the above array.  */
371   int num_copy_templates;
372   /* The nearest enclosing template, if any.  */
373   const struct demangle_component *current_template;
374 };
375 
376 #ifdef CP_DEMANGLE_DEBUG
377 static void d_dump (struct demangle_component *, int);
378 #endif
379 
380 static struct demangle_component *
381 d_make_empty (struct d_info *);
382 
383 static struct demangle_component *
384 d_make_comp (struct d_info *, enum demangle_component_type,
385              struct demangle_component *,
386              struct demangle_component *);
387 
388 static struct demangle_component *
389 d_make_name (struct d_info *, const char *, int);
390 
391 static struct demangle_component *
392 d_make_demangle_mangled_name (struct d_info *, const char *);
393 
394 static struct demangle_component *
395 d_make_builtin_type (struct d_info *,
396                      const struct demangle_builtin_type_info *);
397 
398 static struct demangle_component *
399 d_make_operator (struct d_info *,
400                  const struct demangle_operator_info *);
401 
402 static struct demangle_component *
403 d_make_extended_operator (struct d_info *, int,
404                           struct demangle_component *);
405 
406 static struct demangle_component *
407 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
408              struct demangle_component *);
409 
410 static struct demangle_component *
411 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
412              struct demangle_component *);
413 
414 static struct demangle_component *
415 d_make_template_param (struct d_info *, int);
416 
417 static struct demangle_component *
418 d_make_sub (struct d_info *, const char *, int);
419 
420 static int
421 has_return_type (struct demangle_component *);
422 
423 static int
424 is_ctor_dtor_or_conversion (struct demangle_component *);
425 
426 static struct demangle_component *d_encoding (struct d_info *, int);
427 
428 static struct demangle_component *d_name (struct d_info *, int substable);
429 
430 static struct demangle_component *d_nested_name (struct d_info *);
431 
432 static int d_maybe_module_name (struct d_info *, struct demangle_component **);
433 
434 static struct demangle_component *d_prefix (struct d_info *, int);
435 
436 static struct demangle_component *d_unqualified_name (struct d_info *,
437 	struct demangle_component *scope, struct demangle_component *module);
438 
439 static struct demangle_component *d_source_name (struct d_info *);
440 
441 static int d_number (struct d_info *);
442 
443 static struct demangle_component *d_identifier (struct d_info *, int);
444 
445 static struct demangle_component *d_operator_name (struct d_info *);
446 
447 static struct demangle_component *d_special_name (struct d_info *);
448 
449 static struct demangle_component *d_parmlist (struct d_info *);
450 
451 static int d_call_offset (struct d_info *, int);
452 
453 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
454 
455 static struct demangle_component **
456 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
457 
458 static struct demangle_component *
459 d_ref_qualifier (struct d_info *, struct demangle_component *);
460 
461 static struct demangle_component *
462 d_function_type (struct d_info *);
463 
464 static struct demangle_component *
465 d_bare_function_type (struct d_info *, int);
466 
467 static struct demangle_component *
468 d_class_enum_type (struct d_info *, int);
469 
470 static struct demangle_component *d_array_type (struct d_info *);
471 
472 static struct demangle_component *d_vector_type (struct d_info *);
473 
474 static struct demangle_component *
475 d_pointer_to_member_type (struct d_info *);
476 
477 static struct demangle_component *
478 d_template_param (struct d_info *);
479 
480 static struct demangle_component *d_template_args (struct d_info *);
481 static struct demangle_component *d_template_args_1 (struct d_info *);
482 
483 static struct demangle_component *
484 d_template_arg (struct d_info *);
485 
486 static struct demangle_component *d_expression (struct d_info *);
487 
488 static struct demangle_component *d_expr_primary (struct d_info *);
489 
490 static struct demangle_component *d_local_name (struct d_info *);
491 
492 static int d_discriminator (struct d_info *);
493 
494 static struct demangle_component *d_lambda (struct d_info *);
495 
496 static struct demangle_component *d_unnamed_type (struct d_info *);
497 
498 static struct demangle_component *
499 d_clone_suffix (struct d_info *, struct demangle_component *);
500 
501 static int
502 d_add_substitution (struct d_info *, struct demangle_component *);
503 
504 static struct demangle_component *d_substitution (struct d_info *, int);
505 
506 static void d_checkpoint (struct d_info *, struct d_info_checkpoint *);
507 
508 static void d_backtrack (struct d_info *, struct d_info_checkpoint *);
509 
510 static void d_growable_string_init (struct d_growable_string *, size_t);
511 
512 static inline void
513 d_growable_string_resize (struct d_growable_string *, size_t);
514 
515 static inline void
516 d_growable_string_append_buffer (struct d_growable_string *,
517                                  const char *, size_t);
518 static void
519 d_growable_string_callback_adapter (const char *, size_t, void *);
520 
521 static void
522 d_print_init (struct d_print_info *, demangle_callbackref, void *,
523 	      struct demangle_component *);
524 
525 static inline void d_print_error (struct d_print_info *);
526 
527 static inline int d_print_saw_error (struct d_print_info *);
528 
529 static inline void d_print_flush (struct d_print_info *);
530 
531 static inline void d_append_char (struct d_print_info *, char);
532 
533 static inline void d_append_buffer (struct d_print_info *,
534                                     const char *, size_t);
535 
536 static inline void d_append_string (struct d_print_info *, const char *);
537 
538 static inline char d_last_char (struct d_print_info *);
539 
540 static void
541 d_print_comp (struct d_print_info *, int, struct demangle_component *);
542 
543 static void
544 d_print_java_identifier (struct d_print_info *, const char *, int);
545 
546 static void
547 d_print_mod_list (struct d_print_info *, int, struct d_print_mod *, int);
548 
549 static void
550 d_print_mod (struct d_print_info *, int, struct demangle_component *);
551 
552 static void
553 d_print_function_type (struct d_print_info *, int,
554                        struct demangle_component *,
555                        struct d_print_mod *);
556 
557 static void
558 d_print_array_type (struct d_print_info *, int,
559                     struct demangle_component *,
560                     struct d_print_mod *);
561 
562 static void
563 d_print_expr_op (struct d_print_info *, int, struct demangle_component *);
564 
565 static void d_print_cast (struct d_print_info *, int,
566 			  struct demangle_component *);
567 static void d_print_conversion (struct d_print_info *, int,
568 				struct demangle_component *);
569 
570 static int d_demangle_callback (const char *, int,
571                                 demangle_callbackref, void *);
572 static char *d_demangle (const char *, int, size_t *);
573 
574 #define FNQUAL_COMPONENT_CASE				\
575     case DEMANGLE_COMPONENT_RESTRICT_THIS:		\
576     case DEMANGLE_COMPONENT_VOLATILE_THIS:		\
577     case DEMANGLE_COMPONENT_CONST_THIS:			\
578     case DEMANGLE_COMPONENT_REFERENCE_THIS:		\
579     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:	\
580     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:		\
581     case DEMANGLE_COMPONENT_NOEXCEPT:			\
582     case DEMANGLE_COMPONENT_THROW_SPEC
583 
584 /* True iff TYPE is a demangling component representing a
585    function-type-qualifier.  */
586 
587 static int
is_fnqual_component_type(enum demangle_component_type type)588 is_fnqual_component_type (enum demangle_component_type type)
589 {
590   switch (type)
591     {
592     FNQUAL_COMPONENT_CASE:
593       return 1;
594     default:
595       break;
596     }
597   return 0;
598 }
599 
600 
601 #ifdef CP_DEMANGLE_DEBUG
602 
603 static void
d_dump(struct demangle_component * dc,int indent)604 d_dump (struct demangle_component *dc, int indent)
605 {
606   int i;
607 
608   if (dc == NULL)
609     {
610       if (indent == 0)
611         printf ("failed demangling\n");
612       return;
613     }
614 
615   for (i = 0; i < indent; ++i)
616     putchar (' ');
617 
618   switch (dc->type)
619     {
620     case DEMANGLE_COMPONENT_NAME:
621       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
622       return;
623     case DEMANGLE_COMPONENT_TAGGED_NAME:
624       printf ("tagged name\n");
625       d_dump (dc->u.s_binary.left, indent + 2);
626       d_dump (dc->u.s_binary.right, indent + 2);
627       return;
628     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
629       printf ("template parameter %ld\n", dc->u.s_number.number);
630       return;
631     case DEMANGLE_COMPONENT_TPARM_OBJ:
632       printf ("template parameter object\n");
633       break;
634     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
635       printf ("function parameter %ld\n", dc->u.s_number.number);
636       return;
637     case DEMANGLE_COMPONENT_CTOR:
638       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
639       d_dump (dc->u.s_ctor.name, indent + 2);
640       return;
641     case DEMANGLE_COMPONENT_DTOR:
642       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
643       d_dump (dc->u.s_dtor.name, indent + 2);
644       return;
645     case DEMANGLE_COMPONENT_SUB_STD:
646       printf ("standard substitution %s\n", dc->u.s_string.string);
647       return;
648     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
649       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
650       return;
651     case DEMANGLE_COMPONENT_OPERATOR:
652       printf ("operator %s\n", dc->u.s_operator.op->name);
653       return;
654     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
655       printf ("extended operator with %d args\n",
656 	      dc->u.s_extended_operator.args);
657       d_dump (dc->u.s_extended_operator.name, indent + 2);
658       return;
659 
660     case DEMANGLE_COMPONENT_QUAL_NAME:
661       printf ("qualified name\n");
662       break;
663     case DEMANGLE_COMPONENT_LOCAL_NAME:
664       printf ("local name\n");
665       break;
666     case DEMANGLE_COMPONENT_TYPED_NAME:
667       printf ("typed name\n");
668       break;
669     case DEMANGLE_COMPONENT_TEMPLATE:
670       printf ("template\n");
671       break;
672     case DEMANGLE_COMPONENT_VTABLE:
673       printf ("vtable\n");
674       break;
675     case DEMANGLE_COMPONENT_VTT:
676       printf ("VTT\n");
677       break;
678     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
679       printf ("construction vtable\n");
680       break;
681     case DEMANGLE_COMPONENT_TYPEINFO:
682       printf ("typeinfo\n");
683       break;
684     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
685       printf ("typeinfo name\n");
686       break;
687     case DEMANGLE_COMPONENT_TYPEINFO_FN:
688       printf ("typeinfo function\n");
689       break;
690     case DEMANGLE_COMPONENT_THUNK:
691       printf ("thunk\n");
692       break;
693     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
694       printf ("virtual thunk\n");
695       break;
696     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
697       printf ("covariant thunk\n");
698       break;
699     case DEMANGLE_COMPONENT_JAVA_CLASS:
700       printf ("java class\n");
701       break;
702     case DEMANGLE_COMPONENT_GUARD:
703       printf ("guard\n");
704       break;
705     case DEMANGLE_COMPONENT_REFTEMP:
706       printf ("reference temporary\n");
707       break;
708     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
709       printf ("hidden alias\n");
710       break;
711     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
712       printf ("transaction clone\n");
713       break;
714     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
715       printf ("non-transaction clone\n");
716       break;
717     case DEMANGLE_COMPONENT_RESTRICT:
718       printf ("restrict\n");
719       break;
720     case DEMANGLE_COMPONENT_VOLATILE:
721       printf ("volatile\n");
722       break;
723     case DEMANGLE_COMPONENT_CONST:
724       printf ("const\n");
725       break;
726     case DEMANGLE_COMPONENT_RESTRICT_THIS:
727       printf ("restrict this\n");
728       break;
729     case DEMANGLE_COMPONENT_VOLATILE_THIS:
730       printf ("volatile this\n");
731       break;
732     case DEMANGLE_COMPONENT_CONST_THIS:
733       printf ("const this\n");
734       break;
735     case DEMANGLE_COMPONENT_REFERENCE_THIS:
736       printf ("reference this\n");
737       break;
738     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
739       printf ("rvalue reference this\n");
740       break;
741     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
742       printf ("transaction_safe this\n");
743       break;
744     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
745       printf ("vendor type qualifier\n");
746       break;
747     case DEMANGLE_COMPONENT_POINTER:
748       printf ("pointer\n");
749       break;
750     case DEMANGLE_COMPONENT_REFERENCE:
751       printf ("reference\n");
752       break;
753     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
754       printf ("rvalue reference\n");
755       break;
756     case DEMANGLE_COMPONENT_COMPLEX:
757       printf ("complex\n");
758       break;
759     case DEMANGLE_COMPONENT_IMAGINARY:
760       printf ("imaginary\n");
761       break;
762     case DEMANGLE_COMPONENT_VENDOR_TYPE:
763       printf ("vendor type\n");
764       break;
765     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
766       printf ("function type\n");
767       break;
768     case DEMANGLE_COMPONENT_ARRAY_TYPE:
769       printf ("array type\n");
770       break;
771     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
772       printf ("pointer to member type\n");
773       break;
774     case DEMANGLE_COMPONENT_FIXED_TYPE:
775       printf ("fixed-point type, accum? %d, sat? %d\n",
776               dc->u.s_fixed.accum, dc->u.s_fixed.sat);
777       d_dump (dc->u.s_fixed.length, indent + 2);
778       break;
779     case DEMANGLE_COMPONENT_ARGLIST:
780       printf ("argument list\n");
781       break;
782     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
783       printf ("template argument list\n");
784       break;
785     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
786       printf ("initializer list\n");
787       break;
788     case DEMANGLE_COMPONENT_CAST:
789       printf ("cast\n");
790       break;
791     case DEMANGLE_COMPONENT_CONVERSION:
792       printf ("conversion operator\n");
793       break;
794     case DEMANGLE_COMPONENT_NULLARY:
795       printf ("nullary operator\n");
796       break;
797     case DEMANGLE_COMPONENT_UNARY:
798       printf ("unary operator\n");
799       break;
800     case DEMANGLE_COMPONENT_BINARY:
801       printf ("binary operator\n");
802       break;
803     case DEMANGLE_COMPONENT_BINARY_ARGS:
804       printf ("binary operator arguments\n");
805       break;
806     case DEMANGLE_COMPONENT_TRINARY:
807       printf ("trinary operator\n");
808       break;
809     case DEMANGLE_COMPONENT_TRINARY_ARG1:
810       printf ("trinary operator arguments 1\n");
811       break;
812     case DEMANGLE_COMPONENT_TRINARY_ARG2:
813       printf ("trinary operator arguments 1\n");
814       break;
815     case DEMANGLE_COMPONENT_LITERAL:
816       printf ("literal\n");
817       break;
818     case DEMANGLE_COMPONENT_LITERAL_NEG:
819       printf ("negative literal\n");
820       break;
821     case DEMANGLE_COMPONENT_VENDOR_EXPR:
822       printf ("vendor expression\n");
823       break;
824     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
825       printf ("java resource\n");
826       break;
827     case DEMANGLE_COMPONENT_COMPOUND_NAME:
828       printf ("compound name\n");
829       break;
830     case DEMANGLE_COMPONENT_CHARACTER:
831       printf ("character '%c'\n",  dc->u.s_character.character);
832       return;
833     case DEMANGLE_COMPONENT_NUMBER:
834       printf ("number %ld\n", dc->u.s_number.number);
835       return;
836     case DEMANGLE_COMPONENT_DECLTYPE:
837       printf ("decltype\n");
838       break;
839     case DEMANGLE_COMPONENT_PACK_EXPANSION:
840       printf ("pack expansion\n");
841       break;
842     case DEMANGLE_COMPONENT_TLS_INIT:
843       printf ("tls init function\n");
844       break;
845     case DEMANGLE_COMPONENT_TLS_WRAPPER:
846       printf ("tls wrapper function\n");
847       break;
848     case DEMANGLE_COMPONENT_DEFAULT_ARG:
849       printf ("default argument %d\n", dc->u.s_unary_num.num);
850       d_dump (dc->u.s_unary_num.sub, indent+2);
851       return;
852     case DEMANGLE_COMPONENT_LAMBDA:
853       printf ("lambda %d\n", dc->u.s_unary_num.num);
854       d_dump (dc->u.s_unary_num.sub, indent+2);
855       return;
856     }
857 
858   d_dump (d_left (dc), indent + 2);
859   d_dump (d_right (dc), indent + 2);
860 }
861 
862 #endif /* CP_DEMANGLE_DEBUG */
863 
864 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
865 
866 CP_STATIC_IF_GLIBCPP_V3
867 int
cplus_demangle_fill_name(struct demangle_component * p,const char * s,int len)868 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
869 {
870   if (p == NULL || s == NULL || len <= 0)
871     return 0;
872   p->d_printing = 0;
873   p->d_counting = 0;
874   p->type = DEMANGLE_COMPONENT_NAME;
875   p->u.s_name.s = s;
876   p->u.s_name.len = len;
877   return 1;
878 }
879 
880 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
881 
882 CP_STATIC_IF_GLIBCPP_V3
883 int
cplus_demangle_fill_extended_operator(struct demangle_component * p,int args,struct demangle_component * name)884 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
885                                        struct demangle_component *name)
886 {
887   if (p == NULL || args < 0 || name == NULL)
888     return 0;
889   p->d_printing = 0;
890   p->d_counting = 0;
891   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
892   p->u.s_extended_operator.args = args;
893   p->u.s_extended_operator.name = name;
894   return 1;
895 }
896 
897 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
898 
899 CP_STATIC_IF_GLIBCPP_V3
900 int
cplus_demangle_fill_ctor(struct demangle_component * p,enum gnu_v3_ctor_kinds kind,struct demangle_component * name)901 cplus_demangle_fill_ctor (struct demangle_component *p,
902                           enum gnu_v3_ctor_kinds kind,
903                           struct demangle_component *name)
904 {
905   if (p == NULL
906       || name == NULL
907       || (int) kind < gnu_v3_complete_object_ctor
908       || (int) kind > gnu_v3_object_ctor_group)
909     return 0;
910   p->d_printing = 0;
911   p->d_counting = 0;
912   p->type = DEMANGLE_COMPONENT_CTOR;
913   p->u.s_ctor.kind = kind;
914   p->u.s_ctor.name = name;
915   return 1;
916 }
917 
918 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
919 
920 CP_STATIC_IF_GLIBCPP_V3
921 int
cplus_demangle_fill_dtor(struct demangle_component * p,enum gnu_v3_dtor_kinds kind,struct demangle_component * name)922 cplus_demangle_fill_dtor (struct demangle_component *p,
923                           enum gnu_v3_dtor_kinds kind,
924                           struct demangle_component *name)
925 {
926   if (p == NULL
927       || name == NULL
928       || (int) kind < gnu_v3_deleting_dtor
929       || (int) kind > gnu_v3_object_dtor_group)
930     return 0;
931   p->d_printing = 0;
932   p->d_counting = 0;
933   p->type = DEMANGLE_COMPONENT_DTOR;
934   p->u.s_dtor.kind = kind;
935   p->u.s_dtor.name = name;
936   return 1;
937 }
938 
939 /* Add a new component.  */
940 
941 static struct demangle_component *
d_make_empty(struct d_info * di)942 d_make_empty (struct d_info *di)
943 {
944   struct demangle_component *p;
945 
946   if (di->next_comp >= di->num_comps)
947     return NULL;
948   p = &di->comps[di->next_comp];
949   p->d_printing = 0;
950   p->d_counting = 0;
951   ++di->next_comp;
952   return p;
953 }
954 
955 /* Add a new generic component.  */
956 
957 static struct demangle_component *
d_make_comp(struct d_info * di,enum demangle_component_type type,struct demangle_component * left,struct demangle_component * right)958 d_make_comp (struct d_info *di, enum demangle_component_type type,
959              struct demangle_component *left,
960              struct demangle_component *right)
961 {
962   struct demangle_component *p;
963 
964   /* We check for errors here.  A typical error would be a NULL return
965      from a subroutine.  We catch those here, and return NULL
966      upward.  */
967   switch (type)
968     {
969       /* These types require two parameters.  */
970     case DEMANGLE_COMPONENT_QUAL_NAME:
971     case DEMANGLE_COMPONENT_LOCAL_NAME:
972     case DEMANGLE_COMPONENT_TYPED_NAME:
973     case DEMANGLE_COMPONENT_TAGGED_NAME:
974     case DEMANGLE_COMPONENT_TEMPLATE:
975     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
976     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
977     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
978     case DEMANGLE_COMPONENT_UNARY:
979     case DEMANGLE_COMPONENT_BINARY:
980     case DEMANGLE_COMPONENT_BINARY_ARGS:
981     case DEMANGLE_COMPONENT_TRINARY:
982     case DEMANGLE_COMPONENT_TRINARY_ARG1:
983     case DEMANGLE_COMPONENT_LITERAL:
984     case DEMANGLE_COMPONENT_LITERAL_NEG:
985     case DEMANGLE_COMPONENT_VENDOR_EXPR:
986     case DEMANGLE_COMPONENT_COMPOUND_NAME:
987     case DEMANGLE_COMPONENT_VECTOR_TYPE:
988     case DEMANGLE_COMPONENT_CLONE:
989     case DEMANGLE_COMPONENT_MODULE_ENTITY:
990       if (left == NULL || right == NULL)
991 	return NULL;
992       break;
993 
994       /* These types only require one parameter.  */
995     case DEMANGLE_COMPONENT_VTABLE:
996     case DEMANGLE_COMPONENT_VTT:
997     case DEMANGLE_COMPONENT_TYPEINFO:
998     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
999     case DEMANGLE_COMPONENT_TYPEINFO_FN:
1000     case DEMANGLE_COMPONENT_THUNK:
1001     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
1002     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
1003     case DEMANGLE_COMPONENT_JAVA_CLASS:
1004     case DEMANGLE_COMPONENT_GUARD:
1005     case DEMANGLE_COMPONENT_TLS_INIT:
1006     case DEMANGLE_COMPONENT_TLS_WRAPPER:
1007     case DEMANGLE_COMPONENT_REFTEMP:
1008     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
1009     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
1010     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
1011     case DEMANGLE_COMPONENT_POINTER:
1012     case DEMANGLE_COMPONENT_REFERENCE:
1013     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
1014     case DEMANGLE_COMPONENT_COMPLEX:
1015     case DEMANGLE_COMPONENT_IMAGINARY:
1016     case DEMANGLE_COMPONENT_VENDOR_TYPE:
1017     case DEMANGLE_COMPONENT_CAST:
1018     case DEMANGLE_COMPONENT_CONVERSION:
1019     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
1020     case DEMANGLE_COMPONENT_DECLTYPE:
1021     case DEMANGLE_COMPONENT_PACK_EXPANSION:
1022     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
1023     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
1024     case DEMANGLE_COMPONENT_NULLARY:
1025     case DEMANGLE_COMPONENT_TRINARY_ARG2:
1026     case DEMANGLE_COMPONENT_TPARM_OBJ:
1027     case DEMANGLE_COMPONENT_STRUCTURED_BINDING:
1028     case DEMANGLE_COMPONENT_MODULE_INIT:
1029       if (left == NULL)
1030 	return NULL;
1031       break;
1032 
1033       /* This needs a right parameter, but the left parameter can be
1034 	 empty.  */
1035     case DEMANGLE_COMPONENT_ARRAY_TYPE:
1036     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
1037     case DEMANGLE_COMPONENT_MODULE_NAME:
1038     case DEMANGLE_COMPONENT_MODULE_PARTITION:
1039       if (right == NULL)
1040 	return NULL;
1041       break;
1042 
1043       /* These are allowed to have no parameters--in some cases they
1044 	 will be filled in later.  */
1045     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
1046     case DEMANGLE_COMPONENT_RESTRICT:
1047     case DEMANGLE_COMPONENT_VOLATILE:
1048     case DEMANGLE_COMPONENT_CONST:
1049     case DEMANGLE_COMPONENT_ARGLIST:
1050     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
1051     FNQUAL_COMPONENT_CASE:
1052       break;
1053 
1054       /* Other types should not be seen here.  */
1055     default:
1056       return NULL;
1057     }
1058 
1059   p = d_make_empty (di);
1060   if (p != NULL)
1061     {
1062       p->type = type;
1063       p->u.s_binary.left = left;
1064       p->u.s_binary.right = right;
1065     }
1066   return p;
1067 }
1068 
1069 /* Add a new demangle mangled name component.  */
1070 
1071 static struct demangle_component *
d_make_demangle_mangled_name(struct d_info * di,const char * s)1072 d_make_demangle_mangled_name (struct d_info *di, const char *s)
1073 {
1074   if (d_peek_char (di) != '_' || d_peek_next_char (di) != 'Z')
1075     return d_make_name (di, s, strlen (s));
1076   d_advance (di, 2);
1077   return d_encoding (di, 0);
1078 }
1079 
1080 /* Add a new name component.  */
1081 
1082 static struct demangle_component *
d_make_name(struct d_info * di,const char * s,int len)1083 d_make_name (struct d_info *di, const char *s, int len)
1084 {
1085   struct demangle_component *p;
1086 
1087   p = d_make_empty (di);
1088   if (! cplus_demangle_fill_name (p, s, len))
1089     return NULL;
1090   return p;
1091 }
1092 
1093 /* Add a new builtin type component.  */
1094 
1095 static struct demangle_component *
d_make_builtin_type(struct d_info * di,const struct demangle_builtin_type_info * type)1096 d_make_builtin_type (struct d_info *di,
1097                      const struct demangle_builtin_type_info *type)
1098 {
1099   struct demangle_component *p;
1100 
1101   if (type == NULL)
1102     return NULL;
1103   p = d_make_empty (di);
1104   if (p != NULL)
1105     {
1106       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
1107       p->u.s_builtin.type = type;
1108     }
1109   return p;
1110 }
1111 
1112 /* Add a new operator component.  */
1113 
1114 static struct demangle_component *
d_make_operator(struct d_info * di,const struct demangle_operator_info * op)1115 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
1116 {
1117   struct demangle_component *p;
1118 
1119   p = d_make_empty (di);
1120   if (p != NULL)
1121     {
1122       p->type = DEMANGLE_COMPONENT_OPERATOR;
1123       p->u.s_operator.op = op;
1124     }
1125   return p;
1126 }
1127 
1128 /* Add a new extended operator component.  */
1129 
1130 static struct demangle_component *
d_make_extended_operator(struct d_info * di,int args,struct demangle_component * name)1131 d_make_extended_operator (struct d_info *di, int args,
1132                           struct demangle_component *name)
1133 {
1134   struct demangle_component *p;
1135 
1136   p = d_make_empty (di);
1137   if (! cplus_demangle_fill_extended_operator (p, args, name))
1138     return NULL;
1139   return p;
1140 }
1141 
1142 static struct demangle_component *
d_make_default_arg(struct d_info * di,int num,struct demangle_component * sub)1143 d_make_default_arg (struct d_info *di, int num,
1144 		    struct demangle_component *sub)
1145 {
1146   struct demangle_component *p = d_make_empty (di);
1147   if (p)
1148     {
1149       p->type = DEMANGLE_COMPONENT_DEFAULT_ARG;
1150       p->u.s_unary_num.num = num;
1151       p->u.s_unary_num.sub = sub;
1152     }
1153   return p;
1154 }
1155 
1156 /* Add a new constructor component.  */
1157 
1158 static struct demangle_component *
d_make_ctor(struct d_info * di,enum gnu_v3_ctor_kinds kind,struct demangle_component * name)1159 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
1160              struct demangle_component *name)
1161 {
1162   struct demangle_component *p;
1163 
1164   p = d_make_empty (di);
1165   if (! cplus_demangle_fill_ctor (p, kind, name))
1166     return NULL;
1167   return p;
1168 }
1169 
1170 /* Add a new destructor component.  */
1171 
1172 static struct demangle_component *
d_make_dtor(struct d_info * di,enum gnu_v3_dtor_kinds kind,struct demangle_component * name)1173 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
1174              struct demangle_component *name)
1175 {
1176   struct demangle_component *p;
1177 
1178   p = d_make_empty (di);
1179   if (! cplus_demangle_fill_dtor (p, kind, name))
1180     return NULL;
1181   return p;
1182 }
1183 
1184 /* Add a new template parameter.  */
1185 
1186 static struct demangle_component *
d_make_template_param(struct d_info * di,int i)1187 d_make_template_param (struct d_info *di, int i)
1188 {
1189   struct demangle_component *p;
1190 
1191   p = d_make_empty (di);
1192   if (p != NULL)
1193     {
1194       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
1195       p->u.s_number.number = i;
1196     }
1197   return p;
1198 }
1199 
1200 /* Add a new function parameter.  */
1201 
1202 static struct demangle_component *
d_make_function_param(struct d_info * di,int i)1203 d_make_function_param (struct d_info *di, int i)
1204 {
1205   struct demangle_component *p;
1206 
1207   p = d_make_empty (di);
1208   if (p != NULL)
1209     {
1210       p->type = DEMANGLE_COMPONENT_FUNCTION_PARAM;
1211       p->u.s_number.number = i;
1212     }
1213   return p;
1214 }
1215 
1216 /* Add a new standard substitution component.  */
1217 
1218 static struct demangle_component *
d_make_sub(struct d_info * di,const char * name,int len)1219 d_make_sub (struct d_info *di, const char *name, int len)
1220 {
1221   struct demangle_component *p;
1222 
1223   p = d_make_empty (di);
1224   if (p != NULL)
1225     {
1226       p->type = DEMANGLE_COMPONENT_SUB_STD;
1227       p->u.s_string.string = name;
1228       p->u.s_string.len = len;
1229     }
1230   return p;
1231 }
1232 
1233 /* <mangled-name> ::= _Z <encoding> [<clone-suffix>]*
1234 
1235    TOP_LEVEL is non-zero when called at the top level.  */
1236 
1237 CP_STATIC_IF_GLIBCPP_V3
1238 struct demangle_component *
cplus_demangle_mangled_name(struct d_info * di,int top_level)1239 cplus_demangle_mangled_name (struct d_info *di, int top_level)
1240 {
1241   struct demangle_component *p;
1242 
1243   if (! d_check_char (di, '_')
1244       /* Allow missing _ if not at toplevel to work around a
1245 	 bug in G++ abi-version=2 mangling; see the comment in
1246 	 write_template_arg.  */
1247       && top_level)
1248     return NULL;
1249   if (! d_check_char (di, 'Z'))
1250     return NULL;
1251   p = d_encoding (di, top_level);
1252 
1253   /* If at top level and parsing parameters, check for a clone
1254      suffix.  */
1255   if (top_level && (di->options & DMGL_PARAMS) != 0)
1256     while (d_peek_char (di) == '.'
1257 	   && (IS_LOWER (d_peek_next_char (di))
1258 	       || d_peek_next_char (di) == '_'
1259 	       || IS_DIGIT (d_peek_next_char (di))))
1260       p = d_clone_suffix (di, p);
1261 
1262   return p;
1263 }
1264 
1265 /* Return whether a function should have a return type.  The argument
1266    is the function name, which may be qualified in various ways.  The
1267    rules are that template functions have return types with some
1268    exceptions, function types which are not part of a function name
1269    mangling have return types with some exceptions, and non-template
1270    function names do not have return types.  The exceptions are that
1271    constructors, destructors, and conversion operators do not have
1272    return types.  */
1273 
1274 static int
has_return_type(struct demangle_component * dc)1275 has_return_type (struct demangle_component *dc)
1276 {
1277   if (dc == NULL)
1278     return 0;
1279   switch (dc->type)
1280     {
1281     default:
1282       return 0;
1283     case DEMANGLE_COMPONENT_LOCAL_NAME:
1284       return has_return_type (d_right (dc));
1285     case DEMANGLE_COMPONENT_TEMPLATE:
1286       return ! is_ctor_dtor_or_conversion (d_left (dc));
1287     FNQUAL_COMPONENT_CASE:
1288       return has_return_type (d_left (dc));
1289     }
1290 }
1291 
1292 /* Return whether a name is a constructor, a destructor, or a
1293    conversion operator.  */
1294 
1295 static int
is_ctor_dtor_or_conversion(struct demangle_component * dc)1296 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1297 {
1298   if (dc == NULL)
1299     return 0;
1300   switch (dc->type)
1301     {
1302     default:
1303       return 0;
1304     case DEMANGLE_COMPONENT_QUAL_NAME:
1305     case DEMANGLE_COMPONENT_LOCAL_NAME:
1306       return is_ctor_dtor_or_conversion (d_right (dc));
1307     case DEMANGLE_COMPONENT_CTOR:
1308     case DEMANGLE_COMPONENT_DTOR:
1309     case DEMANGLE_COMPONENT_CONVERSION:
1310       return 1;
1311     }
1312 }
1313 
1314 /* <encoding> ::= <(function) name> <bare-function-type>
1315               ::= <(data) name>
1316               ::= <special-name>
1317 
1318    TOP_LEVEL is non-zero when called at the top level, in which case
1319    if DMGL_PARAMS is not set we do not demangle the function
1320    parameters.  We only set this at the top level, because otherwise
1321    we would not correctly demangle names in local scopes.  */
1322 
1323 static struct demangle_component *
d_encoding(struct d_info * di,int top_level)1324 d_encoding (struct d_info *di, int top_level)
1325 {
1326   char peek = d_peek_char (di);
1327   struct demangle_component *dc;
1328 
1329   if (peek == 'G' || peek == 'T')
1330     dc = d_special_name (di);
1331   else
1332     {
1333       dc = d_name (di, 0);
1334 
1335       if (!dc)
1336 	/* Failed already.  */;
1337       else if (top_level && (di->options & DMGL_PARAMS) == 0)
1338 	{
1339 	  /* Strip off any initial CV-qualifiers, as they really apply
1340 	     to the `this' parameter, and they were not output by the
1341 	     v2 demangler without DMGL_PARAMS.  */
1342 	  while (is_fnqual_component_type (dc->type))
1343 	    dc = d_left (dc);
1344 
1345 	  /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1346 	     there may be function-qualifiers on its right argument which
1347 	     really apply here; this happens when parsing a class
1348 	     which is local to a function.  */
1349 	  if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1350 	    {
1351 	      while (d_right (dc) != NULL
1352 		     && is_fnqual_component_type (d_right (dc)->type))
1353 		d_right (dc) = d_left (d_right (dc));
1354 
1355 	      if (d_right (dc) == NULL)
1356 		dc = NULL;
1357 	    }
1358 	}
1359       else
1360 	{
1361 	  peek = d_peek_char (di);
1362 	  if (peek != '\0' && peek != 'E')
1363 	    {
1364 	      struct demangle_component *ftype;
1365 
1366 	      ftype = d_bare_function_type (di, has_return_type (dc));
1367 	      if (ftype)
1368 		{
1369 		  /* If this is a non-top-level local-name, clear the
1370 		     return type, so it doesn't confuse the user by
1371 		     being confused with the return type of whaever
1372 		     this is nested within.  */
1373 		  if (!top_level && dc->type == DEMANGLE_COMPONENT_LOCAL_NAME
1374 		      && ftype->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
1375 		    d_left (ftype) = NULL;
1376 
1377 		  dc = d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME,
1378 				    dc, ftype);
1379 		}
1380 	      else
1381 		dc = NULL;
1382 	    }
1383 	}
1384     }
1385 
1386   return dc;
1387 }
1388 
1389 /* <tagged-name> ::= <name> B <source-name> */
1390 
1391 static struct demangle_component *
d_abi_tags(struct d_info * di,struct demangle_component * dc)1392 d_abi_tags (struct d_info *di, struct demangle_component *dc)
1393 {
1394   struct demangle_component *hold_last_name;
1395   char peek;
1396 
1397   /* Preserve the last name, so the ABI tag doesn't clobber it.  */
1398   hold_last_name = di->last_name;
1399 
1400   while (peek = d_peek_char (di),
1401 	 peek == 'B')
1402     {
1403       struct demangle_component *tag;
1404       d_advance (di, 1);
1405       tag = d_source_name (di);
1406       dc = d_make_comp (di, DEMANGLE_COMPONENT_TAGGED_NAME, dc, tag);
1407     }
1408 
1409   di->last_name = hold_last_name;
1410 
1411   return dc;
1412 }
1413 
1414 /* <name> ::= <nested-name>
1415           ::= <unscoped-name>
1416           ::= <unscoped-template-name> <template-args>
1417           ::= <local-name>
1418 
1419    <unscoped-name> ::= <unqualified-name>
1420                    ::= St <unqualified-name>
1421 
1422    <unscoped-template-name> ::= <unscoped-name>
1423                             ::= <substitution>
1424 */
1425 
1426 static struct demangle_component *
d_name(struct d_info * di,int substable)1427 d_name (struct d_info *di, int substable)
1428 {
1429   char peek = d_peek_char (di);
1430   struct demangle_component *dc = NULL;
1431   struct demangle_component *module = NULL;
1432   int subst = 0;
1433 
1434   switch (peek)
1435     {
1436     case 'N':
1437       dc = d_nested_name (di);
1438       break;
1439 
1440     case 'Z':
1441       dc = d_local_name (di);
1442       break;
1443 
1444     case 'U':
1445       dc = d_unqualified_name (di, NULL, NULL);
1446       break;
1447 
1448     case 'S':
1449       {
1450 	if (d_peek_next_char (di) == 't')
1451 	  {
1452 	    d_advance (di, 2);
1453 	    dc = d_make_name (di, "std", 3);
1454 	    di->expansion += 3;
1455 	  }
1456 
1457 	if (d_peek_char (di) == 'S')
1458 	  {
1459 	    module = d_substitution (di, 0);
1460 	    if (!module)
1461 	      return NULL;
1462 	    if (!(module->type == DEMANGLE_COMPONENT_MODULE_NAME
1463 		  || module->type == DEMANGLE_COMPONENT_MODULE_PARTITION))
1464 	      {
1465 		if (dc)
1466 		  return NULL;
1467 		subst = 1;
1468 		dc = module;
1469 		module = NULL;
1470 	      }
1471 	  }
1472       }
1473       /* FALLTHROUGH */
1474 
1475     case 'L':
1476     default:
1477       if (!subst)
1478 	dc = d_unqualified_name (di, dc, module);
1479       if (d_peek_char (di) == 'I')
1480 	{
1481 	  /* This is <template-args>, which means that we just saw
1482 	     <unscoped-template-name>, which is a substitution
1483 	     candidate.  */
1484 	  if (!subst && !d_add_substitution (di, dc))
1485 	    return NULL;
1486 	  dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1487 			    d_template_args (di));
1488 	  subst = 0;
1489 	}
1490       break;
1491     }
1492   if (substable && !subst && !d_add_substitution (di, dc))
1493     return NULL;
1494   return dc;
1495 }
1496 
1497 /* <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1498                  ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
1499 */
1500 
1501 static struct demangle_component *
d_nested_name(struct d_info * di)1502 d_nested_name (struct d_info *di)
1503 {
1504   struct demangle_component *ret;
1505   struct demangle_component **pret;
1506   struct demangle_component *rqual;
1507 
1508   if (! d_check_char (di, 'N'))
1509     return NULL;
1510 
1511   pret = d_cv_qualifiers (di, &ret, 1);
1512   if (pret == NULL)
1513     return NULL;
1514 
1515   /* Parse the ref-qualifier now and then attach it
1516      once we have something to attach it to.  */
1517   rqual = d_ref_qualifier (di, NULL);
1518 
1519   *pret = d_prefix (di, 1);
1520   if (*pret == NULL)
1521     return NULL;
1522 
1523   if (rqual)
1524     {
1525       d_left (rqual) = ret;
1526       ret = rqual;
1527     }
1528 
1529   if (! d_check_char (di, 'E'))
1530     return NULL;
1531 
1532   return ret;
1533 }
1534 
1535 /* <prefix> ::= <prefix> <unqualified-name>
1536             ::= <template-prefix> <template-args>
1537             ::= <template-param>
1538             ::= <decltype>
1539             ::=
1540             ::= <substitution>
1541 
1542    <template-prefix> ::= <prefix> <(template) unqualified-name>
1543                      ::= <template-param>
1544                      ::= <substitution>
1545 
1546    SUBST is true if we should add substitutions (as normal), false
1547    if not (in an unresolved-name).  */
1548 
1549 static struct demangle_component *
d_prefix(struct d_info * di,int substable)1550 d_prefix (struct d_info *di, int substable)
1551 {
1552   struct demangle_component *ret = NULL;
1553 
1554   for (;;)
1555     {
1556       char peek = d_peek_char (di);
1557 
1558       /* The older code accepts a <local-name> here, but I don't see
1559 	 that in the grammar.  The older code does not accept a
1560 	 <template-param> here.  */
1561 
1562       if (peek == 'D'
1563 	  && (d_peek_next_char (di) == 'T'
1564 	      || d_peek_next_char (di) == 't'))
1565 	{
1566 	  /* Decltype.  */
1567 	  if (ret)
1568 	    return NULL;
1569 	  ret = cplus_demangle_type (di);
1570 	}
1571       else if (peek == 'I')
1572 	{
1573 	  if (ret == NULL)
1574 	    return NULL;
1575 	  struct demangle_component *dc = d_template_args (di);
1576 	  if (!dc)
1577 	    return NULL;
1578 	  ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret, dc);
1579 	}
1580       else if (peek == 'T')
1581 	{
1582 	  if (ret)
1583 	    return NULL;
1584 	  ret = d_template_param (di);
1585 	}
1586       else if (peek == 'M')
1587 	{
1588 	  /* Initializer scope for a lambda.  We don't need to represent
1589 	     this; the normal code will just treat the variable as a type
1590 	     scope, which gives appropriate output.  */
1591 	  if (ret == NULL)
1592 	    return NULL;
1593 	  d_advance (di, 1);
1594 	}
1595       else
1596 	{
1597 	  struct demangle_component *module = NULL;
1598 	  if (peek == 'S')
1599 	    {
1600 	      module = d_substitution (di, 1);
1601 	      if (!module)
1602 		return NULL;
1603 	      if (!(module->type == DEMANGLE_COMPONENT_MODULE_NAME
1604 		    || module->type == DEMANGLE_COMPONENT_MODULE_PARTITION))
1605 		{
1606 		  if (ret)
1607 		    return NULL;
1608 		  ret = module;
1609 		  continue;
1610 		}
1611 	    }
1612 	  ret = d_unqualified_name (di, ret, module);
1613 	}
1614 
1615       if (!ret)
1616 	break;
1617 
1618       if (d_peek_char (di) == 'E')
1619 	break;
1620 
1621       if (substable && !d_add_substitution (di, ret))
1622 	return NULL;
1623     }
1624 
1625   return ret;
1626 }
1627 
1628 static int
d_maybe_module_name(struct d_info * di,struct demangle_component ** name)1629 d_maybe_module_name (struct d_info *di, struct demangle_component **name)
1630 {
1631   while (d_peek_char (di) == 'W')
1632     {
1633       d_advance (di, 1);
1634       enum demangle_component_type code = DEMANGLE_COMPONENT_MODULE_NAME;
1635       if (d_peek_char (di) == 'P')
1636 	{
1637 	  code = DEMANGLE_COMPONENT_MODULE_PARTITION;
1638 	  d_advance (di, 1);
1639 	}
1640 
1641       *name = d_make_comp (di, code, *name, d_source_name (di));
1642       if (!*name)
1643 	return 0;
1644       if (!d_add_substitution (di, *name))
1645 	return 0;
1646     }
1647   return 1;
1648 }
1649 
1650 /* <unqualified-name> ::= [<module-name>] <operator-name> [<abi-tags>]
1651                       ::= [<module-name>] <ctor-dtor-name> [<abi-tags>]
1652                       ::= [<module-name>] <source-name> [<abi-tags>]
1653 		      ::= [<module-name>] <local-source-name>  [<abi-tags>]
1654                       ::= [<module-name>] DC <source-name>+ E [<abi-tags>]
1655     <local-source-name>	::= L <source-name> <discriminator> [<abi-tags>]
1656 */
1657 
1658 static struct demangle_component *
d_unqualified_name(struct d_info * di,struct demangle_component * scope,struct demangle_component * module)1659 d_unqualified_name (struct d_info *di, struct demangle_component *scope,
1660 		    struct demangle_component *module)
1661 {
1662   struct demangle_component *ret;
1663   char peek;
1664 
1665   if (!d_maybe_module_name (di, &module))
1666     return NULL;
1667 
1668   peek = d_peek_char (di);
1669   if (IS_DIGIT (peek))
1670     ret = d_source_name (di);
1671   else if (IS_LOWER (peek))
1672     {
1673       int was_expr = di->is_expression;
1674       if (peek == 'o' && d_peek_next_char (di) == 'n')
1675 	{
1676 	  d_advance (di, 2);
1677 	  /* Treat cv as naming a conversion operator.  */
1678 	  di->is_expression = 0;
1679 	}
1680       ret = d_operator_name (di);
1681       di->is_expression = was_expr;
1682       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1683 	{
1684 	  di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1685 	  if (!strcmp (ret->u.s_operator.op->code, "li"))
1686 	    ret = d_make_comp (di, DEMANGLE_COMPONENT_UNARY, ret,
1687 			       d_source_name (di));
1688 	}
1689     }
1690   else if (peek == 'D' && d_peek_next_char (di) == 'C')
1691     {
1692       // structured binding
1693       d_advance (di, 2);
1694       struct demangle_component *prev = NULL;
1695       do
1696 	{
1697 	  struct demangle_component *next =
1698 	    d_make_comp (di, DEMANGLE_COMPONENT_STRUCTURED_BINDING,
1699 			 d_source_name (di), NULL);
1700 	  if (prev)
1701 	    d_right (prev) = next;
1702 	  else
1703 	    ret = next;
1704 	  prev = next;
1705 	}
1706       while (prev && d_peek_char (di) != 'E');
1707       if (prev)
1708 	d_advance (di, 1);
1709       else
1710 	ret = NULL;
1711     }
1712   else if (peek == 'C' || peek == 'D')
1713     ret = d_ctor_dtor_name (di);
1714   else if (peek == 'L')
1715     {
1716       d_advance (di, 1);
1717 
1718       ret = d_source_name (di);
1719       if (ret == NULL)
1720 	return NULL;
1721       if (! d_discriminator (di))
1722 	return NULL;
1723     }
1724   else if (peek == 'U')
1725     {
1726       switch (d_peek_next_char (di))
1727 	{
1728 	case 'l':
1729 	  ret = d_lambda (di);
1730 	  break;
1731 	case 't':
1732 	  ret = d_unnamed_type (di);
1733 	  break;
1734 	default:
1735 	  return NULL;
1736 	}
1737     }
1738   else
1739     return NULL;
1740 
1741   if (module)
1742     ret = d_make_comp (di, DEMANGLE_COMPONENT_MODULE_ENTITY, ret, module);
1743   if (d_peek_char (di) == 'B')
1744     ret = d_abi_tags (di, ret);
1745   if (scope)
1746     ret = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, scope, ret);
1747 
1748   return ret;
1749 }
1750 
1751 /* <source-name> ::= <(positive length) number> <identifier>  */
1752 
1753 static struct demangle_component *
d_source_name(struct d_info * di)1754 d_source_name (struct d_info *di)
1755 {
1756   int len;
1757   struct demangle_component *ret;
1758 
1759   len = d_number (di);
1760   if (len <= 0)
1761     return NULL;
1762   ret = d_identifier (di, len);
1763   di->last_name = ret;
1764   return ret;
1765 }
1766 
1767 /* number ::= [n] <(non-negative decimal integer)>  */
1768 
1769 static int
d_number(struct d_info * di)1770 d_number (struct d_info *di)
1771 {
1772   int negative;
1773   char peek;
1774   int ret;
1775 
1776   negative = 0;
1777   peek = d_peek_char (di);
1778   if (peek == 'n')
1779     {
1780       negative = 1;
1781       d_advance (di, 1);
1782       peek = d_peek_char (di);
1783     }
1784 
1785   ret = 0;
1786   while (1)
1787     {
1788       if (! IS_DIGIT (peek))
1789 	{
1790 	  if (negative)
1791 	    ret = - ret;
1792 	  return ret;
1793 	}
1794       if (ret > ((INT_MAX - (peek - '0')) / 10))
1795         return -1;
1796       ret = ret * 10 + (peek - '0');
1797       d_advance (di, 1);
1798       peek = d_peek_char (di);
1799     }
1800 }
1801 
1802 /* Like d_number, but returns a demangle_component.  */
1803 
1804 static struct demangle_component *
d_number_component(struct d_info * di)1805 d_number_component (struct d_info *di)
1806 {
1807   struct demangle_component *ret = d_make_empty (di);
1808   if (ret)
1809     {
1810       ret->type = DEMANGLE_COMPONENT_NUMBER;
1811       ret->u.s_number.number = d_number (di);
1812     }
1813   return ret;
1814 }
1815 
1816 /* identifier ::= <(unqualified source code identifier)>  */
1817 
1818 static struct demangle_component *
d_identifier(struct d_info * di,int len)1819 d_identifier (struct d_info *di, int len)
1820 {
1821   const char *name;
1822 
1823   name = d_str (di);
1824 
1825   if (di->send - name < len)
1826     return NULL;
1827 
1828   d_advance (di, len);
1829 
1830   /* A Java mangled name may have a trailing '$' if it is a C++
1831      keyword.  This '$' is not included in the length count.  We just
1832      ignore the '$'.  */
1833   if ((di->options & DMGL_JAVA) != 0
1834       && d_peek_char (di) == '$')
1835     d_advance (di, 1);
1836 
1837   /* Look for something which looks like a gcc encoding of an
1838      anonymous namespace, and replace it with a more user friendly
1839      name.  */
1840   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1841       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1842 		 ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1843     {
1844       const char *s;
1845 
1846       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1847       if ((*s == '.' || *s == '_' || *s == '$')
1848 	  && s[1] == 'N')
1849 	{
1850 	  di->expansion -= len - sizeof "(anonymous namespace)";
1851 	  return d_make_name (di, "(anonymous namespace)",
1852 			      sizeof "(anonymous namespace)" - 1);
1853 	}
1854     }
1855 
1856   return d_make_name (di, name, len);
1857 }
1858 
1859 /* operator_name ::= many different two character encodings.
1860                  ::= cv <type>
1861                  ::= v <digit> <source-name>
1862 
1863    This list is sorted for binary search.  */
1864 
1865 #define NL(s) s, (sizeof s) - 1
1866 
1867 CP_STATIC_IF_GLIBCPP_V3
1868 const struct demangle_operator_info cplus_demangle_operators[] =
1869 {
1870   { "aN", NL ("&="),        2 },
1871   { "aS", NL ("="),         2 },
1872   { "aa", NL ("&&"),        2 },
1873   { "ad", NL ("&"),         1 },
1874   { "an", NL ("&"),         2 },
1875   { "at", NL ("alignof "),   1 },
1876   { "aw", NL ("co_await "), 1 },
1877   { "az", NL ("alignof "),   1 },
1878   { "cc", NL ("const_cast"), 2 },
1879   { "cl", NL ("()"),        2 },
1880   { "cm", NL (","),         2 },
1881   { "co", NL ("~"),         1 },
1882   { "dV", NL ("/="),        2 },
1883   { "dX", NL ("[...]="),     3 }, /* [expr...expr] = expr */
1884   { "da", NL ("delete[] "), 1 },
1885   { "dc", NL ("dynamic_cast"), 2 },
1886   { "de", NL ("*"),         1 },
1887   { "di", NL ("="),         2 }, /* .name = expr */
1888   { "dl", NL ("delete "),   1 },
1889   { "ds", NL (".*"),        2 },
1890   { "dt", NL ("."),         2 },
1891   { "dv", NL ("/"),         2 },
1892   { "dx", NL ("]="),        2 }, /* [expr] = expr */
1893   { "eO", NL ("^="),        2 },
1894   { "eo", NL ("^"),         2 },
1895   { "eq", NL ("=="),        2 },
1896   { "fL", NL ("..."),       3 },
1897   { "fR", NL ("..."),       3 },
1898   { "fl", NL ("..."),       2 },
1899   { "fr", NL ("..."),       2 },
1900   { "ge", NL (">="),        2 },
1901   { "gs", NL ("::"),	    1 },
1902   { "gt", NL (">"),         2 },
1903   { "ix", NL ("[]"),        2 },
1904   { "lS", NL ("<<="),       2 },
1905   { "le", NL ("<="),        2 },
1906   { "li", NL ("operator\"\" "), 1 },
1907   { "ls", NL ("<<"),        2 },
1908   { "lt", NL ("<"),         2 },
1909   { "mI", NL ("-="),        2 },
1910   { "mL", NL ("*="),        2 },
1911   { "mi", NL ("-"),         2 },
1912   { "ml", NL ("*"),         2 },
1913   { "mm", NL ("--"),        1 },
1914   { "na", NL ("new[]"),     3 },
1915   { "ne", NL ("!="),        2 },
1916   { "ng", NL ("-"),         1 },
1917   { "nt", NL ("!"),         1 },
1918   { "nw", NL ("new"),       3 },
1919   { "oR", NL ("|="),        2 },
1920   { "oo", NL ("||"),        2 },
1921   { "or", NL ("|"),         2 },
1922   { "pL", NL ("+="),        2 },
1923   { "pl", NL ("+"),         2 },
1924   { "pm", NL ("->*"),       2 },
1925   { "pp", NL ("++"),        1 },
1926   { "ps", NL ("+"),         1 },
1927   { "pt", NL ("->"),        2 },
1928   { "qu", NL ("?"),         3 },
1929   { "rM", NL ("%="),        2 },
1930   { "rS", NL (">>="),       2 },
1931   { "rc", NL ("reinterpret_cast"), 2 },
1932   { "rm", NL ("%"),         2 },
1933   { "rs", NL (">>"),        2 },
1934   { "sP", NL ("sizeof..."), 1 },
1935   { "sZ", NL ("sizeof..."), 1 },
1936   { "sc", NL ("static_cast"), 2 },
1937   { "ss", NL ("<=>"),       2 },
1938   { "st", NL ("sizeof "),   1 },
1939   { "sz", NL ("sizeof "),   1 },
1940   { "tr", NL ("throw"),     0 },
1941   { "tw", NL ("throw "),    1 },
1942   { NULL, NULL, 0,          0 }
1943 };
1944 
1945 static struct demangle_component *
d_operator_name(struct d_info * di)1946 d_operator_name (struct d_info *di)
1947 {
1948   char c1;
1949   char c2;
1950 
1951   c1 = d_next_char (di);
1952   c2 = d_next_char (di);
1953   if (c1 == 'v' && IS_DIGIT (c2))
1954     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1955   else if (c1 == 'c' && c2 == 'v')
1956     {
1957       struct demangle_component *type;
1958       int was_conversion = di->is_conversion;
1959       struct demangle_component *res;
1960 
1961       di->is_conversion = ! di->is_expression;
1962       type = cplus_demangle_type (di);
1963       if (di->is_conversion)
1964 	res = d_make_comp (di, DEMANGLE_COMPONENT_CONVERSION, type, NULL);
1965       else
1966 	res = d_make_comp (di, DEMANGLE_COMPONENT_CAST, type, NULL);
1967       di->is_conversion = was_conversion;
1968       return res;
1969     }
1970   else
1971     {
1972       /* LOW is the inclusive lower bound.  */
1973       int low = 0;
1974       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1975 	 the sentinel at the end of the array.  */
1976       int high = ((sizeof (cplus_demangle_operators)
1977 		   / sizeof (cplus_demangle_operators[0]))
1978 		  - 1);
1979 
1980       while (1)
1981 	{
1982 	  int i;
1983 	  const struct demangle_operator_info *p;
1984 
1985 	  i = low + (high - low) / 2;
1986 	  p = cplus_demangle_operators + i;
1987 
1988 	  if (c1 == p->code[0] && c2 == p->code[1])
1989 	    return d_make_operator (di, p);
1990 
1991 	  if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1992 	    high = i;
1993 	  else
1994 	    low = i + 1;
1995 	  if (low == high)
1996 	    return NULL;
1997 	}
1998     }
1999 }
2000 
2001 static struct demangle_component *
d_make_character(struct d_info * di,int c)2002 d_make_character (struct d_info *di, int c)
2003 {
2004   struct demangle_component *p;
2005   p = d_make_empty (di);
2006   if (p != NULL)
2007     {
2008       p->type = DEMANGLE_COMPONENT_CHARACTER;
2009       p->u.s_character.character = c;
2010     }
2011   return p;
2012 }
2013 
2014 static struct demangle_component *
d_java_resource(struct d_info * di)2015 d_java_resource (struct d_info *di)
2016 {
2017   struct demangle_component *p = NULL;
2018   struct demangle_component *next = NULL;
2019   int len, i;
2020   char c;
2021   const char *str;
2022 
2023   len = d_number (di);
2024   if (len <= 1)
2025     return NULL;
2026 
2027   /* Eat the leading '_'.  */
2028   if (d_next_char (di) != '_')
2029     return NULL;
2030   len--;
2031 
2032   str = d_str (di);
2033   i = 0;
2034 
2035   while (len > 0)
2036     {
2037       c = str[i];
2038       if (!c)
2039 	return NULL;
2040 
2041       /* Each chunk is either a '$' escape...  */
2042       if (c == '$')
2043 	{
2044 	  i++;
2045 	  switch (str[i++])
2046 	    {
2047 	    case 'S':
2048 	      c = '/';
2049 	      break;
2050 	    case '_':
2051 	      c = '.';
2052 	      break;
2053 	    case '$':
2054 	      c = '$';
2055 	      break;
2056 	    default:
2057 	      return NULL;
2058 	    }
2059 	  next = d_make_character (di, c);
2060 	  d_advance (di, i);
2061 	  str = d_str (di);
2062 	  len -= i;
2063 	  i = 0;
2064 	  if (next == NULL)
2065 	    return NULL;
2066 	}
2067       /* ... or a sequence of characters.  */
2068       else
2069 	{
2070 	  while (i < len && str[i] && str[i] != '$')
2071 	    i++;
2072 
2073 	  next = d_make_name (di, str, i);
2074 	  d_advance (di, i);
2075 	  str = d_str (di);
2076 	  len -= i;
2077 	  i = 0;
2078 	  if (next == NULL)
2079 	    return NULL;
2080 	}
2081 
2082       if (p == NULL)
2083 	p = next;
2084       else
2085 	{
2086 	  p = d_make_comp (di, DEMANGLE_COMPONENT_COMPOUND_NAME, p, next);
2087 	  if (p == NULL)
2088 	    return NULL;
2089 	}
2090     }
2091 
2092   p = d_make_comp (di, DEMANGLE_COMPONENT_JAVA_RESOURCE, p, NULL);
2093 
2094   return p;
2095 }
2096 
2097 /* <special-name> ::= TV <type>
2098                   ::= TT <type>
2099                   ::= TI <type>
2100                   ::= TS <type>
2101 		  ::= TA <template-arg>
2102                   ::= GV <(object) name>
2103                   ::= T <call-offset> <(base) encoding>
2104                   ::= Tc <call-offset> <call-offset> <(base) encoding>
2105    Also g++ extensions:
2106                   ::= TC <type> <(offset) number> _ <(base) type>
2107                   ::= TF <type>
2108                   ::= TJ <type>
2109                   ::= GR <name>
2110 		  ::= GA <encoding>
2111 		  ::= Gr <resource name>
2112 		  ::= GTt <encoding>
2113 		  ::= GTn <encoding>
2114 */
2115 
2116 static struct demangle_component *
d_special_name(struct d_info * di)2117 d_special_name (struct d_info *di)
2118 {
2119   di->expansion += 20;
2120   if (d_check_char (di, 'T'))
2121     {
2122       switch (d_next_char (di))
2123 	{
2124 	case 'V':
2125 	  di->expansion -= 5;
2126 	  return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
2127 			      cplus_demangle_type (di), NULL);
2128 	case 'T':
2129 	  di->expansion -= 10;
2130 	  return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
2131 			      cplus_demangle_type (di), NULL);
2132 	case 'I':
2133 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
2134 			      cplus_demangle_type (di), NULL);
2135 	case 'S':
2136 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
2137 			      cplus_demangle_type (di), NULL);
2138 
2139 	case 'h':
2140 	  if (! d_call_offset (di, 'h'))
2141 	    return NULL;
2142 	  return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
2143 			      d_encoding (di, 0), NULL);
2144 
2145 	case 'v':
2146 	  if (! d_call_offset (di, 'v'))
2147 	    return NULL;
2148 	  return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
2149 			      d_encoding (di, 0), NULL);
2150 
2151 	case 'c':
2152 	  if (! d_call_offset (di, '\0'))
2153 	    return NULL;
2154 	  if (! d_call_offset (di, '\0'))
2155 	    return NULL;
2156 	  return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
2157 			      d_encoding (di, 0), NULL);
2158 
2159 	case 'C':
2160 	  {
2161 	    struct demangle_component *derived_type;
2162 	    int offset;
2163 	    struct demangle_component *base_type;
2164 
2165 	    derived_type = cplus_demangle_type (di);
2166 	    offset = d_number (di);
2167 	    if (offset < 0)
2168 	      return NULL;
2169 	    if (! d_check_char (di, '_'))
2170 	      return NULL;
2171 	    base_type = cplus_demangle_type (di);
2172 	    /* We don't display the offset.  FIXME: We should display
2173 	       it in verbose mode.  */
2174 	    di->expansion += 5;
2175 	    return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
2176 				base_type, derived_type);
2177 	  }
2178 
2179 	case 'F':
2180 	  return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
2181 			      cplus_demangle_type (di), NULL);
2182 	case 'J':
2183 	  return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
2184 			      cplus_demangle_type (di), NULL);
2185 
2186 	case 'H':
2187 	  return d_make_comp (di, DEMANGLE_COMPONENT_TLS_INIT,
2188 			      d_name (di, 0), NULL);
2189 
2190 	case 'W':
2191 	  return d_make_comp (di, DEMANGLE_COMPONENT_TLS_WRAPPER,
2192 			      d_name (di, 0), NULL);
2193 
2194 	case 'A':
2195 	  return d_make_comp (di, DEMANGLE_COMPONENT_TPARM_OBJ,
2196 			      d_template_arg (di), NULL);
2197 
2198 	default:
2199 	  return NULL;
2200 	}
2201     }
2202   else if (d_check_char (di, 'G'))
2203     {
2204       switch (d_next_char (di))
2205 	{
2206 	case 'V':
2207 	  return d_make_comp (di, DEMANGLE_COMPONENT_GUARD,
2208 			      d_name (di, 0), NULL);
2209 
2210 	case 'R':
2211 	  {
2212 	    struct demangle_component *name = d_name (di, 0);
2213 	    return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, name,
2214 				d_number_component (di));
2215 	  }
2216 
2217 	case 'A':
2218 	  return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
2219 			      d_encoding (di, 0), NULL);
2220 
2221 	case 'I':
2222 	  {
2223 	    struct demangle_component *module = NULL;
2224 	    if (!d_maybe_module_name (di, &module) || !module)
2225 	      return NULL;
2226 	    return d_make_comp (di, DEMANGLE_COMPONENT_MODULE_INIT,
2227 				module, NULL);
2228 	  }
2229 	case 'T':
2230 	  switch (d_next_char (di))
2231 	    {
2232 	    case 'n':
2233 	      return d_make_comp (di, DEMANGLE_COMPONENT_NONTRANSACTION_CLONE,
2234 				  d_encoding (di, 0), NULL);
2235 	    default:
2236 	      /* ??? The proposal is that other letters (such as 'h') stand
2237 		 for different variants of transaction cloning, such as
2238 		 compiling directly for hardware transaction support.  But
2239 		 they still should all be transactional clones of some sort
2240 		 so go ahead and call them that.  */
2241 	    case 't':
2242 	      return d_make_comp (di, DEMANGLE_COMPONENT_TRANSACTION_CLONE,
2243 				  d_encoding (di, 0), NULL);
2244 	    }
2245 
2246 	case 'r':
2247 	  return d_java_resource (di);
2248 
2249 	default:
2250 	  return NULL;
2251 	}
2252     }
2253   else
2254     return NULL;
2255 }
2256 
2257 /* <call-offset> ::= h <nv-offset> _
2258                  ::= v <v-offset> _
2259 
2260    <nv-offset> ::= <(offset) number>
2261 
2262    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
2263 
2264    The C parameter, if not '\0', is a character we just read which is
2265    the start of the <call-offset>.
2266 
2267    We don't display the offset information anywhere.  FIXME: We should
2268    display it in verbose mode.  */
2269 
2270 static int
d_call_offset(struct d_info * di,int c)2271 d_call_offset (struct d_info *di, int c)
2272 {
2273   if (c == '\0')
2274     c = d_next_char (di);
2275 
2276   if (c == 'h')
2277     d_number (di);
2278   else if (c == 'v')
2279     {
2280       d_number (di);
2281       if (! d_check_char (di, '_'))
2282 	return 0;
2283       d_number (di);
2284     }
2285   else
2286     return 0;
2287 
2288   if (! d_check_char (di, '_'))
2289     return 0;
2290 
2291   return 1;
2292 }
2293 
2294 /* <ctor-dtor-name> ::= C1
2295                     ::= C2
2296                     ::= C3
2297                     ::= D0
2298                     ::= D1
2299                     ::= D2
2300 */
2301 
2302 static struct demangle_component *
d_ctor_dtor_name(struct d_info * di)2303 d_ctor_dtor_name (struct d_info *di)
2304 {
2305   if (di->last_name != NULL)
2306     {
2307       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
2308 	di->expansion += di->last_name->u.s_name.len;
2309       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
2310 	di->expansion += di->last_name->u.s_string.len;
2311     }
2312   switch (d_peek_char (di))
2313     {
2314     case 'C':
2315       {
2316 	enum gnu_v3_ctor_kinds kind;
2317 	int inheriting = 0;
2318 
2319 	if (d_peek_next_char (di) == 'I')
2320 	  {
2321 	    inheriting = 1;
2322 	    d_advance (di, 1);
2323 	  }
2324 
2325 	switch (d_peek_next_char (di))
2326 	  {
2327 	  case '1':
2328 	    kind = gnu_v3_complete_object_ctor;
2329 	    break;
2330 	  case '2':
2331 	    kind = gnu_v3_base_object_ctor;
2332 	    break;
2333 	  case '3':
2334 	    kind = gnu_v3_complete_object_allocating_ctor;
2335 	    break;
2336           case '4':
2337 	    kind = gnu_v3_unified_ctor;
2338 	    break;
2339 	  case '5':
2340 	    kind = gnu_v3_object_ctor_group;
2341 	    break;
2342 	  default:
2343 	    return NULL;
2344 	  }
2345 
2346 	d_advance (di, 2);
2347 
2348 	if (inheriting)
2349 	  cplus_demangle_type (di);
2350 
2351 	return d_make_ctor (di, kind, di->last_name);
2352       }
2353 
2354     case 'D':
2355       {
2356 	enum gnu_v3_dtor_kinds kind;
2357 
2358 	switch (d_peek_next_char (di))
2359 	  {
2360 	  case '0':
2361 	    kind = gnu_v3_deleting_dtor;
2362 	    break;
2363 	  case '1':
2364 	    kind = gnu_v3_complete_object_dtor;
2365 	    break;
2366 	  case '2':
2367 	    kind = gnu_v3_base_object_dtor;
2368 	    break;
2369           /*  digit '3' is not used */
2370 	  case '4':
2371 	    kind = gnu_v3_unified_dtor;
2372 	    break;
2373 	  case '5':
2374 	    kind = gnu_v3_object_dtor_group;
2375 	    break;
2376 	  default:
2377 	    return NULL;
2378 	  }
2379 	d_advance (di, 2);
2380 	return d_make_dtor (di, kind, di->last_name);
2381       }
2382 
2383     default:
2384       return NULL;
2385     }
2386 }
2387 
2388 /* True iff we're looking at an order-insensitive type-qualifier, including
2389    function-type-qualifiers.  */
2390 
2391 static int
next_is_type_qual(struct d_info * di)2392 next_is_type_qual (struct d_info *di)
2393 {
2394   char peek = d_peek_char (di);
2395   if (peek == 'r' || peek == 'V' || peek == 'K')
2396     return 1;
2397   if (peek == 'D')
2398     {
2399       peek = d_peek_next_char (di);
2400       if (peek == 'x' || peek == 'o' || peek == 'O' || peek == 'w')
2401 	return 1;
2402     }
2403   return 0;
2404 }
2405 
2406 /* <type> ::= <builtin-type>
2407           ::= <function-type>
2408           ::= <class-enum-type>
2409           ::= <array-type>
2410           ::= <pointer-to-member-type>
2411           ::= <template-param>
2412           ::= <template-template-param> <template-args>
2413           ::= <substitution>
2414           ::= <CV-qualifiers> <type>
2415           ::= P <type>
2416           ::= R <type>
2417           ::= O <type> (C++0x)
2418           ::= C <type>
2419           ::= G <type>
2420           ::= U <source-name> <type>
2421 
2422    <builtin-type> ::= various one letter codes
2423                   ::= u <source-name>
2424 */
2425 
2426 CP_STATIC_IF_GLIBCPP_V3
2427 const struct demangle_builtin_type_info
2428 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
2429 {
2430   /* a */ { NL ("signed char"),	NL ("signed char"),	D_PRINT_DEFAULT },
2431   /* b */ { NL ("bool"),	NL ("boolean"),		D_PRINT_BOOL },
2432   /* c */ { NL ("char"),	NL ("byte"),		D_PRINT_DEFAULT },
2433   /* d */ { NL ("double"),	NL ("double"),		D_PRINT_FLOAT },
2434   /* e */ { NL ("long double"),	NL ("long double"),	D_PRINT_FLOAT },
2435   /* f */ { NL ("float"),	NL ("float"),		D_PRINT_FLOAT },
2436   /* g */ { NL ("__float128"),	NL ("__float128"),	D_PRINT_FLOAT },
2437   /* h */ { NL ("unsigned char"), NL ("unsigned char"),	D_PRINT_DEFAULT },
2438   /* i */ { NL ("int"),		NL ("int"),		D_PRINT_INT },
2439   /* j */ { NL ("unsigned int"), NL ("unsigned"),	D_PRINT_UNSIGNED },
2440   /* k */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2441   /* l */ { NL ("long"),	NL ("long"),		D_PRINT_LONG },
2442   /* m */ { NL ("unsigned long"), NL ("unsigned long"),	D_PRINT_UNSIGNED_LONG },
2443   /* n */ { NL ("__int128"),	NL ("__int128"),	D_PRINT_DEFAULT },
2444   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
2445 	    D_PRINT_DEFAULT },
2446   /* p */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2447   /* q */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2448   /* r */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2449   /* s */ { NL ("short"),	NL ("short"),		D_PRINT_DEFAULT },
2450   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
2451   /* u */ { NULL, 0,		NULL, 0,		D_PRINT_DEFAULT },
2452   /* v */ { NL ("void"),	NL ("void"),		D_PRINT_VOID },
2453   /* w */ { NL ("wchar_t"),	NL ("char"),		D_PRINT_DEFAULT },
2454   /* x */ { NL ("long long"),	NL ("long"),		D_PRINT_LONG_LONG },
2455   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
2456 	    D_PRINT_UNSIGNED_LONG_LONG },
2457   /* z */ { NL ("..."),		NL ("..."),		D_PRINT_DEFAULT },
2458   /* 26 */ { NL ("decimal32"),	NL ("decimal32"),	D_PRINT_DEFAULT },
2459   /* 27 */ { NL ("decimal64"),	NL ("decimal64"),	D_PRINT_DEFAULT },
2460   /* 28 */ { NL ("decimal128"),	NL ("decimal128"),	D_PRINT_DEFAULT },
2461   /* 29 */ { NL ("half"),	NL ("half"),		D_PRINT_FLOAT },
2462   /* 30 */ { NL ("char8_t"),	NL ("char8_t"),		D_PRINT_DEFAULT },
2463   /* 31 */ { NL ("char16_t"),	NL ("char16_t"),	D_PRINT_DEFAULT },
2464   /* 32 */ { NL ("char32_t"),	NL ("char32_t"),	D_PRINT_DEFAULT },
2465   /* 33 */ { NL ("decltype(nullptr)"),	NL ("decltype(nullptr)"),
2466 	     D_PRINT_DEFAULT },
2467 };
2468 
2469 CP_STATIC_IF_GLIBCPP_V3
2470 struct demangle_component *
cplus_demangle_type(struct d_info * di)2471 cplus_demangle_type (struct d_info *di)
2472 {
2473   char peek;
2474   struct demangle_component *ret;
2475   int can_subst;
2476 
2477   /* The ABI specifies that when CV-qualifiers are used, the base type
2478      is substitutable, and the fully qualified type is substitutable,
2479      but the base type with a strict subset of the CV-qualifiers is
2480      not substitutable.  The natural recursive implementation of the
2481      CV-qualifiers would cause subsets to be substitutable, so instead
2482      we pull them all off now.
2483 
2484      FIXME: The ABI says that order-insensitive vendor qualifiers
2485      should be handled in the same way, but we have no way to tell
2486      which vendor qualifiers are order-insensitive and which are
2487      order-sensitive.  So we just assume that they are all
2488      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
2489      __vector, and it treats it as order-sensitive when mangling
2490      names.  */
2491 
2492   if (next_is_type_qual (di))
2493     {
2494       struct demangle_component **pret;
2495 
2496       pret = d_cv_qualifiers (di, &ret, 0);
2497       if (pret == NULL)
2498 	return NULL;
2499       if (d_peek_char (di) == 'F')
2500 	{
2501 	  /* cv-qualifiers before a function type apply to 'this',
2502 	     so avoid adding the unqualified function type to
2503 	     the substitution list.  */
2504 	  *pret = d_function_type (di);
2505 	}
2506       else
2507 	*pret = cplus_demangle_type (di);
2508       if (!*pret)
2509 	return NULL;
2510       if ((*pret)->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
2511 	  || (*pret)->type == DEMANGLE_COMPONENT_REFERENCE_THIS)
2512 	{
2513 	  /* Move the ref-qualifier outside the cv-qualifiers so that
2514 	     they are printed in the right order.  */
2515 	  struct demangle_component *fn = d_left (*pret);
2516 	  d_left (*pret) = ret;
2517 	  ret = *pret;
2518 	  *pret = fn;
2519 	}
2520       if (! d_add_substitution (di, ret))
2521 	return NULL;
2522       return ret;
2523     }
2524 
2525   can_subst = 1;
2526 
2527   peek = d_peek_char (di);
2528   switch (peek)
2529     {
2530     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2531     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
2532     case 'o':                               case 's': case 't':
2533     case 'v': case 'w': case 'x': case 'y': case 'z':
2534       ret = d_make_builtin_type (di,
2535 				 &cplus_demangle_builtin_types[peek - 'a']);
2536       di->expansion += ret->u.s_builtin.type->len;
2537       can_subst = 0;
2538       d_advance (di, 1);
2539       break;
2540 
2541     case 'u':
2542       d_advance (di, 1);
2543       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
2544 			 d_source_name (di), NULL);
2545       break;
2546 
2547     case 'F':
2548       ret = d_function_type (di);
2549       break;
2550 
2551     case 'A':
2552       ret = d_array_type (di);
2553       break;
2554 
2555     case 'M':
2556       ret = d_pointer_to_member_type (di);
2557       break;
2558 
2559     case 'T':
2560       ret = d_template_param (di);
2561       if (d_peek_char (di) == 'I')
2562 	{
2563 	  /* This may be <template-template-param> <template-args>.
2564 	     If this is the type for a conversion operator, we can
2565 	     have a <template-template-param> here only by following
2566 	     a derivation like this:
2567 
2568 	     <nested-name>
2569 	     -> <template-prefix> <template-args>
2570 	     -> <prefix> <template-unqualified-name> <template-args>
2571 	     -> <unqualified-name> <template-unqualified-name> <template-args>
2572 	     -> <source-name> <template-unqualified-name> <template-args>
2573 	     -> <source-name> <operator-name> <template-args>
2574 	     -> <source-name> cv <type> <template-args>
2575 	     -> <source-name> cv <template-template-param> <template-args> <template-args>
2576 
2577 	     where the <template-args> is followed by another.
2578 	     Otherwise, we must have a derivation like this:
2579 
2580 	     <nested-name>
2581 	     -> <template-prefix> <template-args>
2582 	     -> <prefix> <template-unqualified-name> <template-args>
2583 	     -> <unqualified-name> <template-unqualified-name> <template-args>
2584 	     -> <source-name> <template-unqualified-name> <template-args>
2585 	     -> <source-name> <operator-name> <template-args>
2586 	     -> <source-name> cv <type> <template-args>
2587 	     -> <source-name> cv <template-param> <template-args>
2588 
2589 	     where we need to leave the <template-args> to be processed
2590 	     by d_prefix (following the <template-prefix>).
2591 
2592 	     The <template-template-param> part is a substitution
2593 	     candidate.  */
2594 	  if (! di->is_conversion)
2595 	    {
2596 	      if (! d_add_substitution (di, ret))
2597 		return NULL;
2598 	      ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2599 				 d_template_args (di));
2600 	    }
2601 	  else
2602 	    {
2603 	      struct demangle_component *args;
2604 	      struct d_info_checkpoint checkpoint;
2605 
2606 	      d_checkpoint (di, &checkpoint);
2607 	      args = d_template_args (di);
2608 	      if (d_peek_char (di) == 'I')
2609 		{
2610 		  if (! d_add_substitution (di, ret))
2611 		    return NULL;
2612 		  ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2613 				     args);
2614 		}
2615 	      else
2616 		d_backtrack (di, &checkpoint);
2617 	    }
2618 	}
2619       break;
2620 
2621     case 'O':
2622       d_advance (di, 1);
2623       ret = d_make_comp (di, DEMANGLE_COMPONENT_RVALUE_REFERENCE,
2624                          cplus_demangle_type (di), NULL);
2625       break;
2626 
2627     case 'P':
2628       d_advance (di, 1);
2629       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
2630 			 cplus_demangle_type (di), NULL);
2631       break;
2632 
2633     case 'R':
2634       d_advance (di, 1);
2635       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
2636                          cplus_demangle_type (di), NULL);
2637       break;
2638 
2639     case 'C':
2640       d_advance (di, 1);
2641       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
2642 			 cplus_demangle_type (di), NULL);
2643       break;
2644 
2645     case 'G':
2646       d_advance (di, 1);
2647       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
2648 			 cplus_demangle_type (di), NULL);
2649       break;
2650 
2651     case 'U':
2652       d_advance (di, 1);
2653       ret = d_source_name (di);
2654       if (d_peek_char (di) == 'I')
2655 	ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2656 			   d_template_args (di));
2657       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
2658 			 cplus_demangle_type (di), ret);
2659       break;
2660 
2661     case 'D':
2662       can_subst = 0;
2663       d_advance (di, 1);
2664       peek = d_next_char (di);
2665       switch (peek)
2666 	{
2667 	case 'T':
2668 	case 't':
2669 	  /* decltype (expression) */
2670 	  ret = d_make_comp (di, DEMANGLE_COMPONENT_DECLTYPE,
2671 			     d_expression (di), NULL);
2672 	  if (ret && d_next_char (di) != 'E')
2673 	    ret = NULL;
2674 	  can_subst = 1;
2675 	  break;
2676 
2677 	case 'p':
2678 	  /* Pack expansion.  */
2679 	  ret = d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
2680 			     cplus_demangle_type (di), NULL);
2681 	  can_subst = 1;
2682 	  break;
2683 
2684 	case 'a':
2685 	  /* auto */
2686 	  ret = d_make_name (di, "auto", 4);
2687 	  break;
2688 	case 'c':
2689 	  /* decltype(auto) */
2690 	  ret = d_make_name (di, "decltype(auto)", 14);
2691 	  break;
2692 
2693 	case 'f':
2694 	  /* 32-bit decimal floating point */
2695 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[26]);
2696 	  di->expansion += ret->u.s_builtin.type->len;
2697 	  break;
2698 	case 'd':
2699 	  /* 64-bit DFP */
2700 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[27]);
2701 	  di->expansion += ret->u.s_builtin.type->len;
2702 	  break;
2703 	case 'e':
2704 	  /* 128-bit DFP */
2705 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[28]);
2706 	  di->expansion += ret->u.s_builtin.type->len;
2707 	  break;
2708 	case 'h':
2709 	  /* 16-bit half-precision FP */
2710 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[29]);
2711 	  di->expansion += ret->u.s_builtin.type->len;
2712 	  break;
2713 	case 'u':
2714 	  /* char8_t */
2715 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[30]);
2716 	  di->expansion += ret->u.s_builtin.type->len;
2717 	  break;
2718 	case 's':
2719 	  /* char16_t */
2720 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[31]);
2721 	  di->expansion += ret->u.s_builtin.type->len;
2722 	  break;
2723 	case 'i':
2724 	  /* char32_t */
2725 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[32]);
2726 	  di->expansion += ret->u.s_builtin.type->len;
2727 	  break;
2728 
2729 	case 'F':
2730 	  /* Fixed point types. DF<int bits><length><fract bits><sat>  */
2731 	  ret = d_make_empty (di);
2732 	  ret->type = DEMANGLE_COMPONENT_FIXED_TYPE;
2733 	  if ((ret->u.s_fixed.accum = IS_DIGIT (d_peek_char (di))))
2734 	    /* For demangling we don't care about the bits.  */
2735 	    d_number (di);
2736 	  ret->u.s_fixed.length = cplus_demangle_type (di);
2737 	  if (ret->u.s_fixed.length == NULL)
2738 	    return NULL;
2739 	  d_number (di);
2740 	  peek = d_next_char (di);
2741 	  ret->u.s_fixed.sat = (peek == 's');
2742 	  break;
2743 
2744 	case 'v':
2745 	  ret = d_vector_type (di);
2746 	  can_subst = 1;
2747 	  break;
2748 
2749         case 'n':
2750           /* decltype(nullptr) */
2751 	  ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[33]);
2752 	  di->expansion += ret->u.s_builtin.type->len;
2753 	  break;
2754 
2755 	default:
2756 	  return NULL;
2757 	}
2758       break;
2759 
2760     default:
2761       return d_class_enum_type (di, 1);
2762     }
2763 
2764   if (can_subst)
2765     {
2766       if (! d_add_substitution (di, ret))
2767 	return NULL;
2768     }
2769 
2770   return ret;
2771 }
2772 
2773 /* <CV-qualifiers> ::= [r] [V] [K] [Dx] */
2774 
2775 static struct demangle_component **
d_cv_qualifiers(struct d_info * di,struct demangle_component ** pret,int member_fn)2776 d_cv_qualifiers (struct d_info *di,
2777                  struct demangle_component **pret, int member_fn)
2778 {
2779   struct demangle_component **pstart;
2780   char peek;
2781 
2782   pstart = pret;
2783   peek = d_peek_char (di);
2784   while (next_is_type_qual (di))
2785     {
2786       enum demangle_component_type t;
2787       struct demangle_component *right = NULL;
2788 
2789       d_advance (di, 1);
2790       if (peek == 'r')
2791 	{
2792 	  t = (member_fn
2793 	       ? DEMANGLE_COMPONENT_RESTRICT_THIS
2794 	       : DEMANGLE_COMPONENT_RESTRICT);
2795 	  di->expansion += sizeof "restrict";
2796 	}
2797       else if (peek == 'V')
2798 	{
2799 	  t = (member_fn
2800 	       ? DEMANGLE_COMPONENT_VOLATILE_THIS
2801 	       : DEMANGLE_COMPONENT_VOLATILE);
2802 	  di->expansion += sizeof "volatile";
2803 	}
2804       else if (peek == 'K')
2805 	{
2806 	  t = (member_fn
2807 	       ? DEMANGLE_COMPONENT_CONST_THIS
2808 	       : DEMANGLE_COMPONENT_CONST);
2809 	  di->expansion += sizeof "const";
2810 	}
2811       else
2812 	{
2813 	  peek = d_next_char (di);
2814 	  if (peek == 'x')
2815 	    {
2816 	      t = DEMANGLE_COMPONENT_TRANSACTION_SAFE;
2817 	      di->expansion += sizeof "transaction_safe";
2818 	    }
2819 	  else if (peek == 'o'
2820 		   || peek == 'O')
2821 	    {
2822 	      t = DEMANGLE_COMPONENT_NOEXCEPT;
2823 	      di->expansion += sizeof "noexcept";
2824 	      if (peek == 'O')
2825 		{
2826 		  right = d_expression (di);
2827 		  if (right == NULL)
2828 		    return NULL;
2829 		  if (! d_check_char (di, 'E'))
2830 		    return NULL;
2831 		}
2832 	    }
2833 	  else if (peek == 'w')
2834 	    {
2835 	      t = DEMANGLE_COMPONENT_THROW_SPEC;
2836 	      di->expansion += sizeof "throw";
2837 	      right = d_parmlist (di);
2838 	      if (right == NULL)
2839 		return NULL;
2840 	      if (! d_check_char (di, 'E'))
2841 		return NULL;
2842 	    }
2843 	  else
2844 	    return NULL;
2845 	}
2846 
2847       *pret = d_make_comp (di, t, NULL, right);
2848       if (*pret == NULL)
2849 	return NULL;
2850       pret = &d_left (*pret);
2851 
2852       peek = d_peek_char (di);
2853     }
2854 
2855   if (!member_fn && peek == 'F')
2856     {
2857       while (pstart != pret)
2858 	{
2859 	  switch ((*pstart)->type)
2860 	    {
2861 	    case DEMANGLE_COMPONENT_RESTRICT:
2862 	      (*pstart)->type = DEMANGLE_COMPONENT_RESTRICT_THIS;
2863 	      break;
2864 	    case DEMANGLE_COMPONENT_VOLATILE:
2865 	      (*pstart)->type = DEMANGLE_COMPONENT_VOLATILE_THIS;
2866 	      break;
2867 	    case DEMANGLE_COMPONENT_CONST:
2868 	      (*pstart)->type = DEMANGLE_COMPONENT_CONST_THIS;
2869 	      break;
2870 	    default:
2871 	      break;
2872 	    }
2873 	  pstart = &d_left (*pstart);
2874 	}
2875     }
2876 
2877   return pret;
2878 }
2879 
2880 /* <ref-qualifier> ::= R
2881                    ::= O */
2882 
2883 static struct demangle_component *
d_ref_qualifier(struct d_info * di,struct demangle_component * sub)2884 d_ref_qualifier (struct d_info *di, struct demangle_component *sub)
2885 {
2886   struct demangle_component *ret = sub;
2887   char peek;
2888 
2889   peek = d_peek_char (di);
2890   if (peek == 'R' || peek == 'O')
2891     {
2892       enum demangle_component_type t;
2893       if (peek == 'R')
2894 	{
2895 	  t = DEMANGLE_COMPONENT_REFERENCE_THIS;
2896 	  di->expansion += sizeof "&";
2897 	}
2898       else
2899 	{
2900 	  t = DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS;
2901 	  di->expansion += sizeof "&&";
2902 	}
2903       d_advance (di, 1);
2904 
2905       ret = d_make_comp (di, t, ret, NULL);
2906     }
2907 
2908   return ret;
2909 }
2910 
2911 /* <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] [T] E  */
2912 
2913 static struct demangle_component *
d_function_type(struct d_info * di)2914 d_function_type (struct d_info *di)
2915 {
2916   struct demangle_component *ret = NULL;
2917 
2918   if ((di->options & DMGL_NO_RECURSE_LIMIT) == 0)
2919     {
2920       if (di->recursion_level > DEMANGLE_RECURSION_LIMIT)
2921 	/* FIXME: There ought to be a way to report
2922 	   that the recursion limit has been reached.  */
2923 	return NULL;
2924 
2925       di->recursion_level ++;
2926     }
2927 
2928   if (d_check_char (di, 'F'))
2929     {
2930       if (d_peek_char (di) == 'Y')
2931 	{
2932 	  /* Function has C linkage.  We don't print this information.
2933 	     FIXME: We should print it in verbose mode.  */
2934 	  d_advance (di, 1);
2935 	}
2936       ret = d_bare_function_type (di, 1);
2937       ret = d_ref_qualifier (di, ret);
2938 
2939       if (! d_check_char (di, 'E'))
2940 	ret = NULL;
2941     }
2942 
2943   if ((di->options & DMGL_NO_RECURSE_LIMIT) == 0)
2944     di->recursion_level --;
2945   return ret;
2946 }
2947 
2948 /* <type>+ */
2949 
2950 static struct demangle_component *
d_parmlist(struct d_info * di)2951 d_parmlist (struct d_info *di)
2952 {
2953   struct demangle_component *tl;
2954   struct demangle_component **ptl;
2955 
2956   tl = NULL;
2957   ptl = &tl;
2958   while (1)
2959     {
2960       struct demangle_component *type;
2961 
2962       char peek = d_peek_char (di);
2963       if (peek == '\0' || peek == 'E' || peek == '.')
2964 	break;
2965       if ((peek == 'R' || peek == 'O')
2966 	  && d_peek_next_char (di) == 'E')
2967 	/* Function ref-qualifier, not a ref prefix for a parameter type.  */
2968 	break;
2969       type = cplus_demangle_type (di);
2970       if (type == NULL)
2971 	return NULL;
2972       *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2973       if (*ptl == NULL)
2974 	return NULL;
2975       ptl = &d_right (*ptl);
2976     }
2977 
2978   /* There should be at least one parameter type besides the optional
2979      return type.  A function which takes no arguments will have a
2980      single parameter type void.  */
2981   if (tl == NULL)
2982     return NULL;
2983 
2984   /* If we have a single parameter type void, omit it.  */
2985   if (d_right (tl) == NULL
2986       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2987       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2988     {
2989       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2990       d_left (tl) = NULL;
2991     }
2992 
2993   return tl;
2994 }
2995 
2996 /* <bare-function-type> ::= [J]<type>+  */
2997 
2998 static struct demangle_component *
d_bare_function_type(struct d_info * di,int has_return_type)2999 d_bare_function_type (struct d_info *di, int has_return_type)
3000 {
3001   struct demangle_component *return_type;
3002   struct demangle_component *tl;
3003   char peek;
3004 
3005   /* Detect special qualifier indicating that the first argument
3006      is the return type.  */
3007   peek = d_peek_char (di);
3008   if (peek == 'J')
3009     {
3010       d_advance (di, 1);
3011       has_return_type = 1;
3012     }
3013 
3014   if (has_return_type)
3015     {
3016       return_type = cplus_demangle_type (di);
3017       if (return_type == NULL)
3018 	return NULL;
3019     }
3020   else
3021     return_type = NULL;
3022 
3023   tl = d_parmlist (di);
3024   if (tl == NULL)
3025     return NULL;
3026 
3027   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE,
3028 		      return_type, tl);
3029 }
3030 
3031 /* <class-enum-type> ::= <name>  */
3032 
3033 static struct demangle_component *
d_class_enum_type(struct d_info * di,int substable)3034 d_class_enum_type (struct d_info *di, int substable)
3035 {
3036   return d_name (di, substable);
3037 }
3038 
3039 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
3040                 ::= A [<(dimension) expression>] _ <(element) type>
3041 */
3042 
3043 static struct demangle_component *
d_array_type(struct d_info * di)3044 d_array_type (struct d_info *di)
3045 {
3046   char peek;
3047   struct demangle_component *dim;
3048 
3049   if (! d_check_char (di, 'A'))
3050     return NULL;
3051 
3052   peek = d_peek_char (di);
3053   if (peek == '_')
3054     dim = NULL;
3055   else if (IS_DIGIT (peek))
3056     {
3057       const char *s;
3058 
3059       s = d_str (di);
3060       do
3061 	{
3062 	  d_advance (di, 1);
3063 	  peek = d_peek_char (di);
3064 	}
3065       while (IS_DIGIT (peek));
3066       dim = d_make_name (di, s, d_str (di) - s);
3067       if (dim == NULL)
3068 	return NULL;
3069     }
3070   else
3071     {
3072       dim = d_expression (di);
3073       if (dim == NULL)
3074 	return NULL;
3075     }
3076 
3077   if (! d_check_char (di, '_'))
3078     return NULL;
3079 
3080   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
3081 		      cplus_demangle_type (di));
3082 }
3083 
3084 /* <vector-type> ::= Dv <number> _ <type>
3085                  ::= Dv _ <expression> _ <type> */
3086 
3087 static struct demangle_component *
d_vector_type(struct d_info * di)3088 d_vector_type (struct d_info *di)
3089 {
3090   char peek;
3091   struct demangle_component *dim;
3092 
3093   peek = d_peek_char (di);
3094   if (peek == '_')
3095     {
3096       d_advance (di, 1);
3097       dim = d_expression (di);
3098     }
3099   else
3100     dim = d_number_component (di);
3101 
3102   if (dim == NULL)
3103     return NULL;
3104 
3105   if (! d_check_char (di, '_'))
3106     return NULL;
3107 
3108   return d_make_comp (di, DEMANGLE_COMPONENT_VECTOR_TYPE, dim,
3109 		      cplus_demangle_type (di));
3110 }
3111 
3112 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
3113 
3114 static struct demangle_component *
d_pointer_to_member_type(struct d_info * di)3115 d_pointer_to_member_type (struct d_info *di)
3116 {
3117   struct demangle_component *cl;
3118   struct demangle_component *mem;
3119 
3120   if (! d_check_char (di, 'M'))
3121     return NULL;
3122 
3123   cl = cplus_demangle_type (di);
3124   if (cl == NULL)
3125     return NULL;
3126 
3127   /* The ABI says, "The type of a non-static member function is considered
3128      to be different, for the purposes of substitution, from the type of a
3129      namespace-scope or static member function whose type appears
3130      similar. The types of two non-static member functions are considered
3131      to be different, for the purposes of substitution, if the functions
3132      are members of different classes. In other words, for the purposes of
3133      substitution, the class of which the function is a member is
3134      considered part of the type of function."
3135 
3136      For a pointer to member function, this call to cplus_demangle_type
3137      will end up adding a (possibly qualified) non-member function type to
3138      the substitution table, which is not correct; however, the member
3139      function type will never be used in a substitution, so putting the
3140      wrong type in the substitution table is harmless.  */
3141 
3142   mem = cplus_demangle_type (di);
3143   if (mem == NULL)
3144     return NULL;
3145 
3146   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
3147 }
3148 
3149 /* <non-negative number> _ */
3150 
3151 static int
d_compact_number(struct d_info * di)3152 d_compact_number (struct d_info *di)
3153 {
3154   int num;
3155   if (d_peek_char (di) == '_')
3156     num = 0;
3157   else if (d_peek_char (di) == 'n')
3158     return -1;
3159   else
3160     num = d_number (di) + 1;
3161 
3162   if (num < 0 || ! d_check_char (di, '_'))
3163     return -1;
3164   return num;
3165 }
3166 
3167 /* <template-param> ::= T_
3168                     ::= T <(parameter-2 non-negative) number> _
3169 */
3170 
3171 static struct demangle_component *
d_template_param(struct d_info * di)3172 d_template_param (struct d_info *di)
3173 {
3174   int param;
3175 
3176   if (! d_check_char (di, 'T'))
3177     return NULL;
3178 
3179   param = d_compact_number (di);
3180   if (param < 0)
3181     return NULL;
3182 
3183   return d_make_template_param (di, param);
3184 }
3185 
3186 /* <template-args> ::= I <template-arg>+ E  */
3187 
3188 static struct demangle_component *
d_template_args(struct d_info * di)3189 d_template_args (struct d_info *di)
3190 {
3191   if (d_peek_char (di) != 'I'
3192       && d_peek_char (di) != 'J')
3193     return NULL;
3194   d_advance (di, 1);
3195 
3196   return d_template_args_1 (di);
3197 }
3198 
3199 /* <template-arg>* E  */
3200 
3201 static struct demangle_component *
d_template_args_1(struct d_info * di)3202 d_template_args_1 (struct d_info *di)
3203 {
3204   struct demangle_component *hold_last_name;
3205   struct demangle_component *al;
3206   struct demangle_component **pal;
3207 
3208   /* Preserve the last name we saw--don't let the template arguments
3209      clobber it, as that would give us the wrong name for a subsequent
3210      constructor or destructor.  */
3211   hold_last_name = di->last_name;
3212 
3213   if (d_peek_char (di) == 'E')
3214     {
3215       /* An argument pack can be empty.  */
3216       d_advance (di, 1);
3217       return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, NULL, NULL);
3218     }
3219 
3220   al = NULL;
3221   pal = &al;
3222   while (1)
3223     {
3224       struct demangle_component *a;
3225 
3226       a = d_template_arg (di);
3227       if (a == NULL)
3228 	return NULL;
3229 
3230       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
3231       if (*pal == NULL)
3232 	return NULL;
3233       pal = &d_right (*pal);
3234 
3235       if (d_peek_char (di) == 'E')
3236 	{
3237 	  d_advance (di, 1);
3238 	  break;
3239 	}
3240     }
3241 
3242   di->last_name = hold_last_name;
3243 
3244   return al;
3245 }
3246 
3247 /* <template-arg> ::= <type>
3248                   ::= X <expression> E
3249                   ::= <expr-primary>
3250 */
3251 
3252 static struct demangle_component *
d_template_arg(struct d_info * di)3253 d_template_arg (struct d_info *di)
3254 {
3255   struct demangle_component *ret;
3256 
3257   switch (d_peek_char (di))
3258     {
3259     case 'X':
3260       d_advance (di, 1);
3261       ret = d_expression (di);
3262       if (! d_check_char (di, 'E'))
3263 	return NULL;
3264       return ret;
3265 
3266     case 'L':
3267       return d_expr_primary (di);
3268 
3269     case 'I':
3270     case 'J':
3271       /* An argument pack.  */
3272       return d_template_args (di);
3273 
3274     default:
3275       return cplus_demangle_type (di);
3276     }
3277 }
3278 
3279 /* Parse a sequence of expressions until we hit the terminator
3280    character.  */
3281 
3282 static struct demangle_component *
d_exprlist(struct d_info * di,char terminator)3283 d_exprlist (struct d_info *di, char terminator)
3284 {
3285   struct demangle_component *list = NULL;
3286   struct demangle_component **p = &list;
3287 
3288   if (d_peek_char (di) == terminator)
3289     {
3290       d_advance (di, 1);
3291       return d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, NULL, NULL);
3292     }
3293 
3294   while (1)
3295     {
3296       struct demangle_component *arg = d_expression (di);
3297       if (arg == NULL)
3298 	return NULL;
3299 
3300       *p = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, arg, NULL);
3301       if (*p == NULL)
3302 	return NULL;
3303       p = &d_right (*p);
3304 
3305       if (d_peek_char (di) == terminator)
3306 	{
3307 	  d_advance (di, 1);
3308 	  break;
3309 	}
3310     }
3311 
3312   return list;
3313 }
3314 
3315 /* Returns nonzero iff OP is an operator for a C++ cast: const_cast,
3316    dynamic_cast, static_cast or reinterpret_cast.  */
3317 
3318 static int
op_is_new_cast(struct demangle_component * op)3319 op_is_new_cast (struct demangle_component *op)
3320 {
3321   const char *code = op->u.s_operator.op->code;
3322   return (code[1] == 'c'
3323 	  && (code[0] == 's' || code[0] == 'd'
3324 	      || code[0] == 'c' || code[0] == 'r'));
3325 }
3326 
3327 /*   <unresolved-name> ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
3328        ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
3329        # T::N::x /decltype(p)::N::x
3330        ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3331        # A::x, N::y, A<T>::z; "gs" means leading "::"
3332        ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3333 
3334      "gs" is handled elsewhere, as a unary operator.  */
3335 
3336 static struct demangle_component *
d_unresolved_name(struct d_info * di)3337 d_unresolved_name (struct d_info *di)
3338 {
3339   struct demangle_component *type;
3340   struct demangle_component *name;
3341   char peek;
3342 
3343   /* Consume the "sr".  */
3344   d_advance (di, 2);
3345 
3346   peek = d_peek_char (di);
3347   if (di->unresolved_name_state
3348       && (IS_DIGIT (peek)
3349 	  || IS_LOWER (peek)
3350 	  || peek == 'C'
3351 	  || peek == 'U'
3352 	  || peek == 'L'))
3353     {
3354       /* The third production is ambiguous with the old unresolved-name syntax
3355 	 of <type> <base-unresolved-name>; in the old mangling, A::x was mangled
3356 	 as sr1A1x, now sr1AE1x.  So we first try to demangle using the new
3357 	 mangling, then with the old if that fails.  */
3358       di->unresolved_name_state = -1;
3359       type = d_prefix (di, 0);
3360       if (d_peek_char (di) == 'E')
3361 	d_advance (di, 1);
3362     }
3363   else
3364     type = cplus_demangle_type (di);
3365   name = d_unqualified_name (di, type, NULL);
3366   if (d_peek_char (di) == 'I')
3367     name = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3368 			d_template_args (di));
3369   return name;
3370 }
3371 
3372 /* <expression> ::= <(unary) operator-name> <expression>
3373                 ::= <(binary) operator-name> <expression> <expression>
3374                 ::= <(trinary) operator-name> <expression> <expression> <expression>
3375 		::= cl <expression>+ E
3376                 ::= st <type>
3377                 ::= <template-param>
3378 		::= u <source-name> <template-arg>* E # vendor extended expression
3379 		::= <unresolved-name>
3380                 ::= <expr-primary>
3381 
3382   <braced-expression> ::= <expression>
3383 		      ::= di <field source-name> <braced-expression>	# .name = expr
3384 		      ::= dx <index expression> <braced-expression>	# [expr] = expr
3385 		      ::= dX <range begin expression> <range end expression> <braced-expression>
3386 									# [expr ... expr] = expr
3387 */
3388 
3389 static struct demangle_component *
d_expression_1(struct d_info * di)3390 d_expression_1 (struct d_info *di)
3391 {
3392   char peek;
3393 
3394   peek = d_peek_char (di);
3395   if (peek == 'L')
3396     return d_expr_primary (di);
3397   else if (peek == 'T')
3398     return d_template_param (di);
3399   else if (peek == 's' && d_peek_next_char (di) == 'r')
3400     return d_unresolved_name (di);
3401   else if (peek == 's' && d_peek_next_char (di) == 'p')
3402     {
3403       d_advance (di, 2);
3404       return d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
3405 			  d_expression_1 (di), NULL);
3406     }
3407   else if (peek == 'f' && d_peek_next_char (di) == 'p')
3408     {
3409       /* Function parameter used in a late-specified return type.  */
3410       int index;
3411       d_advance (di, 2);
3412       if (d_peek_char (di) == 'T')
3413 	{
3414 	  /* 'this' parameter.  */
3415 	  d_advance (di, 1);
3416 	  index = 0;
3417 	}
3418       else
3419 	{
3420 	  index = d_compact_number (di);
3421 	  if (index == INT_MAX || index == -1)
3422 	    return NULL;
3423 	  index++;
3424 	}
3425       return d_make_function_param (di, index);
3426     }
3427   else if (IS_DIGIT (peek)
3428 	   || (peek == 'o' && d_peek_next_char (di) == 'n'))
3429     {
3430       /* We can get an unqualified name as an expression in the case of
3431          a dependent function call, i.e. decltype(f(t)).  */
3432       struct demangle_component *name;
3433 
3434       if (peek == 'o')
3435 	/* operator-function-id, i.e. operator+(t).  */
3436 	d_advance (di, 2);
3437 
3438       name = d_unqualified_name (di, NULL, NULL);
3439       if (name == NULL)
3440 	return NULL;
3441       if (d_peek_char (di) == 'I')
3442 	return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3443 			    d_template_args (di));
3444       else
3445 	return name;
3446     }
3447   else if ((peek == 'i' || peek == 't')
3448 	   && d_peek_next_char (di) == 'l')
3449     {
3450       /* Brace-enclosed initializer list, untyped or typed.  */
3451       struct demangle_component *type = NULL;
3452       d_advance (di, 2);
3453       if (peek == 't')
3454 	type = cplus_demangle_type (di);
3455       if (!d_peek_char (di) || !d_peek_next_char (di))
3456 	return NULL;
3457       return d_make_comp (di, DEMANGLE_COMPONENT_INITIALIZER_LIST,
3458 			  type, d_exprlist (di, 'E'));
3459     }
3460   else if (peek == 'u')
3461     {
3462       /* A vendor extended expression.  */
3463       struct demangle_component *name, *args;
3464       d_advance (di, 1);
3465       name = d_source_name (di);
3466       args = d_template_args_1 (di);
3467       return d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_EXPR, name, args);
3468     }
3469   else
3470     {
3471       struct demangle_component *op;
3472       const char *code = NULL;
3473       int args;
3474 
3475       op = d_operator_name (di);
3476       if (op == NULL)
3477 	return NULL;
3478 
3479       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
3480 	{
3481 	  code = op->u.s_operator.op->code;
3482 	  di->expansion += op->u.s_operator.op->len - 2;
3483 	  if (strcmp (code, "st") == 0)
3484 	    return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3485 				cplus_demangle_type (di));
3486 	}
3487 
3488       switch (op->type)
3489 	{
3490 	default:
3491 	  return NULL;
3492 	case DEMANGLE_COMPONENT_OPERATOR:
3493 	  args = op->u.s_operator.op->args;
3494 	  break;
3495 	case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3496 	  args = op->u.s_extended_operator.args;
3497 	  break;
3498 	case DEMANGLE_COMPONENT_CAST:
3499 	  args = 1;
3500 	  break;
3501 	}
3502 
3503       switch (args)
3504 	{
3505 	case 0:
3506 	  return d_make_comp (di, DEMANGLE_COMPONENT_NULLARY, op, NULL);
3507 
3508 	case 1:
3509 	  {
3510 	    struct demangle_component *operand;
3511 	    int suffix = 0;
3512 
3513 	    if (code && (code[0] == 'p' || code[0] == 'm')
3514 		&& code[1] == code[0])
3515 	      /* pp_ and mm_ are the prefix variants.  */
3516 	      suffix = !d_check_char (di, '_');
3517 
3518 	    if (op->type == DEMANGLE_COMPONENT_CAST
3519 		&& d_check_char (di, '_'))
3520 	      operand = d_exprlist (di, 'E');
3521 	    else if (code && !strcmp (code, "sP"))
3522 	      operand = d_template_args_1 (di);
3523 	    else
3524 	      operand = d_expression_1 (di);
3525 
3526 	    if (suffix)
3527 	      /* Indicate the suffix variant for d_print_comp.  */
3528 	      operand = d_make_comp (di, DEMANGLE_COMPONENT_BINARY_ARGS,
3529 				     operand, operand);
3530 
3531 	    return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op, operand);
3532 	  }
3533 	case 2:
3534 	  {
3535 	    struct demangle_component *left;
3536 	    struct demangle_component *right;
3537 
3538 	    if (code == NULL)
3539 	      return NULL;
3540 	    if (op_is_new_cast (op))
3541 	      left = cplus_demangle_type (di);
3542 	    else if (code[0] == 'f')
3543 	      /* fold-expression.  */
3544 	      left = d_operator_name (di);
3545 	    else if (!strcmp (code, "di"))
3546 	      left = d_unqualified_name (di, NULL, NULL);
3547 	    else
3548 	      left = d_expression_1 (di);
3549 	    if (!strcmp (code, "cl"))
3550 	      right = d_exprlist (di, 'E');
3551 	    else if (!strcmp (code, "dt") || !strcmp (code, "pt"))
3552 	      {
3553 		peek = d_peek_char (di);
3554 		/* These codes start a qualified name.  */
3555 		if ((peek == 'g' && d_peek_next_char (di) == 's')
3556 		    || (peek == 's' && d_peek_next_char (di) == 'r'))
3557 		  right = d_expression_1 (di);
3558 		else
3559 		  {
3560 		    /* Otherwise it's an unqualified name.  We use
3561 		       d_unqualified_name rather than d_expression_1 here for
3562 		       old mangled names that didn't add 'on' before operator
3563 		       names.  */
3564 		    right = d_unqualified_name (di, NULL, NULL);
3565 		    if (d_peek_char (di) == 'I')
3566 		      right = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE,
3567 					   right, d_template_args (di));
3568 		  }
3569 	      }
3570 	    else
3571 	      right = d_expression_1 (di);
3572 
3573 	    return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
3574 				d_make_comp (di,
3575 					     DEMANGLE_COMPONENT_BINARY_ARGS,
3576 					     left, right));
3577 	  }
3578 	case 3:
3579 	  {
3580 	    struct demangle_component *first;
3581 	    struct demangle_component *second;
3582 	    struct demangle_component *third;
3583 
3584 	    if (code == NULL)
3585 	      return NULL;
3586 	    else if (!strcmp (code, "qu")
3587 		     || !strcmp (code, "dX"))
3588 	      {
3589 		/* ?: expression.  */
3590 		first = d_expression_1 (di);
3591 		second = d_expression_1 (di);
3592 		third = d_expression_1 (di);
3593 		if (third == NULL)
3594 		  return NULL;
3595 	      }
3596 	    else if (code[0] == 'f')
3597 	      {
3598 		/* fold-expression.  */
3599 		first = d_operator_name (di);
3600 		second = d_expression_1 (di);
3601 		third = d_expression_1 (di);
3602 		if (third == NULL)
3603 		  return NULL;
3604 	      }
3605 	    else if (code[0] == 'n')
3606 	      {
3607 		/* new-expression.  */
3608 		if (code[1] != 'w' && code[1] != 'a')
3609 		  return NULL;
3610 		first = d_exprlist (di, '_');
3611 		second = cplus_demangle_type (di);
3612 		if (d_peek_char (di) == 'E')
3613 		  {
3614 		    d_advance (di, 1);
3615 		    third = NULL;
3616 		  }
3617 		else if (d_peek_char (di) == 'p'
3618 			 && d_peek_next_char (di) == 'i')
3619 		  {
3620 		    /* Parenthesized initializer.  */
3621 		    d_advance (di, 2);
3622 		    third = d_exprlist (di, 'E');
3623 		  }
3624 		else if (d_peek_char (di) == 'i'
3625 			 && d_peek_next_char (di) == 'l')
3626 		  /* initializer-list.  */
3627 		  third = d_expression_1 (di);
3628 		else
3629 		  return NULL;
3630 	      }
3631 	    else
3632 	      return NULL;
3633 	    return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
3634 				d_make_comp (di,
3635 					     DEMANGLE_COMPONENT_TRINARY_ARG1,
3636 					     first,
3637 					     d_make_comp (di,
3638 							  DEMANGLE_COMPONENT_TRINARY_ARG2,
3639 							  second, third)));
3640 	  }
3641 	default:
3642 	  return NULL;
3643 	}
3644     }
3645 }
3646 
3647 static struct demangle_component *
d_expression(struct d_info * di)3648 d_expression (struct d_info *di)
3649 {
3650   struct demangle_component *ret;
3651   int was_expression = di->is_expression;
3652 
3653   di->is_expression = 1;
3654   ret = d_expression_1 (di);
3655   di->is_expression = was_expression;
3656   return ret;
3657 }
3658 
3659 /* <expr-primary> ::= L <type> <(value) number> E
3660                   ::= L <type> <(value) float> E
3661                   ::= L <mangled-name> E
3662 */
3663 
3664 static struct demangle_component *
d_expr_primary(struct d_info * di)3665 d_expr_primary (struct d_info *di)
3666 {
3667   struct demangle_component *ret;
3668 
3669   if (! d_check_char (di, 'L'))
3670     return NULL;
3671   if (d_peek_char (di) == '_'
3672       /* Workaround for G++ bug; see comment in write_template_arg.  */
3673       || d_peek_char (di) == 'Z')
3674     ret = cplus_demangle_mangled_name (di, 0);
3675   else
3676     {
3677       struct demangle_component *type;
3678       enum demangle_component_type t;
3679       const char *s;
3680 
3681       type = cplus_demangle_type (di);
3682       if (type == NULL)
3683 	return NULL;
3684 
3685       /* If we have a type we know how to print, we aren't going to
3686 	 print the type name itself.  */
3687       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
3688 	  && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
3689 	di->expansion -= type->u.s_builtin.type->len;
3690 
3691       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
3692 	  && strcmp (type->u.s_builtin.type->name,
3693 		     cplus_demangle_builtin_types[33].name) == 0)
3694 	{
3695 	  if (d_peek_char (di) == 'E')
3696 	    {
3697 	      d_advance (di, 1);
3698 	      return type;
3699 	    }
3700 	}
3701 
3702       /* Rather than try to interpret the literal value, we just
3703 	 collect it as a string.  Note that it's possible to have a
3704 	 floating point literal here.  The ABI specifies that the
3705 	 format of such literals is machine independent.  That's fine,
3706 	 but what's not fine is that versions of g++ up to 3.2 with
3707 	 -fabi-version=1 used upper case letters in the hex constant,
3708 	 and dumped out gcc's internal representation.  That makes it
3709 	 hard to tell where the constant ends, and hard to dump the
3710 	 constant in any readable form anyhow.  We don't attempt to
3711 	 handle these cases.  */
3712 
3713       t = DEMANGLE_COMPONENT_LITERAL;
3714       if (d_peek_char (di) == 'n')
3715 	{
3716 	  t = DEMANGLE_COMPONENT_LITERAL_NEG;
3717 	  d_advance (di, 1);
3718 	}
3719       s = d_str (di);
3720       while (d_peek_char (di) != 'E')
3721 	{
3722 	  if (d_peek_char (di) == '\0')
3723 	    return NULL;
3724 	  d_advance (di, 1);
3725 	}
3726       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
3727     }
3728   if (! d_check_char (di, 'E'))
3729     return NULL;
3730   return ret;
3731 }
3732 
3733 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
3734                 ::= Z <(function) encoding> E s [<discriminator>]
3735                 ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
3736 */
3737 
3738 static struct demangle_component *
d_local_name(struct d_info * di)3739 d_local_name (struct d_info *di)
3740 {
3741   struct demangle_component *function;
3742   struct demangle_component *name;
3743 
3744   if (! d_check_char (di, 'Z'))
3745     return NULL;
3746 
3747   function = d_encoding (di, 0);
3748   if (!function)
3749     return NULL;
3750 
3751   if (! d_check_char (di, 'E'))
3752     return NULL;
3753 
3754   if (d_peek_char (di) == 's')
3755     {
3756       d_advance (di, 1);
3757       if (! d_discriminator (di))
3758 	return NULL;
3759       name = d_make_name (di, "string literal", sizeof "string literal" - 1);
3760     }
3761   else
3762     {
3763       int num = -1;
3764 
3765       if (d_peek_char (di) == 'd')
3766 	{
3767 	  /* Default argument scope: d <number> _.  */
3768 	  d_advance (di, 1);
3769 	  num = d_compact_number (di);
3770 	  if (num < 0)
3771 	    return NULL;
3772 	}
3773 
3774       name = d_name (di, 0);
3775 
3776       if (name
3777 	  /* Lambdas and unnamed types have internal discriminators
3778 	     and are not functions.  */
3779 	  && name->type != DEMANGLE_COMPONENT_LAMBDA
3780 	  && name->type != DEMANGLE_COMPONENT_UNNAMED_TYPE)
3781 	{
3782 	  /* Read and ignore an optional discriminator.  */
3783 	  if (! d_discriminator (di))
3784 	    return NULL;
3785 	}
3786 
3787       if (num >= 0)
3788 	name = d_make_default_arg (di, num, name);
3789     }
3790 
3791   /* Elide the return type of the containing function so as to not
3792      confuse the user thinking it is the return type of whatever local
3793      function we might be containing.  */
3794   if (function->type == DEMANGLE_COMPONENT_TYPED_NAME
3795       && d_right (function)->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
3796     d_left (d_right (function)) = NULL;
3797 
3798   return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
3799 }
3800 
3801 /* <discriminator> ::= _ <number>    # when number < 10
3802                    ::= __ <number> _ # when number >= 10
3803 
3804    <discriminator> ::= _ <number>    # when number >=10
3805    is also accepted to support gcc versions that wrongly mangled that way.
3806 
3807    We demangle the discriminator, but we don't print it out.  FIXME:
3808    We should print it out in verbose mode.  */
3809 
3810 static int
d_discriminator(struct d_info * di)3811 d_discriminator (struct d_info *di)
3812 {
3813   int discrim, num_underscores = 1;
3814 
3815   if (d_peek_char (di) != '_')
3816     return 1;
3817   d_advance (di, 1);
3818   if (d_peek_char (di) == '_')
3819     {
3820       ++num_underscores;
3821       d_advance (di, 1);
3822     }
3823 
3824   discrim = d_number (di);
3825   if (discrim < 0)
3826     return 0;
3827   if (num_underscores > 1 && discrim >= 10)
3828     {
3829       if (d_peek_char (di) == '_')
3830 	d_advance (di, 1);
3831       else
3832 	return 0;
3833     }
3834 
3835   return 1;
3836 }
3837 
3838 /* <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ */
3839 
3840 static struct demangle_component *
d_lambda(struct d_info * di)3841 d_lambda (struct d_info *di)
3842 {
3843   struct demangle_component *tl;
3844   struct demangle_component *ret;
3845   int num;
3846 
3847   if (! d_check_char (di, 'U'))
3848     return NULL;
3849   if (! d_check_char (di, 'l'))
3850     return NULL;
3851 
3852   tl = d_parmlist (di);
3853   if (tl == NULL)
3854     return NULL;
3855 
3856   if (! d_check_char (di, 'E'))
3857     return NULL;
3858 
3859   num = d_compact_number (di);
3860   if (num < 0)
3861     return NULL;
3862 
3863   ret = d_make_empty (di);
3864   if (ret)
3865     {
3866       ret->type = DEMANGLE_COMPONENT_LAMBDA;
3867       ret->u.s_unary_num.sub = tl;
3868       ret->u.s_unary_num.num = num;
3869     }
3870 
3871   return ret;
3872 }
3873 
3874 /* <unnamed-type-name> ::= Ut [ <nonnegative number> ] _ */
3875 
3876 static struct demangle_component *
d_unnamed_type(struct d_info * di)3877 d_unnamed_type (struct d_info *di)
3878 {
3879   struct demangle_component *ret;
3880   int num;
3881 
3882   if (! d_check_char (di, 'U'))
3883     return NULL;
3884   if (! d_check_char (di, 't'))
3885     return NULL;
3886 
3887   num = d_compact_number (di);
3888   if (num < 0)
3889     return NULL;
3890 
3891   ret = d_make_empty (di);
3892   if (ret)
3893     {
3894       ret->type = DEMANGLE_COMPONENT_UNNAMED_TYPE;
3895       ret->u.s_number.number = num;
3896     }
3897 
3898   if (! d_add_substitution (di, ret))
3899     return NULL;
3900 
3901   return ret;
3902 }
3903 
3904 /* <clone-suffix> ::= [ . <clone-type-identifier> ] [ . <nonnegative number> ]*
3905 */
3906 
3907 static struct demangle_component *
d_clone_suffix(struct d_info * di,struct demangle_component * encoding)3908 d_clone_suffix (struct d_info *di, struct demangle_component *encoding)
3909 {
3910   const char *suffix = d_str (di);
3911   const char *pend = suffix;
3912   struct demangle_component *n;
3913 
3914   if (*pend == '.' && (IS_LOWER (pend[1]) || IS_DIGIT (pend[1])
3915 		       || pend[1] == '_'))
3916     {
3917       pend += 2;
3918       while (IS_LOWER (*pend) || IS_DIGIT (*pend) || *pend == '_')
3919 	++pend;
3920     }
3921   while (*pend == '.' && IS_DIGIT (pend[1]))
3922     {
3923       pend += 2;
3924       while (IS_DIGIT (*pend))
3925 	++pend;
3926     }
3927   d_advance (di, pend - suffix);
3928   n = d_make_name (di, suffix, pend - suffix);
3929   return d_make_comp (di, DEMANGLE_COMPONENT_CLONE, encoding, n);
3930 }
3931 
3932 /* Add a new substitution.  */
3933 
3934 static int
d_add_substitution(struct d_info * di,struct demangle_component * dc)3935 d_add_substitution (struct d_info *di, struct demangle_component *dc)
3936 {
3937   if (dc == NULL)
3938     return 0;
3939   if (di->next_sub >= di->num_subs)
3940     return 0;
3941   di->subs[di->next_sub] = dc;
3942   ++di->next_sub;
3943   return 1;
3944 }
3945 
3946 /* <substitution> ::= S <seq-id> _
3947                   ::= S_
3948                   ::= St
3949                   ::= Sa
3950                   ::= Sb
3951                   ::= Ss
3952                   ::= Si
3953                   ::= So
3954                   ::= Sd
3955 
3956    If PREFIX is non-zero, then this type is being used as a prefix in
3957    a qualified name.  In this case, for the standard substitutions, we
3958    need to check whether we are being used as a prefix for a
3959    constructor or destructor, and return a full template name.
3960    Otherwise we will get something like std::iostream::~iostream()
3961    which does not correspond particularly well to any function which
3962    actually appears in the source.
3963 */
3964 
3965 static const struct d_standard_sub_info standard_subs[] =
3966 {
3967   { 't', NL ("std"),
3968     NL ("std"),
3969     NULL, 0 },
3970   { 'a', NL ("std::allocator"),
3971     NL ("std::allocator"),
3972     NL ("allocator") },
3973   { 'b', NL ("std::basic_string"),
3974     NL ("std::basic_string"),
3975     NL ("basic_string") },
3976   { 's', NL ("std::string"),
3977     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
3978     NL ("basic_string") },
3979   { 'i', NL ("std::istream"),
3980     NL ("std::basic_istream<char, std::char_traits<char> >"),
3981     NL ("basic_istream") },
3982   { 'o', NL ("std::ostream"),
3983     NL ("std::basic_ostream<char, std::char_traits<char> >"),
3984     NL ("basic_ostream") },
3985   { 'd', NL ("std::iostream"),
3986     NL ("std::basic_iostream<char, std::char_traits<char> >"),
3987     NL ("basic_iostream") }
3988 };
3989 
3990 static struct demangle_component *
d_substitution(struct d_info * di,int prefix)3991 d_substitution (struct d_info *di, int prefix)
3992 {
3993   char c;
3994 
3995   if (! d_check_char (di, 'S'))
3996     return NULL;
3997 
3998   c = d_next_char (di);
3999   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
4000     {
4001       unsigned int id;
4002 
4003       id = 0;
4004       if (c != '_')
4005 	{
4006 	  do
4007 	    {
4008 	      unsigned int new_id;
4009 
4010 	      if (IS_DIGIT (c))
4011 		new_id = id * 36 + c - '0';
4012 	      else if (IS_UPPER (c))
4013 		new_id = id * 36 + c - 'A' + 10;
4014 	      else
4015 		return NULL;
4016 	      if (new_id < id)
4017 		return NULL;
4018 	      id = new_id;
4019 	      c = d_next_char (di);
4020 	    }
4021 	  while (c != '_');
4022 
4023 	  ++id;
4024 	}
4025 
4026       if (id >= (unsigned int) di->next_sub)
4027 	return NULL;
4028 
4029       return di->subs[id];
4030     }
4031   else
4032     {
4033       int verbose;
4034       const struct d_standard_sub_info *p;
4035       const struct d_standard_sub_info *pend;
4036 
4037       verbose = (di->options & DMGL_VERBOSE) != 0;
4038       if (! verbose && prefix)
4039 	{
4040 	  char peek;
4041 
4042 	  peek = d_peek_char (di);
4043 	  if (peek == 'C' || peek == 'D')
4044 	    verbose = 1;
4045 	}
4046 
4047       pend = (&standard_subs[0]
4048 	      + sizeof standard_subs / sizeof standard_subs[0]);
4049       for (p = &standard_subs[0]; p < pend; ++p)
4050 	{
4051 	  if (c == p->code)
4052 	    {
4053 	      const char *s;
4054 	      int len;
4055 	      struct demangle_component *dc;
4056 
4057 	      if (p->set_last_name != NULL)
4058 		di->last_name = d_make_sub (di, p->set_last_name,
4059 					    p->set_last_name_len);
4060 	      if (verbose)
4061 		{
4062 		  s = p->full_expansion;
4063 		  len = p->full_len;
4064 		}
4065 	      else
4066 		{
4067 		  s = p->simple_expansion;
4068 		  len = p->simple_len;
4069 		}
4070 	      di->expansion += len;
4071 	      dc = d_make_sub (di, s, len);
4072 	      if (d_peek_char (di) == 'B')
4073 		{
4074 		  /* If there are ABI tags on the abbreviation, it becomes
4075 		     a substitution candidate.  */
4076 		  dc = d_abi_tags (di, dc);
4077 		  if (! d_add_substitution (di, dc))
4078 		    return NULL;
4079 		}
4080 	      return dc;
4081 	    }
4082 	}
4083 
4084       return NULL;
4085     }
4086 }
4087 
4088 static void
d_checkpoint(struct d_info * di,struct d_info_checkpoint * checkpoint)4089 d_checkpoint (struct d_info *di, struct d_info_checkpoint *checkpoint)
4090 {
4091   checkpoint->n = di->n;
4092   checkpoint->next_comp = di->next_comp;
4093   checkpoint->next_sub = di->next_sub;
4094   checkpoint->expansion = di->expansion;
4095 }
4096 
4097 static void
d_backtrack(struct d_info * di,struct d_info_checkpoint * checkpoint)4098 d_backtrack (struct d_info *di, struct d_info_checkpoint *checkpoint)
4099 {
4100   di->n = checkpoint->n;
4101   di->next_comp = checkpoint->next_comp;
4102   di->next_sub = checkpoint->next_sub;
4103   di->expansion = checkpoint->expansion;
4104 }
4105 
4106 /* Initialize a growable string.  */
4107 
4108 static void
d_growable_string_init(struct d_growable_string * dgs,size_t estimate)4109 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
4110 {
4111   dgs->buf = NULL;
4112   dgs->len = 0;
4113   dgs->alc = 0;
4114   dgs->allocation_failure = 0;
4115 
4116   if (estimate > 0)
4117     d_growable_string_resize (dgs, estimate);
4118 }
4119 
4120 /* Grow a growable string to a given size.  */
4121 
4122 static inline void
d_growable_string_resize(struct d_growable_string * dgs,size_t need)4123 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
4124 {
4125   size_t newalc;
4126   char *newbuf;
4127 
4128   if (dgs->allocation_failure)
4129     return;
4130 
4131   /* Start allocation at two bytes to avoid any possibility of confusion
4132      with the special value of 1 used as a return in *palc to indicate
4133      allocation failures.  */
4134   newalc = dgs->alc > 0 ? dgs->alc : 2;
4135   while (newalc < need)
4136     newalc <<= 1;
4137 
4138   newbuf = (char *) realloc (dgs->buf, newalc);
4139   if (newbuf == NULL)
4140     {
4141       free (dgs->buf);
4142       dgs->buf = NULL;
4143       dgs->len = 0;
4144       dgs->alc = 0;
4145       dgs->allocation_failure = 1;
4146       return;
4147     }
4148   dgs->buf = newbuf;
4149   dgs->alc = newalc;
4150 }
4151 
4152 /* Append a buffer to a growable string.  */
4153 
4154 static inline void
d_growable_string_append_buffer(struct d_growable_string * dgs,const char * s,size_t l)4155 d_growable_string_append_buffer (struct d_growable_string *dgs,
4156                                  const char *s, size_t l)
4157 {
4158   size_t need;
4159 
4160   need = dgs->len + l + 1;
4161   if (need > dgs->alc)
4162     d_growable_string_resize (dgs, need);
4163 
4164   if (dgs->allocation_failure)
4165     return;
4166 
4167   memcpy (dgs->buf + dgs->len, s, l);
4168   dgs->buf[dgs->len + l] = '\0';
4169   dgs->len += l;
4170 }
4171 
4172 /* Bridge growable strings to the callback mechanism.  */
4173 
4174 static void
d_growable_string_callback_adapter(const char * s,size_t l,void * opaque)4175 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
4176 {
4177   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
4178 
4179   d_growable_string_append_buffer (dgs, s, l);
4180 }
4181 
4182 /* Walk the tree, counting the number of templates encountered, and
4183    the number of times a scope might be saved.  These counts will be
4184    used to allocate data structures for d_print_comp, so the logic
4185    here must mirror the logic d_print_comp will use.  It is not
4186    important that the resulting numbers are exact, so long as they
4187    are larger than the actual numbers encountered.  */
4188 
4189 static void
d_count_templates_scopes(struct d_print_info * dpi,struct demangle_component * dc)4190 d_count_templates_scopes (struct d_print_info *dpi,
4191 			  struct demangle_component *dc)
4192 {
4193   if (dc == NULL || dc->d_counting > 1 || dpi->recursion > MAX_RECURSION_COUNT)
4194     return;
4195 
4196   ++ dc->d_counting;
4197 
4198   switch (dc->type)
4199     {
4200     case DEMANGLE_COMPONENT_NAME:
4201     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4202     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
4203     case DEMANGLE_COMPONENT_SUB_STD:
4204     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4205     case DEMANGLE_COMPONENT_OPERATOR:
4206     case DEMANGLE_COMPONENT_CHARACTER:
4207     case DEMANGLE_COMPONENT_NUMBER:
4208     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4209     case DEMANGLE_COMPONENT_STRUCTURED_BINDING:
4210     case DEMANGLE_COMPONENT_MODULE_NAME:
4211     case DEMANGLE_COMPONENT_MODULE_PARTITION:
4212     case DEMANGLE_COMPONENT_MODULE_INIT:
4213       break;
4214 
4215     case DEMANGLE_COMPONENT_TEMPLATE:
4216       dpi->num_copy_templates++;
4217       goto recurse_left_right;
4218 
4219     case DEMANGLE_COMPONENT_REFERENCE:
4220     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
4221       if (d_left (dc)->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
4222 	dpi->num_saved_scopes++;
4223       goto recurse_left_right;
4224 
4225     case DEMANGLE_COMPONENT_QUAL_NAME:
4226     case DEMANGLE_COMPONENT_LOCAL_NAME:
4227     case DEMANGLE_COMPONENT_TYPED_NAME:
4228     case DEMANGLE_COMPONENT_VTABLE:
4229     case DEMANGLE_COMPONENT_VTT:
4230     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
4231     case DEMANGLE_COMPONENT_TYPEINFO:
4232     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
4233     case DEMANGLE_COMPONENT_TYPEINFO_FN:
4234     case DEMANGLE_COMPONENT_THUNK:
4235     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
4236     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
4237     case DEMANGLE_COMPONENT_JAVA_CLASS:
4238     case DEMANGLE_COMPONENT_GUARD:
4239     case DEMANGLE_COMPONENT_TLS_INIT:
4240     case DEMANGLE_COMPONENT_TLS_WRAPPER:
4241     case DEMANGLE_COMPONENT_REFTEMP:
4242     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4243     case DEMANGLE_COMPONENT_RESTRICT:
4244     case DEMANGLE_COMPONENT_VOLATILE:
4245     case DEMANGLE_COMPONENT_CONST:
4246     case DEMANGLE_COMPONENT_RESTRICT_THIS:
4247     case DEMANGLE_COMPONENT_VOLATILE_THIS:
4248     case DEMANGLE_COMPONENT_CONST_THIS:
4249     case DEMANGLE_COMPONENT_REFERENCE_THIS:
4250     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
4251     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
4252     case DEMANGLE_COMPONENT_NOEXCEPT:
4253     case DEMANGLE_COMPONENT_THROW_SPEC:
4254     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
4255     case DEMANGLE_COMPONENT_POINTER:
4256     case DEMANGLE_COMPONENT_COMPLEX:
4257     case DEMANGLE_COMPONENT_IMAGINARY:
4258     case DEMANGLE_COMPONENT_VENDOR_TYPE:
4259     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
4260     case DEMANGLE_COMPONENT_ARRAY_TYPE:
4261     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
4262     case DEMANGLE_COMPONENT_VECTOR_TYPE:
4263     case DEMANGLE_COMPONENT_ARGLIST:
4264     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
4265     case DEMANGLE_COMPONENT_TPARM_OBJ:
4266     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
4267     case DEMANGLE_COMPONENT_CAST:
4268     case DEMANGLE_COMPONENT_CONVERSION:
4269     case DEMANGLE_COMPONENT_NULLARY:
4270     case DEMANGLE_COMPONENT_UNARY:
4271     case DEMANGLE_COMPONENT_BINARY:
4272     case DEMANGLE_COMPONENT_BINARY_ARGS:
4273     case DEMANGLE_COMPONENT_TRINARY:
4274     case DEMANGLE_COMPONENT_TRINARY_ARG1:
4275     case DEMANGLE_COMPONENT_TRINARY_ARG2:
4276     case DEMANGLE_COMPONENT_LITERAL:
4277     case DEMANGLE_COMPONENT_LITERAL_NEG:
4278     case DEMANGLE_COMPONENT_VENDOR_EXPR:
4279     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
4280     case DEMANGLE_COMPONENT_COMPOUND_NAME:
4281     case DEMANGLE_COMPONENT_DECLTYPE:
4282     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4283     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4284     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4285     case DEMANGLE_COMPONENT_TAGGED_NAME:
4286     case DEMANGLE_COMPONENT_CLONE:
4287     recurse_left_right:
4288       /* PR 89394 - Check for too much recursion.  */
4289       if (dpi->recursion > DEMANGLE_RECURSION_LIMIT)
4290 	/* FIXME: There ought to be a way to report to the
4291 	   user that the recursion limit has been reached.  */
4292 	return;
4293 
4294       ++ dpi->recursion;
4295       d_count_templates_scopes (dpi, d_left (dc));
4296       d_count_templates_scopes (dpi, d_right (dc));
4297       -- dpi->recursion;
4298       break;
4299 
4300     case DEMANGLE_COMPONENT_CTOR:
4301       d_count_templates_scopes (dpi, dc->u.s_ctor.name);
4302       break;
4303 
4304     case DEMANGLE_COMPONENT_DTOR:
4305       d_count_templates_scopes (dpi, dc->u.s_dtor.name);
4306       break;
4307 
4308     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4309       d_count_templates_scopes (dpi, dc->u.s_extended_operator.name);
4310       break;
4311 
4312     case DEMANGLE_COMPONENT_FIXED_TYPE:
4313       d_count_templates_scopes (dpi, dc->u.s_fixed.length);
4314       break;
4315 
4316     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
4317     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
4318     case DEMANGLE_COMPONENT_MODULE_ENTITY:
4319       d_count_templates_scopes (dpi, d_left (dc));
4320       break;
4321 
4322     case DEMANGLE_COMPONENT_LAMBDA:
4323     case DEMANGLE_COMPONENT_DEFAULT_ARG:
4324       d_count_templates_scopes (dpi, dc->u.s_unary_num.sub);
4325       break;
4326     }
4327 }
4328 
4329 /* Initialize a print information structure.  */
4330 
4331 static void
d_print_init(struct d_print_info * dpi,demangle_callbackref callback,void * opaque,struct demangle_component * dc)4332 d_print_init (struct d_print_info *dpi, demangle_callbackref callback,
4333 	      void *opaque, struct demangle_component *dc)
4334 {
4335   dpi->len = 0;
4336   dpi->last_char = '\0';
4337   dpi->templates = NULL;
4338   dpi->modifiers = NULL;
4339   dpi->pack_index = 0;
4340   dpi->flush_count = 0;
4341 
4342   dpi->callback = callback;
4343   dpi->opaque = opaque;
4344 
4345   dpi->demangle_failure = 0;
4346   dpi->recursion = 0;
4347   dpi->is_lambda_arg = 0;
4348 
4349   dpi->component_stack = NULL;
4350 
4351   dpi->saved_scopes = NULL;
4352   dpi->next_saved_scope = 0;
4353   dpi->num_saved_scopes = 0;
4354 
4355   dpi->copy_templates = NULL;
4356   dpi->next_copy_template = 0;
4357   dpi->num_copy_templates = 0;
4358 
4359   d_count_templates_scopes (dpi, dc);
4360   /* If we did not reach the recursion limit, then reset the
4361      current recursion value back to 0, so that we can print
4362      the templates.  */
4363   if (dpi->recursion < DEMANGLE_RECURSION_LIMIT)
4364     dpi->recursion = 0;
4365   dpi->num_copy_templates *= dpi->num_saved_scopes;
4366 
4367   dpi->current_template = NULL;
4368 }
4369 
4370 /* Indicate that an error occurred during printing, and test for error.  */
4371 
4372 static inline void
d_print_error(struct d_print_info * dpi)4373 d_print_error (struct d_print_info *dpi)
4374 {
4375   dpi->demangle_failure = 1;
4376 }
4377 
4378 static inline int
d_print_saw_error(struct d_print_info * dpi)4379 d_print_saw_error (struct d_print_info *dpi)
4380 {
4381   return dpi->demangle_failure != 0;
4382 }
4383 
4384 /* Flush buffered characters to the callback.  */
4385 
4386 static inline void
d_print_flush(struct d_print_info * dpi)4387 d_print_flush (struct d_print_info *dpi)
4388 {
4389   dpi->buf[dpi->len] = '\0';
4390   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
4391   dpi->len = 0;
4392   dpi->flush_count++;
4393 }
4394 
4395 /* Append characters and buffers for printing.  */
4396 
4397 static inline void
d_append_char(struct d_print_info * dpi,char c)4398 d_append_char (struct d_print_info *dpi, char c)
4399 {
4400   if (dpi->len == sizeof (dpi->buf) - 1)
4401     d_print_flush (dpi);
4402 
4403   dpi->buf[dpi->len++] = c;
4404   dpi->last_char = c;
4405 }
4406 
4407 static inline void
d_append_buffer(struct d_print_info * dpi,const char * s,size_t l)4408 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
4409 {
4410   size_t i;
4411 
4412   for (i = 0; i < l; i++)
4413     d_append_char (dpi, s[i]);
4414 }
4415 
4416 static inline void
d_append_string(struct d_print_info * dpi,const char * s)4417 d_append_string (struct d_print_info *dpi, const char *s)
4418 {
4419   d_append_buffer (dpi, s, strlen (s));
4420 }
4421 
4422 static inline void
d_append_num(struct d_print_info * dpi,int l)4423 d_append_num (struct d_print_info *dpi, int l)
4424 {
4425   char buf[25];
4426   sprintf (buf,"%d", l);
4427   d_append_string (dpi, buf);
4428 }
4429 
4430 static inline char
d_last_char(struct d_print_info * dpi)4431 d_last_char (struct d_print_info *dpi)
4432 {
4433   return dpi->last_char;
4434 }
4435 
4436 /* Turn components into a human readable string.  OPTIONS is the
4437    options bits passed to the demangler.  DC is the tree to print.
4438    CALLBACK is a function to call to flush demangled string segments
4439    as they fill the intermediate buffer, and OPAQUE is a generalized
4440    callback argument.  On success, this returns 1.  On failure,
4441    it returns 0, indicating a bad parse.  It does not use heap
4442    memory to build an output string, so cannot encounter memory
4443    allocation failure.  */
4444 
4445 CP_STATIC_IF_GLIBCPP_V3
4446 int
cplus_demangle_print_callback(int options,struct demangle_component * dc,demangle_callbackref callback,void * opaque)4447 cplus_demangle_print_callback (int options,
4448                                struct demangle_component *dc,
4449                                demangle_callbackref callback, void *opaque)
4450 {
4451   struct d_print_info dpi;
4452 
4453   d_print_init (&dpi, callback, opaque, dc);
4454 
4455   {
4456 #ifdef CP_DYNAMIC_ARRAYS
4457     /* Avoid zero-length VLAs, which are prohibited by the C99 standard
4458        and flagged as errors by Address Sanitizer.  */
4459     __extension__ struct d_saved_scope scopes[(dpi.num_saved_scopes > 0)
4460                                               ? dpi.num_saved_scopes : 1];
4461     __extension__ struct d_print_template temps[(dpi.num_copy_templates > 0)
4462                                                 ? dpi.num_copy_templates : 1];
4463 
4464     dpi.saved_scopes = scopes;
4465     dpi.copy_templates = temps;
4466 #else
4467     dpi.saved_scopes = alloca (dpi.num_saved_scopes
4468 			       * sizeof (*dpi.saved_scopes));
4469     dpi.copy_templates = alloca (dpi.num_copy_templates
4470 				 * sizeof (*dpi.copy_templates));
4471 #endif
4472 
4473     d_print_comp (&dpi, options, dc);
4474   }
4475 
4476   d_print_flush (&dpi);
4477 
4478   return ! d_print_saw_error (&dpi);
4479 }
4480 
4481 /* Turn components into a human readable string.  OPTIONS is the
4482    options bits passed to the demangler.  DC is the tree to print.
4483    ESTIMATE is a guess at the length of the result.  This returns a
4484    string allocated by malloc, or NULL on error.  On success, this
4485    sets *PALC to the size of the allocated buffer.  On failure, this
4486    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
4487    failure.  */
4488 
4489 CP_STATIC_IF_GLIBCPP_V3
4490 char *
cplus_demangle_print(int options,struct demangle_component * dc,int estimate,size_t * palc)4491 cplus_demangle_print (int options, struct demangle_component *dc,
4492                       int estimate, size_t *palc)
4493 {
4494   struct d_growable_string dgs;
4495 
4496   d_growable_string_init (&dgs, estimate);
4497 
4498   if (! cplus_demangle_print_callback (options, dc,
4499                                        d_growable_string_callback_adapter,
4500                                        &dgs))
4501     {
4502       free (dgs.buf);
4503       *palc = 0;
4504       return NULL;
4505     }
4506 
4507   *palc = dgs.allocation_failure ? 1 : dgs.alc;
4508   return dgs.buf;
4509 }
4510 
4511 /* Returns the I'th element of the template arglist ARGS, or NULL on
4512    failure.  If I is negative, return the entire arglist.  */
4513 
4514 static struct demangle_component *
d_index_template_argument(struct demangle_component * args,int i)4515 d_index_template_argument (struct demangle_component *args, int i)
4516 {
4517   struct demangle_component *a;
4518 
4519   if (i < 0)
4520     /* Print the whole argument pack.  */
4521     return args;
4522 
4523   for (a = args;
4524        a != NULL;
4525        a = d_right (a))
4526     {
4527       if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4528 	return NULL;
4529       if (i <= 0)
4530 	break;
4531       --i;
4532     }
4533   if (i != 0 || a == NULL)
4534     return NULL;
4535 
4536   return d_left (a);
4537 }
4538 
4539 /* Returns the template argument from the current context indicated by DC,
4540    which is a DEMANGLE_COMPONENT_TEMPLATE_PARAM, or NULL.  */
4541 
4542 static struct demangle_component *
d_lookup_template_argument(struct d_print_info * dpi,const struct demangle_component * dc)4543 d_lookup_template_argument (struct d_print_info *dpi,
4544 			    const struct demangle_component *dc)
4545 {
4546   if (dpi->templates == NULL)
4547     {
4548       d_print_error (dpi);
4549       return NULL;
4550     }
4551 
4552   return d_index_template_argument
4553     (d_right (dpi->templates->template_decl),
4554      dc->u.s_number.number);
4555 }
4556 
4557 /* Returns a template argument pack used in DC (any will do), or NULL.  */
4558 
4559 static struct demangle_component *
d_find_pack(struct d_print_info * dpi,const struct demangle_component * dc)4560 d_find_pack (struct d_print_info *dpi,
4561 	     const struct demangle_component *dc)
4562 {
4563   struct demangle_component *a;
4564   if (dc == NULL)
4565     return NULL;
4566 
4567   switch (dc->type)
4568     {
4569     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4570       a = d_lookup_template_argument (dpi, dc);
4571       if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4572 	return a;
4573       return NULL;
4574 
4575     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4576       return NULL;
4577 
4578     case DEMANGLE_COMPONENT_LAMBDA:
4579     case DEMANGLE_COMPONENT_NAME:
4580     case DEMANGLE_COMPONENT_TAGGED_NAME:
4581     case DEMANGLE_COMPONENT_OPERATOR:
4582     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4583     case DEMANGLE_COMPONENT_SUB_STD:
4584     case DEMANGLE_COMPONENT_CHARACTER:
4585     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
4586     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4587     case DEMANGLE_COMPONENT_FIXED_TYPE:
4588     case DEMANGLE_COMPONENT_DEFAULT_ARG:
4589     case DEMANGLE_COMPONENT_NUMBER:
4590       return NULL;
4591 
4592     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4593       return d_find_pack (dpi, dc->u.s_extended_operator.name);
4594     case DEMANGLE_COMPONENT_CTOR:
4595       return d_find_pack (dpi, dc->u.s_ctor.name);
4596     case DEMANGLE_COMPONENT_DTOR:
4597       return d_find_pack (dpi, dc->u.s_dtor.name);
4598 
4599     default:
4600       a = d_find_pack (dpi, d_left (dc));
4601       if (a)
4602 	return a;
4603       return d_find_pack (dpi, d_right (dc));
4604     }
4605 }
4606 
4607 /* Returns the length of the template argument pack DC.  */
4608 
4609 static int
d_pack_length(const struct demangle_component * dc)4610 d_pack_length (const struct demangle_component *dc)
4611 {
4612   int count = 0;
4613   while (dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST
4614 	 && d_left (dc) != NULL)
4615     {
4616       ++count;
4617       dc = d_right (dc);
4618     }
4619   return count;
4620 }
4621 
4622 /* Returns the number of template args in DC, expanding any pack expansions
4623    found there.  */
4624 
4625 static int
d_args_length(struct d_print_info * dpi,const struct demangle_component * dc)4626 d_args_length (struct d_print_info *dpi, const struct demangle_component *dc)
4627 {
4628   int count = 0;
4629   for (; dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST;
4630        dc = d_right (dc))
4631     {
4632       struct demangle_component *elt = d_left (dc);
4633       if (elt == NULL)
4634 	break;
4635       if (elt->type == DEMANGLE_COMPONENT_PACK_EXPANSION)
4636 	{
4637 	  struct demangle_component *a = d_find_pack (dpi, d_left (elt));
4638 	  count += d_pack_length (a);
4639 	}
4640       else
4641 	++count;
4642     }
4643   return count;
4644 }
4645 
4646 /* DC is a component of a mangled expression.  Print it, wrapped in parens
4647    if needed.  */
4648 
4649 static void
d_print_subexpr(struct d_print_info * dpi,int options,struct demangle_component * dc)4650 d_print_subexpr (struct d_print_info *dpi, int options,
4651 		 struct demangle_component *dc)
4652 {
4653   int simple = 0;
4654   if (dc->type == DEMANGLE_COMPONENT_NAME
4655       || dc->type == DEMANGLE_COMPONENT_QUAL_NAME
4656       || dc->type == DEMANGLE_COMPONENT_INITIALIZER_LIST
4657       || dc->type == DEMANGLE_COMPONENT_FUNCTION_PARAM)
4658     simple = 1;
4659   if (!simple)
4660     d_append_char (dpi, '(');
4661   d_print_comp (dpi, options, dc);
4662   if (!simple)
4663     d_append_char (dpi, ')');
4664 }
4665 
4666 /* Save the current scope.  */
4667 
4668 static void
d_save_scope(struct d_print_info * dpi,const struct demangle_component * container)4669 d_save_scope (struct d_print_info *dpi,
4670 	      const struct demangle_component *container)
4671 {
4672   struct d_saved_scope *scope;
4673   struct d_print_template *src, **link;
4674 
4675   if (dpi->next_saved_scope >= dpi->num_saved_scopes)
4676     {
4677       d_print_error (dpi);
4678       return;
4679     }
4680   scope = &dpi->saved_scopes[dpi->next_saved_scope];
4681   dpi->next_saved_scope++;
4682 
4683   scope->container = container;
4684   link = &scope->templates;
4685 
4686   for (src = dpi->templates; src != NULL; src = src->next)
4687     {
4688       struct d_print_template *dst;
4689 
4690       if (dpi->next_copy_template >= dpi->num_copy_templates)
4691 	{
4692 	  d_print_error (dpi);
4693 	  return;
4694 	}
4695       dst = &dpi->copy_templates[dpi->next_copy_template];
4696       dpi->next_copy_template++;
4697 
4698       dst->template_decl = src->template_decl;
4699       *link = dst;
4700       link = &dst->next;
4701     }
4702 
4703   *link = NULL;
4704 }
4705 
4706 /* Attempt to locate a previously saved scope.  Returns NULL if no
4707    corresponding saved scope was found.  */
4708 
4709 static struct d_saved_scope *
d_get_saved_scope(struct d_print_info * dpi,const struct demangle_component * container)4710 d_get_saved_scope (struct d_print_info *dpi,
4711 		   const struct demangle_component *container)
4712 {
4713   int i;
4714 
4715   for (i = 0; i < dpi->next_saved_scope; i++)
4716     if (dpi->saved_scopes[i].container == container)
4717       return &dpi->saved_scopes[i];
4718 
4719   return NULL;
4720 }
4721 
4722 /* If DC is a C++17 fold-expression, print it and return true; otherwise
4723    return false.  */
4724 
4725 static int
d_maybe_print_fold_expression(struct d_print_info * dpi,int options,struct demangle_component * dc)4726 d_maybe_print_fold_expression (struct d_print_info *dpi, int options,
4727 			       struct demangle_component *dc)
4728 {
4729   struct demangle_component *ops, *operator_, *op1, *op2;
4730   int save_idx;
4731 
4732   const char *fold_code = d_left (dc)->u.s_operator.op->code;
4733   if (fold_code[0] != 'f')
4734     return 0;
4735 
4736   ops = d_right (dc);
4737   operator_ = d_left (ops);
4738   op1 = d_right (ops);
4739   op2 = 0;
4740   if (op1->type == DEMANGLE_COMPONENT_TRINARY_ARG2)
4741     {
4742       op2 = d_right (op1);
4743       op1 = d_left (op1);
4744     }
4745 
4746   /* Print the whole pack.  */
4747   save_idx = dpi->pack_index;
4748   dpi->pack_index = -1;
4749 
4750   switch (fold_code[1])
4751     {
4752       /* Unary left fold, (... + X).  */
4753     case 'l':
4754       d_append_string (dpi, "(...");
4755       d_print_expr_op (dpi, options, operator_);
4756       d_print_subexpr (dpi, options, op1);
4757       d_append_char (dpi, ')');
4758       break;
4759 
4760       /* Unary right fold, (X + ...).  */
4761     case 'r':
4762       d_append_char (dpi, '(');
4763       d_print_subexpr (dpi, options, op1);
4764       d_print_expr_op (dpi, options, operator_);
4765       d_append_string (dpi, "...)");
4766       break;
4767 
4768       /* Binary left fold, (42 + ... + X).  */
4769     case 'L':
4770       /* Binary right fold, (X + ... + 42).  */
4771     case 'R':
4772       d_append_char (dpi, '(');
4773       d_print_subexpr (dpi, options, op1);
4774       d_print_expr_op (dpi, options, operator_);
4775       d_append_string (dpi, "...");
4776       d_print_expr_op (dpi, options, operator_);
4777       d_print_subexpr (dpi, options, op2);
4778       d_append_char (dpi, ')');
4779       break;
4780     }
4781 
4782   dpi->pack_index = save_idx;
4783   return 1;
4784 }
4785 
4786 /* True iff DC represents a C99-style designated initializer.  */
4787 
4788 static int
is_designated_init(struct demangle_component * dc)4789 is_designated_init (struct demangle_component *dc)
4790 {
4791   if (dc->type != DEMANGLE_COMPONENT_BINARY
4792       && dc->type != DEMANGLE_COMPONENT_TRINARY)
4793     return 0;
4794 
4795   struct demangle_component *op = d_left (dc);
4796   const char *code = op->u.s_operator.op->code;
4797   return (code[0] == 'd'
4798 	  && (code[1] == 'i' || code[1] == 'x' || code[1] == 'X'));
4799 }
4800 
4801 /* If DC represents a C99-style designated initializer, print it and return
4802    true; otherwise, return false.  */
4803 
4804 static int
d_maybe_print_designated_init(struct d_print_info * dpi,int options,struct demangle_component * dc)4805 d_maybe_print_designated_init (struct d_print_info *dpi, int options,
4806 			       struct demangle_component *dc)
4807 {
4808   if (!is_designated_init (dc))
4809     return 0;
4810 
4811   const char *code = d_left (dc)->u.s_operator.op->code;
4812 
4813   struct demangle_component *operands = d_right (dc);
4814   struct demangle_component *op1 = d_left (operands);
4815   struct demangle_component *op2 = d_right (operands);
4816 
4817   if (code[1] == 'i')
4818     d_append_char (dpi, '.');
4819   else
4820     d_append_char (dpi, '[');
4821 
4822   d_print_comp (dpi, options, op1);
4823   if (code[1] == 'X')
4824     {
4825       d_append_string (dpi, " ... ");
4826       d_print_comp (dpi, options, d_left (op2));
4827       op2 = d_right (op2);
4828     }
4829   if (code[1] != 'i')
4830     d_append_char (dpi, ']');
4831   if (is_designated_init (op2))
4832     {
4833       /* Don't put '=' or '(' between chained designators.  */
4834       d_print_comp (dpi, options, op2);
4835     }
4836   else
4837     {
4838       d_append_char (dpi, '=');
4839       d_print_subexpr (dpi, options, op2);
4840     }
4841   return 1;
4842 }
4843 
4844 /* Subroutine to handle components.  */
4845 
4846 static void
d_print_comp_inner(struct d_print_info * dpi,int options,struct demangle_component * dc)4847 d_print_comp_inner (struct d_print_info *dpi, int options,
4848 		    struct demangle_component *dc)
4849 {
4850   /* Magic variable to let reference smashing skip over the next modifier
4851      without needing to modify *dc.  */
4852   struct demangle_component *mod_inner = NULL;
4853 
4854   /* Variable used to store the current templates while a previously
4855      captured scope is used.  */
4856   struct d_print_template *saved_templates;
4857 
4858   /* Nonzero if templates have been stored in the above variable.  */
4859   int need_template_restore = 0;
4860 
4861   if (dc == NULL)
4862     {
4863       d_print_error (dpi);
4864       return;
4865     }
4866   if (d_print_saw_error (dpi))
4867     return;
4868 
4869   switch (dc->type)
4870     {
4871     case DEMANGLE_COMPONENT_NAME:
4872       if ((options & DMGL_JAVA) == 0)
4873 	d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
4874       else
4875 	d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
4876       return;
4877 
4878     case DEMANGLE_COMPONENT_TAGGED_NAME:
4879       d_print_comp (dpi, options, d_left (dc));
4880       d_append_string (dpi, "[abi:");
4881       d_print_comp (dpi, options, d_right (dc));
4882       d_append_char (dpi, ']');
4883       return;
4884 
4885     case DEMANGLE_COMPONENT_STRUCTURED_BINDING:
4886       d_append_char (dpi, '[');
4887       for (;;)
4888 	{
4889 	  d_print_comp (dpi, options, d_left (dc));
4890 	  dc = d_right (dc);
4891 	  if (!dc)
4892 	    break;
4893 	  d_append_string (dpi, ", ");
4894 	}
4895       d_append_char (dpi, ']');
4896       return;
4897 
4898     case DEMANGLE_COMPONENT_MODULE_ENTITY:
4899       d_print_comp (dpi, options, d_left (dc));
4900       d_append_char (dpi, '@');
4901       d_print_comp (dpi, options, d_right (dc));
4902       return;
4903 
4904     case DEMANGLE_COMPONENT_MODULE_NAME:
4905     case DEMANGLE_COMPONENT_MODULE_PARTITION:
4906       {
4907 	if (d_left (dc))
4908 	  d_print_comp (dpi, options, d_left (dc));
4909 	char c = dc->type == DEMANGLE_COMPONENT_MODULE_PARTITION
4910 	  ? ':' : d_left (dc) ? '.' : 0;
4911 	if (c)
4912 	  d_append_char (dpi, c);
4913 	d_print_comp (dpi, options, d_right (dc));
4914       }
4915       return;
4916 
4917     case DEMANGLE_COMPONENT_QUAL_NAME:
4918     case DEMANGLE_COMPONENT_LOCAL_NAME:
4919       d_print_comp (dpi, options, d_left (dc));
4920       if ((options & DMGL_JAVA) == 0)
4921 	d_append_string (dpi, "::");
4922       else
4923 	d_append_char (dpi, '.');
4924       {
4925 	struct demangle_component *local_name = d_right (dc);
4926 	if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4927 	  {
4928 	    d_append_string (dpi, "{default arg#");
4929 	    d_append_num (dpi, local_name->u.s_unary_num.num + 1);
4930 	    d_append_string (dpi, "}::");
4931 	    local_name = local_name->u.s_unary_num.sub;
4932 	  }
4933 	d_print_comp (dpi, options, local_name);
4934       }
4935       return;
4936 
4937     case DEMANGLE_COMPONENT_TYPED_NAME:
4938       {
4939 	struct d_print_mod *hold_modifiers;
4940 	struct demangle_component *typed_name;
4941 	struct d_print_mod adpm[4];
4942 	unsigned int i;
4943 	struct d_print_template dpt;
4944 
4945 	/* Pass the name down to the type so that it can be printed in
4946 	   the right place for the type.  We also have to pass down
4947 	   any CV-qualifiers, which apply to the this parameter.  */
4948 	hold_modifiers = dpi->modifiers;
4949 	dpi->modifiers = 0;
4950 	i = 0;
4951 	typed_name = d_left (dc);
4952 	while (typed_name != NULL)
4953 	  {
4954 	    if (i >= sizeof adpm / sizeof adpm[0])
4955 	      {
4956 		d_print_error (dpi);
4957 		return;
4958 	      }
4959 
4960 	    adpm[i].next = dpi->modifiers;
4961 	    dpi->modifiers = &adpm[i];
4962 	    adpm[i].mod = typed_name;
4963 	    adpm[i].printed = 0;
4964 	    adpm[i].templates = dpi->templates;
4965 	    ++i;
4966 
4967 	    if (!is_fnqual_component_type (typed_name->type))
4968 	      break;
4969 
4970 	    typed_name = d_left (typed_name);
4971 	  }
4972 
4973 	if (typed_name == NULL)
4974 	  {
4975 	    d_print_error (dpi);
4976 	    return;
4977 	  }
4978 
4979 	/* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
4980 	   there may be CV-qualifiers on its right argument which
4981 	   really apply here; this happens when parsing a class that
4982 	   is local to a function.  */
4983 	if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
4984 	  {
4985 	    typed_name = d_right (typed_name);
4986 	    if (typed_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4987 	      typed_name = typed_name->u.s_unary_num.sub;
4988 	    while (typed_name != NULL
4989 		   && is_fnqual_component_type (typed_name->type))
4990 	      {
4991 		if (i >= sizeof adpm / sizeof adpm[0])
4992 		  {
4993 		    d_print_error (dpi);
4994 		    return;
4995 		  }
4996 
4997 		adpm[i] = adpm[i - 1];
4998 		adpm[i].next = &adpm[i - 1];
4999 		dpi->modifiers = &adpm[i];
5000 
5001 		adpm[i - 1].mod = typed_name;
5002 		adpm[i - 1].printed = 0;
5003 		adpm[i - 1].templates = dpi->templates;
5004 		++i;
5005 
5006 		typed_name = d_left (typed_name);
5007 	      }
5008 	    if (typed_name == NULL)
5009 	      {
5010 		d_print_error (dpi);
5011 		return;
5012 	      }
5013 	  }
5014 
5015 	/* If typed_name is a template, then it applies to the
5016 	   function type as well.  */
5017 	if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
5018 	  {
5019 	    dpt.next = dpi->templates;
5020 	    dpi->templates = &dpt;
5021 	    dpt.template_decl = typed_name;
5022 	  }
5023 
5024 	d_print_comp (dpi, options, d_right (dc));
5025 
5026 	if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
5027 	  dpi->templates = dpt.next;
5028 
5029 	/* If the modifiers didn't get printed by the type, print them
5030 	   now.  */
5031 	while (i > 0)
5032 	  {
5033 	    --i;
5034 	    if (! adpm[i].printed)
5035 	      {
5036 		d_append_char (dpi, ' ');
5037 		d_print_mod (dpi, options, adpm[i].mod);
5038 	      }
5039 	  }
5040 
5041 	dpi->modifiers = hold_modifiers;
5042 
5043 	return;
5044       }
5045 
5046     case DEMANGLE_COMPONENT_TEMPLATE:
5047       {
5048 	struct d_print_mod *hold_dpm;
5049 	struct demangle_component *dcl;
5050 	const struct demangle_component *hold_current;
5051 
5052 	/* This template may need to be referenced by a cast operator
5053 	   contained in its subtree.  */
5054 	hold_current = dpi->current_template;
5055 	dpi->current_template = dc;
5056 
5057 	/* Don't push modifiers into a template definition.  Doing so
5058 	   could give the wrong definition for a template argument.
5059 	   Instead, treat the template essentially as a name.  */
5060 
5061 	hold_dpm = dpi->modifiers;
5062 	dpi->modifiers = NULL;
5063 
5064         dcl = d_left (dc);
5065 
5066         if ((options & DMGL_JAVA) != 0
5067             && dcl->type == DEMANGLE_COMPONENT_NAME
5068             && dcl->u.s_name.len == 6
5069             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
5070           {
5071             /* Special-case Java arrays, so that JArray<TYPE> appears
5072                instead as TYPE[].  */
5073 
5074             d_print_comp (dpi, options, d_right (dc));
5075             d_append_string (dpi, "[]");
5076           }
5077         else
5078           {
5079 	    d_print_comp (dpi, options, dcl);
5080 	    if (d_last_char (dpi) == '<')
5081 	      d_append_char (dpi, ' ');
5082 	    d_append_char (dpi, '<');
5083 	    d_print_comp (dpi, options, d_right (dc));
5084 	    /* Avoid generating two consecutive '>' characters, to avoid
5085 	       the C++ syntactic ambiguity.  */
5086 	    if (d_last_char (dpi) == '>')
5087 	      d_append_char (dpi, ' ');
5088 	    d_append_char (dpi, '>');
5089           }
5090 
5091 	dpi->modifiers = hold_dpm;
5092 	dpi->current_template = hold_current;
5093 
5094 	return;
5095       }
5096 
5097     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
5098       if (dpi->is_lambda_arg)
5099 	{
5100 	  /* Show the template parm index, as that's how g++ displays
5101 	     these, and future proofs us against potential
5102 	     '[]<typename T> (T *a, T *b) {...}'.  */
5103 	  d_append_buffer (dpi, "auto:", 5);
5104 	  d_append_num (dpi, dc->u.s_number.number + 1);
5105 	}
5106       else
5107 	{
5108 	  struct d_print_template *hold_dpt;
5109 	  struct demangle_component *a = d_lookup_template_argument (dpi, dc);
5110 
5111 	  if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
5112 	    a = d_index_template_argument (a, dpi->pack_index);
5113 
5114 	  if (a == NULL)
5115 	    {
5116 	      d_print_error (dpi);
5117 	      return;
5118 	    }
5119 
5120 	  /* While processing this parameter, we need to pop the list
5121 	     of templates.  This is because the template parameter may
5122 	     itself be a reference to a parameter of an outer
5123 	     template.  */
5124 
5125 	  hold_dpt = dpi->templates;
5126 	  dpi->templates = hold_dpt->next;
5127 
5128 	  d_print_comp (dpi, options, a);
5129 
5130 	  dpi->templates = hold_dpt;
5131 	}
5132       return;
5133 
5134     case DEMANGLE_COMPONENT_TPARM_OBJ:
5135       d_append_string (dpi, "template parameter object for ");
5136       d_print_comp (dpi, options, d_left (dc));
5137       return;
5138 
5139     case DEMANGLE_COMPONENT_CTOR:
5140       d_print_comp (dpi, options, dc->u.s_ctor.name);
5141       return;
5142 
5143     case DEMANGLE_COMPONENT_DTOR:
5144       d_append_char (dpi, '~');
5145       d_print_comp (dpi, options, dc->u.s_dtor.name);
5146       return;
5147 
5148     case DEMANGLE_COMPONENT_MODULE_INIT:
5149       d_append_string (dpi, "initializer for module ");
5150       d_print_comp (dpi, options, d_left (dc));
5151       return;
5152 
5153     case DEMANGLE_COMPONENT_VTABLE:
5154       d_append_string (dpi, "vtable for ");
5155       d_print_comp (dpi, options, d_left (dc));
5156       return;
5157 
5158     case DEMANGLE_COMPONENT_VTT:
5159       d_append_string (dpi, "VTT for ");
5160       d_print_comp (dpi, options, d_left (dc));
5161       return;
5162 
5163     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
5164       d_append_string (dpi, "construction vtable for ");
5165       d_print_comp (dpi, options, d_left (dc));
5166       d_append_string (dpi, "-in-");
5167       d_print_comp (dpi, options, d_right (dc));
5168       return;
5169 
5170     case DEMANGLE_COMPONENT_TYPEINFO:
5171       d_append_string (dpi, "typeinfo for ");
5172       d_print_comp (dpi, options, d_left (dc));
5173       return;
5174 
5175     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
5176       d_append_string (dpi, "typeinfo name for ");
5177       d_print_comp (dpi, options, d_left (dc));
5178       return;
5179 
5180     case DEMANGLE_COMPONENT_TYPEINFO_FN:
5181       d_append_string (dpi, "typeinfo fn for ");
5182       d_print_comp (dpi, options, d_left (dc));
5183       return;
5184 
5185     case DEMANGLE_COMPONENT_THUNK:
5186       d_append_string (dpi, "non-virtual thunk to ");
5187       d_print_comp (dpi, options, d_left (dc));
5188       return;
5189 
5190     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
5191       d_append_string (dpi, "virtual thunk to ");
5192       d_print_comp (dpi, options, d_left (dc));
5193       return;
5194 
5195     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
5196       d_append_string (dpi, "covariant return thunk to ");
5197       d_print_comp (dpi, options, d_left (dc));
5198       return;
5199 
5200     case DEMANGLE_COMPONENT_JAVA_CLASS:
5201       d_append_string (dpi, "java Class for ");
5202       d_print_comp (dpi, options, d_left (dc));
5203       return;
5204 
5205     case DEMANGLE_COMPONENT_GUARD:
5206       d_append_string (dpi, "guard variable for ");
5207       d_print_comp (dpi, options, d_left (dc));
5208       return;
5209 
5210     case DEMANGLE_COMPONENT_TLS_INIT:
5211       d_append_string (dpi, "TLS init function for ");
5212       d_print_comp (dpi, options, d_left (dc));
5213       return;
5214 
5215     case DEMANGLE_COMPONENT_TLS_WRAPPER:
5216       d_append_string (dpi, "TLS wrapper function for ");
5217       d_print_comp (dpi, options, d_left (dc));
5218       return;
5219 
5220     case DEMANGLE_COMPONENT_REFTEMP:
5221       d_append_string (dpi, "reference temporary #");
5222       d_print_comp (dpi, options, d_right (dc));
5223       d_append_string (dpi, " for ");
5224       d_print_comp (dpi, options, d_left (dc));
5225       return;
5226 
5227     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
5228       d_append_string (dpi, "hidden alias for ");
5229       d_print_comp (dpi, options, d_left (dc));
5230       return;
5231 
5232     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
5233       d_append_string (dpi, "transaction clone for ");
5234       d_print_comp (dpi, options, d_left (dc));
5235       return;
5236 
5237     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
5238       d_append_string (dpi, "non-transaction clone for ");
5239       d_print_comp (dpi, options, d_left (dc));
5240       return;
5241 
5242     case DEMANGLE_COMPONENT_SUB_STD:
5243       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
5244       return;
5245 
5246     case DEMANGLE_COMPONENT_RESTRICT:
5247     case DEMANGLE_COMPONENT_VOLATILE:
5248     case DEMANGLE_COMPONENT_CONST:
5249       {
5250 	struct d_print_mod *pdpm;
5251 
5252 	/* When printing arrays, it's possible to have cases where the
5253 	   same CV-qualifier gets pushed on the stack multiple times.
5254 	   We only need to print it once.  */
5255 
5256 	for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
5257 	  {
5258 	    if (! pdpm->printed)
5259 	      {
5260 		if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
5261 		    && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
5262 		    && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
5263 		  break;
5264 		if (pdpm->mod->type == dc->type)
5265 		  {
5266 		    d_print_comp (dpi, options, d_left (dc));
5267 		    return;
5268 		  }
5269 	      }
5270 	  }
5271       }
5272       goto modifier;
5273 
5274     case DEMANGLE_COMPONENT_REFERENCE:
5275     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5276       {
5277 	/* Handle reference smashing: & + && = &.  */
5278 	struct demangle_component *sub = d_left (dc);
5279 	if (!dpi->is_lambda_arg
5280 	    && sub->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
5281 	  {
5282 	    struct d_saved_scope *scope = d_get_saved_scope (dpi, sub);
5283 	    struct demangle_component *a;
5284 
5285 	    if (scope == NULL)
5286 	      {
5287 		/* This is the first time SUB has been traversed.
5288 		   We need to capture the current templates so
5289 		   they can be restored if SUB is reentered as a
5290 		   substitution.  */
5291 		d_save_scope (dpi, sub);
5292 		if (d_print_saw_error (dpi))
5293 		  return;
5294 	      }
5295 	    else
5296 	      {
5297 		const struct d_component_stack *dcse;
5298 		int found_self_or_parent = 0;
5299 
5300 		/* This traversal is reentering SUB as a substition.
5301 		   If we are not beneath SUB or DC in the tree then we
5302 		   need to restore SUB's template stack temporarily.  */
5303 		for (dcse = dpi->component_stack; dcse != NULL;
5304 		     dcse = dcse->parent)
5305 		  {
5306 		    if (dcse->dc == sub
5307 			|| (dcse->dc == dc
5308 			    && dcse != dpi->component_stack))
5309 		      {
5310 			found_self_or_parent = 1;
5311 			break;
5312 		      }
5313 		  }
5314 
5315 		if (!found_self_or_parent)
5316 		  {
5317 		    saved_templates = dpi->templates;
5318 		    dpi->templates = scope->templates;
5319 		    need_template_restore = 1;
5320 		  }
5321 	      }
5322 
5323 	    a = d_lookup_template_argument (dpi, sub);
5324 	    if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
5325 	      a = d_index_template_argument (a, dpi->pack_index);
5326 
5327 	    if (a == NULL)
5328 	      {
5329 		if (need_template_restore)
5330 		  dpi->templates = saved_templates;
5331 
5332 		d_print_error (dpi);
5333 		return;
5334 	      }
5335 
5336 	    sub = a;
5337 	  }
5338 
5339 	if (sub->type == DEMANGLE_COMPONENT_REFERENCE
5340 	    || sub->type == dc->type)
5341 	  dc = sub;
5342 	else if (sub->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE)
5343 	  mod_inner = d_left (sub);
5344       }
5345       /* Fall through.  */
5346 
5347     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5348     case DEMANGLE_COMPONENT_POINTER:
5349     case DEMANGLE_COMPONENT_COMPLEX:
5350     case DEMANGLE_COMPONENT_IMAGINARY:
5351     FNQUAL_COMPONENT_CASE:
5352     modifier:
5353       {
5354 	/* We keep a list of modifiers on the stack.  */
5355 	struct d_print_mod dpm;
5356 
5357 	dpm.next = dpi->modifiers;
5358 	dpi->modifiers = &dpm;
5359 	dpm.mod = dc;
5360 	dpm.printed = 0;
5361 	dpm.templates = dpi->templates;
5362 
5363 	if (!mod_inner)
5364 	  mod_inner = d_left (dc);
5365 
5366 	d_print_comp (dpi, options, mod_inner);
5367 
5368 	/* If the modifier didn't get printed by the type, print it
5369 	   now.  */
5370 	if (! dpm.printed)
5371 	  d_print_mod (dpi, options, dc);
5372 
5373 	dpi->modifiers = dpm.next;
5374 
5375 	if (need_template_restore)
5376 	  dpi->templates = saved_templates;
5377 
5378 	return;
5379       }
5380 
5381     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
5382       if ((options & DMGL_JAVA) == 0)
5383 	d_append_buffer (dpi, dc->u.s_builtin.type->name,
5384 			 dc->u.s_builtin.type->len);
5385       else
5386 	d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
5387 			 dc->u.s_builtin.type->java_len);
5388       return;
5389 
5390     case DEMANGLE_COMPONENT_VENDOR_TYPE:
5391       d_print_comp (dpi, options, d_left (dc));
5392       return;
5393 
5394     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
5395       {
5396 	if ((options & DMGL_RET_POSTFIX) != 0)
5397 	  d_print_function_type (dpi,
5398 				 options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5399 				 dc, dpi->modifiers);
5400 
5401 	/* Print return type if present */
5402 	if (d_left (dc) != NULL && (options & DMGL_RET_POSTFIX) != 0)
5403 	  d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5404 			d_left (dc));
5405 	else if (d_left (dc) != NULL && (options & DMGL_RET_DROP) == 0)
5406 	  {
5407 	    struct d_print_mod dpm;
5408 
5409 	    /* We must pass this type down as a modifier in order to
5410 	       print it in the right location.  */
5411 	    dpm.next = dpi->modifiers;
5412 	    dpi->modifiers = &dpm;
5413 	    dpm.mod = dc;
5414 	    dpm.printed = 0;
5415 	    dpm.templates = dpi->templates;
5416 
5417 	    d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5418 			  d_left (dc));
5419 
5420 	    dpi->modifiers = dpm.next;
5421 
5422 	    if (dpm.printed)
5423 	      return;
5424 
5425 	    /* In standard prefix notation, there is a space between the
5426 	       return type and the function signature.  */
5427 	    if ((options & DMGL_RET_POSTFIX) == 0)
5428 	      d_append_char (dpi, ' ');
5429 	  }
5430 
5431 	if ((options & DMGL_RET_POSTFIX) == 0)
5432 	  d_print_function_type (dpi,
5433 				 options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
5434 				 dc, dpi->modifiers);
5435 
5436 	return;
5437       }
5438 
5439     case DEMANGLE_COMPONENT_ARRAY_TYPE:
5440       {
5441 	struct d_print_mod *hold_modifiers;
5442 	struct d_print_mod adpm[4];
5443 	unsigned int i;
5444 	struct d_print_mod *pdpm;
5445 
5446 	/* We must pass this type down as a modifier in order to print
5447 	   multi-dimensional arrays correctly.  If the array itself is
5448 	   CV-qualified, we act as though the element type were
5449 	   CV-qualified.  We do this by copying the modifiers down
5450 	   rather than fiddling pointers, so that we don't wind up
5451 	   with a d_print_mod higher on the stack pointing into our
5452 	   stack frame after we return.  */
5453 
5454 	hold_modifiers = dpi->modifiers;
5455 
5456 	adpm[0].next = hold_modifiers;
5457 	dpi->modifiers = &adpm[0];
5458 	adpm[0].mod = dc;
5459 	adpm[0].printed = 0;
5460 	adpm[0].templates = dpi->templates;
5461 
5462 	i = 1;
5463 	pdpm = hold_modifiers;
5464 	while (pdpm != NULL
5465 	       && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
5466 		   || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
5467 		   || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
5468 	  {
5469 	    if (! pdpm->printed)
5470 	      {
5471 		if (i >= sizeof adpm / sizeof adpm[0])
5472 		  {
5473 		    d_print_error (dpi);
5474 		    return;
5475 		  }
5476 
5477 		adpm[i] = *pdpm;
5478 		adpm[i].next = dpi->modifiers;
5479 		dpi->modifiers = &adpm[i];
5480 		pdpm->printed = 1;
5481 		++i;
5482 	      }
5483 
5484 	    pdpm = pdpm->next;
5485 	  }
5486 
5487 	d_print_comp (dpi, options, d_right (dc));
5488 
5489 	dpi->modifiers = hold_modifiers;
5490 
5491 	if (adpm[0].printed)
5492 	  return;
5493 
5494 	while (i > 1)
5495 	  {
5496 	    --i;
5497 	    d_print_mod (dpi, options, adpm[i].mod);
5498 	  }
5499 
5500 	d_print_array_type (dpi, options, dc, dpi->modifiers);
5501 
5502 	return;
5503       }
5504 
5505     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5506     case DEMANGLE_COMPONENT_VECTOR_TYPE:
5507       {
5508 	struct d_print_mod dpm;
5509 
5510 	dpm.next = dpi->modifiers;
5511 	dpi->modifiers = &dpm;
5512 	dpm.mod = dc;
5513 	dpm.printed = 0;
5514 	dpm.templates = dpi->templates;
5515 
5516 	d_print_comp (dpi, options, d_right (dc));
5517 
5518 	/* If the modifier didn't get printed by the type, print it
5519 	   now.  */
5520 	if (! dpm.printed)
5521 	  d_print_mod (dpi, options, dc);
5522 
5523 	dpi->modifiers = dpm.next;
5524 
5525 	return;
5526       }
5527 
5528     case DEMANGLE_COMPONENT_FIXED_TYPE:
5529       if (dc->u.s_fixed.sat)
5530 	d_append_string (dpi, "_Sat ");
5531       /* Don't print "int _Accum".  */
5532       if (dc->u.s_fixed.length->u.s_builtin.type
5533 	  != &cplus_demangle_builtin_types['i'-'a'])
5534 	{
5535 	  d_print_comp (dpi, options, dc->u.s_fixed.length);
5536 	  d_append_char (dpi, ' ');
5537 	}
5538       if (dc->u.s_fixed.accum)
5539 	d_append_string (dpi, "_Accum");
5540       else
5541 	d_append_string (dpi, "_Fract");
5542       return;
5543 
5544     case DEMANGLE_COMPONENT_ARGLIST:
5545     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
5546       if (d_left (dc) != NULL)
5547 	d_print_comp (dpi, options, d_left (dc));
5548       if (d_right (dc) != NULL)
5549 	{
5550 	  size_t len;
5551 	  unsigned long int flush_count;
5552 	  /* Make sure ", " isn't flushed by d_append_string, otherwise
5553 	     dpi->len -= 2 wouldn't work.  */
5554 	  if (dpi->len >= sizeof (dpi->buf) - 2)
5555 	    d_print_flush (dpi);
5556 	  d_append_string (dpi, ", ");
5557 	  len = dpi->len;
5558 	  flush_count = dpi->flush_count;
5559 	  d_print_comp (dpi, options, d_right (dc));
5560 	  /* If that didn't print anything (which can happen with empty
5561 	     template argument packs), remove the comma and space.  */
5562 	  if (dpi->flush_count == flush_count && dpi->len == len)
5563 	    dpi->len -= 2;
5564 	}
5565       return;
5566 
5567     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
5568       {
5569 	struct demangle_component *type = d_left (dc);
5570 	struct demangle_component *list = d_right (dc);
5571 
5572 	if (type)
5573 	  d_print_comp (dpi, options, type);
5574 	d_append_char (dpi, '{');
5575 	d_print_comp (dpi, options, list);
5576 	d_append_char (dpi, '}');
5577       }
5578       return;
5579 
5580     case DEMANGLE_COMPONENT_OPERATOR:
5581       {
5582 	const struct demangle_operator_info *op = dc->u.s_operator.op;
5583 	int len = op->len;
5584 
5585 	d_append_string (dpi, "operator");
5586 	/* Add a space before new/delete.  */
5587 	if (IS_LOWER (op->name[0]))
5588 	  d_append_char (dpi, ' ');
5589 	/* Omit a trailing space.  */
5590 	if (op->name[len-1] == ' ')
5591 	  --len;
5592 	d_append_buffer (dpi, op->name, len);
5593 	return;
5594       }
5595 
5596     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
5597       d_append_string (dpi, "operator ");
5598       d_print_comp (dpi, options, dc->u.s_extended_operator.name);
5599       return;
5600 
5601     case DEMANGLE_COMPONENT_CONVERSION:
5602       d_append_string (dpi, "operator ");
5603       d_print_conversion (dpi, options, dc);
5604       return;
5605 
5606     case DEMANGLE_COMPONENT_NULLARY:
5607       d_print_expr_op (dpi, options, d_left (dc));
5608       return;
5609 
5610     case DEMANGLE_COMPONENT_UNARY:
5611       {
5612 	struct demangle_component *op = d_left (dc);
5613 	struct demangle_component *operand = d_right (dc);
5614 	const char *code = NULL;
5615 
5616 	if (op->type == DEMANGLE_COMPONENT_OPERATOR)
5617 	  {
5618 	    code = op->u.s_operator.op->code;
5619 	    if (!strcmp (code, "ad"))
5620 	      {
5621 		/* Don't print the argument list for the address of a
5622 		   function.  */
5623 		if (operand->type == DEMANGLE_COMPONENT_TYPED_NAME
5624 		    && d_left (operand)->type == DEMANGLE_COMPONENT_QUAL_NAME
5625 		    && d_right (operand)->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5626 		  operand = d_left (operand);
5627 	      }
5628 	    if (operand->type == DEMANGLE_COMPONENT_BINARY_ARGS)
5629 	      {
5630 		/* This indicates a suffix operator.  */
5631 		operand = d_left (operand);
5632 		d_print_subexpr (dpi, options, operand);
5633 		d_print_expr_op (dpi, options, op);
5634 		return;
5635 	      }
5636 	  }
5637 
5638 	/* For sizeof..., just print the pack length.  */
5639 	if (code && !strcmp (code, "sZ"))
5640 	  {
5641 	    struct demangle_component *a = d_find_pack (dpi, operand);
5642 	    int len = d_pack_length (a);
5643 	    d_append_num (dpi, len);
5644 	    return;
5645 	  }
5646 	else if (code && !strcmp (code, "sP"))
5647 	  {
5648 	    int len = d_args_length (dpi, operand);
5649 	    d_append_num (dpi, len);
5650 	    return;
5651 	  }
5652 
5653 	if (op->type != DEMANGLE_COMPONENT_CAST)
5654 	  d_print_expr_op (dpi, options, op);
5655 	else
5656 	  {
5657 	    d_append_char (dpi, '(');
5658 	    d_print_cast (dpi, options, op);
5659 	    d_append_char (dpi, ')');
5660 	  }
5661 	if (code && !strcmp (code, "gs"))
5662 	  /* Avoid parens after '::'.  */
5663 	  d_print_comp (dpi, options, operand);
5664 	else if (code && !strcmp (code, "st"))
5665 	  /* Always print parens for sizeof (type).  */
5666 	  {
5667 	    d_append_char (dpi, '(');
5668 	    d_print_comp (dpi, options, operand);
5669 	    d_append_char (dpi, ')');
5670 	  }
5671 	else
5672 	  d_print_subexpr (dpi, options, operand);
5673       }
5674       return;
5675 
5676     case DEMANGLE_COMPONENT_BINARY:
5677       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
5678 	{
5679 	  d_print_error (dpi);
5680 	  return;
5681 	}
5682 
5683       if (op_is_new_cast (d_left (dc)))
5684 	{
5685 	  d_print_expr_op (dpi, options, d_left (dc));
5686 	  d_append_char (dpi, '<');
5687 	  d_print_comp (dpi, options, d_left (d_right (dc)));
5688 	  d_append_string (dpi, ">(");
5689 	  d_print_comp (dpi, options, d_right (d_right (dc)));
5690 	  d_append_char (dpi, ')');
5691 	  return;
5692 	}
5693 
5694       if (d_maybe_print_fold_expression (dpi, options, dc))
5695 	return;
5696 
5697       if (d_maybe_print_designated_init (dpi, options, dc))
5698 	return;
5699 
5700       /* We wrap an expression which uses the greater-than operator in
5701 	 an extra layer of parens so that it does not get confused
5702 	 with the '>' which ends the template parameters.  */
5703       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5704 	  && d_left (dc)->u.s_operator.op->len == 1
5705 	  && d_left (dc)->u.s_operator.op->name[0] == '>')
5706 	d_append_char (dpi, '(');
5707 
5708       if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") == 0
5709           && d_left (d_right (dc))->type == DEMANGLE_COMPONENT_TYPED_NAME)
5710 	{
5711 	  /* Function call used in an expression should not have printed types
5712 	     of the function arguments.  Values of the function arguments still
5713 	     get printed below.  */
5714 
5715 	  const struct demangle_component *func = d_left (d_right (dc));
5716 
5717 	  if (d_right (func)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
5718 	    d_print_error (dpi);
5719 	  d_print_subexpr (dpi, options, d_left (func));
5720 	}
5721       else
5722 	d_print_subexpr (dpi, options, d_left (d_right (dc)));
5723       if (strcmp (d_left (dc)->u.s_operator.op->code, "ix") == 0)
5724 	{
5725 	  d_append_char (dpi, '[');
5726 	  d_print_comp (dpi, options, d_right (d_right (dc)));
5727 	  d_append_char (dpi, ']');
5728 	}
5729       else
5730 	{
5731 	  if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") != 0)
5732 	    d_print_expr_op (dpi, options, d_left (dc));
5733 	  d_print_subexpr (dpi, options, d_right (d_right (dc)));
5734 	}
5735 
5736       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5737 	  && d_left (dc)->u.s_operator.op->len == 1
5738 	  && d_left (dc)->u.s_operator.op->name[0] == '>')
5739 	d_append_char (dpi, ')');
5740 
5741       return;
5742 
5743     case DEMANGLE_COMPONENT_BINARY_ARGS:
5744       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
5745       d_print_error (dpi);
5746       return;
5747 
5748     case DEMANGLE_COMPONENT_TRINARY:
5749       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
5750 	  || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
5751 	{
5752 	  d_print_error (dpi);
5753 	  return;
5754 	}
5755       if (d_maybe_print_fold_expression (dpi, options, dc))
5756 	return;
5757       if (d_maybe_print_designated_init (dpi, options, dc))
5758 	return;
5759       {
5760 	struct demangle_component *op = d_left (dc);
5761 	struct demangle_component *first = d_left (d_right (dc));
5762 	struct demangle_component *second = d_left (d_right (d_right (dc)));
5763 	struct demangle_component *third = d_right (d_right (d_right (dc)));
5764 
5765 	if (!strcmp (op->u.s_operator.op->code, "qu"))
5766 	  {
5767 	    d_print_subexpr (dpi, options, first);
5768 	    d_print_expr_op (dpi, options, op);
5769 	    d_print_subexpr (dpi, options, second);
5770 	    d_append_string (dpi, " : ");
5771 	    d_print_subexpr (dpi, options, third);
5772 	  }
5773 	else
5774 	  {
5775 	    d_append_string (dpi, "new ");
5776 	    if (d_left (first) != NULL)
5777 	      {
5778 		d_print_subexpr (dpi, options, first);
5779 		d_append_char (dpi, ' ');
5780 	      }
5781 	    d_print_comp (dpi, options, second);
5782 	    if (third)
5783 	      d_print_subexpr (dpi, options, third);
5784 	  }
5785       }
5786       return;
5787 
5788     case DEMANGLE_COMPONENT_TRINARY_ARG1:
5789     case DEMANGLE_COMPONENT_TRINARY_ARG2:
5790       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
5791       d_print_error (dpi);
5792       return;
5793 
5794     case DEMANGLE_COMPONENT_LITERAL:
5795     case DEMANGLE_COMPONENT_LITERAL_NEG:
5796       {
5797 	enum d_builtin_type_print tp;
5798 
5799 	/* For some builtin types, produce simpler output.  */
5800 	tp = D_PRINT_DEFAULT;
5801 	if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
5802 	  {
5803 	    tp = d_left (dc)->u.s_builtin.type->print;
5804 	    switch (tp)
5805 	      {
5806 	      case D_PRINT_INT:
5807 	      case D_PRINT_UNSIGNED:
5808 	      case D_PRINT_LONG:
5809 	      case D_PRINT_UNSIGNED_LONG:
5810 	      case D_PRINT_LONG_LONG:
5811 	      case D_PRINT_UNSIGNED_LONG_LONG:
5812 		if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
5813 		  {
5814 		    if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5815 		      d_append_char (dpi, '-');
5816 		    d_print_comp (dpi, options, d_right (dc));
5817 		    switch (tp)
5818 		      {
5819 		      default:
5820 			break;
5821 		      case D_PRINT_UNSIGNED:
5822 			d_append_char (dpi, 'u');
5823 			break;
5824 		      case D_PRINT_LONG:
5825 			d_append_char (dpi, 'l');
5826 			break;
5827 		      case D_PRINT_UNSIGNED_LONG:
5828 			d_append_string (dpi, "ul");
5829 			break;
5830 		      case D_PRINT_LONG_LONG:
5831 			d_append_string (dpi, "ll");
5832 			break;
5833 		      case D_PRINT_UNSIGNED_LONG_LONG:
5834 			d_append_string (dpi, "ull");
5835 			break;
5836 		      }
5837 		    return;
5838 		  }
5839 		break;
5840 
5841 	      case D_PRINT_BOOL:
5842 		if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
5843 		    && d_right (dc)->u.s_name.len == 1
5844 		    && dc->type == DEMANGLE_COMPONENT_LITERAL)
5845 		  {
5846 		    switch (d_right (dc)->u.s_name.s[0])
5847 		      {
5848 		      case '0':
5849 			d_append_string (dpi, "false");
5850 			return;
5851 		      case '1':
5852 			d_append_string (dpi, "true");
5853 			return;
5854 		      default:
5855 			break;
5856 		      }
5857 		  }
5858 		break;
5859 
5860 	      default:
5861 		break;
5862 	      }
5863 	  }
5864 
5865 	d_append_char (dpi, '(');
5866 	d_print_comp (dpi, options, d_left (dc));
5867 	d_append_char (dpi, ')');
5868 	if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5869 	  d_append_char (dpi, '-');
5870 	if (tp == D_PRINT_FLOAT)
5871 	  d_append_char (dpi, '[');
5872 	d_print_comp (dpi, options, d_right (dc));
5873 	if (tp == D_PRINT_FLOAT)
5874 	  d_append_char (dpi, ']');
5875       }
5876       return;
5877 
5878     case DEMANGLE_COMPONENT_VENDOR_EXPR:
5879       d_print_comp (dpi, options, d_left (dc));
5880       d_append_char (dpi, '(');
5881       d_print_comp (dpi, options, d_right (dc));
5882       d_append_char (dpi, ')');
5883       return;
5884 
5885     case DEMANGLE_COMPONENT_NUMBER:
5886       d_append_num (dpi, dc->u.s_number.number);
5887       return;
5888 
5889     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
5890       d_append_string (dpi, "java resource ");
5891       d_print_comp (dpi, options, d_left (dc));
5892       return;
5893 
5894     case DEMANGLE_COMPONENT_COMPOUND_NAME:
5895       d_print_comp (dpi, options, d_left (dc));
5896       d_print_comp (dpi, options, d_right (dc));
5897       return;
5898 
5899     case DEMANGLE_COMPONENT_CHARACTER:
5900       d_append_char (dpi, dc->u.s_character.character);
5901       return;
5902 
5903     case DEMANGLE_COMPONENT_DECLTYPE:
5904       d_append_string (dpi, "decltype (");
5905       d_print_comp (dpi, options, d_left (dc));
5906       d_append_char (dpi, ')');
5907       return;
5908 
5909     case DEMANGLE_COMPONENT_PACK_EXPANSION:
5910       {
5911 	int len;
5912 	int i;
5913 	struct demangle_component *a = d_find_pack (dpi, d_left (dc));
5914 	if (a == NULL)
5915 	  {
5916 	    /* d_find_pack won't find anything if the only packs involved
5917 	       in this expansion are function parameter packs; in that
5918 	       case, just print the pattern and "...".  */
5919 	    d_print_subexpr (dpi, options, d_left (dc));
5920 	    d_append_string (dpi, "...");
5921 	    return;
5922 	  }
5923 
5924 	len = d_pack_length (a);
5925 	dc = d_left (dc);
5926 	for (i = 0; i < len; ++i)
5927 	  {
5928 	    dpi->pack_index = i;
5929 	    d_print_comp (dpi, options, dc);
5930 	    if (i < len-1)
5931 	      d_append_string (dpi, ", ");
5932 	  }
5933       }
5934       return;
5935 
5936     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
5937       {
5938 	long num = dc->u.s_number.number;
5939 	if (num == 0)
5940 	  d_append_string (dpi, "this");
5941 	else
5942 	  {
5943 	    d_append_string (dpi, "{parm#");
5944 	    d_append_num (dpi, num);
5945 	    d_append_char (dpi, '}');
5946 	  }
5947       }
5948       return;
5949 
5950     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
5951       d_append_string (dpi, "global constructors keyed to ");
5952       d_print_comp (dpi, options, dc->u.s_binary.left);
5953       return;
5954 
5955     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
5956       d_append_string (dpi, "global destructors keyed to ");
5957       d_print_comp (dpi, options, dc->u.s_binary.left);
5958       return;
5959 
5960     case DEMANGLE_COMPONENT_LAMBDA:
5961       d_append_string (dpi, "{lambda(");
5962       /* Generic lambda auto parms are mangled as the template type
5963 	 parm they are.  */
5964       dpi->is_lambda_arg++;
5965       d_print_comp (dpi, options, dc->u.s_unary_num.sub);
5966       dpi->is_lambda_arg--;
5967       d_append_string (dpi, ")#");
5968       d_append_num (dpi, dc->u.s_unary_num.num + 1);
5969       d_append_char (dpi, '}');
5970       return;
5971 
5972     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
5973       d_append_string (dpi, "{unnamed type#");
5974       d_append_num (dpi, dc->u.s_number.number + 1);
5975       d_append_char (dpi, '}');
5976       return;
5977 
5978     case DEMANGLE_COMPONENT_CLONE:
5979       d_print_comp (dpi, options, d_left (dc));
5980       d_append_string (dpi, " [clone ");
5981       d_print_comp (dpi, options, d_right (dc));
5982       d_append_char (dpi, ']');
5983       return;
5984 
5985     default:
5986       d_print_error (dpi);
5987       return;
5988     }
5989 }
5990 
5991 static void
d_print_comp(struct d_print_info * dpi,int options,struct demangle_component * dc)5992 d_print_comp (struct d_print_info *dpi, int options,
5993 	      struct demangle_component *dc)
5994 {
5995   struct d_component_stack self;
5996   if (dc == NULL || dc->d_printing > 1 || dpi->recursion > MAX_RECURSION_COUNT)
5997     {
5998       d_print_error (dpi);
5999       return;
6000     }
6001 
6002   dc->d_printing++;
6003   dpi->recursion++;
6004 
6005   self.dc = dc;
6006   self.parent = dpi->component_stack;
6007   dpi->component_stack = &self;
6008 
6009   d_print_comp_inner (dpi, options, dc);
6010 
6011   dpi->component_stack = self.parent;
6012   dc->d_printing--;
6013   dpi->recursion--;
6014 }
6015 
6016 /* Print a Java dentifier.  For Java we try to handle encoded extended
6017    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
6018    so we don't it for C++.  Characters are encoded as
6019    __U<hex-char>+_.  */
6020 
6021 static void
d_print_java_identifier(struct d_print_info * dpi,const char * name,int len)6022 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
6023 {
6024   const char *p;
6025   const char *end;
6026 
6027   end = name + len;
6028   for (p = name; p < end; ++p)
6029     {
6030       if (end - p > 3
6031 	  && p[0] == '_'
6032 	  && p[1] == '_'
6033 	  && p[2] == 'U')
6034 	{
6035 	  unsigned long c;
6036 	  const char *q;
6037 
6038 	  c = 0;
6039 	  for (q = p + 3; q < end; ++q)
6040 	    {
6041 	      int dig;
6042 
6043 	      if (IS_DIGIT (*q))
6044 		dig = *q - '0';
6045 	      else if (*q >= 'A' && *q <= 'F')
6046 		dig = *q - 'A' + 10;
6047 	      else if (*q >= 'a' && *q <= 'f')
6048 		dig = *q - 'a' + 10;
6049 	      else
6050 		break;
6051 
6052 	      c = c * 16 + dig;
6053 	    }
6054 	  /* If the Unicode character is larger than 256, we don't try
6055 	     to deal with it here.  FIXME.  */
6056 	  if (q < end && *q == '_' && c < 256)
6057 	    {
6058 	      d_append_char (dpi, c);
6059 	      p = q;
6060 	      continue;
6061 	    }
6062 	}
6063 
6064       d_append_char (dpi, *p);
6065     }
6066 }
6067 
6068 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
6069    qualifiers on this after printing a function.  */
6070 
6071 static void
d_print_mod_list(struct d_print_info * dpi,int options,struct d_print_mod * mods,int suffix)6072 d_print_mod_list (struct d_print_info *dpi, int options,
6073                   struct d_print_mod *mods, int suffix)
6074 {
6075   struct d_print_template *hold_dpt;
6076 
6077   if (mods == NULL || d_print_saw_error (dpi))
6078     return;
6079 
6080   if (mods->printed
6081       || (! suffix
6082 	  && (is_fnqual_component_type (mods->mod->type))))
6083     {
6084       d_print_mod_list (dpi, options, mods->next, suffix);
6085       return;
6086     }
6087 
6088   mods->printed = 1;
6089 
6090   hold_dpt = dpi->templates;
6091   dpi->templates = mods->templates;
6092 
6093   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
6094     {
6095       d_print_function_type (dpi, options, mods->mod, mods->next);
6096       dpi->templates = hold_dpt;
6097       return;
6098     }
6099   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
6100     {
6101       d_print_array_type (dpi, options, mods->mod, mods->next);
6102       dpi->templates = hold_dpt;
6103       return;
6104     }
6105   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
6106     {
6107       struct d_print_mod *hold_modifiers;
6108       struct demangle_component *dc;
6109 
6110       /* When this is on the modifier stack, we have pulled any
6111 	 qualifiers off the right argument already.  Otherwise, we
6112 	 print it as usual, but don't let the left argument see any
6113 	 modifiers.  */
6114 
6115       hold_modifiers = dpi->modifiers;
6116       dpi->modifiers = NULL;
6117       d_print_comp (dpi, options, d_left (mods->mod));
6118       dpi->modifiers = hold_modifiers;
6119 
6120       if ((options & DMGL_JAVA) == 0)
6121 	d_append_string (dpi, "::");
6122       else
6123 	d_append_char (dpi, '.');
6124 
6125       dc = d_right (mods->mod);
6126 
6127       if (dc->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
6128 	{
6129 	  d_append_string (dpi, "{default arg#");
6130 	  d_append_num (dpi, dc->u.s_unary_num.num + 1);
6131 	  d_append_string (dpi, "}::");
6132 	  dc = dc->u.s_unary_num.sub;
6133 	}
6134 
6135       while (is_fnqual_component_type (dc->type))
6136 	dc = d_left (dc);
6137 
6138       d_print_comp (dpi, options, dc);
6139 
6140       dpi->templates = hold_dpt;
6141       return;
6142     }
6143 
6144   d_print_mod (dpi, options, mods->mod);
6145 
6146   dpi->templates = hold_dpt;
6147 
6148   d_print_mod_list (dpi, options, mods->next, suffix);
6149 }
6150 
6151 /* Print a modifier.  */
6152 
6153 static void
d_print_mod(struct d_print_info * dpi,int options,struct demangle_component * mod)6154 d_print_mod (struct d_print_info *dpi, int options,
6155              struct demangle_component *mod)
6156 {
6157   switch (mod->type)
6158     {
6159     case DEMANGLE_COMPONENT_RESTRICT:
6160     case DEMANGLE_COMPONENT_RESTRICT_THIS:
6161       d_append_string (dpi, " restrict");
6162       return;
6163     case DEMANGLE_COMPONENT_VOLATILE:
6164     case DEMANGLE_COMPONENT_VOLATILE_THIS:
6165       d_append_string (dpi, " volatile");
6166       return;
6167     case DEMANGLE_COMPONENT_CONST:
6168     case DEMANGLE_COMPONENT_CONST_THIS:
6169       d_append_string (dpi, " const");
6170       return;
6171     case DEMANGLE_COMPONENT_TRANSACTION_SAFE:
6172       d_append_string (dpi, " transaction_safe");
6173       return;
6174     case DEMANGLE_COMPONENT_NOEXCEPT:
6175       d_append_string (dpi, " noexcept");
6176       if (d_right (mod))
6177 	{
6178 	  d_append_char (dpi, '(');
6179 	  d_print_comp (dpi, options, d_right (mod));
6180 	  d_append_char (dpi, ')');
6181 	}
6182       return;
6183     case DEMANGLE_COMPONENT_THROW_SPEC:
6184       d_append_string (dpi, " throw");
6185       if (d_right (mod))
6186 	{
6187 	  d_append_char (dpi, '(');
6188 	  d_print_comp (dpi, options, d_right (mod));
6189 	  d_append_char (dpi, ')');
6190 	}
6191       return;
6192     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
6193       d_append_char (dpi, ' ');
6194       d_print_comp (dpi, options, d_right (mod));
6195       return;
6196     case DEMANGLE_COMPONENT_POINTER:
6197       /* There is no pointer symbol in Java.  */
6198       if ((options & DMGL_JAVA) == 0)
6199 	d_append_char (dpi, '*');
6200       return;
6201     case DEMANGLE_COMPONENT_REFERENCE_THIS:
6202       /* For the ref-qualifier, put a space before the &.  */
6203       d_append_char (dpi, ' ');
6204       /* FALLTHRU */
6205     case DEMANGLE_COMPONENT_REFERENCE:
6206       d_append_char (dpi, '&');
6207       return;
6208     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
6209       d_append_char (dpi, ' ');
6210       /* FALLTHRU */
6211     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
6212       d_append_string (dpi, "&&");
6213       return;
6214     case DEMANGLE_COMPONENT_COMPLEX:
6215       d_append_string (dpi, " _Complex");
6216       return;
6217     case DEMANGLE_COMPONENT_IMAGINARY:
6218       d_append_string (dpi, " _Imaginary");
6219       return;
6220     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
6221       if (d_last_char (dpi) != '(')
6222 	d_append_char (dpi, ' ');
6223       d_print_comp (dpi, options, d_left (mod));
6224       d_append_string (dpi, "::*");
6225       return;
6226     case DEMANGLE_COMPONENT_TYPED_NAME:
6227       d_print_comp (dpi, options, d_left (mod));
6228       return;
6229     case DEMANGLE_COMPONENT_VECTOR_TYPE:
6230       d_append_string (dpi, " __vector(");
6231       d_print_comp (dpi, options, d_left (mod));
6232       d_append_char (dpi, ')');
6233       return;
6234 
6235     default:
6236       /* Otherwise, we have something that won't go back on the
6237 	 modifier stack, so we can just print it.  */
6238       d_print_comp (dpi, options, mod);
6239       return;
6240     }
6241 }
6242 
6243 /* Print a function type, except for the return type.  */
6244 
6245 static void
d_print_function_type(struct d_print_info * dpi,int options,struct demangle_component * dc,struct d_print_mod * mods)6246 d_print_function_type (struct d_print_info *dpi, int options,
6247                        struct demangle_component *dc,
6248                        struct d_print_mod *mods)
6249 {
6250   int need_paren;
6251   int need_space;
6252   struct d_print_mod *p;
6253   struct d_print_mod *hold_modifiers;
6254 
6255   need_paren = 0;
6256   need_space = 0;
6257   for (p = mods; p != NULL; p = p->next)
6258     {
6259       if (p->printed)
6260 	break;
6261 
6262       switch (p->mod->type)
6263 	{
6264 	case DEMANGLE_COMPONENT_POINTER:
6265 	case DEMANGLE_COMPONENT_REFERENCE:
6266 	case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
6267 	  need_paren = 1;
6268 	  break;
6269 	case DEMANGLE_COMPONENT_RESTRICT:
6270 	case DEMANGLE_COMPONENT_VOLATILE:
6271 	case DEMANGLE_COMPONENT_CONST:
6272 	case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
6273 	case DEMANGLE_COMPONENT_COMPLEX:
6274 	case DEMANGLE_COMPONENT_IMAGINARY:
6275 	case DEMANGLE_COMPONENT_PTRMEM_TYPE:
6276 	  need_space = 1;
6277 	  need_paren = 1;
6278 	  break;
6279 	FNQUAL_COMPONENT_CASE:
6280 	  break;
6281 	default:
6282 	  break;
6283 	}
6284       if (need_paren)
6285 	break;
6286     }
6287 
6288   if (need_paren)
6289     {
6290       if (! need_space)
6291 	{
6292 	  if (d_last_char (dpi) != '('
6293 	      && d_last_char (dpi) != '*')
6294 	    need_space = 1;
6295 	}
6296       if (need_space && d_last_char (dpi) != ' ')
6297 	d_append_char (dpi, ' ');
6298       d_append_char (dpi, '(');
6299     }
6300 
6301   hold_modifiers = dpi->modifiers;
6302   dpi->modifiers = NULL;
6303 
6304   d_print_mod_list (dpi, options, mods, 0);
6305 
6306   if (need_paren)
6307     d_append_char (dpi, ')');
6308 
6309   d_append_char (dpi, '(');
6310 
6311   if (d_right (dc) != NULL)
6312     d_print_comp (dpi, options, d_right (dc));
6313 
6314   d_append_char (dpi, ')');
6315 
6316   d_print_mod_list (dpi, options, mods, 1);
6317 
6318   dpi->modifiers = hold_modifiers;
6319 }
6320 
6321 /* Print an array type, except for the element type.  */
6322 
6323 static void
d_print_array_type(struct d_print_info * dpi,int options,struct demangle_component * dc,struct d_print_mod * mods)6324 d_print_array_type (struct d_print_info *dpi, int options,
6325                     struct demangle_component *dc,
6326                     struct d_print_mod *mods)
6327 {
6328   int need_space;
6329 
6330   need_space = 1;
6331   if (mods != NULL)
6332     {
6333       int need_paren;
6334       struct d_print_mod *p;
6335 
6336       need_paren = 0;
6337       for (p = mods; p != NULL; p = p->next)
6338 	{
6339 	  if (! p->printed)
6340 	    {
6341 	      if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
6342 		{
6343 		  need_space = 0;
6344 		  break;
6345 		}
6346 	      else
6347 		{
6348 		  need_paren = 1;
6349 		  need_space = 1;
6350 		  break;
6351 		}
6352 	    }
6353 	}
6354 
6355       if (need_paren)
6356 	d_append_string (dpi, " (");
6357 
6358       d_print_mod_list (dpi, options, mods, 0);
6359 
6360       if (need_paren)
6361 	d_append_char (dpi, ')');
6362     }
6363 
6364   if (need_space)
6365     d_append_char (dpi, ' ');
6366 
6367   d_append_char (dpi, '[');
6368 
6369   if (d_left (dc) != NULL)
6370     d_print_comp (dpi, options, d_left (dc));
6371 
6372   d_append_char (dpi, ']');
6373 }
6374 
6375 /* Print an operator in an expression.  */
6376 
6377 static void
d_print_expr_op(struct d_print_info * dpi,int options,struct demangle_component * dc)6378 d_print_expr_op (struct d_print_info *dpi, int options,
6379                  struct demangle_component *dc)
6380 {
6381   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
6382     d_append_buffer (dpi, dc->u.s_operator.op->name,
6383 		     dc->u.s_operator.op->len);
6384   else
6385     d_print_comp (dpi, options, dc);
6386 }
6387 
6388 /* Print a cast.  */
6389 
6390 static void
d_print_cast(struct d_print_info * dpi,int options,struct demangle_component * dc)6391 d_print_cast (struct d_print_info *dpi, int options,
6392 	      struct demangle_component *dc)
6393 {
6394   d_print_comp (dpi, options, d_left (dc));
6395 }
6396 
6397 /* Print a conversion operator.  */
6398 
6399 static void
d_print_conversion(struct d_print_info * dpi,int options,struct demangle_component * dc)6400 d_print_conversion (struct d_print_info *dpi, int options,
6401 		    struct demangle_component *dc)
6402 {
6403   struct d_print_template dpt;
6404 
6405   /* For a conversion operator, we need the template parameters from
6406      the enclosing template in scope for processing the type.  */
6407   if (dpi->current_template != NULL)
6408     {
6409       dpt.next = dpi->templates;
6410       dpi->templates = &dpt;
6411       dpt.template_decl = dpi->current_template;
6412     }
6413 
6414   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
6415     {
6416       d_print_comp (dpi, options, d_left (dc));
6417       if (dpi->current_template != NULL)
6418 	dpi->templates = dpt.next;
6419     }
6420   else
6421     {
6422       d_print_comp (dpi, options, d_left (d_left (dc)));
6423 
6424       /* For a templated cast operator, we need to remove the template
6425 	 parameters from scope after printing the operator name,
6426 	 so we need to handle the template printing here.  */
6427       if (dpi->current_template != NULL)
6428 	dpi->templates = dpt.next;
6429 
6430       if (d_last_char (dpi) == '<')
6431 	d_append_char (dpi, ' ');
6432       d_append_char (dpi, '<');
6433       d_print_comp (dpi, options, d_right (d_left (dc)));
6434       /* Avoid generating two consecutive '>' characters, to avoid
6435 	 the C++ syntactic ambiguity.  */
6436       if (d_last_char (dpi) == '>')
6437 	d_append_char (dpi, ' ');
6438       d_append_char (dpi, '>');
6439     }
6440 }
6441 
6442 /* Initialize the information structure we use to pass around
6443    information.  */
6444 
6445 CP_STATIC_IF_GLIBCPP_V3
6446 void
cplus_demangle_init_info(const char * mangled,int options,size_t len,struct d_info * di)6447 cplus_demangle_init_info (const char *mangled, int options, size_t len,
6448                           struct d_info *di)
6449 {
6450   di->s = mangled;
6451   di->send = mangled + len;
6452   di->options = options;
6453 
6454   di->n = mangled;
6455 
6456   /* We cannot need more components than twice the number of chars in
6457      the mangled string.  Most components correspond directly to
6458      chars, but the ARGLIST types are exceptions.  */
6459   di->num_comps = 2 * len;
6460   di->next_comp = 0;
6461 
6462   /* Similarly, we cannot need more substitutions than there are
6463      chars in the mangled string.  */
6464   di->num_subs = len;
6465   di->next_sub = 0;
6466 
6467   di->last_name = NULL;
6468 
6469   di->expansion = 0;
6470   di->is_expression = 0;
6471   di->is_conversion = 0;
6472   di->recursion_level = 0;
6473 }
6474 
6475 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
6476    mangled name, return strings in repeated callback giving the demangled
6477    name.  OPTIONS is the usual libiberty demangler options.  On success,
6478    this returns 1.  On failure, returns 0.  */
6479 
6480 static int
d_demangle_callback(const char * mangled,int options,demangle_callbackref callback,void * opaque)6481 d_demangle_callback (const char *mangled, int options,
6482                      demangle_callbackref callback, void *opaque)
6483 {
6484   enum
6485     {
6486       DCT_TYPE,
6487       DCT_MANGLED,
6488       DCT_GLOBAL_CTORS,
6489       DCT_GLOBAL_DTORS
6490     }
6491   type;
6492   struct d_info di;
6493   struct demangle_component *dc;
6494   int status;
6495 
6496   if (mangled[0] == '_' && mangled[1] == 'Z')
6497     type = DCT_MANGLED;
6498   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
6499 	   && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
6500 	   && (mangled[9] == 'D' || mangled[9] == 'I')
6501 	   && mangled[10] == '_')
6502     type = mangled[9] == 'I' ? DCT_GLOBAL_CTORS : DCT_GLOBAL_DTORS;
6503   else
6504     {
6505       if ((options & DMGL_TYPES) == 0)
6506 	return 0;
6507       type = DCT_TYPE;
6508     }
6509 
6510   di.unresolved_name_state = 1;
6511 
6512  again:
6513   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
6514 
6515   /* PR 87675 - Check for a mangled string that is so long
6516      that we do not have enough stack space to demangle it.  */
6517   if (((options & DMGL_NO_RECURSE_LIMIT) == 0)
6518       /* This check is a bit arbitrary, since what we really want to do is to
6519 	 compare the sizes of the di.comps and di.subs arrays against the
6520 	 amount of stack space remaining.  But there is no portable way to do
6521 	 this, so instead we use the recursion limit as a guide to the maximum
6522 	 size of the arrays.  */
6523       && (unsigned long) di.num_comps > DEMANGLE_RECURSION_LIMIT)
6524     {
6525       /* FIXME: We need a way to indicate that a stack limit has been reached.  */
6526       return 0;
6527     }
6528 
6529   {
6530 #ifdef CP_DYNAMIC_ARRAYS
6531     __extension__ struct demangle_component comps[di.num_comps];
6532     __extension__ struct demangle_component *subs[di.num_subs];
6533 
6534     di.comps = comps;
6535     di.subs = subs;
6536 #else
6537     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6538     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6539 #endif
6540 
6541     switch (type)
6542       {
6543       case DCT_TYPE:
6544 	dc = cplus_demangle_type (&di);
6545 	break;
6546       case DCT_MANGLED:
6547 	dc = cplus_demangle_mangled_name (&di, 1);
6548 	break;
6549       case DCT_GLOBAL_CTORS:
6550       case DCT_GLOBAL_DTORS:
6551 	d_advance (&di, 11);
6552 	dc = d_make_comp (&di,
6553 			  (type == DCT_GLOBAL_CTORS
6554 			   ? DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS
6555 			   : DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS),
6556 			  d_make_demangle_mangled_name (&di, d_str (&di)),
6557 			  NULL);
6558 	d_advance (&di, strlen (d_str (&di)));
6559 	break;
6560       default:
6561 	abort (); /* We have listed all the cases.  */
6562       }
6563 
6564     /* If DMGL_PARAMS is set, then if we didn't consume the entire
6565        mangled string, then we didn't successfully demangle it.  If
6566        DMGL_PARAMS is not set, we didn't look at the trailing
6567        parameters.  */
6568     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
6569       dc = NULL;
6570 
6571     /* See discussion in d_unresolved_name.  */
6572     if (dc == NULL && di.unresolved_name_state == -1)
6573       {
6574 	di.unresolved_name_state = 0;
6575 	goto again;
6576       }
6577 
6578 #ifdef CP_DEMANGLE_DEBUG
6579     d_dump (dc, 0);
6580 #endif
6581 
6582     status = (dc != NULL)
6583              ? cplus_demangle_print_callback (options, dc, callback, opaque)
6584              : 0;
6585   }
6586 
6587   return status;
6588 }
6589 
6590 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
6591    name, return a buffer allocated with malloc holding the demangled
6592    name.  OPTIONS is the usual libiberty demangler options.  On
6593    success, this sets *PALC to the allocated size of the returned
6594    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
6595    a memory allocation failure, and returns NULL.  */
6596 
6597 static char *
d_demangle(const char * mangled,int options,size_t * palc)6598 d_demangle (const char *mangled, int options, size_t *palc)
6599 {
6600   struct d_growable_string dgs;
6601   int status;
6602 
6603   d_growable_string_init (&dgs, 0);
6604 
6605   status = d_demangle_callback (mangled, options,
6606                                 d_growable_string_callback_adapter, &dgs);
6607   if (status == 0)
6608     {
6609       free (dgs.buf);
6610       *palc = 0;
6611       return NULL;
6612     }
6613 
6614   *palc = dgs.allocation_failure ? 1 : dgs.alc;
6615   return dgs.buf;
6616 }
6617 
6618 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
6619 
6620 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
6621 
6622 /* ia64 ABI-mandated entry point in the C++ runtime library for
6623    performing demangling.  MANGLED_NAME is a NUL-terminated character
6624    string containing the name to be demangled.
6625 
6626    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
6627    *LENGTH bytes, into which the demangled name is stored.  If
6628    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
6629    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
6630    is placed in a region of memory allocated with malloc.
6631 
6632    If LENGTH is non-NULL, the length of the buffer containing the
6633    demangled name, is placed in *LENGTH.
6634 
6635    The return value is a pointer to the start of the NUL-terminated
6636    demangled name, or NULL if the demangling fails.  The caller is
6637    responsible for deallocating this memory using free.
6638 
6639    *STATUS is set to one of the following values:
6640       0: The demangling operation succeeded.
6641      -1: A memory allocation failure occurred.
6642      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6643      -3: One of the arguments is invalid.
6644 
6645    The demangling is performed using the C++ ABI mangling rules, with
6646    GNU extensions.  */
6647 
6648 char *
__cxa_demangle(const char * mangled_name,char * output_buffer,size_t * length,int * status)6649 __cxa_demangle (const char *mangled_name, char *output_buffer,
6650                 size_t *length, int *status)
6651 {
6652   char *demangled;
6653   size_t alc;
6654 
6655   if (mangled_name == NULL)
6656     {
6657       if (status != NULL)
6658 	*status = -3;
6659       return NULL;
6660     }
6661 
6662   if (output_buffer != NULL && length == NULL)
6663     {
6664       if (status != NULL)
6665 	*status = -3;
6666       return NULL;
6667     }
6668 
6669   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
6670 
6671   if (demangled == NULL)
6672     {
6673       if (status != NULL)
6674 	{
6675 	  if (alc == 1)
6676 	    *status = -1;
6677 	  else
6678 	    *status = -2;
6679 	}
6680       return NULL;
6681     }
6682 
6683   if (output_buffer == NULL)
6684     {
6685       if (length != NULL)
6686 	*length = alc;
6687     }
6688   else
6689     {
6690       if (strlen (demangled) < *length)
6691 	{
6692 	  strcpy (output_buffer, demangled);
6693 	  free (demangled);
6694 	  demangled = output_buffer;
6695 	}
6696       else
6697 	{
6698 	  free (output_buffer);
6699 	  *length = alc;
6700 	}
6701     }
6702 
6703   if (status != NULL)
6704     *status = 0;
6705 
6706   return demangled;
6707 }
6708 
6709 extern int __gcclibcxx_demangle_callback (const char *,
6710                                           void (*)
6711                                             (const char *, size_t, void *),
6712                                           void *);
6713 
6714 /* Alternative, allocationless entry point in the C++ runtime library
6715    for performing demangling.  MANGLED_NAME is a NUL-terminated character
6716    string containing the name to be demangled.
6717 
6718    CALLBACK is a callback function, called with demangled string
6719    segments as demangling progresses; it is called at least once,
6720    but may be called more than once.  OPAQUE is a generalized pointer
6721    used as a callback argument.
6722 
6723    The return code is one of the following values, equivalent to
6724    the STATUS values of __cxa_demangle() (excluding -1, since this
6725    function performs no memory allocations):
6726       0: The demangling operation succeeded.
6727      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
6728      -3: One of the arguments is invalid.
6729 
6730    The demangling is performed using the C++ ABI mangling rules, with
6731    GNU extensions.  */
6732 
6733 int
__gcclibcxx_demangle_callback(const char * mangled_name,void (* callback)(const char *,size_t,void *),void * opaque)6734 __gcclibcxx_demangle_callback (const char *mangled_name,
6735                                void (*callback) (const char *, size_t, void *),
6736                                void *opaque)
6737 {
6738   int status;
6739 
6740   if (mangled_name == NULL || callback == NULL)
6741     return -3;
6742 
6743   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
6744                                 callback, opaque);
6745   if (status == 0)
6746     return -2;
6747 
6748   return 0;
6749 }
6750 
6751 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
6752 
6753 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
6754    mangled name, return a buffer allocated with malloc holding the
6755    demangled name.  Otherwise, return NULL.  */
6756 
6757 char *
cplus_demangle_v3(const char * mangled,int options)6758 cplus_demangle_v3 (const char *mangled, int options)
6759 {
6760   size_t alc;
6761 
6762   return d_demangle (mangled, options, &alc);
6763 }
6764 
6765 int
cplus_demangle_v3_callback(const char * mangled,int options,demangle_callbackref callback,void * opaque)6766 cplus_demangle_v3_callback (const char *mangled, int options,
6767                             demangle_callbackref callback, void *opaque)
6768 {
6769   return d_demangle_callback (mangled, options, callback, opaque);
6770 }
6771 
6772 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling
6773    conventions, but the output formatting is a little different.
6774    This instructs the C++ demangler not to emit pointer characters ("*"), to
6775    use Java's namespace separator symbol ("." instead of "::"), and to output
6776    JArray<TYPE> as TYPE[].  */
6777 
6778 char *
java_demangle_v3(const char * mangled)6779 java_demangle_v3 (const char *mangled)
6780 {
6781   size_t alc;
6782 
6783   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
6784 }
6785 
6786 int
java_demangle_v3_callback(const char * mangled,demangle_callbackref callback,void * opaque)6787 java_demangle_v3_callback (const char *mangled,
6788                            demangle_callbackref callback, void *opaque)
6789 {
6790   return d_demangle_callback (mangled,
6791                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
6792                               callback, opaque);
6793 }
6794 
6795 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
6796 
6797 #ifndef IN_GLIBCPP_V3
6798 
6799 /* Demangle a string in order to find out whether it is a constructor
6800    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
6801    *DTOR_KIND appropriately.  */
6802 
6803 static int
is_ctor_or_dtor(const char * mangled,enum gnu_v3_ctor_kinds * ctor_kind,enum gnu_v3_dtor_kinds * dtor_kind)6804 is_ctor_or_dtor (const char *mangled,
6805                  enum gnu_v3_ctor_kinds *ctor_kind,
6806                  enum gnu_v3_dtor_kinds *dtor_kind)
6807 {
6808   struct d_info di;
6809   struct demangle_component *dc;
6810   int ret;
6811 
6812   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
6813   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
6814 
6815   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
6816 
6817   {
6818 #ifdef CP_DYNAMIC_ARRAYS
6819     __extension__ struct demangle_component comps[di.num_comps];
6820     __extension__ struct demangle_component *subs[di.num_subs];
6821 
6822     di.comps = comps;
6823     di.subs = subs;
6824 #else
6825     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6826     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6827 #endif
6828 
6829     dc = cplus_demangle_mangled_name (&di, 1);
6830 
6831     /* Note that because we did not pass DMGL_PARAMS, we don't expect
6832        to demangle the entire string.  */
6833 
6834     ret = 0;
6835     while (dc != NULL)
6836       {
6837 	switch (dc->type)
6838 	  {
6839 	    /* These cannot appear on a constructor or destructor.  */
6840 	  case DEMANGLE_COMPONENT_RESTRICT_THIS:
6841 	  case DEMANGLE_COMPONENT_VOLATILE_THIS:
6842 	  case DEMANGLE_COMPONENT_CONST_THIS:
6843 	  case DEMANGLE_COMPONENT_REFERENCE_THIS:
6844 	  case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
6845 	  default:
6846 	    dc = NULL;
6847 	    break;
6848 	  case DEMANGLE_COMPONENT_TYPED_NAME:
6849 	  case DEMANGLE_COMPONENT_TEMPLATE:
6850 	    dc = d_left (dc);
6851 	    break;
6852 	  case DEMANGLE_COMPONENT_QUAL_NAME:
6853 	  case DEMANGLE_COMPONENT_LOCAL_NAME:
6854 	    dc = d_right (dc);
6855 	    break;
6856 	  case DEMANGLE_COMPONENT_CTOR:
6857 	    *ctor_kind = dc->u.s_ctor.kind;
6858 	    ret = 1;
6859 	    dc = NULL;
6860 	    break;
6861 	  case DEMANGLE_COMPONENT_DTOR:
6862 	    *dtor_kind = dc->u.s_dtor.kind;
6863 	    ret = 1;
6864 	    dc = NULL;
6865 	    break;
6866 	  }
6867       }
6868   }
6869 
6870   return ret;
6871 }
6872 
6873 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
6874    name.  A non-zero return indicates the type of constructor.  */
6875 
6876 enum gnu_v3_ctor_kinds
is_gnu_v3_mangled_ctor(const char * name)6877 is_gnu_v3_mangled_ctor (const char *name)
6878 {
6879   enum gnu_v3_ctor_kinds ctor_kind;
6880   enum gnu_v3_dtor_kinds dtor_kind;
6881 
6882   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6883     return (enum gnu_v3_ctor_kinds) 0;
6884   return ctor_kind;
6885 }
6886 
6887 
6888 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
6889    name.  A non-zero return indicates the type of destructor.  */
6890 
6891 enum gnu_v3_dtor_kinds
is_gnu_v3_mangled_dtor(const char * name)6892 is_gnu_v3_mangled_dtor (const char *name)
6893 {
6894   enum gnu_v3_ctor_kinds ctor_kind;
6895   enum gnu_v3_dtor_kinds dtor_kind;
6896 
6897   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6898     return (enum gnu_v3_dtor_kinds) 0;
6899   return dtor_kind;
6900 }
6901 
6902 #endif /* IN_GLIBCPP_V3 */
6903 
6904 #ifdef STANDALONE_DEMANGLER
6905 
6906 #include "getopt.h"
6907 #include "dyn-string.h"
6908 
6909 static void print_usage (FILE* fp, int exit_value);
6910 
6911 #define IS_ALPHA(CHAR)                                                  \
6912   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
6913    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
6914 
6915 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
6916 #define is_mangled_char(CHAR)                                           \
6917   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
6918    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
6919 
6920 /* The name of this program, as invoked.  */
6921 const char* program_name;
6922 
6923 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
6924 
6925 static void
print_usage(FILE * fp,int exit_value)6926 print_usage (FILE* fp, int exit_value)
6927 {
6928   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
6929   fprintf (fp, "Options:\n");
6930   fprintf (fp, "  -h,--help       Display this message.\n");
6931   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
6932   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
6933   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
6934 
6935   exit (exit_value);
6936 }
6937 
6938 /* Option specification for getopt_long.  */
6939 static const struct option long_options[] =
6940 {
6941   { "help",	 no_argument, NULL, 'h' },
6942   { "no-params", no_argument, NULL, 'p' },
6943   { "verbose",   no_argument, NULL, 'v' },
6944   { NULL,        no_argument, NULL, 0   },
6945 };
6946 
6947 /* Main entry for a demangling filter executable.  It will demangle
6948    its command line arguments, if any.  If none are provided, it will
6949    filter stdin to stdout, replacing any recognized mangled C++ names
6950    with their demangled equivalents.  */
6951 
6952 int
main(int argc,char * argv[])6953 main (int argc, char *argv[])
6954 {
6955   int i;
6956   int opt_char;
6957   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
6958 
6959   /* Use the program name of this program, as invoked.  */
6960   program_name = argv[0];
6961 
6962   /* Parse options.  */
6963   do
6964     {
6965       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
6966       switch (opt_char)
6967 	{
6968 	case '?':  /* Unrecognized option.  */
6969 	  print_usage (stderr, 1);
6970 	  break;
6971 
6972 	case 'h':
6973 	  print_usage (stdout, 0);
6974 	  break;
6975 
6976 	case 'p':
6977 	  options &= ~ DMGL_PARAMS;
6978 	  break;
6979 
6980 	case 'v':
6981 	  options |= DMGL_VERBOSE;
6982 	  break;
6983 	}
6984     }
6985   while (opt_char != -1);
6986 
6987   if (optind == argc)
6988     /* No command line arguments were provided.  Filter stdin.  */
6989     {
6990       dyn_string_t mangled = dyn_string_new (3);
6991       char *s;
6992 
6993       /* Read all of input.  */
6994       while (!feof (stdin))
6995 	{
6996 	  char c;
6997 
6998 	  /* Pile characters into mangled until we hit one that can't
6999 	     occur in a mangled name.  */
7000 	  c = getchar ();
7001 	  while (!feof (stdin) && is_mangled_char (c))
7002 	    {
7003 	      dyn_string_append_char (mangled, c);
7004 	      if (feof (stdin))
7005 		break;
7006 	      c = getchar ();
7007 	    }
7008 
7009 	  if (dyn_string_length (mangled) > 0)
7010 	    {
7011 #ifdef IN_GLIBCPP_V3
7012 	      s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
7013 #else
7014 	      s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
7015 #endif
7016 
7017 	      if (s != NULL)
7018 		{
7019 		  fputs (s, stdout);
7020 		  free (s);
7021 		}
7022 	      else
7023 		{
7024 		  /* It might not have been a mangled name.  Print the
7025 		     original text.  */
7026 		  fputs (dyn_string_buf (mangled), stdout);
7027 		}
7028 
7029 	      dyn_string_clear (mangled);
7030 	    }
7031 
7032 	  /* If we haven't hit EOF yet, we've read one character that
7033 	     can't occur in a mangled name, so print it out.  */
7034 	  if (!feof (stdin))
7035 	    putchar (c);
7036 	}
7037 
7038       dyn_string_delete (mangled);
7039     }
7040   else
7041     /* Demangle command line arguments.  */
7042     {
7043       /* Loop over command line arguments.  */
7044       for (i = optind; i < argc; ++i)
7045 	{
7046 	  char *s;
7047 #ifdef IN_GLIBCPP_V3
7048 	  int status;
7049 #endif
7050 
7051 	  /* Attempt to demangle.  */
7052 #ifdef IN_GLIBCPP_V3
7053 	  s = __cxa_demangle (argv[i], NULL, NULL, &status);
7054 #else
7055 	  s = cplus_demangle_v3 (argv[i], options);
7056 #endif
7057 
7058 	  /* If it worked, print the demangled name.  */
7059 	  if (s != NULL)
7060 	    {
7061 	      printf ("%s\n", s);
7062 	      free (s);
7063 	    }
7064 	  else
7065 	    {
7066 #ifdef IN_GLIBCPP_V3
7067 	      fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
7068 #else
7069 	      fprintf (stderr, "Failed: %s\n", argv[i]);
7070 #endif
7071 	    }
7072 	}
7073     }
7074 
7075   return 0;
7076 }
7077 
7078 #endif /* STANDALONE_DEMANGLER */
7079