merge from gcc
[external/binutils.git] / libiberty / cplus-dem.c
1 /* Demangler for GNU C++
2    Copyright 1989, 1991, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001 Free Software Foundation, Inc.
4    Written by James Clark (jjc@jclark.uucp)
5    Rewritten by Fred Fish (fnf@cygnus.com) for ARM and Lucid demangling
6    Modified by Satish Pai (pai@apollo.hp.com) for HP demangling
7
8 This file is part of the libiberty library.
9 Libiberty is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Library General Public
11 License as published by the Free Software Foundation; either
12 version 2 of the License, or (at your option) any later version.
13
14 Libiberty is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 Library General Public License for more details.
18
19 You should have received a copy of the GNU Library General Public
20 License along with libiberty; see the file COPYING.LIB.  If
21 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* This file exports two functions; cplus_mangle_opname and cplus_demangle.
25
26    This file imports xmalloc and xrealloc, which are like malloc and
27    realloc except that they generate a fatal error if there is no
28    available memory.  */
29
30 /* This file lives in both GCC and libiberty.  When making changes, please
31    try not to break either.  */
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include "safe-ctype.h"
38
39 #include <sys/types.h>
40 #include <string.h>
41 #include <stdio.h>
42
43 #ifdef HAVE_STDLIB_H
44 #include <stdlib.h>
45 #else
46 char * malloc ();
47 char * realloc ();
48 #endif
49
50 #include <demangle.h>
51 #undef CURRENT_DEMANGLING_STYLE
52 #define CURRENT_DEMANGLING_STYLE work->options
53
54 #include "libiberty.h"
55
56 static char *ada_demangle  PARAMS ((const char *, int));
57
58 #define min(X,Y) (((X) < (Y)) ? (X) : (Y))
59
60 /* A value at least one greater than the maximum number of characters
61    that will be output when using the `%d' format with `printf'.  */
62 #define INTBUF_SIZE 32
63
64 extern void fancy_abort PARAMS ((void)) ATTRIBUTE_NORETURN;
65
66 /* In order to allow a single demangler executable to demangle strings
67    using various common values of CPLUS_MARKER, as well as any specific
68    one set at compile time, we maintain a string containing all the
69    commonly used ones, and check to see if the marker we are looking for
70    is in that string.  CPLUS_MARKER is usually '$' on systems where the
71    assembler can deal with that.  Where the assembler can't, it's usually
72    '.' (but on many systems '.' is used for other things).  We put the
73    current defined CPLUS_MARKER first (which defaults to '$'), followed
74    by the next most common value, followed by an explicit '$' in case
75    the value of CPLUS_MARKER is not '$'.
76
77    We could avoid this if we could just get g++ to tell us what the actual
78    cplus marker character is as part of the debug information, perhaps by
79    ensuring that it is the character that terminates the gcc<n>_compiled
80    marker symbol (FIXME).  */
81
82 #if !defined (CPLUS_MARKER)
83 #define CPLUS_MARKER '$'
84 #endif
85
86 enum demangling_styles current_demangling_style = auto_demangling;
87
88 static char cplus_markers[] = { CPLUS_MARKER, '.', '$', '\0' };
89
90 static char char_str[2] = { '\000', '\000' };
91
92 void
93 set_cplus_marker_for_demangling (ch)
94      int ch;
95 {
96   cplus_markers[0] = ch;
97 }
98
99 typedef struct string           /* Beware: these aren't required to be */
100 {                               /*  '\0' terminated.  */
101   char *b;                      /* pointer to start of string */
102   char *p;                      /* pointer after last character */
103   char *e;                      /* pointer after end of allocated space */
104 } string;
105
106 /* Stuff that is shared between sub-routines.
107    Using a shared structure allows cplus_demangle to be reentrant.  */
108
109 struct work_stuff
110 {
111   int options;
112   char **typevec;
113   char **ktypevec;
114   char **btypevec;
115   int numk;
116   int numb;
117   int ksize;
118   int bsize;
119   int ntypes;
120   int typevec_size;
121   int constructor;
122   int destructor;
123   int static_type;      /* A static member function */
124   int temp_start;       /* index in demangled to start of template args */
125   int type_quals;       /* The type qualifiers.  */
126   int dllimported;      /* Symbol imported from a PE DLL */
127   char **tmpl_argvec;   /* Template function arguments. */
128   int ntmpl_args;       /* The number of template function arguments. */
129   int forgetting_types; /* Nonzero if we are not remembering the types
130                            we see.  */
131   string* previous_argument; /* The last function argument demangled.  */
132   int nrepeats;         /* The number of times to repeat the previous
133                            argument.  */
134 };
135
136 #define PRINT_ANSI_QUALIFIERS (work -> options & DMGL_ANSI)
137 #define PRINT_ARG_TYPES       (work -> options & DMGL_PARAMS)
138
139 static const struct optable
140 {
141   const char *const in;
142   const char *const out;
143   const int flags;
144 } optable[] = {
145   {"nw",          " new",       DMGL_ANSI},     /* new (1.92,    ansi) */
146   {"dl",          " delete",    DMGL_ANSI},     /* new (1.92,    ansi) */
147   {"new",         " new",       0},             /* old (1.91,    and 1.x) */
148   {"delete",      " delete",    0},             /* old (1.91,    and 1.x) */
149   {"vn",          " new []",    DMGL_ANSI},     /* GNU, pending ansi */
150   {"vd",          " delete []", DMGL_ANSI},     /* GNU, pending ansi */
151   {"as",          "=",          DMGL_ANSI},     /* ansi */
152   {"ne",          "!=",         DMGL_ANSI},     /* old, ansi */
153   {"eq",          "==",         DMGL_ANSI},     /* old, ansi */
154   {"ge",          ">=",         DMGL_ANSI},     /* old, ansi */
155   {"gt",          ">",          DMGL_ANSI},     /* old, ansi */
156   {"le",          "<=",         DMGL_ANSI},     /* old, ansi */
157   {"lt",          "<",          DMGL_ANSI},     /* old, ansi */
158   {"plus",        "+",          0},             /* old */
159   {"pl",          "+",          DMGL_ANSI},     /* ansi */
160   {"apl",         "+=",         DMGL_ANSI},     /* ansi */
161   {"minus",       "-",          0},             /* old */
162   {"mi",          "-",          DMGL_ANSI},     /* ansi */
163   {"ami",         "-=",         DMGL_ANSI},     /* ansi */
164   {"mult",        "*",          0},             /* old */
165   {"ml",          "*",          DMGL_ANSI},     /* ansi */
166   {"amu",         "*=",         DMGL_ANSI},     /* ansi (ARM/Lucid) */
167   {"aml",         "*=",         DMGL_ANSI},     /* ansi (GNU/g++) */
168   {"convert",     "+",          0},             /* old (unary +) */
169   {"negate",      "-",          0},             /* old (unary -) */
170   {"trunc_mod",   "%",          0},             /* old */
171   {"md",          "%",          DMGL_ANSI},     /* ansi */
172   {"amd",         "%=",         DMGL_ANSI},     /* ansi */
173   {"trunc_div",   "/",          0},             /* old */
174   {"dv",          "/",          DMGL_ANSI},     /* ansi */
175   {"adv",         "/=",         DMGL_ANSI},     /* ansi */
176   {"truth_andif", "&&",         0},             /* old */
177   {"aa",          "&&",         DMGL_ANSI},     /* ansi */
178   {"truth_orif",  "||",         0},             /* old */
179   {"oo",          "||",         DMGL_ANSI},     /* ansi */
180   {"truth_not",   "!",          0},             /* old */
181   {"nt",          "!",          DMGL_ANSI},     /* ansi */
182   {"postincrement","++",        0},             /* old */
183   {"pp",          "++",         DMGL_ANSI},     /* ansi */
184   {"postdecrement","--",        0},             /* old */
185   {"mm",          "--",         DMGL_ANSI},     /* ansi */
186   {"bit_ior",     "|",          0},             /* old */
187   {"or",          "|",          DMGL_ANSI},     /* ansi */
188   {"aor",         "|=",         DMGL_ANSI},     /* ansi */
189   {"bit_xor",     "^",          0},             /* old */
190   {"er",          "^",          DMGL_ANSI},     /* ansi */
191   {"aer",         "^=",         DMGL_ANSI},     /* ansi */
192   {"bit_and",     "&",          0},             /* old */
193   {"ad",          "&",          DMGL_ANSI},     /* ansi */
194   {"aad",         "&=",         DMGL_ANSI},     /* ansi */
195   {"bit_not",     "~",          0},             /* old */
196   {"co",          "~",          DMGL_ANSI},     /* ansi */
197   {"call",        "()",         0},             /* old */
198   {"cl",          "()",         DMGL_ANSI},     /* ansi */
199   {"alshift",     "<<",         0},             /* old */
200   {"ls",          "<<",         DMGL_ANSI},     /* ansi */
201   {"als",         "<<=",        DMGL_ANSI},     /* ansi */
202   {"arshift",     ">>",         0},             /* old */
203   {"rs",          ">>",         DMGL_ANSI},     /* ansi */
204   {"ars",         ">>=",        DMGL_ANSI},     /* ansi */
205   {"component",   "->",         0},             /* old */
206   {"pt",          "->",         DMGL_ANSI},     /* ansi; Lucid C++ form */
207   {"rf",          "->",         DMGL_ANSI},     /* ansi; ARM/GNU form */
208   {"indirect",    "*",          0},             /* old */
209   {"method_call",  "->()",      0},             /* old */
210   {"addr",        "&",          0},             /* old (unary &) */
211   {"array",       "[]",         0},             /* old */
212   {"vc",          "[]",         DMGL_ANSI},     /* ansi */
213   {"compound",    ", ",         0},             /* old */
214   {"cm",          ", ",         DMGL_ANSI},     /* ansi */
215   {"cond",        "?:",         0},             /* old */
216   {"cn",          "?:",         DMGL_ANSI},     /* pseudo-ansi */
217   {"max",         ">?",         0},             /* old */
218   {"mx",          ">?",         DMGL_ANSI},     /* pseudo-ansi */
219   {"min",         "<?",         0},             /* old */
220   {"mn",          "<?",         DMGL_ANSI},     /* pseudo-ansi */
221   {"nop",         "",           0},             /* old (for operator=) */
222   {"rm",          "->*",        DMGL_ANSI},     /* ansi */
223   {"sz",          "sizeof ",    DMGL_ANSI}      /* pseudo-ansi */
224 };
225
226 /* These values are used to indicate the various type varieties.
227    They are all non-zero so that they can be used as `success'
228    values.  */
229 typedef enum type_kind_t
230 {
231   tk_none,
232   tk_pointer,
233   tk_reference,
234   tk_integral,
235   tk_bool,
236   tk_char,
237   tk_real
238 } type_kind_t;
239
240 const struct demangler_engine libiberty_demanglers[] =
241 {
242   {
243     NO_DEMANGLING_STYLE_STRING,
244     no_demangling,
245     "Demangling disabled"
246   }
247   ,
248   {
249     AUTO_DEMANGLING_STYLE_STRING,
250       auto_demangling,
251       "Automatic selection based on executable"
252   }
253   ,
254   {
255     GNU_DEMANGLING_STYLE_STRING,
256       gnu_demangling,
257       "GNU (g++) style demangling"
258   }
259   ,
260   {
261     LUCID_DEMANGLING_STYLE_STRING,
262       lucid_demangling,
263       "Lucid (lcc) style demangling"
264   }
265   ,
266   {
267     ARM_DEMANGLING_STYLE_STRING,
268       arm_demangling,
269       "ARM style demangling"
270   }
271   ,
272   {
273     HP_DEMANGLING_STYLE_STRING,
274       hp_demangling,
275       "HP (aCC) style demangling"
276   }
277   ,
278   {
279     EDG_DEMANGLING_STYLE_STRING,
280       edg_demangling,
281       "EDG style demangling"
282   }
283   ,
284   {
285     GNU_V3_DEMANGLING_STYLE_STRING,
286     gnu_v3_demangling,
287     "GNU (g++) V3 ABI-style demangling"
288   }
289   ,
290   {
291     JAVA_DEMANGLING_STYLE_STRING,
292     java_demangling,
293     "Java style demangling"
294   }
295   ,
296   {
297     GNAT_DEMANGLING_STYLE_STRING,
298     gnat_demangling,
299     "GNAT style demangling"
300   }
301   ,
302   {
303     NULL, unknown_demangling, NULL
304   }
305 };
306
307 #define STRING_EMPTY(str)       ((str) -> b == (str) -> p)
308 #define PREPEND_BLANK(str)      {if (!STRING_EMPTY(str)) \
309     string_prepend(str, " ");}
310 #define APPEND_BLANK(str)       {if (!STRING_EMPTY(str)) \
311     string_append(str, " ");}
312 #define LEN_STRING(str)         ( (STRING_EMPTY(str))?0:((str)->p - (str)->b))
313
314 /* The scope separator appropriate for the language being demangled.  */
315
316 #define SCOPE_STRING(work) ((work->options & DMGL_JAVA) ? "." : "::")
317
318 #define ARM_VTABLE_STRING "__vtbl__"    /* Lucid/ARM virtual table prefix */
319 #define ARM_VTABLE_STRLEN 8             /* strlen (ARM_VTABLE_STRING) */
320
321 /* Prototypes for local functions */
322
323 static void
324 delete_work_stuff PARAMS ((struct work_stuff *));
325
326 static void
327 delete_non_B_K_work_stuff PARAMS ((struct work_stuff *));
328
329 static char *
330 mop_up PARAMS ((struct work_stuff *, string *, int));
331
332 static void
333 squangle_mop_up PARAMS ((struct work_stuff *));
334
335 static void
336 work_stuff_copy_to_from PARAMS ((struct work_stuff *, struct work_stuff *));
337
338 #if 0
339 static int
340 demangle_method_args PARAMS ((struct work_stuff *, const char **, string *));
341 #endif
342
343 static char *
344 internal_cplus_demangle PARAMS ((struct work_stuff *, const char *));
345
346 static int
347 demangle_template_template_parm PARAMS ((struct work_stuff *work,
348                                          const char **, string *));
349
350 static int
351 demangle_template PARAMS ((struct work_stuff *work, const char **, string *,
352                            string *, int, int));
353
354 static int
355 arm_pt PARAMS ((struct work_stuff *, const char *, int, const char **,
356                 const char **));
357
358 static int
359 demangle_class_name PARAMS ((struct work_stuff *, const char **, string *));
360
361 static int
362 demangle_qualified PARAMS ((struct work_stuff *, const char **, string *,
363                             int, int));
364
365 static int
366 demangle_class PARAMS ((struct work_stuff *, const char **, string *));
367
368 static int
369 demangle_fund_type PARAMS ((struct work_stuff *, const char **, string *));
370
371 static int
372 demangle_signature PARAMS ((struct work_stuff *, const char **, string *));
373
374 static int
375 demangle_prefix PARAMS ((struct work_stuff *, const char **, string *));
376
377 static int
378 gnu_special PARAMS ((struct work_stuff *, const char **, string *));
379
380 static int
381 arm_special PARAMS ((const char **, string *));
382
383 static void
384 string_need PARAMS ((string *, int));
385
386 static void
387 string_delete PARAMS ((string *));
388
389 static void
390 string_init PARAMS ((string *));
391
392 static void
393 string_clear PARAMS ((string *));
394
395 #if 0
396 static int
397 string_empty PARAMS ((string *));
398 #endif
399
400 static void
401 string_append PARAMS ((string *, const char *));
402
403 static void
404 string_appends PARAMS ((string *, string *));
405
406 static void
407 string_appendn PARAMS ((string *, const char *, int));
408
409 static void
410 string_prepend PARAMS ((string *, const char *));
411
412 static void
413 string_prependn PARAMS ((string *, const char *, int));
414
415 static void
416 string_append_template_idx PARAMS ((string *, int));
417
418 static int
419 get_count PARAMS ((const char **, int *));
420
421 static int
422 consume_count PARAMS ((const char **));
423
424 static int
425 consume_count_with_underscores PARAMS ((const char**));
426
427 static int
428 demangle_args PARAMS ((struct work_stuff *, const char **, string *));
429
430 static int
431 demangle_nested_args PARAMS ((struct work_stuff*, const char**, string*));
432
433 static int
434 do_type PARAMS ((struct work_stuff *, const char **, string *));
435
436 static int
437 do_arg PARAMS ((struct work_stuff *, const char **, string *));
438
439 static void
440 demangle_function_name PARAMS ((struct work_stuff *, const char **, string *,
441                                 const char *));
442
443 static int
444 iterate_demangle_function PARAMS ((struct work_stuff *,
445                                    const char **, string *, const char *));
446
447 static void
448 remember_type PARAMS ((struct work_stuff *, const char *, int));
449
450 static void
451 remember_Btype PARAMS ((struct work_stuff *, const char *, int, int));
452
453 static int
454 register_Btype PARAMS ((struct work_stuff *));
455
456 static void
457 remember_Ktype PARAMS ((struct work_stuff *, const char *, int));
458
459 static void
460 forget_types PARAMS ((struct work_stuff *));
461
462 static void
463 forget_B_and_K_types PARAMS ((struct work_stuff *));
464
465 static void
466 string_prepends PARAMS ((string *, string *));
467
468 static int
469 demangle_template_value_parm PARAMS ((struct work_stuff*, const char**,
470                                       string*, type_kind_t));
471
472 static int
473 do_hpacc_template_const_value PARAMS ((struct work_stuff *, const char **, string *));
474
475 static int
476 do_hpacc_template_literal PARAMS ((struct work_stuff *, const char **, string *));
477
478 static int
479 snarf_numeric_literal PARAMS ((const char **, string *));
480
481 static char* (*cplus_demangle_v3_p) PARAMS ((const char* mangled))
482   = cplus_demangle_v3;
483
484 /* There is a TYPE_QUAL value for each type qualifier.  They can be
485    combined by bitwise-or to form the complete set of qualifiers for a
486    type.  */
487
488 #define TYPE_UNQUALIFIED   0x0
489 #define TYPE_QUAL_CONST    0x1
490 #define TYPE_QUAL_VOLATILE 0x2
491 #define TYPE_QUAL_RESTRICT 0x4
492
493 static int
494 code_for_qualifier PARAMS ((int));
495
496 static const char*
497 qualifier_string PARAMS ((int));
498
499 static const char*
500 demangle_qualifier PARAMS ((int));
501
502 static int
503 demangle_expression PARAMS ((struct work_stuff *, const char **, string *, 
504                              type_kind_t));
505
506 static int
507 demangle_integral_value PARAMS ((struct work_stuff *, const char **,
508                                  string *));
509
510 static int
511 demangle_real_value PARAMS ((struct work_stuff *, const char **, string *));
512
513 static void
514 demangle_arm_hp_template PARAMS ((struct work_stuff *, const char **, int,
515                                   string *));
516
517 static void
518 recursively_demangle PARAMS ((struct work_stuff *, const char **, string *,
519                               int));
520
521 static void
522 grow_vect PARAMS ((void **, size_t *, size_t, int));
523
524 /* Translate count to integer, consuming tokens in the process.
525    Conversion terminates on the first non-digit character.
526
527    Trying to consume something that isn't a count results in no
528    consumption of input and a return of -1.
529
530    Overflow consumes the rest of the digits, and returns -1.  */
531
532 static int
533 consume_count (type)
534      const char **type;
535 {
536   int count = 0;
537
538   if (! ISDIGIT ((unsigned char)**type))
539     return -1;
540
541   while (ISDIGIT ((unsigned char)**type))
542     {
543       count *= 10;
544
545       /* Check for overflow.
546          We assume that count is represented using two's-complement;
547          no power of two is divisible by ten, so if an overflow occurs
548          when multiplying by ten, the result will not be a multiple of
549          ten.  */
550       if ((count % 10) != 0)
551         {
552           while (ISDIGIT ((unsigned char) **type))
553             (*type)++;
554           return -1;
555         }
556
557       count += **type - '0';
558       (*type)++;
559     }
560
561   if (count < 0)
562     count = -1;
563
564   return (count);
565 }
566
567
568 /* Like consume_count, but for counts that are preceded and followed
569    by '_' if they are greater than 10.  Also, -1 is returned for
570    failure, since 0 can be a valid value.  */
571
572 static int
573 consume_count_with_underscores (mangled)
574      const char **mangled;
575 {
576   int idx;
577
578   if (**mangled == '_')
579     {
580       (*mangled)++;
581       if (!ISDIGIT ((unsigned char)**mangled))
582         return -1;
583
584       idx = consume_count (mangled);
585       if (**mangled != '_')
586         /* The trailing underscore was missing. */
587         return -1;
588
589       (*mangled)++;
590     }
591   else
592     {
593       if (**mangled < '0' || **mangled > '9')
594         return -1;
595
596       idx = **mangled - '0';
597       (*mangled)++;
598     }
599
600   return idx;
601 }
602
603 /* C is the code for a type-qualifier.  Return the TYPE_QUAL
604    corresponding to this qualifier.  */
605
606 static int
607 code_for_qualifier (c)
608   int c;
609 {
610   switch (c)
611     {
612     case 'C':
613       return TYPE_QUAL_CONST;
614
615     case 'V':
616       return TYPE_QUAL_VOLATILE;
617
618     case 'u':
619       return TYPE_QUAL_RESTRICT;
620
621     default:
622       break;
623     }
624
625   /* C was an invalid qualifier.  */
626   abort ();
627 }
628
629 /* Return the string corresponding to the qualifiers given by
630    TYPE_QUALS.  */
631
632 static const char*
633 qualifier_string (type_quals)
634      int type_quals;
635 {
636   switch (type_quals)
637     {
638     case TYPE_UNQUALIFIED:
639       return "";
640
641     case TYPE_QUAL_CONST:
642       return "const";
643
644     case TYPE_QUAL_VOLATILE:
645       return "volatile";
646
647     case TYPE_QUAL_RESTRICT:
648       return "__restrict";
649
650     case TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE:
651       return "const volatile";
652
653     case TYPE_QUAL_CONST | TYPE_QUAL_RESTRICT:
654       return "const __restrict";
655
656     case TYPE_QUAL_VOLATILE | TYPE_QUAL_RESTRICT:
657       return "volatile __restrict";
658
659     case TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE | TYPE_QUAL_RESTRICT:
660       return "const volatile __restrict";
661
662     default:
663       break;
664     }
665
666   /* TYPE_QUALS was an invalid qualifier set.  */
667   abort ();
668 }
669
670 /* C is the code for a type-qualifier.  Return the string
671    corresponding to this qualifier.  This function should only be
672    called with a valid qualifier code.  */
673
674 static const char*
675 demangle_qualifier (c)
676   int c;
677 {
678   return qualifier_string (code_for_qualifier (c));
679 }
680
681 int
682 cplus_demangle_opname (opname, result, options)
683      const char *opname;
684      char *result;
685      int options;
686 {
687   int len, len1, ret;
688   string type;
689   struct work_stuff work[1];
690   const char *tem;
691
692   len = strlen(opname);
693   result[0] = '\0';
694   ret = 0;
695   memset ((char *) work, 0, sizeof (work));
696   work->options = options;
697
698   if (opname[0] == '_' && opname[1] == '_'
699       && opname[2] == 'o' && opname[3] == 'p')
700     {
701       /* ANSI.  */
702       /* type conversion operator.  */
703       tem = opname + 4;
704       if (do_type (work, &tem, &type))
705         {
706           strcat (result, "operator ");
707           strncat (result, type.b, type.p - type.b);
708           string_delete (&type);
709           ret = 1;
710         }
711     }
712   else if (opname[0] == '_' && opname[1] == '_'
713            && ISLOWER((unsigned char)opname[2])
714            && ISLOWER((unsigned char)opname[3]))
715     {
716       if (opname[4] == '\0')
717         {
718           /* Operator.  */
719           size_t i;
720           for (i = 0; i < ARRAY_SIZE (optable); i++)
721             {
722               if (strlen (optable[i].in) == 2
723                   && memcmp (optable[i].in, opname + 2, 2) == 0)
724                 {
725                   strcat (result, "operator");
726                   strcat (result, optable[i].out);
727                   ret = 1;
728                   break;
729                 }
730             }
731         }
732       else
733         {
734           if (opname[2] == 'a' && opname[5] == '\0')
735             {
736               /* Assignment.  */
737               size_t i;
738               for (i = 0; i < ARRAY_SIZE (optable); i++)
739                 {
740                   if (strlen (optable[i].in) == 3
741                       && memcmp (optable[i].in, opname + 2, 3) == 0)
742                     {
743                       strcat (result, "operator");
744                       strcat (result, optable[i].out);
745                       ret = 1;
746                       break;
747                     }
748                 }
749             }
750         }
751     }
752   else if (len >= 3
753            && opname[0] == 'o'
754            && opname[1] == 'p'
755            && strchr (cplus_markers, opname[2]) != NULL)
756     {
757       /* see if it's an assignment expression */
758       if (len >= 10 /* op$assign_ */
759           && memcmp (opname + 3, "assign_", 7) == 0)
760         {
761           size_t i;
762           for (i = 0; i < ARRAY_SIZE (optable); i++)
763             {
764               len1 = len - 10;
765               if ((int) strlen (optable[i].in) == len1
766                   && memcmp (optable[i].in, opname + 10, len1) == 0)
767                 {
768                   strcat (result, "operator");
769                   strcat (result, optable[i].out);
770                   strcat (result, "=");
771                   ret = 1;
772                   break;
773                 }
774             }
775         }
776       else
777         {
778           size_t i;
779           for (i = 0; i < ARRAY_SIZE (optable); i++)
780             {
781               len1 = len - 3;
782               if ((int) strlen (optable[i].in) == len1
783                   && memcmp (optable[i].in, opname + 3, len1) == 0)
784                 {
785                   strcat (result, "operator");
786                   strcat (result, optable[i].out);
787                   ret = 1;
788                   break;
789                 }
790             }
791         }
792     }
793   else if (len >= 5 && memcmp (opname, "type", 4) == 0
794            && strchr (cplus_markers, opname[4]) != NULL)
795     {
796       /* type conversion operator */
797       tem = opname + 5;
798       if (do_type (work, &tem, &type))
799         {
800           strcat (result, "operator ");
801           strncat (result, type.b, type.p - type.b);
802           string_delete (&type);
803           ret = 1;
804         }
805     }
806   squangle_mop_up (work);
807   return ret;
808
809 }
810
811 /* Takes operator name as e.g. "++" and returns mangled
812    operator name (e.g. "postincrement_expr"), or NULL if not found.
813
814    If OPTIONS & DMGL_ANSI == 1, return the ANSI name;
815    if OPTIONS & DMGL_ANSI == 0, return the old GNU name.  */
816
817 const char *
818 cplus_mangle_opname (opname, options)
819      const char *opname;
820      int options;
821 {
822   size_t i;
823   int len;
824
825   len = strlen (opname);
826   for (i = 0; i < ARRAY_SIZE (optable); i++)
827     {
828       if ((int) strlen (optable[i].out) == len
829           && (options & DMGL_ANSI) == (optable[i].flags & DMGL_ANSI)
830           && memcmp (optable[i].out, opname, len) == 0)
831         return optable[i].in;
832     }
833   return (0);
834 }
835
836 /* Add a routine to set the demangling style to be sure it is valid and
837    allow for any demangler initialization that maybe necessary. */
838
839 enum demangling_styles
840 cplus_demangle_set_style (style)
841      enum demangling_styles style;
842 {
843   const struct demangler_engine *demangler = libiberty_demanglers; 
844
845   for (; demangler->demangling_style != unknown_demangling; ++demangler)
846     if (style == demangler->demangling_style)
847       {
848         current_demangling_style = style;
849         return current_demangling_style;
850       }
851
852   return unknown_demangling;
853 }
854
855 /* Do string name to style translation */
856
857 enum demangling_styles
858 cplus_demangle_name_to_style (name)
859      const char *name;
860 {
861   const struct demangler_engine *demangler = libiberty_demanglers; 
862
863   for (; demangler->demangling_style != unknown_demangling; ++demangler)
864     if (strcmp (name, demangler->demangling_style_name) == 0)
865       return demangler->demangling_style;
866
867   return unknown_demangling;
868 }
869
870 /* char *cplus_demangle (const char *mangled, int options)
871
872    If MANGLED is a mangled function name produced by GNU C++, then
873    a pointer to a @code{malloc}ed string giving a C++ representation
874    of the name will be returned; otherwise NULL will be returned.
875    It is the caller's responsibility to free the string which
876    is returned.
877
878    The OPTIONS arg may contain one or more of the following bits:
879
880         DMGL_ANSI       ANSI qualifiers such as `const' and `void' are
881                         included.
882         DMGL_PARAMS     Function parameters are included.
883
884    For example,
885
886    cplus_demangle ("foo__1Ai", DMGL_PARAMS)             => "A::foo(int)"
887    cplus_demangle ("foo__1Ai", DMGL_PARAMS | DMGL_ANSI) => "A::foo(int)"
888    cplus_demangle ("foo__1Ai", 0)                       => "A::foo"
889
890    cplus_demangle ("foo__1Afe", DMGL_PARAMS)            => "A::foo(float,...)"
891    cplus_demangle ("foo__1Afe", DMGL_PARAMS | DMGL_ANSI)=> "A::foo(float,...)"
892    cplus_demangle ("foo__1Afe", 0)                      => "A::foo"
893
894    Note that any leading underscores, or other such characters prepended by
895    the compilation system, are presumed to have already been stripped from
896    MANGLED.  */
897
898 char *
899 cplus_demangle (mangled, options)
900      const char *mangled;
901      int options;
902 {
903   char *ret;
904   struct work_stuff work[1];
905
906   if (current_demangling_style == no_demangling)
907     return xstrdup (mangled);
908
909   memset ((char *) work, 0, sizeof (work));
910   work->options = options;
911   if ((work->options & DMGL_STYLE_MASK) == 0)
912     work->options |= (int) current_demangling_style & DMGL_STYLE_MASK;
913
914   /* The V3 ABI demangling is implemented elsewhere.  */
915   if (GNU_V3_DEMANGLING || AUTO_DEMANGLING)
916     {
917       ret = cplus_demangle_v3_p (mangled);
918       if (ret || GNU_V3_DEMANGLING)
919         return ret;
920     }
921
922   if (JAVA_DEMANGLING)
923     {
924       ret = java_demangle_v3 (mangled);
925       if (ret)
926         return ret;
927     }
928
929   if (GNAT_DEMANGLING)
930     return ada_demangle(mangled,options);
931
932   ret = internal_cplus_demangle (work, mangled);
933   squangle_mop_up (work);
934   return (ret);
935 }
936
937
938 /* Assuming *OLD_VECT points to an array of *SIZE objects of size
939    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
940    updating *OLD_VECT and *SIZE as necessary.  */
941
942 static void
943 grow_vect (old_vect, size, min_size, element_size)
944      void **old_vect;
945      size_t *size;
946      size_t min_size;
947      int element_size;
948 {
949   if (*size < min_size)
950     {
951       *size *= 2;
952       if (*size < min_size)
953         *size = min_size;
954       *old_vect = xrealloc (*old_vect, *size * element_size);
955     }
956 }
957
958 /* Demangle ada names:
959    1. Discard final __{DIGIT}+ or ${DIGIT}+
960    2. Convert other instances of embedded "__" to `.'.
961    3. Discard leading _ada_.
962    4. Remove everything after first ___ if it is followed by 'X'.
963    5. Put symbols that should be suppressed in <...> brackets.
964    The resulting string is valid until the next call of ada_demangle.  */
965
966 static char *
967 ada_demangle (mangled, option)
968      const char *mangled;
969      int option ATTRIBUTE_UNUSED;
970 {
971   int i, j;
972   int len0;
973   const char* p;
974   char *demangled = NULL;
975   int at_start_name;
976   int changed;
977   char *demangling_buffer = NULL;
978   size_t demangling_buffer_size = 0;
979   
980   changed = 0;
981
982   if (strncmp (mangled, "_ada_", 5) == 0)
983     {
984       mangled += 5;
985       changed = 1;
986     }
987   
988   if (mangled[0] == '_' || mangled[0] == '<')
989     goto Suppress;
990   
991   p = strstr (mangled, "___");
992   if (p == NULL)
993     len0 = strlen (mangled);
994   else
995     {
996       if (p[3] == 'X')
997         {
998           len0 = p - mangled;
999           changed = 1;
1000         }
1001       else
1002         goto Suppress;
1003     }
1004   
1005   /* Make demangled big enough for possible expansion by operator name.  */
1006   grow_vect ((void **) &(demangling_buffer),
1007              &demangling_buffer_size,  2 * len0 + 1,
1008              sizeof (char));
1009   demangled = demangling_buffer;
1010   
1011   if (ISDIGIT ((unsigned char) mangled[len0 - 1])) {
1012     for (i = len0 - 2; i >= 0 && ISDIGIT ((unsigned char) mangled[i]); i -= 1)
1013       ;
1014     if (i > 1 && mangled[i] == '_' && mangled[i - 1] == '_')
1015       {
1016         len0 = i - 1;
1017         changed = 1;
1018       }
1019     else if (mangled[i] == '$')
1020       {
1021         len0 = i;
1022         changed = 1;
1023       }
1024   }
1025   
1026   for (i = 0, j = 0; i < len0 && ! ISALPHA ((unsigned char)mangled[i]);
1027        i += 1, j += 1)
1028     demangled[j] = mangled[i];
1029   
1030   at_start_name = 1;
1031   while (i < len0)
1032     {
1033       at_start_name = 0;
1034       
1035       if (i < len0 - 2 && mangled[i] == '_' && mangled[i + 1] == '_')
1036         {
1037           demangled[j] = '.';
1038           changed = at_start_name = 1;
1039           i += 2; j += 1;
1040         }
1041       else
1042         {
1043           demangled[j] = mangled[i];
1044           i += 1;  j += 1;
1045         }
1046     }
1047   demangled[j] = '\000';
1048   
1049   for (i = 0; demangled[i] != '\0'; i += 1)
1050     if (ISUPPER ((unsigned char)demangled[i]) || demangled[i] == ' ')
1051       goto Suppress;
1052
1053   if (! changed)
1054     return NULL;
1055   else
1056     return demangled;
1057   
1058  Suppress:
1059   grow_vect ((void **) &(demangling_buffer),
1060              &demangling_buffer_size,  strlen (mangled) + 3,
1061              sizeof (char));
1062   demangled = demangling_buffer;
1063   if (mangled[0] == '<')
1064      strcpy (demangled, mangled);
1065   else
1066     sprintf (demangled, "<%s>", mangled);
1067
1068   return demangled;
1069 }
1070
1071 /* This function performs most of what cplus_demangle use to do, but
1072    to be able to demangle a name with a B, K or n code, we need to
1073    have a longer term memory of what types have been seen. The original
1074    now intializes and cleans up the squangle code info, while internal
1075    calls go directly to this routine to avoid resetting that info. */
1076
1077 static char *
1078 internal_cplus_demangle (work, mangled)
1079      struct work_stuff *work;
1080      const char *mangled;
1081 {
1082
1083   string decl;
1084   int success = 0;
1085   char *demangled = NULL;
1086   int s1, s2, s3, s4;
1087   s1 = work->constructor;
1088   s2 = work->destructor;
1089   s3 = work->static_type;
1090   s4 = work->type_quals;
1091   work->constructor = work->destructor = 0;
1092   work->type_quals = TYPE_UNQUALIFIED;
1093   work->dllimported = 0;
1094
1095   if ((mangled != NULL) && (*mangled != '\0'))
1096     {
1097       string_init (&decl);
1098
1099       /* First check to see if gnu style demangling is active and if the
1100          string to be demangled contains a CPLUS_MARKER.  If so, attempt to
1101          recognize one of the gnu special forms rather than looking for a
1102          standard prefix.  In particular, don't worry about whether there
1103          is a "__" string in the mangled string.  Consider "_$_5__foo" for
1104          example.  */
1105
1106       if ((AUTO_DEMANGLING || GNU_DEMANGLING))
1107         {
1108           success = gnu_special (work, &mangled, &decl);
1109         }
1110       if (!success)
1111         {
1112           success = demangle_prefix (work, &mangled, &decl);
1113         }
1114       if (success && (*mangled != '\0'))
1115         {
1116           success = demangle_signature (work, &mangled, &decl);
1117         }
1118       if (work->constructor == 2)
1119         {
1120           string_prepend (&decl, "global constructors keyed to ");
1121           work->constructor = 0;
1122         }
1123       else if (work->destructor == 2)
1124         {
1125           string_prepend (&decl, "global destructors keyed to ");
1126           work->destructor = 0;
1127         }
1128       else if (work->dllimported == 1)
1129         {
1130           string_prepend (&decl, "import stub for ");
1131           work->dllimported = 0;
1132         }
1133       demangled = mop_up (work, &decl, success);
1134     }
1135   work->constructor = s1;
1136   work->destructor = s2;
1137   work->static_type = s3;
1138   work->type_quals = s4;
1139   return demangled;
1140 }
1141
1142
1143 /* Clear out and squangling related storage */
1144 static void
1145 squangle_mop_up (work)
1146      struct work_stuff *work;
1147 {
1148   /* clean up the B and K type mangling types. */
1149   forget_B_and_K_types (work);
1150   if (work -> btypevec != NULL)
1151     {
1152       free ((char *) work -> btypevec);
1153     }
1154   if (work -> ktypevec != NULL)
1155     {
1156       free ((char *) work -> ktypevec);
1157     }
1158 }
1159
1160
1161 /* Copy the work state and storage.  */
1162
1163 static void
1164 work_stuff_copy_to_from (to, from)
1165      struct work_stuff *to;
1166      struct work_stuff *from;
1167 {
1168   int i;
1169
1170   delete_work_stuff (to);
1171
1172   /* Shallow-copy scalars.  */
1173   memcpy (to, from, sizeof (*to));
1174
1175   /* Deep-copy dynamic storage.  */
1176   if (from->typevec_size)
1177     to->typevec
1178       = (char **) xmalloc (from->typevec_size * sizeof (to->typevec[0]));
1179
1180   for (i = 0; i < from->ntypes; i++)
1181     {
1182       int len = strlen (from->typevec[i]) + 1;
1183
1184       to->typevec[i] = xmalloc (len);
1185       memcpy (to->typevec[i], from->typevec[i], len);
1186     }
1187
1188   if (from->ksize)
1189     to->ktypevec
1190       = (char **) xmalloc (from->ksize * sizeof (to->ktypevec[0]));
1191
1192   for (i = 0; i < from->numk; i++)
1193     {
1194       int len = strlen (from->ktypevec[i]) + 1;
1195
1196       to->ktypevec[i] = xmalloc (len);
1197       memcpy (to->ktypevec[i], from->ktypevec[i], len);
1198     }
1199
1200   if (from->bsize)
1201     to->btypevec
1202       = (char **) xmalloc (from->bsize * sizeof (to->btypevec[0]));
1203
1204   for (i = 0; i < from->numb; i++)
1205     {
1206       int len = strlen (from->btypevec[i]) + 1;
1207
1208       to->btypevec[i] = xmalloc (len);
1209       memcpy (to->btypevec[i], from->btypevec[i], len);
1210     }
1211
1212   if (from->ntmpl_args)
1213     to->tmpl_argvec
1214       = xmalloc (from->ntmpl_args * sizeof (to->tmpl_argvec[0]));
1215
1216   for (i = 0; i < from->ntmpl_args; i++)
1217     {
1218       int len = strlen (from->tmpl_argvec[i]) + 1;
1219
1220       to->tmpl_argvec[i] = xmalloc (len);
1221       memcpy (to->tmpl_argvec[i], from->tmpl_argvec[i], len);
1222     }
1223
1224   if (from->previous_argument)
1225     {
1226       to->previous_argument = (string*) xmalloc (sizeof (string));
1227       string_init (to->previous_argument);
1228       string_appends (to->previous_argument, from->previous_argument);
1229     }
1230 }
1231
1232
1233 /* Delete dynamic stuff in work_stuff that is not to be re-used.  */
1234
1235 static void
1236 delete_non_B_K_work_stuff (work)
1237      struct work_stuff *work;
1238 {
1239   /* Discard the remembered types, if any.  */
1240
1241   forget_types (work);
1242   if (work -> typevec != NULL)
1243     {
1244       free ((char *) work -> typevec);
1245       work -> typevec = NULL;
1246       work -> typevec_size = 0;
1247     }
1248   if (work->tmpl_argvec)
1249     {
1250       int i;
1251
1252       for (i = 0; i < work->ntmpl_args; i++)
1253         if (work->tmpl_argvec[i])
1254           free ((char*) work->tmpl_argvec[i]);
1255
1256       free ((char*) work->tmpl_argvec);
1257       work->tmpl_argvec = NULL;
1258     }
1259   if (work->previous_argument)
1260     {
1261       string_delete (work->previous_argument);
1262       free ((char*) work->previous_argument);
1263       work->previous_argument = NULL;
1264     }
1265 }
1266
1267
1268 /* Delete all dynamic storage in work_stuff.  */
1269 static void
1270 delete_work_stuff (work)
1271      struct work_stuff *work;
1272 {
1273   delete_non_B_K_work_stuff (work);
1274   squangle_mop_up (work);
1275 }
1276
1277
1278 /* Clear out any mangled storage */
1279
1280 static char *
1281 mop_up (work, declp, success)
1282      struct work_stuff *work;
1283      string *declp;
1284      int success;
1285 {
1286   char *demangled = NULL;
1287
1288   delete_non_B_K_work_stuff (work);
1289
1290   /* If demangling was successful, ensure that the demangled string is null
1291      terminated and return it.  Otherwise, free the demangling decl.  */
1292
1293   if (!success)
1294     {
1295       string_delete (declp);
1296     }
1297   else
1298     {
1299       string_appendn (declp, "", 1);
1300       demangled = declp->b;
1301     }
1302   return (demangled);
1303 }
1304
1305 /*
1306
1307 LOCAL FUNCTION
1308
1309         demangle_signature -- demangle the signature part of a mangled name
1310
1311 SYNOPSIS
1312
1313         static int
1314         demangle_signature (struct work_stuff *work, const char **mangled,
1315                             string *declp);
1316
1317 DESCRIPTION
1318
1319         Consume and demangle the signature portion of the mangled name.
1320
1321         DECLP is the string where demangled output is being built.  At
1322         entry it contains the demangled root name from the mangled name
1323         prefix.  I.E. either a demangled operator name or the root function
1324         name.  In some special cases, it may contain nothing.
1325
1326         *MANGLED points to the current unconsumed location in the mangled
1327         name.  As tokens are consumed and demangling is performed, the
1328         pointer is updated to continuously point at the next token to
1329         be consumed.
1330
1331         Demangling GNU style mangled names is nasty because there is no
1332         explicit token that marks the start of the outermost function
1333         argument list.  */
1334
1335 static int
1336 demangle_signature (work, mangled, declp)
1337      struct work_stuff *work;
1338      const char **mangled;
1339      string *declp;
1340 {
1341   int success = 1;
1342   int func_done = 0;
1343   int expect_func = 0;
1344   int expect_return_type = 0;
1345   const char *oldmangled = NULL;
1346   string trawname;
1347   string tname;
1348
1349   while (success && (**mangled != '\0'))
1350     {
1351       switch (**mangled)
1352         {
1353         case 'Q':
1354           oldmangled = *mangled;
1355           success = demangle_qualified (work, mangled, declp, 1, 0);
1356           if (success)
1357             remember_type (work, oldmangled, *mangled - oldmangled);
1358           if (AUTO_DEMANGLING || GNU_DEMANGLING)
1359             expect_func = 1;
1360           oldmangled = NULL;
1361           break;
1362
1363         case 'K':
1364           oldmangled = *mangled;
1365           success = demangle_qualified (work, mangled, declp, 1, 0);
1366           if (AUTO_DEMANGLING || GNU_DEMANGLING)
1367             {
1368               expect_func = 1;
1369             }
1370           oldmangled = NULL;
1371           break;
1372
1373         case 'S':
1374           /* Static member function */
1375           if (oldmangled == NULL)
1376             {
1377               oldmangled = *mangled;
1378             }
1379           (*mangled)++;
1380           work -> static_type = 1;
1381           break;
1382
1383         case 'C':
1384         case 'V':
1385         case 'u':
1386           work->type_quals |= code_for_qualifier (**mangled);
1387
1388           /* a qualified member function */
1389           if (oldmangled == NULL)
1390             oldmangled = *mangled;
1391           (*mangled)++;
1392           break;
1393
1394         case 'L':
1395           /* Local class name follows after "Lnnn_" */
1396           if (HP_DEMANGLING)
1397             {
1398               while (**mangled && (**mangled != '_'))
1399                 (*mangled)++;
1400               if (!**mangled)
1401                 success = 0;
1402               else
1403                 (*mangled)++;
1404             }
1405           else
1406             success = 0;
1407           break;
1408
1409         case '0': case '1': case '2': case '3': case '4':
1410         case '5': case '6': case '7': case '8': case '9':
1411           if (oldmangled == NULL)
1412             {
1413               oldmangled = *mangled;
1414             }
1415           work->temp_start = -1; /* uppermost call to demangle_class */
1416           success = demangle_class (work, mangled, declp);
1417           if (success)
1418             {
1419               remember_type (work, oldmangled, *mangled - oldmangled);
1420             }
1421           if (AUTO_DEMANGLING || GNU_DEMANGLING || EDG_DEMANGLING)
1422             {
1423               /* EDG and others will have the "F", so we let the loop cycle
1424                  if we are looking at one. */
1425               if (**mangled != 'F')
1426                  expect_func = 1;
1427             }
1428           oldmangled = NULL;
1429           break;
1430
1431         case 'B':
1432           {
1433             string s;
1434             success = do_type (work, mangled, &s);
1435             if (success)
1436               {
1437                 string_append (&s, SCOPE_STRING (work));
1438                 string_prepends (declp, &s);
1439               }
1440             oldmangled = NULL;
1441             expect_func = 1;
1442           }
1443           break;
1444
1445         case 'F':
1446           /* Function */
1447           /* ARM/HP style demangling includes a specific 'F' character after
1448              the class name.  For GNU style, it is just implied.  So we can
1449              safely just consume any 'F' at this point and be compatible
1450              with either style.  */
1451
1452           oldmangled = NULL;
1453           func_done = 1;
1454           (*mangled)++;
1455
1456           /* For lucid/ARM/HP style we have to forget any types we might
1457              have remembered up to this point, since they were not argument
1458              types.  GNU style considers all types seen as available for
1459              back references.  See comment in demangle_args() */
1460
1461           if (LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING)
1462             {
1463               forget_types (work);
1464             }
1465           success = demangle_args (work, mangled, declp);
1466           /* After picking off the function args, we expect to either
1467              find the function return type (preceded by an '_') or the
1468              end of the string. */
1469           if (success && (AUTO_DEMANGLING || EDG_DEMANGLING) && **mangled == '_')
1470             {
1471               ++(*mangled);
1472               /* At this level, we do not care about the return type. */
1473               success = do_type (work, mangled, &tname);
1474               string_delete (&tname);
1475             }
1476
1477           break;
1478
1479         case 't':
1480           /* G++ Template */
1481           string_init(&trawname);
1482           string_init(&tname);
1483           if (oldmangled == NULL)
1484             {
1485               oldmangled = *mangled;
1486             }
1487           success = demangle_template (work, mangled, &tname,
1488                                        &trawname, 1, 1);
1489           if (success)
1490             {
1491               remember_type (work, oldmangled, *mangled - oldmangled);
1492             }
1493           string_append (&tname, SCOPE_STRING (work));
1494
1495           string_prepends(declp, &tname);
1496           if (work -> destructor & 1)
1497             {
1498               string_prepend (&trawname, "~");
1499               string_appends (declp, &trawname);
1500               work->destructor -= 1;
1501             }
1502           if ((work->constructor & 1) || (work->destructor & 1))
1503             {
1504               string_appends (declp, &trawname);
1505               work->constructor -= 1;
1506             }
1507           string_delete(&trawname);
1508           string_delete(&tname);
1509           oldmangled = NULL;
1510           expect_func = 1;
1511           break;
1512
1513         case '_':
1514           if ((AUTO_DEMANGLING || GNU_DEMANGLING) && expect_return_type)
1515             {
1516               /* Read the return type. */
1517               string return_type;
1518               string_init (&return_type);
1519
1520               (*mangled)++;
1521               success = do_type (work, mangled, &return_type);
1522               APPEND_BLANK (&return_type);
1523
1524               string_prepends (declp, &return_type);
1525               string_delete (&return_type);
1526               break;
1527             }
1528           else
1529             /* At the outermost level, we cannot have a return type specified,
1530                so if we run into another '_' at this point we are dealing with
1531                a mangled name that is either bogus, or has been mangled by
1532                some algorithm we don't know how to deal with.  So just
1533                reject the entire demangling.  */
1534             /* However, "_nnn" is an expected suffix for alternate entry point
1535                numbered nnn for a function, with HP aCC, so skip over that
1536                without reporting failure. pai/1997-09-04 */
1537             if (HP_DEMANGLING)
1538               {
1539                 (*mangled)++;
1540                 while (**mangled && ISDIGIT ((unsigned char)**mangled))
1541                   (*mangled)++;
1542               }
1543             else
1544               success = 0;
1545           break;
1546
1547         case 'H':
1548           if (AUTO_DEMANGLING || GNU_DEMANGLING)
1549             {
1550               /* A G++ template function.  Read the template arguments. */
1551               success = demangle_template (work, mangled, declp, 0, 0,
1552                                            0);
1553               if (!(work->constructor & 1))
1554                 expect_return_type = 1;
1555               (*mangled)++;
1556               break;
1557             }
1558           else
1559             /* fall through */
1560             {;}
1561
1562         default:
1563           if (AUTO_DEMANGLING || GNU_DEMANGLING)
1564             {
1565               /* Assume we have stumbled onto the first outermost function
1566                  argument token, and start processing args.  */
1567               func_done = 1;
1568               success = demangle_args (work, mangled, declp);
1569             }
1570           else
1571             {
1572               /* Non-GNU demanglers use a specific token to mark the start
1573                  of the outermost function argument tokens.  Typically 'F',
1574                  for ARM/HP-demangling, for example.  So if we find something
1575                  we are not prepared for, it must be an error.  */
1576               success = 0;
1577             }
1578           break;
1579         }
1580       /*
1581         if (AUTO_DEMANGLING || GNU_DEMANGLING)
1582         */
1583       {
1584         if (success && expect_func)
1585           {
1586             func_done = 1;
1587               if (LUCID_DEMANGLING || ARM_DEMANGLING || EDG_DEMANGLING)
1588                 {
1589                   forget_types (work);
1590                 }
1591             success = demangle_args (work, mangled, declp);
1592             /* Since template include the mangling of their return types,
1593                we must set expect_func to 0 so that we don't try do
1594                demangle more arguments the next time we get here.  */
1595             expect_func = 0;
1596           }
1597       }
1598     }
1599   if (success && !func_done)
1600     {
1601       if (AUTO_DEMANGLING || GNU_DEMANGLING)
1602         {
1603           /* With GNU style demangling, bar__3foo is 'foo::bar(void)', and
1604              bar__3fooi is 'foo::bar(int)'.  We get here when we find the
1605              first case, and need to ensure that the '(void)' gets added to
1606              the current declp.  Note that with ARM/HP, the first case
1607              represents the name of a static data member 'foo::bar',
1608              which is in the current declp, so we leave it alone.  */
1609           success = demangle_args (work, mangled, declp);
1610         }
1611     }
1612   if (success && PRINT_ARG_TYPES)
1613     {
1614       if (work->static_type)
1615         string_append (declp, " static");
1616       if (work->type_quals != TYPE_UNQUALIFIED)
1617         {
1618           APPEND_BLANK (declp);
1619           string_append (declp, qualifier_string (work->type_quals));
1620         }
1621     }
1622
1623   return (success);
1624 }
1625
1626 #if 0
1627
1628 static int
1629 demangle_method_args (work, mangled, declp)
1630      struct work_stuff *work;
1631      const char **mangled;
1632      string *declp;
1633 {
1634   int success = 0;
1635
1636   if (work -> static_type)
1637     {
1638       string_append (declp, *mangled + 1);
1639       *mangled += strlen (*mangled);
1640       success = 1;
1641     }
1642   else
1643     {
1644       success = demangle_args (work, mangled, declp);
1645     }
1646   return (success);
1647 }
1648
1649 #endif
1650
1651 static int
1652 demangle_template_template_parm (work, mangled, tname)
1653      struct work_stuff *work;
1654      const char **mangled;
1655      string *tname;
1656 {
1657   int i;
1658   int r;
1659   int need_comma = 0;
1660   int success = 1;
1661   string temp;
1662
1663   string_append (tname, "template <");
1664   /* get size of template parameter list */
1665   if (get_count (mangled, &r))
1666     {
1667       for (i = 0; i < r; i++)
1668         {
1669           if (need_comma)
1670             {
1671               string_append (tname, ", ");
1672             }
1673
1674             /* Z for type parameters */
1675             if (**mangled == 'Z')
1676               {
1677                 (*mangled)++;
1678                 string_append (tname, "class");
1679               }
1680               /* z for template parameters */
1681             else if (**mangled == 'z')
1682               {
1683                 (*mangled)++;
1684                 success =
1685                   demangle_template_template_parm (work, mangled, tname);
1686                 if (!success)
1687                   {
1688                     break;
1689                   }
1690               }
1691             else
1692               {
1693                 /* temp is initialized in do_type */
1694                 success = do_type (work, mangled, &temp);
1695                 if (success)
1696                   {
1697                     string_appends (tname, &temp);
1698                   }
1699                 string_delete(&temp);
1700                 if (!success)
1701                   {
1702                     break;
1703                   }
1704               }
1705           need_comma = 1;
1706         }
1707
1708     }
1709   if (tname->p[-1] == '>')
1710     string_append (tname, " ");
1711   string_append (tname, "> class");
1712   return (success);
1713 }
1714
1715 static int
1716 demangle_expression (work, mangled, s, tk)
1717      struct work_stuff *work;
1718      const char** mangled;
1719      string* s;
1720      type_kind_t tk;
1721 {
1722   int need_operator = 0;
1723   int success;
1724
1725   success = 1;
1726   string_appendn (s, "(", 1);
1727   (*mangled)++;
1728   while (success && **mangled != 'W' && **mangled != '\0')
1729     {
1730       if (need_operator)
1731         {
1732           size_t i;
1733           size_t len;
1734
1735           success = 0;
1736
1737           len = strlen (*mangled);
1738
1739           for (i = 0; i < ARRAY_SIZE (optable); ++i)
1740             {
1741               size_t l = strlen (optable[i].in);
1742
1743               if (l <= len
1744                   && memcmp (optable[i].in, *mangled, l) == 0)
1745                 {
1746                   string_appendn (s, " ", 1);
1747                   string_append (s, optable[i].out);
1748                   string_appendn (s, " ", 1);
1749                   success = 1;
1750                   (*mangled) += l;
1751                   break;
1752                 }
1753             }
1754
1755           if (!success)
1756             break;
1757         }
1758       else
1759         need_operator = 1;
1760
1761       success = demangle_template_value_parm (work, mangled, s, tk);
1762     }
1763
1764   if (**mangled != 'W')
1765     success = 0;
1766   else
1767     {
1768       string_appendn (s, ")", 1);
1769       (*mangled)++;
1770     }
1771
1772   return success;
1773 }
1774
1775 static int
1776 demangle_integral_value (work, mangled, s)
1777      struct work_stuff *work;
1778      const char** mangled;
1779      string* s;
1780 {
1781   int success;
1782
1783   if (**mangled == 'E')
1784     success = demangle_expression (work, mangled, s, tk_integral);
1785   else if (**mangled == 'Q' || **mangled == 'K')
1786     success = demangle_qualified (work, mangled, s, 0, 1);
1787   else
1788     {
1789       int value;
1790
1791       /* By default, we let the number decide whether we shall consume an
1792          underscore.  */
1793       int consume_following_underscore = 0;
1794       int leave_following_underscore = 0;
1795
1796       success = 0;
1797
1798       /* Negative numbers are indicated with a leading `m'.  */
1799       if (**mangled == 'm')
1800         {
1801           string_appendn (s, "-", 1);
1802           (*mangled)++;
1803         }
1804       else if (mangled[0][0] == '_' && mangled[0][1] == 'm')
1805         {
1806           /* Since consume_count_with_underscores does not handle the
1807              `m'-prefix we must do it here, using consume_count and
1808              adjusting underscores: we have to consume the underscore
1809              matching the prepended one.  */
1810           consume_following_underscore = 1;
1811           string_appendn (s, "-", 1);
1812           (*mangled) += 2;
1813         }
1814       else if (**mangled == '_')
1815         {
1816           /* Do not consume a following underscore;
1817              consume_following_underscore will consume what should be
1818              consumed.  */
1819           leave_following_underscore = 1;
1820         }
1821
1822       /* We must call consume_count if we expect to remove a trailing
1823          underscore, since consume_count_with_underscores expects
1824          the leading underscore (that we consumed) if it is to handle
1825          multi-digit numbers.  */
1826       if (consume_following_underscore)
1827         value = consume_count (mangled);
1828       else
1829         value = consume_count_with_underscores (mangled);
1830
1831       if (value != -1)
1832         {
1833           char buf[INTBUF_SIZE];
1834           sprintf (buf, "%d", value);
1835           string_append (s, buf);
1836
1837           /* Numbers not otherwise delimited, might have an underscore
1838              appended as a delimeter, which we should skip.
1839
1840              ??? This used to always remove a following underscore, which
1841              is wrong.  If other (arbitrary) cases are followed by an
1842              underscore, we need to do something more radical.  */
1843
1844           if ((value > 9 || consume_following_underscore)
1845               && ! leave_following_underscore
1846               && **mangled == '_')
1847             (*mangled)++;
1848
1849           /* All is well.  */
1850           success = 1;
1851         }
1852     }
1853
1854   return success;
1855 }
1856
1857 /* Demangle the real value in MANGLED.  */
1858
1859 static int
1860 demangle_real_value (work, mangled, s)
1861      struct work_stuff *work;
1862      const char **mangled;
1863      string* s;
1864 {
1865   if (**mangled == 'E')
1866     return demangle_expression (work, mangled, s, tk_real);
1867
1868   if (**mangled == 'm')
1869     {
1870       string_appendn (s, "-", 1);
1871       (*mangled)++;
1872     }
1873   while (ISDIGIT ((unsigned char)**mangled))
1874     {
1875       string_appendn (s, *mangled, 1);
1876       (*mangled)++;
1877     }
1878   if (**mangled == '.') /* fraction */
1879     {
1880       string_appendn (s, ".", 1);
1881       (*mangled)++;
1882       while (ISDIGIT ((unsigned char)**mangled))
1883         {
1884           string_appendn (s, *mangled, 1);
1885           (*mangled)++;
1886         }
1887     }
1888   if (**mangled == 'e') /* exponent */
1889     {
1890       string_appendn (s, "e", 1);
1891       (*mangled)++;
1892       while (ISDIGIT ((unsigned char)**mangled))
1893         {
1894           string_appendn (s, *mangled, 1);
1895           (*mangled)++;
1896         }
1897     }
1898
1899   return 1;
1900 }
1901
1902 static int
1903 demangle_template_value_parm (work, mangled, s, tk)
1904      struct work_stuff *work;
1905      const char **mangled;
1906      string* s;
1907      type_kind_t tk;
1908 {
1909   int success = 1;
1910
1911   if (**mangled == 'Y')
1912     {
1913       /* The next argument is a template parameter. */
1914       int idx;
1915
1916       (*mangled)++;
1917       idx = consume_count_with_underscores (mangled);
1918       if (idx == -1
1919           || (work->tmpl_argvec && idx >= work->ntmpl_args)
1920           || consume_count_with_underscores (mangled) == -1)
1921         return -1;
1922       if (work->tmpl_argvec)
1923         string_append (s, work->tmpl_argvec[idx]);
1924       else
1925         string_append_template_idx (s, idx);
1926     }
1927   else if (tk == tk_integral)
1928     success = demangle_integral_value (work, mangled, s);
1929   else if (tk == tk_char)
1930     {
1931       char tmp[2];
1932       int val;
1933       if (**mangled == 'm')
1934         {
1935           string_appendn (s, "-", 1);
1936           (*mangled)++;
1937         }
1938       string_appendn (s, "'", 1);
1939       val = consume_count(mangled);
1940       if (val <= 0)
1941         success = 0;
1942       else
1943         {
1944           tmp[0] = (char)val;
1945           tmp[1] = '\0';
1946           string_appendn (s, &tmp[0], 1);
1947           string_appendn (s, "'", 1);
1948         }
1949     }
1950   else if (tk == tk_bool)
1951     {
1952       int val = consume_count (mangled);
1953       if (val == 0)
1954         string_appendn (s, "false", 5);
1955       else if (val == 1)
1956         string_appendn (s, "true", 4);
1957       else
1958         success = 0;
1959     }
1960   else if (tk == tk_real)
1961     success = demangle_real_value (work, mangled, s);
1962   else if (tk == tk_pointer || tk == tk_reference)
1963     {
1964       if (**mangled == 'Q')
1965         success = demangle_qualified (work, mangled, s,
1966                                       /*isfuncname=*/0, 
1967                                       /*append=*/1);
1968       else
1969         {
1970           int symbol_len  = consume_count (mangled);
1971           if (symbol_len == -1)
1972             return -1;
1973           if (symbol_len == 0)
1974             string_appendn (s, "0", 1);
1975           else
1976             {
1977               char *p = xmalloc (symbol_len + 1), *q;
1978               strncpy (p, *mangled, symbol_len);
1979               p [symbol_len] = '\0';
1980               /* We use cplus_demangle here, rather than
1981                  internal_cplus_demangle, because the name of the entity
1982                  mangled here does not make use of any of the squangling
1983                  or type-code information we have built up thus far; it is
1984                  mangled independently.  */
1985               q = cplus_demangle (p, work->options);
1986               if (tk == tk_pointer)
1987                 string_appendn (s, "&", 1);
1988               /* FIXME: Pointer-to-member constants should get a
1989                  qualifying class name here.  */
1990               if (q)
1991                 {
1992                   string_append (s, q);
1993                   free (q);
1994                 }
1995               else
1996                 string_append (s, p);
1997               free (p);
1998             }
1999           *mangled += symbol_len;
2000         }
2001     }
2002
2003   return success;
2004 }
2005
2006 /* Demangle the template name in MANGLED.  The full name of the
2007    template (e.g., S<int>) is placed in TNAME.  The name without the
2008    template parameters (e.g. S) is placed in TRAWNAME if TRAWNAME is
2009    non-NULL.  If IS_TYPE is nonzero, this template is a type template,
2010    not a function template.  If both IS_TYPE and REMEMBER are nonzero,
2011    the template is remembered in the list of back-referenceable
2012    types.  */
2013
2014 static int
2015 demangle_template (work, mangled, tname, trawname, is_type, remember)
2016      struct work_stuff *work;
2017      const char **mangled;
2018      string *tname;
2019      string *trawname;
2020      int is_type;
2021      int remember;
2022 {
2023   int i;
2024   int r;
2025   int need_comma = 0;
2026   int success = 0;
2027   const char *start;
2028   int is_java_array = 0;
2029   string temp;
2030   int bindex = 0;
2031
2032   (*mangled)++;
2033   if (is_type)
2034     {
2035       if (remember)
2036         bindex = register_Btype (work);
2037       start = *mangled;
2038       /* get template name */
2039       if (**mangled == 'z')
2040         {
2041           int idx;
2042           (*mangled)++;
2043           (*mangled)++;
2044
2045           idx = consume_count_with_underscores (mangled);
2046           if (idx == -1
2047               || (work->tmpl_argvec && idx >= work->ntmpl_args)
2048               || consume_count_with_underscores (mangled) == -1)
2049             return (0);
2050
2051           if (work->tmpl_argvec)
2052             {
2053               string_append (tname, work->tmpl_argvec[idx]);
2054               if (trawname)
2055                 string_append (trawname, work->tmpl_argvec[idx]);
2056             }
2057           else
2058             {
2059               string_append_template_idx (tname, idx);
2060               if (trawname)
2061                 string_append_template_idx (trawname, idx);
2062             }
2063         }
2064       else
2065         {
2066           if ((r = consume_count (mangled)) <= 0
2067               || (int) strlen (*mangled) < r)
2068             {
2069               return (0);
2070             }
2071           is_java_array = (work -> options & DMGL_JAVA)
2072             && strncmp (*mangled, "JArray1Z", 8) == 0;
2073           if (! is_java_array)
2074             {
2075               string_appendn (tname, *mangled, r);
2076             }
2077           if (trawname)
2078             string_appendn (trawname, *mangled, r);
2079           *mangled += r;
2080         }
2081     }
2082   if (!is_java_array)
2083     string_append (tname, "<");
2084   /* get size of template parameter list */
2085   if (!get_count (mangled, &r))
2086     {
2087       return (0);
2088     }
2089   if (!is_type)
2090     {
2091       /* Create an array for saving the template argument values. */
2092       work->tmpl_argvec = (char**) xmalloc (r * sizeof (char *));
2093       work->ntmpl_args = r;
2094       for (i = 0; i < r; i++)
2095         work->tmpl_argvec[i] = 0;
2096     }
2097   for (i = 0; i < r; i++)
2098     {
2099       if (need_comma)
2100         {
2101           string_append (tname, ", ");
2102         }
2103       /* Z for type parameters */
2104       if (**mangled == 'Z')
2105         {
2106           (*mangled)++;
2107           /* temp is initialized in do_type */
2108           success = do_type (work, mangled, &temp);
2109           if (success)
2110             {
2111               string_appends (tname, &temp);
2112
2113               if (!is_type)
2114                 {
2115                   /* Save the template argument. */
2116                   int len = temp.p - temp.b;
2117                   work->tmpl_argvec[i] = xmalloc (len + 1);
2118                   memcpy (work->tmpl_argvec[i], temp.b, len);
2119                   work->tmpl_argvec[i][len] = '\0';
2120                 }
2121             }
2122           string_delete(&temp);
2123           if (!success)
2124             {
2125               break;
2126             }
2127         }
2128       /* z for template parameters */
2129       else if (**mangled == 'z')
2130         {
2131           int r2;
2132           (*mangled)++;
2133           success = demangle_template_template_parm (work, mangled, tname);
2134
2135           if (success
2136               && (r2 = consume_count (mangled)) > 0
2137               && (int) strlen (*mangled) >= r2)
2138             {
2139               string_append (tname, " ");
2140               string_appendn (tname, *mangled, r2);
2141               if (!is_type)
2142                 {
2143                   /* Save the template argument. */
2144                   int len = r2;
2145                   work->tmpl_argvec[i] = xmalloc (len + 1);
2146                   memcpy (work->tmpl_argvec[i], *mangled, len);
2147                   work->tmpl_argvec[i][len] = '\0';
2148                 }
2149               *mangled += r2;
2150             }
2151           if (!success)
2152             {
2153               break;
2154             }
2155         }
2156       else
2157         {
2158           string  param;
2159           string* s;
2160
2161           /* otherwise, value parameter */
2162
2163           /* temp is initialized in do_type */
2164           success = do_type (work, mangled, &temp);
2165           string_delete(&temp);
2166           if (!success)
2167             break;
2168
2169           if (!is_type)
2170             {
2171               s = &param;
2172               string_init (s);
2173             }
2174           else
2175             s = tname;
2176
2177           success = demangle_template_value_parm (work, mangled, s,
2178                                                   (type_kind_t) success);
2179
2180           if (!success)
2181             {
2182               if (!is_type)
2183                 string_delete (s);
2184               success = 0;
2185               break;
2186             }
2187
2188           if (!is_type)
2189             {
2190               int len = s->p - s->b;
2191               work->tmpl_argvec[i] = xmalloc (len + 1);
2192               memcpy (work->tmpl_argvec[i], s->b, len);
2193               work->tmpl_argvec[i][len] = '\0';
2194
2195               string_appends (tname, s);
2196               string_delete (s);
2197             }
2198         }
2199       need_comma = 1;
2200     }
2201   if (is_java_array)
2202     {
2203       string_append (tname, "[]");
2204     }
2205   else
2206     {
2207       if (tname->p[-1] == '>')
2208         string_append (tname, " ");
2209       string_append (tname, ">");
2210     }
2211
2212   if (is_type && remember)
2213     remember_Btype (work, tname->b, LEN_STRING (tname), bindex);
2214
2215   /*
2216     if (work -> static_type)
2217     {
2218     string_append (declp, *mangled + 1);
2219     *mangled += strlen (*mangled);
2220     success = 1;
2221     }
2222     else
2223     {
2224     success = demangle_args (work, mangled, declp);
2225     }
2226     }
2227     */
2228   return (success);
2229 }
2230
2231 static int
2232 arm_pt (work, mangled, n, anchor, args)
2233      struct work_stuff *work;
2234      const char *mangled;
2235      int n;
2236      const char **anchor, **args;
2237 {
2238   /* Check if ARM template with "__pt__" in it ("parameterized type") */
2239   /* Allow HP also here, because HP's cfront compiler follows ARM to some extent */
2240   if ((ARM_DEMANGLING || HP_DEMANGLING) && (*anchor = strstr (mangled, "__pt__")))
2241     {
2242       int len;
2243       *args = *anchor + 6;
2244       len = consume_count (args);
2245       if (len == -1)
2246         return 0;
2247       if (*args + len == mangled + n && **args == '_')
2248         {
2249           ++*args;
2250           return 1;
2251         }
2252     }
2253   if (AUTO_DEMANGLING || EDG_DEMANGLING)
2254     {
2255       if ((*anchor = strstr (mangled, "__tm__"))
2256           || (*anchor = strstr (mangled, "__ps__"))
2257           || (*anchor = strstr (mangled, "__pt__")))
2258         {
2259           int len;
2260           *args = *anchor + 6;
2261           len = consume_count (args);
2262           if (len == -1)
2263             return 0;
2264           if (*args + len == mangled + n && **args == '_')
2265             {
2266               ++*args;
2267               return 1;
2268             }
2269         }
2270       else if ((*anchor = strstr (mangled, "__S")))
2271         {
2272           int len;
2273           *args = *anchor + 3;
2274           len = consume_count (args);
2275           if (len == -1)
2276             return 0;
2277           if (*args + len == mangled + n && **args == '_')
2278             {
2279               ++*args;
2280               return 1;
2281             }
2282         }
2283     }
2284
2285   return 0;
2286 }
2287
2288 static void
2289 demangle_arm_hp_template (work, mangled, n, declp)
2290      struct work_stuff *work;
2291      const char **mangled;
2292      int n;
2293      string *declp;
2294 {
2295   const char *p;
2296   const char *args;
2297   const char *e = *mangled + n;
2298   string arg;
2299
2300   /* Check for HP aCC template spec: classXt1t2 where t1, t2 are
2301      template args */
2302   if (HP_DEMANGLING && ((*mangled)[n] == 'X'))
2303     {
2304       char *start_spec_args = NULL;
2305
2306       /* First check for and omit template specialization pseudo-arguments,
2307          such as in "Spec<#1,#1.*>" */
2308       start_spec_args = strchr (*mangled, '<');
2309       if (start_spec_args && (start_spec_args - *mangled < n))
2310         string_appendn (declp, *mangled, start_spec_args - *mangled);
2311       else
2312         string_appendn (declp, *mangled, n);
2313       (*mangled) += n + 1;
2314       string_init (&arg);
2315       if (work->temp_start == -1) /* non-recursive call */
2316         work->temp_start = declp->p - declp->b;
2317       string_append (declp, "<");
2318       while (1)
2319         {
2320           string_clear (&arg);
2321           switch (**mangled)
2322             {
2323               case 'T':
2324                 /* 'T' signals a type parameter */
2325                 (*mangled)++;
2326                 if (!do_type (work, mangled, &arg))
2327                   goto hpacc_template_args_done;
2328                 break;
2329
2330               case 'U':
2331               case 'S':
2332                 /* 'U' or 'S' signals an integral value */
2333                 if (!do_hpacc_template_const_value (work, mangled, &arg))
2334                   goto hpacc_template_args_done;
2335                 break;
2336
2337               case 'A':
2338                 /* 'A' signals a named constant expression (literal) */
2339                 if (!do_hpacc_template_literal (work, mangled, &arg))
2340                   goto hpacc_template_args_done;
2341                 break;
2342
2343               default:
2344                 /* Today, 1997-09-03, we have only the above types
2345                    of template parameters */
2346                 /* FIXME: maybe this should fail and return null */
2347                 goto hpacc_template_args_done;
2348             }
2349           string_appends (declp, &arg);
2350          /* Check if we're at the end of template args.
2351              0 if at end of static member of template class,
2352              _ if done with template args for a function */
2353           if ((**mangled == '\000') || (**mangled == '_'))
2354             break;
2355           else
2356             string_append (declp, ",");
2357         }
2358     hpacc_template_args_done:
2359       string_append (declp, ">");
2360       string_delete (&arg);
2361       if (**mangled == '_')
2362         (*mangled)++;
2363       return;
2364     }
2365   /* ARM template? (Also handles HP cfront extensions) */
2366   else if (arm_pt (work, *mangled, n, &p, &args))
2367     {
2368       string type_str;
2369
2370       string_init (&arg);
2371       string_appendn (declp, *mangled, p - *mangled);
2372       if (work->temp_start == -1)  /* non-recursive call */
2373         work->temp_start = declp->p - declp->b;
2374       string_append (declp, "<");
2375       /* should do error checking here */
2376       while (args < e) {
2377         string_clear (&arg);
2378
2379         /* Check for type or literal here */
2380         switch (*args)
2381           {
2382             /* HP cfront extensions to ARM for template args */
2383             /* spec: Xt1Lv1 where t1 is a type, v1 is a literal value */
2384             /* FIXME: We handle only numeric literals for HP cfront */
2385           case 'X':
2386             /* A typed constant value follows */
2387             args++;
2388             if (!do_type (work, &args, &type_str))
2389               goto cfront_template_args_done;
2390             string_append (&arg, "(");
2391             string_appends (&arg, &type_str);
2392             string_append (&arg, ")");
2393             if (*args != 'L')
2394               goto cfront_template_args_done;
2395             args++;
2396             /* Now snarf a literal value following 'L' */
2397             if (!snarf_numeric_literal (&args, &arg))
2398               goto cfront_template_args_done;
2399             break;
2400
2401           case 'L':
2402             /* Snarf a literal following 'L' */
2403             args++;
2404             if (!snarf_numeric_literal (&args, &arg))
2405               goto cfront_template_args_done;
2406             break;
2407           default:
2408             /* Not handling other HP cfront stuff */
2409             if (!do_type (work, &args, &arg))
2410               goto cfront_template_args_done;
2411           }
2412         string_appends (declp, &arg);
2413         string_append (declp, ",");
2414       }
2415     cfront_template_args_done:
2416       string_delete (&arg);
2417       if (args >= e)
2418         --declp->p; /* remove extra comma */
2419       string_append (declp, ">");
2420     }
2421   else if (n>10 && strncmp (*mangled, "_GLOBAL_", 8) == 0
2422            && (*mangled)[9] == 'N'
2423            && (*mangled)[8] == (*mangled)[10]
2424            && strchr (cplus_markers, (*mangled)[8]))
2425     {
2426       /* A member of the anonymous namespace.  */
2427       string_append (declp, "{anonymous}");
2428     }
2429   else
2430     {
2431       if (work->temp_start == -1) /* non-recursive call only */
2432         work->temp_start = 0;     /* disable in recursive calls */
2433       string_appendn (declp, *mangled, n);
2434     }
2435   *mangled += n;
2436 }
2437
2438 /* Extract a class name, possibly a template with arguments, from the
2439    mangled string; qualifiers, local class indicators, etc. have
2440    already been dealt with */
2441
2442 static int
2443 demangle_class_name (work, mangled, declp)
2444      struct work_stuff *work;
2445      const char **mangled;
2446      string *declp;
2447 {
2448   int n;
2449   int success = 0;
2450
2451   n = consume_count (mangled);
2452   if (n == -1)
2453     return 0;
2454   if ((int) strlen (*mangled) >= n)
2455     {
2456       demangle_arm_hp_template (work, mangled, n, declp);
2457       success = 1;
2458     }
2459
2460   return (success);
2461 }
2462
2463 /*
2464
2465 LOCAL FUNCTION
2466
2467         demangle_class -- demangle a mangled class sequence
2468
2469 SYNOPSIS
2470
2471         static int
2472         demangle_class (struct work_stuff *work, const char **mangled,
2473                         strint *declp)
2474
2475 DESCRIPTION
2476
2477         DECLP points to the buffer into which demangling is being done.
2478
2479         *MANGLED points to the current token to be demangled.  On input,
2480         it points to a mangled class (I.E. "3foo", "13verylongclass", etc.)
2481         On exit, it points to the next token after the mangled class on
2482         success, or the first unconsumed token on failure.
2483
2484         If the CONSTRUCTOR or DESTRUCTOR flags are set in WORK, then
2485         we are demangling a constructor or destructor.  In this case
2486         we prepend "class::class" or "class::~class" to DECLP.
2487
2488         Otherwise, we prepend "class::" to the current DECLP.
2489
2490         Reset the constructor/destructor flags once they have been
2491         "consumed".  This allows demangle_class to be called later during
2492         the same demangling, to do normal class demangling.
2493
2494         Returns 1 if demangling is successful, 0 otherwise.
2495
2496 */
2497
2498 static int
2499 demangle_class (work, mangled, declp)
2500      struct work_stuff *work;
2501      const char **mangled;
2502      string *declp;
2503 {
2504   int success = 0;
2505   int btype;
2506   string class_name;
2507   char *save_class_name_end = 0;
2508
2509   string_init (&class_name);
2510   btype = register_Btype (work);
2511   if (demangle_class_name (work, mangled, &class_name))
2512     {
2513       save_class_name_end = class_name.p;
2514       if ((work->constructor & 1) || (work->destructor & 1))
2515         {
2516           /* adjust so we don't include template args */
2517           if (work->temp_start && (work->temp_start != -1))
2518             {
2519               class_name.p = class_name.b + work->temp_start;
2520             }
2521           string_prepends (declp, &class_name);
2522           if (work -> destructor & 1)
2523             {
2524               string_prepend (declp, "~");
2525               work -> destructor -= 1;
2526             }
2527           else
2528             {
2529               work -> constructor -= 1;
2530             }
2531         }
2532       class_name.p = save_class_name_end;
2533       remember_Ktype (work, class_name.b, LEN_STRING(&class_name));
2534       remember_Btype (work, class_name.b, LEN_STRING(&class_name), btype);
2535       string_prepend (declp, SCOPE_STRING (work));
2536       string_prepends (declp, &class_name);
2537       success = 1;
2538     }
2539   string_delete (&class_name);
2540   return (success);
2541 }
2542
2543
2544 /* Called when there's a "__" in the mangled name, with `scan' pointing to
2545    the rightmost guess.
2546
2547    Find the correct "__"-sequence where the function name ends and the
2548    signature starts, which is ambiguous with GNU mangling.
2549    Call demangle_signature here, so we can make sure we found the right
2550    one; *mangled will be consumed so caller will not make further calls to
2551    demangle_signature.  */
2552
2553 static int
2554 iterate_demangle_function (work, mangled, declp, scan)
2555      struct work_stuff *work;
2556      const char **mangled;
2557      string *declp;
2558      const char *scan;
2559 {
2560   const char *mangle_init = *mangled;
2561   int success = 0;
2562   string decl_init;
2563   struct work_stuff work_init;
2564
2565   if (*(scan + 2) == '\0')
2566     return 0;
2567
2568   /* Do not iterate for some demangling modes, or if there's only one
2569      "__"-sequence.  This is the normal case.  */
2570   if (ARM_DEMANGLING || LUCID_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING
2571       || strstr (scan + 2, "__") == NULL)
2572     {
2573       demangle_function_name (work, mangled, declp, scan);
2574       return 1;
2575     }
2576
2577   /* Save state so we can restart if the guess at the correct "__" was
2578      wrong.  */
2579   string_init (&decl_init);
2580   string_appends (&decl_init, declp);
2581   memset (&work_init, 0, sizeof work_init);
2582   work_stuff_copy_to_from (&work_init, work);
2583
2584   /* Iterate over occurrences of __, allowing names and types to have a
2585      "__" sequence in them.  We must start with the first (not the last)
2586      occurrence, since "__" most often occur between independent mangled
2587      parts, hence starting at the last occurence inside a signature
2588      might get us a "successful" demangling of the signature.  */
2589
2590   while (scan[2])
2591     {
2592       demangle_function_name (work, mangled, declp, scan);
2593       success = demangle_signature (work, mangled, declp);
2594       if (success)
2595         break;
2596
2597       /* Reset demangle state for the next round.  */
2598       *mangled = mangle_init;
2599       string_clear (declp);
2600       string_appends (declp, &decl_init);
2601       work_stuff_copy_to_from (work, &work_init);
2602
2603       /* Leave this underscore-sequence.  */
2604       scan += 2;
2605
2606       /* Scan for the next "__" sequence.  */
2607       while (*scan && (scan[0] != '_' || scan[1] != '_'))
2608         scan++;
2609
2610       /* Move to last "__" in this sequence.  */
2611       while (*scan && *scan == '_')
2612         scan++;
2613       scan -= 2;
2614     }
2615
2616   /* Delete saved state.  */
2617   delete_work_stuff (&work_init);
2618   string_delete (&decl_init);
2619
2620   return success;
2621 }
2622
2623 /*
2624
2625 LOCAL FUNCTION
2626
2627         demangle_prefix -- consume the mangled name prefix and find signature
2628
2629 SYNOPSIS
2630
2631         static int
2632         demangle_prefix (struct work_stuff *work, const char **mangled,
2633                          string *declp);
2634
2635 DESCRIPTION
2636
2637         Consume and demangle the prefix of the mangled name.
2638         While processing the function name root, arrange to call
2639         demangle_signature if the root is ambiguous.
2640
2641         DECLP points to the string buffer into which demangled output is
2642         placed.  On entry, the buffer is empty.  On exit it contains
2643         the root function name, the demangled operator name, or in some
2644         special cases either nothing or the completely demangled result.
2645
2646         MANGLED points to the current pointer into the mangled name.  As each
2647         token of the mangled name is consumed, it is updated.  Upon entry
2648         the current mangled name pointer points to the first character of
2649         the mangled name.  Upon exit, it should point to the first character
2650         of the signature if demangling was successful, or to the first
2651         unconsumed character if demangling of the prefix was unsuccessful.
2652
2653         Returns 1 on success, 0 otherwise.
2654  */
2655
2656 static int
2657 demangle_prefix (work, mangled, declp)
2658      struct work_stuff *work;
2659      const char **mangled;
2660      string *declp;
2661 {
2662   int success = 1;
2663   const char *scan;
2664   int i;
2665
2666   if (strlen(*mangled) > 6
2667       && (strncmp(*mangled, "_imp__", 6) == 0
2668           || strncmp(*mangled, "__imp_", 6) == 0))
2669     {
2670       /* it's a symbol imported from a PE dynamic library. Check for both
2671          new style prefix _imp__ and legacy __imp_ used by older versions
2672          of dlltool. */
2673       (*mangled) += 6;
2674       work->dllimported = 1;
2675     }
2676   else if (strlen(*mangled) >= 11 && strncmp(*mangled, "_GLOBAL_", 8) == 0)
2677     {
2678       char *marker = strchr (cplus_markers, (*mangled)[8]);
2679       if (marker != NULL && *marker == (*mangled)[10])
2680         {
2681           if ((*mangled)[9] == 'D')
2682             {
2683               /* it's a GNU global destructor to be executed at program exit */
2684               (*mangled) += 11;
2685               work->destructor = 2;
2686               if (gnu_special (work, mangled, declp))
2687                 return success;
2688             }
2689           else if ((*mangled)[9] == 'I')
2690             {
2691               /* it's a GNU global constructor to be executed at program init */
2692               (*mangled) += 11;
2693               work->constructor = 2;
2694               if (gnu_special (work, mangled, declp))
2695                 return success;
2696             }
2697         }
2698     }
2699   else if ((ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING) && strncmp(*mangled, "__std__", 7) == 0)
2700     {
2701       /* it's a ARM global destructor to be executed at program exit */
2702       (*mangled) += 7;
2703       work->destructor = 2;
2704     }
2705   else if ((ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING) && strncmp(*mangled, "__sti__", 7) == 0)
2706     {
2707       /* it's a ARM global constructor to be executed at program initial */
2708       (*mangled) += 7;
2709       work->constructor = 2;
2710     }
2711
2712   /*  This block of code is a reduction in strength time optimization
2713       of:
2714       scan = strstr (*mangled, "__"); */
2715
2716   {
2717     scan = *mangled;
2718
2719     do {
2720       scan = strchr (scan, '_');
2721     } while (scan != NULL && *++scan != '_');
2722
2723     if (scan != NULL) --scan;
2724   }
2725
2726   if (scan != NULL)
2727     {
2728       /* We found a sequence of two or more '_', ensure that we start at
2729          the last pair in the sequence.  */
2730       i = strspn (scan, "_");
2731       if (i > 2)
2732         {
2733           scan += (i - 2);
2734         }
2735     }
2736
2737   if (scan == NULL)
2738     {
2739       success = 0;
2740     }
2741   else if (work -> static_type)
2742     {
2743       if (!ISDIGIT ((unsigned char)scan[0]) && (scan[0] != 't'))
2744         {
2745           success = 0;
2746         }
2747     }
2748   else if ((scan == *mangled)
2749            && (ISDIGIT ((unsigned char)scan[2]) || (scan[2] == 'Q')
2750                || (scan[2] == 't') || (scan[2] == 'K') || (scan[2] == 'H')))
2751     {
2752       /* The ARM says nothing about the mangling of local variables.
2753          But cfront mangles local variables by prepending __<nesting_level>
2754          to them. As an extension to ARM demangling we handle this case.  */
2755       if ((LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING)
2756           && ISDIGIT ((unsigned char)scan[2]))
2757         {
2758           *mangled = scan + 2;
2759           consume_count (mangled);
2760           string_append (declp, *mangled);
2761           *mangled += strlen (*mangled);
2762           success = 1;
2763         }
2764       else
2765         {
2766           /* A GNU style constructor starts with __[0-9Qt].  But cfront uses
2767              names like __Q2_3foo3bar for nested type names.  So don't accept
2768              this style of constructor for cfront demangling.  A GNU
2769              style member-template constructor starts with 'H'. */
2770           if (!(LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING))
2771             work -> constructor += 1;
2772           *mangled = scan + 2;
2773         }
2774     }
2775   else if (ARM_DEMANGLING && scan[2] == 'p' && scan[3] == 't')
2776     {
2777       /* Cfront-style parameterized type.  Handled later as a signature. */
2778       success = 1;
2779
2780       /* ARM template? */
2781       demangle_arm_hp_template (work, mangled, strlen (*mangled), declp);
2782     }
2783   else if (EDG_DEMANGLING && ((scan[2] == 't' && scan[3] == 'm')
2784                               || (scan[2] == 'p' && scan[3] == 's')
2785                               || (scan[2] == 'p' && scan[3] == 't')))
2786     {
2787       /* EDG-style parameterized type.  Handled later as a signature. */
2788       success = 1;
2789
2790       /* EDG template? */
2791       demangle_arm_hp_template (work, mangled, strlen (*mangled), declp);
2792     }
2793   else if ((scan == *mangled) && !ISDIGIT ((unsigned char)scan[2])
2794            && (scan[2] != 't'))
2795     {
2796       /* Mangled name starts with "__".  Skip over any leading '_' characters,
2797          then find the next "__" that separates the prefix from the signature.
2798          */
2799       if (!(ARM_DEMANGLING || LUCID_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING)
2800           || (arm_special (mangled, declp) == 0))
2801         {
2802           while (*scan == '_')
2803             {
2804               scan++;
2805             }
2806           if ((scan = strstr (scan, "__")) == NULL || (*(scan + 2) == '\0'))
2807             {
2808               /* No separator (I.E. "__not_mangled"), or empty signature
2809                  (I.E. "__not_mangled_either__") */
2810               success = 0;
2811             }
2812           else
2813             return iterate_demangle_function (work, mangled, declp, scan);
2814         }
2815     }
2816   else if (*(scan + 2) != '\0')
2817     {
2818       /* Mangled name does not start with "__" but does have one somewhere
2819          in there with non empty stuff after it.  Looks like a global
2820          function name.  Iterate over all "__":s until the right
2821          one is found.  */
2822       return iterate_demangle_function (work, mangled, declp, scan);
2823     }
2824   else
2825     {
2826       /* Doesn't look like a mangled name */
2827       success = 0;
2828     }
2829
2830   if (!success && (work->constructor == 2 || work->destructor == 2))
2831     {
2832       string_append (declp, *mangled);
2833       *mangled += strlen (*mangled);
2834       success = 1;
2835     }
2836   return (success);
2837 }
2838
2839 /*
2840
2841 LOCAL FUNCTION
2842
2843         gnu_special -- special handling of gnu mangled strings
2844
2845 SYNOPSIS
2846
2847         static int
2848         gnu_special (struct work_stuff *work, const char **mangled,
2849                      string *declp);
2850
2851
2852 DESCRIPTION
2853
2854         Process some special GNU style mangling forms that don't fit
2855         the normal pattern.  For example:
2856
2857                 _$_3foo         (destructor for class foo)
2858                 _vt$foo         (foo virtual table)
2859                 _vt$foo$bar     (foo::bar virtual table)
2860                 __vt_foo        (foo virtual table, new style with thunks)
2861                 _3foo$varname   (static data member)
2862                 _Q22rs2tu$vw    (static data member)
2863                 __t6vector1Zii  (constructor with template)
2864                 __thunk_4__$_7ostream (virtual function thunk)
2865  */
2866
2867 static int
2868 gnu_special (work, mangled, declp)
2869      struct work_stuff *work;
2870      const char **mangled;
2871      string *declp;
2872 {
2873   int n;
2874   int success = 1;
2875   const char *p;
2876
2877   if ((*mangled)[0] == '_'
2878       && strchr (cplus_markers, (*mangled)[1]) != NULL
2879       && (*mangled)[2] == '_')
2880     {
2881       /* Found a GNU style destructor, get past "_<CPLUS_MARKER>_" */
2882       (*mangled) += 3;
2883       work -> destructor += 1;
2884     }
2885   else if ((*mangled)[0] == '_'
2886            && (((*mangled)[1] == '_'
2887                 && (*mangled)[2] == 'v'
2888                 && (*mangled)[3] == 't'
2889                 && (*mangled)[4] == '_')
2890                || ((*mangled)[1] == 'v'
2891                    && (*mangled)[2] == 't'
2892                    && strchr (cplus_markers, (*mangled)[3]) != NULL)))
2893     {
2894       /* Found a GNU style virtual table, get past "_vt<CPLUS_MARKER>"
2895          and create the decl.  Note that we consume the entire mangled
2896          input string, which means that demangle_signature has no work
2897          to do.  */
2898       if ((*mangled)[2] == 'v')
2899         (*mangled) += 5; /* New style, with thunks: "__vt_" */
2900       else
2901         (*mangled) += 4; /* Old style, no thunks: "_vt<CPLUS_MARKER>" */
2902       while (**mangled != '\0')
2903         {
2904           switch (**mangled)
2905             {
2906             case 'Q':
2907             case 'K':
2908               success = demangle_qualified (work, mangled, declp, 0, 1);
2909               break;
2910             case 't':
2911               success = demangle_template (work, mangled, declp, 0, 1,
2912                                            1);
2913               break;
2914             default:
2915               if (ISDIGIT((unsigned char)*mangled[0]))
2916                 {
2917                   n = consume_count(mangled);
2918                   /* We may be seeing a too-large size, or else a
2919                      ".<digits>" indicating a static local symbol.  In
2920                      any case, declare victory and move on; *don't* try
2921                      to use n to allocate.  */
2922                   if (n > (int) strlen (*mangled))
2923                     {
2924                       success = 1;
2925                       break;
2926                     }
2927                 }
2928               else
2929                 {
2930                   n = strcspn (*mangled, cplus_markers);
2931                 }
2932               string_appendn (declp, *mangled, n);
2933               (*mangled) += n;
2934             }
2935
2936           p = strpbrk (*mangled, cplus_markers);
2937           if (success && ((p == NULL) || (p == *mangled)))
2938             {
2939               if (p != NULL)
2940                 {
2941                   string_append (declp, SCOPE_STRING (work));
2942                   (*mangled)++;
2943                 }
2944             }
2945           else
2946             {
2947               success = 0;
2948               break;
2949             }
2950         }
2951       if (success)
2952         string_append (declp, " virtual table");
2953     }
2954   else if ((*mangled)[0] == '_'
2955            && (strchr("0123456789Qt", (*mangled)[1]) != NULL)
2956            && (p = strpbrk (*mangled, cplus_markers)) != NULL)
2957     {
2958       /* static data member, "_3foo$varname" for example */
2959       (*mangled)++;
2960       switch (**mangled)
2961         {
2962         case 'Q':
2963         case 'K':
2964           success = demangle_qualified (work, mangled, declp, 0, 1);
2965           break;
2966         case 't':
2967           success = demangle_template (work, mangled, declp, 0, 1, 1);
2968           break;
2969         default:
2970           n = consume_count (mangled);
2971           if (n < 0 || n > (long) strlen (*mangled))
2972             {
2973               success = 0;
2974               break;
2975             }
2976
2977           if (n > 10 && strncmp (*mangled, "_GLOBAL_", 8) == 0
2978               && (*mangled)[9] == 'N'
2979               && (*mangled)[8] == (*mangled)[10]
2980               && strchr (cplus_markers, (*mangled)[8]))
2981             {
2982               /* A member of the anonymous namespace.  There's information
2983                  about what identifier or filename it was keyed to, but
2984                  it's just there to make the mangled name unique; we just
2985                  step over it.  */
2986               string_append (declp, "{anonymous}");
2987               (*mangled) += n;
2988
2989               /* Now p points to the marker before the N, so we need to
2990                  update it to the first marker after what we consumed.  */
2991               p = strpbrk (*mangled, cplus_markers);
2992               break;
2993             }
2994
2995           string_appendn (declp, *mangled, n);
2996           (*mangled) += n;
2997         }
2998       if (success && (p == *mangled))
2999         {
3000           /* Consumed everything up to the cplus_marker, append the
3001              variable name.  */
3002           (*mangled)++;
3003           string_append (declp, SCOPE_STRING (work));
3004           n = strlen (*mangled);
3005           string_appendn (declp, *mangled, n);
3006           (*mangled) += n;
3007         }
3008       else
3009         {
3010           success = 0;
3011         }
3012     }
3013   else if (strncmp (*mangled, "__thunk_", 8) == 0)
3014     {
3015       int delta;
3016
3017       (*mangled) += 8;
3018       delta = consume_count (mangled);
3019       if (delta == -1)
3020         success = 0;
3021       else
3022         {
3023           char *method = internal_cplus_demangle (work, ++*mangled);
3024
3025           if (method)
3026             {
3027               char buf[50];
3028               sprintf (buf, "virtual function thunk (delta:%d) for ", -delta);
3029               string_append (declp, buf);
3030               string_append (declp, method);
3031               free (method);
3032               n = strlen (*mangled);
3033               (*mangled) += n;
3034             }
3035           else
3036             {
3037               success = 0;
3038             }
3039         }
3040     }
3041   else if (strncmp (*mangled, "__t", 3) == 0
3042            && ((*mangled)[3] == 'i' || (*mangled)[3] == 'f'))
3043     {
3044       p = (*mangled)[3] == 'i' ? " type_info node" : " type_info function";
3045       (*mangled) += 4;
3046       switch (**mangled)
3047         {
3048         case 'Q':
3049         case 'K':
3050           success = demangle_qualified (work, mangled, declp, 0, 1);
3051           break;
3052         case 't':
3053           success = demangle_template (work, mangled, declp, 0, 1, 1);
3054           break;
3055         default:
3056           success = do_type (work, mangled, declp);
3057           break;
3058         }
3059       if (success && **mangled != '\0')
3060         success = 0;
3061       if (success)
3062         string_append (declp, p);
3063     }
3064   else
3065     {
3066       success = 0;
3067     }
3068   return (success);
3069 }
3070
3071 static void
3072 recursively_demangle(work, mangled, result, namelength)
3073      struct work_stuff *work;
3074      const char **mangled;
3075      string *result;
3076      int namelength;
3077 {
3078   char * recurse = (char *)NULL;
3079   char * recurse_dem = (char *)NULL;
3080
3081   recurse = (char *) xmalloc (namelength + 1);
3082   memcpy (recurse, *mangled, namelength);
3083   recurse[namelength] = '\000';
3084
3085   recurse_dem = cplus_demangle (recurse, work->options);
3086
3087   if (recurse_dem)
3088     {
3089       string_append (result, recurse_dem);
3090       free (recurse_dem);
3091     }
3092   else
3093     {
3094       string_appendn (result, *mangled, namelength);
3095     }
3096   free (recurse);
3097   *mangled += namelength;
3098 }
3099
3100 /*
3101
3102 LOCAL FUNCTION
3103
3104         arm_special -- special handling of ARM/lucid mangled strings
3105
3106 SYNOPSIS
3107
3108         static int
3109         arm_special (const char **mangled,
3110                      string *declp);
3111
3112
3113 DESCRIPTION
3114
3115         Process some special ARM style mangling forms that don't fit
3116         the normal pattern.  For example:
3117
3118                 __vtbl__3foo            (foo virtual table)
3119                 __vtbl__3foo__3bar      (bar::foo virtual table)
3120
3121  */
3122
3123 static int
3124 arm_special (mangled, declp)
3125      const char **mangled;
3126      string *declp;
3127 {
3128   int n;
3129   int success = 1;
3130   const char *scan;
3131
3132   if (strncmp (*mangled, ARM_VTABLE_STRING, ARM_VTABLE_STRLEN) == 0)
3133     {
3134       /* Found a ARM style virtual table, get past ARM_VTABLE_STRING
3135          and create the decl.  Note that we consume the entire mangled
3136          input string, which means that demangle_signature has no work
3137          to do.  */
3138       scan = *mangled + ARM_VTABLE_STRLEN;
3139       while (*scan != '\0')        /* first check it can be demangled */
3140         {
3141           n = consume_count (&scan);
3142           if (n == -1)
3143             {
3144               return (0);           /* no good */
3145             }
3146           scan += n;
3147           if (scan[0] == '_' && scan[1] == '_')
3148             {
3149               scan += 2;
3150             }
3151         }
3152       (*mangled) += ARM_VTABLE_STRLEN;
3153       while (**mangled != '\0')
3154         {
3155           n = consume_count (mangled);
3156           if (n == -1
3157               || n > (long) strlen (*mangled))
3158             return 0;
3159           string_prependn (declp, *mangled, n);
3160           (*mangled) += n;
3161           if ((*mangled)[0] == '_' && (*mangled)[1] == '_')
3162             {
3163               string_prepend (declp, "::");
3164               (*mangled) += 2;
3165             }
3166         }
3167       string_append (declp, " virtual table");
3168     }
3169   else
3170     {
3171       success = 0;
3172     }
3173   return (success);
3174 }
3175
3176 /*
3177
3178 LOCAL FUNCTION
3179
3180         demangle_qualified -- demangle 'Q' qualified name strings
3181
3182 SYNOPSIS
3183
3184         static int
3185         demangle_qualified (struct work_stuff *, const char *mangled,
3186                             string *result, int isfuncname, int append);
3187
3188 DESCRIPTION
3189
3190         Demangle a qualified name, such as "Q25Outer5Inner" which is
3191         the mangled form of "Outer::Inner".  The demangled output is
3192         prepended or appended to the result string according to the
3193         state of the append flag.
3194
3195         If isfuncname is nonzero, then the qualified name we are building
3196         is going to be used as a member function name, so if it is a
3197         constructor or destructor function, append an appropriate
3198         constructor or destructor name.  I.E. for the above example,
3199         the result for use as a constructor is "Outer::Inner::Inner"
3200         and the result for use as a destructor is "Outer::Inner::~Inner".
3201
3202 BUGS
3203
3204         Numeric conversion is ASCII dependent (FIXME).
3205
3206  */
3207
3208 static int
3209 demangle_qualified (work, mangled, result, isfuncname, append)
3210      struct work_stuff *work;
3211      const char **mangled;
3212      string *result;
3213      int isfuncname;
3214      int append;
3215 {
3216   int qualifiers = 0;
3217   int success = 1;
3218   char num[2];
3219   string temp;
3220   string last_name;
3221   int bindex = register_Btype (work);
3222
3223   /* We only make use of ISFUNCNAME if the entity is a constructor or
3224      destructor.  */
3225   isfuncname = (isfuncname
3226                 && ((work->constructor & 1) || (work->destructor & 1)));
3227
3228   string_init (&temp);
3229   string_init (&last_name);
3230
3231   if ((*mangled)[0] == 'K')
3232     {
3233     /* Squangling qualified name reuse */
3234       int idx;
3235       (*mangled)++;
3236       idx = consume_count_with_underscores (mangled);
3237       if (idx == -1 || idx >= work -> numk)
3238         success = 0;
3239       else
3240         string_append (&temp, work -> ktypevec[idx]);
3241     }
3242   else
3243     switch ((*mangled)[1])
3244     {
3245     case '_':
3246       /* GNU mangled name with more than 9 classes.  The count is preceded
3247          by an underscore (to distinguish it from the <= 9 case) and followed
3248          by an underscore.  */
3249       (*mangled)++;
3250       qualifiers = consume_count_with_underscores (mangled);
3251       if (qualifiers == -1)
3252         success = 0;
3253       break;
3254
3255     case '1':
3256     case '2':
3257     case '3':
3258     case '4':
3259     case '5':
3260     case '6':
3261     case '7':
3262     case '8':
3263     case '9':
3264       /* The count is in a single digit.  */
3265       num[0] = (*mangled)[1];
3266       num[1] = '\0';
3267       qualifiers = atoi (num);
3268
3269       /* If there is an underscore after the digit, skip it.  This is
3270          said to be for ARM-qualified names, but the ARM makes no
3271          mention of such an underscore.  Perhaps cfront uses one.  */
3272       if ((*mangled)[2] == '_')
3273         {
3274           (*mangled)++;
3275         }
3276       (*mangled) += 2;
3277       break;
3278
3279     case '0':
3280     default:
3281       success = 0;
3282     }
3283
3284   if (!success)
3285     return success;
3286
3287   /* Pick off the names and collect them in the temp buffer in the order
3288      in which they are found, separated by '::'.  */
3289
3290   while (qualifiers-- > 0)
3291     {
3292       int remember_K = 1;
3293       string_clear (&last_name);
3294
3295       if (*mangled[0] == '_')
3296         (*mangled)++;
3297
3298       if (*mangled[0] == 't')
3299         {
3300           /* Here we always append to TEMP since we will want to use
3301              the template name without the template parameters as a
3302              constructor or destructor name.  The appropriate
3303              (parameter-less) value is returned by demangle_template
3304              in LAST_NAME.  We do not remember the template type here,
3305              in order to match the G++ mangling algorithm.  */
3306           success = demangle_template(work, mangled, &temp,
3307                                       &last_name, 1, 0);
3308           if (!success)
3309             break;
3310         }
3311       else if (*mangled[0] == 'K')
3312         {
3313           int idx;
3314           (*mangled)++;
3315           idx = consume_count_with_underscores (mangled);
3316           if (idx == -1 || idx >= work->numk)
3317             success = 0;
3318           else
3319             string_append (&temp, work->ktypevec[idx]);
3320           remember_K = 0;
3321
3322           if (!success) break;
3323         }
3324       else
3325         {
3326           if (EDG_DEMANGLING)
3327             {
3328               int namelength;
3329               /* Now recursively demangle the qualifier
3330                * This is necessary to deal with templates in
3331                * mangling styles like EDG */
3332               namelength = consume_count (mangled);
3333               if (namelength == -1)
3334                 {
3335                   success = 0;
3336                   break;
3337                 }
3338               recursively_demangle(work, mangled, &temp, namelength);
3339             }
3340           else
3341             {
3342               success = do_type (work, mangled, &last_name);
3343               if (!success)
3344                 break;
3345               string_appends (&temp, &last_name);
3346             }
3347         }
3348
3349       if (remember_K)
3350         remember_Ktype (work, temp.b, LEN_STRING (&temp));
3351
3352       if (qualifiers > 0)
3353         string_append (&temp, SCOPE_STRING (work));
3354     }
3355
3356   remember_Btype (work, temp.b, LEN_STRING (&temp), bindex);
3357
3358   /* If we are using the result as a function name, we need to append
3359      the appropriate '::' separated constructor or destructor name.
3360      We do this here because this is the most convenient place, where
3361      we already have a pointer to the name and the length of the name.  */
3362
3363   if (isfuncname)
3364     {
3365       string_append (&temp, SCOPE_STRING (work));
3366       if (work -> destructor & 1)
3367         string_append (&temp, "~");
3368       string_appends (&temp, &last_name);
3369     }
3370
3371   /* Now either prepend the temp buffer to the result, or append it,
3372      depending upon the state of the append flag.  */
3373
3374   if (append)
3375     string_appends (result, &temp);
3376   else
3377     {
3378       if (!STRING_EMPTY (result))
3379         string_append (&temp, SCOPE_STRING (work));
3380       string_prepends (result, &temp);
3381     }
3382
3383   string_delete (&last_name);
3384   string_delete (&temp);
3385   return (success);
3386 }
3387
3388 /*
3389
3390 LOCAL FUNCTION
3391
3392         get_count -- convert an ascii count to integer, consuming tokens
3393
3394 SYNOPSIS
3395
3396         static int
3397         get_count (const char **type, int *count)
3398
3399 DESCRIPTION
3400
3401         Assume that *type points at a count in a mangled name; set
3402         *count to its value, and set *type to the next character after
3403         the count.  There are some weird rules in effect here.
3404
3405         If *type does not point at a string of digits, return zero.
3406
3407         If *type points at a string of digits followed by an
3408         underscore, set *count to their value as an integer, advance
3409         *type to point *after the underscore, and return 1.
3410
3411         If *type points at a string of digits not followed by an
3412         underscore, consume only the first digit.  Set *count to its
3413         value as an integer, leave *type pointing after that digit,
3414         and return 1.
3415
3416         The excuse for this odd behavior: in the ARM and HP demangling
3417         styles, a type can be followed by a repeat count of the form
3418         `Nxy', where:
3419
3420         `x' is a single digit specifying how many additional copies
3421             of the type to append to the argument list, and
3422
3423         `y' is one or more digits, specifying the zero-based index of
3424             the first repeated argument in the list.  Yes, as you're
3425             unmangling the name you can figure this out yourself, but
3426             it's there anyway.
3427
3428         So, for example, in `bar__3fooFPiN51', the first argument is a
3429         pointer to an integer (`Pi'), and then the next five arguments
3430         are the same (`N5'), and the first repeat is the function's
3431         second argument (`1').
3432 */
3433
3434 static int
3435 get_count (type, count)
3436      const char **type;
3437      int *count;
3438 {
3439   const char *p;
3440   int n;
3441
3442   if (!ISDIGIT ((unsigned char)**type))
3443     return (0);
3444   else
3445     {
3446       *count = **type - '0';
3447       (*type)++;
3448       if (ISDIGIT ((unsigned char)**type))
3449         {
3450           p = *type;
3451           n = *count;
3452           do
3453             {
3454               n *= 10;
3455               n += *p - '0';
3456               p++;
3457             }
3458           while (ISDIGIT ((unsigned char)*p));
3459           if (*p == '_')
3460             {
3461               *type = p + 1;
3462               *count = n;
3463             }
3464         }
3465     }
3466   return (1);
3467 }
3468
3469 /* RESULT will be initialised here; it will be freed on failure.  The
3470    value returned is really a type_kind_t.  */
3471
3472 static int
3473 do_type (work, mangled, result)
3474      struct work_stuff *work;
3475      const char **mangled;
3476      string *result;
3477 {
3478   int n;
3479   int done;
3480   int success;
3481   string decl;
3482   const char *remembered_type;
3483   int type_quals;
3484   string btype;
3485   type_kind_t tk = tk_none;
3486
3487   string_init (&btype);
3488   string_init (&decl);
3489   string_init (result);
3490
3491   done = 0;
3492   success = 1;
3493   while (success && !done)
3494     {
3495       int member;
3496       switch (**mangled)
3497         {
3498
3499           /* A pointer type */
3500         case 'P':
3501         case 'p':
3502           (*mangled)++;
3503           if (! (work -> options & DMGL_JAVA))
3504             string_prepend (&decl, "*");
3505           if (tk == tk_none)
3506             tk = tk_pointer;
3507           break;
3508
3509           /* A reference type */
3510         case 'R':
3511           (*mangled)++;
3512           string_prepend (&decl, "&");
3513           if (tk == tk_none)
3514             tk = tk_reference;
3515           break;
3516
3517           /* An array */
3518         case 'A':
3519           {
3520             ++(*mangled);
3521             if (!STRING_EMPTY (&decl)
3522                 && (decl.b[0] == '*' || decl.b[0] == '&'))
3523               {
3524                 string_prepend (&decl, "(");
3525                 string_append (&decl, ")");
3526               }
3527             string_append (&decl, "[");
3528             if (**mangled != '_')
3529               success = demangle_template_value_parm (work, mangled, &decl,
3530                                                       tk_integral);
3531             if (**mangled == '_')
3532               ++(*mangled);
3533             string_append (&decl, "]");
3534             break;
3535           }
3536
3537         /* A back reference to a previously seen type */
3538         case 'T':
3539           (*mangled)++;
3540           if (!get_count (mangled, &n) || n >= work -> ntypes)
3541             {
3542               success = 0;
3543             }
3544           else
3545             {
3546               remembered_type = work -> typevec[n];
3547               mangled = &remembered_type;
3548             }
3549           break;
3550
3551           /* A function */
3552         case 'F':
3553           (*mangled)++;
3554             if (!STRING_EMPTY (&decl)
3555                 && (decl.b[0] == '*' || decl.b[0] == '&'))
3556             {
3557               string_prepend (&decl, "(");
3558               string_append (&decl, ")");
3559             }
3560           /* After picking off the function args, we expect to either find the
3561              function return type (preceded by an '_') or the end of the
3562              string.  */
3563           if (!demangle_nested_args (work, mangled, &decl)
3564               || (**mangled != '_' && **mangled != '\0'))
3565             {
3566               success = 0;
3567               break;
3568             }
3569           if (success && (**mangled == '_'))
3570             (*mangled)++;
3571           break;
3572
3573         case 'M':
3574         case 'O':
3575           {
3576             type_quals = TYPE_UNQUALIFIED;
3577
3578             member = **mangled == 'M';
3579             (*mangled)++;
3580
3581             string_append (&decl, ")");
3582
3583             /* We don't need to prepend `::' for a qualified name;
3584                demangle_qualified will do that for us.  */
3585             if (**mangled != 'Q')
3586               string_prepend (&decl, SCOPE_STRING (work));
3587
3588             if (ISDIGIT ((unsigned char)**mangled))
3589               {
3590                 n = consume_count (mangled);
3591                 if (n == -1
3592                     || (int) strlen (*mangled) < n)
3593                   {
3594                     success = 0;
3595                     break;
3596                   }
3597                 string_prependn (&decl, *mangled, n);
3598                 *mangled += n;
3599               }
3600             else if (**mangled == 'X' || **mangled == 'Y')
3601               {
3602                 string temp;
3603                 do_type (work, mangled, &temp);
3604                 string_prepends (&decl, &temp);
3605               }
3606             else if (**mangled == 't')
3607               {
3608                 string temp;
3609                 string_init (&temp);
3610                 success = demangle_template (work, mangled, &temp,
3611                                              NULL, 1, 1);
3612                 if (success)
3613                   {
3614                     string_prependn (&decl, temp.b, temp.p - temp.b);
3615                     string_clear (&temp);
3616                   }
3617                 else
3618                   break;
3619               }
3620             else if (**mangled == 'Q')
3621               {
3622                 success = demangle_qualified (work, mangled, &decl,
3623                                               /*isfuncnam=*/0, 
3624                                               /*append=*/0);
3625                 if (!success)
3626                   break;
3627               }
3628             else
3629               {
3630                 success = 0;
3631                 break;
3632               }
3633
3634             string_prepend (&decl, "(");
3635             if (member)
3636               {
3637                 switch (**mangled)
3638                   {
3639                   case 'C':
3640                   case 'V':
3641                   case 'u':
3642                     type_quals |= code_for_qualifier (**mangled);
3643                     (*mangled)++;
3644                     break;
3645
3646                   default:
3647                     break;
3648                   }
3649
3650                 if (*(*mangled)++ != 'F')
3651                   {
3652                     success = 0;
3653                     break;
3654                   }
3655               }
3656             if ((member && !demangle_nested_args (work, mangled, &decl))
3657                 || **mangled != '_')
3658               {
3659                 success = 0;
3660                 break;
3661               }
3662             (*mangled)++;
3663             if (! PRINT_ANSI_QUALIFIERS)
3664               {
3665                 break;
3666               }
3667             if (type_quals != TYPE_UNQUALIFIED)
3668               {
3669                 APPEND_BLANK (&decl);
3670                 string_append (&decl, qualifier_string (type_quals));
3671               }
3672             break;
3673           }
3674         case 'G':
3675           (*mangled)++;
3676           break;
3677
3678         case 'C':
3679         case 'V':
3680         case 'u':
3681           if (PRINT_ANSI_QUALIFIERS)
3682             {
3683               if (!STRING_EMPTY (&decl))
3684                 string_prepend (&decl, " ");
3685
3686               string_prepend (&decl, demangle_qualifier (**mangled));
3687             }
3688           (*mangled)++;
3689           break;
3690           /*
3691             }
3692             */
3693
3694           /* fall through */
3695         default:
3696           done = 1;
3697           break;
3698         }
3699     }
3700
3701   if (success) switch (**mangled)
3702     {
3703       /* A qualified name, such as "Outer::Inner".  */
3704     case 'Q':
3705     case 'K':
3706       {
3707         success = demangle_qualified (work, mangled, result, 0, 1);
3708         break;
3709       }
3710
3711     /* A back reference to a previously seen squangled type */
3712     case 'B':
3713       (*mangled)++;
3714       if (!get_count (mangled, &n) || n >= work -> numb)
3715         success = 0;
3716       else
3717         string_append (result, work->btypevec[n]);
3718       break;
3719
3720     case 'X':
3721     case 'Y':
3722       /* A template parm.  We substitute the corresponding argument. */
3723       {
3724         int idx;
3725
3726         (*mangled)++;
3727         idx = consume_count_with_underscores (mangled);
3728
3729         if (idx == -1
3730             || (work->tmpl_argvec && idx >= work->ntmpl_args)
3731             || consume_count_with_underscores (mangled) == -1)
3732           {
3733             success = 0;
3734             break;
3735           }
3736
3737         if (work->tmpl_argvec)
3738           string_append (result, work->tmpl_argvec[idx]);
3739         else
3740           string_append_template_idx (result, idx);
3741
3742         success = 1;
3743       }
3744     break;
3745
3746     default:
3747       success = demangle_fund_type (work, mangled, result);
3748       if (tk == tk_none)
3749         tk = (type_kind_t) success;
3750       break;
3751     }
3752
3753   if (success)
3754     {
3755       if (!STRING_EMPTY (&decl))
3756         {
3757           string_append (result, " ");
3758           string_appends (result, &decl);
3759         }
3760     }
3761   else
3762     string_delete (result);
3763   string_delete (&decl);
3764
3765   if (success)
3766     /* Assume an integral type, if we're not sure.  */
3767     return (int) ((tk == tk_none) ? tk_integral : tk);
3768   else
3769     return 0;
3770 }
3771
3772 /* Given a pointer to a type string that represents a fundamental type
3773    argument (int, long, unsigned int, etc) in TYPE, a pointer to the
3774    string in which the demangled output is being built in RESULT, and
3775    the WORK structure, decode the types and add them to the result.
3776
3777    For example:
3778
3779         "Ci"    =>      "const int"
3780         "Sl"    =>      "signed long"
3781         "CUs"   =>      "const unsigned short"
3782
3783    The value returned is really a type_kind_t.  */
3784
3785 static int
3786 demangle_fund_type (work, mangled, result)
3787      struct work_stuff *work;
3788      const char **mangled;
3789      string *result;
3790 {
3791   int done = 0;
3792   int success = 1;
3793   char buf[10];
3794   unsigned int dec = 0;
3795   string btype;
3796   type_kind_t tk = tk_integral;
3797
3798   string_init (&btype);
3799
3800   /* First pick off any type qualifiers.  There can be more than one.  */
3801
3802   while (!done)
3803     {
3804       switch (**mangled)
3805         {
3806         case 'C':
3807         case 'V':
3808         case 'u':
3809           if (PRINT_ANSI_QUALIFIERS)
3810             {
3811               if (!STRING_EMPTY (result))
3812                 string_prepend (result, " ");
3813               string_prepend (result, demangle_qualifier (**mangled));
3814             }
3815           (*mangled)++;
3816           break;
3817         case 'U':
3818           (*mangled)++;
3819           APPEND_BLANK (result);
3820           string_append (result, "unsigned");
3821           break;
3822         case 'S': /* signed char only */
3823           (*mangled)++;
3824           APPEND_BLANK (result);
3825           string_append (result, "signed");
3826           break;
3827         case 'J':
3828           (*mangled)++;
3829           APPEND_BLANK (result);
3830           string_append (result, "__complex");
3831           break;
3832         default:
3833           done = 1;
3834           break;
3835         }
3836     }
3837
3838   /* Now pick off the fundamental type.  There can be only one.  */
3839
3840   switch (**mangled)
3841     {
3842     case '\0':
3843     case '_':
3844       break;
3845     case 'v':
3846       (*mangled)++;
3847       APPEND_BLANK (result);
3848       string_append (result, "void");
3849       break;
3850     case 'x':
3851       (*mangled)++;
3852       APPEND_BLANK (result);
3853       string_append (result, "long long");
3854       break;
3855     case 'l':
3856       (*mangled)++;
3857       APPEND_BLANK (result);
3858       string_append (result, "long");
3859       break;
3860     case 'i':
3861       (*mangled)++;
3862       APPEND_BLANK (result);
3863       string_append (result, "int");
3864       break;
3865     case 's':
3866       (*mangled)++;
3867       APPEND_BLANK (result);
3868       string_append (result, "short");
3869       break;
3870     case 'b':
3871       (*mangled)++;
3872       APPEND_BLANK (result);
3873       string_append (result, "bool");
3874       tk = tk_bool;
3875       break;
3876     case 'c':
3877       (*mangled)++;
3878       APPEND_BLANK (result);
3879       string_append (result, "char");
3880       tk = tk_char;
3881       break;
3882     case 'w':
3883       (*mangled)++;
3884       APPEND_BLANK (result);
3885       string_append (result, "wchar_t");
3886       tk = tk_char;
3887       break;
3888     case 'r':
3889       (*mangled)++;
3890       APPEND_BLANK (result);
3891       string_append (result, "long double");
3892       tk = tk_real;
3893       break;
3894     case 'd':
3895       (*mangled)++;
3896       APPEND_BLANK (result);
3897       string_append (result, "double");
3898       tk = tk_real;
3899       break;
3900     case 'f':
3901       (*mangled)++;
3902       APPEND_BLANK (result);
3903       string_append (result, "float");
3904       tk = tk_real;
3905       break;
3906     case 'G':
3907       (*mangled)++;
3908       if (!ISDIGIT ((unsigned char)**mangled))
3909         {
3910           success = 0;
3911           break;
3912         }
3913     case 'I':
3914       (*mangled)++;
3915       if (**mangled == '_')
3916         {
3917           int i;
3918           (*mangled)++;
3919           for (i = 0;
3920                i < (long) sizeof (buf) - 1 && **mangled && **mangled != '_';
3921                (*mangled)++, i++)
3922             buf[i] = **mangled;
3923           if (**mangled != '_')
3924             {
3925               success = 0;
3926               break;
3927             }
3928           buf[i] = '\0';
3929           (*mangled)++;
3930         }
3931       else
3932         {
3933           strncpy (buf, *mangled, 2);
3934           buf[2] = '\0';
3935           *mangled += min (strlen (*mangled), 2);
3936         }
3937       sscanf (buf, "%x", &dec);
3938       sprintf (buf, "int%u_t", dec);
3939       APPEND_BLANK (result);
3940       string_append (result, buf);
3941       break;
3942
3943       /* fall through */
3944       /* An explicit type, such as "6mytype" or "7integer" */
3945     case '0':
3946     case '1':
3947     case '2':
3948     case '3':
3949     case '4':
3950     case '5':
3951     case '6':
3952     case '7':
3953     case '8':
3954     case '9':
3955       {
3956         int bindex = register_Btype (work);
3957         string btype;
3958         string_init (&btype);
3959         if (demangle_class_name (work, mangled, &btype)) {
3960           remember_Btype (work, btype.b, LEN_STRING (&btype), bindex);
3961           APPEND_BLANK (result);
3962           string_appends (result, &btype);
3963         }
3964         else
3965           success = 0;
3966         string_delete (&btype);
3967         break;
3968       }
3969     case 't':
3970       {
3971         success = demangle_template (work, mangled, &btype, 0, 1, 1);
3972         string_appends (result, &btype);
3973         break;
3974       }
3975     default:
3976       success = 0;
3977       break;
3978     }
3979
3980   return success ? ((int) tk) : 0;
3981 }
3982
3983
3984 /* Handle a template's value parameter for HP aCC (extension from ARM)
3985    **mangled points to 'S' or 'U' */
3986
3987 static int
3988 do_hpacc_template_const_value (work, mangled, result)
3989      struct work_stuff *work ATTRIBUTE_UNUSED;
3990      const char **mangled;
3991      string *result;
3992 {
3993   int unsigned_const;
3994
3995   if (**mangled != 'U' && **mangled != 'S')
3996     return 0;
3997
3998   unsigned_const = (**mangled == 'U');
3999
4000   (*mangled)++;
4001
4002   switch (**mangled)
4003     {
4004       case 'N':
4005         string_append (result, "-");
4006         /* fall through */
4007       case 'P':
4008         (*mangled)++;
4009         break;
4010       case 'M':
4011         /* special case for -2^31 */
4012         string_append (result, "-2147483648");
4013         (*mangled)++;
4014         return 1;
4015       default:
4016         return 0;
4017     }
4018
4019   /* We have to be looking at an integer now */
4020   if (!(ISDIGIT ((unsigned char)**mangled)))
4021     return 0;
4022
4023   /* We only deal with integral values for template
4024      parameters -- so it's OK to look only for digits */
4025   while (ISDIGIT ((unsigned char)**mangled))
4026     {
4027       char_str[0] = **mangled;
4028       string_append (result, char_str);
4029       (*mangled)++;
4030     }
4031
4032   if (unsigned_const)
4033     string_append (result, "U");
4034
4035   /* FIXME? Some day we may have 64-bit (or larger :-) ) constants
4036      with L or LL suffixes. pai/1997-09-03 */
4037
4038   return 1; /* success */
4039 }
4040
4041 /* Handle a template's literal parameter for HP aCC (extension from ARM)
4042    **mangled is pointing to the 'A' */
4043
4044 static int
4045 do_hpacc_template_literal (work, mangled, result)
4046      struct work_stuff *work;
4047      const char **mangled;
4048      string *result;
4049 {
4050   int literal_len = 0;
4051   char * recurse;
4052   char * recurse_dem;
4053
4054   if (**mangled != 'A')
4055     return 0;
4056
4057   (*mangled)++;
4058
4059   literal_len = consume_count (mangled);
4060
4061   if (literal_len <= 0)
4062     return 0;
4063
4064   /* Literal parameters are names of arrays, functions, etc.  and the
4065      canonical representation uses the address operator */
4066   string_append (result, "&");
4067
4068   /* Now recursively demangle the literal name */
4069   recurse = (char *) xmalloc (literal_len + 1);
4070   memcpy (recurse, *mangled, literal_len);
4071   recurse[literal_len] = '\000';
4072
4073   recurse_dem = cplus_demangle (recurse, work->options);
4074
4075   if (recurse_dem)
4076     {
4077       string_append (result, recurse_dem);
4078       free (recurse_dem);
4079     }
4080   else
4081     {
4082       string_appendn (result, *mangled, literal_len);
4083     }
4084   (*mangled) += literal_len;
4085   free (recurse);
4086
4087   return 1;
4088 }
4089
4090 static int
4091 snarf_numeric_literal (args, arg)
4092      const char ** args;
4093      string * arg;
4094 {
4095   if (**args == '-')
4096     {
4097       char_str[0] = '-';
4098       string_append (arg, char_str);
4099       (*args)++;
4100     }
4101   else if (**args == '+')
4102     (*args)++;
4103
4104   if (!ISDIGIT ((unsigned char)**args))
4105     return 0;
4106
4107   while (ISDIGIT ((unsigned char)**args))
4108     {
4109       char_str[0] = **args;
4110       string_append (arg, char_str);
4111       (*args)++;
4112     }
4113
4114   return 1;
4115 }
4116
4117 /* Demangle the next argument, given by MANGLED into RESULT, which
4118    *should be an uninitialized* string.  It will be initialized here,
4119    and free'd should anything go wrong.  */
4120
4121 static int
4122 do_arg (work, mangled, result)
4123      struct work_stuff *work;
4124      const char **mangled;
4125      string *result;
4126 {
4127   /* Remember where we started so that we can record the type, for
4128      non-squangling type remembering.  */
4129   const char *start = *mangled;
4130
4131   string_init (result);
4132
4133   if (work->nrepeats > 0)
4134     {
4135       --work->nrepeats;
4136
4137       if (work->previous_argument == 0)
4138         return 0;
4139
4140       /* We want to reissue the previous type in this argument list.  */
4141       string_appends (result, work->previous_argument);
4142       return 1;
4143     }
4144
4145   if (**mangled == 'n')
4146     {
4147       /* A squangling-style repeat.  */
4148       (*mangled)++;
4149       work->nrepeats = consume_count(mangled);
4150
4151       if (work->nrepeats <= 0)
4152         /* This was not a repeat count after all.  */
4153         return 0;
4154
4155       if (work->nrepeats > 9)
4156         {
4157           if (**mangled != '_')
4158             /* The repeat count should be followed by an '_' in this
4159                case.  */
4160             return 0;
4161           else
4162             (*mangled)++;
4163         }
4164
4165       /* Now, the repeat is all set up.  */
4166       return do_arg (work, mangled, result);
4167     }
4168
4169   /* Save the result in WORK->previous_argument so that we can find it
4170      if it's repeated.  Note that saving START is not good enough: we
4171      do not want to add additional types to the back-referenceable
4172      type vector when processing a repeated type.  */
4173   if (work->previous_argument)
4174     string_clear (work->previous_argument);
4175   else
4176     {
4177       work->previous_argument = (string*) xmalloc (sizeof (string));
4178       string_init (work->previous_argument);
4179     }
4180
4181   if (!do_type (work, mangled, work->previous_argument))
4182     return 0;
4183
4184   string_appends (result, work->previous_argument);
4185
4186   remember_type (work, start, *mangled - start);
4187   return 1;
4188 }
4189
4190 static void
4191 remember_type (work, start, len)
4192      struct work_stuff *work;
4193      const char *start;
4194      int len;
4195 {
4196   char *tem;
4197
4198   if (work->forgetting_types)
4199     return;
4200
4201   if (work -> ntypes >= work -> typevec_size)
4202     {
4203       if (work -> typevec_size == 0)
4204         {
4205           work -> typevec_size = 3;
4206           work -> typevec
4207             = (char **) xmalloc (sizeof (char *) * work -> typevec_size);
4208         }
4209       else
4210         {
4211           work -> typevec_size *= 2;
4212           work -> typevec
4213             = (char **) xrealloc ((char *)work -> typevec,
4214                                   sizeof (char *) * work -> typevec_size);
4215         }
4216     }
4217   tem = xmalloc (len + 1);
4218   memcpy (tem, start, len);
4219   tem[len] = '\0';
4220   work -> typevec[work -> ntypes++] = tem;
4221 }
4222
4223
4224 /* Remember a K type class qualifier. */
4225 static void
4226 remember_Ktype (work, start, len)
4227      struct work_stuff *work;
4228      const char *start;
4229      int len;
4230 {
4231   char *tem;
4232
4233   if (work -> numk >= work -> ksize)
4234     {
4235       if (work -> ksize == 0)
4236         {
4237           work -> ksize = 5;
4238           work -> ktypevec
4239             = (char **) xmalloc (sizeof (char *) * work -> ksize);
4240         }
4241       else
4242         {
4243           work -> ksize *= 2;
4244           work -> ktypevec
4245             = (char **) xrealloc ((char *)work -> ktypevec,
4246                                   sizeof (char *) * work -> ksize);
4247         }
4248     }
4249   tem = xmalloc (len + 1);
4250   memcpy (tem, start, len);
4251   tem[len] = '\0';
4252   work -> ktypevec[work -> numk++] = tem;
4253 }
4254
4255 /* Register a B code, and get an index for it. B codes are registered
4256    as they are seen, rather than as they are completed, so map<temp<char> >
4257    registers map<temp<char> > as B0, and temp<char> as B1 */
4258
4259 static int
4260 register_Btype (work)
4261      struct work_stuff *work;
4262 {
4263   int ret;
4264
4265   if (work -> numb >= work -> bsize)
4266     {
4267       if (work -> bsize == 0)
4268         {
4269           work -> bsize = 5;
4270           work -> btypevec
4271             = (char **) xmalloc (sizeof (char *) * work -> bsize);
4272         }
4273       else
4274         {
4275           work -> bsize *= 2;
4276           work -> btypevec
4277             = (char **) xrealloc ((char *)work -> btypevec,
4278                                   sizeof (char *) * work -> bsize);
4279         }
4280     }
4281   ret = work -> numb++;
4282   work -> btypevec[ret] = NULL;
4283   return(ret);
4284 }
4285
4286 /* Store a value into a previously registered B code type. */
4287
4288 static void
4289 remember_Btype (work, start, len, index)
4290      struct work_stuff *work;
4291      const char *start;
4292      int len, index;
4293 {
4294   char *tem;
4295
4296   tem = xmalloc (len + 1);
4297   memcpy (tem, start, len);
4298   tem[len] = '\0';
4299   work -> btypevec[index] = tem;
4300 }
4301
4302 /* Lose all the info related to B and K type codes. */
4303 static void
4304 forget_B_and_K_types (work)
4305      struct work_stuff *work;
4306 {
4307   int i;
4308
4309   while (work -> numk > 0)
4310     {
4311       i = --(work -> numk);
4312       if (work -> ktypevec[i] != NULL)
4313         {
4314           free (work -> ktypevec[i]);
4315           work -> ktypevec[i] = NULL;
4316         }
4317     }
4318
4319   while (work -> numb > 0)
4320     {
4321       i = --(work -> numb);
4322       if (work -> btypevec[i] != NULL)
4323         {
4324           free (work -> btypevec[i]);
4325           work -> btypevec[i] = NULL;
4326         }
4327     }
4328 }
4329 /* Forget the remembered types, but not the type vector itself.  */
4330
4331 static void
4332 forget_types (work)
4333      struct work_stuff *work;
4334 {
4335   int i;
4336
4337   while (work -> ntypes > 0)
4338     {
4339       i = --(work -> ntypes);
4340       if (work -> typevec[i] != NULL)
4341         {
4342           free (work -> typevec[i]);
4343           work -> typevec[i] = NULL;
4344         }
4345     }
4346 }
4347
4348 /* Process the argument list part of the signature, after any class spec
4349    has been consumed, as well as the first 'F' character (if any).  For
4350    example:
4351
4352    "__als__3fooRT0"             =>      process "RT0"
4353    "complexfunc5__FPFPc_PFl_i"  =>      process "PFPc_PFl_i"
4354
4355    DECLP must be already initialised, usually non-empty.  It won't be freed
4356    on failure.
4357
4358    Note that g++ differs significantly from ARM and lucid style mangling
4359    with regards to references to previously seen types.  For example, given
4360    the source fragment:
4361
4362      class foo {
4363        public:
4364        foo::foo (int, foo &ia, int, foo &ib, int, foo &ic);
4365      };
4366
4367      foo::foo (int, foo &ia, int, foo &ib, int, foo &ic) { ia = ib = ic; }
4368      void foo (int, foo &ia, int, foo &ib, int, foo &ic) { ia = ib = ic; }
4369
4370    g++ produces the names:
4371
4372      __3fooiRT0iT2iT2
4373      foo__FiR3fooiT1iT1
4374
4375    while lcc (and presumably other ARM style compilers as well) produces:
4376
4377      foo__FiR3fooT1T2T1T2
4378      __ct__3fooFiR3fooT1T2T1T2
4379
4380    Note that g++ bases its type numbers starting at zero and counts all
4381    previously seen types, while lucid/ARM bases its type numbers starting
4382    at one and only considers types after it has seen the 'F' character
4383    indicating the start of the function args.  For lucid/ARM style, we
4384    account for this difference by discarding any previously seen types when
4385    we see the 'F' character, and subtracting one from the type number
4386    reference.
4387
4388  */
4389
4390 static int
4391 demangle_args (work, mangled, declp)
4392      struct work_stuff *work;
4393      const char **mangled;
4394      string *declp;
4395 {
4396   string arg;
4397   int need_comma = 0;
4398   int r;
4399   int t;
4400   const char *tem;
4401   char temptype;
4402
4403   if (PRINT_ARG_TYPES)
4404     {
4405       string_append (declp, "(");
4406       if (**mangled == '\0')
4407         {
4408           string_append (declp, "void");
4409         }
4410     }
4411
4412   while ((**mangled != '_' && **mangled != '\0' && **mangled != 'e')
4413          || work->nrepeats > 0)
4414     {
4415       if ((**mangled == 'N') || (**mangled == 'T'))
4416         {
4417           temptype = *(*mangled)++;
4418
4419           if (temptype == 'N')
4420             {
4421               if (!get_count (mangled, &r))
4422                 {
4423                   return (0);
4424                 }
4425             }
4426           else
4427             {
4428               r = 1;
4429             }
4430           if ((HP_DEMANGLING || ARM_DEMANGLING || EDG_DEMANGLING) && work -> ntypes >= 10)
4431             {
4432               /* If we have 10 or more types we might have more than a 1 digit
4433                  index so we'll have to consume the whole count here. This
4434                  will lose if the next thing is a type name preceded by a
4435                  count but it's impossible to demangle that case properly
4436                  anyway. Eg if we already have 12 types is T12Pc "(..., type1,
4437                  Pc, ...)"  or "(..., type12, char *, ...)" */
4438               if ((t = consume_count(mangled)) <= 0)
4439                 {
4440                   return (0);
4441                 }
4442             }
4443           else
4444             {
4445               if (!get_count (mangled, &t))
4446                 {
4447                   return (0);
4448                 }
4449             }
4450           if (LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING)
4451             {
4452               t--;
4453             }
4454           /* Validate the type index.  Protect against illegal indices from
4455              malformed type strings.  */
4456           if ((t < 0) || (t >= work -> ntypes))
4457             {
4458               return (0);
4459             }
4460           while (work->nrepeats > 0 || --r >= 0)
4461             {
4462               tem = work -> typevec[t];
4463               if (need_comma && PRINT_ARG_TYPES)
4464                 {
4465                   string_append (declp, ", ");
4466                 }
4467               if (!do_arg (work, &tem, &arg))
4468                 {
4469                   return (0);
4470                 }
4471               if (PRINT_ARG_TYPES)
4472                 {
4473                   string_appends (declp, &arg);
4474                 }
4475               string_delete (&arg);
4476               need_comma = 1;
4477             }
4478         }
4479       else
4480         {
4481           if (need_comma && PRINT_ARG_TYPES)
4482             string_append (declp, ", ");
4483           if (!do_arg (work, mangled, &arg))
4484             return (0);
4485           if (PRINT_ARG_TYPES)
4486             string_appends (declp, &arg);
4487           string_delete (&arg);
4488           need_comma = 1;
4489         }
4490     }
4491
4492   if (**mangled == 'e')
4493     {
4494       (*mangled)++;
4495       if (PRINT_ARG_TYPES)
4496         {
4497           if (need_comma)
4498             {
4499               string_append (declp, ",");
4500             }
4501           string_append (declp, "...");
4502         }
4503     }
4504
4505   if (PRINT_ARG_TYPES)
4506     {
4507       string_append (declp, ")");
4508     }
4509   return (1);
4510 }
4511
4512 /* Like demangle_args, but for demangling the argument lists of function
4513    and method pointers or references, not top-level declarations.  */
4514
4515 static int
4516 demangle_nested_args (work, mangled, declp)
4517      struct work_stuff *work;
4518      const char **mangled;
4519      string *declp;
4520 {
4521   string* saved_previous_argument;
4522   int result;
4523   int saved_nrepeats;
4524
4525   /* The G++ name-mangling algorithm does not remember types on nested
4526      argument lists, unless -fsquangling is used, and in that case the
4527      type vector updated by remember_type is not used.  So, we turn
4528      off remembering of types here.  */
4529   ++work->forgetting_types;
4530
4531   /* For the repeat codes used with -fsquangling, we must keep track of
4532      the last argument.  */
4533   saved_previous_argument = work->previous_argument;
4534   saved_nrepeats = work->nrepeats;
4535   work->previous_argument = 0;
4536   work->nrepeats = 0;
4537
4538   /* Actually demangle the arguments.  */
4539   result = demangle_args (work, mangled, declp);
4540
4541   /* Restore the previous_argument field.  */
4542   if (work->previous_argument)
4543     string_delete (work->previous_argument);
4544   work->previous_argument = saved_previous_argument;
4545   --work->forgetting_types;
4546   work->nrepeats = saved_nrepeats;
4547
4548   return result;
4549 }
4550
4551 static void
4552 demangle_function_name (work, mangled, declp, scan)
4553      struct work_stuff *work;
4554      const char **mangled;
4555      string *declp;
4556      const char *scan;
4557 {
4558   size_t i;
4559   string type;
4560   const char *tem;
4561
4562   string_appendn (declp, (*mangled), scan - (*mangled));
4563   string_need (declp, 1);
4564   *(declp -> p) = '\0';
4565
4566   /* Consume the function name, including the "__" separating the name
4567      from the signature.  We are guaranteed that SCAN points to the
4568      separator.  */
4569
4570   (*mangled) = scan + 2;
4571   /* We may be looking at an instantiation of a template function:
4572      foo__Xt1t2_Ft3t4, where t1, t2, ... are template arguments and a
4573      following _F marks the start of the function arguments.  Handle
4574      the template arguments first. */
4575
4576   if (HP_DEMANGLING && (**mangled == 'X'))
4577     {
4578       demangle_arm_hp_template (work, mangled, 0, declp);
4579       /* This leaves MANGLED pointing to the 'F' marking func args */
4580     }
4581
4582   if (LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING)
4583     {
4584
4585       /* See if we have an ARM style constructor or destructor operator.
4586          If so, then just record it, clear the decl, and return.
4587          We can't build the actual constructor/destructor decl until later,
4588          when we recover the class name from the signature.  */
4589
4590       if (strcmp (declp -> b, "__ct") == 0)
4591         {
4592           work -> constructor += 1;
4593           string_clear (declp);
4594           return;
4595         }
4596       else if (strcmp (declp -> b, "__dt") == 0)
4597         {
4598           work -> destructor += 1;
4599           string_clear (declp);
4600           return;
4601         }
4602     }
4603
4604   if (declp->p - declp->b >= 3
4605       && declp->b[0] == 'o'
4606       && declp->b[1] == 'p'
4607       && strchr (cplus_markers, declp->b[2]) != NULL)
4608     {
4609       /* see if it's an assignment expression */
4610       if (declp->p - declp->b >= 10 /* op$assign_ */
4611           && memcmp (declp->b + 3, "assign_", 7) == 0)
4612         {
4613           for (i = 0; i < ARRAY_SIZE (optable); i++)
4614             {
4615               int len = declp->p - declp->b - 10;
4616               if ((int) strlen (optable[i].in) == len
4617                   && memcmp (optable[i].in, declp->b + 10, len) == 0)
4618                 {
4619                   string_clear (declp);
4620                   string_append (declp, "operator");
4621                   string_append (declp, optable[i].out);
4622                   string_append (declp, "=");
4623                   break;
4624                 }
4625             }
4626         }
4627       else
4628         {
4629           for (i = 0; i < ARRAY_SIZE (optable); i++)
4630             {
4631               int len = declp->p - declp->b - 3;
4632               if ((int) strlen (optable[i].in) == len
4633                   && memcmp (optable[i].in, declp->b + 3, len) == 0)
4634                 {
4635                   string_clear (declp);
4636                   string_append (declp, "operator");
4637                   string_append (declp, optable[i].out);
4638                   break;
4639                 }
4640             }
4641         }
4642     }
4643   else if (declp->p - declp->b >= 5 && memcmp (declp->b, "type", 4) == 0
4644            && strchr (cplus_markers, declp->b[4]) != NULL)
4645     {
4646       /* type conversion operator */
4647       tem = declp->b + 5;
4648       if (do_type (work, &tem, &type))
4649         {
4650           string_clear (declp);
4651           string_append (declp, "operator ");
4652           string_appends (declp, &type);
4653           string_delete (&type);
4654         }
4655     }
4656   else if (declp->b[0] == '_' && declp->b[1] == '_'
4657            && declp->b[2] == 'o' && declp->b[3] == 'p')
4658     {
4659       /* ANSI.  */
4660       /* type conversion operator.  */
4661       tem = declp->b + 4;
4662       if (do_type (work, &tem, &type))
4663         {
4664           string_clear (declp);
4665           string_append (declp, "operator ");
4666           string_appends (declp, &type);
4667           string_delete (&type);
4668         }
4669     }
4670   else if (declp->b[0] == '_' && declp->b[1] == '_'
4671            && ISLOWER((unsigned char)declp->b[2])
4672            && ISLOWER((unsigned char)declp->b[3]))
4673     {
4674       if (declp->b[4] == '\0')
4675         {
4676           /* Operator.  */
4677           for (i = 0; i < ARRAY_SIZE (optable); i++)
4678             {
4679               if (strlen (optable[i].in) == 2
4680                   && memcmp (optable[i].in, declp->b + 2, 2) == 0)
4681                 {
4682                   string_clear (declp);
4683                   string_append (declp, "operator");
4684                   string_append (declp, optable[i].out);
4685                   break;
4686                 }
4687             }
4688         }
4689       else
4690         {
4691           if (declp->b[2] == 'a' && declp->b[5] == '\0')
4692             {
4693               /* Assignment.  */
4694               for (i = 0; i < ARRAY_SIZE (optable); i++)
4695                 {
4696                   if (strlen (optable[i].in) == 3
4697                       && memcmp (optable[i].in, declp->b + 2, 3) == 0)
4698                     {
4699                       string_clear (declp);
4700                       string_append (declp, "operator");
4701                       string_append (declp, optable[i].out);
4702                       break;
4703                     }
4704                 }
4705             }
4706         }
4707     }
4708 }
4709
4710 /* a mini string-handling package */
4711
4712 static void
4713 string_need (s, n)
4714      string *s;
4715      int n;
4716 {
4717   int tem;
4718
4719   if (s->b == NULL)
4720     {
4721       if (n < 32)
4722         {
4723           n = 32;
4724         }
4725       s->p = s->b = xmalloc (n);
4726       s->e = s->b + n;
4727     }
4728   else if (s->e - s->p < n)
4729     {
4730       tem = s->p - s->b;
4731       n += tem;
4732       n *= 2;
4733       s->b = xrealloc (s->b, n);
4734       s->p = s->b + tem;
4735       s->e = s->b + n;
4736     }
4737 }
4738
4739 static void
4740 string_delete (s)
4741      string *s;
4742 {
4743   if (s->b != NULL)
4744     {
4745       free (s->b);
4746       s->b = s->e = s->p = NULL;
4747     }
4748 }
4749
4750 static void
4751 string_init (s)
4752      string *s;
4753 {
4754   s->b = s->p = s->e = NULL;
4755 }
4756
4757 static void
4758 string_clear (s)
4759      string *s;
4760 {
4761   s->p = s->b;
4762 }
4763
4764 #if 0
4765
4766 static int
4767 string_empty (s)
4768      string *s;
4769 {
4770   return (s->b == s->p);
4771 }
4772
4773 #endif
4774
4775 static void
4776 string_append (p, s)
4777      string *p;
4778      const char *s;
4779 {
4780   int n;
4781   if (s == NULL || *s == '\0')
4782     return;
4783   n = strlen (s);
4784   string_need (p, n);
4785   memcpy (p->p, s, n);
4786   p->p += n;
4787 }
4788
4789 static void
4790 string_appends (p, s)
4791      string *p, *s;
4792 {
4793   int n;
4794
4795   if (s->b != s->p)
4796     {
4797       n = s->p - s->b;
4798       string_need (p, n);
4799       memcpy (p->p, s->b, n);
4800       p->p += n;
4801     }
4802 }
4803
4804 static void
4805 string_appendn (p, s, n)
4806      string *p;
4807      const char *s;
4808      int n;
4809 {
4810   if (n != 0)
4811     {
4812       string_need (p, n);
4813       memcpy (p->p, s, n);
4814       p->p += n;
4815     }
4816 }
4817
4818 static void
4819 string_prepend (p, s)
4820      string *p;
4821      const char *s;
4822 {
4823   if (s != NULL && *s != '\0')
4824     {
4825       string_prependn (p, s, strlen (s));
4826     }
4827 }
4828
4829 static void
4830 string_prepends (p, s)
4831      string *p, *s;
4832 {
4833   if (s->b != s->p)
4834     {
4835       string_prependn (p, s->b, s->p - s->b);
4836     }
4837 }
4838
4839 static void
4840 string_prependn (p, s, n)
4841      string *p;
4842      const char *s;
4843      int n;
4844 {
4845   char *q;
4846
4847   if (n != 0)
4848     {
4849       string_need (p, n);
4850       for (q = p->p - 1; q >= p->b; q--)
4851         {
4852           q[n] = q[0];
4853         }
4854       memcpy (p->b, s, n);
4855       p->p += n;
4856     }
4857 }
4858
4859 static void
4860 string_append_template_idx (s, idx)
4861      string *s;
4862      int idx;
4863 {
4864   char buf[INTBUF_SIZE + 1 /* 'T' */];
4865   sprintf(buf, "T%d", idx);
4866   string_append (s, buf);
4867 }
4868
4869 /* To generate a standalone demangler program for testing purposes,
4870    just compile and link this file with -DMAIN and libiberty.a.  When
4871    run, it demangles each command line arg, or each stdin string, and
4872    prints the result on stdout.  */
4873
4874 #ifdef MAIN
4875
4876 #include "getopt.h"
4877
4878 static const char *program_name;
4879 static const char *program_version = VERSION;
4880 static int flags = DMGL_PARAMS | DMGL_ANSI;
4881
4882 static void demangle_it PARAMS ((char *));
4883 static void usage PARAMS ((FILE *, int)) ATTRIBUTE_NORETURN;
4884 static void fatal PARAMS ((const char *)) ATTRIBUTE_NORETURN;
4885 static void print_demangler_list PARAMS ((FILE *));
4886
4887 static void
4888 demangle_it (mangled_name)
4889      char *mangled_name;
4890 {
4891   char *result;
4892
4893   result = cplus_demangle (mangled_name, flags);
4894   if (result == NULL)
4895     {
4896       printf ("%s\n", mangled_name);
4897     }
4898   else
4899     {
4900       printf ("%s\n", result);
4901       free (result);
4902     }
4903 }
4904
4905 static void 
4906 print_demangler_list (stream)
4907      FILE *stream;
4908 {
4909   const struct demangler_engine *demangler; 
4910
4911   fprintf (stream, "{%s", libiberty_demanglers->demangling_style_name);
4912   
4913   for (demangler = libiberty_demanglers + 1;
4914        demangler->demangling_style != unknown_demangling;
4915        ++demangler)
4916     fprintf (stream, ",%s", demangler->demangling_style_name);
4917
4918   fprintf (stream, "}");
4919 }
4920
4921 static void
4922 usage (stream, status)
4923      FILE *stream;
4924      int status;
4925 {
4926   fprintf (stream, "\
4927 Usage: %s [-_] [-n] [--strip-underscores] [--no-strip-underscores] \n",
4928            program_name);
4929
4930   fprintf (stream, "\
4931        [-s ");
4932   print_demangler_list (stream);
4933   fprintf (stream, "]\n");
4934
4935   fprintf (stream, "\
4936        [--format ");
4937   print_demangler_list (stream);
4938   fprintf (stream, "]\n");
4939
4940   fprintf (stream, "\
4941        [--help] [--version] [arg...]\n");
4942   exit (status);
4943 }
4944
4945 #define MBUF_SIZE 32767
4946 char mbuffer[MBUF_SIZE];
4947
4948 /* Defined in the automatically-generated underscore.c.  */
4949 extern int prepends_underscore;
4950
4951 int strip_underscore = 0;
4952
4953 static const struct option long_options[] = {
4954   {"strip-underscores", no_argument, 0, '_'},
4955   {"format", required_argument, 0, 's'},
4956   {"help", no_argument, 0, 'h'},
4957   {"no-strip-underscores", no_argument, 0, 'n'},
4958   {"version", no_argument, 0, 'v'},
4959   {0, no_argument, 0, 0}
4960 };
4961
4962 /* More 'friendly' abort that prints the line and file.
4963    config.h can #define abort fancy_abort if you like that sort of thing.  */
4964
4965 void
4966 fancy_abort ()
4967 {
4968   fatal ("Internal gcc abort.");
4969 }
4970
4971
4972 static const char *
4973 standard_symbol_characters PARAMS ((void));
4974
4975 static const char *
4976 hp_symbol_characters PARAMS ((void));
4977
4978 static const char *
4979 gnu_v3_symbol_characters PARAMS ((void));
4980
4981 /* Return the string of non-alnum characters that may occur 
4982    as a valid symbol component, in the standard assembler symbol
4983    syntax.  */
4984
4985 static const char *
4986 standard_symbol_characters ()
4987 {
4988   return "_$.";
4989 }
4990
4991
4992 /* Return the string of non-alnum characters that may occur
4993    as a valid symbol name component in an HP object file.
4994
4995    Note that, since HP's compiler generates object code straight from
4996    C++ source, without going through an assembler, its mangled
4997    identifiers can use all sorts of characters that no assembler would
4998    tolerate, so the alphabet this function creates is a little odd.
4999    Here are some sample mangled identifiers offered by HP:
5000
5001         typeid*__XT24AddressIndExpClassMember_
5002         [Vftptr]key:__dt__32OrdinaryCompareIndExpClassMemberFv
5003         __ct__Q2_9Elf64_Dyn18{unnamed.union.#1}Fv
5004
5005    This still seems really weird to me, since nowhere else in this
5006    file is there anything to recognize curly brackets, parens, etc.
5007    I've talked with Srikanth <srikanth@cup.hp.com>, and he assures me
5008    this is right, but I still strongly suspect that there's a
5009    misunderstanding here.
5010
5011    If we decide it's better for c++filt to use HP's assembler syntax
5012    to scrape identifiers out of its input, here's the definition of
5013    the symbol name syntax from the HP assembler manual:
5014
5015        Symbols are composed of uppercase and lowercase letters, decimal
5016        digits, dollar symbol, period (.), ampersand (&), pound sign(#) and
5017        underscore (_). A symbol can begin with a letter, digit underscore or
5018        dollar sign. If a symbol begins with a digit, it must contain a
5019        non-digit character.
5020
5021    So have fun.  */
5022 static const char *
5023 hp_symbol_characters ()
5024 {
5025   return "_$.<>#,*&[]:(){}";
5026 }
5027
5028
5029 /* Return the string of non-alnum characters that may occur 
5030    as a valid symbol component in the GNU C++ V3 ABI mangling
5031    scheme.  */
5032
5033 static const char *
5034 gnu_v3_symbol_characters ()
5035 {
5036   return "_$.";
5037 }
5038
5039
5040 extern int main PARAMS ((int, char **));
5041
5042 int
5043 main (argc, argv)
5044      int argc;
5045      char **argv;
5046 {
5047   char *result;
5048   int c;
5049   const char *valid_symbols;
5050   enum demangling_styles style = auto_demangling;
5051
5052   program_name = argv[0];
5053
5054   strip_underscore = prepends_underscore;
5055
5056   while ((c = getopt_long (argc, argv, "_ns:", long_options, (int *) 0)) != EOF)
5057     {
5058       switch (c)
5059         {
5060         case '?':
5061           usage (stderr, 1);
5062           break;
5063         case 'h':
5064           usage (stdout, 0);
5065         case 'n':
5066           strip_underscore = 0;
5067           break;
5068         case 'v':
5069           printf ("GNU %s (C++ demangler), version %s\n", program_name, program_version);
5070           return (0);
5071         case '_':
5072           strip_underscore = 1;
5073           break;
5074         case 's':
5075           {
5076             style = cplus_demangle_name_to_style (optarg);
5077             if (style == unknown_demangling)
5078               {
5079                 fprintf (stderr, "%s: unknown demangling style `%s'\n",
5080                          program_name, optarg);
5081                 return (1);
5082               }
5083             else
5084               cplus_demangle_set_style (style);
5085           }
5086           break;
5087         }
5088     }
5089
5090   if (optind < argc)
5091     {
5092       cplus_demangle_v3_p = cplus_demangle_v3_type;
5093       for ( ; optind < argc; optind++)
5094         {
5095           demangle_it (argv[optind]);
5096         }
5097     }
5098   else
5099     {
5100       switch (current_demangling_style)
5101         {
5102         case gnu_demangling:
5103         case lucid_demangling:
5104         case arm_demangling:
5105         case java_demangling:
5106         case edg_demangling:
5107         case gnat_demangling:
5108         case auto_demangling:
5109           valid_symbols = standard_symbol_characters ();
5110           break;
5111         case hp_demangling:
5112           valid_symbols = hp_symbol_characters ();
5113           break;
5114         case gnu_v3_demangling:
5115           valid_symbols = gnu_v3_symbol_characters ();
5116           break;
5117         default:
5118           /* Folks should explicitly indicate the appropriate alphabet for
5119              each demangling.  Providing a default would allow the
5120              question to go unconsidered.  */
5121           abort ();
5122         }
5123
5124       for (;;)
5125         {
5126           int i = 0;
5127           c = getchar ();
5128           /* Try to read a label.  */
5129           while (c != EOF && (ISALNUM (c) || strchr (valid_symbols, c)))
5130             {
5131               if (i >= MBUF_SIZE-1)
5132                 break;
5133               mbuffer[i++] = c;
5134               c = getchar ();
5135             }
5136           if (i > 0)
5137             {
5138               int skip_first = 0;
5139
5140               if (mbuffer[0] == '.' || mbuffer[0] == '$')
5141                 ++skip_first;
5142               if (strip_underscore && mbuffer[skip_first] == '_')
5143                 ++skip_first;
5144
5145               if (skip_first > i)
5146                 skip_first = i;
5147
5148               mbuffer[i] = 0;
5149               flags |= (int) style;
5150               result = cplus_demangle (mbuffer + skip_first, flags);
5151               if (result)
5152                 {
5153                   if (mbuffer[0] == '.')
5154                     putc ('.', stdout);
5155                   fputs (result, stdout);
5156                   free (result);
5157                 }
5158               else
5159                 fputs (mbuffer, stdout);
5160
5161               fflush (stdout);
5162             }
5163           if (c == EOF)
5164             break;
5165           putchar (c);
5166           fflush (stdout);
5167         }
5168     }
5169
5170   return (0);
5171 }
5172
5173 static void
5174 fatal (str)
5175      const char *str;
5176 {
5177   fprintf (stderr, "%s: %s\n", program_name, str);
5178   exit (1);
5179 }
5180
5181 PTR
5182 xmalloc (size)
5183   size_t size;
5184 {
5185   register PTR value = (PTR) malloc (size);
5186   if (value == 0)
5187     fatal ("virtual memory exhausted");
5188   return value;
5189 }
5190
5191 PTR
5192 xrealloc (ptr, size)
5193   PTR ptr;
5194   size_t size;
5195 {
5196   register PTR value = (PTR) realloc (ptr, size);
5197   if (value == 0)
5198     fatal ("virtual memory exhausted");
5199   return value;
5200 }
5201 #endif  /* main */