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