OSDN Git Service

* cp-demangle.c (d_substitution): Correct overflow check to avoid
[pf3gnuchains/gcc-fork.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007 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        http://www.codesourcery.com/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
97 #if defined (_AIX) && !defined (__GNUC__)
98  #pragma alloca
99 #endif
100
101 #ifdef HAVE_CONFIG_H
102 #include "config.h"
103 #endif
104
105 #include <stdio.h>
106
107 #ifdef HAVE_STDLIB_H
108 #include <stdlib.h>
109 #endif
110 #ifdef HAVE_STRING_H
111 #include <string.h>
112 #endif
113
114 #ifdef HAVE_ALLOCA_H
115 # include <alloca.h>
116 #else
117 # ifndef alloca
118 #  ifdef __GNUC__
119 #   define alloca __builtin_alloca
120 #  else
121 extern char *alloca ();
122 #  endif /* __GNUC__ */
123 # endif /* alloca */
124 #endif /* HAVE_ALLOCA_H */
125
126 #include "ansidecl.h"
127 #include "libiberty.h"
128 #include "demangle.h"
129 #include "cp-demangle.h"
130
131 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
132    also rename them via #define to avoid compiler errors when the
133    static definition conflicts with the extern declaration in a header
134    file.  */
135 #ifdef IN_GLIBCPP_V3
136
137 #define CP_STATIC_IF_GLIBCPP_V3 static
138
139 #define cplus_demangle_fill_name d_fill_name
140 static int d_fill_name (struct demangle_component *, const char *, int);
141
142 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
143 static int
144 d_fill_extended_operator (struct demangle_component *, int,
145                           struct demangle_component *);
146
147 #define cplus_demangle_fill_ctor d_fill_ctor
148 static int
149 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
150              struct demangle_component *);
151
152 #define cplus_demangle_fill_dtor d_fill_dtor
153 static int
154 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
155              struct demangle_component *);
156
157 #define cplus_demangle_mangled_name d_mangled_name
158 static struct demangle_component *d_mangled_name (struct d_info *, int);
159
160 #define cplus_demangle_type d_type
161 static struct demangle_component *d_type (struct d_info *);
162
163 #define cplus_demangle_print d_print
164 static char *d_print (int, const struct demangle_component *, int, size_t *);
165
166 #define cplus_demangle_print_callback d_print_callback
167 static int d_print_callback (int, const struct demangle_component *,
168                              demangle_callbackref, void *);
169
170 #define cplus_demangle_init_info d_init_info
171 static void d_init_info (const char *, int, size_t, struct d_info *);
172
173 #else /* ! defined(IN_GLIBCPP_V3) */
174 #define CP_STATIC_IF_GLIBCPP_V3
175 #endif /* ! defined(IN_GLIBCPP_V3) */
176
177 /* See if the compiler supports dynamic arrays.  */
178
179 #ifdef __GNUC__
180 #define CP_DYNAMIC_ARRAYS
181 #else
182 #ifdef __STDC__
183 #ifdef __STDC_VERSION__
184 #if __STDC_VERSION__ >= 199901L
185 #define CP_DYNAMIC_ARRAYS
186 #endif /* __STDC__VERSION >= 199901L */
187 #endif /* defined (__STDC_VERSION__) */
188 #endif /* defined (__STDC__) */
189 #endif /* ! defined (__GNUC__) */
190
191 /* We avoid pulling in the ctype tables, to prevent pulling in
192    additional unresolved symbols when this code is used in a library.
193    FIXME: Is this really a valid reason?  This comes from the original
194    V3 demangler code.
195
196    As of this writing this file has the following undefined references
197    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
198    strcat, strlen.  */
199
200 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
201 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
202 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
203
204 /* The prefix prepended by GCC to an identifier represnting the
205    anonymous namespace.  */
206 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
207 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
208   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
209
210 /* Information we keep for the standard substitutions.  */
211
212 struct d_standard_sub_info
213 {
214   /* The code for this substitution.  */
215   char code;
216   /* The simple string it expands to.  */
217   const char *simple_expansion;
218   /* The length of the simple expansion.  */
219   int simple_len;
220   /* The results of a full, verbose, expansion.  This is used when
221      qualifying a constructor/destructor, or when in verbose mode.  */
222   const char *full_expansion;
223   /* The length of the full expansion.  */
224   int full_len;
225   /* What to set the last_name field of d_info to; NULL if we should
226      not set it.  This is only relevant when qualifying a
227      constructor/destructor.  */
228   const char *set_last_name;
229   /* The length of set_last_name.  */
230   int set_last_name_len;
231 };
232
233 /* Accessors for subtrees of struct demangle_component.  */
234
235 #define d_left(dc) ((dc)->u.s_binary.left)
236 #define d_right(dc) ((dc)->u.s_binary.right)
237
238 /* A list of templates.  This is used while printing.  */
239
240 struct d_print_template
241 {
242   /* Next template on the list.  */
243   struct d_print_template *next;
244   /* This template.  */
245   const struct demangle_component *template_decl;
246 };
247
248 /* A list of type modifiers.  This is used while printing.  */
249
250 struct d_print_mod
251 {
252   /* Next modifier on the list.  These are in the reverse of the order
253      in which they appeared in the mangled string.  */
254   struct d_print_mod *next;
255   /* The modifier.  */
256   const struct demangle_component *mod;
257   /* Whether this modifier was printed.  */
258   int printed;
259   /* The list of templates which applies to this modifier.  */
260   struct d_print_template *templates;
261 };
262
263 /* We use these structures to hold information during printing.  */
264
265 struct d_growable_string
266 {
267   /* Buffer holding the result.  */
268   char *buf;
269   /* Current length of data in buffer.  */
270   size_t len;
271   /* Allocated size of buffer.  */
272   size_t alc;
273   /* Set to 1 if we had a memory allocation failure.  */
274   int allocation_failure;
275 };
276
277 enum { D_PRINT_BUFFER_LENGTH = 256 };
278 struct d_print_info
279 {
280   /* The options passed to the demangler.  */
281   int options;
282   /* Fixed-length allocated buffer for demangled data, flushed to the
283      callback with a NUL termination once full.  */
284   char buf[D_PRINT_BUFFER_LENGTH];
285   /* Current length of data in buffer.  */
286   size_t len;
287   /* The last character printed, saved individually so that it survives
288      any buffer flush.  */
289   char last_char;
290   /* Callback function to handle demangled buffer flush.  */
291   demangle_callbackref callback;
292   /* Opaque callback argument.  */
293   void *opaque;
294   /* The current list of templates, if any.  */
295   struct d_print_template *templates;
296   /* The current list of modifiers (e.g., pointer, reference, etc.),
297      if any.  */
298   struct d_print_mod *modifiers;
299   /* Set to 1 if we saw a demangling error.  */
300   int demangle_failure;
301 };
302
303 #ifdef CP_DEMANGLE_DEBUG
304 static void d_dump (struct demangle_component *, int);
305 #endif
306
307 static struct demangle_component *
308 d_make_empty (struct d_info *);
309
310 static struct demangle_component *
311 d_make_comp (struct d_info *, enum demangle_component_type,
312              struct demangle_component *,
313              struct demangle_component *);
314
315 static struct demangle_component *
316 d_make_name (struct d_info *, const char *, int);
317
318 static struct demangle_component *
319 d_make_builtin_type (struct d_info *,
320                      const struct demangle_builtin_type_info *);
321
322 static struct demangle_component *
323 d_make_operator (struct d_info *,
324                  const struct demangle_operator_info *);
325
326 static struct demangle_component *
327 d_make_extended_operator (struct d_info *, int,
328                           struct demangle_component *);
329
330 static struct demangle_component *
331 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
332              struct demangle_component *);
333
334 static struct demangle_component *
335 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
336              struct demangle_component *);
337
338 static struct demangle_component *
339 d_make_template_param (struct d_info *, long);
340
341 static struct demangle_component *
342 d_make_sub (struct d_info *, const char *, int);
343
344 static int
345 has_return_type (struct demangle_component *);
346
347 static int
348 is_ctor_dtor_or_conversion (struct demangle_component *);
349
350 static struct demangle_component *d_encoding (struct d_info *, int);
351
352 static struct demangle_component *d_name (struct d_info *);
353
354 static struct demangle_component *d_nested_name (struct d_info *);
355
356 static struct demangle_component *d_prefix (struct d_info *);
357
358 static struct demangle_component *d_unqualified_name (struct d_info *);
359
360 static struct demangle_component *d_source_name (struct d_info *);
361
362 static long d_number (struct d_info *);
363
364 static struct demangle_component *d_identifier (struct d_info *, int);
365
366 static struct demangle_component *d_operator_name (struct d_info *);
367
368 static struct demangle_component *d_special_name (struct d_info *);
369
370 static int d_call_offset (struct d_info *, int);
371
372 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
373
374 static struct demangle_component **
375 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
376
377 static struct demangle_component *
378 d_function_type (struct d_info *);
379
380 static struct demangle_component *
381 d_bare_function_type (struct d_info *, int);
382
383 static struct demangle_component *
384 d_class_enum_type (struct d_info *);
385
386 static struct demangle_component *d_array_type (struct d_info *);
387
388 static struct demangle_component *
389 d_pointer_to_member_type (struct d_info *);
390
391 static struct demangle_component *
392 d_template_param (struct d_info *);
393
394 static struct demangle_component *d_template_args (struct d_info *);
395
396 static struct demangle_component *
397 d_template_arg (struct d_info *);
398
399 static struct demangle_component *d_expression (struct d_info *);
400
401 static struct demangle_component *d_expr_primary (struct d_info *);
402
403 static struct demangle_component *d_local_name (struct d_info *);
404
405 static int d_discriminator (struct d_info *);
406
407 static int
408 d_add_substitution (struct d_info *, struct demangle_component *);
409
410 static struct demangle_component *d_substitution (struct d_info *, int);
411
412 static void d_growable_string_init (struct d_growable_string *, size_t);
413
414 static inline void
415 d_growable_string_resize (struct d_growable_string *, size_t);
416
417 static inline void
418 d_growable_string_append_buffer (struct d_growable_string *,
419                                  const char *, size_t);
420 static void
421 d_growable_string_callback_adapter (const char *, size_t, void *);
422
423 static void
424 d_print_init (struct d_print_info *, int, demangle_callbackref, void *);
425
426 static inline void d_print_error (struct d_print_info *);
427
428 static inline int d_print_saw_error (struct d_print_info *);
429
430 static inline void d_print_flush (struct d_print_info *);
431
432 static inline void d_append_char (struct d_print_info *, char);
433
434 static inline void d_append_buffer (struct d_print_info *,
435                                     const char *, size_t);
436
437 static inline void d_append_string (struct d_print_info *, const char *);
438
439 static inline char d_last_char (struct d_print_info *);
440
441 static void
442 d_print_comp (struct d_print_info *, const struct demangle_component *);
443
444 static void
445 d_print_java_identifier (struct d_print_info *, const char *, int);
446
447 static void
448 d_print_mod_list (struct d_print_info *, struct d_print_mod *, int);
449
450 static void
451 d_print_mod (struct d_print_info *, const struct demangle_component *);
452
453 static void
454 d_print_function_type (struct d_print_info *,
455                        const struct demangle_component *,
456                        struct d_print_mod *);
457
458 static void
459 d_print_array_type (struct d_print_info *,
460                     const struct demangle_component *,
461                     struct d_print_mod *);
462
463 static void
464 d_print_expr_op (struct d_print_info *, const struct demangle_component *);
465
466 static void
467 d_print_cast (struct d_print_info *, const struct demangle_component *);
468
469 static int d_demangle_callback (const char *, int,
470                                 demangle_callbackref, void *);
471 static char *d_demangle (const char *, int, size_t *);
472
473 #ifdef CP_DEMANGLE_DEBUG
474
475 static void
476 d_dump (struct demangle_component *dc, int indent)
477 {
478   int i;
479
480   if (dc == NULL)
481     {
482       if (indent == 0)
483         printf ("failed demangling\n");
484       return;
485     }
486
487   for (i = 0; i < indent; ++i)
488     putchar (' ');
489
490   switch (dc->type)
491     {
492     case DEMANGLE_COMPONENT_NAME:
493       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
494       return;
495     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
496       printf ("template parameter %ld\n", dc->u.s_number.number);
497       return;
498     case DEMANGLE_COMPONENT_CTOR:
499       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
500       d_dump (dc->u.s_ctor.name, indent + 2);
501       return;
502     case DEMANGLE_COMPONENT_DTOR:
503       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
504       d_dump (dc->u.s_dtor.name, indent + 2);
505       return;
506     case DEMANGLE_COMPONENT_SUB_STD:
507       printf ("standard substitution %s\n", dc->u.s_string.string);
508       return;
509     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
510       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
511       return;
512     case DEMANGLE_COMPONENT_OPERATOR:
513       printf ("operator %s\n", dc->u.s_operator.op->name);
514       return;
515     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
516       printf ("extended operator with %d args\n",
517               dc->u.s_extended_operator.args);
518       d_dump (dc->u.s_extended_operator.name, indent + 2);
519       return;
520
521     case DEMANGLE_COMPONENT_QUAL_NAME:
522       printf ("qualified name\n");
523       break;
524     case DEMANGLE_COMPONENT_LOCAL_NAME:
525       printf ("local name\n");
526       break;
527     case DEMANGLE_COMPONENT_TYPED_NAME:
528       printf ("typed name\n");
529       break;
530     case DEMANGLE_COMPONENT_TEMPLATE:
531       printf ("template\n");
532       break;
533     case DEMANGLE_COMPONENT_VTABLE:
534       printf ("vtable\n");
535       break;
536     case DEMANGLE_COMPONENT_VTT:
537       printf ("VTT\n");
538       break;
539     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
540       printf ("construction vtable\n");
541       break;
542     case DEMANGLE_COMPONENT_TYPEINFO:
543       printf ("typeinfo\n");
544       break;
545     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
546       printf ("typeinfo name\n");
547       break;
548     case DEMANGLE_COMPONENT_TYPEINFO_FN:
549       printf ("typeinfo function\n");
550       break;
551     case DEMANGLE_COMPONENT_THUNK:
552       printf ("thunk\n");
553       break;
554     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
555       printf ("virtual thunk\n");
556       break;
557     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
558       printf ("covariant thunk\n");
559       break;
560     case DEMANGLE_COMPONENT_JAVA_CLASS:
561       printf ("java class\n");
562       break;
563     case DEMANGLE_COMPONENT_GUARD:
564       printf ("guard\n");
565       break;
566     case DEMANGLE_COMPONENT_REFTEMP:
567       printf ("reference temporary\n");
568       break;
569     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
570       printf ("hidden alias\n");
571       break;
572     case DEMANGLE_COMPONENT_RESTRICT:
573       printf ("restrict\n");
574       break;
575     case DEMANGLE_COMPONENT_VOLATILE:
576       printf ("volatile\n");
577       break;
578     case DEMANGLE_COMPONENT_CONST:
579       printf ("const\n");
580       break;
581     case DEMANGLE_COMPONENT_RESTRICT_THIS:
582       printf ("restrict this\n");
583       break;
584     case DEMANGLE_COMPONENT_VOLATILE_THIS:
585       printf ("volatile this\n");
586       break;
587     case DEMANGLE_COMPONENT_CONST_THIS:
588       printf ("const this\n");
589       break;
590     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
591       printf ("vendor type qualifier\n");
592       break;
593     case DEMANGLE_COMPONENT_POINTER:
594       printf ("pointer\n");
595       break;
596     case DEMANGLE_COMPONENT_REFERENCE:
597       printf ("reference\n");
598       break;
599     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
600       printf ("rvalue reference\n");
601       break;
602     case DEMANGLE_COMPONENT_COMPLEX:
603       printf ("complex\n");
604       break;
605     case DEMANGLE_COMPONENT_IMAGINARY:
606       printf ("imaginary\n");
607       break;
608     case DEMANGLE_COMPONENT_VENDOR_TYPE:
609       printf ("vendor type\n");
610       break;
611     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
612       printf ("function type\n");
613       break;
614     case DEMANGLE_COMPONENT_ARRAY_TYPE:
615       printf ("array type\n");
616       break;
617     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
618       printf ("pointer to member type\n");
619       break;
620     case DEMANGLE_COMPONENT_ARGLIST:
621       printf ("argument list\n");
622       break;
623     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
624       printf ("template argument list\n");
625       break;
626     case DEMANGLE_COMPONENT_CAST:
627       printf ("cast\n");
628       break;
629     case DEMANGLE_COMPONENT_UNARY:
630       printf ("unary operator\n");
631       break;
632     case DEMANGLE_COMPONENT_BINARY:
633       printf ("binary operator\n");
634       break;
635     case DEMANGLE_COMPONENT_BINARY_ARGS:
636       printf ("binary operator arguments\n");
637       break;
638     case DEMANGLE_COMPONENT_TRINARY:
639       printf ("trinary operator\n");
640       break;
641     case DEMANGLE_COMPONENT_TRINARY_ARG1:
642       printf ("trinary operator arguments 1\n");
643       break;
644     case DEMANGLE_COMPONENT_TRINARY_ARG2:
645       printf ("trinary operator arguments 1\n");
646       break;
647     case DEMANGLE_COMPONENT_LITERAL:
648       printf ("literal\n");
649       break;
650     case DEMANGLE_COMPONENT_LITERAL_NEG:
651       printf ("negative literal\n");
652       break;
653     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
654       printf ("java resource\n");
655       break;
656     case DEMANGLE_COMPONENT_COMPOUND_NAME:
657       printf ("compound name\n");
658       break;
659     case DEMANGLE_COMPONENT_CHARACTER:
660       printf ("character '%c'\n",  dc->u.s_character.character);
661       return;
662     }
663
664   d_dump (d_left (dc), indent + 2);
665   d_dump (d_right (dc), indent + 2);
666 }
667
668 #endif /* CP_DEMANGLE_DEBUG */
669
670 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
671
672 CP_STATIC_IF_GLIBCPP_V3
673 int
674 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
675 {
676   if (p == NULL || s == NULL || len == 0)
677     return 0;
678   p->type = DEMANGLE_COMPONENT_NAME;
679   p->u.s_name.s = s;
680   p->u.s_name.len = len;
681   return 1;
682 }
683
684 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
685
686 CP_STATIC_IF_GLIBCPP_V3
687 int
688 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
689                                        struct demangle_component *name)
690 {
691   if (p == NULL || args < 0 || name == NULL)
692     return 0;
693   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
694   p->u.s_extended_operator.args = args;
695   p->u.s_extended_operator.name = name;
696   return 1;
697 }
698
699 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
700
701 CP_STATIC_IF_GLIBCPP_V3
702 int
703 cplus_demangle_fill_ctor (struct demangle_component *p,
704                           enum gnu_v3_ctor_kinds kind,
705                           struct demangle_component *name)
706 {
707   if (p == NULL
708       || name == NULL
709       || (kind < gnu_v3_complete_object_ctor
710           && kind > gnu_v3_complete_object_allocating_ctor))
711     return 0;
712   p->type = DEMANGLE_COMPONENT_CTOR;
713   p->u.s_ctor.kind = kind;
714   p->u.s_ctor.name = name;
715   return 1;
716 }
717
718 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
719
720 CP_STATIC_IF_GLIBCPP_V3
721 int
722 cplus_demangle_fill_dtor (struct demangle_component *p,
723                           enum gnu_v3_dtor_kinds kind,
724                           struct demangle_component *name)
725 {
726   if (p == NULL
727       || name == NULL
728       || (kind < gnu_v3_deleting_dtor
729           && kind > gnu_v3_base_object_dtor))
730     return 0;
731   p->type = DEMANGLE_COMPONENT_DTOR;
732   p->u.s_dtor.kind = kind;
733   p->u.s_dtor.name = name;
734   return 1;
735 }
736
737 /* Add a new component.  */
738
739 static struct demangle_component *
740 d_make_empty (struct d_info *di)
741 {
742   struct demangle_component *p;
743
744   if (di->next_comp >= di->num_comps)
745     return NULL;
746   p = &di->comps[di->next_comp];
747   ++di->next_comp;
748   return p;
749 }
750
751 /* Add a new generic component.  */
752
753 static struct demangle_component *
754 d_make_comp (struct d_info *di, enum demangle_component_type type,
755              struct demangle_component *left,
756              struct demangle_component *right)
757 {
758   struct demangle_component *p;
759
760   /* We check for errors here.  A typical error would be a NULL return
761      from a subroutine.  We catch those here, and return NULL
762      upward.  */
763   switch (type)
764     {
765       /* These types require two parameters.  */
766     case DEMANGLE_COMPONENT_QUAL_NAME:
767     case DEMANGLE_COMPONENT_LOCAL_NAME:
768     case DEMANGLE_COMPONENT_TYPED_NAME:
769     case DEMANGLE_COMPONENT_TEMPLATE:
770     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
771     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
772     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
773     case DEMANGLE_COMPONENT_UNARY:
774     case DEMANGLE_COMPONENT_BINARY:
775     case DEMANGLE_COMPONENT_BINARY_ARGS:
776     case DEMANGLE_COMPONENT_TRINARY:
777     case DEMANGLE_COMPONENT_TRINARY_ARG1:
778     case DEMANGLE_COMPONENT_TRINARY_ARG2:
779     case DEMANGLE_COMPONENT_LITERAL:
780     case DEMANGLE_COMPONENT_LITERAL_NEG:
781     case DEMANGLE_COMPONENT_COMPOUND_NAME:
782       if (left == NULL || right == NULL)
783         return NULL;
784       break;
785
786       /* These types only require one parameter.  */
787     case DEMANGLE_COMPONENT_VTABLE:
788     case DEMANGLE_COMPONENT_VTT:
789     case DEMANGLE_COMPONENT_TYPEINFO:
790     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
791     case DEMANGLE_COMPONENT_TYPEINFO_FN:
792     case DEMANGLE_COMPONENT_THUNK:
793     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
794     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
795     case DEMANGLE_COMPONENT_JAVA_CLASS:
796     case DEMANGLE_COMPONENT_GUARD:
797     case DEMANGLE_COMPONENT_REFTEMP:
798     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
799     case DEMANGLE_COMPONENT_POINTER:
800     case DEMANGLE_COMPONENT_REFERENCE:
801     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
802     case DEMANGLE_COMPONENT_COMPLEX:
803     case DEMANGLE_COMPONENT_IMAGINARY:
804     case DEMANGLE_COMPONENT_VENDOR_TYPE:
805     case DEMANGLE_COMPONENT_ARGLIST:
806     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
807     case DEMANGLE_COMPONENT_CAST:
808     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
809       if (left == NULL)
810         return NULL;
811       break;
812
813       /* This needs a right parameter, but the left parameter can be
814          empty.  */
815     case DEMANGLE_COMPONENT_ARRAY_TYPE:
816       if (right == NULL)
817         return NULL;
818       break;
819
820       /* These are allowed to have no parameters--in some cases they
821          will be filled in later.  */
822     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
823     case DEMANGLE_COMPONENT_RESTRICT:
824     case DEMANGLE_COMPONENT_VOLATILE:
825     case DEMANGLE_COMPONENT_CONST:
826     case DEMANGLE_COMPONENT_RESTRICT_THIS:
827     case DEMANGLE_COMPONENT_VOLATILE_THIS:
828     case DEMANGLE_COMPONENT_CONST_THIS:
829       break;
830
831       /* Other types should not be seen here.  */
832     default:
833       return NULL;
834     }
835
836   p = d_make_empty (di);
837   if (p != NULL)
838     {
839       p->type = type;
840       p->u.s_binary.left = left;
841       p->u.s_binary.right = right;
842     }
843   return p;
844 }
845
846 /* Add a new name component.  */
847
848 static struct demangle_component *
849 d_make_name (struct d_info *di, const char *s, int len)
850 {
851   struct demangle_component *p;
852
853   p = d_make_empty (di);
854   if (! cplus_demangle_fill_name (p, s, len))
855     return NULL;
856   return p;
857 }
858
859 /* Add a new builtin type component.  */
860
861 static struct demangle_component *
862 d_make_builtin_type (struct d_info *di,
863                      const struct demangle_builtin_type_info *type)
864 {
865   struct demangle_component *p;
866
867   if (type == NULL)
868     return NULL;
869   p = d_make_empty (di);
870   if (p != NULL)
871     {
872       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
873       p->u.s_builtin.type = type;
874     }
875   return p;
876 }
877
878 /* Add a new operator component.  */
879
880 static struct demangle_component *
881 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
882 {
883   struct demangle_component *p;
884
885   p = d_make_empty (di);
886   if (p != NULL)
887     {
888       p->type = DEMANGLE_COMPONENT_OPERATOR;
889       p->u.s_operator.op = op;
890     }
891   return p;
892 }
893
894 /* Add a new extended operator component.  */
895
896 static struct demangle_component *
897 d_make_extended_operator (struct d_info *di, int args,
898                           struct demangle_component *name)
899 {
900   struct demangle_component *p;
901
902   p = d_make_empty (di);
903   if (! cplus_demangle_fill_extended_operator (p, args, name))
904     return NULL;
905   return p;
906 }
907
908 /* Add a new constructor component.  */
909
910 static struct demangle_component *
911 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
912              struct demangle_component *name)
913 {
914   struct demangle_component *p;
915
916   p = d_make_empty (di);
917   if (! cplus_demangle_fill_ctor (p, kind, name))
918     return NULL;
919   return p;
920 }
921
922 /* Add a new destructor component.  */
923
924 static struct demangle_component *
925 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
926              struct demangle_component *name)
927 {
928   struct demangle_component *p;
929
930   p = d_make_empty (di);
931   if (! cplus_demangle_fill_dtor (p, kind, name))
932     return NULL;
933   return p;
934 }
935
936 /* Add a new template parameter.  */
937
938 static struct demangle_component *
939 d_make_template_param (struct d_info *di, long i)
940 {
941   struct demangle_component *p;
942
943   p = d_make_empty (di);
944   if (p != NULL)
945     {
946       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
947       p->u.s_number.number = i;
948     }
949   return p;
950 }
951
952 /* Add a new standard substitution component.  */
953
954 static struct demangle_component *
955 d_make_sub (struct d_info *di, const char *name, int len)
956 {
957   struct demangle_component *p;
958
959   p = d_make_empty (di);
960   if (p != NULL)
961     {
962       p->type = DEMANGLE_COMPONENT_SUB_STD;
963       p->u.s_string.string = name;
964       p->u.s_string.len = len;
965     }
966   return p;
967 }
968
969 /* <mangled-name> ::= _Z <encoding>
970
971    TOP_LEVEL is non-zero when called at the top level.  */
972
973 CP_STATIC_IF_GLIBCPP_V3
974 struct demangle_component *
975 cplus_demangle_mangled_name (struct d_info *di, int top_level)
976 {
977   if (! d_check_char (di, '_'))
978     return NULL;
979   if (! d_check_char (di, 'Z'))
980     return NULL;
981   return d_encoding (di, top_level);
982 }
983
984 /* Return whether a function should have a return type.  The argument
985    is the function name, which may be qualified in various ways.  The
986    rules are that template functions have return types with some
987    exceptions, function types which are not part of a function name
988    mangling have return types with some exceptions, and non-template
989    function names do not have return types.  The exceptions are that
990    constructors, destructors, and conversion operators do not have
991    return types.  */
992
993 static int
994 has_return_type (struct demangle_component *dc)
995 {
996   if (dc == NULL)
997     return 0;
998   switch (dc->type)
999     {
1000     default:
1001       return 0;
1002     case DEMANGLE_COMPONENT_TEMPLATE:
1003       return ! is_ctor_dtor_or_conversion (d_left (dc));
1004     case DEMANGLE_COMPONENT_RESTRICT_THIS:
1005     case DEMANGLE_COMPONENT_VOLATILE_THIS:
1006     case DEMANGLE_COMPONENT_CONST_THIS:
1007       return has_return_type (d_left (dc));
1008     }
1009 }
1010
1011 /* Return whether a name is a constructor, a destructor, or a
1012    conversion operator.  */
1013
1014 static int
1015 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1016 {
1017   if (dc == NULL)
1018     return 0;
1019   switch (dc->type)
1020     {
1021     default:
1022       return 0;
1023     case DEMANGLE_COMPONENT_QUAL_NAME:
1024     case DEMANGLE_COMPONENT_LOCAL_NAME:
1025       return is_ctor_dtor_or_conversion (d_right (dc));
1026     case DEMANGLE_COMPONENT_CTOR:
1027     case DEMANGLE_COMPONENT_DTOR:
1028     case DEMANGLE_COMPONENT_CAST:
1029       return 1;
1030     }
1031 }
1032
1033 /* <encoding> ::= <(function) name> <bare-function-type>
1034               ::= <(data) name>
1035               ::= <special-name>
1036
1037    TOP_LEVEL is non-zero when called at the top level, in which case
1038    if DMGL_PARAMS is not set we do not demangle the function
1039    parameters.  We only set this at the top level, because otherwise
1040    we would not correctly demangle names in local scopes.  */
1041
1042 static struct demangle_component *
1043 d_encoding (struct d_info *di, int top_level)
1044 {
1045   char peek = d_peek_char (di);
1046
1047   if (peek == 'G' || peek == 'T')
1048     return d_special_name (di);
1049   else
1050     {
1051       struct demangle_component *dc;
1052
1053       dc = d_name (di);
1054
1055       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1056         {
1057           /* Strip off any initial CV-qualifiers, as they really apply
1058              to the `this' parameter, and they were not output by the
1059              v2 demangler without DMGL_PARAMS.  */
1060           while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1061                  || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1062                  || dc->type == DEMANGLE_COMPONENT_CONST_THIS)
1063             dc = d_left (dc);
1064
1065           /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1066              there may be CV-qualifiers on its right argument which
1067              really apply here; this happens when parsing a class
1068              which is local to a function.  */
1069           if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1070             {
1071               struct demangle_component *dcr;
1072
1073               dcr = d_right (dc);
1074               while (dcr->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1075                      || dcr->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1076                      || dcr->type == DEMANGLE_COMPONENT_CONST_THIS)
1077                 dcr = d_left (dcr);
1078               dc->u.s_binary.right = dcr;
1079             }
1080
1081           return dc;
1082         }
1083
1084       peek = d_peek_char (di);
1085       if (dc == NULL || peek == '\0' || peek == 'E')
1086         return dc;
1087       return d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME, dc,
1088                           d_bare_function_type (di, has_return_type (dc)));
1089     }
1090 }
1091
1092 /* <name> ::= <nested-name>
1093           ::= <unscoped-name>
1094           ::= <unscoped-template-name> <template-args>
1095           ::= <local-name>
1096
1097    <unscoped-name> ::= <unqualified-name>
1098                    ::= St <unqualified-name>
1099
1100    <unscoped-template-name> ::= <unscoped-name>
1101                             ::= <substitution>
1102 */
1103
1104 static struct demangle_component *
1105 d_name (struct d_info *di)
1106 {
1107   char peek = d_peek_char (di);
1108   struct demangle_component *dc;
1109
1110   switch (peek)
1111     {
1112     case 'N':
1113       return d_nested_name (di);
1114
1115     case 'Z':
1116       return d_local_name (di);
1117
1118     case 'L':
1119       return d_unqualified_name (di);
1120         
1121     case 'S':
1122       {
1123         int subst;
1124
1125         if (d_peek_next_char (di) != 't')
1126           {
1127             dc = d_substitution (di, 0);
1128             subst = 1;
1129           }
1130         else
1131           {
1132             d_advance (di, 2);
1133             dc = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME,
1134                               d_make_name (di, "std", 3),
1135                               d_unqualified_name (di));
1136             di->expansion += 3;
1137             subst = 0;
1138           }
1139
1140         if (d_peek_char (di) != 'I')
1141           {
1142             /* The grammar does not permit this case to occur if we
1143                called d_substitution() above (i.e., subst == 1).  We
1144                don't bother to check.  */
1145           }
1146         else
1147           {
1148             /* This is <template-args>, which means that we just saw
1149                <unscoped-template-name>, which is a substitution
1150                candidate if we didn't just get it from a
1151                substitution.  */
1152             if (! subst)
1153               {
1154                 if (! d_add_substitution (di, dc))
1155                   return NULL;
1156               }
1157             dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1158                               d_template_args (di));
1159           }
1160
1161         return dc;
1162       }
1163
1164     default:
1165       dc = d_unqualified_name (di);
1166       if (d_peek_char (di) == 'I')
1167         {
1168           /* This is <template-args>, which means that we just saw
1169              <unscoped-template-name>, which is a substitution
1170              candidate.  */
1171           if (! d_add_substitution (di, dc))
1172             return NULL;
1173           dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1174                             d_template_args (di));
1175         }
1176       return dc;
1177     }
1178 }
1179
1180 /* <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
1181                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1182 */
1183
1184 static struct demangle_component *
1185 d_nested_name (struct d_info *di)
1186 {
1187   struct demangle_component *ret;
1188   struct demangle_component **pret;
1189
1190   if (! d_check_char (di, 'N'))
1191     return NULL;
1192
1193   pret = d_cv_qualifiers (di, &ret, 1);
1194   if (pret == NULL)
1195     return NULL;
1196
1197   *pret = d_prefix (di);
1198   if (*pret == NULL)
1199     return NULL;
1200
1201   if (! d_check_char (di, 'E'))
1202     return NULL;
1203
1204   return ret;
1205 }
1206
1207 /* <prefix> ::= <prefix> <unqualified-name>
1208             ::= <template-prefix> <template-args>
1209             ::= <template-param>
1210             ::=
1211             ::= <substitution>
1212
1213    <template-prefix> ::= <prefix> <(template) unqualified-name>
1214                      ::= <template-param>
1215                      ::= <substitution>
1216 */
1217
1218 static struct demangle_component *
1219 d_prefix (struct d_info *di)
1220 {
1221   struct demangle_component *ret = NULL;
1222
1223   while (1)
1224     {
1225       char peek;
1226       enum demangle_component_type comb_type;
1227       struct demangle_component *dc;
1228
1229       peek = d_peek_char (di);
1230       if (peek == '\0')
1231         return NULL;
1232
1233       /* The older code accepts a <local-name> here, but I don't see
1234          that in the grammar.  The older code does not accept a
1235          <template-param> here.  */
1236
1237       comb_type = DEMANGLE_COMPONENT_QUAL_NAME;
1238       if (IS_DIGIT (peek)
1239           || IS_LOWER (peek)
1240           || peek == 'C'
1241           || peek == 'D'
1242           || peek == 'L')
1243         dc = d_unqualified_name (di);
1244       else if (peek == 'S')
1245         dc = d_substitution (di, 1);
1246       else if (peek == 'I')
1247         {
1248           if (ret == NULL)
1249             return NULL;
1250           comb_type = DEMANGLE_COMPONENT_TEMPLATE;
1251           dc = d_template_args (di);
1252         }
1253       else if (peek == 'T')
1254         dc = d_template_param (di);
1255       else if (peek == 'E')
1256         return ret;
1257       else
1258         return NULL;
1259
1260       if (ret == NULL)
1261         ret = dc;
1262       else
1263         ret = d_make_comp (di, comb_type, ret, dc);
1264
1265       if (peek != 'S' && d_peek_char (di) != 'E')
1266         {
1267           if (! d_add_substitution (di, ret))
1268             return NULL;
1269         }
1270     }
1271 }
1272
1273 /* <unqualified-name> ::= <operator-name>
1274                       ::= <ctor-dtor-name>
1275                       ::= <source-name>
1276                       ::= <local-source-name> 
1277
1278     <local-source-name> ::= L <source-name> <discriminator>
1279 */
1280
1281 static struct demangle_component *
1282 d_unqualified_name (struct d_info *di)
1283 {
1284   char peek;
1285
1286   peek = d_peek_char (di);
1287   if (IS_DIGIT (peek))
1288     return d_source_name (di);
1289   else if (IS_LOWER (peek))
1290     {
1291       struct demangle_component *ret;
1292
1293       ret = d_operator_name (di);
1294       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1295         di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1296       return ret;
1297     }
1298   else if (peek == 'C' || peek == 'D')
1299     return d_ctor_dtor_name (di);
1300   else if (peek == 'L')
1301     {
1302       struct demangle_component * ret;
1303
1304       d_advance (di, 1);
1305
1306       ret = d_source_name (di);
1307       if (ret == NULL)
1308         return NULL;
1309       if (! d_discriminator (di))
1310         return NULL;
1311       return ret;
1312     }
1313   else
1314     return NULL;
1315 }
1316
1317 /* <source-name> ::= <(positive length) number> <identifier>  */
1318
1319 static struct demangle_component *
1320 d_source_name (struct d_info *di)
1321 {
1322   long len;
1323   struct demangle_component *ret;
1324
1325   len = d_number (di);
1326   if (len <= 0)
1327     return NULL;
1328   ret = d_identifier (di, len);
1329   di->last_name = ret;
1330   return ret;
1331 }
1332
1333 /* number ::= [n] <(non-negative decimal integer)>  */
1334
1335 static long
1336 d_number (struct d_info *di)
1337 {
1338   int negative;
1339   char peek;
1340   long ret;
1341
1342   negative = 0;
1343   peek = d_peek_char (di);
1344   if (peek == 'n')
1345     {
1346       negative = 1;
1347       d_advance (di, 1);
1348       peek = d_peek_char (di);
1349     }
1350
1351   ret = 0;
1352   while (1)
1353     {
1354       if (! IS_DIGIT (peek))
1355         {
1356           if (negative)
1357             ret = - ret;
1358           return ret;
1359         }
1360       ret = ret * 10 + peek - '0';
1361       d_advance (di, 1);
1362       peek = d_peek_char (di);
1363     }
1364 }
1365
1366 /* identifier ::= <(unqualified source code identifier)>  */
1367
1368 static struct demangle_component *
1369 d_identifier (struct d_info *di, int len)
1370 {
1371   const char *name;
1372
1373   name = d_str (di);
1374
1375   if (di->send - name < len)
1376     return NULL;
1377
1378   d_advance (di, len);
1379
1380   /* A Java mangled name may have a trailing '$' if it is a C++
1381      keyword.  This '$' is not included in the length count.  We just
1382      ignore the '$'.  */
1383   if ((di->options & DMGL_JAVA) != 0
1384       && d_peek_char (di) == '$')
1385     d_advance (di, 1);
1386
1387   /* Look for something which looks like a gcc encoding of an
1388      anonymous namespace, and replace it with a more user friendly
1389      name.  */
1390   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1391       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1392                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1393     {
1394       const char *s;
1395
1396       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1397       if ((*s == '.' || *s == '_' || *s == '$')
1398           && s[1] == 'N')
1399         {
1400           di->expansion -= len - sizeof "(anonymous namespace)";
1401           return d_make_name (di, "(anonymous namespace)",
1402                               sizeof "(anonymous namespace)" - 1);
1403         }
1404     }
1405
1406   return d_make_name (di, name, len);
1407 }
1408
1409 /* operator_name ::= many different two character encodings.
1410                  ::= cv <type>
1411                  ::= v <digit> <source-name>
1412 */
1413
1414 #define NL(s) s, (sizeof s) - 1
1415
1416 CP_STATIC_IF_GLIBCPP_V3
1417 const struct demangle_operator_info cplus_demangle_operators[] =
1418 {
1419   { "aN", NL ("&="),        2 },
1420   { "aS", NL ("="),         2 },
1421   { "aa", NL ("&&"),        2 },
1422   { "ad", NL ("&"),         1 },
1423   { "an", NL ("&"),         2 },
1424   { "cl", NL ("()"),        0 },
1425   { "cm", NL (","),         2 },
1426   { "co", NL ("~"),         1 },
1427   { "dV", NL ("/="),        2 },
1428   { "da", NL ("delete[]"),  1 },
1429   { "de", NL ("*"),         1 },
1430   { "dl", NL ("delete"),    1 },
1431   { "dv", NL ("/"),         2 },
1432   { "eO", NL ("^="),        2 },
1433   { "eo", NL ("^"),         2 },
1434   { "eq", NL ("=="),        2 },
1435   { "ge", NL (">="),        2 },
1436   { "gt", NL (">"),         2 },
1437   { "ix", NL ("[]"),        2 },
1438   { "lS", NL ("<<="),       2 },
1439   { "le", NL ("<="),        2 },
1440   { "ls", NL ("<<"),        2 },
1441   { "lt", NL ("<"),         2 },
1442   { "mI", NL ("-="),        2 },
1443   { "mL", NL ("*="),        2 },
1444   { "mi", NL ("-"),         2 },
1445   { "ml", NL ("*"),         2 },
1446   { "mm", NL ("--"),        1 },
1447   { "na", NL ("new[]"),     1 },
1448   { "ne", NL ("!="),        2 },
1449   { "ng", NL ("-"),         1 },
1450   { "nt", NL ("!"),         1 },
1451   { "nw", NL ("new"),       1 },
1452   { "oR", NL ("|="),        2 },
1453   { "oo", NL ("||"),        2 },
1454   { "or", NL ("|"),         2 },
1455   { "pL", NL ("+="),        2 },
1456   { "pl", NL ("+"),         2 },
1457   { "pm", NL ("->*"),       2 },
1458   { "pp", NL ("++"),        1 },
1459   { "ps", NL ("+"),         1 },
1460   { "pt", NL ("->"),        2 },
1461   { "qu", NL ("?"),         3 },
1462   { "rM", NL ("%="),        2 },
1463   { "rS", NL (">>="),       2 },
1464   { "rm", NL ("%"),         2 },
1465   { "rs", NL (">>"),        2 },
1466   { "st", NL ("sizeof "),   1 },
1467   { "sz", NL ("sizeof "),   1 },
1468   { NULL, NULL, 0,          0 }
1469 };
1470
1471 static struct demangle_component *
1472 d_operator_name (struct d_info *di)
1473 {
1474   char c1;
1475   char c2;
1476
1477   c1 = d_next_char (di);
1478   c2 = d_next_char (di);
1479   if (c1 == 'v' && IS_DIGIT (c2))
1480     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1481   else if (c1 == 'c' && c2 == 'v')
1482     return d_make_comp (di, DEMANGLE_COMPONENT_CAST,
1483                         cplus_demangle_type (di), NULL);
1484   else
1485     {
1486       /* LOW is the inclusive lower bound.  */
1487       int low = 0;
1488       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1489          the sentinel at the end of the array.  */
1490       int high = ((sizeof (cplus_demangle_operators)
1491                    / sizeof (cplus_demangle_operators[0]))
1492                   - 1);
1493
1494       while (1)
1495         {
1496           int i;
1497           const struct demangle_operator_info *p;
1498
1499           i = low + (high - low) / 2;
1500           p = cplus_demangle_operators + i;
1501
1502           if (c1 == p->code[0] && c2 == p->code[1])
1503             return d_make_operator (di, p);
1504
1505           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1506             high = i;
1507           else
1508             low = i + 1;
1509           if (low == high)
1510             return NULL;
1511         }
1512     }
1513 }
1514
1515 static struct demangle_component *
1516 d_make_character (struct d_info *di, int c)
1517 {
1518   struct demangle_component *p;
1519   p = d_make_empty (di);
1520   if (p != NULL)
1521     {
1522       p->type = DEMANGLE_COMPONENT_CHARACTER;
1523       p->u.s_character.character = c;
1524     }
1525   return p;
1526 }
1527
1528 static struct demangle_component *
1529 d_java_resource (struct d_info *di)
1530 {
1531   struct demangle_component *p = NULL;
1532   struct demangle_component *next = NULL;
1533   long len, i;
1534   char c;
1535   const char *str;
1536
1537   len = d_number (di);
1538   if (len <= 1)
1539     return NULL;
1540
1541   /* Eat the leading '_'.  */
1542   if (d_next_char (di) != '_')
1543     return NULL;
1544   len--;
1545
1546   str = d_str (di);
1547   i = 0;
1548
1549   while (len > 0)
1550     {
1551       c = str[i];
1552       if (!c)
1553         return NULL;
1554
1555       /* Each chunk is either a '$' escape...  */
1556       if (c == '$')
1557         {
1558           i++;
1559           switch (str[i++])
1560             {
1561             case 'S':
1562               c = '/';
1563               break;
1564             case '_':
1565               c = '.';
1566               break;
1567             case '$':
1568               c = '$';
1569               break;
1570             default:
1571               return NULL;
1572             }
1573           next = d_make_character (di, c);
1574           d_advance (di, i);
1575           str = d_str (di);
1576           len -= i;
1577           i = 0;
1578           if (next == NULL)
1579             return NULL;
1580         }
1581       /* ... or a sequence of characters.  */
1582       else
1583         {
1584           while (i < len && str[i] && str[i] != '$')
1585             i++;
1586
1587           next = d_make_name (di, str, i);
1588           d_advance (di, i);
1589           str = d_str (di);
1590           len -= i;
1591           i = 0;
1592           if (next == NULL)
1593             return NULL;
1594         }
1595
1596       if (p == NULL)
1597         p = next;
1598       else
1599         {
1600           p = d_make_comp (di, DEMANGLE_COMPONENT_COMPOUND_NAME, p, next);
1601           if (p == NULL)
1602             return NULL;
1603         }
1604     }
1605
1606   p = d_make_comp (di, DEMANGLE_COMPONENT_JAVA_RESOURCE, p, NULL);
1607
1608   return p;
1609 }
1610
1611 /* <special-name> ::= TV <type>
1612                   ::= TT <type>
1613                   ::= TI <type>
1614                   ::= TS <type>
1615                   ::= GV <(object) name>
1616                   ::= T <call-offset> <(base) encoding>
1617                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1618    Also g++ extensions:
1619                   ::= TC <type> <(offset) number> _ <(base) type>
1620                   ::= TF <type>
1621                   ::= TJ <type>
1622                   ::= GR <name>
1623                   ::= GA <encoding>
1624                   ::= Gr <resource name>
1625 */
1626
1627 static struct demangle_component *
1628 d_special_name (struct d_info *di)
1629 {
1630   di->expansion += 20;
1631   if (d_check_char (di, 'T'))
1632     {
1633       switch (d_next_char (di))
1634         {
1635         case 'V':
1636           di->expansion -= 5;
1637           return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
1638                               cplus_demangle_type (di), NULL);
1639         case 'T':
1640           di->expansion -= 10;
1641           return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
1642                               cplus_demangle_type (di), NULL);
1643         case 'I':
1644           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
1645                               cplus_demangle_type (di), NULL);
1646         case 'S':
1647           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
1648                               cplus_demangle_type (di), NULL);
1649
1650         case 'h':
1651           if (! d_call_offset (di, 'h'))
1652             return NULL;
1653           return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
1654                               d_encoding (di, 0), NULL);
1655
1656         case 'v':
1657           if (! d_call_offset (di, 'v'))
1658             return NULL;
1659           return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
1660                               d_encoding (di, 0), NULL);
1661
1662         case 'c':
1663           if (! d_call_offset (di, '\0'))
1664             return NULL;
1665           if (! d_call_offset (di, '\0'))
1666             return NULL;
1667           return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
1668                               d_encoding (di, 0), NULL);
1669
1670         case 'C':
1671           {
1672             struct demangle_component *derived_type;
1673             long offset;
1674             struct demangle_component *base_type;
1675
1676             derived_type = cplus_demangle_type (di);
1677             offset = d_number (di);
1678             if (offset < 0)
1679               return NULL;
1680             if (! d_check_char (di, '_'))
1681               return NULL;
1682             base_type = cplus_demangle_type (di);
1683             /* We don't display the offset.  FIXME: We should display
1684                it in verbose mode.  */
1685             di->expansion += 5;
1686             return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
1687                                 base_type, derived_type);
1688           }
1689
1690         case 'F':
1691           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
1692                               cplus_demangle_type (di), NULL);
1693         case 'J':
1694           return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
1695                               cplus_demangle_type (di), NULL);
1696
1697         default:
1698           return NULL;
1699         }
1700     }
1701   else if (d_check_char (di, 'G'))
1702     {
1703       switch (d_next_char (di))
1704         {
1705         case 'V':
1706           return d_make_comp (di, DEMANGLE_COMPONENT_GUARD, d_name (di), NULL);
1707
1708         case 'R':
1709           return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, d_name (di),
1710                               NULL);
1711
1712         case 'A':
1713           return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
1714                               d_encoding (di, 0), NULL);
1715
1716         case 'r':
1717           return d_java_resource (di);
1718
1719         default:
1720           return NULL;
1721         }
1722     }
1723   else
1724     return NULL;
1725 }
1726
1727 /* <call-offset> ::= h <nv-offset> _
1728                  ::= v <v-offset> _
1729
1730    <nv-offset> ::= <(offset) number>
1731
1732    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
1733
1734    The C parameter, if not '\0', is a character we just read which is
1735    the start of the <call-offset>.
1736
1737    We don't display the offset information anywhere.  FIXME: We should
1738    display it in verbose mode.  */
1739
1740 static int
1741 d_call_offset (struct d_info *di, int c)
1742 {
1743   if (c == '\0')
1744     c = d_next_char (di);
1745
1746   if (c == 'h')
1747     d_number (di);
1748   else if (c == 'v')
1749     {
1750       d_number (di);
1751       if (! d_check_char (di, '_'))
1752         return 0;
1753       d_number (di);
1754     }
1755   else
1756     return 0;
1757
1758   if (! d_check_char (di, '_'))
1759     return 0;
1760
1761   return 1;
1762 }
1763
1764 /* <ctor-dtor-name> ::= C1
1765                     ::= C2
1766                     ::= C3
1767                     ::= D0
1768                     ::= D1
1769                     ::= D2
1770 */
1771
1772 static struct demangle_component *
1773 d_ctor_dtor_name (struct d_info *di)
1774 {
1775   if (di->last_name != NULL)
1776     {
1777       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
1778         di->expansion += di->last_name->u.s_name.len;
1779       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
1780         di->expansion += di->last_name->u.s_string.len;
1781     }
1782   switch (d_peek_char (di))
1783     {
1784     case 'C':
1785       {
1786         enum gnu_v3_ctor_kinds kind;
1787
1788         switch (d_peek_next_char (di))
1789           {
1790           case '1':
1791             kind = gnu_v3_complete_object_ctor;
1792             break;
1793           case '2':
1794             kind = gnu_v3_base_object_ctor;
1795             break;
1796           case '3':
1797             kind = gnu_v3_complete_object_allocating_ctor;
1798             break;
1799           default:
1800             return NULL;
1801           }
1802         d_advance (di, 2);
1803         return d_make_ctor (di, kind, di->last_name);
1804       }
1805
1806     case 'D':
1807       {
1808         enum gnu_v3_dtor_kinds kind;
1809
1810         switch (d_peek_next_char (di))
1811           {
1812           case '0':
1813             kind = gnu_v3_deleting_dtor;
1814             break;
1815           case '1':
1816             kind = gnu_v3_complete_object_dtor;
1817             break;
1818           case '2':
1819             kind = gnu_v3_base_object_dtor;
1820             break;
1821           default:
1822             return NULL;
1823           }
1824         d_advance (di, 2);
1825         return d_make_dtor (di, kind, di->last_name);
1826       }
1827
1828     default:
1829       return NULL;
1830     }
1831 }
1832
1833 /* <type> ::= <builtin-type>
1834           ::= <function-type>
1835           ::= <class-enum-type>
1836           ::= <array-type>
1837           ::= <pointer-to-member-type>
1838           ::= <template-param>
1839           ::= <template-template-param> <template-args>
1840           ::= <substitution>
1841           ::= <CV-qualifiers> <type>
1842           ::= P <type>
1843           ::= R <type>
1844           ::= O <type> (C++0x)
1845           ::= C <type>
1846           ::= G <type>
1847           ::= U <source-name> <type>
1848
1849    <builtin-type> ::= various one letter codes
1850                   ::= u <source-name>
1851 */
1852
1853 CP_STATIC_IF_GLIBCPP_V3
1854 const struct demangle_builtin_type_info
1855 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
1856 {
1857   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_DEFAULT },
1858   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
1859   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_DEFAULT },
1860   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_FLOAT },
1861   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_FLOAT },
1862   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_FLOAT },
1863   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_FLOAT },
1864   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_DEFAULT },
1865   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
1866   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_UNSIGNED },
1867   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1868   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
1869   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_UNSIGNED_LONG },
1870   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
1871   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
1872             D_PRINT_DEFAULT },
1873   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1874   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1875   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1876   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_DEFAULT },
1877   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
1878   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1879   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
1880   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_DEFAULT },
1881   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_LONG_LONG },
1882   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
1883             D_PRINT_UNSIGNED_LONG_LONG },
1884   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
1885 };
1886
1887 CP_STATIC_IF_GLIBCPP_V3
1888 struct demangle_component *
1889 cplus_demangle_type (struct d_info *di)
1890 {
1891   char peek;
1892   struct demangle_component *ret;
1893   int can_subst;
1894
1895   /* The ABI specifies that when CV-qualifiers are used, the base type
1896      is substitutable, and the fully qualified type is substitutable,
1897      but the base type with a strict subset of the CV-qualifiers is
1898      not substitutable.  The natural recursive implementation of the
1899      CV-qualifiers would cause subsets to be substitutable, so instead
1900      we pull them all off now.
1901
1902      FIXME: The ABI says that order-insensitive vendor qualifiers
1903      should be handled in the same way, but we have no way to tell
1904      which vendor qualifiers are order-insensitive and which are
1905      order-sensitive.  So we just assume that they are all
1906      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
1907      __vector, and it treats it as order-sensitive when mangling
1908      names.  */
1909
1910   peek = d_peek_char (di);
1911   if (peek == 'r' || peek == 'V' || peek == 'K')
1912     {
1913       struct demangle_component **pret;
1914
1915       pret = d_cv_qualifiers (di, &ret, 0);
1916       if (pret == NULL)
1917         return NULL;
1918       *pret = cplus_demangle_type (di);
1919       if (! *pret || ! d_add_substitution (di, ret))
1920         return NULL;
1921       return ret;
1922     }
1923
1924   can_subst = 1;
1925
1926   switch (peek)
1927     {
1928     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1929     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
1930     case 'o':                               case 's': case 't':
1931     case 'v': case 'w': case 'x': case 'y': case 'z':
1932       ret = d_make_builtin_type (di,
1933                                  &cplus_demangle_builtin_types[peek - 'a']);
1934       di->expansion += ret->u.s_builtin.type->len;
1935       can_subst = 0;
1936       d_advance (di, 1);
1937       break;
1938
1939     case 'u':
1940       d_advance (di, 1);
1941       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
1942                          d_source_name (di), NULL);
1943       break;
1944
1945     case 'F':
1946       ret = d_function_type (di);
1947       break;
1948
1949     case '0': case '1': case '2': case '3': case '4':
1950     case '5': case '6': case '7': case '8': case '9':
1951     case 'N':
1952     case 'Z':
1953       ret = d_class_enum_type (di);
1954       break;
1955
1956     case 'A':
1957       ret = d_array_type (di);
1958       break;
1959
1960     case 'M':
1961       ret = d_pointer_to_member_type (di);
1962       break;
1963
1964     case 'T':
1965       ret = d_template_param (di);
1966       if (d_peek_char (di) == 'I')
1967         {
1968           /* This is <template-template-param> <template-args>.  The
1969              <template-template-param> part is a substitution
1970              candidate.  */
1971           if (! d_add_substitution (di, ret))
1972             return NULL;
1973           ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
1974                              d_template_args (di));
1975         }
1976       break;
1977
1978     case 'S':
1979       /* If this is a special substitution, then it is the start of
1980          <class-enum-type>.  */
1981       {
1982         char peek_next;
1983
1984         peek_next = d_peek_next_char (di);
1985         if (IS_DIGIT (peek_next)
1986             || peek_next == '_'
1987             || IS_UPPER (peek_next))
1988           {
1989             ret = d_substitution (di, 0);
1990             /* The substituted name may have been a template name and
1991                may be followed by tepmlate args.  */
1992             if (d_peek_char (di) == 'I')
1993               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
1994                                  d_template_args (di));
1995             else
1996               can_subst = 0;
1997           }
1998         else
1999           {
2000             ret = d_class_enum_type (di);
2001             /* If the substitution was a complete type, then it is not
2002                a new substitution candidate.  However, if the
2003                substitution was followed by template arguments, then
2004                the whole thing is a substitution candidate.  */
2005             if (ret != NULL && ret->type == DEMANGLE_COMPONENT_SUB_STD)
2006               can_subst = 0;
2007           }
2008       }
2009       break;
2010
2011     case 'O':
2012       d_advance (di, 1);
2013       ret = d_make_comp (di, DEMANGLE_COMPONENT_RVALUE_REFERENCE,
2014                          cplus_demangle_type (di), NULL);
2015       break;
2016
2017     case 'P':
2018       d_advance (di, 1);
2019       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
2020                          cplus_demangle_type (di), NULL);
2021       break;
2022
2023     case 'R':
2024       d_advance (di, 1);
2025       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
2026                          cplus_demangle_type (di), NULL);
2027       break;
2028
2029     case 'C':
2030       d_advance (di, 1);
2031       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
2032                          cplus_demangle_type (di), NULL);
2033       break;
2034
2035     case 'G':
2036       d_advance (di, 1);
2037       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
2038                          cplus_demangle_type (di), NULL);
2039       break;
2040
2041     case 'U':
2042       d_advance (di, 1);
2043       ret = d_source_name (di);
2044       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
2045                          cplus_demangle_type (di), ret);
2046       break;
2047
2048     default:
2049       return NULL;
2050     }
2051
2052   if (can_subst)
2053     {
2054       if (! d_add_substitution (di, ret))
2055         return NULL;
2056     }
2057
2058   return ret;
2059 }
2060
2061 /* <CV-qualifiers> ::= [r] [V] [K]  */
2062
2063 static struct demangle_component **
2064 d_cv_qualifiers (struct d_info *di,
2065                  struct demangle_component **pret, int member_fn)
2066 {
2067   char peek;
2068
2069   peek = d_peek_char (di);
2070   while (peek == 'r' || peek == 'V' || peek == 'K')
2071     {
2072       enum demangle_component_type t;
2073
2074       d_advance (di, 1);
2075       if (peek == 'r')
2076         {
2077           t = (member_fn
2078                ? DEMANGLE_COMPONENT_RESTRICT_THIS
2079                : DEMANGLE_COMPONENT_RESTRICT);
2080           di->expansion += sizeof "restrict";
2081         }
2082       else if (peek == 'V')
2083         {
2084           t = (member_fn
2085                ? DEMANGLE_COMPONENT_VOLATILE_THIS
2086                : DEMANGLE_COMPONENT_VOLATILE);
2087           di->expansion += sizeof "volatile";
2088         }
2089       else
2090         {
2091           t = (member_fn
2092                ? DEMANGLE_COMPONENT_CONST_THIS
2093                : DEMANGLE_COMPONENT_CONST);
2094           di->expansion += sizeof "const";
2095         }
2096
2097       *pret = d_make_comp (di, t, NULL, NULL);
2098       if (*pret == NULL)
2099         return NULL;
2100       pret = &d_left (*pret);
2101
2102       peek = d_peek_char (di);
2103     }
2104
2105   return pret;
2106 }
2107
2108 /* <function-type> ::= F [Y] <bare-function-type> E  */
2109
2110 static struct demangle_component *
2111 d_function_type (struct d_info *di)
2112 {
2113   struct demangle_component *ret;
2114
2115   if (! d_check_char (di, 'F'))
2116     return NULL;
2117   if (d_peek_char (di) == 'Y')
2118     {
2119       /* Function has C linkage.  We don't print this information.
2120          FIXME: We should print it in verbose mode.  */
2121       d_advance (di, 1);
2122     }
2123   ret = d_bare_function_type (di, 1);
2124   if (! d_check_char (di, 'E'))
2125     return NULL;
2126   return ret;
2127 }
2128
2129 /* <bare-function-type> ::= [J]<type>+  */
2130
2131 static struct demangle_component *
2132 d_bare_function_type (struct d_info *di, int has_return_type)
2133 {
2134   struct demangle_component *return_type;
2135   struct demangle_component *tl;
2136   struct demangle_component **ptl;
2137   char peek;
2138
2139   /* Detect special qualifier indicating that the first argument
2140      is the return type.  */
2141   peek = d_peek_char (di);
2142   if (peek == 'J')
2143     {
2144       d_advance (di, 1);
2145       has_return_type = 1;
2146     }
2147
2148   return_type = NULL;
2149   tl = NULL;
2150   ptl = &tl;
2151   while (1)
2152     {
2153       struct demangle_component *type;
2154
2155       peek = d_peek_char (di);
2156       if (peek == '\0' || peek == 'E')
2157         break;
2158       type = cplus_demangle_type (di);
2159       if (type == NULL)
2160         return NULL;
2161       if (has_return_type)
2162         {
2163           return_type = type;
2164           has_return_type = 0;
2165         }
2166       else
2167         {
2168           *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2169           if (*ptl == NULL)
2170             return NULL;
2171           ptl = &d_right (*ptl);
2172         }
2173     }
2174
2175   /* There should be at least one parameter type besides the optional
2176      return type.  A function which takes no arguments will have a
2177      single parameter type void.  */
2178   if (tl == NULL)
2179     return NULL;
2180
2181   /* If we have a single parameter type void, omit it.  */
2182   if (d_right (tl) == NULL
2183       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2184       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2185     {
2186       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2187       tl = NULL;
2188     }
2189
2190   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE, return_type, tl);
2191 }
2192
2193 /* <class-enum-type> ::= <name>  */
2194
2195 static struct demangle_component *
2196 d_class_enum_type (struct d_info *di)
2197 {
2198   return d_name (di);
2199 }
2200
2201 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2202                 ::= A [<(dimension) expression>] _ <(element) type>
2203 */
2204
2205 static struct demangle_component *
2206 d_array_type (struct d_info *di)
2207 {
2208   char peek;
2209   struct demangle_component *dim;
2210
2211   if (! d_check_char (di, 'A'))
2212     return NULL;
2213
2214   peek = d_peek_char (di);
2215   if (peek == '_')
2216     dim = NULL;
2217   else if (IS_DIGIT (peek))
2218     {
2219       const char *s;
2220
2221       s = d_str (di);
2222       do
2223         {
2224           d_advance (di, 1);
2225           peek = d_peek_char (di);
2226         }
2227       while (IS_DIGIT (peek));
2228       dim = d_make_name (di, s, d_str (di) - s);
2229       if (dim == NULL)
2230         return NULL;
2231     }
2232   else
2233     {
2234       dim = d_expression (di);
2235       if (dim == NULL)
2236         return NULL;
2237     }
2238
2239   if (! d_check_char (di, '_'))
2240     return NULL;
2241
2242   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
2243                       cplus_demangle_type (di));
2244 }
2245
2246 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2247
2248 static struct demangle_component *
2249 d_pointer_to_member_type (struct d_info *di)
2250 {
2251   struct demangle_component *cl;
2252   struct demangle_component *mem;
2253   struct demangle_component **pmem;
2254
2255   if (! d_check_char (di, 'M'))
2256     return NULL;
2257
2258   cl = cplus_demangle_type (di);
2259
2260   /* The ABI specifies that any type can be a substitution source, and
2261      that M is followed by two types, and that when a CV-qualified
2262      type is seen both the base type and the CV-qualified types are
2263      substitution sources.  The ABI also specifies that for a pointer
2264      to a CV-qualified member function, the qualifiers are attached to
2265      the second type.  Given the grammar, a plain reading of the ABI
2266      suggests that both the CV-qualified member function and the
2267      non-qualified member function are substitution sources.  However,
2268      g++ does not work that way.  g++ treats only the CV-qualified
2269      member function as a substitution source.  FIXME.  So to work
2270      with g++, we need to pull off the CV-qualifiers here, in order to
2271      avoid calling add_substitution() in cplus_demangle_type().  But
2272      for a CV-qualified member which is not a function, g++ does
2273      follow the ABI, so we need to handle that case here by calling
2274      d_add_substitution ourselves.  */
2275
2276   pmem = d_cv_qualifiers (di, &mem, 1);
2277   if (pmem == NULL)
2278     return NULL;
2279   *pmem = cplus_demangle_type (di);
2280   if (*pmem == NULL)
2281     return NULL;
2282
2283   if (pmem != &mem && (*pmem)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
2284     {
2285       if (! d_add_substitution (di, mem))
2286         return NULL;
2287     }
2288
2289   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
2290 }
2291
2292 /* <template-param> ::= T_
2293                     ::= T <(parameter-2 non-negative) number> _
2294 */
2295
2296 static struct demangle_component *
2297 d_template_param (struct d_info *di)
2298 {
2299   long param;
2300
2301   if (! d_check_char (di, 'T'))
2302     return NULL;
2303
2304   if (d_peek_char (di) == '_')
2305     param = 0;
2306   else
2307     {
2308       param = d_number (di);
2309       if (param < 0)
2310         return NULL;
2311       param += 1;
2312     }
2313
2314   if (! d_check_char (di, '_'))
2315     return NULL;
2316
2317   ++di->did_subs;
2318
2319   return d_make_template_param (di, param);
2320 }
2321
2322 /* <template-args> ::= I <template-arg>+ E  */
2323
2324 static struct demangle_component *
2325 d_template_args (struct d_info *di)
2326 {
2327   struct demangle_component *hold_last_name;
2328   struct demangle_component *al;
2329   struct demangle_component **pal;
2330
2331   /* Preserve the last name we saw--don't let the template arguments
2332      clobber it, as that would give us the wrong name for a subsequent
2333      constructor or destructor.  */
2334   hold_last_name = di->last_name;
2335
2336   if (! d_check_char (di, 'I'))
2337     return NULL;
2338
2339   al = NULL;
2340   pal = &al;
2341   while (1)
2342     {
2343       struct demangle_component *a;
2344
2345       a = d_template_arg (di);
2346       if (a == NULL)
2347         return NULL;
2348
2349       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
2350       if (*pal == NULL)
2351         return NULL;
2352       pal = &d_right (*pal);
2353
2354       if (d_peek_char (di) == 'E')
2355         {
2356           d_advance (di, 1);
2357           break;
2358         }
2359     }
2360
2361   di->last_name = hold_last_name;
2362
2363   return al;
2364 }
2365
2366 /* <template-arg> ::= <type>
2367                   ::= X <expression> E
2368                   ::= <expr-primary>
2369 */
2370
2371 static struct demangle_component *
2372 d_template_arg (struct d_info *di)
2373 {
2374   struct demangle_component *ret;
2375
2376   switch (d_peek_char (di))
2377     {
2378     case 'X':
2379       d_advance (di, 1);
2380       ret = d_expression (di);
2381       if (! d_check_char (di, 'E'))
2382         return NULL;
2383       return ret;
2384
2385     case 'L':
2386       return d_expr_primary (di);
2387
2388     default:
2389       return cplus_demangle_type (di);
2390     }
2391 }
2392
2393 /* <expression> ::= <(unary) operator-name> <expression>
2394                 ::= <(binary) operator-name> <expression> <expression>
2395                 ::= <(trinary) operator-name> <expression> <expression> <expression>
2396                 ::= st <type>
2397                 ::= <template-param>
2398                 ::= sr <type> <unqualified-name>
2399                 ::= sr <type> <unqualified-name> <template-args>
2400                 ::= <expr-primary>
2401 */
2402
2403 static struct demangle_component *
2404 d_expression (struct d_info *di)
2405 {
2406   char peek;
2407
2408   peek = d_peek_char (di);
2409   if (peek == 'L')
2410     return d_expr_primary (di);
2411   else if (peek == 'T')
2412     return d_template_param (di);
2413   else if (peek == 's' && d_peek_next_char (di) == 'r')
2414     {
2415       struct demangle_component *type;
2416       struct demangle_component *name;
2417
2418       d_advance (di, 2);
2419       type = cplus_demangle_type (di);
2420       name = d_unqualified_name (di);
2421       if (d_peek_char (di) != 'I')
2422         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type, name);
2423       else
2424         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type,
2425                             d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
2426                                          d_template_args (di)));
2427     }
2428   else
2429     {
2430       struct demangle_component *op;
2431       int args;
2432
2433       op = d_operator_name (di);
2434       if (op == NULL)
2435         return NULL;
2436
2437       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
2438         di->expansion += op->u.s_operator.op->len - 2;
2439
2440       if (op->type == DEMANGLE_COMPONENT_OPERATOR
2441           && strcmp (op->u.s_operator.op->code, "st") == 0)
2442         return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
2443                             cplus_demangle_type (di));
2444
2445       switch (op->type)
2446         {
2447         default:
2448           return NULL;
2449         case DEMANGLE_COMPONENT_OPERATOR:
2450           args = op->u.s_operator.op->args;
2451           break;
2452         case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
2453           args = op->u.s_extended_operator.args;
2454           break;
2455         case DEMANGLE_COMPONENT_CAST:
2456           args = 1;
2457           break;
2458         }
2459
2460       switch (args)
2461         {
2462         case 1:
2463           return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
2464                               d_expression (di));
2465         case 2:
2466           {
2467             struct demangle_component *left;
2468
2469             left = d_expression (di);
2470             return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
2471                                 d_make_comp (di,
2472                                              DEMANGLE_COMPONENT_BINARY_ARGS,
2473                                              left,
2474                                              d_expression (di)));
2475           }
2476         case 3:
2477           {
2478             struct demangle_component *first;
2479             struct demangle_component *second;
2480
2481             first = d_expression (di);
2482             second = d_expression (di);
2483             return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
2484                                 d_make_comp (di,
2485                                              DEMANGLE_COMPONENT_TRINARY_ARG1,
2486                                              first,
2487                                              d_make_comp (di,
2488                                                           DEMANGLE_COMPONENT_TRINARY_ARG2,
2489                                                           second,
2490                                                           d_expression (di))));
2491           }
2492         default:
2493           return NULL;
2494         }
2495     }
2496 }
2497
2498 /* <expr-primary> ::= L <type> <(value) number> E
2499                   ::= L <type> <(value) float> E
2500                   ::= L <mangled-name> E
2501 */
2502
2503 static struct demangle_component *
2504 d_expr_primary (struct d_info *di)
2505 {
2506   struct demangle_component *ret;
2507
2508   if (! d_check_char (di, 'L'))
2509     return NULL;
2510   if (d_peek_char (di) == '_')
2511     ret = cplus_demangle_mangled_name (di, 0);
2512   else
2513     {
2514       struct demangle_component *type;
2515       enum demangle_component_type t;
2516       const char *s;
2517
2518       type = cplus_demangle_type (di);
2519       if (type == NULL)
2520         return NULL;
2521
2522       /* If we have a type we know how to print, we aren't going to
2523          print the type name itself.  */
2524       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2525           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
2526         di->expansion -= type->u.s_builtin.type->len;
2527
2528       /* Rather than try to interpret the literal value, we just
2529          collect it as a string.  Note that it's possible to have a
2530          floating point literal here.  The ABI specifies that the
2531          format of such literals is machine independent.  That's fine,
2532          but what's not fine is that versions of g++ up to 3.2 with
2533          -fabi-version=1 used upper case letters in the hex constant,
2534          and dumped out gcc's internal representation.  That makes it
2535          hard to tell where the constant ends, and hard to dump the
2536          constant in any readable form anyhow.  We don't attempt to
2537          handle these cases.  */
2538
2539       t = DEMANGLE_COMPONENT_LITERAL;
2540       if (d_peek_char (di) == 'n')
2541         {
2542           t = DEMANGLE_COMPONENT_LITERAL_NEG;
2543           d_advance (di, 1);
2544         }
2545       s = d_str (di);
2546       while (d_peek_char (di) != 'E')
2547         {
2548           if (d_peek_char (di) == '\0')
2549             return NULL;
2550           d_advance (di, 1);
2551         }
2552       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
2553     }
2554   if (! d_check_char (di, 'E'))
2555     return NULL;
2556   return ret;
2557 }
2558
2559 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2560                 ::= Z <(function) encoding> E s [<discriminator>]
2561 */
2562
2563 static struct demangle_component *
2564 d_local_name (struct d_info *di)
2565 {
2566   struct demangle_component *function;
2567
2568   if (! d_check_char (di, 'Z'))
2569     return NULL;
2570
2571   function = d_encoding (di, 0);
2572
2573   if (! d_check_char (di, 'E'))
2574     return NULL;
2575
2576   if (d_peek_char (di) == 's')
2577     {
2578       d_advance (di, 1);
2579       if (! d_discriminator (di))
2580         return NULL;
2581       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function,
2582                           d_make_name (di, "string literal",
2583                                        sizeof "string literal" - 1));
2584     }
2585   else
2586     {
2587       struct demangle_component *name;
2588
2589       name = d_name (di);
2590       if (! d_discriminator (di))
2591         return NULL;
2592       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
2593     }
2594 }
2595
2596 /* <discriminator> ::= _ <(non-negative) number>
2597
2598    We demangle the discriminator, but we don't print it out.  FIXME:
2599    We should print it out in verbose mode.  */
2600
2601 static int
2602 d_discriminator (struct d_info *di)
2603 {
2604   long discrim;
2605
2606   if (d_peek_char (di) != '_')
2607     return 1;
2608   d_advance (di, 1);
2609   discrim = d_number (di);
2610   if (discrim < 0)
2611     return 0;
2612   return 1;
2613 }
2614
2615 /* Add a new substitution.  */
2616
2617 static int
2618 d_add_substitution (struct d_info *di, struct demangle_component *dc)
2619 {
2620   if (dc == NULL)
2621     return 0;
2622   if (di->next_sub >= di->num_subs)
2623     return 0;
2624   di->subs[di->next_sub] = dc;
2625   ++di->next_sub;
2626   return 1;
2627 }
2628
2629 /* <substitution> ::= S <seq-id> _
2630                   ::= S_
2631                   ::= St
2632                   ::= Sa
2633                   ::= Sb
2634                   ::= Ss
2635                   ::= Si
2636                   ::= So
2637                   ::= Sd
2638
2639    If PREFIX is non-zero, then this type is being used as a prefix in
2640    a qualified name.  In this case, for the standard substitutions, we
2641    need to check whether we are being used as a prefix for a
2642    constructor or destructor, and return a full template name.
2643    Otherwise we will get something like std::iostream::~iostream()
2644    which does not correspond particularly well to any function which
2645    actually appears in the source.
2646 */
2647
2648 static const struct d_standard_sub_info standard_subs[] =
2649 {
2650   { 't', NL ("std"),
2651     NL ("std"),
2652     NULL, 0 },
2653   { 'a', NL ("std::allocator"),
2654     NL ("std::allocator"),
2655     NL ("allocator") },
2656   { 'b', NL ("std::basic_string"),
2657     NL ("std::basic_string"),
2658     NL ("basic_string") },
2659   { 's', NL ("std::string"),
2660     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
2661     NL ("basic_string") },
2662   { 'i', NL ("std::istream"),
2663     NL ("std::basic_istream<char, std::char_traits<char> >"),
2664     NL ("basic_istream") },
2665   { 'o', NL ("std::ostream"),
2666     NL ("std::basic_ostream<char, std::char_traits<char> >"),
2667     NL ("basic_ostream") },
2668   { 'd', NL ("std::iostream"),
2669     NL ("std::basic_iostream<char, std::char_traits<char> >"),
2670     NL ("basic_iostream") }
2671 };
2672
2673 static struct demangle_component *
2674 d_substitution (struct d_info *di, int prefix)
2675 {
2676   char c;
2677
2678   if (! d_check_char (di, 'S'))
2679     return NULL;
2680
2681   c = d_next_char (di);
2682   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
2683     {
2684       unsigned int id;
2685
2686       id = 0;
2687       if (c != '_')
2688         {
2689           do
2690             {
2691               unsigned int new_id;
2692
2693               if (IS_DIGIT (c))
2694                 new_id = id * 36 + c - '0';
2695               else if (IS_UPPER (c))
2696                 new_id = id * 36 + c - 'A' + 10;
2697               else
2698                 return NULL;
2699               if (new_id < id)
2700                 return NULL;
2701               id = new_id;
2702               c = d_next_char (di);
2703             }
2704           while (c != '_');
2705
2706           ++id;
2707         }
2708
2709       if (id >= (unsigned int) di->next_sub)
2710         return NULL;
2711
2712       ++di->did_subs;
2713
2714       return di->subs[id];
2715     }
2716   else
2717     {
2718       int verbose;
2719       const struct d_standard_sub_info *p;
2720       const struct d_standard_sub_info *pend;
2721
2722       verbose = (di->options & DMGL_VERBOSE) != 0;
2723       if (! verbose && prefix)
2724         {
2725           char peek;
2726
2727           peek = d_peek_char (di);
2728           if (peek == 'C' || peek == 'D')
2729             verbose = 1;
2730         }
2731
2732       pend = (&standard_subs[0]
2733               + sizeof standard_subs / sizeof standard_subs[0]);
2734       for (p = &standard_subs[0]; p < pend; ++p)
2735         {
2736           if (c == p->code)
2737             {
2738               const char *s;
2739               int len;
2740
2741               if (p->set_last_name != NULL)
2742                 di->last_name = d_make_sub (di, p->set_last_name,
2743                                             p->set_last_name_len);
2744               if (verbose)
2745                 {
2746                   s = p->full_expansion;
2747                   len = p->full_len;
2748                 }
2749               else
2750                 {
2751                   s = p->simple_expansion;
2752                   len = p->simple_len;
2753                 }
2754               di->expansion += len;
2755               return d_make_sub (di, s, len);
2756             }
2757         }
2758
2759       return NULL;
2760     }
2761 }
2762
2763 /* Initialize a growable string.  */
2764
2765 static void
2766 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
2767 {
2768   dgs->buf = NULL;
2769   dgs->len = 0;
2770   dgs->alc = 0;
2771   dgs->allocation_failure = 0;
2772
2773   if (estimate > 0)
2774     d_growable_string_resize (dgs, estimate);
2775 }
2776
2777 /* Grow a growable string to a given size.  */
2778
2779 static inline void
2780 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
2781 {
2782   size_t newalc;
2783   char *newbuf;
2784
2785   if (dgs->allocation_failure)
2786     return;
2787
2788   /* Start allocation at two bytes to avoid any possibility of confusion
2789      with the special value of 1 used as a return in *palc to indicate
2790      allocation failures.  */
2791   newalc = dgs->alc > 0 ? dgs->alc : 2;
2792   while (newalc < need)
2793     newalc <<= 1;
2794
2795   newbuf = (char *) realloc (dgs->buf, newalc);
2796   if (newbuf == NULL)
2797     {
2798       free (dgs->buf);
2799       dgs->buf = NULL;
2800       dgs->len = 0;
2801       dgs->alc = 0;
2802       dgs->allocation_failure = 1;
2803       return;
2804     }
2805   dgs->buf = newbuf;
2806   dgs->alc = newalc;
2807 }
2808
2809 /* Append a buffer to a growable string.  */
2810
2811 static inline void
2812 d_growable_string_append_buffer (struct d_growable_string *dgs,
2813                                  const char *s, size_t l)
2814 {
2815   size_t need;
2816
2817   need = dgs->len + l + 1;
2818   if (need > dgs->alc)
2819     d_growable_string_resize (dgs, need);
2820
2821   if (dgs->allocation_failure)
2822     return;
2823
2824   memcpy (dgs->buf + dgs->len, s, l);
2825   dgs->buf[dgs->len + l] = '\0';
2826   dgs->len += l;
2827 }
2828
2829 /* Bridge growable strings to the callback mechanism.  */
2830
2831 static void
2832 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
2833 {
2834   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
2835
2836   d_growable_string_append_buffer (dgs, s, l);
2837 }
2838
2839 /* Initialize a print information structure.  */
2840
2841 static void
2842 d_print_init (struct d_print_info *dpi, int options,
2843               demangle_callbackref callback, void *opaque)
2844 {
2845   dpi->options = options;
2846   dpi->len = 0;
2847   dpi->last_char = '\0';
2848   dpi->templates = NULL;
2849   dpi->modifiers = NULL;
2850
2851   dpi->callback = callback;
2852   dpi->opaque = opaque;
2853
2854   dpi->demangle_failure = 0;
2855 }
2856
2857 /* Indicate that an error occurred during printing, and test for error.  */
2858
2859 static inline void
2860 d_print_error (struct d_print_info *dpi)
2861 {
2862   dpi->demangle_failure = 1;
2863 }
2864
2865 static inline int
2866 d_print_saw_error (struct d_print_info *dpi)
2867 {
2868   return dpi->demangle_failure != 0;
2869 }
2870
2871 /* Flush buffered characters to the callback.  */
2872
2873 static inline void
2874 d_print_flush (struct d_print_info *dpi)
2875 {
2876   dpi->buf[dpi->len] = '\0';
2877   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
2878   dpi->len = 0;
2879 }
2880
2881 /* Append characters and buffers for printing.  */
2882
2883 static inline void
2884 d_append_char (struct d_print_info *dpi, char c)
2885 {
2886   if (dpi->len == sizeof (dpi->buf) - 1)
2887     d_print_flush (dpi);
2888
2889   dpi->buf[dpi->len++] = c;
2890   dpi->last_char = c;
2891 }
2892
2893 static inline void
2894 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
2895 {
2896   size_t i;
2897
2898   for (i = 0; i < l; i++)
2899     d_append_char (dpi, s[i]);
2900 }
2901
2902 static inline void
2903 d_append_string (struct d_print_info *dpi, const char *s)
2904 {
2905   d_append_buffer (dpi, s, strlen (s));
2906 }
2907
2908 static inline char
2909 d_last_char (struct d_print_info *dpi)
2910 {
2911   return dpi->last_char;
2912 }
2913
2914 /* Turn components into a human readable string.  OPTIONS is the
2915    options bits passed to the demangler.  DC is the tree to print.
2916    CALLBACK is a function to call to flush demangled string segments
2917    as they fill the intermediate buffer, and OPAQUE is a generalized
2918    callback argument.  On success, this returns 1.  On failure,
2919    it returns 0, indicating a bad parse.  It does not use heap
2920    memory to build an output string, so cannot encounter memory
2921    allocation failure.  */
2922
2923 CP_STATIC_IF_GLIBCPP_V3
2924 int
2925 cplus_demangle_print_callback (int options,
2926                                const struct demangle_component *dc,
2927                                demangle_callbackref callback, void *opaque)
2928 {
2929   struct d_print_info dpi;
2930
2931   d_print_init (&dpi, options, callback, opaque);
2932
2933   d_print_comp (&dpi, dc);
2934
2935   d_print_flush (&dpi);
2936
2937   return ! d_print_saw_error (&dpi);
2938 }
2939
2940 /* Turn components into a human readable string.  OPTIONS is the
2941    options bits passed to the demangler.  DC is the tree to print.
2942    ESTIMATE is a guess at the length of the result.  This returns a
2943    string allocated by malloc, or NULL on error.  On success, this
2944    sets *PALC to the size of the allocated buffer.  On failure, this
2945    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
2946    failure.  */
2947
2948 CP_STATIC_IF_GLIBCPP_V3
2949 char *
2950 cplus_demangle_print (int options, const struct demangle_component *dc,
2951                       int estimate, size_t *palc)
2952 {
2953   struct d_growable_string dgs;
2954
2955   d_growable_string_init (&dgs, estimate);
2956
2957   if (! cplus_demangle_print_callback (options, dc,
2958                                        d_growable_string_callback_adapter,
2959                                        &dgs))
2960     {
2961       free (dgs.buf);
2962       *palc = 0;
2963       return NULL;
2964     }
2965
2966   *palc = dgs.allocation_failure ? 1 : dgs.alc;
2967   return dgs.buf;
2968 }
2969
2970 /* Subroutine to handle components.  */
2971
2972 static void
2973 d_print_comp (struct d_print_info *dpi,
2974               const struct demangle_component *dc)
2975 {
2976   if (dc == NULL)
2977     {
2978       d_print_error (dpi);
2979       return;
2980     }
2981   if (d_print_saw_error (dpi))
2982     return;
2983
2984   switch (dc->type)
2985     {
2986     case DEMANGLE_COMPONENT_NAME:
2987       if ((dpi->options & DMGL_JAVA) == 0)
2988         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
2989       else
2990         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
2991       return;
2992
2993     case DEMANGLE_COMPONENT_QUAL_NAME:
2994     case DEMANGLE_COMPONENT_LOCAL_NAME:
2995       d_print_comp (dpi, d_left (dc));
2996       if ((dpi->options & DMGL_JAVA) == 0)
2997         d_append_string (dpi, "::");
2998       else
2999         d_append_char (dpi, '.');
3000       d_print_comp (dpi, d_right (dc));
3001       return;
3002
3003     case DEMANGLE_COMPONENT_TYPED_NAME:
3004       {
3005         struct d_print_mod *hold_modifiers;
3006         struct demangle_component *typed_name;
3007         struct d_print_mod adpm[4];
3008         unsigned int i;
3009         struct d_print_template dpt;
3010
3011         /* Pass the name down to the type so that it can be printed in
3012            the right place for the type.  We also have to pass down
3013            any CV-qualifiers, which apply to the this parameter.  */
3014         hold_modifiers = dpi->modifiers;
3015         i = 0;
3016         typed_name = d_left (dc);
3017         while (typed_name != NULL)
3018           {
3019             if (i >= sizeof adpm / sizeof adpm[0])
3020               {
3021                 d_print_error (dpi);
3022                 return;
3023               }
3024
3025             adpm[i].next = dpi->modifiers;
3026             dpi->modifiers = &adpm[i];
3027             adpm[i].mod = typed_name;
3028             adpm[i].printed = 0;
3029             adpm[i].templates = dpi->templates;
3030             ++i;
3031
3032             if (typed_name->type != DEMANGLE_COMPONENT_RESTRICT_THIS
3033                 && typed_name->type != DEMANGLE_COMPONENT_VOLATILE_THIS
3034                 && typed_name->type != DEMANGLE_COMPONENT_CONST_THIS)
3035               break;
3036
3037             typed_name = d_left (typed_name);
3038           }
3039
3040         if (typed_name == NULL)
3041           {
3042             d_print_error (dpi);
3043             return;
3044           }
3045
3046         /* If typed_name is a template, then it applies to the
3047            function type as well.  */
3048         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
3049           {
3050             dpt.next = dpi->templates;
3051             dpi->templates = &dpt;
3052             dpt.template_decl = typed_name;
3053           }
3054
3055         /* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
3056            there may be CV-qualifiers on its right argument which
3057            really apply here; this happens when parsing a class which
3058            is local to a function.  */
3059         if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
3060           {
3061             struct demangle_component *local_name;
3062
3063             local_name = d_right (typed_name);
3064             while (local_name->type == DEMANGLE_COMPONENT_RESTRICT_THIS
3065                    || local_name->type == DEMANGLE_COMPONENT_VOLATILE_THIS
3066                    || local_name->type == DEMANGLE_COMPONENT_CONST_THIS)
3067               {
3068                 if (i >= sizeof adpm / sizeof adpm[0])
3069                   {
3070                     d_print_error (dpi);
3071                     return;
3072                   }
3073
3074                 adpm[i] = adpm[i - 1];
3075                 adpm[i].next = &adpm[i - 1];
3076                 dpi->modifiers = &adpm[i];
3077
3078                 adpm[i - 1].mod = local_name;
3079                 adpm[i - 1].printed = 0;
3080                 adpm[i - 1].templates = dpi->templates;
3081                 ++i;
3082
3083                 local_name = d_left (local_name);
3084               }
3085           }
3086
3087         d_print_comp (dpi, d_right (dc));
3088
3089         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
3090           dpi->templates = dpt.next;
3091
3092         /* If the modifiers didn't get printed by the type, print them
3093            now.  */
3094         while (i > 0)
3095           {
3096             --i;
3097             if (! adpm[i].printed)
3098               {
3099                 d_append_char (dpi, ' ');
3100                 d_print_mod (dpi, adpm[i].mod);
3101               }
3102           }
3103
3104         dpi->modifiers = hold_modifiers;
3105
3106         return;
3107       }
3108
3109     case DEMANGLE_COMPONENT_TEMPLATE:
3110       {
3111         struct d_print_mod *hold_dpm;
3112         struct demangle_component *dcl;
3113
3114         /* Don't push modifiers into a template definition.  Doing so
3115            could give the wrong definition for a template argument.
3116            Instead, treat the template essentially as a name.  */
3117
3118         hold_dpm = dpi->modifiers;
3119         dpi->modifiers = NULL;
3120
3121         dcl = d_left (dc);
3122
3123         if ((dpi->options & DMGL_JAVA) != 0
3124             && dcl->type == DEMANGLE_COMPONENT_NAME
3125             && dcl->u.s_name.len == 6
3126             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
3127           {
3128             /* Special-case Java arrays, so that JArray<TYPE> appears
3129                instead as TYPE[].  */
3130
3131             d_print_comp (dpi, d_right (dc));
3132             d_append_string (dpi, "[]");
3133           }
3134         else
3135           {
3136             d_print_comp (dpi, dcl);
3137             if (d_last_char (dpi) == '<')
3138               d_append_char (dpi, ' ');
3139             d_append_char (dpi, '<');
3140             d_print_comp (dpi, d_right (dc));
3141             /* Avoid generating two consecutive '>' characters, to avoid
3142                the C++ syntactic ambiguity.  */
3143             if (d_last_char (dpi) == '>')
3144               d_append_char (dpi, ' ');
3145             d_append_char (dpi, '>');
3146           }
3147
3148         dpi->modifiers = hold_dpm;
3149
3150         return;
3151       }
3152
3153     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
3154       {
3155         long i;
3156         struct demangle_component *a;
3157         struct d_print_template *hold_dpt;
3158
3159         if (dpi->templates == NULL)
3160           {
3161             d_print_error (dpi);
3162             return;
3163           }
3164         i = dc->u.s_number.number;
3165         for (a = d_right (dpi->templates->template_decl);
3166              a != NULL;
3167              a = d_right (a))
3168           {
3169             if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
3170               {
3171                 d_print_error (dpi);
3172                 return;
3173               }
3174             if (i <= 0)
3175               break;
3176             --i;
3177           }
3178         if (i != 0 || a == NULL)
3179           {
3180             d_print_error (dpi);
3181             return;
3182           }
3183
3184         /* While processing this parameter, we need to pop the list of
3185            templates.  This is because the template parameter may
3186            itself be a reference to a parameter of an outer
3187            template.  */
3188
3189         hold_dpt = dpi->templates;
3190         dpi->templates = hold_dpt->next;
3191
3192         d_print_comp (dpi, d_left (a));
3193
3194         dpi->templates = hold_dpt;
3195
3196         return;
3197       }
3198
3199     case DEMANGLE_COMPONENT_CTOR:
3200       d_print_comp (dpi, dc->u.s_ctor.name);
3201       return;
3202
3203     case DEMANGLE_COMPONENT_DTOR:
3204       d_append_char (dpi, '~');
3205       d_print_comp (dpi, dc->u.s_dtor.name);
3206       return;
3207
3208     case DEMANGLE_COMPONENT_VTABLE:
3209       d_append_string (dpi, "vtable for ");
3210       d_print_comp (dpi, d_left (dc));
3211       return;
3212
3213     case DEMANGLE_COMPONENT_VTT:
3214       d_append_string (dpi, "VTT for ");
3215       d_print_comp (dpi, d_left (dc));
3216       return;
3217
3218     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
3219       d_append_string (dpi, "construction vtable for ");
3220       d_print_comp (dpi, d_left (dc));
3221       d_append_string (dpi, "-in-");
3222       d_print_comp (dpi, d_right (dc));
3223       return;
3224
3225     case DEMANGLE_COMPONENT_TYPEINFO:
3226       d_append_string (dpi, "typeinfo for ");
3227       d_print_comp (dpi, d_left (dc));
3228       return;
3229
3230     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
3231       d_append_string (dpi, "typeinfo name for ");
3232       d_print_comp (dpi, d_left (dc));
3233       return;
3234
3235     case DEMANGLE_COMPONENT_TYPEINFO_FN:
3236       d_append_string (dpi, "typeinfo fn for ");
3237       d_print_comp (dpi, d_left (dc));
3238       return;
3239
3240     case DEMANGLE_COMPONENT_THUNK:
3241       d_append_string (dpi, "non-virtual thunk to ");
3242       d_print_comp (dpi, d_left (dc));
3243       return;
3244
3245     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
3246       d_append_string (dpi, "virtual thunk to ");
3247       d_print_comp (dpi, d_left (dc));
3248       return;
3249
3250     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
3251       d_append_string (dpi, "covariant return thunk to ");
3252       d_print_comp (dpi, d_left (dc));
3253       return;
3254
3255     case DEMANGLE_COMPONENT_JAVA_CLASS:
3256       d_append_string (dpi, "java Class for ");
3257       d_print_comp (dpi, d_left (dc));
3258       return;
3259
3260     case DEMANGLE_COMPONENT_GUARD:
3261       d_append_string (dpi, "guard variable for ");
3262       d_print_comp (dpi, d_left (dc));
3263       return;
3264
3265     case DEMANGLE_COMPONENT_REFTEMP:
3266       d_append_string (dpi, "reference temporary for ");
3267       d_print_comp (dpi, d_left (dc));
3268       return;
3269
3270     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
3271       d_append_string (dpi, "hidden alias for ");
3272       d_print_comp (dpi, d_left (dc));
3273       return;
3274
3275     case DEMANGLE_COMPONENT_SUB_STD:
3276       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
3277       return;
3278
3279     case DEMANGLE_COMPONENT_RESTRICT:
3280     case DEMANGLE_COMPONENT_VOLATILE:
3281     case DEMANGLE_COMPONENT_CONST:
3282       {
3283         struct d_print_mod *pdpm;
3284
3285         /* When printing arrays, it's possible to have cases where the
3286            same CV-qualifier gets pushed on the stack multiple times.
3287            We only need to print it once.  */
3288
3289         for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
3290           {
3291             if (! pdpm->printed)
3292               {
3293                 if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
3294                     && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
3295                     && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
3296                   break;
3297                 if (pdpm->mod->type == dc->type)
3298                   {
3299                     d_print_comp (dpi, d_left (dc));
3300                     return;
3301                   }
3302               }
3303           }
3304       }
3305       /* Fall through.  */
3306     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3307     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3308     case DEMANGLE_COMPONENT_CONST_THIS:
3309     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3310     case DEMANGLE_COMPONENT_POINTER:
3311     case DEMANGLE_COMPONENT_REFERENCE:
3312     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
3313     case DEMANGLE_COMPONENT_COMPLEX:
3314     case DEMANGLE_COMPONENT_IMAGINARY:
3315       {
3316         /* We keep a list of modifiers on the stack.  */
3317         struct d_print_mod dpm;
3318
3319         dpm.next = dpi->modifiers;
3320         dpi->modifiers = &dpm;
3321         dpm.mod = dc;
3322         dpm.printed = 0;
3323         dpm.templates = dpi->templates;
3324
3325         d_print_comp (dpi, d_left (dc));
3326
3327         /* If the modifier didn't get printed by the type, print it
3328            now.  */
3329         if (! dpm.printed)
3330           d_print_mod (dpi, dc);
3331
3332         dpi->modifiers = dpm.next;
3333
3334         return;
3335       }
3336
3337     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
3338       if ((dpi->options & DMGL_JAVA) == 0)
3339         d_append_buffer (dpi, dc->u.s_builtin.type->name,
3340                          dc->u.s_builtin.type->len);
3341       else
3342         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
3343                          dc->u.s_builtin.type->java_len);
3344       return;
3345
3346     case DEMANGLE_COMPONENT_VENDOR_TYPE:
3347       d_print_comp (dpi, d_left (dc));
3348       return;
3349
3350     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
3351       {
3352         if ((dpi->options & DMGL_RET_POSTFIX) != 0)
3353           d_print_function_type (dpi, dc, dpi->modifiers);
3354
3355         /* Print return type if present */
3356         if (d_left (dc) != NULL)
3357           {
3358             struct d_print_mod dpm;
3359
3360             /* We must pass this type down as a modifier in order to
3361                print it in the right location.  */
3362             dpm.next = dpi->modifiers;
3363             dpi->modifiers = &dpm;
3364             dpm.mod = dc;
3365             dpm.printed = 0;
3366             dpm.templates = dpi->templates;
3367
3368             d_print_comp (dpi, d_left (dc));
3369
3370             dpi->modifiers = dpm.next;
3371
3372             if (dpm.printed)
3373               return;
3374
3375             /* In standard prefix notation, there is a space between the
3376                return type and the function signature.  */
3377             if ((dpi->options & DMGL_RET_POSTFIX) == 0)
3378               d_append_char (dpi, ' ');
3379           }
3380
3381         if ((dpi->options & DMGL_RET_POSTFIX) == 0) 
3382           d_print_function_type (dpi, dc, dpi->modifiers);
3383
3384         return;
3385       }
3386
3387     case DEMANGLE_COMPONENT_ARRAY_TYPE:
3388       {
3389         struct d_print_mod *hold_modifiers;
3390         struct d_print_mod adpm[4];
3391         unsigned int i;
3392         struct d_print_mod *pdpm;
3393
3394         /* We must pass this type down as a modifier in order to print
3395            multi-dimensional arrays correctly.  If the array itself is
3396            CV-qualified, we act as though the element type were
3397            CV-qualified.  We do this by copying the modifiers down
3398            rather than fiddling pointers, so that we don't wind up
3399            with a d_print_mod higher on the stack pointing into our
3400            stack frame after we return.  */
3401
3402         hold_modifiers = dpi->modifiers;
3403
3404         adpm[0].next = hold_modifiers;
3405         dpi->modifiers = &adpm[0];
3406         adpm[0].mod = dc;
3407         adpm[0].printed = 0;
3408         adpm[0].templates = dpi->templates;
3409
3410         i = 1;
3411         pdpm = hold_modifiers;
3412         while (pdpm != NULL
3413                && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
3414                    || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
3415                    || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
3416           {
3417             if (! pdpm->printed)
3418               {
3419                 if (i >= sizeof adpm / sizeof adpm[0])
3420                   {
3421                     d_print_error (dpi);
3422                     return;
3423                   }
3424
3425                 adpm[i] = *pdpm;
3426                 adpm[i].next = dpi->modifiers;
3427                 dpi->modifiers = &adpm[i];
3428                 pdpm->printed = 1;
3429                 ++i;
3430               }
3431
3432             pdpm = pdpm->next;
3433           }
3434
3435         d_print_comp (dpi, d_right (dc));
3436
3437         dpi->modifiers = hold_modifiers;
3438
3439         if (adpm[0].printed)
3440           return;
3441
3442         while (i > 1)
3443           {
3444             --i;
3445             d_print_mod (dpi, adpm[i].mod);
3446           }
3447
3448         d_print_array_type (dpi, dc, dpi->modifiers);
3449
3450         return;
3451       }
3452
3453     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3454       {
3455         struct d_print_mod dpm;
3456
3457         dpm.next = dpi->modifiers;
3458         dpi->modifiers = &dpm;
3459         dpm.mod = dc;
3460         dpm.printed = 0;
3461         dpm.templates = dpi->templates;
3462
3463         d_print_comp (dpi, d_right (dc));
3464
3465         /* If the modifier didn't get printed by the type, print it
3466            now.  */
3467         if (! dpm.printed)
3468           {
3469             d_append_char (dpi, ' ');
3470             d_print_comp (dpi, d_left (dc));
3471             d_append_string (dpi, "::*");
3472           }
3473
3474         dpi->modifiers = dpm.next;
3475
3476         return;
3477       }
3478
3479     case DEMANGLE_COMPONENT_ARGLIST:
3480     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
3481       d_print_comp (dpi, d_left (dc));
3482       if (d_right (dc) != NULL)
3483         {
3484           d_append_string (dpi, ", ");
3485           d_print_comp (dpi, d_right (dc));
3486         }
3487       return;
3488
3489     case DEMANGLE_COMPONENT_OPERATOR:
3490       {
3491         char c;
3492
3493         d_append_string (dpi, "operator");
3494         c = dc->u.s_operator.op->name[0];
3495         if (IS_LOWER (c))
3496           d_append_char (dpi, ' ');
3497         d_append_buffer (dpi, dc->u.s_operator.op->name,
3498                          dc->u.s_operator.op->len);
3499         return;
3500       }
3501
3502     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3503       d_append_string (dpi, "operator ");
3504       d_print_comp (dpi, dc->u.s_extended_operator.name);
3505       return;
3506
3507     case DEMANGLE_COMPONENT_CAST:
3508       d_append_string (dpi, "operator ");
3509       d_print_cast (dpi, dc);
3510       return;
3511
3512     case DEMANGLE_COMPONENT_UNARY:
3513       if (d_left (dc)->type != DEMANGLE_COMPONENT_CAST)
3514         d_print_expr_op (dpi, d_left (dc));
3515       else
3516         {
3517           d_append_char (dpi, '(');
3518           d_print_cast (dpi, d_left (dc));
3519           d_append_char (dpi, ')');
3520         }
3521       d_append_char (dpi, '(');
3522       d_print_comp (dpi, d_right (dc));
3523       d_append_char (dpi, ')');
3524       return;
3525
3526     case DEMANGLE_COMPONENT_BINARY:
3527       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
3528         {
3529           d_print_error (dpi);
3530           return;
3531         }
3532
3533       /* We wrap an expression which uses the greater-than operator in
3534          an extra layer of parens so that it does not get confused
3535          with the '>' which ends the template parameters.  */
3536       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
3537           && d_left (dc)->u.s_operator.op->len == 1
3538           && d_left (dc)->u.s_operator.op->name[0] == '>')
3539         d_append_char (dpi, '(');
3540
3541       d_append_char (dpi, '(');
3542       d_print_comp (dpi, d_left (d_right (dc)));
3543       d_append_string (dpi, ") ");
3544       d_print_expr_op (dpi, d_left (dc));
3545       d_append_string (dpi, " (");
3546       d_print_comp (dpi, d_right (d_right (dc)));
3547       d_append_char (dpi, ')');
3548
3549       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
3550           && d_left (dc)->u.s_operator.op->len == 1
3551           && d_left (dc)->u.s_operator.op->name[0] == '>')
3552         d_append_char (dpi, ')');
3553
3554       return;
3555
3556     case DEMANGLE_COMPONENT_BINARY_ARGS:
3557       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
3558       d_print_error (dpi);
3559       return;
3560
3561     case DEMANGLE_COMPONENT_TRINARY:
3562       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
3563           || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
3564         {
3565           d_print_error (dpi);
3566           return;
3567         }
3568       d_append_char (dpi, '(');
3569       d_print_comp (dpi, d_left (d_right (dc)));
3570       d_append_string (dpi, ") ");
3571       d_print_expr_op (dpi, d_left (dc));
3572       d_append_string (dpi, " (");
3573       d_print_comp (dpi, d_left (d_right (d_right (dc))));
3574       d_append_string (dpi, ") : (");
3575       d_print_comp (dpi, d_right (d_right (d_right (dc))));
3576       d_append_char (dpi, ')');
3577       return;
3578
3579     case DEMANGLE_COMPONENT_TRINARY_ARG1:
3580     case DEMANGLE_COMPONENT_TRINARY_ARG2:
3581       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
3582       d_print_error (dpi);
3583       return;
3584
3585     case DEMANGLE_COMPONENT_LITERAL:
3586     case DEMANGLE_COMPONENT_LITERAL_NEG:
3587       {
3588         enum d_builtin_type_print tp;
3589
3590         /* For some builtin types, produce simpler output.  */
3591         tp = D_PRINT_DEFAULT;
3592         if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
3593           {
3594             tp = d_left (dc)->u.s_builtin.type->print;
3595             switch (tp)
3596               {
3597               case D_PRINT_INT:
3598               case D_PRINT_UNSIGNED:
3599               case D_PRINT_LONG:
3600               case D_PRINT_UNSIGNED_LONG:
3601               case D_PRINT_LONG_LONG:
3602               case D_PRINT_UNSIGNED_LONG_LONG:
3603                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
3604                   {
3605                     if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
3606                       d_append_char (dpi, '-');
3607                     d_print_comp (dpi, d_right (dc));
3608                     switch (tp)
3609                       {
3610                       default:
3611                         break;
3612                       case D_PRINT_UNSIGNED:
3613                         d_append_char (dpi, 'u');
3614                         break;
3615                       case D_PRINT_LONG:
3616                         d_append_char (dpi, 'l');
3617                         break;
3618                       case D_PRINT_UNSIGNED_LONG:
3619                         d_append_string (dpi, "ul");
3620                         break;
3621                       case D_PRINT_LONG_LONG:
3622                         d_append_string (dpi, "ll");
3623                         break;
3624                       case D_PRINT_UNSIGNED_LONG_LONG:
3625                         d_append_string (dpi, "ull");
3626                         break;
3627                       }
3628                     return;
3629                   }
3630                 break;
3631
3632               case D_PRINT_BOOL:
3633                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
3634                     && d_right (dc)->u.s_name.len == 1
3635                     && dc->type == DEMANGLE_COMPONENT_LITERAL)
3636                   {
3637                     switch (d_right (dc)->u.s_name.s[0])
3638                       {
3639                       case '0':
3640                         d_append_string (dpi, "false");
3641                         return;
3642                       case '1':
3643                         d_append_string (dpi, "true");
3644                         return;
3645                       default:
3646                         break;
3647                       }
3648                   }
3649                 break;
3650
3651               default:
3652                 break;
3653               }
3654           }
3655
3656         d_append_char (dpi, '(');
3657         d_print_comp (dpi, d_left (dc));
3658         d_append_char (dpi, ')');
3659         if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
3660           d_append_char (dpi, '-');
3661         if (tp == D_PRINT_FLOAT)
3662           d_append_char (dpi, '[');
3663         d_print_comp (dpi, d_right (dc));
3664         if (tp == D_PRINT_FLOAT)
3665           d_append_char (dpi, ']');
3666       }
3667       return;
3668
3669     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
3670       d_append_string (dpi, "java resource ");
3671       d_print_comp (dpi, d_left (dc));
3672       return;
3673
3674     case DEMANGLE_COMPONENT_COMPOUND_NAME:
3675       d_print_comp (dpi, d_left (dc));
3676       d_print_comp (dpi, d_right (dc));
3677       return;
3678
3679     case DEMANGLE_COMPONENT_CHARACTER:
3680       d_append_char (dpi, dc->u.s_character.character);
3681       return;
3682
3683     default:
3684       d_print_error (dpi);
3685       return;
3686     }
3687 }
3688
3689 /* Print a Java dentifier.  For Java we try to handle encoded extended
3690    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
3691    so we don't it for C++.  Characters are encoded as
3692    __U<hex-char>+_.  */
3693
3694 static void
3695 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
3696 {
3697   const char *p;
3698   const char *end;
3699
3700   end = name + len;
3701   for (p = name; p < end; ++p)
3702     {
3703       if (end - p > 3
3704           && p[0] == '_'
3705           && p[1] == '_'
3706           && p[2] == 'U')
3707         {
3708           unsigned long c;
3709           const char *q;
3710
3711           c = 0;
3712           for (q = p + 3; q < end; ++q)
3713             {
3714               int dig;
3715
3716               if (IS_DIGIT (*q))
3717                 dig = *q - '0';
3718               else if (*q >= 'A' && *q <= 'F')
3719                 dig = *q - 'A' + 10;
3720               else if (*q >= 'a' && *q <= 'f')
3721                 dig = *q - 'a' + 10;
3722               else
3723                 break;
3724
3725               c = c * 16 + dig;
3726             }
3727           /* If the Unicode character is larger than 256, we don't try
3728              to deal with it here.  FIXME.  */
3729           if (q < end && *q == '_' && c < 256)
3730             {
3731               d_append_char (dpi, c);
3732               p = q;
3733               continue;
3734             }
3735         }
3736
3737       d_append_char (dpi, *p);
3738     }
3739 }
3740
3741 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
3742    qualifiers on this after printing a function.  */
3743
3744 static void
3745 d_print_mod_list (struct d_print_info *dpi,
3746                   struct d_print_mod *mods, int suffix)
3747 {
3748   struct d_print_template *hold_dpt;
3749
3750   if (mods == NULL || d_print_saw_error (dpi))
3751     return;
3752
3753   if (mods->printed
3754       || (! suffix
3755           && (mods->mod->type == DEMANGLE_COMPONENT_RESTRICT_THIS
3756               || mods->mod->type == DEMANGLE_COMPONENT_VOLATILE_THIS
3757               || mods->mod->type == DEMANGLE_COMPONENT_CONST_THIS)))
3758     {
3759       d_print_mod_list (dpi, mods->next, suffix);
3760       return;
3761     }
3762
3763   mods->printed = 1;
3764
3765   hold_dpt = dpi->templates;
3766   dpi->templates = mods->templates;
3767
3768   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
3769     {
3770       d_print_function_type (dpi, mods->mod, mods->next);
3771       dpi->templates = hold_dpt;
3772       return;
3773     }
3774   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
3775     {
3776       d_print_array_type (dpi, mods->mod, mods->next);
3777       dpi->templates = hold_dpt;
3778       return;
3779     }
3780   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
3781     {
3782       struct d_print_mod *hold_modifiers;
3783       struct demangle_component *dc;
3784
3785       /* When this is on the modifier stack, we have pulled any
3786          qualifiers off the right argument already.  Otherwise, we
3787          print it as usual, but don't let the left argument see any
3788          modifiers.  */
3789
3790       hold_modifiers = dpi->modifiers;
3791       dpi->modifiers = NULL;
3792       d_print_comp (dpi, d_left (mods->mod));
3793       dpi->modifiers = hold_modifiers;
3794
3795       if ((dpi->options & DMGL_JAVA) == 0)
3796         d_append_string (dpi, "::");
3797       else
3798         d_append_char (dpi, '.');
3799
3800       dc = d_right (mods->mod);
3801       while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
3802              || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
3803              || dc->type == DEMANGLE_COMPONENT_CONST_THIS)
3804         dc = d_left (dc);
3805
3806       d_print_comp (dpi, dc);
3807
3808       dpi->templates = hold_dpt;
3809       return;
3810     }
3811
3812   d_print_mod (dpi, mods->mod);
3813
3814   dpi->templates = hold_dpt;
3815
3816   d_print_mod_list (dpi, mods->next, suffix);
3817 }
3818
3819 /* Print a modifier.  */
3820
3821 static void
3822 d_print_mod (struct d_print_info *dpi,
3823              const struct demangle_component *mod)
3824 {
3825   switch (mod->type)
3826     {
3827     case DEMANGLE_COMPONENT_RESTRICT:
3828     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3829       d_append_string (dpi, " restrict");
3830       return;
3831     case DEMANGLE_COMPONENT_VOLATILE:
3832     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3833       d_append_string (dpi, " volatile");
3834       return;
3835     case DEMANGLE_COMPONENT_CONST:
3836     case DEMANGLE_COMPONENT_CONST_THIS:
3837       d_append_string (dpi, " const");
3838       return;
3839     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3840       d_append_char (dpi, ' ');
3841       d_print_comp (dpi, d_right (mod));
3842       return;
3843     case DEMANGLE_COMPONENT_POINTER:
3844       /* There is no pointer symbol in Java.  */
3845       if ((dpi->options & DMGL_JAVA) == 0)
3846         d_append_char (dpi, '*');
3847       return;
3848     case DEMANGLE_COMPONENT_REFERENCE:
3849       d_append_char (dpi, '&');
3850       return;
3851     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
3852       d_append_string (dpi, "&&");
3853       return;
3854     case DEMANGLE_COMPONENT_COMPLEX:
3855       d_append_string (dpi, "complex ");
3856       return;
3857     case DEMANGLE_COMPONENT_IMAGINARY:
3858       d_append_string (dpi, "imaginary ");
3859       return;
3860     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3861       if (d_last_char (dpi) != '(')
3862         d_append_char (dpi, ' ');
3863       d_print_comp (dpi, d_left (mod));
3864       d_append_string (dpi, "::*");
3865       return;
3866     case DEMANGLE_COMPONENT_TYPED_NAME:
3867       d_print_comp (dpi, d_left (mod));
3868       return;
3869     default:
3870       /* Otherwise, we have something that won't go back on the
3871          modifier stack, so we can just print it.  */
3872       d_print_comp (dpi, mod);
3873       return;
3874     }
3875 }
3876
3877 /* Print a function type, except for the return type.  */
3878
3879 static void
3880 d_print_function_type (struct d_print_info *dpi,
3881                        const struct demangle_component *dc,
3882                        struct d_print_mod *mods)
3883 {
3884   int need_paren;
3885   int saw_mod;
3886   int need_space;
3887   struct d_print_mod *p;
3888   struct d_print_mod *hold_modifiers;
3889
3890   need_paren = 0;
3891   saw_mod = 0;
3892   need_space = 0;
3893   for (p = mods; p != NULL; p = p->next)
3894     {
3895       if (p->printed)
3896         break;
3897
3898       saw_mod = 1;
3899       switch (p->mod->type)
3900         {
3901         case DEMANGLE_COMPONENT_POINTER:
3902         case DEMANGLE_COMPONENT_REFERENCE:
3903         case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
3904           need_paren = 1;
3905           break;
3906         case DEMANGLE_COMPONENT_RESTRICT:
3907         case DEMANGLE_COMPONENT_VOLATILE:
3908         case DEMANGLE_COMPONENT_CONST:
3909         case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3910         case DEMANGLE_COMPONENT_COMPLEX:
3911         case DEMANGLE_COMPONENT_IMAGINARY:
3912         case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3913           need_space = 1;
3914           need_paren = 1;
3915           break;
3916         case DEMANGLE_COMPONENT_RESTRICT_THIS:
3917         case DEMANGLE_COMPONENT_VOLATILE_THIS:
3918         case DEMANGLE_COMPONENT_CONST_THIS:
3919           break;
3920         default:
3921           break;
3922         }
3923       if (need_paren)
3924         break;
3925     }
3926
3927   if (d_left (dc) != NULL && ! saw_mod)
3928     need_paren = 1;
3929
3930   if (need_paren)
3931     {
3932       if (! need_space)
3933         {
3934           if (d_last_char (dpi) != '('
3935               && d_last_char (dpi) != '*')
3936             need_space = 1;
3937         }
3938       if (need_space && d_last_char (dpi) != ' ')
3939         d_append_char (dpi, ' ');
3940       d_append_char (dpi, '(');
3941     }
3942
3943   hold_modifiers = dpi->modifiers;
3944   dpi->modifiers = NULL;
3945
3946   d_print_mod_list (dpi, mods, 0);
3947
3948   if (need_paren)
3949     d_append_char (dpi, ')');
3950
3951   d_append_char (dpi, '(');
3952
3953   if (d_right (dc) != NULL)
3954     d_print_comp (dpi, d_right (dc));
3955
3956   d_append_char (dpi, ')');
3957
3958   d_print_mod_list (dpi, mods, 1);
3959
3960   dpi->modifiers = hold_modifiers;
3961 }
3962
3963 /* Print an array type, except for the element type.  */
3964
3965 static void
3966 d_print_array_type (struct d_print_info *dpi,
3967                     const struct demangle_component *dc,
3968                     struct d_print_mod *mods)
3969 {
3970   int need_space;
3971
3972   need_space = 1;
3973   if (mods != NULL)
3974     {
3975       int need_paren;
3976       struct d_print_mod *p;
3977
3978       need_paren = 0;
3979       for (p = mods; p != NULL; p = p->next)
3980         {
3981           if (! p->printed)
3982             {
3983               if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
3984                 {
3985                   need_space = 0;
3986                   break;
3987                 }
3988               else
3989                 {
3990                   need_paren = 1;
3991                   need_space = 1;
3992                   break;
3993                 }
3994             }
3995         }
3996
3997       if (need_paren)
3998         d_append_string (dpi, " (");
3999
4000       d_print_mod_list (dpi, mods, 0);
4001
4002       if (need_paren)
4003         d_append_char (dpi, ')');
4004     }
4005
4006   if (need_space)
4007     d_append_char (dpi, ' ');
4008
4009   d_append_char (dpi, '[');
4010
4011   if (d_left (dc) != NULL)
4012     d_print_comp (dpi, d_left (dc));
4013
4014   d_append_char (dpi, ']');
4015 }
4016
4017 /* Print an operator in an expression.  */
4018
4019 static void
4020 d_print_expr_op (struct d_print_info *dpi,
4021                  const struct demangle_component *dc)
4022 {
4023   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
4024     d_append_buffer (dpi, dc->u.s_operator.op->name,
4025                      dc->u.s_operator.op->len);
4026   else
4027     d_print_comp (dpi, dc);
4028 }
4029
4030 /* Print a cast.  */
4031
4032 static void
4033 d_print_cast (struct d_print_info *dpi,
4034               const struct demangle_component *dc)
4035 {
4036   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
4037     d_print_comp (dpi, d_left (dc));
4038   else
4039     {
4040       struct d_print_mod *hold_dpm;
4041       struct d_print_template dpt;
4042
4043       /* It appears that for a templated cast operator, we need to put
4044          the template parameters in scope for the operator name, but
4045          not for the parameters.  The effect is that we need to handle
4046          the template printing here.  */
4047
4048       hold_dpm = dpi->modifiers;
4049       dpi->modifiers = NULL;
4050
4051       dpt.next = dpi->templates;
4052       dpi->templates = &dpt;
4053       dpt.template_decl = d_left (dc);
4054
4055       d_print_comp (dpi, d_left (d_left (dc)));
4056
4057       dpi->templates = dpt.next;
4058
4059       if (d_last_char (dpi) == '<')
4060         d_append_char (dpi, ' ');
4061       d_append_char (dpi, '<');
4062       d_print_comp (dpi, d_right (d_left (dc)));
4063       /* Avoid generating two consecutive '>' characters, to avoid
4064          the C++ syntactic ambiguity.  */
4065       if (d_last_char (dpi) == '>')
4066         d_append_char (dpi, ' ');
4067       d_append_char (dpi, '>');
4068
4069       dpi->modifiers = hold_dpm;
4070     }
4071 }
4072
4073 /* Initialize the information structure we use to pass around
4074    information.  */
4075
4076 CP_STATIC_IF_GLIBCPP_V3
4077 void
4078 cplus_demangle_init_info (const char *mangled, int options, size_t len,
4079                           struct d_info *di)
4080 {
4081   di->s = mangled;
4082   di->send = mangled + len;
4083   di->options = options;
4084
4085   di->n = mangled;
4086
4087   /* We can not need more components than twice the number of chars in
4088      the mangled string.  Most components correspond directly to
4089      chars, but the ARGLIST types are exceptions.  */
4090   di->num_comps = 2 * len;
4091   di->next_comp = 0;
4092
4093   /* Similarly, we can not need more substitutions than there are
4094      chars in the mangled string.  */
4095   di->num_subs = len;
4096   di->next_sub = 0;
4097   di->did_subs = 0;
4098
4099   di->last_name = NULL;
4100
4101   di->expansion = 0;
4102 }
4103
4104 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
4105    mangled name, return strings in repeated callback giving the demangled
4106    name.  OPTIONS is the usual libiberty demangler options.  On success,
4107    this returns 1.  On failure, returns 0.  */
4108
4109 static int
4110 d_demangle_callback (const char *mangled, int options,
4111                      demangle_callbackref callback, void *opaque)
4112 {
4113   int type;
4114   struct d_info di;
4115   struct demangle_component *dc;
4116   int status;
4117
4118   if (mangled[0] == '_' && mangled[1] == 'Z')
4119     type = 0;
4120   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
4121            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
4122            && (mangled[9] == 'D' || mangled[9] == 'I')
4123            && mangled[10] == '_')
4124     {
4125       const char *intro;
4126
4127       intro = (mangled[9] == 'I')
4128               ? "global constructors keyed to "
4129               : "global destructors keyed to ";
4130
4131       callback (intro, strlen (intro), opaque);
4132       callback (mangled + 11, strlen (mangled + 11), opaque);
4133       return 1;
4134     }
4135   else
4136     {
4137       if ((options & DMGL_TYPES) == 0)
4138         return 0;
4139       type = 1;
4140     }
4141
4142   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
4143
4144   {
4145 #ifdef CP_DYNAMIC_ARRAYS
4146     __extension__ struct demangle_component comps[di.num_comps];
4147     __extension__ struct demangle_component *subs[di.num_subs];
4148
4149     di.comps = comps;
4150     di.subs = subs;
4151 #else
4152     di.comps = alloca (di.num_comps * sizeof (*di.comps));
4153     di.subs = alloca (di.num_subs * sizeof (*di.subs));
4154 #endif
4155
4156     if (type)
4157       dc = cplus_demangle_type (&di);
4158     else
4159       dc = cplus_demangle_mangled_name (&di, 1);
4160
4161     /* If DMGL_PARAMS is set, then if we didn't consume the entire
4162        mangled string, then we didn't successfully demangle it.  If
4163        DMGL_PARAMS is not set, we didn't look at the trailing
4164        parameters.  */
4165     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
4166       dc = NULL;
4167
4168 #ifdef CP_DEMANGLE_DEBUG
4169     d_dump (dc, 0);
4170 #endif
4171
4172     status = (dc != NULL)
4173              ? cplus_demangle_print_callback (options, dc, callback, opaque)
4174              : 0;
4175   }
4176
4177   return status;
4178 }
4179
4180 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
4181    name, return a buffer allocated with malloc holding the demangled
4182    name.  OPTIONS is the usual libiberty demangler options.  On
4183    success, this sets *PALC to the allocated size of the returned
4184    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
4185    a memory allocation failure, and returns NULL.  */
4186
4187 static char *
4188 d_demangle (const char *mangled, int options, size_t *palc)
4189 {
4190   struct d_growable_string dgs;
4191   int status;
4192
4193   d_growable_string_init (&dgs, 0);
4194
4195   status = d_demangle_callback (mangled, options,
4196                                 d_growable_string_callback_adapter, &dgs);
4197   if (status == 0)
4198     {
4199       free (dgs.buf);
4200       *palc = 0;
4201       return NULL;
4202     }
4203
4204   *palc = dgs.allocation_failure ? 1 : 0;
4205   return dgs.buf;
4206 }
4207
4208 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
4209
4210 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
4211
4212 /* ia64 ABI-mandated entry point in the C++ runtime library for
4213    performing demangling.  MANGLED_NAME is a NUL-terminated character
4214    string containing the name to be demangled.
4215
4216    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
4217    *LENGTH bytes, into which the demangled name is stored.  If
4218    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
4219    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
4220    is placed in a region of memory allocated with malloc.
4221
4222    If LENGTH is non-NULL, the length of the buffer containing the
4223    demangled name, is placed in *LENGTH.
4224
4225    The return value is a pointer to the start of the NUL-terminated
4226    demangled name, or NULL if the demangling fails.  The caller is
4227    responsible for deallocating this memory using free.
4228
4229    *STATUS is set to one of the following values:
4230       0: The demangling operation succeeded.
4231      -1: A memory allocation failure occurred.
4232      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
4233      -3: One of the arguments is invalid.
4234
4235    The demangling is performed using the C++ ABI mangling rules, with
4236    GNU extensions.  */
4237
4238 char *
4239 __cxa_demangle (const char *mangled_name, char *output_buffer,
4240                 size_t *length, int *status)
4241 {
4242   char *demangled;
4243   size_t alc;
4244
4245   if (mangled_name == NULL)
4246     {
4247       if (status != NULL)
4248         *status = -3;
4249       return NULL;
4250     }
4251
4252   if (output_buffer != NULL && length == NULL)
4253     {
4254       if (status != NULL)
4255         *status = -3;
4256       return NULL;
4257     }
4258
4259   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
4260
4261   if (demangled == NULL)
4262     {
4263       if (status != NULL)
4264         {
4265           if (alc == 1)
4266             *status = -1;
4267           else
4268             *status = -2;
4269         }
4270       return NULL;
4271     }
4272
4273   if (output_buffer == NULL)
4274     {
4275       if (length != NULL)
4276         *length = alc;
4277     }
4278   else
4279     {
4280       if (strlen (demangled) < *length)
4281         {
4282           strcpy (output_buffer, demangled);
4283           free (demangled);
4284           demangled = output_buffer;
4285         }
4286       else
4287         {
4288           free (output_buffer);
4289           *length = alc;
4290         }
4291     }
4292
4293   if (status != NULL)
4294     *status = 0;
4295
4296   return demangled;
4297 }
4298
4299 extern int __gcclibcxx_demangle_callback (const char *,
4300                                           void (*)
4301                                             (const char *, size_t, void *),
4302                                           void *);
4303
4304 /* Alternative, allocationless entry point in the C++ runtime library
4305    for performing demangling.  MANGLED_NAME is a NUL-terminated character
4306    string containing the name to be demangled.
4307
4308    CALLBACK is a callback function, called with demangled string
4309    segments as demangling progresses; it is called at least once,
4310    but may be called more than once.  OPAQUE is a generalized pointer
4311    used as a callback argument.
4312
4313    The return code is one of the following values, equivalent to
4314    the STATUS values of __cxa_demangle() (excluding -1, since this
4315    function performs no memory allocations):
4316       0: The demangling operation succeeded.
4317      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
4318      -3: One of the arguments is invalid.
4319
4320    The demangling is performed using the C++ ABI mangling rules, with
4321    GNU extensions.  */
4322
4323 int
4324 __gcclibcxx_demangle_callback (const char *mangled_name,
4325                                void (*callback) (const char *, size_t, void *),
4326                                void *opaque)
4327 {
4328   int status;
4329
4330   if (mangled_name == NULL || callback == NULL)
4331     return -3;
4332
4333   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
4334                                 callback, opaque);
4335   if (status == 0)
4336     return -2;
4337
4338   return 0;
4339 }
4340
4341 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
4342
4343 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
4344    mangled name, return a buffer allocated with malloc holding the
4345    demangled name.  Otherwise, return NULL.  */
4346
4347 char *
4348 cplus_demangle_v3 (const char *mangled, int options)
4349 {
4350   size_t alc;
4351
4352   return d_demangle (mangled, options, &alc);
4353 }
4354
4355 int
4356 cplus_demangle_v3_callback (const char *mangled, int options,
4357                             demangle_callbackref callback, void *opaque)
4358 {
4359   return d_demangle_callback (mangled, options, callback, opaque);
4360 }
4361
4362 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
4363    conventions, but the output formatting is a little different.
4364    This instructs the C++ demangler not to emit pointer characters ("*"), to
4365    use Java's namespace separator symbol ("." instead of "::"), and to output
4366    JArray<TYPE> as TYPE[].  */
4367
4368 char *
4369 java_demangle_v3 (const char *mangled)
4370 {
4371   size_t alc;
4372
4373   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
4374 }
4375
4376 int
4377 java_demangle_v3_callback (const char *mangled,
4378                            demangle_callbackref callback, void *opaque)
4379 {
4380   return d_demangle_callback (mangled,
4381                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
4382                               callback, opaque);
4383 }
4384
4385 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
4386
4387 #ifndef IN_GLIBCPP_V3
4388
4389 /* Demangle a string in order to find out whether it is a constructor
4390    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
4391    *DTOR_KIND appropriately.  */
4392
4393 static int
4394 is_ctor_or_dtor (const char *mangled,
4395                  enum gnu_v3_ctor_kinds *ctor_kind,
4396                  enum gnu_v3_dtor_kinds *dtor_kind)
4397 {
4398   struct d_info di;
4399   struct demangle_component *dc;
4400   int ret;
4401
4402   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
4403   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
4404
4405   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
4406
4407   {
4408 #ifdef CP_DYNAMIC_ARRAYS
4409     __extension__ struct demangle_component comps[di.num_comps];
4410     __extension__ struct demangle_component *subs[di.num_subs];
4411
4412     di.comps = comps;
4413     di.subs = subs;
4414 #else
4415     di.comps = alloca (di.num_comps * sizeof (*di.comps));
4416     di.subs = alloca (di.num_subs * sizeof (*di.subs));
4417 #endif
4418
4419     dc = cplus_demangle_mangled_name (&di, 1);
4420
4421     /* Note that because we did not pass DMGL_PARAMS, we don't expect
4422        to demangle the entire string.  */
4423
4424     ret = 0;
4425     while (dc != NULL)
4426       {
4427         switch (dc->type)
4428           {
4429           default:
4430             dc = NULL;
4431             break;
4432           case DEMANGLE_COMPONENT_TYPED_NAME:
4433           case DEMANGLE_COMPONENT_TEMPLATE:
4434           case DEMANGLE_COMPONENT_RESTRICT_THIS:
4435           case DEMANGLE_COMPONENT_VOLATILE_THIS:
4436           case DEMANGLE_COMPONENT_CONST_THIS:
4437             dc = d_left (dc);
4438             break;
4439           case DEMANGLE_COMPONENT_QUAL_NAME:
4440           case DEMANGLE_COMPONENT_LOCAL_NAME:
4441             dc = d_right (dc);
4442             break;
4443           case DEMANGLE_COMPONENT_CTOR:
4444             *ctor_kind = dc->u.s_ctor.kind;
4445             ret = 1;
4446             dc = NULL;
4447             break;
4448           case DEMANGLE_COMPONENT_DTOR:
4449             *dtor_kind = dc->u.s_dtor.kind;
4450             ret = 1;
4451             dc = NULL;
4452             break;
4453           }
4454       }
4455   }
4456
4457   return ret;
4458 }
4459
4460 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
4461    name.  A non-zero return indicates the type of constructor.  */
4462
4463 enum gnu_v3_ctor_kinds
4464 is_gnu_v3_mangled_ctor (const char *name)
4465 {
4466   enum gnu_v3_ctor_kinds ctor_kind;
4467   enum gnu_v3_dtor_kinds dtor_kind;
4468
4469   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4470     return (enum gnu_v3_ctor_kinds) 0;
4471   return ctor_kind;
4472 }
4473
4474
4475 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
4476    name.  A non-zero return indicates the type of destructor.  */
4477
4478 enum gnu_v3_dtor_kinds
4479 is_gnu_v3_mangled_dtor (const char *name)
4480 {
4481   enum gnu_v3_ctor_kinds ctor_kind;
4482   enum gnu_v3_dtor_kinds dtor_kind;
4483
4484   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4485     return (enum gnu_v3_dtor_kinds) 0;
4486   return dtor_kind;
4487 }
4488
4489 #endif /* IN_GLIBCPP_V3 */
4490
4491 #ifdef STANDALONE_DEMANGLER
4492
4493 #include "getopt.h"
4494 #include "dyn-string.h"
4495
4496 static void print_usage (FILE* fp, int exit_value);
4497
4498 #define IS_ALPHA(CHAR)                                                  \
4499   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
4500    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
4501
4502 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
4503 #define is_mangled_char(CHAR)                                           \
4504   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
4505    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
4506
4507 /* The name of this program, as invoked.  */
4508 const char* program_name;
4509
4510 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
4511
4512 static void
4513 print_usage (FILE* fp, int exit_value)
4514 {
4515   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
4516   fprintf (fp, "Options:\n");
4517   fprintf (fp, "  -h,--help       Display this message.\n");
4518   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
4519   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
4520   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
4521
4522   exit (exit_value);
4523 }
4524
4525 /* Option specification for getopt_long.  */
4526 static const struct option long_options[] = 
4527 {
4528   { "help",      no_argument, NULL, 'h' },
4529   { "no-params", no_argument, NULL, 'p' },
4530   { "verbose",   no_argument, NULL, 'v' },
4531   { NULL,        no_argument, NULL, 0   },
4532 };
4533
4534 /* Main entry for a demangling filter executable.  It will demangle
4535    its command line arguments, if any.  If none are provided, it will
4536    filter stdin to stdout, replacing any recognized mangled C++ names
4537    with their demangled equivalents.  */
4538
4539 int
4540 main (int argc, char *argv[])
4541 {
4542   int i;
4543   int opt_char;
4544   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
4545
4546   /* Use the program name of this program, as invoked.  */
4547   program_name = argv[0];
4548
4549   /* Parse options.  */
4550   do 
4551     {
4552       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
4553       switch (opt_char)
4554         {
4555         case '?':  /* Unrecognized option.  */
4556           print_usage (stderr, 1);
4557           break;
4558
4559         case 'h':
4560           print_usage (stdout, 0);
4561           break;
4562
4563         case 'p':
4564           options &= ~ DMGL_PARAMS;
4565           break;
4566
4567         case 'v':
4568           options |= DMGL_VERBOSE;
4569           break;
4570         }
4571     }
4572   while (opt_char != -1);
4573
4574   if (optind == argc) 
4575     /* No command line arguments were provided.  Filter stdin.  */
4576     {
4577       dyn_string_t mangled = dyn_string_new (3);
4578       char *s;
4579
4580       /* Read all of input.  */
4581       while (!feof (stdin))
4582         {
4583           char c;
4584
4585           /* Pile characters into mangled until we hit one that can't
4586              occur in a mangled name.  */
4587           c = getchar ();
4588           while (!feof (stdin) && is_mangled_char (c))
4589             {
4590               dyn_string_append_char (mangled, c);
4591               if (feof (stdin))
4592                 break;
4593               c = getchar ();
4594             }
4595
4596           if (dyn_string_length (mangled) > 0)
4597             {
4598 #ifdef IN_GLIBCPP_V3
4599               s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
4600 #else
4601               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
4602 #endif
4603
4604               if (s != NULL)
4605                 {
4606                   fputs (s, stdout);
4607                   free (s);
4608                 }
4609               else
4610                 {
4611                   /* It might not have been a mangled name.  Print the
4612                      original text.  */
4613                   fputs (dyn_string_buf (mangled), stdout);
4614                 }
4615
4616               dyn_string_clear (mangled);
4617             }
4618
4619           /* If we haven't hit EOF yet, we've read one character that
4620              can't occur in a mangled name, so print it out.  */
4621           if (!feof (stdin))
4622             putchar (c);
4623         }
4624
4625       dyn_string_delete (mangled);
4626     }
4627   else
4628     /* Demangle command line arguments.  */
4629     {
4630       /* Loop over command line arguments.  */
4631       for (i = optind; i < argc; ++i)
4632         {
4633           char *s;
4634 #ifdef IN_GLIBCPP_V3
4635           int status;
4636 #endif
4637
4638           /* Attempt to demangle.  */
4639 #ifdef IN_GLIBCPP_V3
4640           s = __cxa_demangle (argv[i], NULL, NULL, &status);
4641 #else
4642           s = cplus_demangle_v3 (argv[i], options);
4643 #endif
4644
4645           /* If it worked, print the demangled name.  */
4646           if (s != NULL)
4647             {
4648               printf ("%s\n", s);
4649               free (s);
4650             }
4651           else
4652             {
4653 #ifdef IN_GLIBCPP_V3
4654               fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
4655 #else
4656               fprintf (stderr, "Failed: %s\n", argv[i]);
4657 #endif
4658             }
4659         }
4660     }
4661
4662   return 0;
4663 }
4664
4665 #endif /* STANDALONE_DEMANGLER */