Automatic date update in version.in
[binutils-gdb.git] / gdb / symtab.c
blobd931b3a694b32382e6536be787b2d8b1f1dfbe4d
1 /* Symbol table lookup for the GNU debugger, GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "dwarf2/call-site.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "gdbcore.h"
24 #include "frame.h"
25 #include "target.h"
26 #include "value.h"
27 #include "symfile.h"
28 #include "objfiles.h"
29 #include "gdbcmd.h"
30 #include "gdbsupport/gdb_regex.h"
31 #include "expression.h"
32 #include "language.h"
33 #include "demangle.h"
34 #include "inferior.h"
35 #include "source.h"
36 #include "filenames.h"
37 #include "objc-lang.h"
38 #include "d-lang.h"
39 #include "ada-lang.h"
40 #include "go-lang.h"
41 #include "p-lang.h"
42 #include "addrmap.h"
43 #include "cli/cli-utils.h"
44 #include "cli/cli-style.h"
45 #include "cli/cli-cmds.h"
46 #include "fnmatch.h"
47 #include "hashtab.h"
48 #include "typeprint.h"
50 #include "gdbsupport/gdb_obstack.h"
51 #include "block.h"
52 #include "dictionary.h"
54 #include <sys/types.h>
55 #include <fcntl.h>
56 #include <sys/stat.h>
57 #include <ctype.h>
58 #include "cp-abi.h"
59 #include "cp-support.h"
60 #include "observable.h"
61 #include "solist.h"
62 #include "macrotab.h"
63 #include "macroscope.h"
65 #include "parser-defs.h"
66 #include "completer.h"
67 #include "progspace-and-thread.h"
68 #include <optional>
69 #include "filename-seen-cache.h"
70 #include "arch-utils.h"
71 #include <algorithm>
72 #include <string_view>
73 #include "gdbsupport/pathstuff.h"
74 #include "gdbsupport/common-utils.h"
75 #include <optional>
77 /* Forward declarations for local functions. */
79 static void rbreak_command (const char *, int);
81 static int find_line_common (const linetable *, int, int *, int);
83 static struct block_symbol
84 lookup_symbol_aux (const char *name,
85 symbol_name_match_type match_type,
86 const struct block *block,
87 const domain_search_flags domain,
88 enum language language,
89 struct field_of_this_result *);
91 static
92 struct block_symbol lookup_local_symbol (const char *name,
93 symbol_name_match_type match_type,
94 const struct block *block,
95 const domain_search_flags domain,
96 enum language language);
98 static struct block_symbol
99 lookup_symbol_in_objfile (struct objfile *objfile,
100 enum block_enum block_index,
101 const char *name,
102 const domain_search_flags domain);
104 static void set_main_name (program_space *pspace, const char *name,
105 language lang);
107 /* Type of the data stored on the program space. */
109 struct main_info
111 /* Name of "main". */
113 std::string name_of_main;
115 /* Language of "main". */
117 enum language language_of_main = language_unknown;
120 /* Program space key for finding name and language of "main". */
122 static const registry<program_space>::key<main_info> main_progspace_key;
124 /* The default symbol cache size.
125 There is no extra cpu cost for large N (except when flushing the cache,
126 which is rare). The value here is just a first attempt. A better default
127 value may be higher or lower. A prime number can make up for a bad hash
128 computation, so that's why the number is what it is. */
129 #define DEFAULT_SYMBOL_CACHE_SIZE 1021
131 /* The maximum symbol cache size.
132 There's no method to the decision of what value to use here, other than
133 there's no point in allowing a user typo to make gdb consume all memory. */
134 #define MAX_SYMBOL_CACHE_SIZE (1024*1024)
136 /* symbol_cache_lookup returns this if a previous lookup failed to find the
137 symbol in any objfile. */
138 #define SYMBOL_LOOKUP_FAILED \
139 ((struct block_symbol) {(struct symbol *) 1, NULL})
140 #define SYMBOL_LOOKUP_FAILED_P(SIB) (SIB.symbol == (struct symbol *) 1)
142 /* Recording lookups that don't find the symbol is just as important, if not
143 more so, than recording found symbols. */
145 enum symbol_cache_slot_state
147 SYMBOL_SLOT_UNUSED,
148 SYMBOL_SLOT_NOT_FOUND,
149 SYMBOL_SLOT_FOUND
152 struct symbol_cache_slot
154 enum symbol_cache_slot_state state;
156 /* The objfile that was current when the symbol was looked up.
157 This is only needed for global blocks, but for simplicity's sake
158 we allocate the space for both. If data shows the extra space used
159 for static blocks is a problem, we can split things up then.
161 Global blocks need cache lookup to include the objfile context because
162 we need to account for gdbarch_iterate_over_objfiles_in_search_order
163 which can traverse objfiles in, effectively, any order, depending on
164 the current objfile, thus affecting which symbol is found. Normally,
165 only the current objfile is searched first, and then the rest are
166 searched in recorded order; but putting cache lookup inside
167 gdbarch_iterate_over_objfiles_in_search_order would be awkward.
168 Instead we just make the current objfile part of the context of
169 cache lookup. This means we can record the same symbol multiple times,
170 each with a different "current objfile" that was in effect when the
171 lookup was saved in the cache, but cache space is pretty cheap. */
172 const struct objfile *objfile_context;
174 /* The domain that was searched for initially. This must exactly
175 match. */
176 domain_search_flags domain;
178 union
180 struct block_symbol found;
181 char *name;
182 } value;
185 /* Clear out SLOT. */
187 static void
188 symbol_cache_clear_slot (struct symbol_cache_slot *slot)
190 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
191 xfree (slot->value.name);
192 slot->state = SYMBOL_SLOT_UNUSED;
195 /* Symbols don't specify global vs static block.
196 So keep them in separate caches. */
198 struct block_symbol_cache
200 unsigned int hits;
201 unsigned int misses;
202 unsigned int collisions;
204 /* SYMBOLS is a variable length array of this size.
205 One can imagine that in general one cache (global/static) should be a
206 fraction of the size of the other, but there's no data at the moment
207 on which to decide. */
208 unsigned int size;
210 struct symbol_cache_slot symbols[1];
213 /* Clear all slots of BSC and free BSC. */
215 static void
216 destroy_block_symbol_cache (struct block_symbol_cache *bsc)
218 if (bsc != nullptr)
220 for (unsigned int i = 0; i < bsc->size; i++)
221 symbol_cache_clear_slot (&bsc->symbols[i]);
222 xfree (bsc);
226 /* The symbol cache.
228 Searching for symbols in the static and global blocks over multiple objfiles
229 again and again can be slow, as can searching very big objfiles. This is a
230 simple cache to improve symbol lookup performance, which is critical to
231 overall gdb performance.
233 Symbols are hashed on the name, its domain, and block.
234 They are also hashed on their objfile for objfile-specific lookups. */
236 struct symbol_cache
238 symbol_cache () = default;
240 ~symbol_cache ()
242 destroy_block_symbol_cache (global_symbols);
243 destroy_block_symbol_cache (static_symbols);
246 struct block_symbol_cache *global_symbols = nullptr;
247 struct block_symbol_cache *static_symbols = nullptr;
250 /* Program space key for finding its symbol cache. */
252 static const registry<program_space>::key<symbol_cache> symbol_cache_key;
254 /* When non-zero, print debugging messages related to symtab creation. */
255 unsigned int symtab_create_debug = 0;
257 /* When non-zero, print debugging messages related to symbol lookup. */
258 unsigned int symbol_lookup_debug = 0;
260 /* The size of the cache is staged here. */
261 static unsigned int new_symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
263 /* The current value of the symbol cache size.
264 This is saved so that if the user enters a value too big we can restore
265 the original value from here. */
266 static unsigned int symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
268 /* True if a file may be known by two different basenames.
269 This is the uncommon case, and significantly slows down gdb.
270 Default set to "off" to not slow down the common case. */
271 bool basenames_may_differ = false;
273 /* Allow the user to configure the debugger behavior with respect
274 to multiple-choice menus when more than one symbol matches during
275 a symbol lookup. */
277 const char multiple_symbols_ask[] = "ask";
278 const char multiple_symbols_all[] = "all";
279 const char multiple_symbols_cancel[] = "cancel";
280 static const char *const multiple_symbols_modes[] =
282 multiple_symbols_ask,
283 multiple_symbols_all,
284 multiple_symbols_cancel,
285 NULL
287 static const char *multiple_symbols_mode = multiple_symbols_all;
289 /* When TRUE, ignore the prologue-end flag in linetable_entry when searching
290 for the SAL past a function prologue. */
291 static bool ignore_prologue_end_flag = false;
293 /* Read-only accessor to AUTO_SELECT_MODE. */
295 const char *
296 multiple_symbols_select_mode (void)
298 return multiple_symbols_mode;
301 /* Return the name of a domain_enum. */
303 const char *
304 domain_name (domain_enum e)
306 switch (e)
308 #define SYM_DOMAIN(X) \
309 case X ## _DOMAIN: return #X "_DOMAIN";
310 #include "sym-domains.def"
311 #undef SYM_DOMAIN
312 default: gdb_assert_not_reached ("bad domain_enum");
316 /* See symtab.h. */
318 std::string
319 domain_name (domain_search_flags flags)
321 static constexpr domain_search_flags::string_mapping mapping[] = {
322 #define SYM_DOMAIN(X) \
323 MAP_ENUM_FLAG (SEARCH_ ## X ## _DOMAIN),
324 #include "sym-domains.def"
325 #undef SYM_DOMAIN
328 return flags.to_string (mapping);
331 /* See symtab.h. */
333 domain_search_flags
334 from_scripting_domain (int val)
336 if ((val & SCRIPTING_SEARCH_FLAG) == 0)
338 /* VAL should be one of the domain constants. Verify this and
339 convert it to a search constant. */
340 switch (val)
342 #define SYM_DOMAIN(X) \
343 case X ## _DOMAIN: break;
344 #include "sym-domains.def"
345 #undef SYM_DOMAIN
346 default:
347 error (_("unrecognized domain constant"));
349 domain_search_flags result = to_search_flags ((domain_enum) val);
350 if (val == VAR_DOMAIN)
352 /* This matches the historical practice. */
353 result |= SEARCH_TYPE_DOMAIN | SEARCH_FUNCTION_DOMAIN;
355 return result;
357 else
359 /* VAL is several search constants or'd together. Verify
360 this. */
361 val &= ~SCRIPTING_SEARCH_FLAG;
362 int check = val;
363 #define SYM_DOMAIN(X) \
364 check &= ~ (int) SEARCH_ ## X ## _DOMAIN;
365 #include "sym-domains.def"
366 #undef SYM_DOMAIN
367 if (check != 0)
368 error (_("unrecognized domain constant"));
369 return (domain_search_flag) val;
373 /* See symtab.h. */
375 CORE_ADDR
376 linetable_entry::pc (const struct objfile *objfile) const
378 return CORE_ADDR (m_pc) + objfile->text_section_offset ();
381 /* See symtab.h. */
383 call_site *
384 compunit_symtab::find_call_site (CORE_ADDR pc) const
386 if (m_call_site_htab == nullptr)
387 return nullptr;
389 CORE_ADDR delta = this->objfile ()->text_section_offset ();
390 unrelocated_addr unrelocated_pc = (unrelocated_addr) (pc - delta);
392 struct call_site call_site_local (unrelocated_pc, nullptr, nullptr);
393 void **slot
394 = htab_find_slot (m_call_site_htab, &call_site_local, NO_INSERT);
395 if (slot != nullptr)
396 return (call_site *) *slot;
398 /* See if the arch knows another PC we should try. On some
399 platforms, GCC emits a DWARF call site that is offset from the
400 actual return location. */
401 struct gdbarch *arch = objfile ()->arch ();
402 CORE_ADDR new_pc = gdbarch_update_call_site_pc (arch, pc);
403 if (pc == new_pc)
404 return nullptr;
406 unrelocated_pc = (unrelocated_addr) (new_pc - delta);
407 call_site new_call_site_local (unrelocated_pc, nullptr, nullptr);
408 slot = htab_find_slot (m_call_site_htab, &new_call_site_local, NO_INSERT);
409 if (slot == nullptr)
410 return nullptr;
412 return (call_site *) *slot;
415 /* See symtab.h. */
417 void
418 compunit_symtab::set_call_site_htab (htab_t call_site_htab)
420 gdb_assert (m_call_site_htab == nullptr);
421 m_call_site_htab = call_site_htab;
424 /* See symtab.h. */
426 void
427 compunit_symtab::set_primary_filetab (symtab *primary_filetab)
429 symtab *prev_filetab = nullptr;
431 /* Move PRIMARY_FILETAB to the head of the filetab list. */
432 for (symtab *filetab : this->filetabs ())
434 if (filetab == primary_filetab)
436 if (prev_filetab != nullptr)
438 prev_filetab->next = primary_filetab->next;
439 primary_filetab->next = m_filetabs;
440 m_filetabs = primary_filetab;
443 break;
446 prev_filetab = filetab;
449 gdb_assert (primary_filetab == m_filetabs);
452 /* See symtab.h. */
454 struct symtab *
455 compunit_symtab::primary_filetab () const
457 gdb_assert (m_filetabs != nullptr);
459 /* The primary file symtab is the first one in the list. */
460 return m_filetabs;
463 /* See symtab.h. */
465 enum language
466 compunit_symtab::language () const
468 struct symtab *symtab = primary_filetab ();
470 /* The language of the compunit symtab is the language of its
471 primary source file. */
472 return symtab->language ();
475 /* The relocated address of the minimal symbol, using the section
476 offsets from OBJFILE. */
478 CORE_ADDR
479 minimal_symbol::value_address (objfile *objfile) const
481 if (this->maybe_copied (objfile))
482 return this->get_maybe_copied_address (objfile);
483 else
484 return (CORE_ADDR (this->unrelocated_address ())
485 + objfile->section_offsets[this->section_index ()]);
488 /* See symtab.h. */
490 bool
491 minimal_symbol::data_p () const
493 return m_type == mst_data
494 || m_type == mst_bss
495 || m_type == mst_abs
496 || m_type == mst_file_data
497 || m_type == mst_file_bss;
500 /* See symtab.h. */
502 bool
503 minimal_symbol::text_p () const
505 return m_type == mst_text
506 || m_type == mst_text_gnu_ifunc
507 || m_type == mst_data_gnu_ifunc
508 || m_type == mst_slot_got_plt
509 || m_type == mst_solib_trampoline
510 || m_type == mst_file_text;
513 /* See symtab.h. */
515 bool
516 minimal_symbol::maybe_copied (objfile *objfile) const
518 return (objfile->object_format_has_copy_relocs
519 && (objfile->flags & OBJF_MAINLINE) == 0
520 && (m_type == mst_data || m_type == mst_bss));
523 /* See whether FILENAME matches SEARCH_NAME using the rule that we
524 advertise to the user. (The manual's description of linespecs
525 describes what we advertise). Returns true if they match, false
526 otherwise. */
528 bool
529 compare_filenames_for_search (const char *filename, const char *search_name)
531 int len = strlen (filename);
532 size_t search_len = strlen (search_name);
534 if (len < search_len)
535 return false;
537 /* The tail of FILENAME must match. */
538 if (FILENAME_CMP (filename + len - search_len, search_name) != 0)
539 return false;
541 /* Either the names must completely match, or the character
542 preceding the trailing SEARCH_NAME segment of FILENAME must be a
543 directory separator.
545 The check !IS_ABSOLUTE_PATH ensures SEARCH_NAME "/dir/file.c"
546 cannot match FILENAME "/path//dir/file.c" - as user has requested
547 absolute path. The sama applies for "c:\file.c" possibly
548 incorrectly hypothetically matching "d:\dir\c:\file.c".
550 The HAS_DRIVE_SPEC purpose is to make FILENAME "c:file.c"
551 compatible with SEARCH_NAME "file.c". In such case a compiler had
552 to put the "c:file.c" name into debug info. Such compatibility
553 works only on GDB built for DOS host. */
554 return (len == search_len
555 || (!IS_ABSOLUTE_PATH (search_name)
556 && IS_DIR_SEPARATOR (filename[len - search_len - 1]))
557 || (HAS_DRIVE_SPEC (filename)
558 && STRIP_DRIVE_SPEC (filename) == &filename[len - search_len]));
561 /* Same as compare_filenames_for_search, but for glob-style patterns.
562 Heads up on the order of the arguments. They match the order of
563 compare_filenames_for_search, but it's the opposite of the order of
564 arguments to gdb_filename_fnmatch. */
566 bool
567 compare_glob_filenames_for_search (const char *filename,
568 const char *search_name)
570 /* We rely on the property of glob-style patterns with FNM_FILE_NAME that
571 all /s have to be explicitly specified. */
572 int file_path_elements = count_path_elements (filename);
573 int search_path_elements = count_path_elements (search_name);
575 if (search_path_elements > file_path_elements)
576 return false;
578 if (IS_ABSOLUTE_PATH (search_name))
580 return (search_path_elements == file_path_elements
581 && gdb_filename_fnmatch (search_name, filename,
582 FNM_FILE_NAME | FNM_NOESCAPE) == 0);
586 const char *file_to_compare
587 = strip_leading_path_elements (filename,
588 file_path_elements - search_path_elements);
590 return gdb_filename_fnmatch (search_name, file_to_compare,
591 FNM_FILE_NAME | FNM_NOESCAPE) == 0;
595 /* Check for a symtab of a specific name by searching some symtabs.
596 This is a helper function for callbacks of iterate_over_symtabs.
598 If NAME is not absolute, then REAL_PATH is NULL
599 If NAME is absolute, then REAL_PATH is the gdb_realpath form of NAME.
601 The return value, NAME, REAL_PATH and CALLBACK are identical to the
602 `map_symtabs_matching_filename' method of quick_symbol_functions.
604 FIRST and AFTER_LAST indicate the range of compunit symtabs to search.
605 Each symtab within the specified compunit symtab is also searched.
606 AFTER_LAST is one past the last compunit symtab to search; NULL means to
607 search until the end of the list. */
609 bool
610 iterate_over_some_symtabs (const char *name,
611 const char *real_path,
612 struct compunit_symtab *first,
613 struct compunit_symtab *after_last,
614 gdb::function_view<bool (symtab *)> callback)
616 struct compunit_symtab *cust;
617 const char* base_name = lbasename (name);
619 for (cust = first; cust != NULL && cust != after_last; cust = cust->next)
621 /* Skip included compunits. */
622 if (cust->user != nullptr)
623 continue;
625 for (symtab *s : cust->filetabs ())
627 if (compare_filenames_for_search (s->filename, name))
629 if (callback (s))
630 return true;
631 continue;
634 /* Before we invoke realpath, which can get expensive when many
635 files are involved, do a quick comparison of the basenames. */
636 if (! basenames_may_differ
637 && FILENAME_CMP (base_name, lbasename (s->filename)) != 0)
638 continue;
640 if (compare_filenames_for_search (symtab_to_fullname (s), name))
642 if (callback (s))
643 return true;
644 continue;
647 /* If the user gave us an absolute path, try to find the file in
648 this symtab and use its absolute path. */
649 if (real_path != NULL)
651 const char *fullname = symtab_to_fullname (s);
653 gdb_assert (IS_ABSOLUTE_PATH (real_path));
654 gdb_assert (IS_ABSOLUTE_PATH (name));
655 gdb::unique_xmalloc_ptr<char> fullname_real_path
656 = gdb_realpath (fullname);
657 fullname = fullname_real_path.get ();
658 if (FILENAME_CMP (real_path, fullname) == 0)
660 if (callback (s))
661 return true;
662 continue;
668 return false;
671 /* Check for a symtab of a specific name; first in symtabs, then in
672 psymtabs. *If* there is no '/' in the name, a match after a '/'
673 in the symtab filename will also work.
675 Calls CALLBACK with each symtab that is found. If CALLBACK returns
676 true, the search stops. */
678 void
679 iterate_over_symtabs (const char *name,
680 gdb::function_view<bool (symtab *)> callback)
682 gdb::unique_xmalloc_ptr<char> real_path;
684 /* Here we are interested in canonicalizing an absolute path, not
685 absolutizing a relative path. */
686 if (IS_ABSOLUTE_PATH (name))
688 real_path = gdb_realpath (name);
689 gdb_assert (IS_ABSOLUTE_PATH (real_path.get ()));
692 for (objfile *objfile : current_program_space->objfiles ())
694 if (iterate_over_some_symtabs (name, real_path.get (),
695 objfile->compunit_symtabs, NULL,
696 callback))
697 return;
700 /* Same search rules as above apply here, but now we look thru the
701 psymtabs. */
703 for (objfile *objfile : current_program_space->objfiles ())
705 if (objfile->map_symtabs_matching_filename (name, real_path.get (),
706 callback))
707 return;
711 /* A wrapper for iterate_over_symtabs that returns the first matching
712 symtab, or NULL. */
714 struct symtab *
715 lookup_symtab (const char *name)
717 struct symtab *result = NULL;
719 iterate_over_symtabs (name, [&] (symtab *symtab)
721 result = symtab;
722 return true;
725 return result;
729 /* Mangle a GDB method stub type. This actually reassembles the pieces of the
730 full method name, which consist of the class name (from T), the unadorned
731 method name from METHOD_ID, and the signature for the specific overload,
732 specified by SIGNATURE_ID. Note that this function is g++ specific. */
734 char *
735 gdb_mangle_name (struct type *type, int method_id, int signature_id)
737 int mangled_name_len;
738 char *mangled_name;
739 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
740 struct fn_field *method = &f[signature_id];
741 const char *field_name = TYPE_FN_FIELDLIST_NAME (type, method_id);
742 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, signature_id);
743 const char *newname = type->name ();
745 /* Does the form of physname indicate that it is the full mangled name
746 of a constructor (not just the args)? */
747 int is_full_physname_constructor;
749 int is_constructor;
750 int is_destructor = is_destructor_name (physname);
751 /* Need a new type prefix. */
752 const char *const_prefix = method->is_const ? "C" : "";
753 const char *volatile_prefix = method->is_volatile ? "V" : "";
754 char buf[20];
755 int len = (newname == NULL ? 0 : strlen (newname));
757 /* Nothing to do if physname already contains a fully mangled v3 abi name
758 or an operator name. */
759 if ((physname[0] == '_' && physname[1] == 'Z')
760 || is_operator_name (field_name))
761 return xstrdup (physname);
763 is_full_physname_constructor = is_constructor_name (physname);
765 is_constructor = is_full_physname_constructor
766 || (newname && strcmp (field_name, newname) == 0);
768 if (!is_destructor)
769 is_destructor = (startswith (physname, "__dt"));
771 if (is_destructor || is_full_physname_constructor)
773 mangled_name = (char *) xmalloc (strlen (physname) + 1);
774 strcpy (mangled_name, physname);
775 return mangled_name;
778 if (len == 0)
780 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
782 else if (physname[0] == 't' || physname[0] == 'Q')
784 /* The physname for template and qualified methods already includes
785 the class name. */
786 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
787 newname = NULL;
788 len = 0;
790 else
792 xsnprintf (buf, sizeof (buf), "__%s%s%d", const_prefix,
793 volatile_prefix, len);
795 mangled_name_len = ((is_constructor ? 0 : strlen (field_name))
796 + strlen (buf) + len + strlen (physname) + 1);
798 mangled_name = (char *) xmalloc (mangled_name_len);
799 if (is_constructor)
800 mangled_name[0] = '\0';
801 else
802 strcpy (mangled_name, field_name);
804 strcat (mangled_name, buf);
805 /* If the class doesn't have a name, i.e. newname NULL, then we just
806 mangle it using 0 for the length of the class. Thus it gets mangled
807 as something starting with `::' rather than `classname::'. */
808 if (newname != NULL)
809 strcat (mangled_name, newname);
811 strcat (mangled_name, physname);
812 return (mangled_name);
815 /* See symtab.h. */
817 void
818 general_symbol_info::set_demangled_name (const char *name,
819 struct obstack *obstack)
821 if (language () == language_ada)
823 if (name == NULL)
825 ada_mangled = 0;
826 language_specific.obstack = obstack;
828 else
830 ada_mangled = 1;
831 language_specific.demangled_name = name;
834 else
835 language_specific.demangled_name = name;
839 /* Initialize the language dependent portion of a symbol
840 depending upon the language for the symbol. */
842 void
843 general_symbol_info::set_language (enum language language,
844 struct obstack *obstack)
846 m_language = language;
847 if (language == language_cplus
848 || language == language_d
849 || language == language_go
850 || language == language_objc
851 || language == language_fortran)
853 set_demangled_name (NULL, obstack);
855 else if (language == language_ada)
857 gdb_assert (ada_mangled == 0);
858 language_specific.obstack = obstack;
860 else
862 memset (&language_specific, 0, sizeof (language_specific));
866 /* Functions to initialize a symbol's mangled name. */
868 /* Objects of this type are stored in the demangled name hash table. */
869 struct demangled_name_entry
871 demangled_name_entry (std::string_view mangled_name)
872 : mangled (mangled_name) {}
874 std::string_view mangled;
875 enum language language;
876 gdb::unique_xmalloc_ptr<char> demangled;
879 /* Hash function for the demangled name hash. */
881 static hashval_t
882 hash_demangled_name_entry (const void *data)
884 const struct demangled_name_entry *e
885 = (const struct demangled_name_entry *) data;
887 return gdb::string_view_hash () (e->mangled);
890 /* Equality function for the demangled name hash. */
892 static int
893 eq_demangled_name_entry (const void *a, const void *b)
895 const struct demangled_name_entry *da
896 = (const struct demangled_name_entry *) a;
897 const struct demangled_name_entry *db
898 = (const struct demangled_name_entry *) b;
900 return da->mangled == db->mangled;
903 static void
904 free_demangled_name_entry (void *data)
906 struct demangled_name_entry *e
907 = (struct demangled_name_entry *) data;
909 e->~demangled_name_entry();
912 /* Create the hash table used for demangled names. Each hash entry is
913 a pair of strings; one for the mangled name and one for the demangled
914 name. The entry is hashed via just the mangled name. */
916 static void
917 create_demangled_names_hash (struct objfile_per_bfd_storage *per_bfd)
919 /* Choose 256 as the starting size of the hash table, somewhat arbitrarily.
920 The hash table code will round this up to the next prime number.
921 Choosing a much larger table size wastes memory, and saves only about
922 1% in symbol reading. However, if the minsym count is already
923 initialized (e.g. because symbol name setting was deferred to
924 a background thread) we can initialize the hashtable with a count
925 based on that, because we will almost certainly have at least that
926 many entries. If we have a nonzero number but less than 256,
927 we still stay with 256 to have some space for psymbols, etc. */
929 /* htab will expand the table when it is 3/4th full, so we account for that
930 here. +2 to round up. */
931 int minsym_based_count = (per_bfd->minimal_symbol_count + 2) / 3 * 4;
932 int count = std::max (per_bfd->minimal_symbol_count, minsym_based_count);
934 per_bfd->demangled_names_hash.reset (htab_create_alloc
935 (count, hash_demangled_name_entry, eq_demangled_name_entry,
936 free_demangled_name_entry, xcalloc, xfree));
939 /* See symtab.h */
941 gdb::unique_xmalloc_ptr<char>
942 symbol_find_demangled_name (struct general_symbol_info *gsymbol,
943 const char *mangled)
945 gdb::unique_xmalloc_ptr<char> demangled;
946 int i;
948 if (gsymbol->language () != language_unknown)
950 const struct language_defn *lang = language_def (gsymbol->language ());
952 lang->sniff_from_mangled_name (mangled, &demangled);
953 return demangled;
956 for (i = language_unknown; i < nr_languages; ++i)
958 enum language l = (enum language) i;
959 const struct language_defn *lang = language_def (l);
961 if (lang->sniff_from_mangled_name (mangled, &demangled))
963 gsymbol->m_language = l;
964 return demangled;
968 return NULL;
971 /* Set both the mangled and demangled (if any) names for GSYMBOL based
972 on LINKAGE_NAME and LEN. Ordinarily, NAME is copied onto the
973 objfile's obstack; but if COPY_NAME is 0 and if NAME is
974 NUL-terminated, then this function assumes that NAME is already
975 correctly saved (either permanently or with a lifetime tied to the
976 objfile), and it will not be copied.
978 The hash table corresponding to OBJFILE is used, and the memory
979 comes from the per-BFD storage_obstack. LINKAGE_NAME is copied,
980 so the pointer can be discarded after calling this function. */
982 void
983 general_symbol_info::compute_and_set_names (std::string_view linkage_name,
984 bool copy_name,
985 objfile_per_bfd_storage *per_bfd,
986 std::optional<hashval_t> hash)
988 struct demangled_name_entry **slot;
990 if (language () == language_ada)
992 /* In Ada, we do the symbol lookups using the mangled name, so
993 we can save some space by not storing the demangled name. */
994 if (!copy_name)
995 m_name = linkage_name.data ();
996 else
997 m_name = obstack_strndup (&per_bfd->storage_obstack,
998 linkage_name.data (),
999 linkage_name.length ());
1000 set_demangled_name (NULL, &per_bfd->storage_obstack);
1002 return;
1005 if (per_bfd->demangled_names_hash == NULL)
1006 create_demangled_names_hash (per_bfd);
1008 struct demangled_name_entry entry (linkage_name);
1009 if (!hash.has_value ())
1010 hash = hash_demangled_name_entry (&entry);
1011 slot = ((struct demangled_name_entry **)
1012 htab_find_slot_with_hash (per_bfd->demangled_names_hash.get (),
1013 &entry, *hash, INSERT));
1015 /* The const_cast is safe because the only reason it is already
1016 initialized is if we purposefully set it from a background
1017 thread to avoid doing the work here. However, it is still
1018 allocated from the heap and needs to be freed by us, just
1019 like if we called symbol_find_demangled_name here. If this is
1020 nullptr, we call symbol_find_demangled_name below, but we put
1021 this smart pointer here to be sure that we don't leak this name. */
1022 gdb::unique_xmalloc_ptr<char> demangled_name
1023 (const_cast<char *> (language_specific.demangled_name));
1025 /* If this name is not in the hash table, add it. */
1026 if (*slot == NULL
1027 /* A C version of the symbol may have already snuck into the table.
1028 This happens to, e.g., main.init (__go_init_main). Cope. */
1029 || (language () == language_go && (*slot)->demangled == nullptr))
1031 /* A 0-terminated copy of the linkage name. Callers must set COPY_NAME
1032 to true if the string might not be nullterminated. We have to make
1033 this copy because demangling needs a nullterminated string. */
1034 std::string_view linkage_name_copy;
1035 if (copy_name)
1037 char *alloc_name = (char *) alloca (linkage_name.length () + 1);
1038 memcpy (alloc_name, linkage_name.data (), linkage_name.length ());
1039 alloc_name[linkage_name.length ()] = '\0';
1041 linkage_name_copy = std::string_view (alloc_name,
1042 linkage_name.length ());
1044 else
1045 linkage_name_copy = linkage_name;
1047 if (demangled_name.get () == nullptr)
1048 demangled_name
1049 = symbol_find_demangled_name (this, linkage_name_copy.data ());
1051 /* Suppose we have demangled_name==NULL, copy_name==0, and
1052 linkage_name_copy==linkage_name. In this case, we already have the
1053 mangled name saved, and we don't have a demangled name. So,
1054 you might think we could save a little space by not recording
1055 this in the hash table at all.
1057 It turns out that it is actually important to still save such
1058 an entry in the hash table, because storing this name gives
1059 us better bcache hit rates for partial symbols. */
1060 if (!copy_name)
1062 *slot
1063 = ((struct demangled_name_entry *)
1064 obstack_alloc (&per_bfd->storage_obstack,
1065 sizeof (demangled_name_entry)));
1066 new (*slot) demangled_name_entry (linkage_name);
1068 else
1070 /* If we must copy the mangled name, put it directly after
1071 the struct so we can have a single allocation. */
1072 *slot
1073 = ((struct demangled_name_entry *)
1074 obstack_alloc (&per_bfd->storage_obstack,
1075 sizeof (demangled_name_entry)
1076 + linkage_name.length () + 1));
1077 char *mangled_ptr = reinterpret_cast<char *> (*slot + 1);
1078 memcpy (mangled_ptr, linkage_name.data (), linkage_name.length ());
1079 mangled_ptr [linkage_name.length ()] = '\0';
1080 new (*slot) demangled_name_entry
1081 (std::string_view (mangled_ptr, linkage_name.length ()));
1083 (*slot)->demangled = std::move (demangled_name);
1084 (*slot)->language = language ();
1086 else if (language () == language_unknown)
1087 m_language = (*slot)->language;
1089 m_name = (*slot)->mangled.data ();
1090 set_demangled_name ((*slot)->demangled.get (), &per_bfd->storage_obstack);
1093 /* See symtab.h. */
1095 const char *
1096 general_symbol_info::natural_name () const
1098 switch (language ())
1100 case language_cplus:
1101 case language_d:
1102 case language_go:
1103 case language_objc:
1104 case language_fortran:
1105 case language_rust:
1106 if (language_specific.demangled_name != nullptr)
1107 return language_specific.demangled_name;
1108 break;
1109 case language_ada:
1110 return ada_decode_symbol (this);
1111 default:
1112 break;
1114 return linkage_name ();
1117 /* See symtab.h. */
1119 const char *
1120 general_symbol_info::demangled_name () const
1122 const char *dem_name = NULL;
1124 switch (language ())
1126 case language_cplus:
1127 case language_d:
1128 case language_go:
1129 case language_objc:
1130 case language_fortran:
1131 case language_rust:
1132 dem_name = language_specific.demangled_name;
1133 break;
1134 case language_ada:
1135 dem_name = ada_decode_symbol (this);
1136 break;
1137 default:
1138 break;
1140 return dem_name;
1143 /* See symtab.h. */
1145 const char *
1146 general_symbol_info::search_name () const
1148 if (language () == language_ada)
1149 return linkage_name ();
1150 else
1151 return natural_name ();
1154 /* See symtab.h. */
1156 struct obj_section *
1157 general_symbol_info::obj_section (const struct objfile *objfile) const
1159 if (section_index () >= 0)
1160 return &objfile->sections_start[section_index ()];
1161 return nullptr;
1164 /* See symtab.h. */
1166 bool
1167 symbol_matches_search_name (const struct general_symbol_info *gsymbol,
1168 const lookup_name_info &name)
1170 symbol_name_matcher_ftype *name_match
1171 = language_def (gsymbol->language ())->get_symbol_name_matcher (name);
1172 return name_match (gsymbol->search_name (), name, NULL);
1177 /* Return true if the two sections are the same, or if they could
1178 plausibly be copies of each other, one in an original object
1179 file and another in a separated debug file. */
1181 bool
1182 matching_obj_sections (struct obj_section *obj_first,
1183 struct obj_section *obj_second)
1185 asection *first = obj_first? obj_first->the_bfd_section : NULL;
1186 asection *second = obj_second? obj_second->the_bfd_section : NULL;
1188 /* If they're the same section, then they match. */
1189 if (first == second)
1190 return true;
1192 /* If either is NULL, give up. */
1193 if (first == NULL || second == NULL)
1194 return false;
1196 /* This doesn't apply to absolute symbols. */
1197 if (first->owner == NULL || second->owner == NULL)
1198 return false;
1200 /* If they're in the same object file, they must be different sections. */
1201 if (first->owner == second->owner)
1202 return false;
1204 /* Check whether the two sections are potentially corresponding. They must
1205 have the same size, address, and name. We can't compare section indexes,
1206 which would be more reliable, because some sections may have been
1207 stripped. */
1208 if (bfd_section_size (first) != bfd_section_size (second))
1209 return false;
1211 /* In-memory addresses may start at a different offset, relativize them. */
1212 if (bfd_section_vma (first) - bfd_get_start_address (first->owner)
1213 != bfd_section_vma (second) - bfd_get_start_address (second->owner))
1214 return false;
1216 if (bfd_section_name (first) == NULL
1217 || bfd_section_name (second) == NULL
1218 || strcmp (bfd_section_name (first), bfd_section_name (second)) != 0)
1219 return false;
1221 /* Otherwise check that they are in corresponding objfiles. */
1223 struct objfile *obj = NULL;
1224 for (objfile *objfile : current_program_space->objfiles ())
1225 if (objfile->obfd == first->owner)
1227 obj = objfile;
1228 break;
1230 gdb_assert (obj != NULL);
1232 if (obj->separate_debug_objfile != NULL
1233 && obj->separate_debug_objfile->obfd == second->owner)
1234 return true;
1235 if (obj->separate_debug_objfile_backlink != NULL
1236 && obj->separate_debug_objfile_backlink->obfd == second->owner)
1237 return true;
1239 return false;
1242 /* Hash function for the symbol cache. */
1244 static unsigned int
1245 hash_symbol_entry (const struct objfile *objfile_context,
1246 const char *name, domain_search_flags domain)
1248 unsigned int hash = (uintptr_t) objfile_context;
1250 if (name != NULL)
1251 hash += htab_hash_string (name);
1253 hash += domain * 7;
1255 return hash;
1258 /* Equality function for the symbol cache. */
1260 static int
1261 eq_symbol_entry (const struct symbol_cache_slot *slot,
1262 const struct objfile *objfile_context,
1263 const char *name, domain_search_flags domain)
1265 const char *slot_name;
1267 if (slot->state == SYMBOL_SLOT_UNUSED)
1268 return 0;
1270 if (slot->objfile_context != objfile_context)
1271 return 0;
1273 domain_search_flags slot_domain = slot->domain;
1274 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1275 slot_name = slot->value.name;
1276 else
1277 slot_name = slot->value.found.symbol->search_name ();
1279 /* NULL names match. */
1280 if (slot_name == NULL && name == NULL)
1282 /* But there's no point in calling symbol_matches_domain in the
1283 SYMBOL_SLOT_FOUND case. */
1284 if (slot_domain != domain)
1285 return 0;
1287 else if (slot_name != NULL && name != NULL)
1289 /* It's important that we use the same comparison that was done
1290 the first time through. If the slot records a found symbol,
1291 then this means using the symbol name comparison function of
1292 the symbol's language with symbol->search_name (). See
1293 dictionary.c.
1295 If the slot records a not-found symbol, then require a precise match.
1296 We could still be lax with whitespace like strcmp_iw though. */
1298 if (slot_domain != domain)
1299 return 0;
1301 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1303 if (strcmp (slot_name, name) != 0)
1304 return 0;
1306 else
1308 struct symbol *sym = slot->value.found.symbol;
1309 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1311 if (!symbol_matches_search_name (sym, lookup_name))
1312 return 0;
1315 else
1317 /* Only one name is NULL. */
1318 return 0;
1321 return 1;
1324 /* Given a cache of size SIZE, return the size of the struct (with variable
1325 length array) in bytes. */
1327 static size_t
1328 symbol_cache_byte_size (unsigned int size)
1330 return (sizeof (struct block_symbol_cache)
1331 + ((size - 1) * sizeof (struct symbol_cache_slot)));
1334 /* Resize CACHE. */
1336 static void
1337 resize_symbol_cache (struct symbol_cache *cache, unsigned int new_size)
1339 /* If there's no change in size, don't do anything.
1340 All caches have the same size, so we can just compare with the size
1341 of the global symbols cache. */
1342 if ((cache->global_symbols != NULL
1343 && cache->global_symbols->size == new_size)
1344 || (cache->global_symbols == NULL
1345 && new_size == 0))
1346 return;
1348 destroy_block_symbol_cache (cache->global_symbols);
1349 destroy_block_symbol_cache (cache->static_symbols);
1351 if (new_size == 0)
1353 cache->global_symbols = NULL;
1354 cache->static_symbols = NULL;
1356 else
1358 size_t total_size = symbol_cache_byte_size (new_size);
1360 cache->global_symbols
1361 = (struct block_symbol_cache *) xcalloc (1, total_size);
1362 cache->static_symbols
1363 = (struct block_symbol_cache *) xcalloc (1, total_size);
1364 cache->global_symbols->size = new_size;
1365 cache->static_symbols->size = new_size;
1369 /* Return the symbol cache of PSPACE.
1370 Create one if it doesn't exist yet. */
1372 static struct symbol_cache *
1373 get_symbol_cache (struct program_space *pspace)
1375 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1377 if (cache == NULL)
1379 cache = symbol_cache_key.emplace (pspace);
1380 resize_symbol_cache (cache, symbol_cache_size);
1383 return cache;
1386 /* Set the size of the symbol cache in all program spaces. */
1388 static void
1389 set_symbol_cache_size (unsigned int new_size)
1391 for (struct program_space *pspace : program_spaces)
1393 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1395 /* The pspace could have been created but not have a cache yet. */
1396 if (cache != NULL)
1397 resize_symbol_cache (cache, new_size);
1401 /* Called when symbol-cache-size is set. */
1403 static void
1404 set_symbol_cache_size_handler (const char *args, int from_tty,
1405 struct cmd_list_element *c)
1407 if (new_symbol_cache_size > MAX_SYMBOL_CACHE_SIZE)
1409 /* Restore the previous value.
1410 This is the value the "show" command prints. */
1411 new_symbol_cache_size = symbol_cache_size;
1413 error (_("Symbol cache size is too large, max is %u."),
1414 MAX_SYMBOL_CACHE_SIZE);
1416 symbol_cache_size = new_symbol_cache_size;
1418 set_symbol_cache_size (symbol_cache_size);
1421 /* Lookup symbol NAME,DOMAIN in BLOCK in the symbol cache of PSPACE.
1422 OBJFILE_CONTEXT is the current objfile, which may be NULL.
1423 The result is the symbol if found, SYMBOL_LOOKUP_FAILED if a previous lookup
1424 failed (and thus this one will too), or NULL if the symbol is not present
1425 in the cache.
1426 *BSC_PTR and *SLOT_PTR are set to the cache and slot of the symbol, which
1427 can be used to save the result of a full lookup attempt. */
1429 static struct block_symbol
1430 symbol_cache_lookup (struct symbol_cache *cache,
1431 struct objfile *objfile_context, enum block_enum block,
1432 const char *name, domain_search_flags domain,
1433 struct block_symbol_cache **bsc_ptr,
1434 struct symbol_cache_slot **slot_ptr)
1436 struct block_symbol_cache *bsc;
1437 unsigned int hash;
1438 struct symbol_cache_slot *slot;
1440 if (block == GLOBAL_BLOCK)
1441 bsc = cache->global_symbols;
1442 else
1443 bsc = cache->static_symbols;
1444 if (bsc == NULL)
1446 *bsc_ptr = NULL;
1447 *slot_ptr = NULL;
1448 return {};
1451 hash = hash_symbol_entry (objfile_context, name, domain);
1452 slot = bsc->symbols + hash % bsc->size;
1454 *bsc_ptr = bsc;
1455 *slot_ptr = slot;
1457 if (eq_symbol_entry (slot, objfile_context, name, domain))
1459 symbol_lookup_debug_printf ("%s block symbol cache hit%s for %s, %s",
1460 block == GLOBAL_BLOCK ? "Global" : "Static",
1461 slot->state == SYMBOL_SLOT_NOT_FOUND
1462 ? " (not found)" : "", name,
1463 domain_name (domain).c_str ());
1464 ++bsc->hits;
1465 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1466 return SYMBOL_LOOKUP_FAILED;
1467 return slot->value.found;
1470 /* Symbol is not present in the cache. */
1472 symbol_lookup_debug_printf ("%s block symbol cache miss for %s, %s",
1473 block == GLOBAL_BLOCK ? "Global" : "Static",
1474 name, domain_name (domain).c_str ());
1475 ++bsc->misses;
1476 return {};
1479 /* Mark SYMBOL as found in SLOT.
1480 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1481 if it's not needed to distinguish lookups (STATIC_BLOCK). It is *not*
1482 necessarily the objfile the symbol was found in. */
1484 static void
1485 symbol_cache_mark_found (struct block_symbol_cache *bsc,
1486 struct symbol_cache_slot *slot,
1487 struct objfile *objfile_context,
1488 struct symbol *symbol,
1489 const struct block *block,
1490 domain_search_flags domain)
1492 if (bsc == NULL)
1493 return;
1494 if (slot->state != SYMBOL_SLOT_UNUSED)
1496 ++bsc->collisions;
1497 symbol_cache_clear_slot (slot);
1499 slot->state = SYMBOL_SLOT_FOUND;
1500 slot->objfile_context = objfile_context;
1501 slot->value.found.symbol = symbol;
1502 slot->value.found.block = block;
1503 slot->domain = domain;
1506 /* Mark symbol NAME, DOMAIN as not found in SLOT.
1507 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1508 if it's not needed to distinguish lookups (STATIC_BLOCK). */
1510 static void
1511 symbol_cache_mark_not_found (struct block_symbol_cache *bsc,
1512 struct symbol_cache_slot *slot,
1513 struct objfile *objfile_context,
1514 const char *name, domain_search_flags domain)
1516 if (bsc == NULL)
1517 return;
1518 if (slot->state != SYMBOL_SLOT_UNUSED)
1520 ++bsc->collisions;
1521 symbol_cache_clear_slot (slot);
1523 slot->state = SYMBOL_SLOT_NOT_FOUND;
1524 slot->objfile_context = objfile_context;
1525 slot->value.name = xstrdup (name);
1526 slot->domain = domain;
1529 /* Flush the symbol cache of PSPACE. */
1531 static void
1532 symbol_cache_flush (struct program_space *pspace)
1534 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1535 int pass;
1537 if (cache == NULL)
1538 return;
1539 if (cache->global_symbols == NULL)
1541 gdb_assert (symbol_cache_size == 0);
1542 gdb_assert (cache->static_symbols == NULL);
1543 return;
1546 /* If the cache is untouched since the last flush, early exit.
1547 This is important for performance during the startup of a program linked
1548 with 100s (or 1000s) of shared libraries. */
1549 if (cache->global_symbols->misses == 0
1550 && cache->static_symbols->misses == 0)
1551 return;
1553 gdb_assert (cache->global_symbols->size == symbol_cache_size);
1554 gdb_assert (cache->static_symbols->size == symbol_cache_size);
1556 for (pass = 0; pass < 2; ++pass)
1558 struct block_symbol_cache *bsc
1559 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1560 unsigned int i;
1562 for (i = 0; i < bsc->size; ++i)
1563 symbol_cache_clear_slot (&bsc->symbols[i]);
1566 cache->global_symbols->hits = 0;
1567 cache->global_symbols->misses = 0;
1568 cache->global_symbols->collisions = 0;
1569 cache->static_symbols->hits = 0;
1570 cache->static_symbols->misses = 0;
1571 cache->static_symbols->collisions = 0;
1574 /* Dump CACHE. */
1576 static void
1577 symbol_cache_dump (const struct symbol_cache *cache)
1579 int pass;
1581 if (cache->global_symbols == NULL)
1583 gdb_printf (" <disabled>\n");
1584 return;
1587 for (pass = 0; pass < 2; ++pass)
1589 const struct block_symbol_cache *bsc
1590 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1591 unsigned int i;
1593 if (pass == 0)
1594 gdb_printf ("Global symbols:\n");
1595 else
1596 gdb_printf ("Static symbols:\n");
1598 for (i = 0; i < bsc->size; ++i)
1600 const struct symbol_cache_slot *slot = &bsc->symbols[i];
1602 QUIT;
1604 switch (slot->state)
1606 case SYMBOL_SLOT_UNUSED:
1607 break;
1608 case SYMBOL_SLOT_NOT_FOUND:
1609 gdb_printf (" [%4u] = %s, %s %s (not found)\n", i,
1610 host_address_to_string (slot->objfile_context),
1611 slot->value.name,
1612 domain_name (slot->domain).c_str ());
1613 break;
1614 case SYMBOL_SLOT_FOUND:
1616 struct symbol *found = slot->value.found.symbol;
1617 const struct objfile *context = slot->objfile_context;
1619 gdb_printf (" [%4u] = %s, %s %s\n", i,
1620 host_address_to_string (context),
1621 found->print_name (),
1622 domain_name (found->domain ()));
1623 break;
1630 /* The "mt print symbol-cache" command. */
1632 static void
1633 maintenance_print_symbol_cache (const char *args, int from_tty)
1635 for (struct program_space *pspace : program_spaces)
1637 struct symbol_cache *cache;
1639 gdb_printf (_("Symbol cache for pspace %d\n%s:\n"),
1640 pspace->num,
1641 pspace->symfile_object_file != NULL
1642 ? objfile_name (pspace->symfile_object_file)
1643 : "(no object file)");
1645 /* If the cache hasn't been created yet, avoid creating one. */
1646 cache = symbol_cache_key.get (pspace);
1647 if (cache == NULL)
1648 gdb_printf (" <empty>\n");
1649 else
1650 symbol_cache_dump (cache);
1654 /* The "mt flush-symbol-cache" command. */
1656 static void
1657 maintenance_flush_symbol_cache (const char *args, int from_tty)
1659 for (struct program_space *pspace : program_spaces)
1661 symbol_cache_flush (pspace);
1665 /* Print usage statistics of CACHE. */
1667 static void
1668 symbol_cache_stats (struct symbol_cache *cache)
1670 int pass;
1672 if (cache->global_symbols == NULL)
1674 gdb_printf (" <disabled>\n");
1675 return;
1678 for (pass = 0; pass < 2; ++pass)
1680 const struct block_symbol_cache *bsc
1681 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1683 QUIT;
1685 if (pass == 0)
1686 gdb_printf ("Global block cache stats:\n");
1687 else
1688 gdb_printf ("Static block cache stats:\n");
1690 gdb_printf (" size: %u\n", bsc->size);
1691 gdb_printf (" hits: %u\n", bsc->hits);
1692 gdb_printf (" misses: %u\n", bsc->misses);
1693 gdb_printf (" collisions: %u\n", bsc->collisions);
1697 /* The "mt print symbol-cache-statistics" command. */
1699 static void
1700 maintenance_print_symbol_cache_statistics (const char *args, int from_tty)
1702 for (struct program_space *pspace : program_spaces)
1704 struct symbol_cache *cache;
1706 gdb_printf (_("Symbol cache statistics for pspace %d\n%s:\n"),
1707 pspace->num,
1708 pspace->symfile_object_file != NULL
1709 ? objfile_name (pspace->symfile_object_file)
1710 : "(no object file)");
1712 /* If the cache hasn't been created yet, avoid creating one. */
1713 cache = symbol_cache_key.get (pspace);
1714 if (cache == NULL)
1715 gdb_printf (" empty, no stats available\n");
1716 else
1717 symbol_cache_stats (cache);
1721 /* This module's 'new_objfile' observer. */
1723 static void
1724 symtab_new_objfile_observer (struct objfile *objfile)
1726 symbol_cache_flush (objfile->pspace);
1729 /* This module's 'all_objfiles_removed' observer. */
1731 static void
1732 symtab_all_objfiles_removed (program_space *pspace)
1734 symbol_cache_flush (pspace);
1736 /* Forget everything we know about the main function. */
1737 set_main_name (pspace, nullptr, language_unknown);
1740 /* This module's 'free_objfile' observer. */
1742 static void
1743 symtab_free_objfile_observer (struct objfile *objfile)
1745 symbol_cache_flush (objfile->pspace);
1748 /* See symtab.h. */
1750 void
1751 fixup_symbol_section (struct symbol *sym, struct objfile *objfile)
1753 gdb_assert (sym != nullptr);
1754 gdb_assert (sym->is_objfile_owned ());
1755 gdb_assert (objfile != nullptr);
1756 gdb_assert (sym->section_index () == -1);
1758 /* Note that if this ends up as -1, fixup_section will handle that
1759 reasonably well. So, it's fine to use the objfile's section
1760 index without doing the check that is done by the wrapper macros
1761 like SECT_OFF_TEXT. */
1762 int fallback;
1763 switch (sym->aclass ())
1765 case LOC_STATIC:
1766 fallback = objfile->sect_index_data;
1767 break;
1769 case LOC_LABEL:
1770 fallback = objfile->sect_index_text;
1771 break;
1773 default:
1774 /* Nothing else will be listed in the minsyms -- no use looking
1775 it up. */
1776 return;
1779 CORE_ADDR addr = sym->value_address ();
1781 struct minimal_symbol *msym;
1783 /* First, check whether a minimal symbol with the same name exists
1784 and points to the same address. The address check is required
1785 e.g. on PowerPC64, where the minimal symbol for a function will
1786 point to the function descriptor, while the debug symbol will
1787 point to the actual function code. */
1788 msym = lookup_minimal_symbol_by_pc_name (addr, sym->linkage_name (),
1789 objfile);
1790 if (msym)
1791 sym->set_section_index (msym->section_index ());
1792 else
1794 /* Static, function-local variables do appear in the linker
1795 (minimal) symbols, but are frequently given names that won't
1796 be found via lookup_minimal_symbol(). E.g., it has been
1797 observed in frv-uclinux (ELF) executables that a static,
1798 function-local variable named "foo" might appear in the
1799 linker symbols as "foo.6" or "foo.3". Thus, there is no
1800 point in attempting to extend the lookup-by-name mechanism to
1801 handle this case due to the fact that there can be multiple
1802 names.
1804 So, instead, search the section table when lookup by name has
1805 failed. The ``addr'' and ``endaddr'' fields may have already
1806 been relocated. If so, the relocation offset needs to be
1807 subtracted from these values when performing the comparison.
1808 We unconditionally subtract it, because, when no relocation
1809 has been performed, the value will simply be zero.
1811 The address of the symbol whose section we're fixing up HAS
1812 NOT BEEN adjusted (relocated) yet. It can't have been since
1813 the section isn't yet known and knowing the section is
1814 necessary in order to add the correct relocation value. In
1815 other words, we wouldn't even be in this function (attempting
1816 to compute the section) if it were already known.
1818 Note that it is possible to search the minimal symbols
1819 (subtracting the relocation value if necessary) to find the
1820 matching minimal symbol, but this is overkill and much less
1821 efficient. It is not necessary to find the matching minimal
1822 symbol, only its section.
1824 Note that this technique (of doing a section table search)
1825 can fail when unrelocated section addresses overlap. For
1826 this reason, we still attempt a lookup by name prior to doing
1827 a search of the section table. */
1829 for (obj_section *s : objfile->sections ())
1831 if ((bfd_section_flags (s->the_bfd_section) & SEC_ALLOC) == 0)
1832 continue;
1834 int idx = s - objfile->sections_start;
1835 CORE_ADDR offset = objfile->section_offsets[idx];
1837 if (fallback == -1)
1838 fallback = idx;
1840 if (s->addr () - offset <= addr && addr < s->endaddr () - offset)
1842 sym->set_section_index (idx);
1843 return;
1847 /* If we didn't find the section, assume it is in the first
1848 section. If there is no allocated section, then it hardly
1849 matters what we pick, so just pick zero. */
1850 if (fallback == -1)
1851 sym->set_section_index (0);
1852 else
1853 sym->set_section_index (fallback);
1857 /* See symtab.h. */
1859 demangle_for_lookup_info::demangle_for_lookup_info
1860 (const lookup_name_info &lookup_name, language lang)
1862 demangle_result_storage storage;
1864 if (lookup_name.ignore_parameters () && lang == language_cplus)
1866 gdb::unique_xmalloc_ptr<char> without_params
1867 = cp_remove_params_if_any (lookup_name.c_str (),
1868 lookup_name.completion_mode ());
1870 if (without_params != NULL)
1872 if (lookup_name.match_type () != symbol_name_match_type::SEARCH_NAME)
1873 m_demangled_name = demangle_for_lookup (without_params.get (),
1874 lang, storage);
1875 return;
1879 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
1880 m_demangled_name = lookup_name.c_str ();
1881 else
1882 m_demangled_name = demangle_for_lookup (lookup_name.c_str (),
1883 lang, storage);
1886 /* See symtab.h. */
1888 const lookup_name_info &
1889 lookup_name_info::match_any ()
1891 /* Lookup any symbol that "" would complete. I.e., this matches all
1892 symbol names. */
1893 static const lookup_name_info lookup_name ("", symbol_name_match_type::FULL,
1894 true);
1896 return lookup_name;
1899 /* Compute the demangled form of NAME as used by the various symbol
1900 lookup functions. The result can either be the input NAME
1901 directly, or a pointer to a buffer owned by the STORAGE object.
1903 For Ada, this function just returns NAME, unmodified.
1904 Normally, Ada symbol lookups are performed using the encoded name
1905 rather than the demangled name, and so it might seem to make sense
1906 for this function to return an encoded version of NAME.
1907 Unfortunately, we cannot do this, because this function is used in
1908 circumstances where it is not appropriate to try to encode NAME.
1909 For instance, when displaying the frame info, we demangle the name
1910 of each parameter, and then perform a symbol lookup inside our
1911 function using that demangled name. In Ada, certain functions
1912 have internally-generated parameters whose name contain uppercase
1913 characters. Encoding those name would result in those uppercase
1914 characters to become lowercase, and thus cause the symbol lookup
1915 to fail. */
1917 const char *
1918 demangle_for_lookup (const char *name, enum language lang,
1919 demangle_result_storage &storage)
1921 /* If we are using C++, D, or Go, demangle the name before doing a
1922 lookup, so we can always binary search. */
1923 if (lang == language_cplus)
1925 gdb::unique_xmalloc_ptr<char> demangled_name
1926 = gdb_demangle (name, DMGL_ANSI | DMGL_PARAMS);
1927 if (demangled_name != NULL)
1928 return storage.set_malloc_ptr (std::move (demangled_name));
1930 /* If we were given a non-mangled name, canonicalize it
1931 according to the language (so far only for C++). */
1932 gdb::unique_xmalloc_ptr<char> canon = cp_canonicalize_string (name);
1933 if (canon != nullptr)
1934 return storage.set_malloc_ptr (std::move (canon));
1936 else if (lang == language_d)
1938 gdb::unique_xmalloc_ptr<char> demangled_name = d_demangle (name, 0);
1939 if (demangled_name != NULL)
1940 return storage.set_malloc_ptr (std::move (demangled_name));
1942 else if (lang == language_go)
1944 gdb::unique_xmalloc_ptr<char> demangled_name
1945 = language_def (language_go)->demangle_symbol (name, 0);
1946 if (demangled_name != NULL)
1947 return storage.set_malloc_ptr (std::move (demangled_name));
1950 return name;
1953 /* See symtab.h. */
1955 unsigned int
1956 search_name_hash (enum language language, const char *search_name)
1958 return language_def (language)->search_name_hash (search_name);
1961 /* See symtab.h.
1963 This function (or rather its subordinates) have a bunch of loops and
1964 it would seem to be attractive to put in some QUIT's (though I'm not really
1965 sure whether it can run long enough to be really important). But there
1966 are a few calls for which it would appear to be bad news to quit
1967 out of here: e.g., find_proc_desc in alpha-mdebug-tdep.c. (Note
1968 that there is C++ code below which can error(), but that probably
1969 doesn't affect these calls since they are looking for a known
1970 variable and thus can probably assume it will never hit the C++
1971 code). */
1973 struct block_symbol
1974 lookup_symbol_in_language (const char *name, const struct block *block,
1975 const domain_search_flags domain,
1976 enum language lang,
1977 struct field_of_this_result *is_a_field_of_this)
1979 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
1981 demangle_result_storage storage;
1982 const char *modified_name = demangle_for_lookup (name, lang, storage);
1984 return lookup_symbol_aux (modified_name,
1985 symbol_name_match_type::FULL,
1986 block, domain, lang,
1987 is_a_field_of_this);
1990 /* See symtab.h. */
1992 struct block_symbol
1993 lookup_symbol (const char *name, const struct block *block,
1994 domain_search_flags domain,
1995 struct field_of_this_result *is_a_field_of_this)
1997 return lookup_symbol_in_language (name, block, domain,
1998 current_language->la_language,
1999 is_a_field_of_this);
2002 /* See symtab.h. */
2004 struct block_symbol
2005 lookup_symbol_search_name (const char *search_name, const struct block *block,
2006 domain_search_flags domain)
2008 return lookup_symbol_aux (search_name, symbol_name_match_type::SEARCH_NAME,
2009 block, domain, language_asm, NULL);
2012 /* See symtab.h. */
2014 struct block_symbol
2015 lookup_language_this (const struct language_defn *lang,
2016 const struct block *block)
2018 if (lang->name_of_this () == NULL || block == NULL)
2019 return {};
2021 symbol_lookup_debug_printf_v ("lookup_language_this (%s, %s (objfile %s))",
2022 lang->name (), host_address_to_string (block),
2023 objfile_debug_name (block->objfile ()));
2025 lookup_name_info this_name (lang->name_of_this (),
2026 symbol_name_match_type::SEARCH_NAME);
2028 while (block)
2030 struct symbol *sym;
2032 sym = block_lookup_symbol (block, this_name, SEARCH_VFT);
2033 if (sym != NULL)
2035 symbol_lookup_debug_printf_v
2036 ("lookup_language_this (...) = %s (%s, block %s)",
2037 sym->print_name (), host_address_to_string (sym),
2038 host_address_to_string (block));
2039 return (struct block_symbol) {sym, block};
2041 if (block->function ())
2042 break;
2043 block = block->superblock ();
2046 symbol_lookup_debug_printf_v ("lookup_language_this (...) = NULL");
2047 return {};
2050 /* Given TYPE, a structure/union,
2051 return 1 if the component named NAME from the ultimate target
2052 structure/union is defined, otherwise, return 0. */
2054 static int
2055 check_field (struct type *type, const char *name,
2056 struct field_of_this_result *is_a_field_of_this)
2058 int i;
2060 /* The type may be a stub. */
2061 type = check_typedef (type);
2063 for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
2065 const char *t_field_name = type->field (i).name ();
2067 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2069 is_a_field_of_this->type = type;
2070 is_a_field_of_this->field = &type->field (i);
2071 return 1;
2075 /* C++: If it was not found as a data field, then try to return it
2076 as a pointer to a method. */
2078 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
2080 if (strcmp_iw (TYPE_FN_FIELDLIST_NAME (type, i), name) == 0)
2082 is_a_field_of_this->type = type;
2083 is_a_field_of_this->fn_field = &TYPE_FN_FIELDLIST (type, i);
2084 return 1;
2088 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2089 if (check_field (TYPE_BASECLASS (type, i), name, is_a_field_of_this))
2090 return 1;
2092 return 0;
2095 /* Behave like lookup_symbol except that NAME is the natural name
2096 (e.g., demangled name) of the symbol that we're looking for. */
2098 static struct block_symbol
2099 lookup_symbol_aux (const char *name, symbol_name_match_type match_type,
2100 const struct block *block,
2101 const domain_search_flags domain, enum language language,
2102 struct field_of_this_result *is_a_field_of_this)
2104 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2106 struct block_symbol result;
2107 const struct language_defn *langdef;
2109 if (symbol_lookup_debug)
2111 struct objfile *objfile = (block == nullptr
2112 ? nullptr : block->objfile ());
2114 symbol_lookup_debug_printf
2115 ("demangled symbol name = \"%s\", block @ %s (objfile %s)",
2116 name, host_address_to_string (block),
2117 objfile != NULL ? objfile_debug_name (objfile) : "NULL");
2118 symbol_lookup_debug_printf
2119 ("domain name = \"%s\", language = \"%s\")",
2120 domain_name (domain).c_str (), language_str (language));
2123 /* Make sure we do something sensible with is_a_field_of_this, since
2124 the callers that set this parameter to some non-null value will
2125 certainly use it later. If we don't set it, the contents of
2126 is_a_field_of_this are undefined. */
2127 if (is_a_field_of_this != NULL)
2128 memset (is_a_field_of_this, 0, sizeof (*is_a_field_of_this));
2130 /* Search specified block and its superiors. Don't search
2131 STATIC_BLOCK or GLOBAL_BLOCK. */
2133 result = lookup_local_symbol (name, match_type, block, domain, language);
2134 if (result.symbol != NULL)
2136 symbol_lookup_debug_printf
2137 ("found symbol @ %s (using lookup_local_symbol)",
2138 host_address_to_string (result.symbol));
2139 return result;
2142 /* If requested to do so by the caller and if appropriate for LANGUAGE,
2143 check to see if NAME is a field of `this'. */
2145 langdef = language_def (language);
2147 /* Don't do this check if we are searching for a struct. It will
2148 not be found by check_field, but will be found by other
2149 means. */
2150 if (is_a_field_of_this != NULL && (domain & SEARCH_STRUCT_DOMAIN) == 0)
2152 result = lookup_language_this (langdef, block);
2154 if (result.symbol)
2156 struct type *t = result.symbol->type ();
2158 /* I'm not really sure that type of this can ever
2159 be typedefed; just be safe. */
2160 t = check_typedef (t);
2161 if (t->is_pointer_or_reference ())
2162 t = t->target_type ();
2164 if (t->code () != TYPE_CODE_STRUCT
2165 && t->code () != TYPE_CODE_UNION)
2166 error (_("Internal error: `%s' is not an aggregate"),
2167 langdef->name_of_this ());
2169 if (check_field (t, name, is_a_field_of_this))
2171 symbol_lookup_debug_printf ("no symbol found");
2172 return {};
2177 /* Now do whatever is appropriate for LANGUAGE to look
2178 up static and global variables. */
2180 result = langdef->lookup_symbol_nonlocal (name, block, domain);
2181 if (result.symbol != NULL)
2183 symbol_lookup_debug_printf
2184 ("found symbol @ %s (using language lookup_symbol_nonlocal)",
2185 host_address_to_string (result.symbol));
2186 return result;
2189 /* Now search all static file-level symbols. Not strictly correct,
2190 but more useful than an error. */
2192 result = lookup_static_symbol (name, domain);
2193 symbol_lookup_debug_printf
2194 ("found symbol @ %s (using lookup_static_symbol)",
2195 result.symbol != NULL ? host_address_to_string (result.symbol) : "NULL");
2196 return result;
2199 /* Check to see if the symbol is defined in BLOCK or its superiors.
2200 Don't search STATIC_BLOCK or GLOBAL_BLOCK. */
2202 static struct block_symbol
2203 lookup_local_symbol (const char *name,
2204 symbol_name_match_type match_type,
2205 const struct block *block,
2206 const domain_search_flags domain,
2207 enum language language)
2209 if (block == nullptr)
2210 return {};
2212 struct symbol *sym;
2213 const struct block *static_block = block->static_block ();
2214 const char *scope = block->scope ();
2216 /* Check if it's a global block. */
2217 if (static_block == nullptr)
2218 return {};
2220 while (block != static_block)
2222 sym = lookup_symbol_in_block (name, match_type, block, domain);
2223 if (sym != NULL)
2224 return (struct block_symbol) {sym, block};
2226 if (language == language_cplus || language == language_fortran)
2228 struct block_symbol blocksym
2229 = cp_lookup_symbol_imports_or_template (scope, name, block,
2230 domain);
2232 if (blocksym.symbol != NULL)
2233 return blocksym;
2236 if (block->function () != NULL && block->inlined_p ())
2237 break;
2238 block = block->superblock ();
2241 /* We've reached the end of the function without finding a result. */
2243 return {};
2246 /* See symtab.h. */
2248 struct symbol *
2249 lookup_symbol_in_block (const char *name, symbol_name_match_type match_type,
2250 const struct block *block,
2251 const domain_search_flags domain)
2253 struct symbol *sym;
2255 if (symbol_lookup_debug)
2257 struct objfile *objfile
2258 = block == nullptr ? nullptr : block->objfile ();
2260 symbol_lookup_debug_printf_v
2261 ("lookup_symbol_in_block (%s, %s (objfile %s), %s)",
2262 name, host_address_to_string (block),
2263 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2264 domain_name (domain).c_str ());
2267 lookup_name_info lookup_name (name, match_type);
2268 sym = block_lookup_symbol (block, lookup_name, domain);
2269 if (sym)
2271 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = %s",
2272 host_address_to_string (sym));
2273 return sym;
2276 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = NULL");
2277 return NULL;
2280 /* See symtab.h. */
2282 struct block_symbol
2283 lookup_global_symbol_from_objfile (struct objfile *main_objfile,
2284 enum block_enum block_index,
2285 const char *name,
2286 const domain_search_flags domain)
2288 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2290 for (objfile *objfile : main_objfile->separate_debug_objfiles ())
2292 struct block_symbol result
2293 = lookup_symbol_in_objfile (objfile, block_index, name, domain);
2295 if (result.symbol != nullptr)
2296 return result;
2299 return {};
2302 /* Check to see if the symbol is defined in one of the OBJFILE's
2303 symtabs. BLOCK_INDEX should be either GLOBAL_BLOCK or STATIC_BLOCK,
2304 depending on whether or not we want to search global symbols or
2305 static symbols. */
2307 static struct block_symbol
2308 lookup_symbol_in_objfile_symtabs (struct objfile *objfile,
2309 enum block_enum block_index, const char *name,
2310 const domain_search_flags domain)
2312 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2314 symbol_lookup_debug_printf_v
2315 ("lookup_symbol_in_objfile_symtabs (%s, %s, %s, %s)",
2316 objfile_debug_name (objfile),
2317 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2318 name, domain_name (domain).c_str ());
2320 struct block_symbol other;
2321 other.symbol = NULL;
2322 for (compunit_symtab *cust : objfile->compunits ())
2324 const struct blockvector *bv;
2325 const struct block *block;
2326 struct block_symbol result;
2328 bv = cust->blockvector ();
2329 block = bv->block (block_index);
2330 result.symbol = block_lookup_symbol_primary (block, name, domain);
2331 result.block = block;
2332 if (result.symbol == NULL)
2333 continue;
2334 if (best_symbol (result.symbol, domain))
2336 other = result;
2337 break;
2339 if (result.symbol->matches (domain))
2341 struct symbol *better
2342 = better_symbol (other.symbol, result.symbol, domain);
2343 if (better != other.symbol)
2345 other.symbol = better;
2346 other.block = block;
2351 if (other.symbol != NULL)
2353 symbol_lookup_debug_printf_v
2354 ("lookup_symbol_in_objfile_symtabs (...) = %s (block %s)",
2355 host_address_to_string (other.symbol),
2356 host_address_to_string (other.block));
2357 return other;
2360 symbol_lookup_debug_printf_v
2361 ("lookup_symbol_in_objfile_symtabs (...) = NULL");
2362 return {};
2365 /* Wrapper around lookup_symbol_in_objfile_symtabs for search_symbols.
2366 Look up LINKAGE_NAME in DOMAIN in the global and static blocks of OBJFILE
2367 and all associated separate debug objfiles.
2369 Normally we only look in OBJFILE, and not any separate debug objfiles
2370 because the outer loop will cause them to be searched too. This case is
2371 different. Here we're called from search_symbols where it will only
2372 call us for the objfile that contains a matching minsym. */
2374 static struct block_symbol
2375 lookup_symbol_in_objfile_from_linkage_name (struct objfile *objfile,
2376 const char *linkage_name,
2377 domain_search_flags domain)
2379 enum language lang = current_language->la_language;
2380 struct objfile *main_objfile;
2382 demangle_result_storage storage;
2383 const char *modified_name = demangle_for_lookup (linkage_name, lang, storage);
2385 if (objfile->separate_debug_objfile_backlink)
2386 main_objfile = objfile->separate_debug_objfile_backlink;
2387 else
2388 main_objfile = objfile;
2390 for (::objfile *cur_objfile : main_objfile->separate_debug_objfiles ())
2392 struct block_symbol result;
2394 result = lookup_symbol_in_objfile_symtabs (cur_objfile, GLOBAL_BLOCK,
2395 modified_name, domain);
2396 if (result.symbol == NULL)
2397 result = lookup_symbol_in_objfile_symtabs (cur_objfile, STATIC_BLOCK,
2398 modified_name, domain);
2399 if (result.symbol != NULL)
2400 return result;
2403 return {};
2406 /* A helper function that throws an exception when a symbol was found
2407 in a psymtab but not in a symtab. */
2409 static void ATTRIBUTE_NORETURN
2410 error_in_psymtab_expansion (enum block_enum block_index, const char *name,
2411 struct compunit_symtab *cust)
2413 error (_("\
2414 Internal: %s symbol `%s' found in %s psymtab but not in symtab.\n\
2415 %s may be an inlined function, or may be a template function\n \
2416 (if a template, try specifying an instantiation: %s<type>)."),
2417 block_index == GLOBAL_BLOCK ? "global" : "static",
2418 name,
2419 symtab_to_filename_for_display (cust->primary_filetab ()),
2420 name, name);
2423 /* A helper function for various lookup routines that interfaces with
2424 the "quick" symbol table functions. */
2426 static struct block_symbol
2427 lookup_symbol_via_quick_fns (struct objfile *objfile,
2428 enum block_enum block_index, const char *name,
2429 const domain_search_flags domain)
2431 struct compunit_symtab *cust;
2432 const struct blockvector *bv;
2433 const struct block *block;
2434 struct block_symbol result;
2436 symbol_lookup_debug_printf_v
2437 ("lookup_symbol_via_quick_fns (%s, %s, %s, %s)",
2438 objfile_debug_name (objfile),
2439 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2440 name, domain_name (domain).c_str ());
2442 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2443 cust = objfile->lookup_symbol (block_index, lookup_name, domain);
2444 if (cust == NULL)
2446 symbol_lookup_debug_printf_v
2447 ("lookup_symbol_via_quick_fns (...) = NULL");
2448 return {};
2451 bv = cust->blockvector ();
2452 block = bv->block (block_index);
2453 result.symbol = block_lookup_symbol (block, lookup_name, domain);
2454 if (result.symbol == NULL)
2455 error_in_psymtab_expansion (block_index, name, cust);
2457 symbol_lookup_debug_printf_v
2458 ("lookup_symbol_via_quick_fns (...) = %s (block %s)",
2459 host_address_to_string (result.symbol),
2460 host_address_to_string (block));
2462 result.block = block;
2463 return result;
2466 /* See language.h. */
2468 struct block_symbol
2469 language_defn::lookup_symbol_nonlocal (const char *name,
2470 const struct block *block,
2471 const domain_search_flags domain) const
2473 struct block_symbol result;
2475 /* NOTE: dje/2014-10-26: The lookup in all objfiles search could skip
2476 the current objfile. Searching the current objfile first is useful
2477 for both matching user expectations as well as performance. */
2479 result = lookup_symbol_in_static_block (name, block, domain);
2480 if (result.symbol != NULL)
2481 return result;
2483 /* If we didn't find a definition for a builtin type in the static block,
2484 search for it now. This is actually the right thing to do and can be
2485 a massive performance win. E.g., when debugging a program with lots of
2486 shared libraries we could search all of them only to find out the
2487 builtin type isn't defined in any of them. This is common for types
2488 like "void". */
2489 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
2491 struct gdbarch *gdbarch;
2493 if (block == NULL)
2494 gdbarch = current_inferior ()->arch ();
2495 else
2496 gdbarch = block->gdbarch ();
2497 result.symbol = language_lookup_primitive_type_as_symbol (this,
2498 gdbarch, name);
2499 result.block = NULL;
2500 if (result.symbol != NULL)
2501 return result;
2504 return lookup_global_symbol (name, block, domain);
2507 /* See symtab.h. */
2509 struct block_symbol
2510 lookup_symbol_in_static_block (const char *name,
2511 const struct block *block,
2512 const domain_search_flags domain)
2514 if (block == nullptr)
2515 return {};
2517 const struct block *static_block = block->static_block ();
2518 struct symbol *sym;
2520 if (static_block == NULL)
2521 return {};
2523 if (symbol_lookup_debug)
2525 struct objfile *objfile = (block == nullptr
2526 ? nullptr : block->objfile ());
2528 symbol_lookup_debug_printf
2529 ("lookup_symbol_in_static_block (%s, %s (objfile %s), %s)",
2530 name, host_address_to_string (block),
2531 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2532 domain_name (domain).c_str ());
2535 sym = lookup_symbol_in_block (name,
2536 symbol_name_match_type::FULL,
2537 static_block, domain);
2538 symbol_lookup_debug_printf ("lookup_symbol_in_static_block (...) = %s",
2539 sym != NULL
2540 ? host_address_to_string (sym) : "NULL");
2541 return (struct block_symbol) {sym, static_block};
2544 /* Perform the standard symbol lookup of NAME in OBJFILE:
2545 1) First search expanded symtabs, and if not found
2546 2) Search the "quick" symtabs (partial or .gdb_index).
2547 BLOCK_INDEX is one of GLOBAL_BLOCK or STATIC_BLOCK. */
2549 static struct block_symbol
2550 lookup_symbol_in_objfile (struct objfile *objfile, enum block_enum block_index,
2551 const char *name, const domain_search_flags domain)
2553 struct block_symbol result;
2555 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2557 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (%s, %s, %s, %s)",
2558 objfile_debug_name (objfile),
2559 block_index == GLOBAL_BLOCK
2560 ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2561 name, domain_name (domain).c_str ());
2563 result = lookup_symbol_in_objfile_symtabs (objfile, block_index,
2564 name, domain);
2565 if (result.symbol != NULL)
2567 symbol_lookup_debug_printf
2568 ("lookup_symbol_in_objfile (...) = %s (in symtabs)",
2569 host_address_to_string (result.symbol));
2570 return result;
2573 result = lookup_symbol_via_quick_fns (objfile, block_index,
2574 name, domain);
2575 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (...) = %s%s",
2576 result.symbol != NULL
2577 ? host_address_to_string (result.symbol)
2578 : "NULL",
2579 result.symbol != NULL ? " (via quick fns)"
2580 : "");
2581 return result;
2584 /* This function contains the common code of lookup_{global,static}_symbol.
2585 OBJFILE is only used if BLOCK_INDEX is GLOBAL_SCOPE, in which case it is
2586 the objfile to start the lookup in. */
2588 static struct block_symbol
2589 lookup_global_or_static_symbol (const char *name,
2590 enum block_enum block_index,
2591 struct objfile *objfile,
2592 const domain_search_flags domain)
2594 struct symbol_cache *cache = get_symbol_cache (current_program_space);
2595 struct block_symbol result;
2596 struct block_symbol_cache *bsc;
2597 struct symbol_cache_slot *slot;
2599 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2600 gdb_assert (objfile == nullptr || block_index == GLOBAL_BLOCK);
2602 /* First see if we can find the symbol in the cache.
2603 This works because we use the current objfile to qualify the lookup. */
2604 result = symbol_cache_lookup (cache, objfile, block_index, name, domain,
2605 &bsc, &slot);
2606 if (result.symbol != NULL)
2608 if (SYMBOL_LOOKUP_FAILED_P (result))
2609 return {};
2610 return result;
2613 /* Do a global search (of global blocks, heh). */
2614 if (result.symbol == NULL)
2615 gdbarch_iterate_over_objfiles_in_search_order
2616 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
2617 [&result, block_index, name, domain] (struct objfile *objfile_iter)
2619 result = lookup_symbol_in_objfile (objfile_iter, block_index,
2620 name, domain);
2621 return result.symbol != nullptr;
2623 objfile);
2625 if (result.symbol != NULL)
2626 symbol_cache_mark_found (bsc, slot, objfile, result.symbol, result.block,
2627 domain);
2628 else
2629 symbol_cache_mark_not_found (bsc, slot, objfile, name, domain);
2631 return result;
2634 /* See symtab.h. */
2636 struct block_symbol
2637 lookup_static_symbol (const char *name, const domain_search_flags domain)
2639 return lookup_global_or_static_symbol (name, STATIC_BLOCK, nullptr, domain);
2642 /* See symtab.h. */
2644 struct block_symbol
2645 lookup_global_symbol (const char *name,
2646 const struct block *block,
2647 const domain_search_flags domain)
2649 /* If a block was passed in, we want to search the corresponding
2650 global block first. This yields "more expected" behavior, and is
2651 needed to support 'FILENAME'::VARIABLE lookups. */
2652 const struct block *global_block
2653 = block == nullptr ? nullptr : block->global_block ();
2654 symbol *sym = NULL;
2655 if (global_block != nullptr)
2657 sym = lookup_symbol_in_block (name,
2658 symbol_name_match_type::FULL,
2659 global_block, domain);
2660 if (sym != NULL && best_symbol (sym, domain))
2661 return { sym, global_block };
2664 struct objfile *objfile = nullptr;
2665 if (block != nullptr)
2667 objfile = block->objfile ();
2668 if (objfile->separate_debug_objfile_backlink != nullptr)
2669 objfile = objfile->separate_debug_objfile_backlink;
2672 block_symbol bs
2673 = lookup_global_or_static_symbol (name, GLOBAL_BLOCK, objfile, domain);
2674 if (better_symbol (sym, bs.symbol, domain) == sym)
2675 return { sym, global_block };
2676 else
2677 return bs;
2680 /* See symtab.h. */
2682 bool
2683 symbol::matches (domain_search_flags flags) const
2685 /* C++ has a typedef for every tag, and the types are in the struct
2686 domain. */
2687 if (language () == language_cplus && (flags & SEARCH_TYPE_DOMAIN) != 0)
2688 flags |= SEARCH_STRUCT_DOMAIN;
2690 return search_flags_matches (flags, m_domain);
2693 /* See symtab.h. */
2695 struct type *
2696 lookup_transparent_type (const char *name, domain_search_flags flags)
2698 return current_language->lookup_transparent_type (name, flags);
2701 /* A helper for basic_lookup_transparent_type that interfaces with the
2702 "quick" symbol table functions. */
2704 static struct type *
2705 basic_lookup_transparent_type_quick (struct objfile *objfile,
2706 enum block_enum block_index,
2707 domain_search_flags flags,
2708 const lookup_name_info &name)
2710 struct compunit_symtab *cust;
2711 const struct blockvector *bv;
2712 const struct block *block;
2713 struct symbol *sym;
2715 cust = objfile->lookup_symbol (block_index, name, flags);
2716 if (cust == NULL)
2717 return NULL;
2719 bv = cust->blockvector ();
2720 block = bv->block (block_index);
2722 sym = block_find_symbol (block, name, flags, nullptr);
2723 if (sym == nullptr)
2724 error_in_psymtab_expansion (block_index, name.c_str (), cust);
2725 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2726 return sym->type ();
2729 /* Subroutine of basic_lookup_transparent_type to simplify it.
2730 Look up the non-opaque definition of NAME in BLOCK_INDEX of OBJFILE.
2731 BLOCK_INDEX is either GLOBAL_BLOCK or STATIC_BLOCK. */
2733 static struct type *
2734 basic_lookup_transparent_type_1 (struct objfile *objfile,
2735 enum block_enum block_index,
2736 domain_search_flags flags,
2737 const lookup_name_info &name)
2739 const struct blockvector *bv;
2740 const struct block *block;
2741 const struct symbol *sym;
2743 for (compunit_symtab *cust : objfile->compunits ())
2745 bv = cust->blockvector ();
2746 block = bv->block (block_index);
2747 sym = block_find_symbol (block, name, flags, nullptr);
2748 if (sym != nullptr)
2750 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2751 return sym->type ();
2755 return NULL;
2758 /* The standard implementation of lookup_transparent_type. This code
2759 was modeled on lookup_symbol -- the parts not relevant to looking
2760 up types were just left out. In particular it's assumed here that
2761 types are available in STRUCT_DOMAIN and only in file-static or
2762 global blocks. */
2764 struct type *
2765 basic_lookup_transparent_type (const char *name, domain_search_flags flags)
2767 struct type *t;
2769 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2771 /* Now search all the global symbols. Do the symtab's first, then
2772 check the psymtab's. If a psymtab indicates the existence
2773 of the desired name as a global, then do psymtab-to-symtab
2774 conversion on the fly and return the found symbol. */
2776 for (objfile *objfile : current_program_space->objfiles ())
2778 t = basic_lookup_transparent_type_1 (objfile, GLOBAL_BLOCK,
2779 flags, lookup_name);
2780 if (t)
2781 return t;
2784 for (objfile *objfile : current_program_space->objfiles ())
2786 t = basic_lookup_transparent_type_quick (objfile, GLOBAL_BLOCK,
2787 flags, lookup_name);
2788 if (t)
2789 return t;
2792 /* Now search the static file-level symbols.
2793 Not strictly correct, but more useful than an error.
2794 Do the symtab's first, then
2795 check the psymtab's. If a psymtab indicates the existence
2796 of the desired name as a file-level static, then do psymtab-to-symtab
2797 conversion on the fly and return the found symbol. */
2799 for (objfile *objfile : current_program_space->objfiles ())
2801 t = basic_lookup_transparent_type_1 (objfile, STATIC_BLOCK,
2802 flags, lookup_name);
2803 if (t)
2804 return t;
2807 for (objfile *objfile : current_program_space->objfiles ())
2809 t = basic_lookup_transparent_type_quick (objfile, STATIC_BLOCK,
2810 flags, lookup_name);
2811 if (t)
2812 return t;
2815 return (struct type *) 0;
2818 /* See symtab.h. */
2820 bool
2821 iterate_over_symbols (const struct block *block,
2822 const lookup_name_info &name,
2823 const domain_search_flags domain,
2824 gdb::function_view<symbol_found_callback_ftype> callback)
2826 for (struct symbol *sym : block_iterator_range (block, &name))
2828 if (sym->matches (domain))
2830 struct block_symbol block_sym = {sym, block};
2832 if (!callback (&block_sym))
2833 return false;
2836 return true;
2839 /* See symtab.h. */
2841 bool
2842 iterate_over_symbols_terminated
2843 (const struct block *block,
2844 const lookup_name_info &name,
2845 const domain_search_flags domain,
2846 gdb::function_view<symbol_found_callback_ftype> callback)
2848 if (!iterate_over_symbols (block, name, domain, callback))
2849 return false;
2850 struct block_symbol block_sym = {nullptr, block};
2851 return callback (&block_sym);
2854 /* Find the compunit symtab associated with PC and SECTION.
2855 This will read in debug info as necessary. */
2857 struct compunit_symtab *
2858 find_pc_sect_compunit_symtab (CORE_ADDR pc, struct obj_section *section)
2860 struct compunit_symtab *best_cust = NULL;
2861 CORE_ADDR best_cust_range = 0;
2862 struct bound_minimal_symbol msymbol;
2864 /* If we know that this is not a text address, return failure. This is
2865 necessary because we loop based on the block's high and low code
2866 addresses, which do not include the data ranges, and because
2867 we call find_pc_sect_psymtab which has a similar restriction based
2868 on the partial_symtab's texthigh and textlow. */
2869 msymbol = lookup_minimal_symbol_by_pc_section (pc, section);
2870 if (msymbol.minsym && msymbol.minsym->data_p ())
2871 return NULL;
2873 /* Search all symtabs for the one whose file contains our address, and which
2874 is the smallest of all the ones containing the address. This is designed
2875 to deal with a case like symtab a is at 0x1000-0x2000 and 0x3000-0x4000
2876 and symtab b is at 0x2000-0x3000. So the GLOBAL_BLOCK for a is from
2877 0x1000-0x4000, but for address 0x2345 we want to return symtab b.
2879 This happens for native ecoff format, where code from included files
2880 gets its own symtab. The symtab for the included file should have
2881 been read in already via the dependency mechanism.
2882 It might be swifter to create several symtabs with the same name
2883 like xcoff does (I'm not sure).
2885 It also happens for objfiles that have their functions reordered.
2886 For these, the symtab we are looking for is not necessarily read in. */
2888 for (objfile *obj_file : current_program_space->objfiles ())
2890 for (compunit_symtab *cust : obj_file->compunits ())
2892 const struct blockvector *bv = cust->blockvector ();
2893 const struct block *global_block = bv->global_block ();
2894 CORE_ADDR start = global_block->start ();
2895 CORE_ADDR end = global_block->end ();
2896 bool in_range_p = start <= pc && pc < end;
2897 if (!in_range_p)
2898 continue;
2900 if (bv->map () != nullptr)
2902 if (bv->map ()->find (pc) == nullptr)
2903 continue;
2905 return cust;
2908 CORE_ADDR range = end - start;
2909 if (best_cust != nullptr
2910 && range >= best_cust_range)
2911 /* Cust doesn't have a smaller range than best_cust, skip it. */
2912 continue;
2914 /* For an objfile that has its functions reordered,
2915 find_pc_psymtab will find the proper partial symbol table
2916 and we simply return its corresponding symtab. */
2917 /* In order to better support objfiles that contain both
2918 stabs and coff debugging info, we continue on if a psymtab
2919 can't be found. */
2920 struct compunit_symtab *result
2921 = obj_file->find_pc_sect_compunit_symtab (msymbol, pc,
2922 section, 0);
2923 if (result != nullptr)
2924 return result;
2926 if (section != 0)
2928 struct symbol *found_sym = nullptr;
2930 for (int b_index = GLOBAL_BLOCK;
2931 b_index <= STATIC_BLOCK && found_sym == nullptr;
2932 ++b_index)
2934 const struct block *b = bv->block (b_index);
2935 for (struct symbol *sym : block_iterator_range (b))
2937 if (matching_obj_sections (sym->obj_section (obj_file),
2938 section))
2940 found_sym = sym;
2941 break;
2945 if (found_sym == nullptr)
2946 continue; /* No symbol in this symtab matches
2947 section. */
2950 /* Cust is best found sofar, save it. */
2951 best_cust = cust;
2952 best_cust_range = range;
2956 if (best_cust != NULL)
2957 return best_cust;
2959 /* Not found in symtabs, search the "quick" symtabs (e.g. psymtabs). */
2961 for (objfile *objf : current_program_space->objfiles ())
2963 struct compunit_symtab *result
2964 = objf->find_pc_sect_compunit_symtab (msymbol, pc, section, 1);
2965 if (result != NULL)
2966 return result;
2969 return NULL;
2972 /* Find the compunit symtab associated with PC.
2973 This will read in debug info as necessary.
2974 Backward compatibility, no section. */
2976 struct compunit_symtab *
2977 find_pc_compunit_symtab (CORE_ADDR pc)
2979 return find_pc_sect_compunit_symtab (pc, find_pc_mapped_section (pc));
2982 /* See symtab.h. */
2984 struct symbol *
2985 find_symbol_at_address (CORE_ADDR address)
2987 /* A helper function to search a given symtab for a symbol matching
2988 ADDR. */
2989 auto search_symtab = [] (compunit_symtab *symtab, CORE_ADDR addr) -> symbol *
2991 const struct blockvector *bv = symtab->blockvector ();
2993 for (int i = GLOBAL_BLOCK; i <= STATIC_BLOCK; ++i)
2995 const struct block *b = bv->block (i);
2997 for (struct symbol *sym : block_iterator_range (b))
2999 if (sym->aclass () == LOC_STATIC
3000 && sym->value_address () == addr)
3001 return sym;
3004 return nullptr;
3007 for (objfile *objfile : current_program_space->objfiles ())
3009 /* If this objfile was read with -readnow, then we need to
3010 search the symtabs directly. */
3011 if ((objfile->flags & OBJF_READNOW) != 0)
3013 for (compunit_symtab *symtab : objfile->compunits ())
3015 struct symbol *sym = search_symtab (symtab, address);
3016 if (sym != nullptr)
3017 return sym;
3020 else
3022 struct compunit_symtab *symtab
3023 = objfile->find_compunit_symtab_by_address (address);
3024 if (symtab != NULL)
3026 struct symbol *sym = search_symtab (symtab, address);
3027 if (sym != nullptr)
3028 return sym;
3033 return NULL;
3038 /* Find the source file and line number for a given PC value and SECTION.
3039 Return a structure containing a symtab pointer, a line number,
3040 and a pc range for the entire source line.
3041 The value's .pc field is NOT the specified pc.
3042 NOTCURRENT nonzero means, if specified pc is on a line boundary,
3043 use the line that ends there. Otherwise, in that case, the line
3044 that begins there is used. */
3046 /* The big complication here is that a line may start in one file, and end just
3047 before the start of another file. This usually occurs when you #include
3048 code in the middle of a subroutine. To properly find the end of a line's PC
3049 range, we must search all symtabs associated with this compilation unit, and
3050 find the one whose first PC is closer than that of the next line in this
3051 symtab. */
3053 struct symtab_and_line
3054 find_pc_sect_line (CORE_ADDR pc, struct obj_section *section, int notcurrent)
3056 struct compunit_symtab *cust;
3057 const linetable *l;
3058 int len;
3059 const linetable_entry *item;
3060 const struct blockvector *bv;
3061 struct bound_minimal_symbol msymbol;
3063 /* Info on best line seen so far, and where it starts, and its file. */
3065 const linetable_entry *best = NULL;
3066 CORE_ADDR best_end = 0;
3067 struct symtab *best_symtab = 0;
3069 /* Store here the first line number
3070 of a file which contains the line at the smallest pc after PC.
3071 If we don't find a line whose range contains PC,
3072 we will use a line one less than this,
3073 with a range from the start of that file to the first line's pc. */
3074 const linetable_entry *alt = NULL;
3076 /* Info on best line seen in this file. */
3078 const linetable_entry *prev;
3080 /* If this pc is not from the current frame,
3081 it is the address of the end of a call instruction.
3082 Quite likely that is the start of the following statement.
3083 But what we want is the statement containing the instruction.
3084 Fudge the pc to make sure we get that. */
3086 /* It's tempting to assume that, if we can't find debugging info for
3087 any function enclosing PC, that we shouldn't search for line
3088 number info, either. However, GAS can emit line number info for
3089 assembly files --- very helpful when debugging hand-written
3090 assembly code. In such a case, we'd have no debug info for the
3091 function, but we would have line info. */
3093 if (notcurrent)
3094 pc -= 1;
3096 /* elz: added this because this function returned the wrong
3097 information if the pc belongs to a stub (import/export)
3098 to call a shlib function. This stub would be anywhere between
3099 two functions in the target, and the line info was erroneously
3100 taken to be the one of the line before the pc. */
3102 /* RT: Further explanation:
3104 * We have stubs (trampolines) inserted between procedures.
3106 * Example: "shr1" exists in a shared library, and a "shr1" stub also
3107 * exists in the main image.
3109 * In the minimal symbol table, we have a bunch of symbols
3110 * sorted by start address. The stubs are marked as "trampoline",
3111 * the others appear as text. E.g.:
3113 * Minimal symbol table for main image
3114 * main: code for main (text symbol)
3115 * shr1: stub (trampoline symbol)
3116 * foo: code for foo (text symbol)
3117 * ...
3118 * Minimal symbol table for "shr1" image:
3119 * ...
3120 * shr1: code for shr1 (text symbol)
3121 * ...
3123 * So the code below is trying to detect if we are in the stub
3124 * ("shr1" stub), and if so, find the real code ("shr1" trampoline),
3125 * and if found, do the symbolization from the real-code address
3126 * rather than the stub address.
3128 * Assumptions being made about the minimal symbol table:
3129 * 1. lookup_minimal_symbol_by_pc() will return a trampoline only
3130 * if we're really in the trampoline.s If we're beyond it (say
3131 * we're in "foo" in the above example), it'll have a closer
3132 * symbol (the "foo" text symbol for example) and will not
3133 * return the trampoline.
3134 * 2. lookup_minimal_symbol_text() will find a real text symbol
3135 * corresponding to the trampoline, and whose address will
3136 * be different than the trampoline address. I put in a sanity
3137 * check for the address being the same, to avoid an
3138 * infinite recursion.
3140 msymbol = lookup_minimal_symbol_by_pc (pc);
3141 if (msymbol.minsym != NULL)
3142 if (msymbol.minsym->type () == mst_solib_trampoline)
3144 struct bound_minimal_symbol mfunsym
3145 = lookup_minimal_symbol_text (msymbol.minsym->linkage_name (),
3146 NULL);
3148 if (mfunsym.minsym == NULL)
3149 /* I eliminated this warning since it is coming out
3150 * in the following situation:
3151 * gdb shmain // test program with shared libraries
3152 * (gdb) break shr1 // function in shared lib
3153 * Warning: In stub for ...
3154 * In the above situation, the shared lib is not loaded yet,
3155 * so of course we can't find the real func/line info,
3156 * but the "break" still works, and the warning is annoying.
3157 * So I commented out the warning. RT */
3158 /* warning ("In stub for %s; unable to find real function/line info",
3159 msymbol->linkage_name ()); */
3161 /* fall through */
3162 else if (mfunsym.value_address ()
3163 == msymbol.value_address ())
3164 /* Avoid infinite recursion */
3165 /* See above comment about why warning is commented out. */
3166 /* warning ("In stub for %s; unable to find real function/line info",
3167 msymbol->linkage_name ()); */
3169 /* fall through */
3170 else
3172 /* Detect an obvious case of infinite recursion. If this
3173 should occur, we'd like to know about it, so error out,
3174 fatally. */
3175 if (mfunsym.value_address () == pc)
3176 internal_error (_("Infinite recursion detected in find_pc_sect_line;"
3177 "please file a bug report"));
3179 return find_pc_line (mfunsym.value_address (), 0);
3183 symtab_and_line val;
3184 val.pspace = current_program_space;
3186 cust = find_pc_sect_compunit_symtab (pc, section);
3187 if (cust == NULL)
3189 /* If no symbol information, return previous pc. */
3190 if (notcurrent)
3191 pc++;
3192 val.pc = pc;
3193 return val;
3196 bv = cust->blockvector ();
3197 struct objfile *objfile = cust->objfile ();
3199 /* Look at all the symtabs that share this blockvector.
3200 They all have the same apriori range, that we found was right;
3201 but they have different line tables. */
3203 for (symtab *iter_s : cust->filetabs ())
3205 /* Find the best line in this symtab. */
3206 l = iter_s->linetable ();
3207 if (!l)
3208 continue;
3209 len = l->nitems;
3210 if (len <= 0)
3212 /* I think len can be zero if the symtab lacks line numbers
3213 (e.g. gcc -g1). (Either that or the LINETABLE is NULL;
3214 I'm not sure which, and maybe it depends on the symbol
3215 reader). */
3216 continue;
3219 prev = NULL;
3220 item = l->item; /* Get first line info. */
3222 /* Is this file's first line closer than the first lines of other files?
3223 If so, record this file, and its first line, as best alternate. */
3224 if (item->pc (objfile) > pc
3225 && (!alt || item->unrelocated_pc () < alt->unrelocated_pc ()))
3226 alt = item;
3228 auto pc_compare = [] (const unrelocated_addr &comp_pc,
3229 const struct linetable_entry & lhs)
3231 return comp_pc < lhs.unrelocated_pc ();
3234 const linetable_entry *first = item;
3235 const linetable_entry *last = item + len;
3236 item = (std::upper_bound
3237 (first, last,
3238 unrelocated_addr (pc - objfile->text_section_offset ()),
3239 pc_compare));
3240 if (item != first)
3242 prev = item - 1; /* Found a matching item. */
3243 /* At this point, prev is a line whose address is <= pc. However, we
3244 don't know if ITEM is pointing to the same statement or not. */
3245 while (item != last && prev->line == item->line && !item->is_stmt)
3246 item++;
3249 /* At this point, prev points at the line whose start addr is <= pc, and
3250 item points at the next statement. If we ran off the end of the linetable
3251 (pc >= start of the last line), then prev == item. If pc < start of
3252 the first line, prev will not be set. */
3254 /* Is this file's best line closer than the best in the other files?
3255 If so, record this file, and its best line, as best so far. Don't
3256 save prev if it represents the end of a function (i.e. line number
3257 0) instead of a real line. */
3259 if (prev && prev->line
3260 && (!best || prev->unrelocated_pc () > best->unrelocated_pc ()))
3262 best = prev;
3263 best_symtab = iter_s;
3265 /* If during the binary search we land on a non-statement entry,
3266 scan backward through entries at the same address to see if
3267 there is an entry marked as is-statement. In theory this
3268 duplication should have been removed from the line table
3269 during construction, this is just a double check. If the line
3270 table has had the duplication removed then this should be
3271 pretty cheap. */
3272 if (!best->is_stmt)
3274 const linetable_entry *tmp = best;
3275 while (tmp > first
3276 && (tmp - 1)->unrelocated_pc () == tmp->unrelocated_pc ()
3277 && (tmp - 1)->line != 0 && !tmp->is_stmt)
3278 --tmp;
3279 if (tmp->is_stmt)
3280 best = tmp;
3283 /* Discard BEST_END if it's before the PC of the current BEST. */
3284 if (best_end <= best->pc (objfile))
3285 best_end = 0;
3288 /* If another line (denoted by ITEM) is in the linetable and its
3289 PC is after BEST's PC, but before the current BEST_END, then
3290 use ITEM's PC as the new best_end. */
3291 if (best && item < last
3292 && item->unrelocated_pc () > best->unrelocated_pc ()
3293 && (best_end == 0 || best_end > item->pc (objfile)))
3294 best_end = item->pc (objfile);
3297 if (!best_symtab)
3299 /* If we didn't find any line number info, just return zeros.
3300 We used to return alt->line - 1 here, but that could be
3301 anywhere; if we don't have line number info for this PC,
3302 don't make some up. */
3303 val.pc = pc;
3305 else if (best->line == 0)
3307 /* If our best fit is in a range of PC's for which no line
3308 number info is available (line number is zero) then we didn't
3309 find any valid line information. */
3310 val.pc = pc;
3312 else
3314 val.is_stmt = best->is_stmt;
3315 val.symtab = best_symtab;
3316 val.line = best->line;
3317 val.pc = best->pc (objfile);
3318 if (best_end && (!alt || best_end < alt->pc (objfile)))
3319 val.end = best_end;
3320 else if (alt)
3321 val.end = alt->pc (objfile);
3322 else
3323 val.end = bv->global_block ()->end ();
3325 val.section = section;
3326 return val;
3329 /* Backward compatibility (no section). */
3331 struct symtab_and_line
3332 find_pc_line (CORE_ADDR pc, int notcurrent)
3334 struct obj_section *section;
3336 section = find_pc_overlay (pc);
3337 if (!pc_in_unmapped_range (pc, section))
3338 return find_pc_sect_line (pc, section, notcurrent);
3340 /* If the original PC was an unmapped address then we translate this to a
3341 mapped address in order to lookup the sal. However, as the user
3342 passed us an unmapped address it makes more sense to return a result
3343 that has the pc and end fields translated to unmapped addresses. */
3344 pc = overlay_mapped_address (pc, section);
3345 symtab_and_line sal = find_pc_sect_line (pc, section, notcurrent);
3346 sal.pc = overlay_unmapped_address (sal.pc, section);
3347 sal.end = overlay_unmapped_address (sal.end, section);
3348 return sal;
3351 /* Compare two symtab_and_line entries. Return true if both have
3352 the same line number and the same symtab pointer. That means we
3353 are dealing with two entries from the same line and from the same
3354 source file.
3356 Return false otherwise. */
3358 static bool
3359 sal_line_symtab_matches_p (const symtab_and_line &sal1,
3360 const symtab_and_line &sal2)
3362 return sal1.line == sal2.line && sal1.symtab == sal2.symtab;
3365 /* See symtah.h. */
3367 std::optional<CORE_ADDR>
3368 find_line_range_start (CORE_ADDR pc)
3370 struct symtab_and_line current_sal = find_pc_line (pc, 0);
3372 if (current_sal.line == 0)
3373 return {};
3375 struct symtab_and_line prev_sal = find_pc_line (current_sal.pc - 1, 0);
3377 /* If the previous entry is for a different line, that means we are already
3378 at the entry with the start PC for this line. */
3379 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3380 return current_sal.pc;
3382 /* Otherwise, keep looking for entries for the same line but with
3383 smaller PC's. */
3384 bool done = false;
3385 CORE_ADDR prev_pc;
3386 while (!done)
3388 prev_pc = prev_sal.pc;
3390 prev_sal = find_pc_line (prev_pc - 1, 0);
3392 /* Did we notice a line change? If so, we are done searching. */
3393 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3394 done = true;
3397 return prev_pc;
3400 /* See symtab.h. */
3402 struct symtab *
3403 find_pc_line_symtab (CORE_ADDR pc)
3405 struct symtab_and_line sal;
3407 /* This always passes zero for NOTCURRENT to find_pc_line.
3408 There are currently no callers that ever pass non-zero. */
3409 sal = find_pc_line (pc, 0);
3410 return sal.symtab;
3413 /* Find line number LINE in any symtab whose name is the same as
3414 SYMTAB.
3416 If found, return the symtab that contains the linetable in which it was
3417 found, set *INDEX to the index in the linetable of the best entry
3418 found, and set *EXACT_MATCH to true if the value returned is an
3419 exact match.
3421 If not found, return NULL. */
3423 struct symtab *
3424 find_line_symtab (struct symtab *sym_tab, int line,
3425 int *index, bool *exact_match)
3427 int exact = 0; /* Initialized here to avoid a compiler warning. */
3429 /* BEST_INDEX and BEST_LINETABLE identify the smallest linenumber > LINE
3430 so far seen. */
3432 int best_index;
3433 const struct linetable *best_linetable;
3434 struct symtab *best_symtab;
3436 /* First try looking it up in the given symtab. */
3437 best_linetable = sym_tab->linetable ();
3438 best_symtab = sym_tab;
3439 best_index = find_line_common (best_linetable, line, &exact, 0);
3440 if (best_index < 0 || !exact)
3442 /* Didn't find an exact match. So we better keep looking for
3443 another symtab with the same name. In the case of xcoff,
3444 multiple csects for one source file (produced by IBM's FORTRAN
3445 compiler) produce multiple symtabs (this is unavoidable
3446 assuming csects can be at arbitrary places in memory and that
3447 the GLOBAL_BLOCK of a symtab has a begin and end address). */
3449 /* BEST is the smallest linenumber > LINE so far seen,
3450 or 0 if none has been seen so far.
3451 BEST_INDEX and BEST_LINETABLE identify the item for it. */
3452 int best;
3454 if (best_index >= 0)
3455 best = best_linetable->item[best_index].line;
3456 else
3457 best = 0;
3459 for (objfile *objfile : current_program_space->objfiles ())
3460 objfile->expand_symtabs_with_fullname (symtab_to_fullname (sym_tab));
3462 for (objfile *objfile : current_program_space->objfiles ())
3464 for (compunit_symtab *cu : objfile->compunits ())
3466 for (symtab *s : cu->filetabs ())
3468 const struct linetable *l;
3469 int ind;
3471 if (FILENAME_CMP (sym_tab->filename, s->filename) != 0)
3472 continue;
3473 if (FILENAME_CMP (symtab_to_fullname (sym_tab),
3474 symtab_to_fullname (s)) != 0)
3475 continue;
3476 l = s->linetable ();
3477 ind = find_line_common (l, line, &exact, 0);
3478 if (ind >= 0)
3480 if (exact)
3482 best_index = ind;
3483 best_linetable = l;
3484 best_symtab = s;
3485 goto done;
3487 if (best == 0 || l->item[ind].line < best)
3489 best = l->item[ind].line;
3490 best_index = ind;
3491 best_linetable = l;
3492 best_symtab = s;
3499 done:
3500 if (best_index < 0)
3501 return NULL;
3503 if (index)
3504 *index = best_index;
3505 if (exact_match)
3506 *exact_match = (exact != 0);
3508 return best_symtab;
3511 /* Given SYMTAB, returns all the PCs function in the symtab that
3512 exactly match LINE. Returns an empty vector if there are no exact
3513 matches, but updates BEST_ITEM in this case. */
3515 std::vector<CORE_ADDR>
3516 find_pcs_for_symtab_line (struct symtab *symtab, int line,
3517 const linetable_entry **best_item)
3519 int start = 0;
3520 std::vector<CORE_ADDR> result;
3521 struct objfile *objfile = symtab->compunit ()->objfile ();
3523 /* First, collect all the PCs that are at this line. */
3524 while (1)
3526 int was_exact;
3527 int idx;
3529 idx = find_line_common (symtab->linetable (), line, &was_exact,
3530 start);
3531 if (idx < 0)
3532 break;
3534 if (!was_exact)
3536 const linetable_entry *item = &symtab->linetable ()->item[idx];
3538 if (*best_item == NULL
3539 || (item->line < (*best_item)->line && item->is_stmt))
3540 *best_item = item;
3542 break;
3545 result.push_back (symtab->linetable ()->item[idx].pc (objfile));
3546 start = idx + 1;
3549 return result;
3553 /* Set the PC value for a given source file and line number and return true.
3554 Returns false for invalid line number (and sets the PC to 0).
3555 The source file is specified with a struct symtab. */
3557 bool
3558 find_line_pc (struct symtab *symtab, int line, CORE_ADDR *pc)
3560 const struct linetable *l;
3561 int ind;
3563 *pc = 0;
3564 if (symtab == 0)
3565 return false;
3567 symtab = find_line_symtab (symtab, line, &ind, NULL);
3568 if (symtab != NULL)
3570 l = symtab->linetable ();
3571 *pc = l->item[ind].pc (symtab->compunit ()->objfile ());
3572 return true;
3574 else
3575 return false;
3578 /* Find the range of pc values in a line.
3579 Store the starting pc of the line into *STARTPTR
3580 and the ending pc (start of next line) into *ENDPTR.
3581 Returns true to indicate success.
3582 Returns false if could not find the specified line. */
3584 bool
3585 find_line_pc_range (struct symtab_and_line sal, CORE_ADDR *startptr,
3586 CORE_ADDR *endptr)
3588 CORE_ADDR startaddr;
3589 struct symtab_and_line found_sal;
3591 startaddr = sal.pc;
3592 if (startaddr == 0 && !find_line_pc (sal.symtab, sal.line, &startaddr))
3593 return false;
3595 /* This whole function is based on address. For example, if line 10 has
3596 two parts, one from 0x100 to 0x200 and one from 0x300 to 0x400, then
3597 "info line *0x123" should say the line goes from 0x100 to 0x200
3598 and "info line *0x355" should say the line goes from 0x300 to 0x400.
3599 This also insures that we never give a range like "starts at 0x134
3600 and ends at 0x12c". */
3602 found_sal = find_pc_sect_line (startaddr, sal.section, 0);
3603 if (found_sal.line != sal.line)
3605 /* The specified line (sal) has zero bytes. */
3606 *startptr = found_sal.pc;
3607 *endptr = found_sal.pc;
3609 else
3611 *startptr = found_sal.pc;
3612 *endptr = found_sal.end;
3614 return true;
3617 /* Given a line table and a line number, return the index into the line
3618 table for the pc of the nearest line whose number is >= the specified one.
3619 Return -1 if none is found. The value is >= 0 if it is an index.
3620 START is the index at which to start searching the line table.
3622 Set *EXACT_MATCH nonzero if the value returned is an exact match. */
3624 static int
3625 find_line_common (const linetable *l, int lineno,
3626 int *exact_match, int start)
3628 int i;
3629 int len;
3631 /* BEST is the smallest linenumber > LINENO so far seen,
3632 or 0 if none has been seen so far.
3633 BEST_INDEX identifies the item for it. */
3635 int best_index = -1;
3636 int best = 0;
3638 *exact_match = 0;
3640 if (lineno <= 0)
3641 return -1;
3642 if (l == 0)
3643 return -1;
3645 len = l->nitems;
3646 for (i = start; i < len; i++)
3648 const linetable_entry *item = &(l->item[i]);
3650 /* Ignore non-statements. */
3651 if (!item->is_stmt)
3652 continue;
3654 if (item->line == lineno)
3656 /* Return the first (lowest address) entry which matches. */
3657 *exact_match = 1;
3658 return i;
3661 if (item->line > lineno && (best == 0 || item->line < best))
3663 best = item->line;
3664 best_index = i;
3668 /* If we got here, we didn't get an exact match. */
3669 return best_index;
3672 bool
3673 find_pc_line_pc_range (CORE_ADDR pc, CORE_ADDR *startptr, CORE_ADDR *endptr)
3675 struct symtab_and_line sal;
3677 sal = find_pc_line (pc, 0);
3678 *startptr = sal.pc;
3679 *endptr = sal.end;
3680 return sal.symtab != 0;
3683 /* Helper for find_function_start_sal. Does most of the work, except
3684 setting the sal's symbol. */
3686 static symtab_and_line
3687 find_function_start_sal_1 (CORE_ADDR func_addr, obj_section *section,
3688 bool funfirstline)
3690 symtab_and_line sal = find_pc_sect_line (func_addr, section, 0);
3692 if (funfirstline && sal.symtab != NULL
3693 && (sal.symtab->compunit ()->locations_valid ()
3694 || sal.symtab->language () == language_asm))
3696 struct gdbarch *gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
3698 sal.pc = func_addr;
3699 if (gdbarch_skip_entrypoint_p (gdbarch))
3700 sal.pc = gdbarch_skip_entrypoint (gdbarch, sal.pc);
3701 return sal;
3704 /* We always should have a line for the function start address.
3705 If we don't, something is odd. Create a plain SAL referring
3706 just the PC and hope that skip_prologue_sal (if requested)
3707 can find a line number for after the prologue. */
3708 if (sal.pc < func_addr)
3710 sal = {};
3711 sal.pspace = current_program_space;
3712 sal.pc = func_addr;
3713 sal.section = section;
3716 if (funfirstline)
3717 skip_prologue_sal (&sal);
3719 return sal;
3722 /* See symtab.h. */
3724 symtab_and_line
3725 find_function_start_sal (CORE_ADDR func_addr, obj_section *section,
3726 bool funfirstline)
3728 symtab_and_line sal
3729 = find_function_start_sal_1 (func_addr, section, funfirstline);
3731 /* find_function_start_sal_1 does a linetable search, so it finds
3732 the symtab and linenumber, but not a symbol. Fill in the
3733 function symbol too. */
3734 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
3736 return sal;
3739 /* See symtab.h. */
3741 symtab_and_line
3742 find_function_start_sal (symbol *sym, bool funfirstline)
3744 symtab_and_line sal
3745 = find_function_start_sal_1 (sym->value_block ()->entry_pc (),
3746 sym->obj_section (sym->objfile ()),
3747 funfirstline);
3748 sal.symbol = sym;
3749 return sal;
3753 /* Given a function start address FUNC_ADDR and SYMTAB, find the first
3754 address for that function that has an entry in SYMTAB's line info
3755 table. If such an entry cannot be found, return FUNC_ADDR
3756 unaltered. */
3758 static CORE_ADDR
3759 skip_prologue_using_lineinfo (CORE_ADDR func_addr, struct symtab *symtab)
3761 CORE_ADDR func_start, func_end;
3762 const struct linetable *l;
3763 int i;
3765 /* Give up if this symbol has no lineinfo table. */
3766 l = symtab->linetable ();
3767 if (l == NULL)
3768 return func_addr;
3770 /* Get the range for the function's PC values, or give up if we
3771 cannot, for some reason. */
3772 if (!find_pc_partial_function (func_addr, NULL, &func_start, &func_end))
3773 return func_addr;
3775 struct objfile *objfile = symtab->compunit ()->objfile ();
3777 /* Linetable entries are ordered by PC values, see the commentary in
3778 symtab.h where `struct linetable' is defined. Thus, the first
3779 entry whose PC is in the range [FUNC_START..FUNC_END[ is the
3780 address we are looking for. */
3781 for (i = 0; i < l->nitems; i++)
3783 const linetable_entry *item = &(l->item[i]);
3784 CORE_ADDR item_pc = item->pc (objfile);
3786 /* Don't use line numbers of zero, they mark special entries in
3787 the table. See the commentary on symtab.h before the
3788 definition of struct linetable. */
3789 if (item->line > 0 && func_start <= item_pc && item_pc < func_end)
3790 return item_pc;
3793 return func_addr;
3796 /* Try to locate the address where a breakpoint should be placed past the
3797 prologue of function starting at FUNC_ADDR using the line table.
3799 Return the address associated with the first entry in the line-table for
3800 the function starting at FUNC_ADDR which has prologue_end set to true if
3801 such entry exist, otherwise return an empty optional. */
3803 static std::optional<CORE_ADDR>
3804 skip_prologue_using_linetable (CORE_ADDR func_addr)
3806 CORE_ADDR start_pc, end_pc;
3808 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
3809 return {};
3811 const struct symtab_and_line prologue_sal = find_pc_line (start_pc, 0);
3812 if (prologue_sal.symtab != nullptr
3813 && prologue_sal.symtab->language () != language_asm)
3815 const linetable *linetable = prologue_sal.symtab->linetable ();
3817 struct objfile *objfile = prologue_sal.symtab->compunit ()->objfile ();
3819 unrelocated_addr unrel_start
3820 = unrelocated_addr (start_pc - objfile->text_section_offset ());
3821 unrelocated_addr unrel_end
3822 = unrelocated_addr (end_pc - objfile->text_section_offset ());
3824 auto it = std::lower_bound
3825 (linetable->item, linetable->item + linetable->nitems, unrel_start,
3826 [] (const linetable_entry &lte, unrelocated_addr pc)
3828 return lte.unrelocated_pc () < pc;
3831 for (;
3832 (it < linetable->item + linetable->nitems
3833 && it->unrelocated_pc () < unrel_end);
3834 it++)
3835 if (it->prologue_end)
3836 return {it->pc (objfile)};
3839 return {};
3842 /* Adjust SAL to the first instruction past the function prologue.
3843 If the PC was explicitly specified, the SAL is not changed.
3844 If the line number was explicitly specified then the SAL can still be
3845 updated, unless the language for SAL is assembler, in which case the SAL
3846 will be left unchanged.
3847 If SAL is already past the prologue, then do nothing. */
3849 void
3850 skip_prologue_sal (struct symtab_and_line *sal)
3852 struct symbol *sym;
3853 struct symtab_and_line start_sal;
3854 CORE_ADDR pc, saved_pc;
3855 struct obj_section *section;
3856 const char *name;
3857 struct objfile *objfile;
3858 struct gdbarch *gdbarch;
3859 const struct block *b, *function_block;
3860 int force_skip, skip;
3862 /* Do not change the SAL if PC was specified explicitly. */
3863 if (sal->explicit_pc)
3864 return;
3866 /* In assembly code, if the user asks for a specific line then we should
3867 not adjust the SAL. The user already has instruction level
3868 visibility in this case, so selecting a line other than one requested
3869 is likely to be the wrong choice. */
3870 if (sal->symtab != nullptr
3871 && sal->explicit_line
3872 && sal->symtab->language () == language_asm)
3873 return;
3875 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3877 switch_to_program_space_and_thread (sal->pspace);
3879 sym = find_pc_sect_function (sal->pc, sal->section);
3880 if (sym != NULL)
3882 objfile = sym->objfile ();
3883 pc = sym->value_block ()->entry_pc ();
3884 section = sym->obj_section (objfile);
3885 name = sym->linkage_name ();
3887 else
3889 struct bound_minimal_symbol msymbol
3890 = lookup_minimal_symbol_by_pc_section (sal->pc, sal->section);
3892 if (msymbol.minsym == NULL)
3893 return;
3895 objfile = msymbol.objfile;
3896 pc = msymbol.value_address ();
3897 section = msymbol.minsym->obj_section (objfile);
3898 name = msymbol.minsym->linkage_name ();
3901 gdbarch = objfile->arch ();
3903 /* Process the prologue in two passes. In the first pass try to skip the
3904 prologue (SKIP is true) and verify there is a real need for it (indicated
3905 by FORCE_SKIP). If no such reason was found run a second pass where the
3906 prologue is not skipped (SKIP is false). */
3908 skip = 1;
3909 force_skip = 1;
3911 /* Be conservative - allow direct PC (without skipping prologue) only if we
3912 have proven the CU (Compilation Unit) supports it. sal->SYMTAB does not
3913 have to be set by the caller so we use SYM instead. */
3914 if (sym != NULL
3915 && sym->symtab ()->compunit ()->locations_valid ())
3916 force_skip = 0;
3918 saved_pc = pc;
3921 pc = saved_pc;
3923 /* Check if the compiler explicitly indicated where a breakpoint should
3924 be placed to skip the prologue. */
3925 if (!ignore_prologue_end_flag && skip)
3927 std::optional<CORE_ADDR> linetable_pc
3928 = skip_prologue_using_linetable (pc);
3929 if (linetable_pc)
3931 pc = *linetable_pc;
3932 start_sal = find_pc_sect_line (pc, section, 0);
3933 force_skip = 1;
3934 continue;
3938 /* If the function is in an unmapped overlay, use its unmapped LMA address,
3939 so that gdbarch_skip_prologue has something unique to work on. */
3940 if (section_is_overlay (section) && !section_is_mapped (section))
3941 pc = overlay_unmapped_address (pc, section);
3943 /* Skip "first line" of function (which is actually its prologue). */
3944 pc += gdbarch_deprecated_function_start_offset (gdbarch);
3945 if (gdbarch_skip_entrypoint_p (gdbarch))
3946 pc = gdbarch_skip_entrypoint (gdbarch, pc);
3947 if (skip)
3948 pc = gdbarch_skip_prologue_noexcept (gdbarch, pc);
3950 /* For overlays, map pc back into its mapped VMA range. */
3951 pc = overlay_mapped_address (pc, section);
3953 /* Calculate line number. */
3954 start_sal = find_pc_sect_line (pc, section, 0);
3956 /* Check if gdbarch_skip_prologue left us in mid-line, and the next
3957 line is still part of the same function. */
3958 if (skip && start_sal.pc != pc
3959 && (sym ? (sym->value_block ()->entry_pc () <= start_sal.end
3960 && start_sal.end < sym->value_block()->end ())
3961 : (lookup_minimal_symbol_by_pc_section (start_sal.end, section).minsym
3962 == lookup_minimal_symbol_by_pc_section (pc, section).minsym)))
3964 /* First pc of next line */
3965 pc = start_sal.end;
3966 /* Recalculate the line number (might not be N+1). */
3967 start_sal = find_pc_sect_line (pc, section, 0);
3970 /* On targets with executable formats that don't have a concept of
3971 constructors (ELF with .init has, PE doesn't), gcc emits a call
3972 to `__main' in `main' between the prologue and before user
3973 code. */
3974 if (gdbarch_skip_main_prologue_p (gdbarch)
3975 && name && strcmp_iw (name, "main") == 0)
3977 pc = gdbarch_skip_main_prologue (gdbarch, pc);
3978 /* Recalculate the line number (might not be N+1). */
3979 start_sal = find_pc_sect_line (pc, section, 0);
3980 force_skip = 1;
3983 while (!force_skip && skip--);
3985 /* If we still don't have a valid source line, try to find the first
3986 PC in the lineinfo table that belongs to the same function. This
3987 happens with COFF debug info, which does not seem to have an
3988 entry in lineinfo table for the code after the prologue which has
3989 no direct relation to source. For example, this was found to be
3990 the case with the DJGPP target using "gcc -gcoff" when the
3991 compiler inserted code after the prologue to make sure the stack
3992 is aligned. */
3993 if (!force_skip && sym && start_sal.symtab == NULL)
3995 pc = skip_prologue_using_lineinfo (pc, sym->symtab ());
3996 /* Recalculate the line number. */
3997 start_sal = find_pc_sect_line (pc, section, 0);
4000 /* If we're already past the prologue, leave SAL unchanged. Otherwise
4001 forward SAL to the end of the prologue. */
4002 if (sal->pc >= pc)
4003 return;
4005 sal->pc = pc;
4006 sal->section = section;
4007 sal->symtab = start_sal.symtab;
4008 sal->line = start_sal.line;
4009 sal->end = start_sal.end;
4011 /* Check if we are now inside an inlined function. If we can,
4012 use the call site of the function instead. */
4013 b = block_for_pc_sect (sal->pc, sal->section);
4014 function_block = NULL;
4015 while (b != NULL)
4017 if (b->function () != NULL && b->inlined_p ())
4018 function_block = b;
4019 else if (b->function () != NULL)
4020 break;
4021 b = b->superblock ();
4023 if (function_block != NULL
4024 && function_block->function ()->line () != 0)
4026 sal->line = function_block->function ()->line ();
4027 sal->symtab = function_block->function ()->symtab ();
4031 /* Given PC at the function's start address, attempt to find the
4032 prologue end using SAL information. Return zero if the skip fails.
4034 A non-optimized prologue traditionally has one SAL for the function
4035 and a second for the function body. A single line function has
4036 them both pointing at the same line.
4038 An optimized prologue is similar but the prologue may contain
4039 instructions (SALs) from the instruction body. Need to skip those
4040 while not getting into the function body.
4042 The functions end point and an increasing SAL line are used as
4043 indicators of the prologue's endpoint.
4045 This code is based on the function refine_prologue_limit
4046 (found in ia64). */
4048 CORE_ADDR
4049 skip_prologue_using_sal (struct gdbarch *gdbarch, CORE_ADDR func_addr)
4051 struct symtab_and_line prologue_sal;
4052 CORE_ADDR start_pc;
4053 CORE_ADDR end_pc;
4054 const struct block *bl;
4056 /* Get an initial range for the function. */
4057 find_pc_partial_function (func_addr, NULL, &start_pc, &end_pc);
4058 start_pc += gdbarch_deprecated_function_start_offset (gdbarch);
4060 prologue_sal = find_pc_line (start_pc, 0);
4061 if (prologue_sal.line != 0)
4063 /* For languages other than assembly, treat two consecutive line
4064 entries at the same address as a zero-instruction prologue.
4065 The GNU assembler emits separate line notes for each instruction
4066 in a multi-instruction macro, but compilers generally will not
4067 do this. */
4068 if (prologue_sal.symtab->language () != language_asm)
4070 struct objfile *objfile
4071 = prologue_sal.symtab->compunit ()->objfile ();
4072 const linetable *linetable = prologue_sal.symtab->linetable ();
4073 gdb_assert (linetable->nitems > 0);
4074 int idx = 0;
4076 /* Skip any earlier lines, and any end-of-sequence marker
4077 from a previous function. */
4078 while (idx + 1 < linetable->nitems
4079 && (linetable->item[idx].pc (objfile) != prologue_sal.pc
4080 || linetable->item[idx].line == 0))
4081 idx++;
4083 if (idx + 1 < linetable->nitems
4084 && linetable->item[idx+1].line != 0
4085 && linetable->item[idx+1].pc (objfile) == start_pc)
4086 return start_pc;
4089 /* If there is only one sal that covers the entire function,
4090 then it is probably a single line function, like
4091 "foo(){}". */
4092 if (prologue_sal.end >= end_pc)
4093 return 0;
4095 while (prologue_sal.end < end_pc)
4097 struct symtab_and_line sal;
4099 sal = find_pc_line (prologue_sal.end, 0);
4100 if (sal.line == 0)
4101 break;
4102 /* Assume that a consecutive SAL for the same (or larger)
4103 line mark the prologue -> body transition. */
4104 if (sal.line >= prologue_sal.line)
4105 break;
4106 /* Likewise if we are in a different symtab altogether
4107 (e.g. within a file included via #include).  */
4108 if (sal.symtab != prologue_sal.symtab)
4109 break;
4111 /* The line number is smaller. Check that it's from the
4112 same function, not something inlined. If it's inlined,
4113 then there is no point comparing the line numbers. */
4114 bl = block_for_pc (prologue_sal.end);
4115 while (bl)
4117 if (bl->inlined_p ())
4118 break;
4119 if (bl->function ())
4121 bl = NULL;
4122 break;
4124 bl = bl->superblock ();
4126 if (bl != NULL)
4127 break;
4129 /* The case in which compiler's optimizer/scheduler has
4130 moved instructions into the prologue. We look ahead in
4131 the function looking for address ranges whose
4132 corresponding line number is less the first one that we
4133 found for the function. This is more conservative then
4134 refine_prologue_limit which scans a large number of SALs
4135 looking for any in the prologue. */
4136 prologue_sal = sal;
4140 if (prologue_sal.end < end_pc)
4141 /* Return the end of this line, or zero if we could not find a
4142 line. */
4143 return prologue_sal.end;
4144 else
4145 /* Don't return END_PC, which is past the end of the function. */
4146 return prologue_sal.pc;
4149 /* See symtab.h. */
4151 std::optional<CORE_ADDR>
4152 find_epilogue_using_linetable (CORE_ADDR func_addr)
4154 CORE_ADDR start_pc, end_pc;
4156 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
4157 return {};
4159 const struct symtab_and_line sal = find_pc_line (start_pc, 0);
4160 if (sal.symtab != nullptr && sal.symtab->language () != language_asm)
4162 struct objfile *objfile = sal.symtab->compunit ()->objfile ();
4163 unrelocated_addr unrel_start
4164 = unrelocated_addr (start_pc - objfile->text_section_offset ());
4165 unrelocated_addr unrel_end
4166 = unrelocated_addr (end_pc - objfile->text_section_offset ());
4168 const linetable *linetable = sal.symtab->linetable ();
4169 /* This should find the last linetable entry of the current function.
4170 It is probably where the epilogue begins, but since the DWARF 5
4171 spec doesn't guarantee it, we iterate backwards through the function
4172 until we either find it or are sure that it doesn't exist. */
4173 auto it = std::lower_bound
4174 (linetable->item, linetable->item + linetable->nitems, unrel_end,
4175 [] (const linetable_entry &lte, unrelocated_addr pc)
4177 return lte.unrelocated_pc () < pc;
4180 while (it->unrelocated_pc () >= unrel_start)
4182 if (it->epilogue_begin)
4183 return {it->pc (objfile)};
4184 it --;
4187 return {};
4190 /* See symtab.h. */
4192 symbol *
4193 find_function_alias_target (bound_minimal_symbol msymbol)
4195 CORE_ADDR func_addr;
4196 if (!msymbol_is_function (msymbol.objfile, msymbol.minsym, &func_addr))
4197 return NULL;
4199 symbol *sym = find_pc_function (func_addr);
4200 if (sym != NULL
4201 && sym->aclass () == LOC_BLOCK
4202 && sym->value_block ()->entry_pc () == func_addr)
4203 return sym;
4205 return NULL;
4209 /* If P is of the form "operator[ \t]+..." where `...' is
4210 some legitimate operator text, return a pointer to the
4211 beginning of the substring of the operator text.
4212 Otherwise, return "". */
4214 static const char *
4215 operator_chars (const char *p, const char **end)
4217 *end = "";
4218 if (!startswith (p, CP_OPERATOR_STR))
4219 return *end;
4220 p += CP_OPERATOR_LEN;
4222 /* Don't get faked out by `operator' being part of a longer
4223 identifier. */
4224 if (isalpha (*p) || *p == '_' || *p == '$' || *p == '\0')
4225 return *end;
4227 /* Allow some whitespace between `operator' and the operator symbol. */
4228 while (*p == ' ' || *p == '\t')
4229 p++;
4231 /* Recognize 'operator TYPENAME'. */
4233 if (isalpha (*p) || *p == '_' || *p == '$')
4235 const char *q = p + 1;
4237 while (isalnum (*q) || *q == '_' || *q == '$')
4238 q++;
4239 *end = q;
4240 return p;
4243 while (*p)
4244 switch (*p)
4246 case '\\': /* regexp quoting */
4247 if (p[1] == '*')
4249 if (p[2] == '=') /* 'operator\*=' */
4250 *end = p + 3;
4251 else /* 'operator\*' */
4252 *end = p + 2;
4253 return p;
4255 else if (p[1] == '[')
4257 if (p[2] == ']')
4258 error (_("mismatched quoting on brackets, "
4259 "try 'operator\\[\\]'"));
4260 else if (p[2] == '\\' && p[3] == ']')
4262 *end = p + 4; /* 'operator\[\]' */
4263 return p;
4265 else
4266 error (_("nothing is allowed between '[' and ']'"));
4268 else
4270 /* Gratuitous quote: skip it and move on. */
4271 p++;
4272 continue;
4274 break;
4275 case '!':
4276 case '=':
4277 case '*':
4278 case '/':
4279 case '%':
4280 case '^':
4281 if (p[1] == '=')
4282 *end = p + 2;
4283 else
4284 *end = p + 1;
4285 return p;
4286 case '<':
4287 case '>':
4288 case '+':
4289 case '-':
4290 case '&':
4291 case '|':
4292 if (p[0] == '-' && p[1] == '>')
4294 /* Struct pointer member operator 'operator->'. */
4295 if (p[2] == '*')
4297 *end = p + 3; /* 'operator->*' */
4298 return p;
4300 else if (p[2] == '\\')
4302 *end = p + 4; /* Hopefully 'operator->\*' */
4303 return p;
4305 else
4307 *end = p + 2; /* 'operator->' */
4308 return p;
4311 if (p[1] == '=' || p[1] == p[0])
4312 *end = p + 2;
4313 else
4314 *end = p + 1;
4315 return p;
4316 case '~':
4317 case ',':
4318 *end = p + 1;
4319 return p;
4320 case '(':
4321 if (p[1] != ')')
4322 error (_("`operator ()' must be specified "
4323 "without whitespace in `()'"));
4324 *end = p + 2;
4325 return p;
4326 case '?':
4327 if (p[1] != ':')
4328 error (_("`operator ?:' must be specified "
4329 "without whitespace in `?:'"));
4330 *end = p + 2;
4331 return p;
4332 case '[':
4333 if (p[1] != ']')
4334 error (_("`operator []' must be specified "
4335 "without whitespace in `[]'"));
4336 *end = p + 2;
4337 return p;
4338 default:
4339 error (_("`operator %s' not supported"), p);
4340 break;
4343 *end = "";
4344 return *end;
4348 /* See class declaration. */
4350 info_sources_filter::info_sources_filter (match_on match_type,
4351 const char *regexp)
4352 : m_match_type (match_type),
4353 m_regexp (regexp)
4355 /* Setup the compiled regular expression M_C_REGEXP based on M_REGEXP. */
4356 if (m_regexp != nullptr && *m_regexp != '\0')
4358 gdb_assert (m_regexp != nullptr);
4360 int cflags = REG_NOSUB;
4361 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
4362 cflags |= REG_ICASE;
4363 #endif
4364 m_c_regexp.emplace (m_regexp, cflags, _("Invalid regexp"));
4368 /* See class declaration. */
4370 bool
4371 info_sources_filter::matches (const char *fullname) const
4373 /* Does it match regexp? */
4374 if (m_c_regexp.has_value ())
4376 const char *to_match;
4377 std::string dirname;
4379 switch (m_match_type)
4381 case match_on::DIRNAME:
4382 dirname = ldirname (fullname);
4383 to_match = dirname.c_str ();
4384 break;
4385 case match_on::BASENAME:
4386 to_match = lbasename (fullname);
4387 break;
4388 case match_on::FULLNAME:
4389 to_match = fullname;
4390 break;
4391 default:
4392 gdb_assert_not_reached ("bad m_match_type");
4395 if (m_c_regexp->exec (to_match, 0, NULL, 0) != 0)
4396 return false;
4399 return true;
4402 /* Data structure to maintain the state used for printing the results of
4403 the 'info sources' command. */
4405 struct output_source_filename_data
4407 /* Create an object for displaying the results of the 'info sources'
4408 command to UIOUT. FILTER must remain valid and unchanged for the
4409 lifetime of this object as this object retains a reference to FILTER. */
4410 output_source_filename_data (struct ui_out *uiout,
4411 const info_sources_filter &filter)
4412 : m_filter (filter),
4413 m_uiout (uiout)
4414 { /* Nothing. */ }
4416 DISABLE_COPY_AND_ASSIGN (output_source_filename_data);
4418 /* Reset enough state of this object so we can match against a new set of
4419 files. The existing regular expression is retained though. */
4420 void reset_output ()
4422 m_first = true;
4423 m_filename_seen_cache.clear ();
4426 /* Worker for sources_info, outputs the file name formatted for either
4427 cli or mi (based on the current_uiout). In cli mode displays
4428 FULLNAME with a comma separating this name from any previously
4429 printed name (line breaks are added at the comma). In MI mode
4430 outputs a tuple containing DISP_NAME (the files display name),
4431 FULLNAME, and EXPANDED_P (true when this file is from a fully
4432 expanded symtab, otherwise false). */
4433 void output (const char *disp_name, const char *fullname, bool expanded_p);
4435 /* An overload suitable for use as a callback to
4436 quick_symbol_functions::map_symbol_filenames. */
4437 void operator() (const char *filename, const char *fullname)
4439 /* The false here indicates that this file is from an unexpanded
4440 symtab. */
4441 output (filename, fullname, false);
4444 /* Return true if at least one filename has been printed (after a call to
4445 output) since either this object was created, or the last call to
4446 reset_output. */
4447 bool printed_filename_p () const
4449 return !m_first;
4452 private:
4454 /* Flag of whether we're printing the first one. */
4455 bool m_first = true;
4457 /* Cache of what we've seen so far. */
4458 filename_seen_cache m_filename_seen_cache;
4460 /* How source filename should be filtered. */
4461 const info_sources_filter &m_filter;
4463 /* The object to which output is sent. */
4464 struct ui_out *m_uiout;
4467 /* See comment in class declaration above. */
4469 void
4470 output_source_filename_data::output (const char *disp_name,
4471 const char *fullname,
4472 bool expanded_p)
4474 /* Since a single source file can result in several partial symbol
4475 tables, we need to avoid printing it more than once. Note: if
4476 some of the psymtabs are read in and some are not, it gets
4477 printed both under "Source files for which symbols have been
4478 read" and "Source files for which symbols will be read in on
4479 demand". I consider this a reasonable way to deal with the
4480 situation. I'm not sure whether this can also happen for
4481 symtabs; it doesn't hurt to check. */
4483 /* Was NAME already seen? If so, then don't print it again. */
4484 if (m_filename_seen_cache.seen (fullname))
4485 return;
4487 /* If the filter rejects this file then don't print it. */
4488 if (!m_filter.matches (fullname))
4489 return;
4491 ui_out_emit_tuple ui_emitter (m_uiout, nullptr);
4493 /* Print it and reset *FIRST. */
4494 if (!m_first)
4495 m_uiout->text (", ");
4496 m_first = false;
4498 m_uiout->wrap_hint (0);
4499 if (m_uiout->is_mi_like_p ())
4501 m_uiout->field_string ("file", disp_name, file_name_style.style ());
4502 if (fullname != nullptr)
4503 m_uiout->field_string ("fullname", fullname,
4504 file_name_style.style ());
4505 m_uiout->field_string ("debug-fully-read",
4506 (expanded_p ? "true" : "false"));
4508 else
4510 if (fullname == nullptr)
4511 fullname = disp_name;
4512 m_uiout->field_string ("fullname", fullname,
4513 file_name_style.style ());
4517 /* For the 'info sources' command, what part of the file names should we be
4518 matching the user supplied regular expression against? */
4520 struct filename_partial_match_opts
4522 /* Only match the directory name part. */
4523 bool dirname = false;
4525 /* Only match the basename part. */
4526 bool basename = false;
4529 using isrc_flag_option_def
4530 = gdb::option::flag_option_def<filename_partial_match_opts>;
4532 static const gdb::option::option_def info_sources_option_defs[] = {
4534 isrc_flag_option_def {
4535 "dirname",
4536 [] (filename_partial_match_opts *opts) { return &opts->dirname; },
4537 N_("Show only the files having a dirname matching REGEXP."),
4540 isrc_flag_option_def {
4541 "basename",
4542 [] (filename_partial_match_opts *opts) { return &opts->basename; },
4543 N_("Show only the files having a basename matching REGEXP."),
4548 /* Create an option_def_group for the "info sources" options, with
4549 ISRC_OPTS as context. */
4551 static inline gdb::option::option_def_group
4552 make_info_sources_options_def_group (filename_partial_match_opts *isrc_opts)
4554 return {{info_sources_option_defs}, isrc_opts};
4557 /* Completer for "info sources". */
4559 static void
4560 info_sources_command_completer (cmd_list_element *ignore,
4561 completion_tracker &tracker,
4562 const char *text, const char *word)
4564 const auto group = make_info_sources_options_def_group (nullptr);
4565 if (gdb::option::complete_options
4566 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
4567 return;
4570 /* See symtab.h. */
4572 void
4573 info_sources_worker (struct ui_out *uiout,
4574 bool group_by_objfile,
4575 const info_sources_filter &filter)
4577 output_source_filename_data data (uiout, filter);
4579 ui_out_emit_list results_emitter (uiout, "files");
4580 std::optional<ui_out_emit_tuple> output_tuple;
4581 std::optional<ui_out_emit_list> sources_list;
4583 gdb_assert (group_by_objfile || uiout->is_mi_like_p ());
4585 for (objfile *objfile : current_program_space->objfiles ())
4587 if (group_by_objfile)
4589 output_tuple.emplace (uiout, nullptr);
4590 uiout->field_string ("filename", objfile_name (objfile),
4591 file_name_style.style ());
4592 uiout->text (":\n");
4593 bool debug_fully_readin = !objfile->has_unexpanded_symtabs ();
4594 if (uiout->is_mi_like_p ())
4596 const char *debug_info_state;
4597 if (objfile_has_symbols (objfile))
4599 if (debug_fully_readin)
4600 debug_info_state = "fully-read";
4601 else
4602 debug_info_state = "partially-read";
4604 else
4605 debug_info_state = "none";
4606 current_uiout->field_string ("debug-info", debug_info_state);
4608 else
4610 if (!debug_fully_readin)
4611 uiout->text ("(Full debug information has not yet been read "
4612 "for this file.)\n");
4613 if (!objfile_has_symbols (objfile))
4614 uiout->text ("(Objfile has no debug information.)\n");
4615 uiout->text ("\n");
4617 sources_list.emplace (uiout, "sources");
4620 for (compunit_symtab *cu : objfile->compunits ())
4622 for (symtab *s : cu->filetabs ())
4624 const char *file = symtab_to_filename_for_display (s);
4625 const char *fullname = symtab_to_fullname (s);
4626 data.output (file, fullname, true);
4630 if (group_by_objfile)
4632 objfile->map_symbol_filenames (data, true /* need_fullname */);
4633 if (data.printed_filename_p ())
4634 uiout->text ("\n\n");
4635 data.reset_output ();
4636 sources_list.reset ();
4637 output_tuple.reset ();
4641 if (!group_by_objfile)
4643 data.reset_output ();
4644 map_symbol_filenames (data, true /*need_fullname*/);
4648 /* Implement the 'info sources' command. */
4650 static void
4651 info_sources_command (const char *args, int from_tty)
4653 if (!have_full_symbols () && !have_partial_symbols ())
4654 error (_("No symbol table is loaded. Use the \"file\" command."));
4656 filename_partial_match_opts match_opts;
4657 auto group = make_info_sources_options_def_group (&match_opts);
4658 gdb::option::process_options
4659 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
4661 if (match_opts.dirname && match_opts.basename)
4662 error (_("You cannot give both -basename and -dirname to 'info sources'."));
4664 const char *regex = nullptr;
4665 if (args != NULL && *args != '\000')
4666 regex = args;
4668 if ((match_opts.dirname || match_opts.basename) && regex == nullptr)
4669 error (_("Missing REGEXP for 'info sources'."));
4671 info_sources_filter::match_on match_type;
4672 if (match_opts.dirname)
4673 match_type = info_sources_filter::match_on::DIRNAME;
4674 else if (match_opts.basename)
4675 match_type = info_sources_filter::match_on::BASENAME;
4676 else
4677 match_type = info_sources_filter::match_on::FULLNAME;
4679 info_sources_filter filter (match_type, regex);
4680 info_sources_worker (current_uiout, true, filter);
4683 /* Compare FILE against all the entries of FILENAMES. If BASENAMES is
4684 true compare only lbasename of FILENAMES. */
4686 static bool
4687 file_matches (const char *file, const std::vector<const char *> &filenames,
4688 bool basenames)
4690 if (filenames.empty ())
4691 return true;
4693 for (const char *name : filenames)
4695 name = (basenames ? lbasename (name) : name);
4696 if (compare_filenames_for_search (file, name))
4697 return true;
4700 return false;
4703 /* Helper function for std::sort on symbol_search objects. Can only sort
4704 symbols, not minimal symbols. */
4707 symbol_search::compare_search_syms (const symbol_search &sym_a,
4708 const symbol_search &sym_b)
4710 int c;
4712 c = FILENAME_CMP (sym_a.symbol->symtab ()->filename,
4713 sym_b.symbol->symtab ()->filename);
4714 if (c != 0)
4715 return c;
4717 if (sym_a.block != sym_b.block)
4718 return sym_a.block - sym_b.block;
4720 return strcmp (sym_a.symbol->print_name (), sym_b.symbol->print_name ());
4723 /* Returns true if the type_name of symbol_type of SYM matches TREG.
4724 If SYM has no symbol_type or symbol_name, returns false. */
4726 bool
4727 treg_matches_sym_type_name (const compiled_regex &treg,
4728 const struct symbol *sym)
4730 struct type *sym_type;
4731 std::string printed_sym_type_name;
4733 symbol_lookup_debug_printf_v ("treg_matches_sym_type_name, sym %s",
4734 sym->natural_name ());
4736 sym_type = sym->type ();
4737 if (sym_type == NULL)
4738 return false;
4741 scoped_switch_to_sym_language_if_auto l (sym);
4743 printed_sym_type_name = type_to_string (sym_type);
4746 symbol_lookup_debug_printf_v ("sym_type_name %s",
4747 printed_sym_type_name.c_str ());
4749 if (printed_sym_type_name.empty ())
4750 return false;
4752 return treg.exec (printed_sym_type_name.c_str (), 0, NULL, 0) == 0;
4755 /* See symtab.h. */
4757 bool
4758 global_symbol_searcher::is_suitable_msymbol
4759 (const domain_search_flags kind, const minimal_symbol *msymbol)
4761 switch (msymbol->type ())
4763 case mst_data:
4764 case mst_bss:
4765 case mst_file_data:
4766 case mst_file_bss:
4767 return (kind & SEARCH_VAR_DOMAIN) != 0;
4768 case mst_text:
4769 case mst_file_text:
4770 case mst_solib_trampoline:
4771 case mst_text_gnu_ifunc:
4772 return (kind & SEARCH_FUNCTION_DOMAIN) != 0;
4773 default:
4774 return false;
4778 /* See symtab.h. */
4780 bool
4781 global_symbol_searcher::expand_symtabs
4782 (objfile *objfile, const std::optional<compiled_regex> &preg) const
4784 domain_search_flags kind = m_kind;
4785 bool found_msymbol = false;
4787 auto do_file_match = [&] (const char *filename, bool basenames)
4789 return file_matches (filename, filenames, basenames);
4791 gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher = nullptr;
4792 if (!filenames.empty ())
4793 file_matcher = do_file_match;
4795 objfile->expand_symtabs_matching
4796 (file_matcher,
4797 &lookup_name_info::match_any (),
4798 [&] (const char *symname)
4800 return (!preg.has_value ()
4801 || preg->exec (symname, 0, NULL, 0) == 0);
4803 NULL,
4804 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
4805 kind);
4807 /* Here, we search through the minimal symbol tables for functions and
4808 variables that match, and force their symbols to be read. This is in
4809 particular necessary for demangled variable names, which are no longer
4810 put into the partial symbol tables. The symbol will then be found
4811 during the scan of symtabs later.
4813 For functions, find_pc_symtab should succeed if we have debug info for
4814 the function, for variables we have to call
4815 lookup_symbol_in_objfile_from_linkage_name to determine if the
4816 variable has debug info. If the lookup fails, set found_msymbol so
4817 that we will rescan to print any matching symbols without debug info.
4818 We only search the objfile the msymbol came from, we no longer search
4819 all objfiles. In large programs (1000s of shared libs) searching all
4820 objfiles is not worth the pain. */
4821 if (filenames.empty ()
4822 && (kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN)) != 0)
4824 for (minimal_symbol *msymbol : objfile->msymbols ())
4826 QUIT;
4828 if (msymbol->created_by_gdb)
4829 continue;
4831 if (is_suitable_msymbol (kind, msymbol))
4833 if (!preg.has_value ()
4834 || preg->exec (msymbol->natural_name (), 0,
4835 NULL, 0) == 0)
4837 /* An important side-effect of these lookup functions is
4838 to expand the symbol table if msymbol is found, later
4839 in the process we will add matching symbols or
4840 msymbols to the results list, and that requires that
4841 the symbols tables are expanded. */
4842 if ((kind & SEARCH_FUNCTION_DOMAIN) != 0
4843 ? (find_pc_compunit_symtab
4844 (msymbol->value_address (objfile)) == NULL)
4845 : (lookup_symbol_in_objfile_from_linkage_name
4846 (objfile, msymbol->linkage_name (),
4847 SEARCH_VFT)
4848 .symbol == NULL))
4849 found_msymbol = true;
4855 return found_msymbol;
4858 /* See symtab.h. */
4860 bool
4861 global_symbol_searcher::add_matching_symbols
4862 (objfile *objfile,
4863 const std::optional<compiled_regex> &preg,
4864 const std::optional<compiled_regex> &treg,
4865 std::set<symbol_search> *result_set) const
4867 domain_search_flags kind = m_kind;
4869 /* Add matching symbols (if not already present). */
4870 for (compunit_symtab *cust : objfile->compunits ())
4872 const struct blockvector *bv = cust->blockvector ();
4874 for (block_enum block : { GLOBAL_BLOCK, STATIC_BLOCK })
4876 const struct block *b = bv->block (block);
4878 for (struct symbol *sym : block_iterator_range (b))
4880 struct symtab *real_symtab = sym->symtab ();
4882 QUIT;
4884 /* Check first sole REAL_SYMTAB->FILENAME. It does
4885 not need to be a substring of symtab_to_fullname as
4886 it may contain "./" etc. */
4887 if (!(file_matches (real_symtab->filename, filenames, false)
4888 || ((basenames_may_differ
4889 || file_matches (lbasename (real_symtab->filename),
4890 filenames, true))
4891 && file_matches (symtab_to_fullname (real_symtab),
4892 filenames, false))))
4893 continue;
4895 if (!sym->matches (kind))
4896 continue;
4898 if (preg.has_value () && preg->exec (sym->natural_name (), 0,
4899 nullptr, 0) != 0)
4900 continue;
4902 if (((sym->domain () == VAR_DOMAIN
4903 || sym->domain () == FUNCTION_DOMAIN)
4904 && treg.has_value ()
4905 && !treg_matches_sym_type_name (*treg, sym)))
4906 continue;
4908 if ((kind & SEARCH_VAR_DOMAIN) != 0)
4910 if (sym->aclass () == LOC_UNRESOLVED
4911 /* LOC_CONST can be used for more than
4912 just enums, e.g., c++ static const
4913 members. We only want to skip enums
4914 here. */
4915 || (sym->aclass () == LOC_CONST
4916 && (sym->type ()->code () == TYPE_CODE_ENUM)))
4917 continue;
4919 if (sym->domain () == MODULE_DOMAIN && sym->line () == 0)
4920 continue;
4922 if (result_set->size () < m_max_search_results)
4924 /* Match, insert if not already in the results. */
4925 symbol_search ss (block, sym);
4926 if (result_set->find (ss) == result_set->end ())
4927 result_set->insert (ss);
4929 else
4930 return false;
4935 return true;
4938 /* See symtab.h. */
4940 bool
4941 global_symbol_searcher::add_matching_msymbols
4942 (objfile *objfile, const std::optional<compiled_regex> &preg,
4943 std::vector<symbol_search> *results) const
4945 domain_search_flags kind = m_kind;
4947 for (minimal_symbol *msymbol : objfile->msymbols ())
4949 QUIT;
4951 if (msymbol->created_by_gdb)
4952 continue;
4954 if (is_suitable_msymbol (kind, msymbol))
4956 if (!preg.has_value ()
4957 || preg->exec (msymbol->natural_name (), 0,
4958 NULL, 0) == 0)
4960 /* For functions we can do a quick check of whether the
4961 symbol might be found via find_pc_symtab. */
4962 if ((kind & SEARCH_FUNCTION_DOMAIN) == 0
4963 || (find_pc_compunit_symtab
4964 (msymbol->value_address (objfile)) == NULL))
4966 if (lookup_symbol_in_objfile_from_linkage_name
4967 (objfile, msymbol->linkage_name (),
4968 SEARCH_VFT).symbol == NULL)
4970 /* Matching msymbol, add it to the results list. */
4971 if (results->size () < m_max_search_results)
4972 results->emplace_back (GLOBAL_BLOCK, msymbol, objfile);
4973 else
4974 return false;
4981 return true;
4984 /* See symtab.h. */
4986 std::vector<symbol_search>
4987 global_symbol_searcher::search () const
4989 std::optional<compiled_regex> preg;
4990 std::optional<compiled_regex> treg;
4992 if (m_symbol_name_regexp != NULL)
4994 const char *symbol_name_regexp = m_symbol_name_regexp;
4995 std::string symbol_name_regexp_holder;
4997 /* Make sure spacing is right for C++ operators.
4998 This is just a courtesy to make the matching less sensitive
4999 to how many spaces the user leaves between 'operator'
5000 and <TYPENAME> or <OPERATOR>. */
5001 const char *opend;
5002 const char *opname = operator_chars (symbol_name_regexp, &opend);
5004 if (*opname)
5006 int fix = -1; /* -1 means ok; otherwise number of
5007 spaces needed. */
5009 if (isalpha (*opname) || *opname == '_' || *opname == '$')
5011 /* There should 1 space between 'operator' and 'TYPENAME'. */
5012 if (opname[-1] != ' ' || opname[-2] == ' ')
5013 fix = 1;
5015 else
5017 /* There should 0 spaces between 'operator' and 'OPERATOR'. */
5018 if (opname[-1] == ' ')
5019 fix = 0;
5021 /* If wrong number of spaces, fix it. */
5022 if (fix >= 0)
5024 symbol_name_regexp_holder
5025 = string_printf ("operator%.*s%s", fix, " ", opname);
5026 symbol_name_regexp = symbol_name_regexp_holder.c_str ();
5030 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5031 ? REG_ICASE : 0);
5032 preg.emplace (symbol_name_regexp, cflags,
5033 _("Invalid regexp"));
5036 if (m_symbol_type_regexp != NULL)
5038 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5039 ? REG_ICASE : 0);
5040 treg.emplace (m_symbol_type_regexp, cflags,
5041 _("Invalid regexp"));
5044 bool found_msymbol = false;
5045 std::set<symbol_search> result_set;
5046 for (objfile *objfile : current_program_space->objfiles ())
5048 /* Expand symtabs within objfile that possibly contain matching
5049 symbols. */
5050 found_msymbol |= expand_symtabs (objfile, preg);
5052 /* Find matching symbols within OBJFILE and add them in to the
5053 RESULT_SET set. Use a set here so that we can easily detect
5054 duplicates as we go, and can therefore track how many unique
5055 matches we have found so far. */
5056 if (!add_matching_symbols (objfile, preg, treg, &result_set))
5057 break;
5060 /* Convert the result set into a sorted result list, as std::set is
5061 defined to be sorted then no explicit call to std::sort is needed. */
5062 std::vector<symbol_search> result (result_set.begin (), result_set.end ());
5064 /* If there are no debug symbols, then add matching minsyms. But if the
5065 user wants to see symbols matching a type regexp, then never give a
5066 minimal symbol, as we assume that a minimal symbol does not have a
5067 type. */
5068 if ((found_msymbol
5069 || (filenames.empty () && (m_kind & SEARCH_VAR_DOMAIN) != 0))
5070 && !m_exclude_minsyms
5071 && !treg.has_value ())
5073 gdb_assert ((m_kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN))
5074 != 0);
5075 for (objfile *objfile : current_program_space->objfiles ())
5076 if (!add_matching_msymbols (objfile, preg, &result))
5077 break;
5080 return result;
5083 /* See symtab.h. */
5085 std::string
5086 symbol_to_info_string (struct symbol *sym, int block)
5088 std::string str;
5090 gdb_assert (block == GLOBAL_BLOCK || block == STATIC_BLOCK);
5092 if (block == STATIC_BLOCK
5093 && (sym->domain () == VAR_DOMAIN
5094 || sym->domain () == FUNCTION_DOMAIN))
5095 str += "static ";
5097 /* Typedef that is not a C++ class. */
5098 if (sym->domain () == TYPE_DOMAIN)
5100 string_file tmp_stream;
5102 /* FIXME: For C (and C++) we end up with a difference in output here
5103 between how a typedef is printed, and non-typedefs are printed.
5104 The TYPEDEF_PRINT code places a ";" at the end in an attempt to
5105 appear C-like, while TYPE_PRINT doesn't.
5107 For the struct printing case below, things are worse, we force
5108 printing of the ";" in this function, which is going to be wrong
5109 for languages that don't require a ";" between statements. */
5110 if (sym->type ()->code () == TYPE_CODE_TYPEDEF)
5111 typedef_print (sym->type (), sym, &tmp_stream);
5112 else
5113 type_print (sym->type (), "", &tmp_stream, -1);
5114 str += tmp_stream.string ();
5116 /* variable, func, or typedef-that-is-c++-class. */
5117 else if (sym->domain () == VAR_DOMAIN || sym->domain () == STRUCT_DOMAIN
5118 || sym->domain () == FUNCTION_DOMAIN)
5120 string_file tmp_stream;
5122 type_print (sym->type (),
5123 (sym->aclass () == LOC_TYPEDEF
5124 ? "" : sym->print_name ()),
5125 &tmp_stream, 0);
5127 str += tmp_stream.string ();
5128 str += ";";
5130 /* Printing of modules is currently done here, maybe at some future
5131 point we might want a language specific method to print the module
5132 symbol so that we can customise the output more. */
5133 else if (sym->domain () == MODULE_DOMAIN)
5134 str += sym->print_name ();
5136 return str;
5139 /* Helper function for symbol info commands, for example 'info
5140 functions', 'info variables', etc. BLOCK is the type of block the
5141 symbols was found in, either GLOBAL_BLOCK or STATIC_BLOCK. SYM is
5142 the symbol we found. If LAST is not NULL, print file and line
5143 number information for the symbol as well. Skip printing the
5144 filename if it matches LAST. */
5146 static void
5147 print_symbol_info (struct symbol *sym, int block, const char *last)
5149 scoped_switch_to_sym_language_if_auto l (sym);
5150 struct symtab *s = sym->symtab ();
5152 if (last != NULL)
5154 const char *s_filename = symtab_to_filename_for_display (s);
5156 if (filename_cmp (last, s_filename) != 0)
5158 gdb_printf (_("\nFile %ps:\n"),
5159 styled_string (file_name_style.style (),
5160 s_filename));
5163 if (sym->line () != 0)
5164 gdb_printf ("%d:\t", sym->line ());
5165 else
5166 gdb_puts ("\t");
5169 std::string str = symbol_to_info_string (sym, block);
5170 gdb_printf ("%s\n", str.c_str ());
5173 /* This help function for symtab_symbol_info() prints information
5174 for non-debugging symbols to gdb_stdout. */
5176 static void
5177 print_msymbol_info (struct bound_minimal_symbol msymbol)
5179 struct gdbarch *gdbarch = msymbol.objfile->arch ();
5180 const char *tmp;
5182 if (gdbarch_addr_bit (gdbarch) <= 32)
5183 tmp = hex_string_custom (msymbol.value_address ()
5184 & (CORE_ADDR) 0xffffffff,
5186 else
5187 tmp = hex_string_custom (msymbol.value_address (),
5188 16);
5190 ui_file_style sym_style = (msymbol.minsym->text_p ()
5191 ? function_name_style.style ()
5192 : ui_file_style ());
5194 gdb_printf (_("%ps %ps\n"),
5195 styled_string (address_style.style (), tmp),
5196 styled_string (sym_style, msymbol.minsym->print_name ()));
5199 /* This is the guts of the commands "info functions", "info types", and
5200 "info variables". It calls search_symbols to find all matches and then
5201 print_[m]symbol_info to print out some useful information about the
5202 matches. */
5204 static void
5205 symtab_symbol_info (bool quiet, bool exclude_minsyms,
5206 const char *regexp, domain_enum kind,
5207 const char *t_regexp, int from_tty)
5209 const char *last_filename = "";
5210 int first = 1;
5212 if (regexp != nullptr && *regexp == '\0')
5213 regexp = nullptr;
5215 domain_search_flags flags = to_search_flags (kind);
5216 if (kind == TYPE_DOMAIN)
5217 flags |= SEARCH_STRUCT_DOMAIN;
5219 global_symbol_searcher spec (flags, regexp);
5220 spec.set_symbol_type_regexp (t_regexp);
5221 spec.set_exclude_minsyms (exclude_minsyms);
5222 std::vector<symbol_search> symbols = spec.search ();
5224 if (!quiet)
5226 const char *classname;
5227 switch (kind)
5229 case VAR_DOMAIN:
5230 classname = "variable";
5231 break;
5232 case FUNCTION_DOMAIN:
5233 classname = "function";
5234 break;
5235 case TYPE_DOMAIN:
5236 classname = "type";
5237 break;
5238 case MODULE_DOMAIN:
5239 classname = "module";
5240 break;
5241 default:
5242 gdb_assert_not_reached ("invalid domain enum");
5245 if (regexp != NULL)
5247 if (t_regexp != NULL)
5248 gdb_printf
5249 (_("All %ss matching regular expression \"%s\""
5250 " with type matching regular expression \"%s\":\n"),
5251 classname, regexp, t_regexp);
5252 else
5253 gdb_printf (_("All %ss matching regular expression \"%s\":\n"),
5254 classname, regexp);
5256 else
5258 if (t_regexp != NULL)
5259 gdb_printf
5260 (_("All defined %ss"
5261 " with type matching regular expression \"%s\" :\n"),
5262 classname, t_regexp);
5263 else
5264 gdb_printf (_("All defined %ss:\n"), classname);
5268 for (const symbol_search &p : symbols)
5270 QUIT;
5272 if (p.msymbol.minsym != NULL)
5274 if (first)
5276 if (!quiet)
5277 gdb_printf (_("\nNon-debugging symbols:\n"));
5278 first = 0;
5280 print_msymbol_info (p.msymbol);
5282 else
5284 print_symbol_info (p.symbol, p.block, last_filename);
5285 last_filename
5286 = symtab_to_filename_for_display (p.symbol->symtab ());
5291 /* Structure to hold the values of the options used by the 'info variables'
5292 and 'info functions' commands. These correspond to the -q, -t, and -n
5293 options. */
5295 struct info_vars_funcs_options
5297 bool quiet = false;
5298 bool exclude_minsyms = false;
5299 std::string type_regexp;
5302 /* The options used by the 'info variables' and 'info functions'
5303 commands. */
5305 static const gdb::option::option_def info_vars_funcs_options_defs[] = {
5306 gdb::option::boolean_option_def<info_vars_funcs_options> {
5307 "q",
5308 [] (info_vars_funcs_options *opt) { return &opt->quiet; },
5309 nullptr, /* show_cmd_cb */
5310 nullptr /* set_doc */
5313 gdb::option::boolean_option_def<info_vars_funcs_options> {
5314 "n",
5315 [] (info_vars_funcs_options *opt) { return &opt->exclude_minsyms; },
5316 nullptr, /* show_cmd_cb */
5317 nullptr /* set_doc */
5320 gdb::option::string_option_def<info_vars_funcs_options> {
5321 "t",
5322 [] (info_vars_funcs_options *opt) { return &opt->type_regexp; },
5323 nullptr, /* show_cmd_cb */
5324 nullptr /* set_doc */
5328 /* Returns the option group used by 'info variables' and 'info
5329 functions'. */
5331 static gdb::option::option_def_group
5332 make_info_vars_funcs_options_def_group (info_vars_funcs_options *opts)
5334 return {{info_vars_funcs_options_defs}, opts};
5337 /* Command completer for 'info variables' and 'info functions'. */
5339 static void
5340 info_vars_funcs_command_completer (struct cmd_list_element *ignore,
5341 completion_tracker &tracker,
5342 const char *text, const char * /* word */)
5344 const auto group
5345 = make_info_vars_funcs_options_def_group (nullptr);
5346 if (gdb::option::complete_options
5347 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5348 return;
5350 const char *word = advance_to_expression_complete_word_point (tracker, text);
5351 symbol_completer (ignore, tracker, text, word);
5354 /* Implement the 'info variables' command. */
5356 static void
5357 info_variables_command (const char *args, int from_tty)
5359 info_vars_funcs_options opts;
5360 auto grp = make_info_vars_funcs_options_def_group (&opts);
5361 gdb::option::process_options
5362 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5363 if (args != nullptr && *args == '\0')
5364 args = nullptr;
5366 symtab_symbol_info
5367 (opts.quiet, opts.exclude_minsyms, args, VAR_DOMAIN,
5368 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5369 from_tty);
5372 /* Implement the 'info functions' command. */
5374 static void
5375 info_functions_command (const char *args, int from_tty)
5377 info_vars_funcs_options opts;
5379 auto grp = make_info_vars_funcs_options_def_group (&opts);
5380 gdb::option::process_options
5381 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5382 if (args != nullptr && *args == '\0')
5383 args = nullptr;
5385 symtab_symbol_info
5386 (opts.quiet, opts.exclude_minsyms, args, FUNCTION_DOMAIN,
5387 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5388 from_tty);
5391 /* Holds the -q option for the 'info types' command. */
5393 struct info_types_options
5395 bool quiet = false;
5398 /* The options used by the 'info types' command. */
5400 static const gdb::option::option_def info_types_options_defs[] = {
5401 gdb::option::boolean_option_def<info_types_options> {
5402 "q",
5403 [] (info_types_options *opt) { return &opt->quiet; },
5404 nullptr, /* show_cmd_cb */
5405 nullptr /* set_doc */
5409 /* Returns the option group used by 'info types'. */
5411 static gdb::option::option_def_group
5412 make_info_types_options_def_group (info_types_options *opts)
5414 return {{info_types_options_defs}, opts};
5417 /* Implement the 'info types' command. */
5419 static void
5420 info_types_command (const char *args, int from_tty)
5422 info_types_options opts;
5424 auto grp = make_info_types_options_def_group (&opts);
5425 gdb::option::process_options
5426 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5427 if (args != nullptr && *args == '\0')
5428 args = nullptr;
5429 symtab_symbol_info (opts.quiet, false, args, TYPE_DOMAIN, nullptr,
5430 from_tty);
5433 /* Command completer for 'info types' command. */
5435 static void
5436 info_types_command_completer (struct cmd_list_element *ignore,
5437 completion_tracker &tracker,
5438 const char *text, const char * /* word */)
5440 const auto group
5441 = make_info_types_options_def_group (nullptr);
5442 if (gdb::option::complete_options
5443 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5444 return;
5446 const char *word = advance_to_expression_complete_word_point (tracker, text);
5447 symbol_completer (ignore, tracker, text, word);
5450 /* Implement the 'info modules' command. */
5452 static void
5453 info_modules_command (const char *args, int from_tty)
5455 info_types_options opts;
5457 auto grp = make_info_types_options_def_group (&opts);
5458 gdb::option::process_options
5459 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5460 if (args != nullptr && *args == '\0')
5461 args = nullptr;
5462 symtab_symbol_info (opts.quiet, true, args, MODULE_DOMAIN, nullptr,
5463 from_tty);
5466 /* Implement the 'info main' command. */
5468 static void
5469 info_main_command (const char *args, int from_tty)
5471 gdb_printf ("%s\n", main_name ());
5474 static void
5475 rbreak_command (const char *regexp, int from_tty)
5477 std::string string;
5478 const char *file_name = nullptr;
5480 if (regexp != nullptr)
5482 const char *colon = strchr (regexp, ':');
5484 /* Ignore the colon if it is part of a Windows drive. */
5485 if (HAS_DRIVE_SPEC (regexp)
5486 && (regexp[2] == '/' || regexp[2] == '\\'))
5487 colon = strchr (STRIP_DRIVE_SPEC (regexp), ':');
5489 if (colon && *(colon + 1) != ':')
5491 int colon_index;
5492 char *local_name;
5494 colon_index = colon - regexp;
5495 local_name = (char *) alloca (colon_index + 1);
5496 memcpy (local_name, regexp, colon_index);
5497 local_name[colon_index--] = 0;
5498 while (isspace (local_name[colon_index]))
5499 local_name[colon_index--] = 0;
5500 file_name = local_name;
5501 regexp = skip_spaces (colon + 1);
5505 global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regexp);
5506 if (file_name != nullptr)
5507 spec.filenames.push_back (file_name);
5508 std::vector<symbol_search> symbols = spec.search ();
5510 scoped_rbreak_breakpoints finalize;
5511 for (const symbol_search &p : symbols)
5513 if (p.msymbol.minsym == NULL)
5515 struct symtab *symtab = p.symbol->symtab ();
5516 const char *fullname = symtab_to_fullname (symtab);
5518 string = string_printf ("%s:'%s'", fullname,
5519 p.symbol->linkage_name ());
5520 break_command (&string[0], from_tty);
5521 print_symbol_info (p.symbol, p.block, nullptr);
5523 else
5525 string = string_printf ("'%s'",
5526 p.msymbol.minsym->linkage_name ());
5528 break_command (&string[0], from_tty);
5529 gdb_printf ("<function, no debug info> %s;\n",
5530 p.msymbol.minsym->print_name ());
5536 /* Evaluate if SYMNAME matches LOOKUP_NAME. */
5538 static int
5539 compare_symbol_name (const char *symbol_name, language symbol_language,
5540 const lookup_name_info &lookup_name,
5541 completion_match_result &match_res)
5543 const language_defn *lang = language_def (symbol_language);
5545 symbol_name_matcher_ftype *name_match
5546 = lang->get_symbol_name_matcher (lookup_name);
5548 return name_match (symbol_name, lookup_name, &match_res);
5551 /* See symtab.h. */
5553 bool
5554 completion_list_add_name (completion_tracker &tracker,
5555 language symbol_language,
5556 const char *symname,
5557 const lookup_name_info &lookup_name,
5558 const char *text, const char *word)
5560 completion_match_result &match_res
5561 = tracker.reset_completion_match_result ();
5563 /* Clip symbols that cannot match. */
5564 if (!compare_symbol_name (symname, symbol_language, lookup_name, match_res))
5565 return false;
5567 /* Refresh SYMNAME from the match string. It's potentially
5568 different depending on language. (E.g., on Ada, the match may be
5569 the encoded symbol name wrapped in "<>"). */
5570 symname = match_res.match.match ();
5571 gdb_assert (symname != NULL);
5573 /* We have a match for a completion, so add SYMNAME to the current list
5574 of matches. Note that the name is moved to freshly malloc'd space. */
5577 gdb::unique_xmalloc_ptr<char> completion
5578 = make_completion_match_str (symname, text, word);
5580 /* Here we pass the match-for-lcd object to add_completion. Some
5581 languages match the user text against substrings of symbol
5582 names in some cases. E.g., in C++, "b push_ba" completes to
5583 "std::vector::push_back", "std::string::push_back", etc., and
5584 in this case we want the completion lowest common denominator
5585 to be "push_back" instead of "std::". */
5586 tracker.add_completion (std::move (completion),
5587 &match_res.match_for_lcd, text, word);
5590 return true;
5593 /* completion_list_add_name wrapper for struct symbol. */
5595 static void
5596 completion_list_add_symbol (completion_tracker &tracker,
5597 symbol *sym,
5598 const lookup_name_info &lookup_name,
5599 const char *text, const char *word)
5601 if (!completion_list_add_name (tracker, sym->language (),
5602 sym->natural_name (),
5603 lookup_name, text, word))
5604 return;
5606 /* C++ function symbols include the parameters within both the msymbol
5607 name and the symbol name. The problem is that the msymbol name will
5608 describe the parameters in the most basic way, with typedefs stripped
5609 out, while the symbol name will represent the types as they appear in
5610 the program. This means we will see duplicate entries in the
5611 completion tracker. The following converts the symbol name back to
5612 the msymbol name and removes the msymbol name from the completion
5613 tracker. */
5614 if (sym->language () == language_cplus
5615 && sym->aclass () == LOC_BLOCK)
5617 /* The call to canonicalize returns the empty string if the input
5618 string is already in canonical form, thanks to this we don't
5619 remove the symbol we just added above. */
5620 gdb::unique_xmalloc_ptr<char> str
5621 = cp_canonicalize_string_no_typedefs (sym->natural_name ());
5622 if (str != nullptr)
5623 tracker.remove_completion (str.get ());
5627 /* completion_list_add_name wrapper for struct minimal_symbol. */
5629 static void
5630 completion_list_add_msymbol (completion_tracker &tracker,
5631 minimal_symbol *sym,
5632 const lookup_name_info &lookup_name,
5633 const char *text, const char *word)
5635 completion_list_add_name (tracker, sym->language (),
5636 sym->natural_name (),
5637 lookup_name, text, word);
5641 /* ObjC: In case we are completing on a selector, look as the msymbol
5642 again and feed all the selectors into the mill. */
5644 static void
5645 completion_list_objc_symbol (completion_tracker &tracker,
5646 struct minimal_symbol *msymbol,
5647 const lookup_name_info &lookup_name,
5648 const char *text, const char *word)
5650 static char *tmp = NULL;
5651 static unsigned int tmplen = 0;
5653 const char *method, *category, *selector;
5654 char *tmp2 = NULL;
5656 method = msymbol->natural_name ();
5658 /* Is it a method? */
5659 if ((method[0] != '-') && (method[0] != '+'))
5660 return;
5662 if (text[0] == '[')
5663 /* Complete on shortened method method. */
5664 completion_list_add_name (tracker, language_objc,
5665 method + 1,
5666 lookup_name,
5667 text, word);
5669 while ((strlen (method) + 1) >= tmplen)
5671 if (tmplen == 0)
5672 tmplen = 1024;
5673 else
5674 tmplen *= 2;
5675 tmp = (char *) xrealloc (tmp, tmplen);
5677 selector = strchr (method, ' ');
5678 if (selector != NULL)
5679 selector++;
5681 category = strchr (method, '(');
5683 if ((category != NULL) && (selector != NULL))
5685 memcpy (tmp, method, (category - method));
5686 tmp[category - method] = ' ';
5687 memcpy (tmp + (category - method) + 1, selector, strlen (selector) + 1);
5688 completion_list_add_name (tracker, language_objc, tmp,
5689 lookup_name, text, word);
5690 if (text[0] == '[')
5691 completion_list_add_name (tracker, language_objc, tmp + 1,
5692 lookup_name, text, word);
5695 if (selector != NULL)
5697 /* Complete on selector only. */
5698 strcpy (tmp, selector);
5699 tmp2 = strchr (tmp, ']');
5700 if (tmp2 != NULL)
5701 *tmp2 = '\0';
5703 completion_list_add_name (tracker, language_objc, tmp,
5704 lookup_name, text, word);
5708 /* Break the non-quoted text based on the characters which are in
5709 symbols. FIXME: This should probably be language-specific. */
5711 static const char *
5712 language_search_unquoted_string (const char *text, const char *p)
5714 for (; p > text; --p)
5716 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
5717 continue;
5718 else
5720 if ((current_language->la_language == language_objc))
5722 if (p[-1] == ':') /* Might be part of a method name. */
5723 continue;
5724 else if (p[-1] == '[' && (p[-2] == '-' || p[-2] == '+'))
5725 p -= 2; /* Beginning of a method name. */
5726 else if (p[-1] == ' ' || p[-1] == '(' || p[-1] == ')')
5727 { /* Might be part of a method name. */
5728 const char *t = p;
5730 /* Seeing a ' ' or a '(' is not conclusive evidence
5731 that we are in the middle of a method name. However,
5732 finding "-[" or "+[" should be pretty un-ambiguous.
5733 Unfortunately we have to find it now to decide. */
5735 while (t > text)
5736 if (isalnum (t[-1]) || t[-1] == '_' ||
5737 t[-1] == ' ' || t[-1] == ':' ||
5738 t[-1] == '(' || t[-1] == ')')
5739 --t;
5740 else
5741 break;
5743 if (t[-1] == '[' && (t[-2] == '-' || t[-2] == '+'))
5744 p = t - 2; /* Method name detected. */
5745 /* Else we leave with p unchanged. */
5748 break;
5751 return p;
5754 static void
5755 completion_list_add_fields (completion_tracker &tracker,
5756 struct symbol *sym,
5757 const lookup_name_info &lookup_name,
5758 const char *text, const char *word)
5760 if (sym->aclass () == LOC_TYPEDEF)
5762 struct type *t = sym->type ();
5763 enum type_code c = t->code ();
5764 int j;
5766 if (c == TYPE_CODE_UNION || c == TYPE_CODE_STRUCT)
5767 for (j = TYPE_N_BASECLASSES (t); j < t->num_fields (); j++)
5768 if (t->field (j).name ())
5769 completion_list_add_name (tracker, sym->language (),
5770 t->field (j).name (),
5771 lookup_name, text, word);
5775 /* See symtab.h. */
5777 bool
5778 symbol_is_function_or_method (symbol *sym)
5780 switch (sym->type ()->code ())
5782 case TYPE_CODE_FUNC:
5783 case TYPE_CODE_METHOD:
5784 return true;
5785 default:
5786 return false;
5790 /* See symtab.h. */
5792 bool
5793 symbol_is_function_or_method (minimal_symbol *msymbol)
5795 switch (msymbol->type ())
5797 case mst_text:
5798 case mst_text_gnu_ifunc:
5799 case mst_solib_trampoline:
5800 case mst_file_text:
5801 return true;
5802 default:
5803 return false;
5807 /* See symtab.h. */
5809 bound_minimal_symbol
5810 find_gnu_ifunc (const symbol *sym)
5812 if (sym->aclass () != LOC_BLOCK)
5813 return {};
5815 lookup_name_info lookup_name (sym->search_name (),
5816 symbol_name_match_type::SEARCH_NAME);
5817 struct objfile *objfile = sym->objfile ();
5819 CORE_ADDR address = sym->value_block ()->entry_pc ();
5820 minimal_symbol *ifunc = NULL;
5822 iterate_over_minimal_symbols (objfile, lookup_name,
5823 [&] (minimal_symbol *minsym)
5825 if (minsym->type () == mst_text_gnu_ifunc
5826 || minsym->type () == mst_data_gnu_ifunc)
5828 CORE_ADDR msym_addr = minsym->value_address (objfile);
5829 if (minsym->type () == mst_data_gnu_ifunc)
5831 struct gdbarch *gdbarch = objfile->arch ();
5832 msym_addr = gdbarch_convert_from_func_ptr_addr
5833 (gdbarch, msym_addr, current_inferior ()->top_target ());
5835 if (msym_addr == address)
5837 ifunc = minsym;
5838 return true;
5841 return false;
5844 if (ifunc != NULL)
5845 return {ifunc, objfile};
5846 return {};
5849 /* Add matching symbols from SYMTAB to the current completion list. */
5851 static void
5852 add_symtab_completions (struct compunit_symtab *cust,
5853 completion_tracker &tracker,
5854 complete_symbol_mode mode,
5855 const lookup_name_info &lookup_name,
5856 const char *text, const char *word,
5857 enum type_code code)
5859 int i;
5861 if (cust == NULL)
5862 return;
5864 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
5866 QUIT;
5868 const struct block *b = cust->blockvector ()->block (i);
5869 for (struct symbol *sym : block_iterator_range (b))
5871 if (completion_skip_symbol (mode, sym))
5872 continue;
5874 if (code == TYPE_CODE_UNDEF
5875 || (sym->domain () == STRUCT_DOMAIN
5876 && sym->type ()->code () == code))
5877 completion_list_add_symbol (tracker, sym,
5878 lookup_name,
5879 text, word);
5884 void
5885 default_collect_symbol_completion_matches_break_on
5886 (completion_tracker &tracker, complete_symbol_mode mode,
5887 symbol_name_match_type name_match_type,
5888 const char *text, const char *word,
5889 const char *break_on, enum type_code code)
5891 /* Problem: All of the symbols have to be copied because readline
5892 frees them. I'm not going to worry about this; hopefully there
5893 won't be that many. */
5895 const struct block *b;
5896 const struct block *surrounding_static_block, *surrounding_global_block;
5897 /* The symbol we are completing on. Points in same buffer as text. */
5898 const char *sym_text;
5900 /* Now look for the symbol we are supposed to complete on. */
5901 if (mode == complete_symbol_mode::LINESPEC)
5902 sym_text = text;
5903 else
5905 const char *p;
5906 char quote_found;
5907 const char *quote_pos = NULL;
5909 /* First see if this is a quoted string. */
5910 quote_found = '\0';
5911 for (p = text; *p != '\0'; ++p)
5913 if (quote_found != '\0')
5915 if (*p == quote_found)
5916 /* Found close quote. */
5917 quote_found = '\0';
5918 else if (*p == '\\' && p[1] == quote_found)
5919 /* A backslash followed by the quote character
5920 doesn't end the string. */
5921 ++p;
5923 else if (*p == '\'' || *p == '"')
5925 quote_found = *p;
5926 quote_pos = p;
5929 if (quote_found == '\'')
5930 /* A string within single quotes can be a symbol, so complete on it. */
5931 sym_text = quote_pos + 1;
5932 else if (quote_found == '"')
5933 /* A double-quoted string is never a symbol, nor does it make sense
5934 to complete it any other way. */
5936 return;
5938 else
5940 /* It is not a quoted string. Break it based on the characters
5941 which are in symbols. */
5942 while (p > text)
5944 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0'
5945 || p[-1] == ':' || strchr (break_on, p[-1]) != NULL)
5946 --p;
5947 else
5948 break;
5950 sym_text = p;
5954 lookup_name_info lookup_name (sym_text, name_match_type, true);
5956 /* At this point scan through the misc symbol vectors and add each
5957 symbol you find to the list. Eventually we want to ignore
5958 anything that isn't a text symbol (everything else will be
5959 handled by the psymtab code below). */
5961 if (code == TYPE_CODE_UNDEF)
5963 for (objfile *objfile : current_program_space->objfiles ())
5965 for (minimal_symbol *msymbol : objfile->msymbols ())
5967 QUIT;
5969 if (completion_skip_symbol (mode, msymbol))
5970 continue;
5972 completion_list_add_msymbol (tracker, msymbol, lookup_name,
5973 sym_text, word);
5975 completion_list_objc_symbol (tracker, msymbol, lookup_name,
5976 sym_text, word);
5981 /* Add completions for all currently loaded symbol tables. */
5982 for (objfile *objfile : current_program_space->objfiles ())
5984 for (compunit_symtab *cust : objfile->compunits ())
5985 add_symtab_completions (cust, tracker, mode, lookup_name,
5986 sym_text, word, code);
5989 /* Look through the partial symtabs for all symbols which begin by
5990 matching SYM_TEXT. Expand all CUs that you find to the list. */
5991 expand_symtabs_matching (NULL,
5992 lookup_name,
5993 NULL,
5994 [&] (compunit_symtab *symtab) /* expansion notify */
5996 add_symtab_completions (symtab,
5997 tracker, mode, lookup_name,
5998 sym_text, word, code);
5999 return true;
6001 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
6002 SEARCH_ALL_DOMAINS);
6004 /* Search upwards from currently selected frame (so that we can
6005 complete on local vars). Also catch fields of types defined in
6006 this places which match our text string. Only complete on types
6007 visible from current context. */
6009 b = get_selected_block (0);
6010 surrounding_static_block = b == nullptr ? nullptr : b->static_block ();
6011 surrounding_global_block = b == nullptr ? nullptr : b->global_block ();
6012 if (surrounding_static_block != NULL)
6013 while (b != surrounding_static_block)
6015 QUIT;
6017 for (struct symbol *sym : block_iterator_range (b))
6019 if (code == TYPE_CODE_UNDEF)
6021 completion_list_add_symbol (tracker, sym, lookup_name,
6022 sym_text, word);
6023 completion_list_add_fields (tracker, sym, lookup_name,
6024 sym_text, word);
6026 else if (sym->domain () == STRUCT_DOMAIN
6027 && sym->type ()->code () == code)
6028 completion_list_add_symbol (tracker, sym, lookup_name,
6029 sym_text, word);
6032 /* Stop when we encounter an enclosing function. Do not stop for
6033 non-inlined functions - the locals of the enclosing function
6034 are in scope for a nested function. */
6035 if (b->function () != NULL && b->inlined_p ())
6036 break;
6037 b = b->superblock ();
6040 /* Add fields from the file's types; symbols will be added below. */
6042 if (code == TYPE_CODE_UNDEF)
6044 if (surrounding_static_block != NULL)
6045 for (struct symbol *sym : block_iterator_range (surrounding_static_block))
6046 completion_list_add_fields (tracker, sym, lookup_name,
6047 sym_text, word);
6049 if (surrounding_global_block != NULL)
6050 for (struct symbol *sym : block_iterator_range (surrounding_global_block))
6051 completion_list_add_fields (tracker, sym, lookup_name,
6052 sym_text, word);
6055 /* Skip macros if we are completing a struct tag -- arguable but
6056 usually what is expected. */
6057 if (current_language->macro_expansion () == macro_expansion_c
6058 && code == TYPE_CODE_UNDEF)
6060 gdb::unique_xmalloc_ptr<struct macro_scope> scope;
6062 /* This adds a macro's name to the current completion list. */
6063 auto add_macro_name = [&] (const char *macro_name,
6064 const macro_definition *,
6065 macro_source_file *,
6066 int)
6068 completion_list_add_name (tracker, language_c, macro_name,
6069 lookup_name, sym_text, word);
6072 /* Add any macros visible in the default scope. Note that this
6073 may yield the occasional wrong result, because an expression
6074 might be evaluated in a scope other than the default. For
6075 example, if the user types "break file:line if <TAB>", the
6076 resulting expression will be evaluated at "file:line" -- but
6077 at there does not seem to be a way to detect this at
6078 completion time. */
6079 scope = default_macro_scope ();
6080 if (scope)
6081 macro_for_each_in_scope (scope->file, scope->line,
6082 add_macro_name);
6084 /* User-defined macros are always visible. */
6085 macro_for_each (macro_user_macros, add_macro_name);
6089 /* Collect all symbols (regardless of class) which begin by matching
6090 TEXT. */
6092 void
6093 collect_symbol_completion_matches (completion_tracker &tracker,
6094 complete_symbol_mode mode,
6095 symbol_name_match_type name_match_type,
6096 const char *text, const char *word)
6098 current_language->collect_symbol_completion_matches (tracker, mode,
6099 name_match_type,
6100 text, word,
6101 TYPE_CODE_UNDEF);
6104 /* Like collect_symbol_completion_matches, but only collect
6105 STRUCT_DOMAIN symbols whose type code is CODE. */
6107 void
6108 collect_symbol_completion_matches_type (completion_tracker &tracker,
6109 const char *text, const char *word,
6110 enum type_code code)
6112 complete_symbol_mode mode = complete_symbol_mode::EXPRESSION;
6113 symbol_name_match_type name_match_type = symbol_name_match_type::EXPRESSION;
6115 gdb_assert (code == TYPE_CODE_UNION
6116 || code == TYPE_CODE_STRUCT
6117 || code == TYPE_CODE_ENUM);
6118 current_language->collect_symbol_completion_matches (tracker, mode,
6119 name_match_type,
6120 text, word, code);
6123 /* Like collect_symbol_completion_matches, but collects a list of
6124 symbols defined in all source files named SRCFILE. */
6126 void
6127 collect_file_symbol_completion_matches (completion_tracker &tracker,
6128 complete_symbol_mode mode,
6129 symbol_name_match_type name_match_type,
6130 const char *text, const char *word,
6131 const char *srcfile)
6133 /* The symbol we are completing on. Points in same buffer as text. */
6134 const char *sym_text;
6136 /* Now look for the symbol we are supposed to complete on.
6137 FIXME: This should be language-specific. */
6138 if (mode == complete_symbol_mode::LINESPEC)
6139 sym_text = text;
6140 else
6142 const char *p;
6143 char quote_found;
6144 const char *quote_pos = NULL;
6146 /* First see if this is a quoted string. */
6147 quote_found = '\0';
6148 for (p = text; *p != '\0'; ++p)
6150 if (quote_found != '\0')
6152 if (*p == quote_found)
6153 /* Found close quote. */
6154 quote_found = '\0';
6155 else if (*p == '\\' && p[1] == quote_found)
6156 /* A backslash followed by the quote character
6157 doesn't end the string. */
6158 ++p;
6160 else if (*p == '\'' || *p == '"')
6162 quote_found = *p;
6163 quote_pos = p;
6166 if (quote_found == '\'')
6167 /* A string within single quotes can be a symbol, so complete on it. */
6168 sym_text = quote_pos + 1;
6169 else if (quote_found == '"')
6170 /* A double-quoted string is never a symbol, nor does it make sense
6171 to complete it any other way. */
6173 return;
6175 else
6177 /* Not a quoted string. */
6178 sym_text = language_search_unquoted_string (text, p);
6182 lookup_name_info lookup_name (sym_text, name_match_type, true);
6184 /* Go through symtabs for SRCFILE and check the externs and statics
6185 for symbols which match. */
6186 iterate_over_symtabs (srcfile, [&] (symtab *s)
6188 add_symtab_completions (s->compunit (),
6189 tracker, mode, lookup_name,
6190 sym_text, word, TYPE_CODE_UNDEF);
6191 return false;
6195 /* A helper function for make_source_files_completion_list. It adds
6196 another file name to a list of possible completions, growing the
6197 list as necessary. */
6199 static void
6200 add_filename_to_list (const char *fname, const char *text, const char *word,
6201 completion_list *list)
6203 list->emplace_back (make_completion_match_str (fname, text, word));
6206 static int
6207 not_interesting_fname (const char *fname)
6209 static const char *illegal_aliens[] = {
6210 "_globals_", /* inserted by coff_symtab_read */
6211 NULL
6213 int i;
6215 for (i = 0; illegal_aliens[i]; i++)
6217 if (filename_cmp (fname, illegal_aliens[i]) == 0)
6218 return 1;
6220 return 0;
6223 /* An object of this type is passed as the callback argument to
6224 map_partial_symbol_filenames. */
6225 struct add_partial_filename_data
6227 struct filename_seen_cache *filename_seen_cache;
6228 const char *text;
6229 const char *word;
6230 int text_len;
6231 completion_list *list;
6233 void operator() (const char *filename, const char *fullname);
6236 /* A callback for map_partial_symbol_filenames. */
6238 void
6239 add_partial_filename_data::operator() (const char *filename,
6240 const char *fullname)
6242 if (not_interesting_fname (filename))
6243 return;
6244 if (!filename_seen_cache->seen (filename)
6245 && filename_ncmp (filename, text, text_len) == 0)
6247 /* This file matches for a completion; add it to the
6248 current list of matches. */
6249 add_filename_to_list (filename, text, word, list);
6251 else
6253 const char *base_name = lbasename (filename);
6255 if (base_name != filename
6256 && !filename_seen_cache->seen (base_name)
6257 && filename_ncmp (base_name, text, text_len) == 0)
6258 add_filename_to_list (base_name, text, word, list);
6262 /* Return a list of all source files whose names begin with matching
6263 TEXT. The file names are looked up in the symbol tables of this
6264 program. */
6266 completion_list
6267 make_source_files_completion_list (const char *text, const char *word)
6269 size_t text_len = strlen (text);
6270 completion_list list;
6271 const char *base_name;
6272 struct add_partial_filename_data datum;
6274 if (!have_full_symbols () && !have_partial_symbols ())
6275 return list;
6277 filename_seen_cache filenames_seen;
6279 for (objfile *objfile : current_program_space->objfiles ())
6281 for (compunit_symtab *cu : objfile->compunits ())
6283 for (symtab *s : cu->filetabs ())
6285 if (not_interesting_fname (s->filename))
6286 continue;
6287 if (!filenames_seen.seen (s->filename)
6288 && filename_ncmp (s->filename, text, text_len) == 0)
6290 /* This file matches for a completion; add it to the current
6291 list of matches. */
6292 add_filename_to_list (s->filename, text, word, &list);
6294 else
6296 /* NOTE: We allow the user to type a base name when the
6297 debug info records leading directories, but not the other
6298 way around. This is what subroutines of breakpoint
6299 command do when they parse file names. */
6300 base_name = lbasename (s->filename);
6301 if (base_name != s->filename
6302 && !filenames_seen.seen (base_name)
6303 && filename_ncmp (base_name, text, text_len) == 0)
6304 add_filename_to_list (base_name, text, word, &list);
6310 datum.filename_seen_cache = &filenames_seen;
6311 datum.text = text;
6312 datum.word = word;
6313 datum.text_len = text_len;
6314 datum.list = &list;
6315 map_symbol_filenames (datum, false /*need_fullname*/);
6317 return list;
6320 /* Track MAIN */
6322 /* Return the "main_info" object for the current program space. If
6323 the object has not yet been created, create it and fill in some
6324 default values. */
6326 static main_info *
6327 get_main_info (program_space *pspace)
6329 main_info *info = main_progspace_key.get (pspace);
6331 if (info == NULL)
6333 /* It may seem strange to store the main name in the progspace
6334 and also in whatever objfile happens to see a main name in
6335 its debug info. The reason for this is mainly historical:
6336 gdb returned "main" as the name even if no function named
6337 "main" was defined the program; and this approach lets us
6338 keep compatibility. */
6339 info = main_progspace_key.emplace (pspace);
6342 return info;
6345 static void
6346 set_main_name (program_space *pspace, const char *name, enum language lang)
6348 main_info *info = get_main_info (pspace);
6350 if (!info->name_of_main.empty ())
6352 info->name_of_main.clear ();
6353 info->language_of_main = language_unknown;
6355 if (name != NULL)
6357 info->name_of_main = name;
6358 info->language_of_main = lang;
6362 /* Deduce the name of the main procedure, and set NAME_OF_MAIN
6363 accordingly. */
6365 static void
6366 find_main_name (void)
6368 const char *new_main_name;
6369 program_space *pspace = current_program_space;
6371 /* First check the objfiles to see whether a debuginfo reader has
6372 picked up the appropriate main name. Historically the main name
6373 was found in a more or less random way; this approach instead
6374 relies on the order of objfile creation -- which still isn't
6375 guaranteed to get the correct answer, but is just probably more
6376 accurate. */
6377 for (objfile *objfile : current_program_space->objfiles ())
6379 objfile->compute_main_name ();
6381 if (objfile->per_bfd->name_of_main != NULL)
6383 set_main_name (pspace,
6384 objfile->per_bfd->name_of_main,
6385 objfile->per_bfd->language_of_main);
6386 return;
6390 /* Try to see if the main procedure is in Ada. */
6391 /* FIXME: brobecker/2005-03-07: Another way of doing this would
6392 be to add a new method in the language vector, and call this
6393 method for each language until one of them returns a non-empty
6394 name. This would allow us to remove this hard-coded call to
6395 an Ada function. It is not clear that this is a better approach
6396 at this point, because all methods need to be written in a way
6397 such that false positives never be returned. For instance, it is
6398 important that a method does not return a wrong name for the main
6399 procedure if the main procedure is actually written in a different
6400 language. It is easy to guaranty this with Ada, since we use a
6401 special symbol generated only when the main in Ada to find the name
6402 of the main procedure. It is difficult however to see how this can
6403 be guarantied for languages such as C, for instance. This suggests
6404 that order of call for these methods becomes important, which means
6405 a more complicated approach. */
6406 new_main_name = ada_main_name ();
6407 if (new_main_name != NULL)
6409 set_main_name (pspace, new_main_name, language_ada);
6410 return;
6413 new_main_name = d_main_name ();
6414 if (new_main_name != NULL)
6416 set_main_name (pspace, new_main_name, language_d);
6417 return;
6420 new_main_name = go_main_name ();
6421 if (new_main_name != NULL)
6423 set_main_name (pspace, new_main_name, language_go);
6424 return;
6427 new_main_name = pascal_main_name ();
6428 if (new_main_name != NULL)
6430 set_main_name (pspace, new_main_name, language_pascal);
6431 return;
6434 /* The languages above didn't identify the name of the main procedure.
6435 Fallback to "main". */
6437 /* Try to find language for main in psymtabs. */
6438 bool symbol_found_p = false;
6439 gdbarch_iterate_over_objfiles_in_search_order
6440 (current_inferior ()->arch (),
6441 [&symbol_found_p, pspace] (objfile *obj)
6443 language lang
6444 = obj->lookup_global_symbol_language ("main",
6445 SEARCH_FUNCTION_DOMAIN,
6446 &symbol_found_p);
6447 if (symbol_found_p)
6449 set_main_name (pspace, "main", lang);
6450 return 1;
6453 return 0;
6454 }, nullptr);
6456 if (symbol_found_p)
6457 return;
6459 set_main_name (pspace, "main", language_unknown);
6462 /* See symtab.h. */
6464 const char *
6465 main_name ()
6467 main_info *info = get_main_info (current_program_space);
6469 if (info->name_of_main.empty ())
6470 find_main_name ();
6472 return info->name_of_main.c_str ();
6475 /* Return the language of the main function. If it is not known,
6476 return language_unknown. */
6478 enum language
6479 main_language (void)
6481 main_info *info = get_main_info (current_program_space);
6483 if (info->name_of_main.empty ())
6484 find_main_name ();
6486 return info->language_of_main;
6489 /* Return 1 if the supplied producer string matches the ARM RealView
6490 compiler (armcc). */
6492 bool
6493 producer_is_realview (const char *producer)
6495 static const char *const arm_idents[] = {
6496 "ARM C Compiler, ADS",
6497 "Thumb C Compiler, ADS",
6498 "ARM C++ Compiler, ADS",
6499 "Thumb C++ Compiler, ADS",
6500 "ARM/Thumb C/C++ Compiler, RVCT",
6501 "ARM C/C++ Compiler, RVCT"
6504 if (producer == NULL)
6505 return false;
6507 for (const char *ident : arm_idents)
6508 if (startswith (producer, ident))
6509 return true;
6511 return false;
6516 /* The next index to hand out in response to a registration request. */
6518 static int next_aclass_value = LOC_FINAL_VALUE;
6520 /* The maximum number of "aclass" registrations we support. This is
6521 constant for convenience. */
6522 #define MAX_SYMBOL_IMPLS (LOC_FINAL_VALUE + 11)
6524 /* The objects representing the various "aclass" values. The elements
6525 from 0 up to LOC_FINAL_VALUE-1 represent themselves, and subsequent
6526 elements are those registered at gdb initialization time. */
6528 static struct symbol_impl symbol_impl[MAX_SYMBOL_IMPLS];
6530 /* The globally visible pointer. This is separate from 'symbol_impl'
6531 so that it can be const. */
6533 gdb::array_view<const struct symbol_impl> symbol_impls (symbol_impl);
6535 /* Make sure we saved enough room in struct symbol. */
6537 static_assert (MAX_SYMBOL_IMPLS <= (1 << SYMBOL_ACLASS_BITS));
6539 /* Register a computed symbol type. ACLASS must be LOC_COMPUTED. OPS
6540 is the ops vector associated with this index. This returns the new
6541 index, which should be used as the aclass_index field for symbols
6542 of this type. */
6545 register_symbol_computed_impl (enum address_class aclass,
6546 const struct symbol_computed_ops *ops)
6548 int result = next_aclass_value++;
6550 gdb_assert (aclass == LOC_COMPUTED);
6551 gdb_assert (result < MAX_SYMBOL_IMPLS);
6552 symbol_impl[result].aclass = aclass;
6553 symbol_impl[result].ops_computed = ops;
6555 /* Sanity check OPS. */
6556 gdb_assert (ops != NULL);
6557 gdb_assert (ops->tracepoint_var_ref != NULL);
6558 gdb_assert (ops->describe_location != NULL);
6559 gdb_assert (ops->get_symbol_read_needs != NULL);
6560 gdb_assert (ops->read_variable != NULL);
6562 return result;
6565 /* Register a function with frame base type. ACLASS must be LOC_BLOCK.
6566 OPS is the ops vector associated with this index. This returns the
6567 new index, which should be used as the aclass_index field for symbols
6568 of this type. */
6571 register_symbol_block_impl (enum address_class aclass,
6572 const struct symbol_block_ops *ops)
6574 int result = next_aclass_value++;
6576 gdb_assert (aclass == LOC_BLOCK);
6577 gdb_assert (result < MAX_SYMBOL_IMPLS);
6578 symbol_impl[result].aclass = aclass;
6579 symbol_impl[result].ops_block = ops;
6581 /* Sanity check OPS. */
6582 gdb_assert (ops != NULL);
6583 gdb_assert (ops->find_frame_base_location != nullptr
6584 || ops->get_block_value != nullptr);
6586 return result;
6589 /* Register a register symbol type. ACLASS must be LOC_REGISTER or
6590 LOC_REGPARM_ADDR. OPS is the register ops vector associated with
6591 this index. This returns the new index, which should be used as
6592 the aclass_index field for symbols of this type. */
6595 register_symbol_register_impl (enum address_class aclass,
6596 const struct symbol_register_ops *ops)
6598 int result = next_aclass_value++;
6600 gdb_assert (aclass == LOC_REGISTER || aclass == LOC_REGPARM_ADDR);
6601 gdb_assert (result < MAX_SYMBOL_IMPLS);
6602 symbol_impl[result].aclass = aclass;
6603 symbol_impl[result].ops_register = ops;
6605 return result;
6608 /* Initialize elements of 'symbol_impl' for the constants in enum
6609 address_class. */
6611 static void
6612 initialize_ordinary_address_classes (void)
6614 int i;
6616 for (i = 0; i < LOC_FINAL_VALUE; ++i)
6617 symbol_impl[i].aclass = (enum address_class) i;
6622 /* See symtab.h. */
6624 struct objfile *
6625 symbol::objfile () const
6627 gdb_assert (is_objfile_owned ());
6628 return owner.symtab->compunit ()->objfile ();
6631 /* See symtab.h. */
6633 struct gdbarch *
6634 symbol::arch () const
6636 if (!is_objfile_owned ())
6637 return owner.arch;
6638 return owner.symtab->compunit ()->objfile ()->arch ();
6641 /* See symtab.h. */
6643 struct symtab *
6644 symbol::symtab () const
6646 gdb_assert (is_objfile_owned ());
6647 return owner.symtab;
6650 /* See symtab.h. */
6652 void
6653 symbol::set_symtab (struct symtab *symtab)
6655 gdb_assert (is_objfile_owned ());
6656 owner.symtab = symtab;
6659 /* See symtab.h. */
6661 CORE_ADDR
6662 symbol::get_maybe_copied_address () const
6664 gdb_assert (this->maybe_copied);
6665 gdb_assert (this->aclass () == LOC_STATIC);
6667 const char *linkage_name = this->linkage_name ();
6668 bound_minimal_symbol minsym = lookup_minimal_symbol_linkage (linkage_name,
6669 false);
6670 if (minsym.minsym != nullptr)
6671 return minsym.value_address ();
6672 return this->m_value.address;
6675 /* See symtab.h. */
6677 CORE_ADDR
6678 minimal_symbol::get_maybe_copied_address (objfile *objf) const
6680 gdb_assert (this->maybe_copied (objf));
6681 gdb_assert ((objf->flags & OBJF_MAINLINE) == 0);
6683 const char *linkage_name = this->linkage_name ();
6684 bound_minimal_symbol found = lookup_minimal_symbol_linkage (linkage_name,
6685 true);
6686 if (found.minsym != nullptr)
6687 return found.value_address ();
6688 return (this->m_value.address
6689 + objf->section_offsets[this->section_index ()]);
6694 /* Hold the sub-commands of 'info module'. */
6696 static struct cmd_list_element *info_module_cmdlist = NULL;
6698 /* See symtab.h. */
6700 std::vector<module_symbol_search>
6701 search_module_symbols (const char *module_regexp, const char *regexp,
6702 const char *type_regexp, domain_search_flags kind)
6704 std::vector<module_symbol_search> results;
6706 /* Search for all modules matching MODULE_REGEXP. */
6707 global_symbol_searcher spec1 (SEARCH_MODULE_DOMAIN, module_regexp);
6708 spec1.set_exclude_minsyms (true);
6709 std::vector<symbol_search> modules = spec1.search ();
6711 /* Now search for all symbols of the required KIND matching the required
6712 regular expressions. We figure out which ones are in which modules
6713 below. */
6714 global_symbol_searcher spec2 (kind, regexp);
6715 spec2.set_symbol_type_regexp (type_regexp);
6716 spec2.set_exclude_minsyms (true);
6717 std::vector<symbol_search> symbols = spec2.search ();
6719 /* Now iterate over all MODULES, checking to see which items from
6720 SYMBOLS are in each module. */
6721 for (const symbol_search &p : modules)
6723 QUIT;
6725 /* This is a module. */
6726 gdb_assert (p.symbol != nullptr);
6728 std::string prefix = p.symbol->print_name ();
6729 prefix += "::";
6731 for (const symbol_search &q : symbols)
6733 if (q.symbol == nullptr)
6734 continue;
6736 if (strncmp (q.symbol->print_name (), prefix.c_str (),
6737 prefix.size ()) != 0)
6738 continue;
6740 results.push_back ({p, q});
6744 return results;
6747 /* Implement the core of both 'info module functions' and 'info module
6748 variables'. */
6750 static void
6751 info_module_subcommand (bool quiet, const char *module_regexp,
6752 const char *regexp, const char *type_regexp,
6753 domain_search_flags kind)
6755 gdb_assert (kind == SEARCH_FUNCTION_DOMAIN || kind == SEARCH_VAR_DOMAIN);
6757 /* Print a header line. Don't build the header line bit by bit as this
6758 prevents internationalisation. */
6759 if (!quiet)
6761 if (module_regexp == nullptr)
6763 if (type_regexp == nullptr)
6765 if (regexp == nullptr)
6766 gdb_printf ((kind == SEARCH_VAR_DOMAIN
6767 ? _("All variables in all modules:")
6768 : _("All functions in all modules:")));
6769 else
6770 gdb_printf
6771 ((kind == SEARCH_VAR_DOMAIN
6772 ? _("All variables matching regular expression"
6773 " \"%s\" in all modules:")
6774 : _("All functions matching regular expression"
6775 " \"%s\" in all modules:")),
6776 regexp);
6778 else
6780 if (regexp == nullptr)
6781 gdb_printf
6782 ((kind == SEARCH_VAR_DOMAIN
6783 ? _("All variables with type matching regular "
6784 "expression \"%s\" in all modules:")
6785 : _("All functions with type matching regular "
6786 "expression \"%s\" in all modules:")),
6787 type_regexp);
6788 else
6789 gdb_printf
6790 ((kind == SEARCH_VAR_DOMAIN
6791 ? _("All variables matching regular expression "
6792 "\"%s\",\n\twith type matching regular "
6793 "expression \"%s\" in all modules:")
6794 : _("All functions matching regular expression "
6795 "\"%s\",\n\twith type matching regular "
6796 "expression \"%s\" in all modules:")),
6797 regexp, type_regexp);
6800 else
6802 if (type_regexp == nullptr)
6804 if (regexp == nullptr)
6805 gdb_printf
6806 ((kind == SEARCH_VAR_DOMAIN
6807 ? _("All variables in all modules matching regular "
6808 "expression \"%s\":")
6809 : _("All functions in all modules matching regular "
6810 "expression \"%s\":")),
6811 module_regexp);
6812 else
6813 gdb_printf
6814 ((kind == SEARCH_VAR_DOMAIN
6815 ? _("All variables matching regular expression "
6816 "\"%s\",\n\tin all modules matching regular "
6817 "expression \"%s\":")
6818 : _("All functions matching regular expression "
6819 "\"%s\",\n\tin all modules matching regular "
6820 "expression \"%s\":")),
6821 regexp, module_regexp);
6823 else
6825 if (regexp == nullptr)
6826 gdb_printf
6827 ((kind == SEARCH_VAR_DOMAIN
6828 ? _("All variables with type matching regular "
6829 "expression \"%s\"\n\tin all modules matching "
6830 "regular expression \"%s\":")
6831 : _("All functions with type matching regular "
6832 "expression \"%s\"\n\tin all modules matching "
6833 "regular expression \"%s\":")),
6834 type_regexp, module_regexp);
6835 else
6836 gdb_printf
6837 ((kind == SEARCH_VAR_DOMAIN
6838 ? _("All variables matching regular expression "
6839 "\"%s\",\n\twith type matching regular expression "
6840 "\"%s\",\n\tin all modules matching regular "
6841 "expression \"%s\":")
6842 : _("All functions matching regular expression "
6843 "\"%s\",\n\twith type matching regular expression "
6844 "\"%s\",\n\tin all modules matching regular "
6845 "expression \"%s\":")),
6846 regexp, type_regexp, module_regexp);
6849 gdb_printf ("\n");
6852 /* Find all symbols of type KIND matching the given regular expressions
6853 along with the symbols for the modules in which those symbols
6854 reside. */
6855 std::vector<module_symbol_search> module_symbols
6856 = search_module_symbols (module_regexp, regexp, type_regexp, kind);
6858 std::sort (module_symbols.begin (), module_symbols.end (),
6859 [] (const module_symbol_search &a, const module_symbol_search &b)
6861 if (a.first < b.first)
6862 return true;
6863 else if (a.first == b.first)
6864 return a.second < b.second;
6865 else
6866 return false;
6869 const char *last_filename = "";
6870 const symbol *last_module_symbol = nullptr;
6871 for (const module_symbol_search &ms : module_symbols)
6873 const symbol_search &p = ms.first;
6874 const symbol_search &q = ms.second;
6876 gdb_assert (q.symbol != nullptr);
6878 if (last_module_symbol != p.symbol)
6880 gdb_printf ("\n");
6881 gdb_printf (_("Module \"%s\":\n"), p.symbol->print_name ());
6882 last_module_symbol = p.symbol;
6883 last_filename = "";
6886 print_symbol_info (q.symbol, q.block, last_filename);
6887 last_filename
6888 = symtab_to_filename_for_display (q.symbol->symtab ());
6892 /* Hold the option values for the 'info module .....' sub-commands. */
6894 struct info_modules_var_func_options
6896 bool quiet = false;
6897 std::string type_regexp;
6898 std::string module_regexp;
6901 /* The options used by 'info module variables' and 'info module functions'
6902 commands. */
6904 static const gdb::option::option_def info_modules_var_func_options_defs [] = {
6905 gdb::option::boolean_option_def<info_modules_var_func_options> {
6906 "q",
6907 [] (info_modules_var_func_options *opt) { return &opt->quiet; },
6908 nullptr, /* show_cmd_cb */
6909 nullptr /* set_doc */
6912 gdb::option::string_option_def<info_modules_var_func_options> {
6913 "t",
6914 [] (info_modules_var_func_options *opt) { return &opt->type_regexp; },
6915 nullptr, /* show_cmd_cb */
6916 nullptr /* set_doc */
6919 gdb::option::string_option_def<info_modules_var_func_options> {
6920 "m",
6921 [] (info_modules_var_func_options *opt) { return &opt->module_regexp; },
6922 nullptr, /* show_cmd_cb */
6923 nullptr /* set_doc */
6927 /* Return the option group used by the 'info module ...' sub-commands. */
6929 static inline gdb::option::option_def_group
6930 make_info_modules_var_func_options_def_group
6931 (info_modules_var_func_options *opts)
6933 return {{info_modules_var_func_options_defs}, opts};
6936 /* Implements the 'info module functions' command. */
6938 static void
6939 info_module_functions_command (const char *args, int from_tty)
6941 info_modules_var_func_options opts;
6942 auto grp = make_info_modules_var_func_options_def_group (&opts);
6943 gdb::option::process_options
6944 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
6945 if (args != nullptr && *args == '\0')
6946 args = nullptr;
6948 info_module_subcommand
6949 (opts.quiet,
6950 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
6951 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
6952 SEARCH_FUNCTION_DOMAIN);
6955 /* Implements the 'info module variables' command. */
6957 static void
6958 info_module_variables_command (const char *args, int from_tty)
6960 info_modules_var_func_options opts;
6961 auto grp = make_info_modules_var_func_options_def_group (&opts);
6962 gdb::option::process_options
6963 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
6964 if (args != nullptr && *args == '\0')
6965 args = nullptr;
6967 info_module_subcommand
6968 (opts.quiet,
6969 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
6970 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
6971 SEARCH_VAR_DOMAIN);
6974 /* Command completer for 'info module ...' sub-commands. */
6976 static void
6977 info_module_var_func_command_completer (struct cmd_list_element *ignore,
6978 completion_tracker &tracker,
6979 const char *text,
6980 const char * /* word */)
6983 const auto group = make_info_modules_var_func_options_def_group (nullptr);
6984 if (gdb::option::complete_options
6985 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
6986 return;
6988 const char *word = advance_to_expression_complete_word_point (tracker, text);
6989 symbol_completer (ignore, tracker, text, word);
6994 void _initialize_symtab ();
6995 void
6996 _initialize_symtab ()
6998 cmd_list_element *c;
7000 initialize_ordinary_address_classes ();
7002 c = add_info ("variables", info_variables_command,
7003 info_print_args_help (_("\
7004 All global and static variable names or those matching REGEXPs.\n\
7005 Usage: info variables [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7006 Prints the global and static variables.\n"),
7007 _("global and static variables"),
7008 true));
7009 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7011 c = add_info ("functions", info_functions_command,
7012 info_print_args_help (_("\
7013 All function names or those matching REGEXPs.\n\
7014 Usage: info functions [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7015 Prints the functions.\n"),
7016 _("functions"),
7017 true));
7018 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7020 c = add_info ("types", info_types_command, _("\
7021 All type names, or those matching REGEXP.\n\
7022 Usage: info types [-q] [REGEXP]\n\
7023 Print information about all types matching REGEXP, or all types if no\n\
7024 REGEXP is given. The optional flag -q disables printing of headers."));
7025 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7027 const auto info_sources_opts
7028 = make_info_sources_options_def_group (nullptr);
7030 static std::string info_sources_help
7031 = gdb::option::build_help (_("\
7032 All source files in the program or those matching REGEXP.\n\
7033 Usage: info sources [OPTION]... [REGEXP]\n\
7034 By default, REGEXP is used to match anywhere in the filename.\n\
7036 Options:\n\
7037 %OPTIONS%"),
7038 info_sources_opts);
7040 c = add_info ("sources", info_sources_command, info_sources_help.c_str ());
7041 set_cmd_completer_handle_brkchars (c, info_sources_command_completer);
7043 c = add_info ("modules", info_modules_command,
7044 _("All module names, or those matching REGEXP."));
7045 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7047 add_info ("main", info_main_command,
7048 _("Get main symbol to identify entry point into program."));
7050 add_basic_prefix_cmd ("module", class_info, _("\
7051 Print information about modules."),
7052 &info_module_cmdlist, 0, &infolist);
7054 c = add_cmd ("functions", class_info, info_module_functions_command, _("\
7055 Display functions arranged by modules.\n\
7056 Usage: info module functions [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7057 Print a summary of all functions within each Fortran module, grouped by\n\
7058 module and file. For each function the line on which the function is\n\
7059 defined is given along with the type signature and name of the function.\n\
7061 If REGEXP is provided then only functions whose name matches REGEXP are\n\
7062 listed. If MODREGEXP is provided then only functions in modules matching\n\
7063 MODREGEXP are listed. If TYPEREGEXP is given then only functions whose\n\
7064 type signature matches TYPEREGEXP are listed.\n\
7066 The -q flag suppresses printing some header information."),
7067 &info_module_cmdlist);
7068 set_cmd_completer_handle_brkchars
7069 (c, info_module_var_func_command_completer);
7071 c = add_cmd ("variables", class_info, info_module_variables_command, _("\
7072 Display variables arranged by modules.\n\
7073 Usage: info module variables [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7074 Print a summary of all variables within each Fortran module, grouped by\n\
7075 module and file. For each variable the line on which the variable is\n\
7076 defined is given along with the type and name of the variable.\n\
7078 If REGEXP is provided then only variables whose name matches REGEXP are\n\
7079 listed. If MODREGEXP is provided then only variables in modules matching\n\
7080 MODREGEXP are listed. If TYPEREGEXP is given then only variables whose\n\
7081 type matches TYPEREGEXP are listed.\n\
7083 The -q flag suppresses printing some header information."),
7084 &info_module_cmdlist);
7085 set_cmd_completer_handle_brkchars
7086 (c, info_module_var_func_command_completer);
7088 add_com ("rbreak", class_breakpoint, rbreak_command,
7089 _("Set a breakpoint for all functions matching REGEXP."));
7091 add_setshow_enum_cmd ("multiple-symbols", no_class,
7092 multiple_symbols_modes, &multiple_symbols_mode,
7093 _("\
7094 Set how the debugger handles ambiguities in expressions."), _("\
7095 Show how the debugger handles ambiguities in expressions."), _("\
7096 Valid values are \"ask\", \"all\", \"cancel\", and the default is \"all\"."),
7097 NULL, NULL, &setlist, &showlist);
7099 add_setshow_boolean_cmd ("basenames-may-differ", class_obscure,
7100 &basenames_may_differ, _("\
7101 Set whether a source file may have multiple base names."), _("\
7102 Show whether a source file may have multiple base names."), _("\
7103 (A \"base name\" is the name of a file with the directory part removed.\n\
7104 Example: The base name of \"/home/user/hello.c\" is \"hello.c\".)\n\
7105 If set, GDB will canonicalize file names (e.g., expand symlinks)\n\
7106 before comparing them. Canonicalization is an expensive operation,\n\
7107 but it allows the same file be known by more than one base name.\n\
7108 If not set (the default), all source files are assumed to have just\n\
7109 one base name, and gdb will do file name comparisons more efficiently."),
7110 NULL, NULL,
7111 &setlist, &showlist);
7113 add_setshow_zuinteger_cmd ("symtab-create", no_class, &symtab_create_debug,
7114 _("Set debugging of symbol table creation."),
7115 _("Show debugging of symbol table creation."), _("\
7116 When enabled (non-zero), debugging messages are printed when building\n\
7117 symbol tables. A value of 1 (one) normally provides enough information.\n\
7118 A value greater than 1 provides more verbose information."),
7119 NULL,
7120 NULL,
7121 &setdebuglist, &showdebuglist);
7123 add_setshow_zuinteger_cmd ("symbol-lookup", no_class, &symbol_lookup_debug,
7124 _("\
7125 Set debugging of symbol lookup."), _("\
7126 Show debugging of symbol lookup."), _("\
7127 When enabled (non-zero), symbol lookups are logged."),
7128 NULL, NULL,
7129 &setdebuglist, &showdebuglist);
7131 add_setshow_zuinteger_cmd ("symbol-cache-size", no_class,
7132 &new_symbol_cache_size,
7133 _("Set the size of the symbol cache."),
7134 _("Show the size of the symbol cache."), _("\
7135 The size of the symbol cache.\n\
7136 If zero then the symbol cache is disabled."),
7137 set_symbol_cache_size_handler, NULL,
7138 &maintenance_set_cmdlist,
7139 &maintenance_show_cmdlist);
7141 add_setshow_boolean_cmd ("ignore-prologue-end-flag", no_class,
7142 &ignore_prologue_end_flag,
7143 _("Set if the PROLOGUE-END flag is ignored."),
7144 _("Show if the PROLOGUE-END flag is ignored."),
7145 _("\
7146 The PROLOGUE-END flag from the line-table entries is used to place \
7147 breakpoints past the prologue of functions. Disabling its use forces \
7148 the use of prologue scanners."),
7149 nullptr, nullptr,
7150 &maintenance_set_cmdlist,
7151 &maintenance_show_cmdlist);
7154 add_cmd ("symbol-cache", class_maintenance, maintenance_print_symbol_cache,
7155 _("Dump the symbol cache for each program space."),
7156 &maintenanceprintlist);
7158 add_cmd ("symbol-cache-statistics", class_maintenance,
7159 maintenance_print_symbol_cache_statistics,
7160 _("Print symbol cache statistics for each program space."),
7161 &maintenanceprintlist);
7163 cmd_list_element *maintenance_flush_symbol_cache_cmd
7164 = add_cmd ("symbol-cache", class_maintenance,
7165 maintenance_flush_symbol_cache,
7166 _("Flush the symbol cache for each program space."),
7167 &maintenanceflushlist);
7168 c = add_alias_cmd ("flush-symbol-cache", maintenance_flush_symbol_cache_cmd,
7169 class_maintenance, 0, &maintenancelist);
7170 deprecate_cmd (c, "maintenancelist flush symbol-cache");
7172 gdb::observers::new_objfile.attach (symtab_new_objfile_observer, "symtab");
7173 gdb::observers::all_objfiles_removed.attach (symtab_all_objfiles_removed,
7174 "symtab");
7175 gdb::observers::free_objfile.attach (symtab_free_objfile_observer, "symtab");