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