Automatic date update in version.in
[binutils-gdb.git] / gdb / cp-support.c
blob9eb5577dd3386ea8b40d86cef747e37e278c5017
1 /* Helper routines for C++ support in GDB.
2 Copyright (C) 2002-2023 Free Software Foundation, Inc.
4 Contributed by MontaVista Software.
6 This file is part of GDB.
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.
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.
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/>. */
21 #include "defs.h"
22 #include "cp-support.h"
23 #include "language.h"
24 #include "demangle.h"
25 #include "gdbcmd.h"
26 #include "dictionary.h"
27 #include "objfiles.h"
28 #include "frame.h"
29 #include "symtab.h"
30 #include "block.h"
31 #include "complaints.h"
32 #include "gdbtypes.h"
33 #include "expression.h"
34 #include "value.h"
35 #include "cp-abi.h"
36 #include "namespace.h"
37 #include <signal.h>
38 #include "gdbsupport/gdb_setjmp.h"
39 #include "gdbsupport/gdb-safe-ctype.h"
40 #include "gdbsupport/selftest.h"
41 #include "gdbsupport/gdb-sigmask.h"
42 #include <atomic>
43 #include "event-top.h"
44 #include "run-on-main-thread.h"
45 #include "typeprint.h"
46 #include "inferior.h"
48 #define d_left(dc) (dc)->u.s_binary.left
49 #define d_right(dc) (dc)->u.s_binary.right
51 /* Functions related to demangled name parsing. */
53 static unsigned int cp_find_first_component_aux (const char *name,
54 int permissive);
56 static void demangled_name_complaint (const char *name);
58 /* Functions related to overload resolution. */
60 static void overload_list_add_symbol (struct symbol *sym,
61 const char *oload_name,
62 std::vector<symbol *> *overload_list);
64 static void add_symbol_overload_list_using
65 (const char *func_name, const char *the_namespace,
66 std::vector<symbol *> *overload_list);
68 static void add_symbol_overload_list_qualified
69 (const char *func_name,
70 std::vector<symbol *> *overload_list);
72 /* The list of "maint cplus" commands. */
74 struct cmd_list_element *maint_cplus_cmd_list = NULL;
76 static void
77 replace_typedefs (struct demangle_parse_info *info,
78 struct demangle_component *ret_comp,
79 canonicalization_ftype *finder,
80 void *data);
82 static struct demangle_component *
83 gdb_cplus_demangle_v3_components (const char *mangled,
84 int options, void **mem);
86 /* A convenience function to copy STRING into OBSTACK, returning a pointer
87 to the newly allocated string and saving the number of bytes saved in LEN.
89 It does not copy the terminating '\0' byte! */
91 static char *
92 copy_string_to_obstack (struct obstack *obstack, const char *string,
93 long *len)
95 *len = strlen (string);
96 return (char *) obstack_copy (obstack, string, *len);
99 /* Return 1 if STRING is clearly already in canonical form. This
100 function is conservative; things which it does not recognize are
101 assumed to be non-canonical, and the parser will sort them out
102 afterwards. This speeds up the critical path for alphanumeric
103 identifiers. */
105 static int
106 cp_already_canonical (const char *string)
108 /* Identifier start character [a-zA-Z_]. */
109 if (!ISIDST (string[0]))
110 return 0;
112 /* These are the only two identifiers which canonicalize to other
113 than themselves or an error: unsigned -> unsigned int and
114 signed -> int. */
115 if (string[0] == 'u' && strcmp (&string[1], "nsigned") == 0)
116 return 0;
117 else if (string[0] == 's' && strcmp (&string[1], "igned") == 0)
118 return 0;
120 /* Identifier character [a-zA-Z0-9_]. */
121 while (ISIDNUM (string[1]))
122 string++;
124 if (string[1] == '\0')
125 return 1;
126 else
127 return 0;
130 /* Inspect the given RET_COMP for its type. If it is a typedef,
131 replace the node with the typedef's tree.
133 Returns 1 if any typedef substitutions were made, 0 otherwise. */
135 static int
136 inspect_type (struct demangle_parse_info *info,
137 struct demangle_component *ret_comp,
138 canonicalization_ftype *finder,
139 void *data)
141 char *name;
142 struct symbol *sym;
144 /* Copy the symbol's name from RET_COMP and look it up
145 in the symbol table. */
146 name = (char *) alloca (ret_comp->u.s_name.len + 1);
147 memcpy (name, ret_comp->u.s_name.s, ret_comp->u.s_name.len);
148 name[ret_comp->u.s_name.len] = '\0';
150 sym = NULL;
154 sym = lookup_symbol (name, 0, VAR_DOMAIN, 0).symbol;
156 catch (const gdb_exception &except)
158 return 0;
161 if (sym != NULL)
163 struct type *otype = sym->type ();
165 if (finder != NULL)
167 const char *new_name = (*finder) (otype, data);
169 if (new_name != NULL)
171 ret_comp->u.s_name.s = new_name;
172 ret_comp->u.s_name.len = strlen (new_name);
173 return 1;
176 return 0;
179 /* If the type is a typedef or namespace alias, replace it. */
180 if (otype->code () == TYPE_CODE_TYPEDEF
181 || otype->code () == TYPE_CODE_NAMESPACE)
183 long len;
184 int is_anon;
185 struct type *type;
186 std::unique_ptr<demangle_parse_info> i;
188 /* Get the real type of the typedef. */
189 type = check_typedef (otype);
191 /* If the symbol name is the same as the original type name,
192 don't substitute. That would cause infinite recursion in
193 symbol lookups, as the typedef symbol is often the first
194 found symbol in the symbol table.
196 However, this can happen in a number of situations, such as:
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.
202 If the symbol is typedef and its type name is the same
203 as the symbol's name, e.g., "typedef struct foo foo;". */
204 if (type->name () != nullptr
205 && strcmp (type->name (), name) == 0)
206 return 0;
208 is_anon = (type->name () == NULL
209 && (type->code () == TYPE_CODE_ENUM
210 || type->code () == TYPE_CODE_STRUCT
211 || type->code () == TYPE_CODE_UNION));
212 if (is_anon)
214 struct type *last = otype;
216 /* Find the last typedef for the type. */
217 while (last->target_type () != NULL
218 && (last->target_type ()->code ()
219 == TYPE_CODE_TYPEDEF))
220 last = last->target_type ();
222 /* If there is only one typedef for this anonymous type,
223 do not substitute it. */
224 if (type == otype)
225 return 0;
226 else
227 /* Use the last typedef seen as the type for this
228 anonymous type. */
229 type = last;
232 string_file buf;
235 /* Avoid using the current language. If the language is
236 C, and TYPE is a struct/class, the printed type is
237 prefixed with "struct " or "class ", which we don't
238 want when we're expanding a C++ typedef. Print using
239 the type symbol's language to expand a C++ typedef
240 the C++ way even if the current language is C. */
241 const language_defn *lang = language_def (sym->language ());
242 lang->print_type (type, "", &buf, -1, 0, &type_print_raw_options);
244 /* If type_print threw an exception, there is little point
245 in continuing, so just bow out gracefully. */
246 catch (const gdb_exception_error &except)
248 return 0;
251 len = buf.size ();
252 name = obstack_strdup (&info->obstack, buf.string ());
254 /* Turn the result into a new tree. Note that this
255 tree will contain pointers into NAME, so NAME cannot
256 be free'd until all typedef conversion is done and
257 the final result is converted into a string. */
258 i = cp_demangled_name_to_comp (name, NULL);
259 if (i != NULL)
261 /* Merge the two trees. */
262 cp_merge_demangle_parse_infos (info, ret_comp, i.get ());
264 /* Replace any newly introduced typedefs -- but not
265 if the type is anonymous (that would lead to infinite
266 looping). */
267 if (!is_anon)
268 replace_typedefs (info, ret_comp, finder, data);
270 else
272 /* This shouldn't happen unless the type printer has
273 output something that the name parser cannot grok.
274 Nonetheless, an ounce of prevention...
276 Canonicalize the name again, and store it in the
277 current node (RET_COMP). */
278 gdb::unique_xmalloc_ptr<char> canon
279 = cp_canonicalize_string_no_typedefs (name);
281 if (canon != nullptr)
283 /* Copy the canonicalization into the obstack. */
284 name = copy_string_to_obstack (&info->obstack, canon.get (), &len);
287 ret_comp->u.s_name.s = name;
288 ret_comp->u.s_name.len = len;
291 return 1;
295 return 0;
298 /* Helper for replace_typedefs_qualified_name to handle
299 DEMANGLE_COMPONENT_TEMPLATE. TMPL is the template node. BUF is
300 the buffer that holds the qualified name being built by
301 replace_typedefs_qualified_name. REPL is the node that will be
302 rewritten as a DEMANGLE_COMPONENT_NAME node holding the 'template
303 plus template arguments' name with typedefs replaced. */
305 static bool
306 replace_typedefs_template (struct demangle_parse_info *info,
307 string_file &buf,
308 struct demangle_component *tmpl,
309 struct demangle_component *repl,
310 canonicalization_ftype *finder,
311 void *data)
313 demangle_component *tmpl_arglist = d_right (tmpl);
315 /* Replace typedefs in the template argument list. */
316 replace_typedefs (info, tmpl_arglist, finder, data);
318 /* Convert 'template + replaced template argument list' to a string
319 and replace the REPL node. */
320 gdb::unique_xmalloc_ptr<char> tmpl_str = cp_comp_to_string (tmpl, 100);
321 if (tmpl_str == nullptr)
323 /* If something went astray, abort typedef substitutions. */
324 return false;
326 buf.puts (tmpl_str.get ());
328 repl->type = DEMANGLE_COMPONENT_NAME;
329 repl->u.s_name.s = obstack_strdup (&info->obstack, buf.string ());
330 repl->u.s_name.len = buf.size ();
331 return true;
334 /* Replace any typedefs appearing in the qualified name
335 (DEMANGLE_COMPONENT_QUAL_NAME) represented in RET_COMP for the name parse
336 given in INFO. */
338 static void
339 replace_typedefs_qualified_name (struct demangle_parse_info *info,
340 struct demangle_component *ret_comp,
341 canonicalization_ftype *finder,
342 void *data)
344 string_file buf;
345 struct demangle_component *comp = ret_comp;
347 /* Walk each node of the qualified name, reconstructing the name of
348 this element. With every node, check for any typedef substitutions.
349 If a substitution has occurred, replace the qualified name node
350 with a DEMANGLE_COMPONENT_NAME node representing the new, typedef-
351 substituted name. */
352 while (comp->type == DEMANGLE_COMPONENT_QUAL_NAME)
354 if (d_left (comp)->type == DEMANGLE_COMPONENT_TEMPLATE)
356 /* Convert 'template + replaced template argument list' to a
357 string and replace the top DEMANGLE_COMPONENT_QUAL_NAME
358 node. */
359 if (!replace_typedefs_template (info, buf,
360 d_left (comp), d_left (ret_comp),
361 finder, data))
362 return;
364 buf.clear ();
365 d_right (ret_comp) = d_right (comp);
366 comp = ret_comp;
368 /* Fallback to DEMANGLE_COMPONENT_NAME processing. We want
369 to call inspect_type for this template, in case we have a
370 template alias, like:
371 template<typename T> using alias = base<int, t>;
372 in which case we want inspect_type to do a replacement like:
373 alias<int> -> base<int, int>
377 if (d_left (comp)->type == DEMANGLE_COMPONENT_NAME)
379 struct demangle_component newobj;
381 buf.write (d_left (comp)->u.s_name.s, d_left (comp)->u.s_name.len);
382 newobj.type = DEMANGLE_COMPONENT_NAME;
383 newobj.u.s_name.s = obstack_strdup (&info->obstack, buf.string ());
384 newobj.u.s_name.len = buf.size ();
385 if (inspect_type (info, &newobj, finder, data))
387 char *s;
388 long slen;
390 /* A typedef was substituted in NEW. Convert it to a
391 string and replace the top DEMANGLE_COMPONENT_QUAL_NAME
392 node. */
394 buf.clear ();
395 gdb::unique_xmalloc_ptr<char> n
396 = cp_comp_to_string (&newobj, 100);
397 if (n == NULL)
399 /* If something went astray, abort typedef substitutions. */
400 return;
403 s = copy_string_to_obstack (&info->obstack, n.get (), &slen);
405 d_left (ret_comp)->type = DEMANGLE_COMPONENT_NAME;
406 d_left (ret_comp)->u.s_name.s = s;
407 d_left (ret_comp)->u.s_name.len = slen;
408 d_right (ret_comp) = d_right (comp);
409 comp = ret_comp;
410 continue;
413 else
415 /* The current node is not a name, so simply replace any
416 typedefs in it. Then print it to the stream to continue
417 checking for more typedefs in the tree. */
418 replace_typedefs (info, d_left (comp), finder, data);
419 gdb::unique_xmalloc_ptr<char> name
420 = cp_comp_to_string (d_left (comp), 100);
421 if (name == NULL)
423 /* If something went astray, abort typedef substitutions. */
424 return;
426 buf.puts (name.get ());
429 buf.write ("::", 2);
430 comp = d_right (comp);
433 /* If the next component is DEMANGLE_COMPONENT_TEMPLATE or
434 DEMANGLE_COMPONENT_NAME, save the qualified name assembled above
435 and append the name given by COMP. Then use this reassembled
436 name to check for a typedef. */
438 if (comp->type == DEMANGLE_COMPONENT_TEMPLATE)
440 /* Replace the top (DEMANGLE_COMPONENT_QUAL_NAME) node with a
441 DEMANGLE_COMPONENT_NAME node containing the whole name. */
442 if (!replace_typedefs_template (info, buf, comp, ret_comp, finder, data))
443 return;
444 inspect_type (info, ret_comp, finder, data);
446 else if (comp->type == DEMANGLE_COMPONENT_NAME)
448 buf.write (comp->u.s_name.s, comp->u.s_name.len);
450 /* Replace the top (DEMANGLE_COMPONENT_QUAL_NAME) node
451 with a DEMANGLE_COMPONENT_NAME node containing the whole
452 name. */
453 ret_comp->type = DEMANGLE_COMPONENT_NAME;
454 ret_comp->u.s_name.s = obstack_strdup (&info->obstack, buf.string ());
455 ret_comp->u.s_name.len = buf.size ();
456 inspect_type (info, ret_comp, finder, data);
458 else
459 replace_typedefs (info, comp, finder, data);
463 /* A function to check const and volatile qualifiers for argument types.
465 "Parameter declarations that differ only in the presence
466 or absence of `const' and/or `volatile' are equivalent."
467 C++ Standard N3290, clause 13.1.3 #4. */
469 static void
470 check_cv_qualifiers (struct demangle_component *ret_comp)
472 while (d_left (ret_comp) != NULL
473 && (d_left (ret_comp)->type == DEMANGLE_COMPONENT_CONST
474 || d_left (ret_comp)->type == DEMANGLE_COMPONENT_VOLATILE))
476 d_left (ret_comp) = d_left (d_left (ret_comp));
480 /* Walk the parse tree given by RET_COMP, replacing any typedefs with
481 their basic types. */
483 static void
484 replace_typedefs (struct demangle_parse_info *info,
485 struct demangle_component *ret_comp,
486 canonicalization_ftype *finder,
487 void *data)
489 if (ret_comp)
491 if (finder != NULL
492 && (ret_comp->type == DEMANGLE_COMPONENT_NAME
493 || ret_comp->type == DEMANGLE_COMPONENT_QUAL_NAME
494 || ret_comp->type == DEMANGLE_COMPONENT_TEMPLATE
495 || ret_comp->type == DEMANGLE_COMPONENT_BUILTIN_TYPE))
497 gdb::unique_xmalloc_ptr<char> local_name
498 = cp_comp_to_string (ret_comp, 10);
500 if (local_name != NULL)
502 struct symbol *sym = NULL;
504 sym = NULL;
507 sym = lookup_symbol (local_name.get (), 0,
508 VAR_DOMAIN, 0).symbol;
510 catch (const gdb_exception &except)
514 if (sym != NULL)
516 struct type *otype = sym->type ();
517 const char *new_name = (*finder) (otype, data);
519 if (new_name != NULL)
521 ret_comp->type = DEMANGLE_COMPONENT_NAME;
522 ret_comp->u.s_name.s = new_name;
523 ret_comp->u.s_name.len = strlen (new_name);
524 return;
530 switch (ret_comp->type)
532 case DEMANGLE_COMPONENT_ARGLIST:
533 check_cv_qualifiers (ret_comp);
534 [[fallthrough]];
536 case DEMANGLE_COMPONENT_FUNCTION_TYPE:
537 case DEMANGLE_COMPONENT_TEMPLATE:
538 case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
539 case DEMANGLE_COMPONENT_TYPED_NAME:
540 replace_typedefs (info, d_left (ret_comp), finder, data);
541 replace_typedefs (info, d_right (ret_comp), finder, data);
542 break;
544 case DEMANGLE_COMPONENT_NAME:
545 inspect_type (info, ret_comp, finder, data);
546 break;
548 case DEMANGLE_COMPONENT_QUAL_NAME:
549 replace_typedefs_qualified_name (info, ret_comp, finder, data);
550 break;
552 case DEMANGLE_COMPONENT_LOCAL_NAME:
553 case DEMANGLE_COMPONENT_CTOR:
554 case DEMANGLE_COMPONENT_ARRAY_TYPE:
555 case DEMANGLE_COMPONENT_PTRMEM_TYPE:
556 replace_typedefs (info, d_right (ret_comp), finder, data);
557 break;
559 case DEMANGLE_COMPONENT_CONST:
560 case DEMANGLE_COMPONENT_RESTRICT:
561 case DEMANGLE_COMPONENT_VOLATILE:
562 case DEMANGLE_COMPONENT_VOLATILE_THIS:
563 case DEMANGLE_COMPONENT_CONST_THIS:
564 case DEMANGLE_COMPONENT_RESTRICT_THIS:
565 case DEMANGLE_COMPONENT_POINTER:
566 case DEMANGLE_COMPONENT_REFERENCE:
567 case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
568 replace_typedefs (info, d_left (ret_comp), finder, data);
569 break;
571 default:
572 break;
577 /* Parse STRING and convert it to canonical form, resolving any
578 typedefs. If parsing fails, or if STRING is already canonical,
579 return nullptr. Otherwise return the canonical form. If
580 FINDER is not NULL, then type components are passed to FINDER to be
581 looked up. DATA is passed verbatim to FINDER. */
583 gdb::unique_xmalloc_ptr<char>
584 cp_canonicalize_string_full (const char *string,
585 canonicalization_ftype *finder,
586 void *data)
588 unsigned int estimated_len;
589 std::unique_ptr<demangle_parse_info> info;
591 estimated_len = strlen (string) * 2;
592 info = cp_demangled_name_to_comp (string, NULL);
593 if (info != NULL)
595 /* Replace all the typedefs in the tree. */
596 replace_typedefs (info.get (), info->tree, finder, data);
598 /* Convert the tree back into a string. */
599 gdb::unique_xmalloc_ptr<char> us = cp_comp_to_string (info->tree,
600 estimated_len);
601 gdb_assert (us);
603 /* Finally, compare the original string with the computed
604 name, returning NULL if they are the same. */
605 if (strcmp (us.get (), string) == 0)
606 return nullptr;
608 return us;
611 return nullptr;
614 /* Like cp_canonicalize_string_full, but always passes NULL for
615 FINDER. */
617 gdb::unique_xmalloc_ptr<char>
618 cp_canonicalize_string_no_typedefs (const char *string)
620 return cp_canonicalize_string_full (string, NULL, NULL);
623 /* Parse STRING and convert it to canonical form. If parsing fails,
624 or if STRING is already canonical, return nullptr.
625 Otherwise return the canonical form. */
627 gdb::unique_xmalloc_ptr<char>
628 cp_canonicalize_string (const char *string)
630 std::unique_ptr<demangle_parse_info> info;
631 unsigned int estimated_len;
633 if (cp_already_canonical (string))
634 return nullptr;
636 info = cp_demangled_name_to_comp (string, NULL);
637 if (info == NULL)
638 return nullptr;
640 estimated_len = strlen (string) * 2;
641 gdb::unique_xmalloc_ptr<char> us (cp_comp_to_string (info->tree,
642 estimated_len));
644 if (!us)
646 warning (_("internal error: string \"%s\" failed to be canonicalized"),
647 string);
648 return nullptr;
651 if (strcmp (us.get (), string) == 0)
652 return nullptr;
654 return us;
657 /* Convert a mangled name to a demangle_component tree. *MEMORY is
658 set to the block of used memory that should be freed when finished
659 with the tree. DEMANGLED_P is set to the char * that should be
660 freed when finished with the tree, or NULL if none was needed.
661 OPTIONS will be passed to the demangler. */
663 static std::unique_ptr<demangle_parse_info>
664 mangled_name_to_comp (const char *mangled_name, int options,
665 void **memory,
666 gdb::unique_xmalloc_ptr<char> *demangled_p)
668 /* If it looks like a v3 mangled name, then try to go directly
669 to trees. */
670 if (mangled_name[0] == '_' && mangled_name[1] == 'Z')
672 struct demangle_component *ret;
674 ret = gdb_cplus_demangle_v3_components (mangled_name,
675 options, memory);
676 if (ret)
678 auto info = std::make_unique<demangle_parse_info> ();
679 info->tree = ret;
680 *demangled_p = NULL;
681 return info;
685 /* If it doesn't, or if that failed, then try to demangle the
686 name. */
687 gdb::unique_xmalloc_ptr<char> demangled_name = gdb_demangle (mangled_name,
688 options);
689 if (demangled_name == NULL)
690 return NULL;
692 /* If we could demangle the name, parse it to build the component
693 tree. */
694 std::unique_ptr<demangle_parse_info> info
695 = cp_demangled_name_to_comp (demangled_name.get (), NULL);
697 if (info == NULL)
698 return NULL;
700 *demangled_p = std::move (demangled_name);
701 return info;
704 /* Return the name of the class containing method PHYSNAME. */
706 char *
707 cp_class_name_from_physname (const char *physname)
709 void *storage = NULL;
710 gdb::unique_xmalloc_ptr<char> demangled_name;
711 gdb::unique_xmalloc_ptr<char> ret;
712 struct demangle_component *ret_comp, *prev_comp, *cur_comp;
713 std::unique_ptr<demangle_parse_info> info;
714 int done;
716 info = mangled_name_to_comp (physname, DMGL_ANSI,
717 &storage, &demangled_name);
718 if (info == NULL)
719 return NULL;
721 done = 0;
722 ret_comp = info->tree;
724 /* First strip off any qualifiers, if we have a function or
725 method. */
726 while (!done)
727 switch (ret_comp->type)
729 case DEMANGLE_COMPONENT_CONST:
730 case DEMANGLE_COMPONENT_RESTRICT:
731 case DEMANGLE_COMPONENT_VOLATILE:
732 case DEMANGLE_COMPONENT_CONST_THIS:
733 case DEMANGLE_COMPONENT_RESTRICT_THIS:
734 case DEMANGLE_COMPONENT_VOLATILE_THIS:
735 case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
736 ret_comp = d_left (ret_comp);
737 break;
738 default:
739 done = 1;
740 break;
743 /* If what we have now is a function, discard the argument list. */
744 if (ret_comp->type == DEMANGLE_COMPONENT_TYPED_NAME)
745 ret_comp = d_left (ret_comp);
747 /* If what we have now is a template, strip off the template
748 arguments. The left subtree may be a qualified name. */
749 if (ret_comp->type == DEMANGLE_COMPONENT_TEMPLATE)
750 ret_comp = d_left (ret_comp);
752 /* What we have now should be a name, possibly qualified.
753 Additional qualifiers could live in the left subtree or the right
754 subtree. Find the last piece. */
755 done = 0;
756 prev_comp = NULL;
757 cur_comp = ret_comp;
758 while (!done)
759 switch (cur_comp->type)
761 case DEMANGLE_COMPONENT_QUAL_NAME:
762 case DEMANGLE_COMPONENT_LOCAL_NAME:
763 prev_comp = cur_comp;
764 cur_comp = d_right (cur_comp);
765 break;
766 case DEMANGLE_COMPONENT_TEMPLATE:
767 case DEMANGLE_COMPONENT_NAME:
768 case DEMANGLE_COMPONENT_CTOR:
769 case DEMANGLE_COMPONENT_DTOR:
770 case DEMANGLE_COMPONENT_OPERATOR:
771 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
772 done = 1;
773 break;
774 default:
775 done = 1;
776 cur_comp = NULL;
777 break;
780 if (cur_comp != NULL && prev_comp != NULL)
782 /* We want to discard the rightmost child of PREV_COMP. */
783 *prev_comp = *d_left (prev_comp);
784 /* The ten is completely arbitrary; we don't have a good
785 estimate. */
786 ret = cp_comp_to_string (ret_comp, 10);
789 xfree (storage);
790 return ret.release ();
793 /* Return the child of COMP which is the basename of a method,
794 variable, et cetera. All scope qualifiers are discarded, but
795 template arguments will be included. The component tree may be
796 modified. */
798 static struct demangle_component *
799 unqualified_name_from_comp (struct demangle_component *comp)
801 struct demangle_component *ret_comp = comp, *last_template;
802 int done;
804 done = 0;
805 last_template = NULL;
806 while (!done)
807 switch (ret_comp->type)
809 case DEMANGLE_COMPONENT_QUAL_NAME:
810 case DEMANGLE_COMPONENT_LOCAL_NAME:
811 ret_comp = d_right (ret_comp);
812 break;
813 case DEMANGLE_COMPONENT_TYPED_NAME:
814 ret_comp = d_left (ret_comp);
815 break;
816 case DEMANGLE_COMPONENT_TEMPLATE:
817 gdb_assert (last_template == NULL);
818 last_template = ret_comp;
819 ret_comp = d_left (ret_comp);
820 break;
821 case DEMANGLE_COMPONENT_CONST:
822 case DEMANGLE_COMPONENT_RESTRICT:
823 case DEMANGLE_COMPONENT_VOLATILE:
824 case DEMANGLE_COMPONENT_CONST_THIS:
825 case DEMANGLE_COMPONENT_RESTRICT_THIS:
826 case DEMANGLE_COMPONENT_VOLATILE_THIS:
827 case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
828 ret_comp = d_left (ret_comp);
829 break;
830 case DEMANGLE_COMPONENT_NAME:
831 case DEMANGLE_COMPONENT_CTOR:
832 case DEMANGLE_COMPONENT_DTOR:
833 case DEMANGLE_COMPONENT_OPERATOR:
834 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
835 done = 1;
836 break;
837 default:
838 return NULL;
839 break;
842 if (last_template)
844 d_left (last_template) = ret_comp;
845 return last_template;
848 return ret_comp;
851 /* Return the name of the method whose linkage name is PHYSNAME. */
853 char *
854 method_name_from_physname (const char *physname)
856 void *storage = NULL;
857 gdb::unique_xmalloc_ptr<char> demangled_name;
858 gdb::unique_xmalloc_ptr<char> ret;
859 struct demangle_component *ret_comp;
860 std::unique_ptr<demangle_parse_info> info;
862 info = mangled_name_to_comp (physname, DMGL_ANSI,
863 &storage, &demangled_name);
864 if (info == NULL)
865 return NULL;
867 ret_comp = unqualified_name_from_comp (info->tree);
869 if (ret_comp != NULL)
870 /* The ten is completely arbitrary; we don't have a good
871 estimate. */
872 ret = cp_comp_to_string (ret_comp, 10);
874 xfree (storage);
875 return ret.release ();
878 /* If FULL_NAME is the demangled name of a C++ function (including an
879 arg list, possibly including namespace/class qualifications),
880 return a new string containing only the function name (without the
881 arg list/class qualifications). Otherwise, return NULL. */
883 gdb::unique_xmalloc_ptr<char>
884 cp_func_name (const char *full_name)
886 gdb::unique_xmalloc_ptr<char> ret;
887 struct demangle_component *ret_comp;
888 std::unique_ptr<demangle_parse_info> info;
890 info = cp_demangled_name_to_comp (full_name, NULL);
891 if (!info)
892 return nullptr;
894 ret_comp = unqualified_name_from_comp (info->tree);
896 if (ret_comp != NULL)
897 ret = cp_comp_to_string (ret_comp, 10);
899 return ret;
902 /* Helper for cp_remove_params. DEMANGLED_NAME is the name of a
903 function, including parameters and (optionally) a return type.
904 Return the name of the function without parameters or return type,
905 or NULL if we can not parse the name. If REQUIRE_PARAMS is false,
906 then tolerate a non-existing or unbalanced parameter list. */
908 static gdb::unique_xmalloc_ptr<char>
909 cp_remove_params_1 (const char *demangled_name, bool require_params)
911 bool done = false;
912 struct demangle_component *ret_comp;
913 std::unique_ptr<demangle_parse_info> info;
914 gdb::unique_xmalloc_ptr<char> ret;
916 if (demangled_name == NULL)
917 return NULL;
919 info = cp_demangled_name_to_comp (demangled_name, NULL);
920 if (info == NULL)
921 return NULL;
923 /* First strip off any qualifiers, if we have a function or method. */
924 ret_comp = info->tree;
925 while (!done)
926 switch (ret_comp->type)
928 case DEMANGLE_COMPONENT_CONST:
929 case DEMANGLE_COMPONENT_RESTRICT:
930 case DEMANGLE_COMPONENT_VOLATILE:
931 case DEMANGLE_COMPONENT_CONST_THIS:
932 case DEMANGLE_COMPONENT_RESTRICT_THIS:
933 case DEMANGLE_COMPONENT_VOLATILE_THIS:
934 case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
935 ret_comp = d_left (ret_comp);
936 break;
937 default:
938 done = true;
939 break;
942 /* What we have now should be a function. Return its name. */
943 if (ret_comp->type == DEMANGLE_COMPONENT_TYPED_NAME)
944 ret = cp_comp_to_string (d_left (ret_comp), 10);
945 else if (!require_params
946 && (ret_comp->type == DEMANGLE_COMPONENT_NAME
947 || ret_comp->type == DEMANGLE_COMPONENT_QUAL_NAME
948 || ret_comp->type == DEMANGLE_COMPONENT_TEMPLATE))
949 ret = cp_comp_to_string (ret_comp, 10);
951 return ret;
954 /* DEMANGLED_NAME is the name of a function, including parameters and
955 (optionally) a return type. Return the name of the function
956 without parameters or return type, or NULL if we can not parse the
957 name. */
959 gdb::unique_xmalloc_ptr<char>
960 cp_remove_params (const char *demangled_name)
962 return cp_remove_params_1 (demangled_name, true);
965 /* See cp-support.h. */
967 gdb::unique_xmalloc_ptr<char>
968 cp_remove_params_if_any (const char *demangled_name, bool completion_mode)
970 /* Trying to remove parameters from the empty string fails. If
971 we're completing / matching everything, avoid returning NULL
972 which would make callers interpret the result as an error. */
973 if (demangled_name[0] == '\0' && completion_mode)
974 return make_unique_xstrdup ("");
976 gdb::unique_xmalloc_ptr<char> without_params
977 = cp_remove_params_1 (demangled_name, false);
979 if (without_params == NULL && completion_mode)
981 std::string copy = demangled_name;
983 while (!copy.empty ())
985 copy.pop_back ();
986 without_params = cp_remove_params_1 (copy.c_str (), false);
987 if (without_params != NULL)
988 break;
992 return without_params;
995 /* Here are some random pieces of trivia to keep in mind while trying
996 to take apart demangled names:
998 - Names can contain function arguments or templates, so the process
999 has to be, to some extent recursive: maybe keep track of your
1000 depth based on encountering <> and ().
1002 - Parentheses don't just have to happen at the end of a name: they
1003 can occur even if the name in question isn't a function, because
1004 a template argument might be a type that's a function.
1006 - Conversely, even if you're trying to deal with a function, its
1007 demangled name might not end with ')': it could be a const or
1008 volatile class method, in which case it ends with "const" or
1009 "volatile".
1011 - Parentheses are also used in anonymous namespaces: a variable
1012 'foo' in an anonymous namespace gets demangled as "(anonymous
1013 namespace)::foo".
1015 - And operator names can contain parentheses or angle brackets. */
1017 /* FIXME: carlton/2003-03-13: We have several functions here with
1018 overlapping functionality; can we combine them? Also, do they
1019 handle all the above considerations correctly? */
1022 /* This returns the length of first component of NAME, which should be
1023 the demangled name of a C++ variable/function/method/etc.
1024 Specifically, it returns the index of the first colon forming the
1025 boundary of the first component: so, given 'A::foo' or 'A::B::foo'
1026 it returns the 1, and given 'foo', it returns 0. */
1028 /* The character in NAME indexed by the return value is guaranteed to
1029 always be either ':' or '\0'. */
1031 /* NOTE: carlton/2003-03-13: This function is currently only intended
1032 for internal use: it's probably not entirely safe when called on
1033 user-generated input, because some of the 'index += 2' lines in
1034 cp_find_first_component_aux might go past the end of malformed
1035 input. */
1037 unsigned int
1038 cp_find_first_component (const char *name)
1040 return cp_find_first_component_aux (name, 0);
1043 /* Helper function for cp_find_first_component. Like that function,
1044 it returns the length of the first component of NAME, but to make
1045 the recursion easier, it also stops if it reaches an unexpected ')'
1046 or '>' if the value of PERMISSIVE is nonzero. */
1048 static unsigned int
1049 cp_find_first_component_aux (const char *name, int permissive)
1051 unsigned int index = 0;
1052 /* Operator names can show up in unexpected places. Since these can
1053 contain parentheses or angle brackets, they can screw up the
1054 recursion. But not every string 'operator' is part of an
1055 operator name: e.g. you could have a variable 'cooperator'. So
1056 this variable tells us whether or not we should treat the string
1057 'operator' as starting an operator. */
1058 int operator_possible = 1;
1060 for (;; ++index)
1062 switch (name[index])
1064 case '<':
1065 /* Template; eat it up. The calls to cp_first_component
1066 should only return (I hope!) when they reach the '>'
1067 terminating the component or a '::' between two
1068 components. (Hence the '+ 2'.) */
1069 index += 1;
1070 for (index += cp_find_first_component_aux (name + index, 1);
1071 name[index] != '>';
1072 index += cp_find_first_component_aux (name + index, 1))
1074 if (name[index] != ':')
1076 demangled_name_complaint (name);
1077 return strlen (name);
1079 index += 2;
1081 operator_possible = 1;
1082 break;
1083 case '(':
1084 /* Similar comment as to '<'. */
1085 index += 1;
1086 for (index += cp_find_first_component_aux (name + index, 1);
1087 name[index] != ')';
1088 index += cp_find_first_component_aux (name + index, 1))
1090 if (name[index] != ':')
1092 demangled_name_complaint (name);
1093 return strlen (name);
1095 index += 2;
1097 operator_possible = 1;
1098 break;
1099 case '>':
1100 case ')':
1101 if (permissive)
1102 return index;
1103 else
1105 demangled_name_complaint (name);
1106 return strlen (name);
1108 case '\0':
1109 return index;
1110 case ':':
1111 /* ':' marks a component iff the next character is also a ':'.
1112 Otherwise it is probably malformed input. */
1113 if (name[index + 1] == ':')
1114 return index;
1115 break;
1116 case 'o':
1117 /* Operator names can screw up the recursion. */
1118 if (operator_possible
1119 && startswith (name + index, CP_OPERATOR_STR))
1121 index += CP_OPERATOR_LEN;
1122 while (ISSPACE(name[index]))
1123 ++index;
1124 switch (name[index])
1126 case '\0':
1127 return index;
1128 /* Skip over one less than the appropriate number of
1129 characters: the for loop will skip over the last
1130 one. */
1131 case '<':
1132 if (name[index + 1] == '<')
1133 index += 1;
1134 else
1135 index += 0;
1136 break;
1137 case '>':
1138 case '-':
1139 if (name[index + 1] == '>')
1140 index += 1;
1141 else
1142 index += 0;
1143 break;
1144 case '(':
1145 index += 1;
1146 break;
1147 default:
1148 index += 0;
1149 break;
1152 operator_possible = 0;
1153 break;
1154 case ' ':
1155 case ',':
1156 case '.':
1157 case '&':
1158 case '*':
1159 /* NOTE: carlton/2003-04-18: I'm not sure what the precise
1160 set of relevant characters are here: it's necessary to
1161 include any character that can show up before 'operator'
1162 in a demangled name, and it's safe to include any
1163 character that can't be part of an identifier's name. */
1164 operator_possible = 1;
1165 break;
1166 default:
1167 operator_possible = 0;
1168 break;
1173 /* Complain about a demangled name that we don't know how to parse.
1174 NAME is the demangled name in question. */
1176 static void
1177 demangled_name_complaint (const char *name)
1179 complaint ("unexpected demangled name '%s'", name);
1182 /* If NAME is the fully-qualified name of a C++
1183 function/variable/method/etc., this returns the length of its
1184 entire prefix: all of the namespaces and classes that make up its
1185 name. Given 'A::foo', it returns 1, given 'A::B::foo', it returns
1186 4, given 'foo', it returns 0. */
1188 unsigned int
1189 cp_entire_prefix_len (const char *name)
1191 unsigned int current_len = cp_find_first_component (name);
1192 unsigned int previous_len = 0;
1194 while (name[current_len] != '\0')
1196 gdb_assert (name[current_len] == ':');
1197 previous_len = current_len;
1198 /* Skip the '::'. */
1199 current_len += 2;
1200 current_len += cp_find_first_component (name + current_len);
1203 return previous_len;
1206 /* Overload resolution functions. */
1208 /* Test to see if SYM is a symbol that we haven't seen corresponding
1209 to a function named OLOAD_NAME. If so, add it to
1210 OVERLOAD_LIST. */
1212 static void
1213 overload_list_add_symbol (struct symbol *sym,
1214 const char *oload_name,
1215 std::vector<symbol *> *overload_list)
1217 /* If there is no type information, we can't do anything, so
1218 skip. */
1219 if (sym->type () == NULL)
1220 return;
1222 /* skip any symbols that we've already considered. */
1223 for (symbol *listed_sym : *overload_list)
1224 if (strcmp (sym->linkage_name (), listed_sym->linkage_name ()) == 0)
1225 return;
1227 /* Get the demangled name without parameters */
1228 gdb::unique_xmalloc_ptr<char> sym_name
1229 = cp_remove_params (sym->natural_name ());
1230 if (!sym_name)
1231 return;
1233 /* skip symbols that cannot match */
1234 if (strcmp (sym_name.get (), oload_name) != 0)
1235 return;
1237 overload_list->push_back (sym);
1240 /* Return a null-terminated list of pointers to function symbols that
1241 are named FUNC_NAME and are visible within NAMESPACE. */
1243 struct std::vector<symbol *>
1244 make_symbol_overload_list (const char *func_name,
1245 const char *the_namespace)
1247 const char *name;
1248 std::vector<symbol *> overload_list;
1250 overload_list.reserve (100);
1252 add_symbol_overload_list_using (func_name, the_namespace, &overload_list);
1254 if (the_namespace[0] == '\0')
1255 name = func_name;
1256 else
1258 char *concatenated_name
1259 = (char *) alloca (strlen (the_namespace) + 2 + strlen (func_name) + 1);
1260 strcpy (concatenated_name, the_namespace);
1261 strcat (concatenated_name, "::");
1262 strcat (concatenated_name, func_name);
1263 name = concatenated_name;
1266 add_symbol_overload_list_qualified (name, &overload_list);
1267 return overload_list;
1270 /* Add all symbols with a name matching NAME in BLOCK to the overload
1271 list. */
1273 static void
1274 add_symbol_overload_list_block (const char *name,
1275 const struct block *block,
1276 std::vector<symbol *> *overload_list)
1278 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1280 for (struct symbol *sym : block_iterator_range (block, &lookup_name))
1281 overload_list_add_symbol (sym, name, overload_list);
1284 /* Adds the function FUNC_NAME from NAMESPACE to the overload set. */
1286 static void
1287 add_symbol_overload_list_namespace (const char *func_name,
1288 const char *the_namespace,
1289 std::vector<symbol *> *overload_list)
1291 const char *name;
1292 const struct block *block = NULL;
1294 if (the_namespace[0] == '\0')
1295 name = func_name;
1296 else
1298 char *concatenated_name
1299 = (char *) alloca (strlen (the_namespace) + 2 + strlen (func_name) + 1);
1301 strcpy (concatenated_name, the_namespace);
1302 strcat (concatenated_name, "::");
1303 strcat (concatenated_name, func_name);
1304 name = concatenated_name;
1307 /* Look in the static block. */
1308 block = get_selected_block (0);
1309 block = block == nullptr ? nullptr : block->static_block ();
1310 if (block != nullptr)
1312 add_symbol_overload_list_block (name, block, overload_list);
1314 /* Look in the global block. */
1315 block = block->global_block ();
1316 if (block)
1317 add_symbol_overload_list_block (name, block, overload_list);
1321 /* Search the namespace of the given type and namespace of and public
1322 base types. */
1324 static void
1325 add_symbol_overload_list_adl_namespace (struct type *type,
1326 const char *func_name,
1327 std::vector<symbol *> *overload_list)
1329 char *the_namespace;
1330 const char *type_name;
1331 int i, prefix_len;
1333 while (type->is_pointer_or_reference ()
1334 || type->code () == TYPE_CODE_ARRAY
1335 || type->code () == TYPE_CODE_TYPEDEF)
1337 if (type->code () == TYPE_CODE_TYPEDEF)
1338 type = check_typedef (type);
1339 else
1340 type = type->target_type ();
1343 type_name = type->name ();
1345 if (type_name == NULL)
1346 return;
1348 prefix_len = cp_entire_prefix_len (type_name);
1350 if (prefix_len != 0)
1352 the_namespace = (char *) alloca (prefix_len + 1);
1353 strncpy (the_namespace, type_name, prefix_len);
1354 the_namespace[prefix_len] = '\0';
1356 add_symbol_overload_list_namespace (func_name, the_namespace,
1357 overload_list);
1360 /* Check public base type */
1361 if (type->code () == TYPE_CODE_STRUCT)
1362 for (i = 0; i < TYPE_N_BASECLASSES (type); i++)
1364 if (BASETYPE_VIA_PUBLIC (type, i))
1365 add_symbol_overload_list_adl_namespace (TYPE_BASECLASS (type, i),
1366 func_name,
1367 overload_list);
1371 /* Adds to OVERLOAD_LIST the overload list overload candidates for
1372 FUNC_NAME found through argument dependent lookup. */
1374 void
1375 add_symbol_overload_list_adl (gdb::array_view<type *> arg_types,
1376 const char *func_name,
1377 std::vector<symbol *> *overload_list)
1379 for (type *arg_type : arg_types)
1380 add_symbol_overload_list_adl_namespace (arg_type, func_name,
1381 overload_list);
1384 /* This applies the using directives to add namespaces to search in,
1385 and then searches for overloads in all of those namespaces. It
1386 adds the symbols found to sym_return_val. Arguments are as in
1387 make_symbol_overload_list. */
1389 static void
1390 add_symbol_overload_list_using (const char *func_name,
1391 const char *the_namespace,
1392 std::vector<symbol *> *overload_list)
1394 struct using_direct *current;
1395 const struct block *block;
1397 /* First, go through the using directives. If any of them apply,
1398 look in the appropriate namespaces for new functions to match
1399 on. */
1401 for (block = get_selected_block (0);
1402 block != NULL;
1403 block = block->superblock ())
1404 for (current = block->get_using ();
1405 current != NULL;
1406 current = current->next)
1408 /* Prevent recursive calls. */
1409 if (current->searched)
1410 continue;
1412 /* If this is a namespace alias or imported declaration ignore
1413 it. */
1414 if (current->alias != NULL || current->declaration != NULL)
1415 continue;
1417 if (strcmp (the_namespace, current->import_dest) == 0)
1419 /* Mark this import as searched so that the recursive call
1420 does not search it again. */
1421 scoped_restore reset_directive_searched
1422 = make_scoped_restore (&current->searched, 1);
1424 add_symbol_overload_list_using (func_name,
1425 current->import_src,
1426 overload_list);
1430 /* Now, add names for this namespace. */
1431 add_symbol_overload_list_namespace (func_name, the_namespace,
1432 overload_list);
1435 /* This does the bulk of the work of finding overloaded symbols.
1436 FUNC_NAME is the name of the overloaded function we're looking for
1437 (possibly including namespace info). */
1439 static void
1440 add_symbol_overload_list_qualified (const char *func_name,
1441 std::vector<symbol *> *overload_list)
1443 const struct block *surrounding_static_block = 0;
1445 /* Look through the partial symtabs for all symbols which begin by
1446 matching FUNC_NAME. Make sure we read that symbol table in. */
1448 for (objfile *objf : current_program_space->objfiles ())
1449 objf->expand_symtabs_for_function (func_name);
1451 /* Search upwards from currently selected frame (so that we can
1452 complete on local vars. */
1454 for (const block *b = get_selected_block (0);
1455 b != nullptr;
1456 b = b->superblock ())
1457 add_symbol_overload_list_block (func_name, b, overload_list);
1459 surrounding_static_block = get_selected_block (0);
1460 surrounding_static_block = (surrounding_static_block == nullptr
1461 ? nullptr
1462 : surrounding_static_block->static_block ());
1464 /* Go through the symtabs and check the externs and statics for
1465 symbols which match. */
1467 const block *block = get_selected_block (0);
1468 struct objfile *current_objfile = block ? block->objfile () : nullptr;
1470 gdbarch_iterate_over_objfiles_in_search_order
1471 (current_objfile ? current_objfile->arch () : current_inferior ()->arch (),
1472 [func_name, surrounding_static_block, &overload_list]
1473 (struct objfile *obj)
1475 for (compunit_symtab *cust : obj->compunits ())
1477 QUIT;
1478 const struct block *b = cust->blockvector ()->global_block ();
1479 add_symbol_overload_list_block (func_name, b, overload_list);
1481 b = cust->blockvector ()->static_block ();
1482 /* Don't do this block twice. */
1483 if (b == surrounding_static_block)
1484 continue;
1486 add_symbol_overload_list_block (func_name, b, overload_list);
1489 return 0;
1490 }, current_objfile);
1493 /* Lookup the rtti type for a class name. */
1495 struct type *
1496 cp_lookup_rtti_type (const char *name, const struct block *block)
1498 struct symbol * rtti_sym;
1499 struct type * rtti_type;
1501 /* Use VAR_DOMAIN here as NAME may be a typedef. PR 18141, 18417.
1502 Classes "live" in both STRUCT_DOMAIN and VAR_DOMAIN. */
1503 rtti_sym = lookup_symbol (name, block, VAR_DOMAIN, NULL).symbol;
1505 if (rtti_sym == NULL)
1507 warning (_("RTTI symbol not found for class '%s'"), name);
1508 return NULL;
1511 if (rtti_sym->aclass () != LOC_TYPEDEF)
1513 warning (_("RTTI symbol for class '%s' is not a type"), name);
1514 return NULL;
1517 rtti_type = check_typedef (rtti_sym->type ());
1519 switch (rtti_type->code ())
1521 case TYPE_CODE_STRUCT:
1522 break;
1523 case TYPE_CODE_NAMESPACE:
1524 /* chastain/2003-11-26: the symbol tables often contain fake
1525 symbols for namespaces with the same name as the struct.
1526 This warning is an indication of a bug in the lookup order
1527 or a bug in the way that the symbol tables are populated. */
1528 warning (_("RTTI symbol for class '%s' is a namespace"), name);
1529 return NULL;
1530 default:
1531 warning (_("RTTI symbol for class '%s' has bad type"), name);
1532 return NULL;
1535 return rtti_type;
1538 #ifdef HAVE_WORKING_FORK
1540 /* If true, attempt to catch crashes in the demangler and print
1541 useful debugging information. */
1543 static bool catch_demangler_crashes = true;
1545 /* Stack context and environment for demangler crash recovery. */
1547 static thread_local SIGJMP_BUF *gdb_demangle_jmp_buf;
1549 /* If true, attempt to dump core from the signal handler. */
1551 static std::atomic<bool> gdb_demangle_attempt_core_dump;
1553 /* Signal handler for gdb_demangle. */
1555 static void
1556 gdb_demangle_signal_handler (int signo)
1558 if (gdb_demangle_attempt_core_dump)
1560 if (fork () == 0)
1561 dump_core ();
1563 gdb_demangle_attempt_core_dump = false;
1566 SIGLONGJMP (*gdb_demangle_jmp_buf, signo);
1569 /* A helper for gdb_demangle that reports a demangling failure. */
1571 static void
1572 report_failed_demangle (const char *name, bool core_dump_allowed,
1573 int crash_signal)
1575 static bool error_reported = false;
1577 if (!error_reported)
1579 std::string short_msg
1580 = string_printf (_("unable to demangle '%s' "
1581 "(demangler failed with signal %d)"),
1582 name, crash_signal);
1584 std::string long_msg
1585 = string_printf ("%s:%d: %s: %s", __FILE__, __LINE__,
1586 "demangler-warning", short_msg.c_str ());
1588 target_terminal::scoped_restore_terminal_state term_state;
1589 target_terminal::ours_for_output ();
1591 begin_line ();
1592 if (core_dump_allowed)
1593 gdb_printf (gdb_stderr,
1594 _("%s\nAttempting to dump core.\n"),
1595 long_msg.c_str ());
1596 else
1597 warn_cant_dump_core (long_msg.c_str ());
1599 demangler_warning (__FILE__, __LINE__, "%s", short_msg.c_str ());
1601 error_reported = true;
1605 #endif
1607 /* A wrapper for bfd_demangle. */
1609 gdb::unique_xmalloc_ptr<char>
1610 gdb_demangle (const char *name, int options)
1612 gdb::unique_xmalloc_ptr<char> result;
1613 int crash_signal = 0;
1615 #ifdef HAVE_WORKING_FORK
1616 scoped_segv_handler_restore restore_segv
1617 (catch_demangler_crashes
1618 ? gdb_demangle_signal_handler
1619 : nullptr);
1621 bool core_dump_allowed = gdb_demangle_attempt_core_dump;
1622 SIGJMP_BUF jmp_buf;
1623 scoped_restore restore_jmp_buf
1624 = make_scoped_restore (&gdb_demangle_jmp_buf, &jmp_buf);
1625 if (catch_demangler_crashes)
1627 /* The signal handler may keep the signal blocked when we longjmp out
1628 of it. If we have sigprocmask, we can use it to unblock the signal
1629 afterwards and we can avoid the performance overhead of saving the
1630 signal mask just in case the signal gets triggered. Otherwise, just
1631 tell sigsetjmp to save the mask. */
1632 #ifdef HAVE_SIGPROCMASK
1633 crash_signal = SIGSETJMP (*gdb_demangle_jmp_buf, 0);
1634 #else
1635 crash_signal = SIGSETJMP (*gdb_demangle_jmp_buf, 1);
1636 #endif
1638 #endif
1640 if (crash_signal == 0)
1641 result.reset (bfd_demangle (NULL, name, options | DMGL_VERBOSE));
1643 #ifdef HAVE_WORKING_FORK
1644 if (catch_demangler_crashes)
1646 if (crash_signal != 0)
1648 #ifdef HAVE_SIGPROCMASK
1649 /* If we got the signal, SIGSEGV may still be blocked; restore it. */
1650 sigset_t segv_sig_set;
1651 sigemptyset (&segv_sig_set);
1652 sigaddset (&segv_sig_set, SIGSEGV);
1653 gdb_sigmask (SIG_UNBLOCK, &segv_sig_set, NULL);
1654 #endif
1656 /* If there was a failure, we can't report it here, because
1657 we might be in a background thread. Instead, arrange for
1658 the reporting to happen on the main thread. */
1659 std::string copy = name;
1660 run_on_main_thread ([=, copy = std::move (copy)] ()
1662 report_failed_demangle (copy.c_str (), core_dump_allowed,
1663 crash_signal);
1666 result = NULL;
1669 #endif
1671 return result;
1674 /* See cp-support.h. */
1676 char *
1677 gdb_cplus_demangle_print (int options,
1678 struct demangle_component *tree,
1679 int estimated_length,
1680 size_t *p_allocated_size)
1682 return cplus_demangle_print (options | DMGL_VERBOSE, tree,
1683 estimated_length, p_allocated_size);
1686 /* A wrapper for cplus_demangle_v3_components that forces
1687 DMGL_VERBOSE. */
1689 static struct demangle_component *
1690 gdb_cplus_demangle_v3_components (const char *mangled,
1691 int options, void **mem)
1693 return cplus_demangle_v3_components (mangled, options | DMGL_VERBOSE, mem);
1696 /* See cp-support.h. */
1698 unsigned int
1699 cp_search_name_hash (const char *search_name)
1701 /* cp_entire_prefix_len assumes a fully-qualified name with no
1702 leading "::". */
1703 if (startswith (search_name, "::"))
1704 search_name += 2;
1706 unsigned int prefix_len = cp_entire_prefix_len (search_name);
1707 if (prefix_len != 0)
1708 search_name += prefix_len + 2;
1710 unsigned int hash = 0;
1711 for (const char *string = search_name; *string != '\0'; ++string)
1713 string = skip_spaces (string);
1715 if (*string == '(')
1716 break;
1718 /* Ignore ABI tags such as "[abi:cxx11]. */
1719 if (*string == '['
1720 && startswith (string + 1, "abi:")
1721 && string[5] != ':')
1722 break;
1724 /* Ignore template parameter lists. */
1725 if (string[0] == '<'
1726 && string[1] != '(' && string[1] != '<' && string[1] != '='
1727 && string[1] != ' ' && string[1] != '\0')
1728 break;
1730 hash = SYMBOL_HASH_NEXT (hash, *string);
1732 return hash;
1735 /* Helper for cp_symbol_name_matches (i.e., symbol_name_matcher_ftype
1736 implementation for symbol_name_match_type::WILD matching). Split
1737 to a separate function for unit-testing convenience.
1739 If SYMBOL_SEARCH_NAME has more scopes than LOOKUP_NAME, we try to
1740 match ignoring the extra leading scopes of SYMBOL_SEARCH_NAME.
1741 This allows conveniently setting breakpoints on functions/methods
1742 inside any namespace/class without specifying the fully-qualified
1743 name.
1745 E.g., these match:
1747 [symbol search name] [lookup name]
1748 foo::bar::func foo::bar::func
1749 foo::bar::func bar::func
1750 foo::bar::func func
1752 While these don't:
1754 [symbol search name] [lookup name]
1755 foo::zbar::func bar::func
1756 foo::bar::func foo::func
1758 See more examples in the test_cp_symbol_name_matches selftest
1759 function below.
1761 See symbol_name_matcher_ftype for description of SYMBOL_SEARCH_NAME
1762 and COMP_MATCH_RES.
1764 LOOKUP_NAME/LOOKUP_NAME_LEN is the name we're looking up.
1766 See strncmp_iw_with_mode for description of MODE.
1769 static bool
1770 cp_symbol_name_matches_1 (const char *symbol_search_name,
1771 const char *lookup_name,
1772 size_t lookup_name_len,
1773 strncmp_iw_mode mode,
1774 completion_match_result *comp_match_res)
1776 const char *sname = symbol_search_name;
1777 completion_match_for_lcd *match_for_lcd
1778 = (comp_match_res != NULL ? &comp_match_res->match_for_lcd : NULL);
1780 gdb_assert (match_for_lcd == nullptr || match_for_lcd->empty ());
1782 while (true)
1784 if (strncmp_iw_with_mode (sname, lookup_name, lookup_name_len,
1785 mode, language_cplus, match_for_lcd, true) == 0)
1787 if (comp_match_res != NULL)
1789 /* Note here we set different MATCH and MATCH_FOR_LCD
1790 strings. This is because with
1792 (gdb) b push_bac[TAB]
1794 we want the completion matches to list
1796 std::vector<int>::push_back(...)
1797 std::vector<char>::push_back(...)
1799 etc., which are SYMBOL_SEARCH_NAMEs, while we want
1800 the input line to auto-complete to
1802 (gdb) push_back(...)
1804 which is SNAME, not to
1806 (gdb) std::vector<
1808 which would be the regular common prefix between all
1809 the matches otherwise. */
1810 comp_match_res->set_match (symbol_search_name, sname);
1812 return true;
1815 /* Clear match_for_lcd so the next strncmp_iw_with_mode call starts
1816 from scratch. */
1817 if (match_for_lcd != nullptr)
1818 match_for_lcd->clear ();
1820 unsigned int len = cp_find_first_component (sname);
1822 if (sname[len] == '\0')
1823 return false;
1825 gdb_assert (sname[len] == ':');
1826 /* Skip the '::'. */
1827 sname += len + 2;
1831 /* C++ symbol_name_matcher_ftype implementation. */
1833 static bool
1834 cp_fq_symbol_name_matches (const char *symbol_search_name,
1835 const lookup_name_info &lookup_name,
1836 completion_match_result *comp_match_res)
1838 /* Get the demangled name. */
1839 const std::string &name = lookup_name.cplus ().lookup_name ();
1840 completion_match_for_lcd *match_for_lcd
1841 = (comp_match_res != NULL ? &comp_match_res->match_for_lcd : NULL);
1842 strncmp_iw_mode mode = (lookup_name.completion_mode ()
1843 ? strncmp_iw_mode::NORMAL
1844 : strncmp_iw_mode::MATCH_PARAMS);
1846 if (strncmp_iw_with_mode (symbol_search_name,
1847 name.c_str (), name.size (),
1848 mode, language_cplus, match_for_lcd) == 0)
1850 if (comp_match_res != NULL)
1851 comp_match_res->set_match (symbol_search_name);
1852 return true;
1855 return false;
1858 /* C++ symbol_name_matcher_ftype implementation for wild matches.
1859 Defers work to cp_symbol_name_matches_1. */
1861 static bool
1862 cp_symbol_name_matches (const char *symbol_search_name,
1863 const lookup_name_info &lookup_name,
1864 completion_match_result *comp_match_res)
1866 /* Get the demangled name. */
1867 const std::string &name = lookup_name.cplus ().lookup_name ();
1869 strncmp_iw_mode mode = (lookup_name.completion_mode ()
1870 ? strncmp_iw_mode::NORMAL
1871 : strncmp_iw_mode::MATCH_PARAMS);
1873 return cp_symbol_name_matches_1 (symbol_search_name,
1874 name.c_str (), name.size (),
1875 mode, comp_match_res);
1878 /* See cp-support.h. */
1880 symbol_name_matcher_ftype *
1881 cp_get_symbol_name_matcher (const lookup_name_info &lookup_name)
1883 switch (lookup_name.match_type ())
1885 case symbol_name_match_type::FULL:
1886 case symbol_name_match_type::EXPRESSION:
1887 case symbol_name_match_type::SEARCH_NAME:
1888 return cp_fq_symbol_name_matches;
1889 case symbol_name_match_type::WILD:
1890 return cp_symbol_name_matches;
1893 gdb_assert_not_reached ("");
1896 #if GDB_SELF_TEST
1898 namespace selftests {
1900 static void
1901 test_cp_symbol_name_matches ()
1903 #define CHECK_MATCH(SYMBOL, INPUT) \
1904 SELF_CHECK (cp_symbol_name_matches_1 (SYMBOL, \
1905 INPUT, sizeof (INPUT) - 1, \
1906 strncmp_iw_mode::MATCH_PARAMS, \
1907 NULL))
1909 #define CHECK_NOT_MATCH(SYMBOL, INPUT) \
1910 SELF_CHECK (!cp_symbol_name_matches_1 (SYMBOL, \
1911 INPUT, sizeof (INPUT) - 1, \
1912 strncmp_iw_mode::MATCH_PARAMS, \
1913 NULL))
1915 /* Like CHECK_MATCH, and also check that INPUT (and all substrings
1916 that start at index 0) completes to SYMBOL. */
1917 #define CHECK_MATCH_C(SYMBOL, INPUT) \
1918 do \
1920 CHECK_MATCH (SYMBOL, INPUT); \
1921 for (size_t i = 0; i < sizeof (INPUT) - 1; i++) \
1922 SELF_CHECK (cp_symbol_name_matches_1 (SYMBOL, INPUT, i, \
1923 strncmp_iw_mode::NORMAL, \
1924 NULL)); \
1925 } while (0)
1927 /* Like CHECK_NOT_MATCH, and also check that INPUT does NOT complete
1928 to SYMBOL. */
1929 #define CHECK_NOT_MATCH_C(SYMBOL, INPUT) \
1930 do \
1932 CHECK_NOT_MATCH (SYMBOL, INPUT); \
1933 SELF_CHECK (!cp_symbol_name_matches_1 (SYMBOL, INPUT, \
1934 sizeof (INPUT) - 1, \
1935 strncmp_iw_mode::NORMAL, \
1936 NULL)); \
1937 } while (0)
1939 /* Lookup name without parens matches all overloads. */
1940 CHECK_MATCH_C ("function()", "function");
1941 CHECK_MATCH_C ("function(int)", "function");
1943 /* Check whitespace around parameters is ignored. */
1944 CHECK_MATCH_C ("function()", "function ()");
1945 CHECK_MATCH_C ("function ( )", "function()");
1946 CHECK_MATCH_C ("function ()", "function( )");
1947 CHECK_MATCH_C ("func(int)", "func( int )");
1948 CHECK_MATCH_C ("func(int)", "func ( int ) ");
1949 CHECK_MATCH_C ("func ( int )", "func( int )");
1950 CHECK_MATCH_C ("func ( int )", "func ( int ) ");
1952 /* Check symbol name prefixes aren't incorrectly matched. */
1953 CHECK_NOT_MATCH ("func", "function");
1954 CHECK_NOT_MATCH ("function", "func");
1955 CHECK_NOT_MATCH ("function()", "func");
1957 /* Check that if the lookup name includes parameters, only the right
1958 overload matches. */
1959 CHECK_MATCH_C ("function(int)", "function(int)");
1960 CHECK_NOT_MATCH_C ("function(int)", "function()");
1962 /* Check that whitespace within symbol names is not ignored. */
1963 CHECK_NOT_MATCH_C ("function", "func tion");
1964 CHECK_NOT_MATCH_C ("func__tion", "func_ _tion");
1965 CHECK_NOT_MATCH_C ("func11tion", "func1 1tion");
1967 /* Check the converse, which can happen with template function,
1968 where the return type is part of the demangled name. */
1969 CHECK_NOT_MATCH_C ("func tion", "function");
1970 CHECK_NOT_MATCH_C ("func1 1tion", "func11tion");
1971 CHECK_NOT_MATCH_C ("func_ _tion", "func__tion");
1973 /* Within parameters too. */
1974 CHECK_NOT_MATCH_C ("func(param)", "func(par am)");
1976 /* Check handling of whitespace around C++ operators. */
1977 CHECK_NOT_MATCH_C ("operator<<", "opera tor<<");
1978 CHECK_NOT_MATCH_C ("operator<<", "operator< <");
1979 CHECK_NOT_MATCH_C ("operator<<", "operator < <");
1980 CHECK_NOT_MATCH_C ("operator==", "operator= =");
1981 CHECK_NOT_MATCH_C ("operator==", "operator = =");
1982 CHECK_MATCH_C ("operator<<", "operator <<");
1983 CHECK_MATCH_C ("operator<<()", "operator <<");
1984 CHECK_NOT_MATCH_C ("operator<<()", "operator<<(int)");
1985 CHECK_NOT_MATCH_C ("operator<<(int)", "operator<<()");
1986 CHECK_MATCH_C ("operator==", "operator ==");
1987 CHECK_MATCH_C ("operator==()", "operator ==");
1988 CHECK_MATCH_C ("operator <<", "operator<<");
1989 CHECK_MATCH_C ("operator ==", "operator==");
1990 CHECK_MATCH_C ("operator bool", "operator bool");
1991 CHECK_MATCH_C ("operator bool ()", "operator bool");
1992 CHECK_MATCH_C ("operatorX<<", "operatorX < <");
1993 CHECK_MATCH_C ("Xoperator<<", "Xoperator < <");
1995 CHECK_MATCH_C ("operator()(int)", "operator()(int)");
1996 CHECK_MATCH_C ("operator()(int)", "operator ( ) ( int )");
1997 CHECK_MATCH_C ("operator()<long>(int)", "operator ( ) < long > ( int )");
1998 /* The first "()" is not the parameter list. */
1999 CHECK_NOT_MATCH ("operator()(int)", "operator");
2001 /* Misc user-defined operator tests. */
2003 CHECK_NOT_MATCH_C ("operator/=()", "operator ^=");
2004 /* Same length at end of input. */
2005 CHECK_NOT_MATCH_C ("operator>>", "operator[]");
2006 /* Same length but not at end of input. */
2007 CHECK_NOT_MATCH_C ("operator>>()", "operator[]()");
2009 CHECK_MATCH_C ("base::operator char*()", "base::operator char*()");
2010 CHECK_MATCH_C ("base::operator char*()", "base::operator char * ()");
2011 CHECK_MATCH_C ("base::operator char**()", "base::operator char * * ()");
2012 CHECK_MATCH ("base::operator char**()", "base::operator char * *");
2013 CHECK_MATCH_C ("base::operator*()", "base::operator*()");
2014 CHECK_NOT_MATCH_C ("base::operator char*()", "base::operatorc");
2015 CHECK_NOT_MATCH ("base::operator char*()", "base::operator char");
2016 CHECK_NOT_MATCH ("base::operator char*()", "base::operat");
2018 /* Check handling of whitespace around C++ scope operators. */
2019 CHECK_NOT_MATCH_C ("foo::bar", "foo: :bar");
2020 CHECK_MATCH_C ("foo::bar", "foo :: bar");
2021 CHECK_MATCH_C ("foo :: bar", "foo::bar");
2023 CHECK_MATCH_C ("abc::def::ghi()", "abc::def::ghi()");
2024 CHECK_MATCH_C ("abc::def::ghi ( )", "abc::def::ghi()");
2025 CHECK_MATCH_C ("abc::def::ghi()", "abc::def::ghi ( )");
2026 CHECK_MATCH_C ("function()", "function()");
2027 CHECK_MATCH_C ("bar::function()", "bar::function()");
2029 /* Wild matching tests follow. */
2031 /* Tests matching symbols in some scope. */
2032 CHECK_MATCH_C ("foo::function()", "function");
2033 CHECK_MATCH_C ("foo::function(int)", "function");
2034 CHECK_MATCH_C ("foo::bar::function()", "function");
2035 CHECK_MATCH_C ("bar::function()", "bar::function");
2036 CHECK_MATCH_C ("foo::bar::function()", "bar::function");
2037 CHECK_MATCH_C ("foo::bar::function(int)", "bar::function");
2039 /* Same, with parameters in the lookup name. */
2040 CHECK_MATCH_C ("foo::function()", "function()");
2041 CHECK_MATCH_C ("foo::bar::function()", "function()");
2042 CHECK_MATCH_C ("foo::function(int)", "function(int)");
2043 CHECK_MATCH_C ("foo::function()", "foo::function()");
2044 CHECK_MATCH_C ("foo::bar::function()", "bar::function()");
2045 CHECK_MATCH_C ("foo::bar::function(int)", "bar::function(int)");
2046 CHECK_MATCH_C ("bar::function()", "bar::function()");
2048 CHECK_NOT_MATCH_C ("foo::bar::function(int)", "bar::function()");
2050 CHECK_MATCH_C ("(anonymous namespace)::bar::function(int)",
2051 "bar::function(int)");
2052 CHECK_MATCH_C ("foo::(anonymous namespace)::bar::function(int)",
2053 "function(int)");
2055 /* Lookup scope wider than symbol scope, should not match. */
2056 CHECK_NOT_MATCH_C ("function()", "bar::function");
2057 CHECK_NOT_MATCH_C ("function()", "bar::function()");
2059 /* Explicit global scope doesn't match. */
2060 CHECK_NOT_MATCH_C ("foo::function()", "::function");
2061 CHECK_NOT_MATCH_C ("foo::function()", "::function()");
2062 CHECK_NOT_MATCH_C ("foo::function(int)", "::function()");
2063 CHECK_NOT_MATCH_C ("foo::function(int)", "::function(int)");
2065 /* Test ABI tag matching/ignoring. */
2067 /* If the symbol name has an ABI tag, but the lookup name doesn't,
2068 then the ABI tag in the symbol name is ignored. */
2069 CHECK_MATCH_C ("function[abi:foo]()", "function");
2070 CHECK_MATCH_C ("function[abi:foo](int)", "function");
2071 CHECK_MATCH_C ("function[abi:foo]()", "function ()");
2072 CHECK_NOT_MATCH_C ("function[abi:foo]()", "function (int)");
2074 CHECK_MATCH_C ("function[abi:foo]()", "function[abi:foo]");
2075 CHECK_MATCH_C ("function[abi:foo](int)", "function[abi:foo]");
2076 CHECK_MATCH_C ("function[abi:foo]()", "function[abi:foo] ()");
2077 CHECK_MATCH_C ("function[abi:foo][abi:bar]()", "function");
2078 CHECK_MATCH_C ("function[abi:foo][abi:bar](int)", "function");
2079 CHECK_MATCH_C ("function[abi:foo][abi:bar]()", "function[abi:foo]");
2080 CHECK_MATCH_C ("function[abi:foo][abi:bar](int)", "function[abi:foo]");
2081 CHECK_MATCH_C ("function[abi:foo][abi:bar]()", "function[abi:foo] ()");
2082 CHECK_NOT_MATCH_C ("function[abi:foo][abi:bar]()", "function[abi:foo] (int)");
2084 CHECK_MATCH_C ("function [abi:foo][abi:bar] ( )", "function [abi:foo]");
2086 /* If the symbol name does not have an ABI tag, while the lookup
2087 name has one, then there's no match. */
2088 CHECK_NOT_MATCH_C ("function()", "function[abi:foo]()");
2089 CHECK_NOT_MATCH_C ("function()", "function[abi:foo]");
2092 /* If non-NULL, return STR wrapped in quotes. Otherwise, return a
2093 "<null>" string (with no quotes). */
2095 static std::string
2096 quote (const char *str)
2098 if (str != NULL)
2099 return std::string (1, '"') + str + '"';
2100 else
2101 return "<null>";
2104 /* Check that removing parameter info out of NAME produces EXPECTED.
2105 COMPLETION_MODE indicates whether we're testing normal and
2106 completion mode. FILE and LINE are used to provide better test
2107 location information in case the check fails. */
2109 static void
2110 check_remove_params (const char *file, int line,
2111 const char *name, const char *expected,
2112 bool completion_mode)
2114 gdb::unique_xmalloc_ptr<char> result
2115 = cp_remove_params_if_any (name, completion_mode);
2117 if ((expected == NULL) != (result == NULL)
2118 || (expected != NULL
2119 && strcmp (result.get (), expected) != 0))
2121 error (_("%s:%d: make-paramless self-test failed: (completion=%d) "
2122 "\"%s\" -> %s, expected %s"),
2123 file, line, completion_mode, name,
2124 quote (result.get ()).c_str (), quote (expected).c_str ());
2128 /* Entry point for cp_remove_params unit tests. */
2130 static void
2131 test_cp_remove_params ()
2133 /* Check that removing parameter info out of NAME produces EXPECTED.
2134 Checks both normal and completion modes. */
2135 #define CHECK(NAME, EXPECTED) \
2136 do \
2138 check_remove_params (__FILE__, __LINE__, NAME, EXPECTED, false); \
2139 check_remove_params (__FILE__, __LINE__, NAME, EXPECTED, true); \
2141 while (0)
2143 /* Similar, but used when NAME is incomplete -- i.e., is has
2144 unbalanced parentheses. In this case, looking for the exact name
2145 should fail / return empty. */
2146 #define CHECK_INCOMPL(NAME, EXPECTED) \
2147 do \
2149 check_remove_params (__FILE__, __LINE__, NAME, NULL, false); \
2150 check_remove_params (__FILE__, __LINE__, NAME, EXPECTED, true); \
2152 while (0)
2154 CHECK ("function()", "function");
2155 CHECK_INCOMPL ("function(", "function");
2156 CHECK ("function() const", "function");
2158 CHECK ("(anonymous namespace)::A::B::C",
2159 "(anonymous namespace)::A::B::C");
2161 CHECK ("A::(anonymous namespace)",
2162 "A::(anonymous namespace)");
2164 CHECK_INCOMPL ("A::(anonymou", "A");
2166 CHECK ("A::foo<int>()",
2167 "A::foo<int>");
2169 CHECK_INCOMPL ("A::foo<int>(",
2170 "A::foo<int>");
2172 CHECK ("A::foo<(anonymous namespace)::B>::func(int)",
2173 "A::foo<(anonymous namespace)::B>::func");
2175 CHECK_INCOMPL ("A::foo<(anonymous namespace)::B>::func(in",
2176 "A::foo<(anonymous namespace)::B>::func");
2178 CHECK_INCOMPL ("A::foo<(anonymous namespace)::B>::",
2179 "A::foo<(anonymous namespace)::B>");
2181 CHECK_INCOMPL ("A::foo<(anonymous namespace)::B>:",
2182 "A::foo<(anonymous namespace)::B>");
2184 CHECK ("A::foo<(anonymous namespace)::B>",
2185 "A::foo<(anonymous namespace)::B>");
2187 CHECK_INCOMPL ("A::foo<(anonymous namespace)::B",
2188 "A::foo");
2190 /* Shouldn't this parse? Looks like a bug in
2191 cp_demangled_name_to_comp. See PR c++/22411. */
2192 #if 0
2193 CHECK ("A::foo<void(int)>::func(int)",
2194 "A::foo<void(int)>::func");
2195 #else
2196 CHECK_INCOMPL ("A::foo<void(int)>::func(int)",
2197 "A::foo");
2198 #endif
2200 CHECK_INCOMPL ("A::foo<void(int",
2201 "A::foo");
2203 #undef CHECK
2204 #undef CHECK_INCOMPL
2207 } // namespace selftests
2209 #endif /* GDB_SELF_CHECK */
2211 /* This is a front end for cp_find_first_component, for unit testing.
2212 Be careful when using it: see the NOTE above
2213 cp_find_first_component. */
2215 static void
2216 first_component_command (const char *arg, int from_tty)
2218 int len;
2219 char *prefix;
2221 if (!arg)
2222 return;
2224 len = cp_find_first_component (arg);
2225 prefix = (char *) alloca (len + 1);
2227 memcpy (prefix, arg, len);
2228 prefix[len] = '\0';
2230 gdb_printf ("%s\n", prefix);
2233 /* Implement "info vtbl". */
2235 static void
2236 info_vtbl_command (const char *arg, int from_tty)
2238 struct value *value;
2240 value = parse_and_eval (arg);
2241 cplus_print_vtable (value);
2244 /* See description in cp-support.h. */
2246 const char *
2247 find_toplevel_char (const char *s, char c)
2249 int quoted = 0; /* zero if we're not in quotes;
2250 '"' if we're in a double-quoted string;
2251 '\'' if we're in a single-quoted string. */
2252 int depth = 0; /* Number of unclosed parens we've seen. */
2253 const char *scan;
2255 for (scan = s; *scan; scan++)
2257 if (quoted)
2259 if (*scan == quoted)
2260 quoted = 0;
2261 else if (*scan == '\\' && *(scan + 1))
2262 scan++;
2264 else if (*scan == c && ! quoted && depth == 0)
2265 return scan;
2266 else if (*scan == '"' || *scan == '\'')
2267 quoted = *scan;
2268 else if (*scan == '(' || *scan == '<')
2269 depth++;
2270 else if ((*scan == ')' || *scan == '>') && depth > 0)
2271 depth--;
2272 else if (*scan == 'o' && !quoted && depth == 0)
2274 /* Handle C++ operator names. */
2275 if (strncmp (scan, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0)
2277 scan += CP_OPERATOR_LEN;
2278 if (*scan == c)
2279 return scan;
2280 while (ISSPACE (*scan))
2282 ++scan;
2283 if (*scan == c)
2284 return scan;
2286 if (*scan == '\0')
2287 break;
2289 switch (*scan)
2291 /* Skip over one less than the appropriate number of
2292 characters: the for loop will skip over the last
2293 one. */
2294 case '<':
2295 if (scan[1] == '<')
2297 scan++;
2298 if (*scan == c)
2299 return scan;
2301 break;
2302 case '>':
2303 if (scan[1] == '>')
2305 scan++;
2306 if (*scan == c)
2307 return scan;
2309 break;
2315 return 0;
2318 void _initialize_cp_support ();
2319 void
2320 _initialize_cp_support ()
2322 cmd_list_element *maintenance_cplus
2323 = add_basic_prefix_cmd ("cplus", class_maintenance,
2324 _("C++ maintenance commands."),
2325 &maint_cplus_cmd_list,
2326 0, &maintenancelist);
2327 add_alias_cmd ("cp", maintenance_cplus, class_maintenance, 1,
2328 &maintenancelist);
2330 add_cmd ("first_component",
2331 class_maintenance,
2332 first_component_command,
2333 _("Print the first class/namespace component of NAME."),
2334 &maint_cplus_cmd_list);
2336 add_info ("vtbl", info_vtbl_command,
2337 _("Show the virtual function table for a C++ object.\n\
2338 Usage: info vtbl EXPRESSION\n\
2339 Evaluate EXPRESSION and display the virtual function table for the\n\
2340 resulting object."));
2342 #ifdef HAVE_WORKING_FORK
2343 add_setshow_boolean_cmd ("catch-demangler-crashes", class_maintenance,
2344 &catch_demangler_crashes, _("\
2345 Set whether to attempt to catch demangler crashes."), _("\
2346 Show whether to attempt to catch demangler crashes."), _("\
2347 If enabled GDB will attempt to catch demangler crashes and\n\
2348 display the offending symbol."),
2349 NULL,
2350 NULL,
2351 &maintenance_set_cmdlist,
2352 &maintenance_show_cmdlist);
2354 gdb_demangle_attempt_core_dump = can_dump_core (LIMIT_CUR);
2355 #endif
2357 #if GDB_SELF_TEST
2358 selftests::register_test ("cp_symbol_name_matches",
2359 selftests::test_cp_symbol_name_matches);
2360 selftests::register_test ("cp_remove_params",
2361 selftests::test_cp_remove_params);
2362 #endif