Remove cleanups from cp-support.c
[external/binutils.git] / gdb / cp-support.c
1 /* Helper routines for C++ support in GDB.
2    Copyright (C) 2002-2017 Free Software Foundation, Inc.
3
4    Contributed by MontaVista Software.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "cp-support.h"
23 #include "demangle.h"
24 #include "gdbcmd.h"
25 #include "dictionary.h"
26 #include "objfiles.h"
27 #include "frame.h"
28 #include "symtab.h"
29 #include "block.h"
30 #include "complaints.h"
31 #include "gdbtypes.h"
32 #include "expression.h"
33 #include "value.h"
34 #include "cp-abi.h"
35 #include "namespace.h"
36 #include <signal.h>
37 #include "gdb_setjmp.h"
38 #include "safe-ctype.h"
39
40 #define d_left(dc) (dc)->u.s_binary.left
41 #define d_right(dc) (dc)->u.s_binary.right
42
43 /* Functions related to demangled name parsing.  */
44
45 static unsigned int cp_find_first_component_aux (const char *name,
46                                                  int permissive);
47
48 static void demangled_name_complaint (const char *name);
49
50 /* Functions/variables related to overload resolution.  */
51
52 static int sym_return_val_size = -1;
53 static int sym_return_val_index;
54 static struct symbol **sym_return_val;
55
56 static void overload_list_add_symbol (struct symbol *sym,
57                                       const char *oload_name);
58
59 static void make_symbol_overload_list_using (const char *func_name,
60                                              const char *the_namespace);
61
62 static void make_symbol_overload_list_qualified (const char *func_name);
63
64 /* The list of "maint cplus" commands.  */
65
66 struct cmd_list_element *maint_cplus_cmd_list = NULL;
67
68 /* The actual commands.  */
69
70 static void maint_cplus_command (char *arg, int from_tty);
71
72 /* A list of typedefs which should not be substituted by replace_typedefs.  */
73 static const char * const ignore_typedefs[] =
74   {
75     "std::istream", "std::iostream", "std::ostream", "std::string"
76   };
77
78 static void
79   replace_typedefs (struct demangle_parse_info *info,
80                     struct demangle_component *ret_comp,
81                     canonicalization_ftype *finder,
82                     void *data);
83
84 /* A convenience function to copy STRING into OBSTACK, returning a pointer
85    to the newly allocated string and saving the number of bytes saved in LEN.
86
87    It does not copy the terminating '\0' byte!  */
88
89 static char *
90 copy_string_to_obstack (struct obstack *obstack, const char *string,
91                         long *len)
92 {
93   *len = strlen (string);
94   return (char *) obstack_copy (obstack, string, *len);
95 }
96
97 /* Return 1 if STRING is clearly already in canonical form.  This
98    function is conservative; things which it does not recognize are
99    assumed to be non-canonical, and the parser will sort them out
100    afterwards.  This speeds up the critical path for alphanumeric
101    identifiers.  */
102
103 static int
104 cp_already_canonical (const char *string)
105 {
106   /* Identifier start character [a-zA-Z_].  */
107   if (!ISIDST (string[0]))
108     return 0;
109
110   /* These are the only two identifiers which canonicalize to other
111      than themselves or an error: unsigned -> unsigned int and
112      signed -> int.  */
113   if (string[0] == 'u' && strcmp (&string[1], "nsigned") == 0)
114     return 0;
115   else if (string[0] == 's' && strcmp (&string[1], "igned") == 0)
116     return 0;
117
118   /* Identifier character [a-zA-Z0-9_].  */
119   while (ISIDNUM (string[1]))
120     string++;
121
122   if (string[1] == '\0')
123     return 1;
124   else
125     return 0;
126 }
127
128 /* Inspect the given RET_COMP for its type.  If it is a typedef,
129    replace the node with the typedef's tree.
130
131    Returns 1 if any typedef substitutions were made, 0 otherwise.  */
132
133 static int
134 inspect_type (struct demangle_parse_info *info,
135               struct demangle_component *ret_comp,
136               canonicalization_ftype *finder,
137               void *data)
138 {
139   int i;
140   char *name;
141   struct symbol *sym;
142
143   /* Copy the symbol's name from RET_COMP and look it up
144      in the symbol table.  */
145   name = (char *) alloca (ret_comp->u.s_name.len + 1);
146   memcpy (name, ret_comp->u.s_name.s, ret_comp->u.s_name.len);
147   name[ret_comp->u.s_name.len] = '\0';
148
149   /* Ignore any typedefs that should not be substituted.  */
150   for (i = 0; i < ARRAY_SIZE (ignore_typedefs); ++i)
151     {
152       if (strcmp (name, ignore_typedefs[i]) == 0)
153         return 0;
154     }
155
156   sym = NULL;
157
158   TRY
159     {
160       sym = lookup_symbol (name, 0, VAR_DOMAIN, 0).symbol;
161     }
162   CATCH (except, RETURN_MASK_ALL)
163     {
164       return 0;
165     }
166   END_CATCH
167
168   if (sym != NULL)
169     {
170       struct type *otype = SYMBOL_TYPE (sym);
171
172       if (finder != NULL)
173         {
174           const char *new_name = (*finder) (otype, data);
175
176           if (new_name != NULL)
177             {
178               ret_comp->u.s_name.s = new_name;
179               ret_comp->u.s_name.len = strlen (new_name);
180               return 1;
181             }
182
183           return 0;
184         }
185
186       /* If the type is a typedef or namespace alias, replace it.  */
187       if (TYPE_CODE (otype) == TYPE_CODE_TYPEDEF
188           || TYPE_CODE (otype) == TYPE_CODE_NAMESPACE)
189         {
190           long len;
191           int is_anon;
192           struct type *type;
193           std::unique_ptr<demangle_parse_info> i;
194
195           /* Get the real type of the typedef.  */
196           type = check_typedef (otype);
197
198           /* If the symbol is a namespace and its type name is no different
199              than the name we looked up, this symbol is not a namespace
200              alias and does not need to be substituted.  */
201           if (TYPE_CODE (otype) == TYPE_CODE_NAMESPACE
202               && strcmp (TYPE_NAME (type), name) == 0)
203             return 0;
204
205           is_anon = (TYPE_TAG_NAME (type) == NULL
206                      && (TYPE_CODE (type) == TYPE_CODE_ENUM
207                          || TYPE_CODE (type) == TYPE_CODE_STRUCT
208                          || TYPE_CODE (type) == TYPE_CODE_UNION));
209           if (is_anon)
210             {
211               struct type *last = otype;
212
213               /* Find the last typedef for the type.  */
214               while (TYPE_TARGET_TYPE (last) != NULL
215                      && (TYPE_CODE (TYPE_TARGET_TYPE (last))
216                          == TYPE_CODE_TYPEDEF))
217                 last = TYPE_TARGET_TYPE (last);
218
219               /* If there is only one typedef for this anonymous type,
220                  do not substitute it.  */
221               if (type == otype)
222                 return 0;
223               else
224                 /* Use the last typedef seen as the type for this
225                    anonymous type.  */
226                 type = last;
227             }
228
229           string_file buf;
230           TRY
231             {
232               type_print (type, "", &buf, -1);
233             }
234           /* If type_print threw an exception, there is little point
235              in continuing, so just bow out gracefully.  */
236           CATCH (except, RETURN_MASK_ERROR)
237             {
238               return 0;
239             }
240           END_CATCH
241
242           len = buf.size ();
243           name = (char *) obstack_copy0 (&info->obstack, buf.c_str (), len);
244
245           /* Turn the result into a new tree.  Note that this
246              tree will contain pointers into NAME, so NAME cannot
247              be free'd until all typedef conversion is done and
248              the final result is converted into a string.  */
249           i = cp_demangled_name_to_comp (name, NULL);
250           if (i != NULL)
251             {
252               /* Merge the two trees.  */
253               cp_merge_demangle_parse_infos (info, ret_comp, i.get ());
254
255               /* Replace any newly introduced typedefs -- but not
256                  if the type is anonymous (that would lead to infinite
257                  looping).  */
258               if (!is_anon)
259                 replace_typedefs (info, ret_comp, finder, data);
260             }
261           else
262             {
263               /* This shouldn't happen unless the type printer has
264                  output something that the name parser cannot grok.
265                  Nonetheless, an ounce of prevention...
266
267                  Canonicalize the name again, and store it in the
268                  current node (RET_COMP).  */
269               std::string canon = cp_canonicalize_string_no_typedefs (name);
270
271               if (!canon.empty ())
272                 {
273                   /* Copy the canonicalization into the obstack.  */
274                   name = copy_string_to_obstack (&info->obstack, canon.c_str (), &len);
275                 }
276
277               ret_comp->u.s_name.s = name;
278               ret_comp->u.s_name.len = len;
279             }
280
281           return 1;
282         }
283     }
284
285   return 0;
286 }
287
288 /* Replace any typedefs appearing in the qualified name
289    (DEMANGLE_COMPONENT_QUAL_NAME) represented in RET_COMP for the name parse
290    given in INFO.  */
291
292 static void
293 replace_typedefs_qualified_name (struct demangle_parse_info *info,
294                                  struct demangle_component *ret_comp,
295                                  canonicalization_ftype *finder,
296                                  void *data)
297 {
298   string_file buf;
299   struct demangle_component *comp = ret_comp;
300
301   /* Walk each node of the qualified name, reconstructing the name of
302      this element.  With every node, check for any typedef substitutions.
303      If a substitution has occurred, replace the qualified name node
304      with a DEMANGLE_COMPONENT_NAME node representing the new, typedef-
305      substituted name.  */
306   while (comp->type == DEMANGLE_COMPONENT_QUAL_NAME)
307     {
308       if (d_left (comp)->type == DEMANGLE_COMPONENT_NAME)
309         {
310           struct demangle_component newobj;
311
312           buf.write (d_left (comp)->u.s_name.s, d_left (comp)->u.s_name.len);
313           newobj.type = DEMANGLE_COMPONENT_NAME;
314           newobj.u.s_name.s
315             = (char *) obstack_copy0 (&info->obstack,
316                                       buf.c_str (), buf.size ());
317           newobj.u.s_name.len = buf.size ();
318           if (inspect_type (info, &newobj, finder, data))
319             {
320               char *s;
321               long slen;
322
323               /* A typedef was substituted in NEW.  Convert it to a
324                  string and replace the top DEMANGLE_COMPONENT_QUAL_NAME
325                  node.  */
326
327               buf.clear ();
328               gdb::unique_xmalloc_ptr<char> n
329                 = cp_comp_to_string (&newobj, 100);
330               if (n == NULL)
331                 {
332                   /* If something went astray, abort typedef substitutions.  */
333                   return;
334                 }
335
336               s = copy_string_to_obstack (&info->obstack, n.get (), &slen);
337
338               d_left (ret_comp)->type = DEMANGLE_COMPONENT_NAME;
339               d_left (ret_comp)->u.s_name.s = s;
340               d_left (ret_comp)->u.s_name.len = slen;
341               d_right (ret_comp) = d_right (comp);
342               comp = ret_comp;
343               continue;
344             }
345         }
346       else
347         {
348           /* The current node is not a name, so simply replace any
349              typedefs in it.  Then print it to the stream to continue
350              checking for more typedefs in the tree.  */
351           replace_typedefs (info, d_left (comp), finder, data);
352           gdb::unique_xmalloc_ptr<char> name
353             = cp_comp_to_string (d_left (comp), 100);
354           if (name == NULL)
355             {
356               /* If something went astray, abort typedef substitutions.  */
357               return;
358             }
359           buf.puts (name.get ());
360         }
361
362       buf.write ("::", 2);
363       comp = d_right (comp);
364     }
365
366   /* If the next component is DEMANGLE_COMPONENT_NAME, save the qualified
367      name assembled above and append the name given by COMP.  Then use this
368      reassembled name to check for a typedef.  */
369
370   if (comp->type == DEMANGLE_COMPONENT_NAME)
371     {
372       buf.write (comp->u.s_name.s, comp->u.s_name.len);
373
374       /* Replace the top (DEMANGLE_COMPONENT_QUAL_NAME) node
375          with a DEMANGLE_COMPONENT_NAME node containing the whole
376          name.  */
377       ret_comp->type = DEMANGLE_COMPONENT_NAME;
378       ret_comp->u.s_name.s
379         = (char *) obstack_copy0 (&info->obstack,
380                                   buf.c_str (), buf.size ());
381       ret_comp->u.s_name.len = buf.size ();
382       inspect_type (info, ret_comp, finder, data);
383     }
384   else
385     replace_typedefs (info, comp, finder, data);
386 }
387
388
389 /* A function to check const and volatile qualifiers for argument types.
390
391    "Parameter declarations that differ only in the presence
392    or absence of `const' and/or `volatile' are equivalent."
393    C++ Standard N3290, clause 13.1.3 #4.  */
394
395 static void
396 check_cv_qualifiers (struct demangle_component *ret_comp)
397 {
398   while (d_left (ret_comp) != NULL
399          && (d_left (ret_comp)->type == DEMANGLE_COMPONENT_CONST
400              || d_left (ret_comp)->type == DEMANGLE_COMPONENT_VOLATILE))
401     {
402       d_left (ret_comp) = d_left (d_left (ret_comp));
403     }
404 }
405
406 /* Walk the parse tree given by RET_COMP, replacing any typedefs with
407    their basic types.  */
408
409 static void
410 replace_typedefs (struct demangle_parse_info *info,
411                   struct demangle_component *ret_comp,
412                   canonicalization_ftype *finder,
413                   void *data)
414 {
415   if (ret_comp)
416     {
417       if (finder != NULL
418           && (ret_comp->type == DEMANGLE_COMPONENT_NAME
419               || ret_comp->type == DEMANGLE_COMPONENT_QUAL_NAME
420               || ret_comp->type == DEMANGLE_COMPONENT_TEMPLATE
421               || ret_comp->type == DEMANGLE_COMPONENT_BUILTIN_TYPE))
422         {
423           gdb::unique_xmalloc_ptr<char> local_name
424             = cp_comp_to_string (ret_comp, 10);
425
426           if (local_name != NULL)
427             {
428               struct symbol *sym = NULL;
429
430               sym = NULL;
431               TRY
432                 {
433                   sym = lookup_symbol (local_name.get (), 0,
434                                        VAR_DOMAIN, 0).symbol;
435                 }
436               CATCH (except, RETURN_MASK_ALL)
437                 {
438                 }
439               END_CATCH
440
441               if (sym != NULL)
442                 {
443                   struct type *otype = SYMBOL_TYPE (sym);
444                   const char *new_name = (*finder) (otype, data);
445
446                   if (new_name != NULL)
447                     {
448                       ret_comp->type = DEMANGLE_COMPONENT_NAME;
449                       ret_comp->u.s_name.s = new_name;
450                       ret_comp->u.s_name.len = strlen (new_name);
451                       return;
452                     }
453                 }
454             }
455         }
456
457       switch (ret_comp->type)
458         {
459         case DEMANGLE_COMPONENT_ARGLIST:
460           check_cv_qualifiers (ret_comp);
461           /* Fall through */
462
463         case DEMANGLE_COMPONENT_FUNCTION_TYPE:
464         case DEMANGLE_COMPONENT_TEMPLATE:
465         case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
466         case DEMANGLE_COMPONENT_TYPED_NAME:
467           replace_typedefs (info, d_left (ret_comp), finder, data);
468           replace_typedefs (info, d_right (ret_comp), finder, data);
469           break;
470
471         case DEMANGLE_COMPONENT_NAME:
472           inspect_type (info, ret_comp, finder, data);
473           break;
474
475         case DEMANGLE_COMPONENT_QUAL_NAME:
476           replace_typedefs_qualified_name (info, ret_comp, finder, data);
477           break;
478
479         case DEMANGLE_COMPONENT_LOCAL_NAME:
480         case DEMANGLE_COMPONENT_CTOR:
481         case DEMANGLE_COMPONENT_ARRAY_TYPE:
482         case DEMANGLE_COMPONENT_PTRMEM_TYPE:
483           replace_typedefs (info, d_right (ret_comp), finder, data);
484           break;
485
486         case DEMANGLE_COMPONENT_CONST:
487         case DEMANGLE_COMPONENT_RESTRICT:
488         case DEMANGLE_COMPONENT_VOLATILE:
489         case DEMANGLE_COMPONENT_VOLATILE_THIS:
490         case DEMANGLE_COMPONENT_CONST_THIS:
491         case DEMANGLE_COMPONENT_RESTRICT_THIS:
492         case DEMANGLE_COMPONENT_POINTER:
493         case DEMANGLE_COMPONENT_REFERENCE:
494         case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
495           replace_typedefs (info, d_left (ret_comp), finder, data);
496           break;
497
498         default:
499           break;
500         }
501     }
502 }
503
504 /* Parse STRING and convert it to canonical form, resolving any
505    typedefs.  If parsing fails, or if STRING is already canonical,
506    return the empty string.  Otherwise return the canonical form.  If
507    FINDER is not NULL, then type components are passed to FINDER to be
508    looked up.  DATA is passed verbatim to FINDER.  */
509
510 std::string
511 cp_canonicalize_string_full (const char *string,
512                              canonicalization_ftype *finder,
513                              void *data)
514 {
515   std::string ret;
516   unsigned int estimated_len;
517   std::unique_ptr<demangle_parse_info> info;
518
519   estimated_len = strlen (string) * 2;
520   info = cp_demangled_name_to_comp (string, NULL);
521   if (info != NULL)
522     {
523       /* Replace all the typedefs in the tree.  */
524       replace_typedefs (info.get (), info->tree, finder, data);
525
526       /* Convert the tree back into a string.  */
527       gdb::unique_xmalloc_ptr<char> us = cp_comp_to_string (info->tree,
528                                                             estimated_len);
529       gdb_assert (us);
530
531       ret = us.get ();
532       /* Finally, compare the original string with the computed
533          name, returning NULL if they are the same.  */
534       if (ret == string)
535         return std::string ();
536     }
537
538   return ret;
539 }
540
541 /* Like cp_canonicalize_string_full, but always passes NULL for
542    FINDER.  */
543
544 std::string
545 cp_canonicalize_string_no_typedefs (const char *string)
546 {
547   return cp_canonicalize_string_full (string, NULL, NULL);
548 }
549
550 /* Parse STRING and convert it to canonical form.  If parsing fails,
551    or if STRING is already canonical, return the empty string.
552    Otherwise return the canonical form.  */
553
554 std::string
555 cp_canonicalize_string (const char *string)
556 {
557   std::unique_ptr<demangle_parse_info> info;
558   unsigned int estimated_len;
559
560   if (cp_already_canonical (string))
561     return std::string ();
562
563   info = cp_demangled_name_to_comp (string, NULL);
564   if (info == NULL)
565     return std::string ();
566
567   estimated_len = strlen (string) * 2;
568   gdb::unique_xmalloc_ptr<char> us (cp_comp_to_string (info->tree,
569                                                        estimated_len));
570
571   if (!us)
572     {
573       warning (_("internal error: string \"%s\" failed to be canonicalized"),
574                string);
575       return std::string ();
576     }
577
578   std::string ret (us.get ());
579
580   if (ret == string)
581     return std::string ();
582
583   return ret;
584 }
585
586 /* Convert a mangled name to a demangle_component tree.  *MEMORY is
587    set to the block of used memory that should be freed when finished
588    with the tree.  DEMANGLED_P is set to the char * that should be
589    freed when finished with the tree, or NULL if none was needed.
590    OPTIONS will be passed to the demangler.  */
591
592 static std::unique_ptr<demangle_parse_info>
593 mangled_name_to_comp (const char *mangled_name, int options,
594                       void **memory, char **demangled_p)
595 {
596   char *demangled_name;
597
598   /* If it looks like a v3 mangled name, then try to go directly
599      to trees.  */
600   if (mangled_name[0] == '_' && mangled_name[1] == 'Z')
601     {
602       struct demangle_component *ret;
603
604       ret = cplus_demangle_v3_components (mangled_name,
605                                           options, memory);
606       if (ret)
607         {
608           std::unique_ptr<demangle_parse_info> info (new demangle_parse_info);
609           info->tree = ret;
610           *demangled_p = NULL;
611           return info;
612         }
613     }
614
615   /* If it doesn't, or if that failed, then try to demangle the
616      name.  */
617   demangled_name = gdb_demangle (mangled_name, options);
618   if (demangled_name == NULL)
619    return NULL;
620   
621   /* If we could demangle the name, parse it to build the component
622      tree.  */
623   std::unique_ptr<demangle_parse_info> info
624     = cp_demangled_name_to_comp (demangled_name, NULL);
625
626   if (info == NULL)
627     {
628       xfree (demangled_name);
629       return NULL;
630     }
631
632   *demangled_p = demangled_name;
633   return info;
634 }
635
636 /* Return the name of the class containing method PHYSNAME.  */
637
638 char *
639 cp_class_name_from_physname (const char *physname)
640 {
641   void *storage = NULL;
642   char *demangled_name = NULL;
643   gdb::unique_xmalloc_ptr<char> ret;
644   struct demangle_component *ret_comp, *prev_comp, *cur_comp;
645   std::unique_ptr<demangle_parse_info> info;
646   int done;
647
648   info = mangled_name_to_comp (physname, DMGL_ANSI,
649                                &storage, &demangled_name);
650   if (info == NULL)
651     return NULL;
652
653   done = 0;
654   ret_comp = info->tree;
655
656   /* First strip off any qualifiers, if we have a function or
657      method.  */
658   while (!done)
659     switch (ret_comp->type)
660       {
661       case DEMANGLE_COMPONENT_CONST:
662       case DEMANGLE_COMPONENT_RESTRICT:
663       case DEMANGLE_COMPONENT_VOLATILE:
664       case DEMANGLE_COMPONENT_CONST_THIS:
665       case DEMANGLE_COMPONENT_RESTRICT_THIS:
666       case DEMANGLE_COMPONENT_VOLATILE_THIS:
667       case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
668         ret_comp = d_left (ret_comp);
669         break;
670       default:
671         done = 1;
672         break;
673       }
674
675   /* If what we have now is a function, discard the argument list.  */
676   if (ret_comp->type == DEMANGLE_COMPONENT_TYPED_NAME)
677     ret_comp = d_left (ret_comp);
678
679   /* If what we have now is a template, strip off the template
680      arguments.  The left subtree may be a qualified name.  */
681   if (ret_comp->type == DEMANGLE_COMPONENT_TEMPLATE)
682     ret_comp = d_left (ret_comp);
683
684   /* What we have now should be a name, possibly qualified.
685      Additional qualifiers could live in the left subtree or the right
686      subtree.  Find the last piece.  */
687   done = 0;
688   prev_comp = NULL;
689   cur_comp = ret_comp;
690   while (!done)
691     switch (cur_comp->type)
692       {
693       case DEMANGLE_COMPONENT_QUAL_NAME:
694       case DEMANGLE_COMPONENT_LOCAL_NAME:
695         prev_comp = cur_comp;
696         cur_comp = d_right (cur_comp);
697         break;
698       case DEMANGLE_COMPONENT_TEMPLATE:
699       case DEMANGLE_COMPONENT_NAME:
700       case DEMANGLE_COMPONENT_CTOR:
701       case DEMANGLE_COMPONENT_DTOR:
702       case DEMANGLE_COMPONENT_OPERATOR:
703       case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
704         done = 1;
705         break;
706       default:
707         done = 1;
708         cur_comp = NULL;
709         break;
710       }
711
712   if (cur_comp != NULL && prev_comp != NULL)
713     {
714       /* We want to discard the rightmost child of PREV_COMP.  */
715       *prev_comp = *d_left (prev_comp);
716       /* The ten is completely arbitrary; we don't have a good
717          estimate.  */
718       ret = cp_comp_to_string (ret_comp, 10);
719     }
720
721   xfree (storage);
722   xfree (demangled_name);
723   return ret.release ();
724 }
725
726 /* Return the child of COMP which is the basename of a method,
727    variable, et cetera.  All scope qualifiers are discarded, but
728    template arguments will be included.  The component tree may be
729    modified.  */
730
731 static struct demangle_component *
732 unqualified_name_from_comp (struct demangle_component *comp)
733 {
734   struct demangle_component *ret_comp = comp, *last_template;
735   int done;
736
737   done = 0;
738   last_template = NULL;
739   while (!done)
740     switch (ret_comp->type)
741       {
742       case DEMANGLE_COMPONENT_QUAL_NAME:
743       case DEMANGLE_COMPONENT_LOCAL_NAME:
744         ret_comp = d_right (ret_comp);
745         break;
746       case DEMANGLE_COMPONENT_TYPED_NAME:
747         ret_comp = d_left (ret_comp);
748         break;
749       case DEMANGLE_COMPONENT_TEMPLATE:
750         gdb_assert (last_template == NULL);
751         last_template = ret_comp;
752         ret_comp = d_left (ret_comp);
753         break;
754       case DEMANGLE_COMPONENT_CONST:
755       case DEMANGLE_COMPONENT_RESTRICT:
756       case DEMANGLE_COMPONENT_VOLATILE:
757       case DEMANGLE_COMPONENT_CONST_THIS:
758       case DEMANGLE_COMPONENT_RESTRICT_THIS:
759       case DEMANGLE_COMPONENT_VOLATILE_THIS:
760       case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
761         ret_comp = d_left (ret_comp);
762         break;
763       case DEMANGLE_COMPONENT_NAME:
764       case DEMANGLE_COMPONENT_CTOR:
765       case DEMANGLE_COMPONENT_DTOR:
766       case DEMANGLE_COMPONENT_OPERATOR:
767       case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
768         done = 1;
769         break;
770       default:
771         return NULL;
772         break;
773       }
774
775   if (last_template)
776     {
777       d_left (last_template) = ret_comp;
778       return last_template;
779     }
780
781   return ret_comp;
782 }
783
784 /* Return the name of the method whose linkage name is PHYSNAME.  */
785
786 char *
787 method_name_from_physname (const char *physname)
788 {
789   void *storage = NULL;
790   char *demangled_name = NULL;
791   gdb::unique_xmalloc_ptr<char> ret;
792   struct demangle_component *ret_comp;
793   std::unique_ptr<demangle_parse_info> info;
794
795   info = mangled_name_to_comp (physname, DMGL_ANSI,
796                                &storage, &demangled_name);
797   if (info == NULL)
798     return NULL;
799
800   ret_comp = unqualified_name_from_comp (info->tree);
801
802   if (ret_comp != NULL)
803     /* The ten is completely arbitrary; we don't have a good
804        estimate.  */
805     ret = cp_comp_to_string (ret_comp, 10);
806
807   xfree (storage);
808   xfree (demangled_name);
809   return ret.release ();
810 }
811
812 /* If FULL_NAME is the demangled name of a C++ function (including an
813    arg list, possibly including namespace/class qualifications),
814    return a new string containing only the function name (without the
815    arg list/class qualifications).  Otherwise, return NULL.  The
816    caller is responsible for freeing the memory in question.  */
817
818 char *
819 cp_func_name (const char *full_name)
820 {
821   gdb::unique_xmalloc_ptr<char> ret;
822   struct demangle_component *ret_comp;
823   std::unique_ptr<demangle_parse_info> info;
824
825   info = cp_demangled_name_to_comp (full_name, NULL);
826   if (!info)
827     return NULL;
828
829   ret_comp = unqualified_name_from_comp (info->tree);
830
831   if (ret_comp != NULL)
832     ret = cp_comp_to_string (ret_comp, 10);
833
834   return ret.release ();
835 }
836
837 /* DEMANGLED_NAME is the name of a function, including parameters and
838    (optionally) a return type.  Return the name of the function without
839    parameters or return type, or NULL if we can not parse the name.  */
840
841 char *
842 cp_remove_params (const char *demangled_name)
843 {
844   int done = 0;
845   struct demangle_component *ret_comp;
846   std::unique_ptr<demangle_parse_info> info;
847   gdb::unique_xmalloc_ptr<char> ret;
848
849   if (demangled_name == NULL)
850     return NULL;
851
852   info = cp_demangled_name_to_comp (demangled_name, NULL);
853   if (info == NULL)
854     return NULL;
855
856   /* First strip off any qualifiers, if we have a function or method.  */
857   ret_comp = info->tree;
858   while (!done)
859     switch (ret_comp->type)
860       {
861       case DEMANGLE_COMPONENT_CONST:
862       case DEMANGLE_COMPONENT_RESTRICT:
863       case DEMANGLE_COMPONENT_VOLATILE:
864       case DEMANGLE_COMPONENT_CONST_THIS:
865       case DEMANGLE_COMPONENT_RESTRICT_THIS:
866       case DEMANGLE_COMPONENT_VOLATILE_THIS:
867       case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
868         ret_comp = d_left (ret_comp);
869         break;
870       default:
871         done = 1;
872         break;
873       }
874
875   /* What we have now should be a function.  Return its name.  */
876   if (ret_comp->type == DEMANGLE_COMPONENT_TYPED_NAME)
877     ret = cp_comp_to_string (d_left (ret_comp), 10);
878
879   return ret.release ();
880 }
881
882 /* Here are some random pieces of trivia to keep in mind while trying
883    to take apart demangled names:
884
885    - Names can contain function arguments or templates, so the process
886      has to be, to some extent recursive: maybe keep track of your
887      depth based on encountering <> and ().
888
889    - Parentheses don't just have to happen at the end of a name: they
890      can occur even if the name in question isn't a function, because
891      a template argument might be a type that's a function.
892
893    - Conversely, even if you're trying to deal with a function, its
894      demangled name might not end with ')': it could be a const or
895      volatile class method, in which case it ends with "const" or
896      "volatile".
897
898    - Parentheses are also used in anonymous namespaces: a variable
899      'foo' in an anonymous namespace gets demangled as "(anonymous
900      namespace)::foo".
901
902    - And operator names can contain parentheses or angle brackets.  */
903
904 /* FIXME: carlton/2003-03-13: We have several functions here with
905    overlapping functionality; can we combine them?  Also, do they
906    handle all the above considerations correctly?  */
907
908
909 /* This returns the length of first component of NAME, which should be
910    the demangled name of a C++ variable/function/method/etc.
911    Specifically, it returns the index of the first colon forming the
912    boundary of the first component: so, given 'A::foo' or 'A::B::foo'
913    it returns the 1, and given 'foo', it returns 0.  */
914
915 /* The character in NAME indexed by the return value is guaranteed to
916    always be either ':' or '\0'.  */
917
918 /* NOTE: carlton/2003-03-13: This function is currently only intended
919    for internal use: it's probably not entirely safe when called on
920    user-generated input, because some of the 'index += 2' lines in
921    cp_find_first_component_aux might go past the end of malformed
922    input.  */
923
924 unsigned int
925 cp_find_first_component (const char *name)
926 {
927   return cp_find_first_component_aux (name, 0);
928 }
929
930 /* Helper function for cp_find_first_component.  Like that function,
931    it returns the length of the first component of NAME, but to make
932    the recursion easier, it also stops if it reaches an unexpected ')'
933    or '>' if the value of PERMISSIVE is nonzero.  */
934
935 static unsigned int
936 cp_find_first_component_aux (const char *name, int permissive)
937 {
938   unsigned int index = 0;
939   /* Operator names can show up in unexpected places.  Since these can
940      contain parentheses or angle brackets, they can screw up the
941      recursion.  But not every string 'operator' is part of an
942      operater name: e.g. you could have a variable 'cooperator'.  So
943      this variable tells us whether or not we should treat the string
944      'operator' as starting an operator.  */
945   int operator_possible = 1;
946
947   for (;; ++index)
948     {
949       switch (name[index])
950         {
951         case '<':
952           /* Template; eat it up.  The calls to cp_first_component
953              should only return (I hope!) when they reach the '>'
954              terminating the component or a '::' between two
955              components.  (Hence the '+ 2'.)  */
956           index += 1;
957           for (index += cp_find_first_component_aux (name + index, 1);
958                name[index] != '>';
959                index += cp_find_first_component_aux (name + index, 1))
960             {
961               if (name[index] != ':')
962                 {
963                   demangled_name_complaint (name);
964                   return strlen (name);
965                 }
966               index += 2;
967             }
968           operator_possible = 1;
969           break;
970         case '(':
971           /* Similar comment as to '<'.  */
972           index += 1;
973           for (index += cp_find_first_component_aux (name + index, 1);
974                name[index] != ')';
975                index += cp_find_first_component_aux (name + index, 1))
976             {
977               if (name[index] != ':')
978                 {
979                   demangled_name_complaint (name);
980                   return strlen (name);
981                 }
982               index += 2;
983             }
984           operator_possible = 1;
985           break;
986         case '>':
987         case ')':
988           if (permissive)
989             return index;
990           else
991             {
992               demangled_name_complaint (name);
993               return strlen (name);
994             }
995         case '\0':
996           return index;
997         case ':':
998           /* ':' marks a component iff the next character is also a ':'.
999              Otherwise it is probably malformed input.  */
1000           if (name[index + 1] == ':')
1001             return index;
1002           break;
1003         case 'o':
1004           /* Operator names can screw up the recursion.  */
1005           if (operator_possible
1006               && startswith (name + index, CP_OPERATOR_STR))
1007             {
1008               index += CP_OPERATOR_LEN;
1009               while (ISSPACE(name[index]))
1010                 ++index;
1011               switch (name[index])
1012                 {
1013                 case '\0':
1014                   return index;
1015                   /* Skip over one less than the appropriate number of
1016                      characters: the for loop will skip over the last
1017                      one.  */
1018                 case '<':
1019                   if (name[index + 1] == '<')
1020                     index += 1;
1021                   else
1022                     index += 0;
1023                   break;
1024                 case '>':
1025                 case '-':
1026                   if (name[index + 1] == '>')
1027                     index += 1;
1028                   else
1029                     index += 0;
1030                   break;
1031                 case '(':
1032                   index += 1;
1033                   break;
1034                 default:
1035                   index += 0;
1036                   break;
1037                 }
1038             }
1039           operator_possible = 0;
1040           break;
1041         case ' ':
1042         case ',':
1043         case '.':
1044         case '&':
1045         case '*':
1046           /* NOTE: carlton/2003-04-18: I'm not sure what the precise
1047              set of relevant characters are here: it's necessary to
1048              include any character that can show up before 'operator'
1049              in a demangled name, and it's safe to include any
1050              character that can't be part of an identifier's name.  */
1051           operator_possible = 1;
1052           break;
1053         default:
1054           operator_possible = 0;
1055           break;
1056         }
1057     }
1058 }
1059
1060 /* Complain about a demangled name that we don't know how to parse.
1061    NAME is the demangled name in question.  */
1062
1063 static void
1064 demangled_name_complaint (const char *name)
1065 {
1066   complaint (&symfile_complaints,
1067              "unexpected demangled name '%s'", name);
1068 }
1069
1070 /* If NAME is the fully-qualified name of a C++
1071    function/variable/method/etc., this returns the length of its
1072    entire prefix: all of the namespaces and classes that make up its
1073    name.  Given 'A::foo', it returns 1, given 'A::B::foo', it returns
1074    4, given 'foo', it returns 0.  */
1075
1076 unsigned int
1077 cp_entire_prefix_len (const char *name)
1078 {
1079   unsigned int current_len = cp_find_first_component (name);
1080   unsigned int previous_len = 0;
1081
1082   while (name[current_len] != '\0')
1083     {
1084       gdb_assert (name[current_len] == ':');
1085       previous_len = current_len;
1086       /* Skip the '::'.  */
1087       current_len += 2;
1088       current_len += cp_find_first_component (name + current_len);
1089     }
1090
1091   return previous_len;
1092 }
1093
1094 /* Overload resolution functions.  */
1095
1096 /* Test to see if SYM is a symbol that we haven't seen corresponding
1097    to a function named OLOAD_NAME.  If so, add it to the current
1098    completion list.  */
1099
1100 static void
1101 overload_list_add_symbol (struct symbol *sym,
1102                           const char *oload_name)
1103 {
1104   int newsize;
1105   int i;
1106   char *sym_name;
1107
1108   /* If there is no type information, we can't do anything, so
1109      skip.  */
1110   if (SYMBOL_TYPE (sym) == NULL)
1111     return;
1112
1113   /* skip any symbols that we've already considered.  */
1114   for (i = 0; i < sym_return_val_index; ++i)
1115     if (strcmp (SYMBOL_LINKAGE_NAME (sym),
1116                 SYMBOL_LINKAGE_NAME (sym_return_val[i])) == 0)
1117       return;
1118
1119   /* Get the demangled name without parameters */
1120   sym_name = cp_remove_params (SYMBOL_NATURAL_NAME (sym));
1121   if (!sym_name)
1122     return;
1123
1124   /* skip symbols that cannot match */
1125   if (strcmp (sym_name, oload_name) != 0)
1126     {
1127       xfree (sym_name);
1128       return;
1129     }
1130
1131   xfree (sym_name);
1132
1133   /* We have a match for an overload instance, so add SYM to the
1134      current list of overload instances */
1135   if (sym_return_val_index + 3 > sym_return_val_size)
1136     {
1137       newsize = (sym_return_val_size *= 2) * sizeof (struct symbol *);
1138       sym_return_val = (struct symbol **)
1139         xrealloc ((char *) sym_return_val, newsize);
1140     }
1141   sym_return_val[sym_return_val_index++] = sym;
1142   sym_return_val[sym_return_val_index] = NULL;
1143 }
1144
1145 /* Return a null-terminated list of pointers to function symbols that
1146    are named FUNC_NAME and are visible within NAMESPACE.  */
1147
1148 struct symbol **
1149 make_symbol_overload_list (const char *func_name,
1150                            const char *the_namespace)
1151 {
1152   struct cleanup *old_cleanups;
1153   const char *name;
1154
1155   sym_return_val_size = 100;
1156   sym_return_val_index = 0;
1157   sym_return_val = XNEWVEC (struct symbol *, sym_return_val_size + 1);
1158   sym_return_val[0] = NULL;
1159
1160   old_cleanups = make_cleanup (xfree, sym_return_val);
1161
1162   make_symbol_overload_list_using (func_name, the_namespace);
1163
1164   if (the_namespace[0] == '\0')
1165     name = func_name;
1166   else
1167     {
1168       char *concatenated_name
1169         = (char *) alloca (strlen (the_namespace) + 2 + strlen (func_name) + 1);
1170       strcpy (concatenated_name, the_namespace);
1171       strcat (concatenated_name, "::");
1172       strcat (concatenated_name, func_name);
1173       name = concatenated_name;
1174     }
1175
1176   make_symbol_overload_list_qualified (name);
1177
1178   discard_cleanups (old_cleanups);
1179
1180   return sym_return_val;
1181 }
1182
1183 /* Add all symbols with a name matching NAME in BLOCK to the overload
1184    list.  */
1185
1186 static void
1187 make_symbol_overload_list_block (const char *name,
1188                                  const struct block *block)
1189 {
1190   struct block_iterator iter;
1191   struct symbol *sym;
1192
1193   ALL_BLOCK_SYMBOLS_WITH_NAME (block, name, iter, sym)
1194     overload_list_add_symbol (sym, name);
1195 }
1196
1197 /* Adds the function FUNC_NAME from NAMESPACE to the overload set.  */
1198
1199 static void
1200 make_symbol_overload_list_namespace (const char *func_name,
1201                                      const char *the_namespace)
1202 {
1203   const char *name;
1204   const struct block *block = NULL;
1205
1206   if (the_namespace[0] == '\0')
1207     name = func_name;
1208   else
1209     {
1210       char *concatenated_name
1211         = (char *) alloca (strlen (the_namespace) + 2 + strlen (func_name) + 1);
1212
1213       strcpy (concatenated_name, the_namespace);
1214       strcat (concatenated_name, "::");
1215       strcat (concatenated_name, func_name);
1216       name = concatenated_name;
1217     }
1218
1219   /* Look in the static block.  */
1220   block = block_static_block (get_selected_block (0));
1221   if (block)
1222     make_symbol_overload_list_block (name, block);
1223
1224   /* Look in the global block.  */
1225   block = block_global_block (block);
1226   if (block)
1227     make_symbol_overload_list_block (name, block);
1228
1229 }
1230
1231 /* Search the namespace of the given type and namespace of and public
1232    base types.  */
1233
1234 static void
1235 make_symbol_overload_list_adl_namespace (struct type *type,
1236                                          const char *func_name)
1237 {
1238   char *the_namespace;
1239   const char *type_name;
1240   int i, prefix_len;
1241
1242   while (TYPE_CODE (type) == TYPE_CODE_PTR
1243          || TYPE_IS_REFERENCE (type)
1244          || TYPE_CODE (type) == TYPE_CODE_ARRAY
1245          || TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1246     {
1247       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
1248         type = check_typedef(type);
1249       else
1250         type = TYPE_TARGET_TYPE (type);
1251     }
1252
1253   type_name = TYPE_NAME (type);
1254
1255   if (type_name == NULL)
1256     return;
1257
1258   prefix_len = cp_entire_prefix_len (type_name);
1259
1260   if (prefix_len != 0)
1261     {
1262       the_namespace = (char *) alloca (prefix_len + 1);
1263       strncpy (the_namespace, type_name, prefix_len);
1264       the_namespace[prefix_len] = '\0';
1265
1266       make_symbol_overload_list_namespace (func_name, the_namespace);
1267     }
1268
1269   /* Check public base type */
1270   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1271     for (i = 0; i < TYPE_N_BASECLASSES (type); i++)
1272       {
1273         if (BASETYPE_VIA_PUBLIC (type, i))
1274           make_symbol_overload_list_adl_namespace (TYPE_BASECLASS (type,
1275                                                                    i),
1276                                                    func_name);
1277       }
1278 }
1279
1280 /* Adds the overload list overload candidates for FUNC_NAME found
1281    through argument dependent lookup.  */
1282
1283 struct symbol **
1284 make_symbol_overload_list_adl (struct type **arg_types, int nargs,
1285                                const char *func_name)
1286 {
1287   int i;
1288
1289   gdb_assert (sym_return_val_size != -1);
1290
1291   for (i = 1; i <= nargs; i++)
1292     make_symbol_overload_list_adl_namespace (arg_types[i - 1],
1293                                              func_name);
1294
1295   return sym_return_val;
1296 }
1297
1298 /* Used for cleanups to reset the "searched" flag in case of an
1299    error.  */
1300
1301 static void
1302 reset_directive_searched (void *data)
1303 {
1304   struct using_direct *direct = (struct using_direct *) data;
1305   direct->searched = 0;
1306 }
1307
1308 /* This applies the using directives to add namespaces to search in,
1309    and then searches for overloads in all of those namespaces.  It
1310    adds the symbols found to sym_return_val.  Arguments are as in
1311    make_symbol_overload_list.  */
1312
1313 static void
1314 make_symbol_overload_list_using (const char *func_name,
1315                                  const char *the_namespace)
1316 {
1317   struct using_direct *current;
1318   const struct block *block;
1319
1320   /* First, go through the using directives.  If any of them apply,
1321      look in the appropriate namespaces for new functions to match
1322      on.  */
1323
1324   for (block = get_selected_block (0);
1325        block != NULL;
1326        block = BLOCK_SUPERBLOCK (block))
1327     for (current = block_using (block);
1328         current != NULL;
1329         current = current->next)
1330       {
1331         /* Prevent recursive calls.  */
1332         if (current->searched)
1333           continue;
1334
1335         /* If this is a namespace alias or imported declaration ignore
1336            it.  */
1337         if (current->alias != NULL || current->declaration != NULL)
1338           continue;
1339
1340         if (strcmp (the_namespace, current->import_dest) == 0)
1341           {
1342             /* Mark this import as searched so that the recursive call
1343                does not search it again.  */
1344             struct cleanup *old_chain;
1345             current->searched = 1;
1346             old_chain = make_cleanup (reset_directive_searched,
1347                                       current);
1348
1349             make_symbol_overload_list_using (func_name,
1350                                              current->import_src);
1351
1352             current->searched = 0;
1353             discard_cleanups (old_chain);
1354           }
1355       }
1356
1357   /* Now, add names for this namespace.  */
1358   make_symbol_overload_list_namespace (func_name, the_namespace);
1359 }
1360
1361 /* This does the bulk of the work of finding overloaded symbols.
1362    FUNC_NAME is the name of the overloaded function we're looking for
1363    (possibly including namespace info).  */
1364
1365 static void
1366 make_symbol_overload_list_qualified (const char *func_name)
1367 {
1368   struct compunit_symtab *cust;
1369   struct objfile *objfile;
1370   const struct block *b, *surrounding_static_block = 0;
1371
1372   /* Look through the partial symtabs for all symbols which begin by
1373      matching FUNC_NAME.  Make sure we read that symbol table in.  */
1374
1375   ALL_OBJFILES (objfile)
1376   {
1377     if (objfile->sf)
1378       objfile->sf->qf->expand_symtabs_for_function (objfile, func_name);
1379   }
1380
1381   /* Search upwards from currently selected frame (so that we can
1382      complete on local vars.  */
1383
1384   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
1385     make_symbol_overload_list_block (func_name, b);
1386
1387   surrounding_static_block = block_static_block (get_selected_block (0));
1388
1389   /* Go through the symtabs and check the externs and statics for
1390      symbols which match.  */
1391
1392   ALL_COMPUNITS (objfile, cust)
1393   {
1394     QUIT;
1395     b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), GLOBAL_BLOCK);
1396     make_symbol_overload_list_block (func_name, b);
1397   }
1398
1399   ALL_COMPUNITS (objfile, cust)
1400   {
1401     QUIT;
1402     b = BLOCKVECTOR_BLOCK (COMPUNIT_BLOCKVECTOR (cust), STATIC_BLOCK);
1403     /* Don't do this block twice.  */
1404     if (b == surrounding_static_block)
1405       continue;
1406     make_symbol_overload_list_block (func_name, b);
1407   }
1408 }
1409
1410 /* Lookup the rtti type for a class name.  */
1411
1412 struct type *
1413 cp_lookup_rtti_type (const char *name, struct block *block)
1414 {
1415   struct symbol * rtti_sym;
1416   struct type * rtti_type;
1417
1418   /* Use VAR_DOMAIN here as NAME may be a typedef.  PR 18141, 18417.
1419      Classes "live" in both STRUCT_DOMAIN and VAR_DOMAIN.  */
1420   rtti_sym = lookup_symbol (name, block, VAR_DOMAIN, NULL).symbol;
1421
1422   if (rtti_sym == NULL)
1423     {
1424       warning (_("RTTI symbol not found for class '%s'"), name);
1425       return NULL;
1426     }
1427
1428   if (SYMBOL_CLASS (rtti_sym) != LOC_TYPEDEF)
1429     {
1430       warning (_("RTTI symbol for class '%s' is not a type"), name);
1431       return NULL;
1432     }
1433
1434   rtti_type = check_typedef (SYMBOL_TYPE (rtti_sym));
1435
1436   switch (TYPE_CODE (rtti_type))
1437     {
1438     case TYPE_CODE_STRUCT:
1439       break;
1440     case TYPE_CODE_NAMESPACE:
1441       /* chastain/2003-11-26: the symbol tables often contain fake
1442          symbols for namespaces with the same name as the struct.
1443          This warning is an indication of a bug in the lookup order
1444          or a bug in the way that the symbol tables are populated.  */
1445       warning (_("RTTI symbol for class '%s' is a namespace"), name);
1446       return NULL;
1447     default:
1448       warning (_("RTTI symbol for class '%s' has bad type"), name);
1449       return NULL;
1450     }
1451
1452   return rtti_type;
1453 }
1454
1455 #ifdef HAVE_WORKING_FORK
1456
1457 /* If nonzero, attempt to catch crashes in the demangler and print
1458    useful debugging information.  */
1459
1460 static int catch_demangler_crashes = 1;
1461
1462 /* Stack context and environment for demangler crash recovery.  */
1463
1464 static SIGJMP_BUF gdb_demangle_jmp_buf;
1465
1466 /* If nonzero, attempt to dump core from the signal handler.  */
1467
1468 static int gdb_demangle_attempt_core_dump = 1;
1469
1470 /* Signal handler for gdb_demangle.  */
1471
1472 static void
1473 gdb_demangle_signal_handler (int signo)
1474 {
1475   if (gdb_demangle_attempt_core_dump)
1476     {
1477       if (fork () == 0)
1478         dump_core ();
1479
1480       gdb_demangle_attempt_core_dump = 0;
1481     }
1482
1483   SIGLONGJMP (gdb_demangle_jmp_buf, signo);
1484 }
1485
1486 #endif
1487
1488 /* A wrapper for bfd_demangle.  */
1489
1490 char *
1491 gdb_demangle (const char *name, int options)
1492 {
1493   char *result = NULL;
1494   int crash_signal = 0;
1495
1496 #ifdef HAVE_WORKING_FORK
1497 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
1498   struct sigaction sa, old_sa;
1499 #else
1500   sighandler_t ofunc;
1501 #endif
1502   static int core_dump_allowed = -1;
1503
1504   if (core_dump_allowed == -1)
1505     {
1506       core_dump_allowed = can_dump_core (LIMIT_CUR);
1507
1508       if (!core_dump_allowed)
1509         gdb_demangle_attempt_core_dump = 0;
1510     }
1511
1512   if (catch_demangler_crashes)
1513     {
1514 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
1515       sa.sa_handler = gdb_demangle_signal_handler;
1516       sigemptyset (&sa.sa_mask);
1517 #ifdef HAVE_SIGALTSTACK
1518       sa.sa_flags = SA_ONSTACK;
1519 #else
1520       sa.sa_flags = 0;
1521 #endif
1522       sigaction (SIGSEGV, &sa, &old_sa);
1523 #else
1524       ofunc = signal (SIGSEGV, gdb_demangle_signal_handler);
1525 #endif
1526
1527       crash_signal = SIGSETJMP (gdb_demangle_jmp_buf);
1528     }
1529 #endif
1530
1531   if (crash_signal == 0)
1532     result = bfd_demangle (NULL, name, options);
1533
1534 #ifdef HAVE_WORKING_FORK
1535   if (catch_demangler_crashes)
1536     {
1537 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
1538       sigaction (SIGSEGV, &old_sa, NULL);
1539 #else
1540       signal (SIGSEGV, ofunc);
1541 #endif
1542
1543       if (crash_signal != 0)
1544         {
1545           static int error_reported = 0;
1546
1547           if (!error_reported)
1548             {
1549               std::string short_msg
1550                 = string_printf (_("unable to demangle '%s' "
1551                                    "(demangler failed with signal %d)"),
1552                                  name, crash_signal);
1553
1554               std::string long_msg
1555                 = string_printf ("%s:%d: %s: %s", __FILE__, __LINE__,
1556                                  "demangler-warning", short_msg.c_str ());
1557
1558               target_terminal::scoped_restore_terminal_state term_state;
1559               target_terminal::ours_for_output ();
1560
1561               begin_line ();
1562               if (core_dump_allowed)
1563                 fprintf_unfiltered (gdb_stderr,
1564                                     _("%s\nAttempting to dump core.\n"),
1565                                     long_msg.c_str ());
1566               else
1567                 warn_cant_dump_core (long_msg.c_str ());
1568
1569               demangler_warning (__FILE__, __LINE__, "%s", short_msg.c_str ());
1570
1571               error_reported = 1;
1572             }
1573
1574           result = NULL;
1575         }
1576     }
1577 #endif
1578
1579   return result;
1580 }
1581
1582 /* See cp-support.h.  */
1583
1584 int
1585 gdb_sniff_from_mangled_name (const char *mangled, char **demangled)
1586 {
1587   *demangled = gdb_demangle (mangled, DMGL_PARAMS | DMGL_ANSI);
1588   return *demangled != NULL;
1589 }
1590
1591 /* Don't allow just "maintenance cplus".  */
1592
1593 static  void
1594 maint_cplus_command (char *arg, int from_tty)
1595 {
1596   printf_unfiltered (_("\"maintenance cplus\" must be followed "
1597                        "by the name of a command.\n"));
1598   help_list (maint_cplus_cmd_list,
1599              "maintenance cplus ",
1600              all_commands, gdb_stdout);
1601 }
1602
1603 /* This is a front end for cp_find_first_component, for unit testing.
1604    Be careful when using it: see the NOTE above
1605    cp_find_first_component.  */
1606
1607 static void
1608 first_component_command (const char *arg, int from_tty)
1609 {
1610   int len;  
1611   char *prefix; 
1612
1613   if (!arg)
1614     return;
1615
1616   len = cp_find_first_component (arg);
1617   prefix = (char *) alloca (len + 1);
1618
1619   memcpy (prefix, arg, len);
1620   prefix[len] = '\0';
1621
1622   printf_unfiltered ("%s\n", prefix);
1623 }
1624
1625 /* Implement "info vtbl".  */
1626
1627 static void
1628 info_vtbl_command (char *arg, int from_tty)
1629 {
1630   struct value *value;
1631
1632   value = parse_and_eval (arg);
1633   cplus_print_vtable (value);
1634 }
1635
1636 void
1637 _initialize_cp_support (void)
1638 {
1639   add_prefix_cmd ("cplus", class_maintenance,
1640                   maint_cplus_command,
1641                   _("C++ maintenance commands."),
1642                   &maint_cplus_cmd_list,
1643                   "maintenance cplus ",
1644                   0, &maintenancelist);
1645   add_alias_cmd ("cp", "cplus",
1646                  class_maintenance, 1,
1647                  &maintenancelist);
1648
1649   add_cmd ("first_component",
1650            class_maintenance,
1651            first_component_command,
1652            _("Print the first class/namespace component of NAME."),
1653            &maint_cplus_cmd_list);
1654
1655   add_info ("vtbl", info_vtbl_command,
1656             _("Show the virtual function table for a C++ object.\n\
1657 Usage: info vtbl EXPRESSION\n\
1658 Evaluate EXPRESSION and display the virtual function table for the\n\
1659 resulting object."));
1660
1661 #ifdef HAVE_WORKING_FORK
1662   add_setshow_boolean_cmd ("catch-demangler-crashes", class_maintenance,
1663                            &catch_demangler_crashes, _("\
1664 Set whether to attempt to catch demangler crashes."), _("\
1665 Show whether to attempt to catch demangler crashes."), _("\
1666 If enabled GDB will attempt to catch demangler crashes and\n\
1667 display the offending symbol."),
1668                            NULL,
1669                            NULL,
1670                            &maintenance_set_cmdlist,
1671                            &maintenance_show_cmdlist);
1672 #endif
1673 }