arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / symtab.c
blob74ba8b4bbf47e2a5b1c74358a8817de8ca186f8b
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 "event-top.h"
23 #include "gdbtypes.h"
24 #include "gdbcore.h"
25 #include "frame.h"
26 #include "target.h"
27 #include "value.h"
28 #include "symfile.h"
29 #include "objfiles.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 const struct language_defn *langdef);
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 struct symbol *
376 search_symbol_list (const char *name, int num, struct symbol **syms)
378 for (int i = 0; i < num; ++i)
380 if (strcmp (name, syms[i]->natural_name ()) == 0)
381 return syms[i];
383 return nullptr;
386 /* See symtab.h. */
388 CORE_ADDR
389 linetable_entry::pc (const struct objfile *objfile) const
391 return CORE_ADDR (m_pc) + objfile->text_section_offset ();
394 /* See symtab.h. */
396 call_site *
397 compunit_symtab::find_call_site (CORE_ADDR pc) const
399 if (m_call_site_htab == nullptr)
400 return nullptr;
402 CORE_ADDR delta = this->objfile ()->text_section_offset ();
403 unrelocated_addr unrelocated_pc = (unrelocated_addr) (pc - delta);
405 struct call_site call_site_local (unrelocated_pc, nullptr, nullptr);
406 void **slot
407 = htab_find_slot (m_call_site_htab, &call_site_local, NO_INSERT);
408 if (slot != nullptr)
409 return (call_site *) *slot;
411 /* See if the arch knows another PC we should try. On some
412 platforms, GCC emits a DWARF call site that is offset from the
413 actual return location. */
414 struct gdbarch *arch = objfile ()->arch ();
415 CORE_ADDR new_pc = gdbarch_update_call_site_pc (arch, pc);
416 if (pc == new_pc)
417 return nullptr;
419 unrelocated_pc = (unrelocated_addr) (new_pc - delta);
420 call_site new_call_site_local (unrelocated_pc, nullptr, nullptr);
421 slot = htab_find_slot (m_call_site_htab, &new_call_site_local, NO_INSERT);
422 if (slot == nullptr)
423 return nullptr;
425 return (call_site *) *slot;
428 /* See symtab.h. */
430 void
431 compunit_symtab::set_call_site_htab (htab_up call_site_htab)
433 gdb_assert (m_call_site_htab == nullptr);
434 m_call_site_htab = call_site_htab.release ();
437 /* See symtab.h. */
439 void
440 compunit_symtab::set_primary_filetab (symtab *primary_filetab)
442 symtab *prev_filetab = nullptr;
444 /* Move PRIMARY_FILETAB to the head of the filetab list. */
445 for (symtab *filetab : this->filetabs ())
447 if (filetab == primary_filetab)
449 if (prev_filetab != nullptr)
451 prev_filetab->next = primary_filetab->next;
452 primary_filetab->next = m_filetabs;
453 m_filetabs = primary_filetab;
456 break;
459 prev_filetab = filetab;
462 gdb_assert (primary_filetab == m_filetabs);
465 /* See symtab.h. */
467 struct symtab *
468 compunit_symtab::primary_filetab () const
470 gdb_assert (m_filetabs != nullptr);
472 /* The primary file symtab is the first one in the list. */
473 return m_filetabs;
476 /* See symtab.h. */
478 enum language
479 compunit_symtab::language () const
481 struct symtab *symtab = primary_filetab ();
483 /* The language of the compunit symtab is the language of its
484 primary source file. */
485 return symtab->language ();
488 /* See symtab.h. */
490 void
491 compunit_symtab::forget_cached_source_info ()
493 for (symtab *s : filetabs ())
494 s->release_fullname ();
497 /* See symtab.h. */
499 void
500 compunit_symtab::finalize ()
502 this->forget_cached_source_info ();
503 if (m_call_site_htab != nullptr)
504 htab_delete (m_call_site_htab);
507 /* The relocated address of the minimal symbol, using the section
508 offsets from OBJFILE. */
510 CORE_ADDR
511 minimal_symbol::value_address (objfile *objfile) const
513 if (this->maybe_copied (objfile))
514 return this->get_maybe_copied_address (objfile);
515 else
516 return (CORE_ADDR (this->unrelocated_address ())
517 + objfile->section_offsets[this->section_index ()]);
520 /* See symtab.h. */
522 bool
523 minimal_symbol::data_p () const
525 return m_type == mst_data
526 || m_type == mst_bss
527 || m_type == mst_abs
528 || m_type == mst_file_data
529 || m_type == mst_file_bss;
532 /* See symtab.h. */
534 bool
535 minimal_symbol::text_p () const
537 return m_type == mst_text
538 || m_type == mst_text_gnu_ifunc
539 || m_type == mst_data_gnu_ifunc
540 || m_type == mst_slot_got_plt
541 || m_type == mst_solib_trampoline
542 || m_type == mst_file_text;
545 /* See symtab.h. */
547 bool
548 minimal_symbol::maybe_copied (objfile *objfile) const
550 return (objfile->object_format_has_copy_relocs
551 && (objfile->flags & OBJF_MAINLINE) == 0
552 && (m_type == mst_data || m_type == mst_bss));
555 /* See whether FILENAME matches SEARCH_NAME using the rule that we
556 advertise to the user. (The manual's description of linespecs
557 describes what we advertise). Returns true if they match, false
558 otherwise. */
560 bool
561 compare_filenames_for_search (const char *filename, const char *search_name)
563 int len = strlen (filename);
564 size_t search_len = strlen (search_name);
566 if (len < search_len)
567 return false;
569 /* The tail of FILENAME must match. */
570 if (FILENAME_CMP (filename + len - search_len, search_name) != 0)
571 return false;
573 /* Either the names must completely match, or the character
574 preceding the trailing SEARCH_NAME segment of FILENAME must be a
575 directory separator.
577 The check !IS_ABSOLUTE_PATH ensures SEARCH_NAME "/dir/file.c"
578 cannot match FILENAME "/path//dir/file.c" - as user has requested
579 absolute path. The sama applies for "c:\file.c" possibly
580 incorrectly hypothetically matching "d:\dir\c:\file.c".
582 The HAS_DRIVE_SPEC purpose is to make FILENAME "c:file.c"
583 compatible with SEARCH_NAME "file.c". In such case a compiler had
584 to put the "c:file.c" name into debug info. Such compatibility
585 works only on GDB built for DOS host. */
586 return (len == search_len
587 || (!IS_ABSOLUTE_PATH (search_name)
588 && IS_DIR_SEPARATOR (filename[len - search_len - 1]))
589 || (HAS_DRIVE_SPEC (filename)
590 && STRIP_DRIVE_SPEC (filename) == &filename[len - search_len]));
593 /* Same as compare_filenames_for_search, but for glob-style patterns.
594 Heads up on the order of the arguments. They match the order of
595 compare_filenames_for_search, but it's the opposite of the order of
596 arguments to gdb_filename_fnmatch. */
598 bool
599 compare_glob_filenames_for_search (const char *filename,
600 const char *search_name)
602 /* We rely on the property of glob-style patterns with FNM_FILE_NAME that
603 all /s have to be explicitly specified. */
604 int file_path_elements = count_path_elements (filename);
605 int search_path_elements = count_path_elements (search_name);
607 if (search_path_elements > file_path_elements)
608 return false;
610 if (IS_ABSOLUTE_PATH (search_name))
612 return (search_path_elements == file_path_elements
613 && gdb_filename_fnmatch (search_name, filename,
614 FNM_FILE_NAME | FNM_NOESCAPE) == 0);
618 const char *file_to_compare
619 = strip_leading_path_elements (filename,
620 file_path_elements - search_path_elements);
622 return gdb_filename_fnmatch (search_name, file_to_compare,
623 FNM_FILE_NAME | FNM_NOESCAPE) == 0;
627 /* Check for a symtab of a specific name by searching some symtabs.
628 This is a helper function for callbacks of iterate_over_symtabs.
630 If NAME is not absolute, then REAL_PATH is NULL
631 If NAME is absolute, then REAL_PATH is the gdb_realpath form of NAME.
633 The return value, NAME, REAL_PATH and CALLBACK are identical to the
634 `map_symtabs_matching_filename' method of quick_symbol_functions.
636 FIRST and AFTER_LAST indicate the range of compunit symtabs to search.
637 Each symtab within the specified compunit symtab is also searched.
638 AFTER_LAST is one past the last compunit symtab to search; NULL means to
639 search until the end of the list. */
641 bool
642 iterate_over_some_symtabs (const char *name,
643 const char *real_path,
644 struct compunit_symtab *first,
645 struct compunit_symtab *after_last,
646 gdb::function_view<bool (symtab *)> callback)
648 struct compunit_symtab *cust;
649 const char* base_name = lbasename (name);
651 for (cust = first; cust != NULL && cust != after_last; cust = cust->next)
653 /* Skip included compunits. */
654 if (cust->user != nullptr)
655 continue;
657 for (symtab *s : cust->filetabs ())
659 if (compare_filenames_for_search (s->filename, name))
661 if (callback (s))
662 return true;
663 continue;
666 /* Before we invoke realpath, which can get expensive when many
667 files are involved, do a quick comparison of the basenames. */
668 if (! basenames_may_differ
669 && FILENAME_CMP (base_name, lbasename (s->filename)) != 0)
670 continue;
672 if (compare_filenames_for_search (symtab_to_fullname (s), name))
674 if (callback (s))
675 return true;
676 continue;
679 /* If the user gave us an absolute path, try to find the file in
680 this symtab and use its absolute path. */
681 if (real_path != NULL)
683 const char *fullname = symtab_to_fullname (s);
685 gdb_assert (IS_ABSOLUTE_PATH (real_path));
686 gdb_assert (IS_ABSOLUTE_PATH (name));
687 gdb::unique_xmalloc_ptr<char> fullname_real_path
688 = gdb_realpath (fullname);
689 fullname = fullname_real_path.get ();
690 if (FILENAME_CMP (real_path, fullname) == 0)
692 if (callback (s))
693 return true;
694 continue;
700 return false;
703 /* See symtab.h. */
705 void
706 iterate_over_symtabs (program_space *pspace, const char *name,
707 gdb::function_view<bool (symtab *)> callback)
709 gdb::unique_xmalloc_ptr<char> real_path;
711 /* Here we are interested in canonicalizing an absolute path, not
712 absolutizing a relative path. */
713 if (IS_ABSOLUTE_PATH (name))
715 real_path = gdb_realpath (name);
716 gdb_assert (IS_ABSOLUTE_PATH (real_path.get ()));
719 for (objfile *objfile : pspace->objfiles ())
720 if (iterate_over_some_symtabs (name, real_path.get (),
721 objfile->compunit_symtabs, nullptr,
722 callback))
723 return;
725 /* Same search rules as above apply here, but now we look through the
726 psymtabs. */
727 for (objfile *objfile : pspace->objfiles ())
728 if (objfile->map_symtabs_matching_filename (name, real_path.get (),
729 callback))
730 return;
733 /* See symtab.h. */
735 symtab *
736 lookup_symtab (program_space *pspace, const char *name)
738 struct symtab *result = NULL;
740 iterate_over_symtabs (pspace, name, [&] (symtab *symtab)
742 result = symtab;
743 return true;
746 return result;
750 /* Mangle a GDB method stub type. This actually reassembles the pieces of the
751 full method name, which consist of the class name (from T), the unadorned
752 method name from METHOD_ID, and the signature for the specific overload,
753 specified by SIGNATURE_ID. Note that this function is g++ specific. */
755 char *
756 gdb_mangle_name (struct type *type, int method_id, int signature_id)
758 int mangled_name_len;
759 char *mangled_name;
760 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
761 struct fn_field *method = &f[signature_id];
762 const char *field_name = TYPE_FN_FIELDLIST_NAME (type, method_id);
763 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, signature_id);
764 const char *newname = type->name ();
766 /* Does the form of physname indicate that it is the full mangled name
767 of a constructor (not just the args)? */
768 int is_full_physname_constructor;
770 int is_constructor;
771 int is_destructor = is_destructor_name (physname);
772 /* Need a new type prefix. */
773 const char *const_prefix = method->is_const ? "C" : "";
774 const char *volatile_prefix = method->is_volatile ? "V" : "";
775 char buf[20];
776 int len = (newname == NULL ? 0 : strlen (newname));
778 /* Nothing to do if physname already contains a fully mangled v3 abi name
779 or an operator name. */
780 if ((physname[0] == '_' && physname[1] == 'Z')
781 || is_operator_name (field_name))
782 return xstrdup (physname);
784 is_full_physname_constructor = is_constructor_name (physname);
786 is_constructor = is_full_physname_constructor
787 || (newname && strcmp (field_name, newname) == 0);
789 if (!is_destructor)
790 is_destructor = (startswith (physname, "__dt"));
792 if (is_destructor || is_full_physname_constructor)
794 mangled_name = (char *) xmalloc (strlen (physname) + 1);
795 strcpy (mangled_name, physname);
796 return mangled_name;
799 if (len == 0)
801 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
803 else if (physname[0] == 't' || physname[0] == 'Q')
805 /* The physname for template and qualified methods already includes
806 the class name. */
807 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
808 newname = NULL;
809 len = 0;
811 else
813 xsnprintf (buf, sizeof (buf), "__%s%s%d", const_prefix,
814 volatile_prefix, len);
816 mangled_name_len = ((is_constructor ? 0 : strlen (field_name))
817 + strlen (buf) + len + strlen (physname) + 1);
819 mangled_name = (char *) xmalloc (mangled_name_len);
820 if (is_constructor)
821 mangled_name[0] = '\0';
822 else
823 strcpy (mangled_name, field_name);
825 strcat (mangled_name, buf);
826 /* If the class doesn't have a name, i.e. newname NULL, then we just
827 mangle it using 0 for the length of the class. Thus it gets mangled
828 as something starting with `::' rather than `classname::'. */
829 if (newname != NULL)
830 strcat (mangled_name, newname);
832 strcat (mangled_name, physname);
833 return (mangled_name);
836 /* See symtab.h. */
838 void
839 general_symbol_info::set_demangled_name (const char *name,
840 struct obstack *obstack)
842 if (language () == language_ada)
844 if (name == NULL)
846 ada_mangled = 0;
847 language_specific.obstack = obstack;
849 else
851 ada_mangled = 1;
852 language_specific.demangled_name = name;
855 else
856 language_specific.demangled_name = name;
860 /* Initialize the language dependent portion of a symbol
861 depending upon the language for the symbol. */
863 void
864 general_symbol_info::set_language (enum language language,
865 struct obstack *obstack)
867 m_language = language;
868 if (language == language_cplus
869 || language == language_d
870 || language == language_go
871 || language == language_objc
872 || language == language_fortran)
874 set_demangled_name (NULL, obstack);
876 else if (language == language_ada)
878 gdb_assert (ada_mangled == 0);
879 language_specific.obstack = obstack;
881 else
883 memset (&language_specific, 0, sizeof (language_specific));
887 /* Functions to initialize a symbol's mangled name. */
889 /* Objects of this type are stored in the demangled name hash table. */
890 struct demangled_name_entry
892 demangled_name_entry (std::string_view mangled_name)
893 : mangled (mangled_name) {}
895 std::string_view mangled;
896 enum language language;
897 gdb::unique_xmalloc_ptr<char> demangled;
900 /* Hash function for the demangled name hash. */
902 static hashval_t
903 hash_demangled_name_entry (const void *data)
905 const struct demangled_name_entry *e
906 = (const struct demangled_name_entry *) data;
908 return gdb::string_view_hash () (e->mangled);
911 /* Equality function for the demangled name hash. */
913 static int
914 eq_demangled_name_entry (const void *a, const void *b)
916 const struct demangled_name_entry *da
917 = (const struct demangled_name_entry *) a;
918 const struct demangled_name_entry *db
919 = (const struct demangled_name_entry *) b;
921 return da->mangled == db->mangled;
924 static void
925 free_demangled_name_entry (void *data)
927 struct demangled_name_entry *e
928 = (struct demangled_name_entry *) data;
930 e->~demangled_name_entry();
933 /* Create the hash table used for demangled names. Each hash entry is
934 a pair of strings; one for the mangled name and one for the demangled
935 name. The entry is hashed via just the mangled name. */
937 static void
938 create_demangled_names_hash (struct objfile_per_bfd_storage *per_bfd)
940 /* Choose 256 as the starting size of the hash table, somewhat arbitrarily.
941 The hash table code will round this up to the next prime number.
942 Choosing a much larger table size wastes memory, and saves only about
943 1% in symbol reading. However, if the minsym count is already
944 initialized (e.g. because symbol name setting was deferred to
945 a background thread) we can initialize the hashtable with a count
946 based on that, because we will almost certainly have at least that
947 many entries. If we have a nonzero number but less than 256,
948 we still stay with 256 to have some space for psymbols, etc. */
950 /* htab will expand the table when it is 3/4th full, so we account for that
951 here. +2 to round up. */
952 int minsym_based_count = (per_bfd->minimal_symbol_count + 2) / 3 * 4;
953 int count = std::max (per_bfd->minimal_symbol_count, minsym_based_count);
955 per_bfd->demangled_names_hash.reset (htab_create_alloc
956 (count, hash_demangled_name_entry, eq_demangled_name_entry,
957 free_demangled_name_entry, xcalloc, xfree));
960 /* See symtab.h */
962 gdb::unique_xmalloc_ptr<char>
963 symbol_find_demangled_name (struct general_symbol_info *gsymbol,
964 const char *mangled)
966 gdb::unique_xmalloc_ptr<char> demangled;
967 int i;
969 if (gsymbol->language () != language_unknown)
971 const struct language_defn *lang = language_def (gsymbol->language ());
973 lang->sniff_from_mangled_name (mangled, &demangled);
974 return demangled;
977 for (i = language_unknown; i < nr_languages; ++i)
979 enum language l = (enum language) i;
980 const struct language_defn *lang = language_def (l);
982 if (lang->sniff_from_mangled_name (mangled, &demangled))
984 gsymbol->m_language = l;
985 return demangled;
989 return NULL;
992 /* Set both the mangled and demangled (if any) names for GSYMBOL based
993 on LINKAGE_NAME and LEN. Ordinarily, NAME is copied onto the
994 objfile's obstack; but if COPY_NAME is 0 and if NAME is
995 NUL-terminated, then this function assumes that NAME is already
996 correctly saved (either permanently or with a lifetime tied to the
997 objfile), and it will not be copied.
999 The hash table corresponding to OBJFILE is used, and the memory
1000 comes from the per-BFD storage_obstack. LINKAGE_NAME is copied,
1001 so the pointer can be discarded after calling this function. */
1003 void
1004 general_symbol_info::compute_and_set_names (std::string_view linkage_name,
1005 bool copy_name,
1006 objfile_per_bfd_storage *per_bfd,
1007 std::optional<hashval_t> hash)
1009 struct demangled_name_entry **slot;
1011 if (language () == language_ada)
1013 /* In Ada, we do the symbol lookups using the mangled name, so
1014 we can save some space by not storing the demangled name. */
1015 if (!copy_name)
1016 m_name = linkage_name.data ();
1017 else
1018 m_name = obstack_strndup (&per_bfd->storage_obstack,
1019 linkage_name.data (),
1020 linkage_name.length ());
1021 set_demangled_name (NULL, &per_bfd->storage_obstack);
1023 return;
1026 if (per_bfd->demangled_names_hash == NULL)
1027 create_demangled_names_hash (per_bfd);
1029 struct demangled_name_entry entry (linkage_name);
1030 if (!hash.has_value ())
1031 hash = hash_demangled_name_entry (&entry);
1032 slot = ((struct demangled_name_entry **)
1033 htab_find_slot_with_hash (per_bfd->demangled_names_hash.get (),
1034 &entry, *hash, INSERT));
1036 /* The const_cast is safe because the only reason it is already
1037 initialized is if we purposefully set it from a background
1038 thread to avoid doing the work here. However, it is still
1039 allocated from the heap and needs to be freed by us, just
1040 like if we called symbol_find_demangled_name here. If this is
1041 nullptr, we call symbol_find_demangled_name below, but we put
1042 this smart pointer here to be sure that we don't leak this name. */
1043 gdb::unique_xmalloc_ptr<char> demangled_name
1044 (const_cast<char *> (language_specific.demangled_name));
1046 /* If this name is not in the hash table, add it. */
1047 if (*slot == NULL
1048 /* A C version of the symbol may have already snuck into the table.
1049 This happens to, e.g., main.init (__go_init_main). Cope. */
1050 || (language () == language_go && (*slot)->demangled == nullptr))
1052 /* A 0-terminated copy of the linkage name. Callers must set COPY_NAME
1053 to true if the string might not be nullterminated. We have to make
1054 this copy because demangling needs a nullterminated string. */
1055 std::string_view linkage_name_copy;
1056 if (copy_name)
1058 char *alloc_name = (char *) alloca (linkage_name.length () + 1);
1059 memcpy (alloc_name, linkage_name.data (), linkage_name.length ());
1060 alloc_name[linkage_name.length ()] = '\0';
1062 linkage_name_copy = std::string_view (alloc_name,
1063 linkage_name.length ());
1065 else
1066 linkage_name_copy = linkage_name;
1068 if (demangled_name.get () == nullptr)
1069 demangled_name
1070 = symbol_find_demangled_name (this, linkage_name_copy.data ());
1072 /* Suppose we have demangled_name==NULL, copy_name==0, and
1073 linkage_name_copy==linkage_name. In this case, we already have the
1074 mangled name saved, and we don't have a demangled name. So,
1075 you might think we could save a little space by not recording
1076 this in the hash table at all.
1078 It turns out that it is actually important to still save such
1079 an entry in the hash table, because storing this name gives
1080 us better bcache hit rates for partial symbols. */
1081 if (!copy_name)
1083 *slot
1084 = ((struct demangled_name_entry *)
1085 obstack_alloc (&per_bfd->storage_obstack,
1086 sizeof (demangled_name_entry)));
1087 new (*slot) demangled_name_entry (linkage_name);
1089 else
1091 /* If we must copy the mangled name, put it directly after
1092 the struct so we can have a single allocation. */
1093 *slot
1094 = ((struct demangled_name_entry *)
1095 obstack_alloc (&per_bfd->storage_obstack,
1096 sizeof (demangled_name_entry)
1097 + linkage_name.length () + 1));
1098 char *mangled_ptr = reinterpret_cast<char *> (*slot + 1);
1099 memcpy (mangled_ptr, linkage_name.data (), linkage_name.length ());
1100 mangled_ptr [linkage_name.length ()] = '\0';
1101 new (*slot) demangled_name_entry
1102 (std::string_view (mangled_ptr, linkage_name.length ()));
1104 (*slot)->demangled = std::move (demangled_name);
1105 (*slot)->language = language ();
1107 else if (language () == language_unknown)
1108 m_language = (*slot)->language;
1110 m_name = (*slot)->mangled.data ();
1111 set_demangled_name ((*slot)->demangled.get (), &per_bfd->storage_obstack);
1114 /* See symtab.h. */
1116 const char *
1117 general_symbol_info::natural_name () const
1119 switch (language ())
1121 case language_cplus:
1122 case language_d:
1123 case language_go:
1124 case language_objc:
1125 case language_fortran:
1126 case language_rust:
1127 if (language_specific.demangled_name != nullptr)
1128 return language_specific.demangled_name;
1129 break;
1130 case language_ada:
1131 return ada_decode_symbol (this);
1132 default:
1133 break;
1135 return linkage_name ();
1138 /* See symtab.h. */
1140 const char *
1141 general_symbol_info::demangled_name () const
1143 const char *dem_name = NULL;
1145 switch (language ())
1147 case language_cplus:
1148 case language_d:
1149 case language_go:
1150 case language_objc:
1151 case language_fortran:
1152 case language_rust:
1153 dem_name = language_specific.demangled_name;
1154 break;
1155 case language_ada:
1156 dem_name = ada_decode_symbol (this);
1157 break;
1158 default:
1159 break;
1161 return dem_name;
1164 /* See symtab.h. */
1166 const char *
1167 general_symbol_info::search_name () const
1169 if (language () == language_ada)
1170 return linkage_name ();
1171 else
1172 return natural_name ();
1175 /* See symtab.h. */
1177 struct obj_section *
1178 general_symbol_info::obj_section (const struct objfile *objfile) const
1180 if (section_index () >= 0)
1181 return &objfile->sections_start[section_index ()];
1182 return nullptr;
1185 /* See symtab.h. */
1187 bool
1188 symbol_matches_search_name (const struct general_symbol_info *gsymbol,
1189 const lookup_name_info &name)
1191 symbol_name_matcher_ftype *name_match
1192 = language_def (gsymbol->language ())->get_symbol_name_matcher (name);
1193 return name_match (gsymbol->search_name (), name, NULL);
1198 /* Return true if the two sections are the same, or if they could
1199 plausibly be copies of each other, one in an original object
1200 file and another in a separated debug file. */
1202 bool
1203 matching_obj_sections (struct obj_section *obj_first,
1204 struct obj_section *obj_second)
1206 asection *first = obj_first? obj_first->the_bfd_section : NULL;
1207 asection *second = obj_second? obj_second->the_bfd_section : NULL;
1209 /* If they're the same section, then they match. */
1210 if (first == second)
1211 return true;
1213 /* If either is NULL, give up. */
1214 if (first == NULL || second == NULL)
1215 return false;
1217 /* This doesn't apply to absolute symbols. */
1218 if (first->owner == NULL || second->owner == NULL)
1219 return false;
1221 /* If they're in the same object file, they must be different sections. */
1222 if (first->owner == second->owner)
1223 return false;
1225 /* Check whether the two sections are potentially corresponding. They must
1226 have the same size, address, and name. We can't compare section indexes,
1227 which would be more reliable, because some sections may have been
1228 stripped. */
1229 if (bfd_section_size (first) != bfd_section_size (second))
1230 return false;
1232 /* In-memory addresses may start at a different offset, relativize them. */
1233 if (bfd_section_vma (first) - bfd_get_start_address (first->owner)
1234 != bfd_section_vma (second) - bfd_get_start_address (second->owner))
1235 return false;
1237 if (bfd_section_name (first) == NULL
1238 || bfd_section_name (second) == NULL
1239 || strcmp (bfd_section_name (first), bfd_section_name (second)) != 0)
1240 return false;
1242 /* Otherwise check that they are in corresponding objfiles. */
1244 struct objfile *obj = NULL;
1245 for (objfile *objfile : current_program_space->objfiles ())
1246 if (objfile->obfd == first->owner)
1248 obj = objfile;
1249 break;
1251 gdb_assert (obj != NULL);
1253 if (obj->separate_debug_objfile != NULL
1254 && obj->separate_debug_objfile->obfd == second->owner)
1255 return true;
1256 if (obj->separate_debug_objfile_backlink != NULL
1257 && obj->separate_debug_objfile_backlink->obfd == second->owner)
1258 return true;
1260 return false;
1263 /* Hash function for the symbol cache. */
1265 static unsigned int
1266 hash_symbol_entry (const struct objfile *objfile_context,
1267 const char *name, domain_search_flags domain)
1269 unsigned int hash = (uintptr_t) objfile_context;
1271 if (name != NULL)
1272 hash += htab_hash_string (name);
1274 hash += domain * 7;
1276 return hash;
1279 /* Equality function for the symbol cache. */
1281 static int
1282 eq_symbol_entry (const struct symbol_cache_slot *slot,
1283 const struct objfile *objfile_context,
1284 const char *name, domain_search_flags domain)
1286 const char *slot_name;
1288 if (slot->state == SYMBOL_SLOT_UNUSED)
1289 return 0;
1291 if (slot->objfile_context != objfile_context)
1292 return 0;
1294 domain_search_flags slot_domain = slot->domain;
1295 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1296 slot_name = slot->value.name;
1297 else
1298 slot_name = slot->value.found.symbol->search_name ();
1300 /* NULL names match. */
1301 if (slot_name == NULL && name == NULL)
1303 /* But there's no point in calling symbol_matches_domain in the
1304 SYMBOL_SLOT_FOUND case. */
1305 if (slot_domain != domain)
1306 return 0;
1308 else if (slot_name != NULL && name != NULL)
1310 /* It's important that we use the same comparison that was done
1311 the first time through. If the slot records a found symbol,
1312 then this means using the symbol name comparison function of
1313 the symbol's language with symbol->search_name (). See
1314 dictionary.c.
1316 If the slot records a not-found symbol, then require a precise match.
1317 We could still be lax with whitespace like strcmp_iw though. */
1319 if (slot_domain != domain)
1320 return 0;
1322 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1324 if (strcmp (slot_name, name) != 0)
1325 return 0;
1327 else
1329 struct symbol *sym = slot->value.found.symbol;
1330 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1332 if (!symbol_matches_search_name (sym, lookup_name))
1333 return 0;
1336 else
1338 /* Only one name is NULL. */
1339 return 0;
1342 return 1;
1345 /* Given a cache of size SIZE, return the size of the struct (with variable
1346 length array) in bytes. */
1348 static size_t
1349 symbol_cache_byte_size (unsigned int size)
1351 return (sizeof (struct block_symbol_cache)
1352 + ((size - 1) * sizeof (struct symbol_cache_slot)));
1355 /* Resize CACHE. */
1357 static void
1358 resize_symbol_cache (struct symbol_cache *cache, unsigned int new_size)
1360 /* If there's no change in size, don't do anything.
1361 All caches have the same size, so we can just compare with the size
1362 of the global symbols cache. */
1363 if ((cache->global_symbols != NULL
1364 && cache->global_symbols->size == new_size)
1365 || (cache->global_symbols == NULL
1366 && new_size == 0))
1367 return;
1369 destroy_block_symbol_cache (cache->global_symbols);
1370 destroy_block_symbol_cache (cache->static_symbols);
1372 if (new_size == 0)
1374 cache->global_symbols = NULL;
1375 cache->static_symbols = NULL;
1377 else
1379 size_t total_size = symbol_cache_byte_size (new_size);
1381 cache->global_symbols
1382 = (struct block_symbol_cache *) xcalloc (1, total_size);
1383 cache->static_symbols
1384 = (struct block_symbol_cache *) xcalloc (1, total_size);
1385 cache->global_symbols->size = new_size;
1386 cache->static_symbols->size = new_size;
1390 /* Return the symbol cache of PSPACE.
1391 Create one if it doesn't exist yet. */
1393 static struct symbol_cache *
1394 get_symbol_cache (struct program_space *pspace)
1396 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1398 if (cache == NULL)
1400 cache = symbol_cache_key.emplace (pspace);
1401 resize_symbol_cache (cache, symbol_cache_size);
1404 return cache;
1407 /* Set the size of the symbol cache in all program spaces. */
1409 static void
1410 set_symbol_cache_size (unsigned int new_size)
1412 for (struct program_space *pspace : program_spaces)
1414 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1416 /* The pspace could have been created but not have a cache yet. */
1417 if (cache != NULL)
1418 resize_symbol_cache (cache, new_size);
1422 /* Called when symbol-cache-size is set. */
1424 static void
1425 set_symbol_cache_size_handler (const char *args, int from_tty,
1426 struct cmd_list_element *c)
1428 if (new_symbol_cache_size > MAX_SYMBOL_CACHE_SIZE)
1430 /* Restore the previous value.
1431 This is the value the "show" command prints. */
1432 new_symbol_cache_size = symbol_cache_size;
1434 error (_("Symbol cache size is too large, max is %u."),
1435 MAX_SYMBOL_CACHE_SIZE);
1437 symbol_cache_size = new_symbol_cache_size;
1439 set_symbol_cache_size (symbol_cache_size);
1442 /* Lookup symbol NAME,DOMAIN in BLOCK in the symbol cache of PSPACE.
1443 OBJFILE_CONTEXT is the current objfile, which may be NULL.
1444 The result is the symbol if found, SYMBOL_LOOKUP_FAILED if a previous lookup
1445 failed (and thus this one will too), or NULL if the symbol is not present
1446 in the cache.
1447 *BSC_PTR and *SLOT_PTR are set to the cache and slot of the symbol, which
1448 can be used to save the result of a full lookup attempt. */
1450 static struct block_symbol
1451 symbol_cache_lookup (struct symbol_cache *cache,
1452 struct objfile *objfile_context, enum block_enum block,
1453 const char *name, domain_search_flags domain,
1454 struct block_symbol_cache **bsc_ptr,
1455 struct symbol_cache_slot **slot_ptr)
1457 struct block_symbol_cache *bsc;
1458 unsigned int hash;
1459 struct symbol_cache_slot *slot;
1461 if (block == GLOBAL_BLOCK)
1462 bsc = cache->global_symbols;
1463 else
1464 bsc = cache->static_symbols;
1465 if (bsc == NULL)
1467 *bsc_ptr = NULL;
1468 *slot_ptr = NULL;
1469 return {};
1472 hash = hash_symbol_entry (objfile_context, name, domain);
1473 slot = bsc->symbols + hash % bsc->size;
1475 *bsc_ptr = bsc;
1476 *slot_ptr = slot;
1478 if (eq_symbol_entry (slot, objfile_context, name, domain))
1480 symbol_lookup_debug_printf ("%s block symbol cache hit%s for %s, %s",
1481 block == GLOBAL_BLOCK ? "Global" : "Static",
1482 slot->state == SYMBOL_SLOT_NOT_FOUND
1483 ? " (not found)" : "", name,
1484 domain_name (domain).c_str ());
1485 ++bsc->hits;
1486 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1487 return SYMBOL_LOOKUP_FAILED;
1488 return slot->value.found;
1491 /* Symbol is not present in the cache. */
1493 symbol_lookup_debug_printf ("%s block symbol cache miss for %s, %s",
1494 block == GLOBAL_BLOCK ? "Global" : "Static",
1495 name, domain_name (domain).c_str ());
1496 ++bsc->misses;
1497 return {};
1500 /* Mark SYMBOL as found in SLOT.
1501 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1502 if it's not needed to distinguish lookups (STATIC_BLOCK). It is *not*
1503 necessarily the objfile the symbol was found in. */
1505 static void
1506 symbol_cache_mark_found (struct block_symbol_cache *bsc,
1507 struct symbol_cache_slot *slot,
1508 struct objfile *objfile_context,
1509 struct symbol *symbol,
1510 const struct block *block,
1511 domain_search_flags domain)
1513 if (bsc == NULL)
1514 return;
1515 if (slot->state != SYMBOL_SLOT_UNUSED)
1517 ++bsc->collisions;
1518 symbol_cache_clear_slot (slot);
1520 slot->state = SYMBOL_SLOT_FOUND;
1521 slot->objfile_context = objfile_context;
1522 slot->value.found.symbol = symbol;
1523 slot->value.found.block = block;
1524 slot->domain = domain;
1527 /* Mark symbol NAME, DOMAIN as not found in SLOT.
1528 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1529 if it's not needed to distinguish lookups (STATIC_BLOCK). */
1531 static void
1532 symbol_cache_mark_not_found (struct block_symbol_cache *bsc,
1533 struct symbol_cache_slot *slot,
1534 struct objfile *objfile_context,
1535 const char *name, domain_search_flags domain)
1537 if (bsc == NULL)
1538 return;
1539 if (slot->state != SYMBOL_SLOT_UNUSED)
1541 ++bsc->collisions;
1542 symbol_cache_clear_slot (slot);
1544 slot->state = SYMBOL_SLOT_NOT_FOUND;
1545 slot->objfile_context = objfile_context;
1546 slot->value.name = xstrdup (name);
1547 slot->domain = domain;
1550 /* Flush the symbol cache of PSPACE. */
1552 static void
1553 symbol_cache_flush (struct program_space *pspace)
1555 ada_clear_symbol_cache (pspace);
1556 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1557 int pass;
1559 if (cache == NULL)
1560 return;
1561 if (cache->global_symbols == NULL)
1563 gdb_assert (symbol_cache_size == 0);
1564 gdb_assert (cache->static_symbols == NULL);
1565 return;
1568 /* If the cache is untouched since the last flush, early exit.
1569 This is important for performance during the startup of a program linked
1570 with 100s (or 1000s) of shared libraries. */
1571 if (cache->global_symbols->misses == 0
1572 && cache->static_symbols->misses == 0)
1573 return;
1575 gdb_assert (cache->global_symbols->size == symbol_cache_size);
1576 gdb_assert (cache->static_symbols->size == symbol_cache_size);
1578 for (pass = 0; pass < 2; ++pass)
1580 struct block_symbol_cache *bsc
1581 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1582 unsigned int i;
1584 for (i = 0; i < bsc->size; ++i)
1585 symbol_cache_clear_slot (&bsc->symbols[i]);
1588 cache->global_symbols->hits = 0;
1589 cache->global_symbols->misses = 0;
1590 cache->global_symbols->collisions = 0;
1591 cache->static_symbols->hits = 0;
1592 cache->static_symbols->misses = 0;
1593 cache->static_symbols->collisions = 0;
1596 /* Dump CACHE. */
1598 static void
1599 symbol_cache_dump (const struct symbol_cache *cache)
1601 int pass;
1603 if (cache->global_symbols == NULL)
1605 gdb_printf (" <disabled>\n");
1606 return;
1609 for (pass = 0; pass < 2; ++pass)
1611 const struct block_symbol_cache *bsc
1612 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1613 unsigned int i;
1615 if (pass == 0)
1616 gdb_printf ("Global symbols:\n");
1617 else
1618 gdb_printf ("Static symbols:\n");
1620 for (i = 0; i < bsc->size; ++i)
1622 const struct symbol_cache_slot *slot = &bsc->symbols[i];
1624 QUIT;
1626 switch (slot->state)
1628 case SYMBOL_SLOT_UNUSED:
1629 break;
1630 case SYMBOL_SLOT_NOT_FOUND:
1631 gdb_printf (" [%4u] = %s, %s %s (not found)\n", i,
1632 host_address_to_string (slot->objfile_context),
1633 slot->value.name,
1634 domain_name (slot->domain).c_str ());
1635 break;
1636 case SYMBOL_SLOT_FOUND:
1638 struct symbol *found = slot->value.found.symbol;
1639 const struct objfile *context = slot->objfile_context;
1641 gdb_printf (" [%4u] = %s, %s %s\n", i,
1642 host_address_to_string (context),
1643 found->print_name (),
1644 domain_name (found->domain ()));
1645 break;
1652 /* The "mt print symbol-cache" command. */
1654 static void
1655 maintenance_print_symbol_cache (const char *args, int from_tty)
1657 for (struct program_space *pspace : program_spaces)
1659 struct symbol_cache *cache;
1661 gdb_printf (_("Symbol cache for pspace %d\n%s:\n"),
1662 pspace->num,
1663 pspace->symfile_object_file != NULL
1664 ? objfile_name (pspace->symfile_object_file)
1665 : "(no object file)");
1667 /* If the cache hasn't been created yet, avoid creating one. */
1668 cache = symbol_cache_key.get (pspace);
1669 if (cache == NULL)
1670 gdb_printf (" <empty>\n");
1671 else
1672 symbol_cache_dump (cache);
1676 /* The "mt flush-symbol-cache" command. */
1678 static void
1679 maintenance_flush_symbol_cache (const char *args, int from_tty)
1681 for (struct program_space *pspace : program_spaces)
1683 symbol_cache_flush (pspace);
1687 /* Print usage statistics of CACHE. */
1689 static void
1690 symbol_cache_stats (struct symbol_cache *cache)
1692 int pass;
1694 if (cache->global_symbols == NULL)
1696 gdb_printf (" <disabled>\n");
1697 return;
1700 for (pass = 0; pass < 2; ++pass)
1702 const struct block_symbol_cache *bsc
1703 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1705 QUIT;
1707 if (pass == 0)
1708 gdb_printf ("Global block cache stats:\n");
1709 else
1710 gdb_printf ("Static block cache stats:\n");
1712 gdb_printf (" size: %u\n", bsc->size);
1713 gdb_printf (" hits: %u\n", bsc->hits);
1714 gdb_printf (" misses: %u\n", bsc->misses);
1715 gdb_printf (" collisions: %u\n", bsc->collisions);
1719 /* The "mt print symbol-cache-statistics" command. */
1721 static void
1722 maintenance_print_symbol_cache_statistics (const char *args, int from_tty)
1724 for (struct program_space *pspace : program_spaces)
1726 struct symbol_cache *cache;
1728 gdb_printf (_("Symbol cache statistics for pspace %d\n%s:\n"),
1729 pspace->num,
1730 pspace->symfile_object_file != NULL
1731 ? objfile_name (pspace->symfile_object_file)
1732 : "(no object file)");
1734 /* If the cache hasn't been created yet, avoid creating one. */
1735 cache = symbol_cache_key.get (pspace);
1736 if (cache == NULL)
1737 gdb_printf (" empty, no stats available\n");
1738 else
1739 symbol_cache_stats (cache);
1743 /* This module's 'new_objfile' observer. */
1745 static void
1746 symtab_new_objfile_observer (struct objfile *objfile)
1748 symbol_cache_flush (objfile->pspace ());
1751 /* This module's 'all_objfiles_removed' observer. */
1753 static void
1754 symtab_all_objfiles_removed (program_space *pspace)
1756 symbol_cache_flush (pspace);
1758 /* Forget everything we know about the main function. */
1759 main_progspace_key.clear (pspace);
1762 /* This module's 'free_objfile' observer. */
1764 static void
1765 symtab_free_objfile_observer (struct objfile *objfile)
1767 symbol_cache_flush (objfile->pspace ());
1770 /* See symtab.h. */
1772 void
1773 fixup_symbol_section (struct symbol *sym, struct objfile *objfile)
1775 gdb_assert (sym != nullptr);
1776 gdb_assert (sym->is_objfile_owned ());
1777 gdb_assert (objfile != nullptr);
1778 gdb_assert (sym->section_index () == -1);
1780 /* Note that if this ends up as -1, fixup_section will handle that
1781 reasonably well. So, it's fine to use the objfile's section
1782 index without doing the check that is done by the wrapper macros
1783 like SECT_OFF_TEXT. */
1784 int fallback;
1785 switch (sym->aclass ())
1787 case LOC_STATIC:
1788 fallback = objfile->sect_index_data;
1789 break;
1791 case LOC_LABEL:
1792 fallback = objfile->sect_index_text;
1793 break;
1795 default:
1796 /* Nothing else will be listed in the minsyms -- no use looking
1797 it up. */
1798 return;
1801 CORE_ADDR addr = sym->value_address ();
1803 struct minimal_symbol *msym;
1805 /* First, check whether a minimal symbol with the same name exists
1806 and points to the same address. The address check is required
1807 e.g. on PowerPC64, where the minimal symbol for a function will
1808 point to the function descriptor, while the debug symbol will
1809 point to the actual function code. */
1810 msym = lookup_minimal_symbol_by_pc_name (addr, sym->linkage_name (),
1811 objfile);
1812 if (msym)
1813 sym->set_section_index (msym->section_index ());
1814 else
1816 /* Static, function-local variables do appear in the linker
1817 (minimal) symbols, but are frequently given names that won't
1818 be found via lookup_minimal_symbol(). E.g., it has been
1819 observed in frv-uclinux (ELF) executables that a static,
1820 function-local variable named "foo" might appear in the
1821 linker symbols as "foo.6" or "foo.3". Thus, there is no
1822 point in attempting to extend the lookup-by-name mechanism to
1823 handle this case due to the fact that there can be multiple
1824 names.
1826 So, instead, search the section table when lookup by name has
1827 failed. The ``addr'' and ``endaddr'' fields may have already
1828 been relocated. If so, the relocation offset needs to be
1829 subtracted from these values when performing the comparison.
1830 We unconditionally subtract it, because, when no relocation
1831 has been performed, the value will simply be zero.
1833 The address of the symbol whose section we're fixing up HAS
1834 NOT BEEN adjusted (relocated) yet. It can't have been since
1835 the section isn't yet known and knowing the section is
1836 necessary in order to add the correct relocation value. In
1837 other words, we wouldn't even be in this function (attempting
1838 to compute the section) if it were already known.
1840 Note that it is possible to search the minimal symbols
1841 (subtracting the relocation value if necessary) to find the
1842 matching minimal symbol, but this is overkill and much less
1843 efficient. It is not necessary to find the matching minimal
1844 symbol, only its section.
1846 Note that this technique (of doing a section table search)
1847 can fail when unrelocated section addresses overlap. For
1848 this reason, we still attempt a lookup by name prior to doing
1849 a search of the section table. */
1851 for (obj_section *s : objfile->sections ())
1853 if ((bfd_section_flags (s->the_bfd_section) & SEC_ALLOC) == 0)
1854 continue;
1856 int idx = s - objfile->sections_start;
1857 CORE_ADDR offset = objfile->section_offsets[idx];
1859 if (fallback == -1)
1860 fallback = idx;
1862 if (s->addr () - offset <= addr && addr < s->endaddr () - offset)
1864 sym->set_section_index (idx);
1865 return;
1869 /* If we didn't find the section, assume it is in the first
1870 section. If there is no allocated section, then it hardly
1871 matters what we pick, so just pick zero. */
1872 if (fallback == -1)
1873 sym->set_section_index (0);
1874 else
1875 sym->set_section_index (fallback);
1879 /* See symtab.h. */
1881 demangle_for_lookup_info::demangle_for_lookup_info
1882 (const lookup_name_info &lookup_name, language lang)
1884 demangle_result_storage storage;
1886 if (lookup_name.ignore_parameters () && lang == language_cplus)
1888 gdb::unique_xmalloc_ptr<char> without_params
1889 = cp_remove_params_if_any (lookup_name.c_str (),
1890 lookup_name.completion_mode ());
1892 if (without_params != NULL)
1894 if (lookup_name.match_type () != symbol_name_match_type::SEARCH_NAME)
1895 m_demangled_name = demangle_for_lookup (without_params.get (),
1896 lang, storage);
1897 return;
1901 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
1902 m_demangled_name = lookup_name.c_str ();
1903 else
1904 m_demangled_name = demangle_for_lookup (lookup_name.c_str (),
1905 lang, storage);
1908 /* See symtab.h. */
1910 const lookup_name_info &
1911 lookup_name_info::match_any ()
1913 /* Lookup any symbol that "" would complete. I.e., this matches all
1914 symbol names. */
1915 static const lookup_name_info lookup_name ("", symbol_name_match_type::FULL,
1916 true);
1918 return lookup_name;
1921 /* See symtab.h. */
1923 unsigned int
1924 lookup_name_info::search_name_hash (language lang) const
1926 /* This works around an obscure problem. If currently in Ada mode,
1927 and the name is wrapped in '<...>' (indicating verbatim mode),
1928 force the use of the Ada language here so that the '<' and '>'
1929 will be removed. */
1930 if (current_language->la_language == language_ada && ada ().verbatim_p ())
1931 lang = language_ada;
1933 /* Only compute each language's hash once. */
1934 if (!m_demangled_hashes_p[lang])
1936 m_demangled_hashes[lang]
1937 = ::search_name_hash (lang, language_lookup_name (lang));
1938 m_demangled_hashes_p[lang] = true;
1940 return m_demangled_hashes[lang];
1943 /* Compute the demangled form of NAME as used by the various symbol
1944 lookup functions. The result can either be the input NAME
1945 directly, or a pointer to a buffer owned by the STORAGE object.
1947 For Ada, this function just returns NAME, unmodified.
1948 Normally, Ada symbol lookups are performed using the encoded name
1949 rather than the demangled name, and so it might seem to make sense
1950 for this function to return an encoded version of NAME.
1951 Unfortunately, we cannot do this, because this function is used in
1952 circumstances where it is not appropriate to try to encode NAME.
1953 For instance, when displaying the frame info, we demangle the name
1954 of each parameter, and then perform a symbol lookup inside our
1955 function using that demangled name. In Ada, certain functions
1956 have internally-generated parameters whose name contain uppercase
1957 characters. Encoding those name would result in those uppercase
1958 characters to become lowercase, and thus cause the symbol lookup
1959 to fail. */
1961 const char *
1962 demangle_for_lookup (const char *name, enum language lang,
1963 demangle_result_storage &storage)
1965 /* If we are using C++, D, or Go, demangle the name before doing a
1966 lookup, so we can always binary search. */
1967 if (lang == language_cplus)
1969 gdb::unique_xmalloc_ptr<char> demangled_name
1970 = gdb_demangle (name, DMGL_ANSI | DMGL_PARAMS);
1971 if (demangled_name != NULL)
1972 return storage.set_malloc_ptr (std::move (demangled_name));
1974 /* If we were given a non-mangled name, canonicalize it
1975 according to the language (so far only for C++). */
1976 gdb::unique_xmalloc_ptr<char> canon = cp_canonicalize_string (name);
1977 if (canon != nullptr)
1978 return storage.set_malloc_ptr (std::move (canon));
1980 else if (lang == language_d)
1982 gdb::unique_xmalloc_ptr<char> demangled_name = d_demangle (name, 0);
1983 if (demangled_name != NULL)
1984 return storage.set_malloc_ptr (std::move (demangled_name));
1986 else if (lang == language_go)
1988 gdb::unique_xmalloc_ptr<char> demangled_name
1989 = language_def (language_go)->demangle_symbol (name, 0);
1990 if (demangled_name != NULL)
1991 return storage.set_malloc_ptr (std::move (demangled_name));
1994 return name;
1997 /* See symtab.h. */
1999 unsigned int
2000 search_name_hash (enum language language, const char *search_name)
2002 return language_def (language)->search_name_hash (search_name);
2005 /* See symtab.h.
2007 This function (or rather its subordinates) have a bunch of loops and
2008 it would seem to be attractive to put in some QUIT's (though I'm not really
2009 sure whether it can run long enough to be really important). But there
2010 are a few calls for which it would appear to be bad news to quit
2011 out of here: e.g., find_proc_desc in alpha-mdebug-tdep.c. (Note
2012 that there is C++ code below which can error(), but that probably
2013 doesn't affect these calls since they are looking for a known
2014 variable and thus can probably assume it will never hit the C++
2015 code). */
2017 struct block_symbol
2018 lookup_symbol_in_language (const char *name, const struct block *block,
2019 const domain_search_flags domain,
2020 enum language lang,
2021 struct field_of_this_result *is_a_field_of_this)
2023 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2025 demangle_result_storage storage;
2026 const char *modified_name = demangle_for_lookup (name, lang, storage);
2028 return lookup_symbol_aux (modified_name,
2029 symbol_name_match_type::FULL,
2030 block, domain, lang,
2031 is_a_field_of_this);
2034 /* See symtab.h. */
2036 struct block_symbol
2037 lookup_symbol (const char *name, const struct block *block,
2038 domain_search_flags domain,
2039 struct field_of_this_result *is_a_field_of_this)
2041 return lookup_symbol_in_language (name, block, domain,
2042 current_language->la_language,
2043 is_a_field_of_this);
2046 /* See symtab.h. */
2048 struct block_symbol
2049 lookup_symbol_search_name (const char *search_name, const struct block *block,
2050 domain_search_flags domain)
2052 return lookup_symbol_aux (search_name, symbol_name_match_type::SEARCH_NAME,
2053 block, domain, language_asm, NULL);
2056 /* See symtab.h. */
2058 struct block_symbol
2059 lookup_language_this (const struct language_defn *lang,
2060 const struct block *block)
2062 if (lang->name_of_this () == NULL || block == NULL)
2063 return {};
2065 symbol_lookup_debug_printf_v ("lookup_language_this (%s, %s (objfile %s))",
2066 lang->name (), host_address_to_string (block),
2067 objfile_debug_name (block->objfile ()));
2069 lookup_name_info this_name (lang->name_of_this (),
2070 symbol_name_match_type::SEARCH_NAME);
2072 while (block)
2074 struct symbol *sym;
2076 sym = block_lookup_symbol (block, this_name, SEARCH_VFT);
2077 if (sym != NULL)
2079 symbol_lookup_debug_printf_v
2080 ("lookup_language_this (...) = %s (%s, block %s)",
2081 sym->print_name (), host_address_to_string (sym),
2082 host_address_to_string (block));
2083 return (struct block_symbol) {sym, block};
2085 if (block->function ())
2086 break;
2087 block = block->superblock ();
2090 symbol_lookup_debug_printf_v ("lookup_language_this (...) = NULL");
2091 return {};
2094 /* Given TYPE, a structure/union,
2095 return 1 if the component named NAME from the ultimate target
2096 structure/union is defined, otherwise, return 0. */
2098 static int
2099 check_field (struct type *type, const char *name,
2100 struct field_of_this_result *is_a_field_of_this)
2102 int i;
2104 /* The type may be a stub. */
2105 type = check_typedef (type);
2107 for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
2109 const char *t_field_name = type->field (i).name ();
2111 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2113 is_a_field_of_this->type = type;
2114 is_a_field_of_this->field = &type->field (i);
2115 return 1;
2119 /* C++: If it was not found as a data field, then try to return it
2120 as a pointer to a method. */
2122 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
2124 if (strcmp_iw (TYPE_FN_FIELDLIST_NAME (type, i), name) == 0)
2126 is_a_field_of_this->type = type;
2127 is_a_field_of_this->fn_field = &TYPE_FN_FIELDLIST (type, i);
2128 return 1;
2132 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2133 if (check_field (TYPE_BASECLASS (type, i), name, is_a_field_of_this))
2134 return 1;
2136 return 0;
2139 /* Behave like lookup_symbol except that NAME is the natural name
2140 (e.g., demangled name) of the symbol that we're looking for. */
2142 static struct block_symbol
2143 lookup_symbol_aux (const char *name, symbol_name_match_type match_type,
2144 const struct block *block,
2145 const domain_search_flags domain, enum language language,
2146 struct field_of_this_result *is_a_field_of_this)
2148 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2150 struct block_symbol result;
2151 const struct language_defn *langdef;
2153 if (symbol_lookup_debug)
2155 struct objfile *objfile = (block == nullptr
2156 ? nullptr : block->objfile ());
2158 symbol_lookup_debug_printf
2159 ("demangled symbol name = \"%s\", block @ %s (objfile %s)",
2160 name, host_address_to_string (block),
2161 objfile != NULL ? objfile_debug_name (objfile) : "NULL");
2162 symbol_lookup_debug_printf
2163 ("domain name = \"%s\", language = \"%s\")",
2164 domain_name (domain).c_str (), language_str (language));
2167 /* Make sure we do something sensible with is_a_field_of_this, since
2168 the callers that set this parameter to some non-null value will
2169 certainly use it later. If we don't set it, the contents of
2170 is_a_field_of_this are undefined. */
2171 if (is_a_field_of_this != NULL)
2172 memset (is_a_field_of_this, 0, sizeof (*is_a_field_of_this));
2174 langdef = language_def (language);
2176 /* Search specified block and its superiors. Don't search
2177 STATIC_BLOCK or GLOBAL_BLOCK. */
2179 result = lookup_local_symbol (name, match_type, block, domain, langdef);
2180 if (result.symbol != NULL)
2182 symbol_lookup_debug_printf
2183 ("found symbol @ %s (using lookup_local_symbol)",
2184 host_address_to_string (result.symbol));
2185 return result;
2188 /* If requested to do so by the caller and if appropriate for LANGUAGE,
2189 check to see if NAME is a field of `this'. */
2191 /* Don't do this check if we are searching for a struct. It will
2192 not be found by check_field, but will be found by other
2193 means. */
2194 if (is_a_field_of_this != NULL && (domain & SEARCH_STRUCT_DOMAIN) == 0)
2196 result = lookup_language_this (langdef, block);
2198 if (result.symbol)
2200 struct type *t = result.symbol->type ();
2202 /* I'm not really sure that type of this can ever
2203 be typedefed; just be safe. */
2204 t = check_typedef (t);
2205 if (t->is_pointer_or_reference ())
2206 t = t->target_type ();
2208 if (t->code () != TYPE_CODE_STRUCT
2209 && t->code () != TYPE_CODE_UNION)
2210 error (_("Internal error: `%s' is not an aggregate"),
2211 langdef->name_of_this ());
2213 if (check_field (t, name, is_a_field_of_this))
2215 symbol_lookup_debug_printf ("no symbol found");
2216 return {};
2221 /* Now do whatever is appropriate for LANGUAGE to look
2222 up static and global variables. */
2224 result = langdef->lookup_symbol_nonlocal (name, block, domain);
2225 if (result.symbol != NULL)
2227 symbol_lookup_debug_printf
2228 ("found symbol @ %s (using language lookup_symbol_nonlocal)",
2229 host_address_to_string (result.symbol));
2230 return result;
2233 /* Now search all static file-level symbols. Not strictly correct,
2234 but more useful than an error. */
2236 result = lookup_static_symbol (name, domain);
2237 symbol_lookup_debug_printf
2238 ("found symbol @ %s (using lookup_static_symbol)",
2239 result.symbol != NULL ? host_address_to_string (result.symbol) : "NULL");
2240 return result;
2243 /* Check to see if the symbol is defined in BLOCK or its superiors.
2244 Don't search STATIC_BLOCK or GLOBAL_BLOCK. */
2246 static struct block_symbol
2247 lookup_local_symbol (const char *name,
2248 symbol_name_match_type match_type,
2249 const struct block *block,
2250 const domain_search_flags domain,
2251 const struct language_defn *langdef)
2253 if (block == nullptr)
2254 return {};
2256 const char *scope = block->scope ();
2258 while (!block->is_global_block () && !block->is_static_block ())
2260 struct symbol *sym = lookup_symbol_in_block (name, match_type,
2261 block, domain);
2262 if (sym != NULL)
2263 return (struct block_symbol) {sym, block};
2265 struct symbol *function = block->function ();
2266 if (function != nullptr && function->is_template_function ())
2268 struct template_symbol *templ = (struct template_symbol *) function;
2269 sym = search_symbol_list (name,
2270 templ->n_template_arguments,
2271 templ->template_arguments);
2272 if (sym != nullptr)
2273 return (struct block_symbol) {sym, block};
2276 struct block_symbol blocksym
2277 = langdef->lookup_symbol_local (scope, name, block, domain);
2278 if (blocksym.symbol != nullptr)
2279 return blocksym;
2281 if (block->inlined_p ())
2282 break;
2283 block = block->superblock ();
2286 /* We've reached the end of the function without finding a result. */
2288 return {};
2291 /* See symtab.h. */
2293 struct symbol *
2294 lookup_symbol_in_block (const char *name, symbol_name_match_type match_type,
2295 const struct block *block,
2296 const domain_search_flags domain)
2298 struct symbol *sym;
2300 if (symbol_lookup_debug)
2302 struct objfile *objfile
2303 = block == nullptr ? nullptr : block->objfile ();
2305 symbol_lookup_debug_printf_v
2306 ("lookup_symbol_in_block (%s, %s (objfile %s), %s)",
2307 name, host_address_to_string (block),
2308 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2309 domain_name (domain).c_str ());
2312 lookup_name_info lookup_name (name, match_type);
2313 sym = block_lookup_symbol (block, lookup_name, domain);
2314 if (sym)
2316 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = %s",
2317 host_address_to_string (sym));
2318 return sym;
2321 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = NULL");
2322 return NULL;
2325 /* See symtab.h. */
2327 struct block_symbol
2328 lookup_global_symbol_from_objfile (struct objfile *main_objfile,
2329 enum block_enum block_index,
2330 const char *name,
2331 const domain_search_flags domain)
2333 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2335 for (objfile *objfile : main_objfile->separate_debug_objfiles ())
2337 struct block_symbol result
2338 = lookup_symbol_in_objfile (objfile, block_index, name, domain);
2340 if (result.symbol != nullptr)
2341 return result;
2344 return {};
2347 /* Check to see if the symbol is defined in one of the OBJFILE's
2348 symtabs. BLOCK_INDEX should be either GLOBAL_BLOCK or STATIC_BLOCK,
2349 depending on whether or not we want to search global symbols or
2350 static symbols. */
2352 static struct block_symbol
2353 lookup_symbol_in_objfile_symtabs (struct objfile *objfile,
2354 enum block_enum block_index, const char *name,
2355 const domain_search_flags domain)
2357 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2359 symbol_lookup_debug_printf_v
2360 ("lookup_symbol_in_objfile_symtabs (%s, %s, %s, %s)",
2361 objfile_debug_name (objfile),
2362 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2363 name, domain_name (domain).c_str ());
2365 struct block_symbol other;
2366 other.symbol = NULL;
2367 for (compunit_symtab *cust : objfile->compunits ())
2369 const struct blockvector *bv;
2370 const struct block *block;
2371 struct block_symbol result;
2373 bv = cust->blockvector ();
2374 block = bv->block (block_index);
2375 result.symbol = block_lookup_symbol_primary (block, name, domain);
2376 result.block = block;
2377 if (result.symbol == NULL)
2378 continue;
2379 if (best_symbol (result.symbol, domain))
2381 other = result;
2382 break;
2384 if (result.symbol->matches (domain))
2386 struct symbol *better
2387 = better_symbol (other.symbol, result.symbol, domain);
2388 if (better != other.symbol)
2390 other.symbol = better;
2391 other.block = block;
2396 if (other.symbol != NULL)
2398 symbol_lookup_debug_printf_v
2399 ("lookup_symbol_in_objfile_symtabs (...) = %s (block %s)",
2400 host_address_to_string (other.symbol),
2401 host_address_to_string (other.block));
2402 return other;
2405 symbol_lookup_debug_printf_v
2406 ("lookup_symbol_in_objfile_symtabs (...) = NULL");
2407 return {};
2410 /* Wrapper around lookup_symbol_in_objfile_symtabs for search_symbols.
2411 Look up LINKAGE_NAME in DOMAIN in the global and static blocks of OBJFILE
2412 and all associated separate debug objfiles.
2414 Normally we only look in OBJFILE, and not any separate debug objfiles
2415 because the outer loop will cause them to be searched too. This case is
2416 different. Here we're called from search_symbols where it will only
2417 call us for the objfile that contains a matching minsym. */
2419 static struct block_symbol
2420 lookup_symbol_in_objfile_from_linkage_name (struct objfile *objfile,
2421 const char *linkage_name,
2422 domain_search_flags domain)
2424 enum language lang = current_language->la_language;
2425 struct objfile *main_objfile;
2427 demangle_result_storage storage;
2428 const char *modified_name = demangle_for_lookup (linkage_name, lang, storage);
2430 if (objfile->separate_debug_objfile_backlink)
2431 main_objfile = objfile->separate_debug_objfile_backlink;
2432 else
2433 main_objfile = objfile;
2435 for (::objfile *cur_objfile : main_objfile->separate_debug_objfiles ())
2437 struct block_symbol result;
2439 result = lookup_symbol_in_objfile_symtabs (cur_objfile, GLOBAL_BLOCK,
2440 modified_name, domain);
2441 if (result.symbol == NULL)
2442 result = lookup_symbol_in_objfile_symtabs (cur_objfile, STATIC_BLOCK,
2443 modified_name, domain);
2444 if (result.symbol != NULL)
2445 return result;
2448 return {};
2451 /* A helper function that throws an exception when a symbol was found
2452 in a psymtab but not in a symtab. */
2454 [[noreturn]] static void
2455 error_in_psymtab_expansion (enum block_enum block_index, const char *name,
2456 struct compunit_symtab *cust)
2458 error (_("\
2459 Internal: %s symbol `%s' found in %s psymtab but not in symtab.\n\
2460 %s may be an inlined function, or may be a template function\n \
2461 (if a template, try specifying an instantiation: %s<type>)."),
2462 block_index == GLOBAL_BLOCK ? "global" : "static",
2463 name,
2464 symtab_to_filename_for_display (cust->primary_filetab ()),
2465 name, name);
2468 /* A helper function for various lookup routines that interfaces with
2469 the "quick" symbol table functions. */
2471 static struct block_symbol
2472 lookup_symbol_via_quick_fns (struct objfile *objfile,
2473 enum block_enum block_index, const char *name,
2474 const domain_search_flags domain)
2476 struct compunit_symtab *cust;
2477 const struct blockvector *bv;
2478 const struct block *block;
2479 struct block_symbol result;
2481 symbol_lookup_debug_printf_v
2482 ("lookup_symbol_via_quick_fns (%s, %s, %s, %s)",
2483 objfile_debug_name (objfile),
2484 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2485 name, domain_name (domain).c_str ());
2487 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2488 cust = objfile->lookup_symbol (block_index, lookup_name, domain);
2489 if (cust == NULL)
2491 symbol_lookup_debug_printf_v
2492 ("lookup_symbol_via_quick_fns (...) = NULL");
2493 return {};
2496 bv = cust->blockvector ();
2497 block = bv->block (block_index);
2498 result.symbol = block_lookup_symbol (block, lookup_name, domain);
2499 if (result.symbol == NULL)
2500 error_in_psymtab_expansion (block_index, name, cust);
2502 symbol_lookup_debug_printf_v
2503 ("lookup_symbol_via_quick_fns (...) = %s (block %s)",
2504 host_address_to_string (result.symbol),
2505 host_address_to_string (block));
2507 result.block = block;
2508 return result;
2511 /* See language.h. */
2513 struct block_symbol
2514 language_defn::lookup_symbol_nonlocal (const char *name,
2515 const struct block *block,
2516 const domain_search_flags domain) const
2518 struct block_symbol result;
2520 /* NOTE: dje/2014-10-26: The lookup in all objfiles search could skip
2521 the current objfile. Searching the current objfile first is useful
2522 for both matching user expectations as well as performance. */
2524 result = lookup_symbol_in_static_block (name, block, domain);
2525 if (result.symbol != NULL)
2526 return result;
2528 /* If we didn't find a definition for a builtin type in the static block,
2529 search for it now. This is actually the right thing to do and can be
2530 a massive performance win. E.g., when debugging a program with lots of
2531 shared libraries we could search all of them only to find out the
2532 builtin type isn't defined in any of them. This is common for types
2533 like "void". */
2534 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
2536 struct gdbarch *gdbarch;
2538 if (block == NULL)
2539 gdbarch = current_inferior ()->arch ();
2540 else
2541 gdbarch = block->gdbarch ();
2542 result.symbol = language_lookup_primitive_type_as_symbol (this,
2543 gdbarch, name);
2544 result.block = NULL;
2545 if (result.symbol != NULL)
2546 return result;
2549 return lookup_global_symbol (name, block, domain);
2552 /* See symtab.h. */
2554 struct block_symbol
2555 lookup_symbol_in_static_block (const char *name,
2556 const struct block *block,
2557 const domain_search_flags domain)
2559 if (block == nullptr)
2560 return {};
2562 const struct block *static_block = block->static_block ();
2563 struct symbol *sym;
2565 if (static_block == NULL)
2566 return {};
2568 if (symbol_lookup_debug)
2570 struct objfile *objfile = (block == nullptr
2571 ? nullptr : block->objfile ());
2573 symbol_lookup_debug_printf
2574 ("lookup_symbol_in_static_block (%s, %s (objfile %s), %s)",
2575 name, host_address_to_string (block),
2576 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2577 domain_name (domain).c_str ());
2580 sym = lookup_symbol_in_block (name,
2581 symbol_name_match_type::FULL,
2582 static_block, domain);
2583 symbol_lookup_debug_printf ("lookup_symbol_in_static_block (...) = %s",
2584 sym != NULL
2585 ? host_address_to_string (sym) : "NULL");
2586 return (struct block_symbol) {sym, static_block};
2589 /* Perform the standard symbol lookup of NAME in OBJFILE:
2590 1) First search expanded symtabs, and if not found
2591 2) Search the "quick" symtabs (partial or .gdb_index).
2592 BLOCK_INDEX is one of GLOBAL_BLOCK or STATIC_BLOCK. */
2594 static struct block_symbol
2595 lookup_symbol_in_objfile (struct objfile *objfile, enum block_enum block_index,
2596 const char *name, const domain_search_flags domain)
2598 struct block_symbol result;
2600 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2602 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (%s, %s, %s, %s)",
2603 objfile_debug_name (objfile),
2604 block_index == GLOBAL_BLOCK
2605 ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2606 name, domain_name (domain).c_str ());
2608 result = lookup_symbol_in_objfile_symtabs (objfile, block_index,
2609 name, domain);
2610 if (result.symbol != NULL)
2612 symbol_lookup_debug_printf
2613 ("lookup_symbol_in_objfile (...) = %s (in symtabs)",
2614 host_address_to_string (result.symbol));
2615 return result;
2618 result = lookup_symbol_via_quick_fns (objfile, block_index,
2619 name, domain);
2620 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (...) = %s%s",
2621 result.symbol != NULL
2622 ? host_address_to_string (result.symbol)
2623 : "NULL",
2624 result.symbol != NULL ? " (via quick fns)"
2625 : "");
2626 return result;
2629 /* This function contains the common code of lookup_{global,static}_symbol.
2630 OBJFILE is only used if BLOCK_INDEX is GLOBAL_SCOPE, in which case it is
2631 the objfile to start the lookup in. */
2633 static struct block_symbol
2634 lookup_global_or_static_symbol (const char *name,
2635 enum block_enum block_index,
2636 struct objfile *objfile,
2637 const domain_search_flags domain)
2639 struct symbol_cache *cache = get_symbol_cache (current_program_space);
2640 struct block_symbol result;
2641 struct block_symbol_cache *bsc;
2642 struct symbol_cache_slot *slot;
2644 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2645 gdb_assert (objfile == nullptr || block_index == GLOBAL_BLOCK);
2647 /* First see if we can find the symbol in the cache.
2648 This works because we use the current objfile to qualify the lookup. */
2649 result = symbol_cache_lookup (cache, objfile, block_index, name, domain,
2650 &bsc, &slot);
2651 if (result.symbol != NULL)
2653 if (SYMBOL_LOOKUP_FAILED_P (result))
2654 return {};
2655 return result;
2658 /* Do a global search (of global blocks, heh). */
2659 if (result.symbol == NULL)
2660 gdbarch_iterate_over_objfiles_in_search_order
2661 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
2662 [&result, block_index, name, domain] (struct objfile *objfile_iter)
2664 result = lookup_symbol_in_objfile (objfile_iter, block_index,
2665 name, domain);
2666 return result.symbol != nullptr;
2668 objfile);
2670 if (result.symbol != NULL)
2671 symbol_cache_mark_found (bsc, slot, objfile, result.symbol, result.block,
2672 domain);
2673 else
2674 symbol_cache_mark_not_found (bsc, slot, objfile, name, domain);
2676 return result;
2679 /* See symtab.h. */
2681 struct block_symbol
2682 lookup_static_symbol (const char *name, const domain_search_flags domain)
2684 return lookup_global_or_static_symbol (name, STATIC_BLOCK, nullptr, domain);
2687 /* See symtab.h. */
2689 struct block_symbol
2690 lookup_global_symbol (const char *name,
2691 const struct block *block,
2692 const domain_search_flags domain)
2694 /* If a block was passed in, we want to search the corresponding
2695 global block first. This yields "more expected" behavior, and is
2696 needed to support 'FILENAME'::VARIABLE lookups. */
2697 const struct block *global_block
2698 = block == nullptr ? nullptr : block->global_block ();
2699 symbol *sym = NULL;
2700 if (global_block != nullptr)
2702 sym = lookup_symbol_in_block (name,
2703 symbol_name_match_type::FULL,
2704 global_block, domain);
2705 if (sym != NULL && best_symbol (sym, domain))
2706 return { sym, global_block };
2709 struct objfile *objfile = nullptr;
2710 if (block != nullptr)
2712 objfile = block->objfile ();
2713 if (objfile->separate_debug_objfile_backlink != nullptr)
2714 objfile = objfile->separate_debug_objfile_backlink;
2717 block_symbol bs
2718 = lookup_global_or_static_symbol (name, GLOBAL_BLOCK, objfile, domain);
2719 if (better_symbol (sym, bs.symbol, domain) == sym)
2720 return { sym, global_block };
2721 else
2722 return bs;
2725 /* See symtab.h. */
2727 bool
2728 symbol::matches (domain_search_flags flags) const
2730 /* C++ has a typedef for every tag, and the types are in the struct
2731 domain. */
2732 if (language () == language_cplus && (flags & SEARCH_TYPE_DOMAIN) != 0)
2733 flags |= SEARCH_STRUCT_DOMAIN;
2735 return search_flags_matches (flags, m_domain);
2738 /* See symtab.h. */
2740 struct type *
2741 lookup_transparent_type (const char *name, domain_search_flags flags)
2743 return current_language->lookup_transparent_type (name, flags);
2746 /* A helper for basic_lookup_transparent_type that interfaces with the
2747 "quick" symbol table functions. */
2749 static struct type *
2750 basic_lookup_transparent_type_quick (struct objfile *objfile,
2751 enum block_enum block_index,
2752 domain_search_flags flags,
2753 const lookup_name_info &name)
2755 struct compunit_symtab *cust;
2756 const struct blockvector *bv;
2757 const struct block *block;
2758 struct symbol *sym;
2760 cust = objfile->lookup_symbol (block_index, name, flags);
2761 if (cust == NULL)
2762 return NULL;
2764 bv = cust->blockvector ();
2765 block = bv->block (block_index);
2767 sym = block_find_symbol (block, name, flags, nullptr);
2768 if (sym == nullptr)
2769 error_in_psymtab_expansion (block_index, name.c_str (), cust);
2770 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2771 return sym->type ();
2774 /* Subroutine of basic_lookup_transparent_type to simplify it.
2775 Look up the non-opaque definition of NAME in BLOCK_INDEX of OBJFILE.
2776 BLOCK_INDEX is either GLOBAL_BLOCK or STATIC_BLOCK. */
2778 static struct type *
2779 basic_lookup_transparent_type_1 (struct objfile *objfile,
2780 enum block_enum block_index,
2781 domain_search_flags flags,
2782 const lookup_name_info &name)
2784 const struct blockvector *bv;
2785 const struct block *block;
2786 const struct symbol *sym;
2788 for (compunit_symtab *cust : objfile->compunits ())
2790 bv = cust->blockvector ();
2791 block = bv->block (block_index);
2792 sym = block_find_symbol (block, name, flags, nullptr);
2793 if (sym != nullptr)
2795 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2796 return sym->type ();
2800 return NULL;
2803 /* The standard implementation of lookup_transparent_type. This code
2804 was modeled on lookup_symbol -- the parts not relevant to looking
2805 up types were just left out. In particular it's assumed here that
2806 types are available in STRUCT_DOMAIN and only in file-static or
2807 global blocks. */
2809 struct type *
2810 basic_lookup_transparent_type (const char *name, domain_search_flags flags)
2812 struct type *t;
2814 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2816 /* Now search all the global symbols. Do the symtab's first, then
2817 check the psymtab's. If a psymtab indicates the existence
2818 of the desired name as a global, then do psymtab-to-symtab
2819 conversion on the fly and return the found symbol. */
2821 for (objfile *objfile : current_program_space->objfiles ())
2823 t = basic_lookup_transparent_type_1 (objfile, GLOBAL_BLOCK,
2824 flags, lookup_name);
2825 if (t)
2826 return t;
2829 for (objfile *objfile : current_program_space->objfiles ())
2831 t = basic_lookup_transparent_type_quick (objfile, GLOBAL_BLOCK,
2832 flags, lookup_name);
2833 if (t)
2834 return t;
2837 /* Now search the static file-level symbols.
2838 Not strictly correct, but more useful than an error.
2839 Do the symtab's first, then
2840 check the psymtab's. If a psymtab indicates the existence
2841 of the desired name as a file-level static, then do psymtab-to-symtab
2842 conversion on the fly and return the found symbol. */
2844 for (objfile *objfile : current_program_space->objfiles ())
2846 t = basic_lookup_transparent_type_1 (objfile, STATIC_BLOCK,
2847 flags, lookup_name);
2848 if (t)
2849 return t;
2852 for (objfile *objfile : current_program_space->objfiles ())
2854 t = basic_lookup_transparent_type_quick (objfile, STATIC_BLOCK,
2855 flags, lookup_name);
2856 if (t)
2857 return t;
2860 return (struct type *) 0;
2863 /* See symtab.h. */
2865 bool
2866 iterate_over_symbols (const struct block *block,
2867 const lookup_name_info &name,
2868 const domain_search_flags domain,
2869 gdb::function_view<symbol_found_callback_ftype> callback)
2871 for (struct symbol *sym : block_iterator_range (block, &name))
2873 if (sym->matches (domain))
2875 struct block_symbol block_sym = {sym, block};
2877 if (!callback (&block_sym))
2878 return false;
2881 return true;
2884 /* See symtab.h. */
2886 bool
2887 iterate_over_symbols_terminated
2888 (const struct block *block,
2889 const lookup_name_info &name,
2890 const domain_search_flags domain,
2891 gdb::function_view<symbol_found_callback_ftype> callback)
2893 if (!iterate_over_symbols (block, name, domain, callback))
2894 return false;
2895 struct block_symbol block_sym = {nullptr, block};
2896 return callback (&block_sym);
2899 /* Find the compunit symtab associated with PC and SECTION.
2900 This will read in debug info as necessary. */
2902 struct compunit_symtab *
2903 find_pc_sect_compunit_symtab (CORE_ADDR pc, struct obj_section *section)
2905 struct compunit_symtab *best_cust = NULL;
2906 CORE_ADDR best_cust_range = 0;
2908 /* If we know that this is not a text address, return failure. This is
2909 necessary because we loop based on the block's high and low code
2910 addresses, which do not include the data ranges, and because
2911 we call find_pc_sect_psymtab which has a similar restriction based
2912 on the partial_symtab's texthigh and textlow. */
2913 bound_minimal_symbol msymbol
2914 = lookup_minimal_symbol_by_pc_section (pc, section);
2915 if (msymbol.minsym && msymbol.minsym->data_p ())
2916 return NULL;
2918 /* Search all symtabs for the one whose file contains our address, and which
2919 is the smallest of all the ones containing the address. This is designed
2920 to deal with a case like symtab a is at 0x1000-0x2000 and 0x3000-0x4000
2921 and symtab b is at 0x2000-0x3000. So the GLOBAL_BLOCK for a is from
2922 0x1000-0x4000, but for address 0x2345 we want to return symtab b.
2924 This happens for native ecoff format, where code from included files
2925 gets its own symtab. The symtab for the included file should have
2926 been read in already via the dependency mechanism.
2927 It might be swifter to create several symtabs with the same name
2928 like xcoff does (I'm not sure).
2930 It also happens for objfiles that have their functions reordered.
2931 For these, the symtab we are looking for is not necessarily read in. */
2933 for (objfile *obj_file : current_program_space->objfiles ())
2935 for (compunit_symtab *cust : obj_file->compunits ())
2937 const struct blockvector *bv = cust->blockvector ();
2938 const struct block *global_block = bv->global_block ();
2939 CORE_ADDR start = global_block->start ();
2940 CORE_ADDR end = global_block->end ();
2941 bool in_range_p = start <= pc && pc < end;
2942 if (!in_range_p)
2943 continue;
2945 if (bv->map () != nullptr)
2947 if (bv->map ()->find (pc) == nullptr)
2948 continue;
2950 return cust;
2953 CORE_ADDR range = end - start;
2954 if (best_cust != nullptr
2955 && range >= best_cust_range)
2956 /* Cust doesn't have a smaller range than best_cust, skip it. */
2957 continue;
2959 /* For an objfile that has its functions reordered,
2960 find_pc_psymtab will find the proper partial symbol table
2961 and we simply return its corresponding symtab. */
2962 /* In order to better support objfiles that contain both
2963 stabs and coff debugging info, we continue on if a psymtab
2964 can't be found. */
2965 struct compunit_symtab *result
2966 = obj_file->find_pc_sect_compunit_symtab (msymbol, pc,
2967 section, 0);
2968 if (result != nullptr)
2969 return result;
2971 if (section != 0)
2973 struct symbol *found_sym = nullptr;
2975 for (int b_index = GLOBAL_BLOCK;
2976 b_index <= STATIC_BLOCK && found_sym == nullptr;
2977 ++b_index)
2979 const struct block *b = bv->block (b_index);
2980 for (struct symbol *sym : block_iterator_range (b))
2982 if (matching_obj_sections (sym->obj_section (obj_file),
2983 section))
2985 found_sym = sym;
2986 break;
2990 if (found_sym == nullptr)
2991 continue; /* No symbol in this symtab matches
2992 section. */
2995 /* Cust is best found so far, save it. */
2996 best_cust = cust;
2997 best_cust_range = range;
3001 if (best_cust != NULL)
3002 return best_cust;
3004 /* Not found in symtabs, search the "quick" symtabs (e.g. psymtabs). */
3006 for (objfile *objf : current_program_space->objfiles ())
3008 struct compunit_symtab *result
3009 = objf->find_pc_sect_compunit_symtab (msymbol, pc, section, 1);
3010 if (result != NULL)
3011 return result;
3014 return NULL;
3017 /* Find the compunit symtab associated with PC.
3018 This will read in debug info as necessary.
3019 Backward compatibility, no section. */
3021 struct compunit_symtab *
3022 find_pc_compunit_symtab (CORE_ADDR pc)
3024 return find_pc_sect_compunit_symtab (pc, find_pc_mapped_section (pc));
3027 /* See symtab.h. */
3029 struct symbol *
3030 find_symbol_at_address (CORE_ADDR address)
3032 /* A helper function to search a given symtab for a symbol matching
3033 ADDR. */
3034 auto search_symtab = [] (compunit_symtab *symtab, CORE_ADDR addr) -> symbol *
3036 const struct blockvector *bv = symtab->blockvector ();
3038 for (int i = GLOBAL_BLOCK; i <= STATIC_BLOCK; ++i)
3040 const struct block *b = bv->block (i);
3042 for (struct symbol *sym : block_iterator_range (b))
3044 if (sym->aclass () == LOC_STATIC
3045 && sym->value_address () == addr)
3046 return sym;
3049 return nullptr;
3052 for (objfile *objfile : current_program_space->objfiles ())
3054 /* If this objfile was read with -readnow, then we need to
3055 search the symtabs directly. */
3056 if ((objfile->flags & OBJF_READNOW) != 0)
3058 for (compunit_symtab *symtab : objfile->compunits ())
3060 struct symbol *sym = search_symtab (symtab, address);
3061 if (sym != nullptr)
3062 return sym;
3065 else
3067 struct compunit_symtab *symtab
3068 = objfile->find_compunit_symtab_by_address (address);
3069 if (symtab != NULL)
3071 struct symbol *sym = search_symtab (symtab, address);
3072 if (sym != nullptr)
3073 return sym;
3078 return NULL;
3083 /* Find the source file and line number for a given PC value and SECTION.
3084 Return a structure containing a symtab pointer, a line number,
3085 and a pc range for the entire source line.
3086 The value's .pc field is NOT the specified pc.
3087 NOTCURRENT nonzero means, if specified pc is on a line boundary,
3088 use the line that ends there. Otherwise, in that case, the line
3089 that begins there is used. */
3091 /* The big complication here is that a line may start in one file, and end just
3092 before the start of another file. This usually occurs when you #include
3093 code in the middle of a subroutine. To properly find the end of a line's PC
3094 range, we must search all symtabs associated with this compilation unit, and
3095 find the one whose first PC is closer than that of the next line in this
3096 symtab. */
3098 struct symtab_and_line
3099 find_pc_sect_line (CORE_ADDR pc, struct obj_section *section, int notcurrent)
3101 struct compunit_symtab *cust;
3102 const linetable *l;
3103 int len;
3104 const linetable_entry *item;
3105 const struct blockvector *bv;
3107 /* Info on best line seen so far, and where it starts, and its file. */
3109 const linetable_entry *best = NULL;
3110 CORE_ADDR best_end = 0;
3111 struct symtab *best_symtab = 0;
3113 /* Store here the first line number
3114 of a file which contains the line at the smallest pc after PC.
3115 If we don't find a line whose range contains PC,
3116 we will use a line one less than this,
3117 with a range from the start of that file to the first line's pc. */
3118 const linetable_entry *alt = NULL;
3120 /* Info on best line seen in this file. */
3122 const linetable_entry *prev;
3124 /* If this pc is not from the current frame,
3125 it is the address of the end of a call instruction.
3126 Quite likely that is the start of the following statement.
3127 But what we want is the statement containing the instruction.
3128 Fudge the pc to make sure we get that. */
3130 /* It's tempting to assume that, if we can't find debugging info for
3131 any function enclosing PC, that we shouldn't search for line
3132 number info, either. However, GAS can emit line number info for
3133 assembly files --- very helpful when debugging hand-written
3134 assembly code. In such a case, we'd have no debug info for the
3135 function, but we would have line info. */
3137 if (notcurrent)
3138 pc -= 1;
3140 /* elz: added this because this function returned the wrong
3141 information if the pc belongs to a stub (import/export)
3142 to call a shlib function. This stub would be anywhere between
3143 two functions in the target, and the line info was erroneously
3144 taken to be the one of the line before the pc. */
3146 /* RT: Further explanation:
3148 * We have stubs (trampolines) inserted between procedures.
3150 * Example: "shr1" exists in a shared library, and a "shr1" stub also
3151 * exists in the main image.
3153 * In the minimal symbol table, we have a bunch of symbols
3154 * sorted by start address. The stubs are marked as "trampoline",
3155 * the others appear as text. E.g.:
3157 * Minimal symbol table for main image
3158 * main: code for main (text symbol)
3159 * shr1: stub (trampoline symbol)
3160 * foo: code for foo (text symbol)
3161 * ...
3162 * Minimal symbol table for "shr1" image:
3163 * ...
3164 * shr1: code for shr1 (text symbol)
3165 * ...
3167 * So the code below is trying to detect if we are in the stub
3168 * ("shr1" stub), and if so, find the real code ("shr1" trampoline),
3169 * and if found, do the symbolization from the real-code address
3170 * rather than the stub address.
3172 * Assumptions being made about the minimal symbol table:
3173 * 1. lookup_minimal_symbol_by_pc() will return a trampoline only
3174 * if we're really in the trampoline.s If we're beyond it (say
3175 * we're in "foo" in the above example), it'll have a closer
3176 * symbol (the "foo" text symbol for example) and will not
3177 * return the trampoline.
3178 * 2. lookup_minimal_symbol_text() will find a real text symbol
3179 * corresponding to the trampoline, and whose address will
3180 * be different than the trampoline address. I put in a sanity
3181 * check for the address being the same, to avoid an
3182 * infinite recursion.
3184 bound_minimal_symbol msymbol = lookup_minimal_symbol_by_pc (pc);
3185 if (msymbol.minsym != NULL)
3186 if (msymbol.minsym->type () == mst_solib_trampoline)
3188 bound_minimal_symbol mfunsym
3189 = lookup_minimal_symbol_text (current_program_space,
3190 msymbol.minsym->linkage_name (),
3191 nullptr);
3193 if (mfunsym.minsym == NULL)
3194 /* I eliminated this warning since it is coming out
3195 * in the following situation:
3196 * gdb shmain // test program with shared libraries
3197 * (gdb) break shr1 // function in shared lib
3198 * Warning: In stub for ...
3199 * In the above situation, the shared lib is not loaded yet,
3200 * so of course we can't find the real func/line info,
3201 * but the "break" still works, and the warning is annoying.
3202 * So I commented out the warning. RT */
3203 /* warning ("In stub for %s; unable to find real function/line info",
3204 msymbol->linkage_name ()); */
3206 /* fall through */
3207 else if (mfunsym.value_address ()
3208 == msymbol.value_address ())
3209 /* Avoid infinite recursion */
3210 /* See above comment about why warning is commented out. */
3211 /* warning ("In stub for %s; unable to find real function/line info",
3212 msymbol->linkage_name ()); */
3214 /* fall through */
3215 else
3217 /* Detect an obvious case of infinite recursion. If this
3218 should occur, we'd like to know about it, so error out,
3219 fatally. */
3220 if (mfunsym.value_address () == pc)
3221 internal_error (_("Infinite recursion detected in find_pc_sect_line;"
3222 "please file a bug report"));
3224 return find_pc_line (mfunsym.value_address (), 0);
3228 symtab_and_line val;
3229 val.pspace = current_program_space;
3231 cust = find_pc_sect_compunit_symtab (pc, section);
3232 if (cust == NULL)
3234 /* If no symbol information, return previous pc. */
3235 if (notcurrent)
3236 pc++;
3237 val.pc = pc;
3238 return val;
3241 bv = cust->blockvector ();
3242 struct objfile *objfile = cust->objfile ();
3244 /* Look at all the symtabs that share this blockvector.
3245 They all have the same apriori range, that we found was right;
3246 but they have different line tables. */
3248 for (symtab *iter_s : cust->filetabs ())
3250 /* Find the best line in this symtab. */
3251 l = iter_s->linetable ();
3252 if (!l)
3253 continue;
3254 len = l->nitems;
3255 if (len <= 0)
3257 /* I think len can be zero if the symtab lacks line numbers
3258 (e.g. gcc -g1). (Either that or the LINETABLE is NULL;
3259 I'm not sure which, and maybe it depends on the symbol
3260 reader). */
3261 continue;
3264 prev = NULL;
3265 item = l->item; /* Get first line info. */
3267 /* Is this file's first line closer than the first lines of other files?
3268 If so, record this file, and its first line, as best alternate. */
3269 if (item->pc (objfile) > pc
3270 && (!alt || item->unrelocated_pc () < alt->unrelocated_pc ()))
3271 alt = item;
3273 auto pc_compare = [] (const unrelocated_addr &comp_pc,
3274 const struct linetable_entry & lhs)
3276 return comp_pc < lhs.unrelocated_pc ();
3279 const linetable_entry *first = item;
3280 const linetable_entry *last = item + len;
3281 item = (std::upper_bound
3282 (first, last,
3283 unrelocated_addr (pc - objfile->text_section_offset ()),
3284 pc_compare));
3285 if (item != first)
3287 prev = item - 1; /* Found a matching item. */
3288 /* At this point, prev is a line whose address is <= pc. However, we
3289 don't know if ITEM is pointing to the same statement or not. */
3290 while (item != last && prev->line == item->line && !item->is_stmt)
3291 item++;
3294 /* At this point, prev points at the line whose start addr is <= pc, and
3295 item points at the next statement. If we ran off the end of the linetable
3296 (pc >= start of the last line), then prev == item. If pc < start of
3297 the first line, prev will not be set. */
3299 /* Is this file's best line closer than the best in the other files?
3300 If so, record this file, and its best line, as best so far. Don't
3301 save prev if it represents the end of a function (i.e. line number
3302 0) instead of a real line. */
3304 if (prev && prev->line
3305 && (!best || prev->unrelocated_pc () > best->unrelocated_pc ()))
3307 best = prev;
3308 best_symtab = iter_s;
3310 /* If during the binary search we land on a non-statement entry,
3311 scan backward through entries at the same address to see if
3312 there is an entry marked as is-statement. In theory this
3313 duplication should have been removed from the line table
3314 during construction, this is just a double check. If the line
3315 table has had the duplication removed then this should be
3316 pretty cheap. */
3317 if (!best->is_stmt)
3319 const linetable_entry *tmp = best;
3320 while (tmp > first
3321 && (tmp - 1)->unrelocated_pc () == tmp->unrelocated_pc ()
3322 && (tmp - 1)->line != 0 && !tmp->is_stmt)
3323 --tmp;
3324 if (tmp->is_stmt)
3325 best = tmp;
3328 /* Discard BEST_END if it's before the PC of the current BEST. */
3329 if (best_end <= best->pc (objfile))
3330 best_end = 0;
3333 /* If another line (denoted by ITEM) is in the linetable and its
3334 PC is after BEST's PC, but before the current BEST_END, then
3335 use ITEM's PC as the new best_end. */
3336 if (best && item < last
3337 && item->unrelocated_pc () > best->unrelocated_pc ()
3338 && (best_end == 0 || best_end > item->pc (objfile)))
3339 best_end = item->pc (objfile);
3342 if (!best_symtab)
3344 /* If we didn't find any line number info, just return zeros.
3345 We used to return alt->line - 1 here, but that could be
3346 anywhere; if we don't have line number info for this PC,
3347 don't make some up. */
3348 val.pc = pc;
3350 else if (best->line == 0)
3352 /* If our best fit is in a range of PC's for which no line
3353 number info is available (line number is zero) then we didn't
3354 find any valid line information. */
3355 val.pc = pc;
3357 else
3359 val.is_stmt = best->is_stmt;
3360 val.symtab = best_symtab;
3361 val.line = best->line;
3362 val.pc = best->pc (objfile);
3363 if (best_end && (!alt || best_end < alt->pc (objfile)))
3364 val.end = best_end;
3365 else if (alt)
3366 val.end = alt->pc (objfile);
3367 else
3368 val.end = bv->global_block ()->end ();
3370 val.section = section;
3371 return val;
3374 /* Backward compatibility (no section). */
3376 struct symtab_and_line
3377 find_pc_line (CORE_ADDR pc, int notcurrent)
3379 struct obj_section *section;
3381 section = find_pc_overlay (pc);
3382 if (!pc_in_unmapped_range (pc, section))
3383 return find_pc_sect_line (pc, section, notcurrent);
3385 /* If the original PC was an unmapped address then we translate this to a
3386 mapped address in order to lookup the sal. However, as the user
3387 passed us an unmapped address it makes more sense to return a result
3388 that has the pc and end fields translated to unmapped addresses. */
3389 pc = overlay_mapped_address (pc, section);
3390 symtab_and_line sal = find_pc_sect_line (pc, section, notcurrent);
3391 sal.pc = overlay_unmapped_address (sal.pc, section);
3392 sal.end = overlay_unmapped_address (sal.end, section);
3393 return sal;
3396 /* Compare two symtab_and_line entries. Return true if both have
3397 the same line number and the same symtab pointer. That means we
3398 are dealing with two entries from the same line and from the same
3399 source file.
3401 Return false otherwise. */
3403 static bool
3404 sal_line_symtab_matches_p (const symtab_and_line &sal1,
3405 const symtab_and_line &sal2)
3407 return sal1.line == sal2.line && sal1.symtab == sal2.symtab;
3410 /* See symtah.h. */
3412 std::optional<CORE_ADDR>
3413 find_line_range_start (CORE_ADDR pc)
3415 struct symtab_and_line current_sal = find_pc_line (pc, 0);
3417 if (current_sal.line == 0)
3418 return {};
3420 struct symtab_and_line prev_sal = find_pc_line (current_sal.pc - 1, 0);
3422 /* If the previous entry is for a different line, that means we are already
3423 at the entry with the start PC for this line. */
3424 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3425 return current_sal.pc;
3427 /* Otherwise, keep looking for entries for the same line but with
3428 smaller PC's. */
3429 bool done = false;
3430 CORE_ADDR prev_pc;
3431 while (!done)
3433 prev_pc = prev_sal.pc;
3435 prev_sal = find_pc_line (prev_pc - 1, 0);
3437 /* Did we notice a line change? If so, we are done searching. */
3438 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3439 done = true;
3442 return prev_pc;
3445 /* See symtab.h. */
3447 struct symtab *
3448 find_pc_line_symtab (CORE_ADDR pc)
3450 struct symtab_and_line sal;
3452 /* This always passes zero for NOTCURRENT to find_pc_line.
3453 There are currently no callers that ever pass non-zero. */
3454 sal = find_pc_line (pc, 0);
3455 return sal.symtab;
3458 /* See symtab.h. */
3460 symtab *
3461 find_line_symtab (symtab *sym_tab, int line, int *index)
3463 int exact = 0; /* Initialized here to avoid a compiler warning. */
3465 /* BEST_INDEX and BEST_LINETABLE identify the smallest linenumber > LINE
3466 so far seen. */
3468 int best_index;
3469 const struct linetable *best_linetable;
3470 struct symtab *best_symtab;
3472 /* First try looking it up in the given symtab. */
3473 best_linetable = sym_tab->linetable ();
3474 best_symtab = sym_tab;
3475 best_index = find_line_common (best_linetable, line, &exact, 0);
3476 if (best_index < 0 || !exact)
3478 /* Didn't find an exact match. So we better keep looking for
3479 another symtab with the same name. In the case of xcoff,
3480 multiple csects for one source file (produced by IBM's FORTRAN
3481 compiler) produce multiple symtabs (this is unavoidable
3482 assuming csects can be at arbitrary places in memory and that
3483 the GLOBAL_BLOCK of a symtab has a begin and end address). */
3485 /* BEST is the smallest linenumber > LINE so far seen,
3486 or 0 if none has been seen so far.
3487 BEST_INDEX and BEST_LINETABLE identify the item for it. */
3488 int best;
3490 if (best_index >= 0)
3491 best = best_linetable->item[best_index].line;
3492 else
3493 best = 0;
3495 for (objfile *objfile : current_program_space->objfiles ())
3496 objfile->expand_symtabs_with_fullname (symtab_to_fullname (sym_tab));
3498 for (objfile *objfile : current_program_space->objfiles ())
3500 for (compunit_symtab *cu : objfile->compunits ())
3502 for (symtab *s : cu->filetabs ())
3504 const struct linetable *l;
3505 int ind;
3507 if (FILENAME_CMP (sym_tab->filename, s->filename) != 0)
3508 continue;
3509 if (FILENAME_CMP (symtab_to_fullname (sym_tab),
3510 symtab_to_fullname (s)) != 0)
3511 continue;
3512 l = s->linetable ();
3513 ind = find_line_common (l, line, &exact, 0);
3514 if (ind >= 0)
3516 if (exact)
3518 best_index = ind;
3519 best_linetable = l;
3520 best_symtab = s;
3521 goto done;
3523 if (best == 0 || l->item[ind].line < best)
3525 best = l->item[ind].line;
3526 best_index = ind;
3527 best_linetable = l;
3528 best_symtab = s;
3535 done:
3536 if (best_index < 0)
3537 return NULL;
3539 if (index)
3540 *index = best_index;
3542 return best_symtab;
3545 /* Given SYMTAB, returns all the PCs function in the symtab that
3546 exactly match LINE. Returns an empty vector if there are no exact
3547 matches, but updates BEST_ITEM in this case. */
3549 std::vector<CORE_ADDR>
3550 find_pcs_for_symtab_line (struct symtab *symtab, int line,
3551 const linetable_entry **best_item)
3553 int start = 0;
3554 std::vector<CORE_ADDR> result;
3555 struct objfile *objfile = symtab->compunit ()->objfile ();
3557 /* First, collect all the PCs that are at this line. */
3558 while (1)
3560 int was_exact;
3561 int idx;
3563 idx = find_line_common (symtab->linetable (), line, &was_exact,
3564 start);
3565 if (idx < 0)
3566 break;
3568 if (!was_exact)
3570 const linetable_entry *item = &symtab->linetable ()->item[idx];
3572 if (*best_item == NULL
3573 || (item->line < (*best_item)->line && item->is_stmt))
3574 *best_item = item;
3576 break;
3579 result.push_back (symtab->linetable ()->item[idx].pc (objfile));
3580 start = idx + 1;
3583 return result;
3587 /* Set the PC value for a given source file and line number and return true.
3588 Returns false for invalid line number (and sets the PC to 0).
3589 The source file is specified with a struct symtab. */
3591 bool
3592 find_line_pc (struct symtab *symtab, int line, CORE_ADDR *pc)
3594 const struct linetable *l;
3595 int ind;
3597 *pc = 0;
3598 if (symtab == 0)
3599 return false;
3601 symtab = find_line_symtab (symtab, line, &ind);
3602 if (symtab != NULL)
3604 l = symtab->linetable ();
3605 *pc = l->item[ind].pc (symtab->compunit ()->objfile ());
3606 return true;
3608 else
3609 return false;
3612 /* Find the range of pc values in a line.
3613 Store the starting pc of the line into *STARTPTR
3614 and the ending pc (start of next line) into *ENDPTR.
3615 Returns true to indicate success.
3616 Returns false if could not find the specified line. */
3618 bool
3619 find_line_pc_range (struct symtab_and_line sal, CORE_ADDR *startptr,
3620 CORE_ADDR *endptr)
3622 CORE_ADDR startaddr;
3623 struct symtab_and_line found_sal;
3625 startaddr = sal.pc;
3626 if (startaddr == 0 && !find_line_pc (sal.symtab, sal.line, &startaddr))
3627 return false;
3629 /* This whole function is based on address. For example, if line 10 has
3630 two parts, one from 0x100 to 0x200 and one from 0x300 to 0x400, then
3631 "info line *0x123" should say the line goes from 0x100 to 0x200
3632 and "info line *0x355" should say the line goes from 0x300 to 0x400.
3633 This also insures that we never give a range like "starts at 0x134
3634 and ends at 0x12c". */
3636 found_sal = find_pc_sect_line (startaddr, sal.section, 0);
3637 if (found_sal.line != sal.line)
3639 /* The specified line (sal) has zero bytes. */
3640 *startptr = found_sal.pc;
3641 *endptr = found_sal.pc;
3643 else
3645 *startptr = found_sal.pc;
3646 *endptr = found_sal.end;
3648 return true;
3651 /* Given a line table and a line number, return the index into the line
3652 table for the pc of the nearest line whose number is >= the specified one.
3653 Return -1 if none is found. The value is >= 0 if it is an index.
3654 START is the index at which to start searching the line table.
3656 Set *EXACT_MATCH nonzero if the value returned is an exact match. */
3658 static int
3659 find_line_common (const linetable *l, int lineno,
3660 int *exact_match, int start)
3662 int i;
3663 int len;
3665 /* BEST is the smallest linenumber > LINENO so far seen,
3666 or 0 if none has been seen so far.
3667 BEST_INDEX identifies the item for it. */
3669 int best_index = -1;
3670 int best = 0;
3672 *exact_match = 0;
3674 if (lineno <= 0)
3675 return -1;
3676 if (l == 0)
3677 return -1;
3679 len = l->nitems;
3680 for (i = start; i < len; i++)
3682 const linetable_entry *item = &(l->item[i]);
3684 /* Ignore non-statements. */
3685 if (!item->is_stmt)
3686 continue;
3688 if (item->line == lineno)
3690 /* Return the first (lowest address) entry which matches. */
3691 *exact_match = 1;
3692 return i;
3695 if (item->line > lineno && (best == 0 || item->line < best))
3697 best = item->line;
3698 best_index = i;
3702 /* If we got here, we didn't get an exact match. */
3703 return best_index;
3706 bool
3707 find_pc_line_pc_range (CORE_ADDR pc, CORE_ADDR *startptr, CORE_ADDR *endptr)
3709 struct symtab_and_line sal;
3711 sal = find_pc_line (pc, 0);
3712 *startptr = sal.pc;
3713 *endptr = sal.end;
3714 return sal.symtab != 0;
3717 /* Helper for find_function_start_sal. Does most of the work, except
3718 setting the sal's symbol. */
3720 static symtab_and_line
3721 find_function_start_sal_1 (CORE_ADDR func_addr, obj_section *section,
3722 bool funfirstline)
3724 symtab_and_line sal = find_pc_sect_line (func_addr, section, 0);
3726 if (funfirstline && sal.symtab != NULL
3727 && (sal.symtab->compunit ()->locations_valid ()
3728 || sal.symtab->language () == language_asm))
3730 struct gdbarch *gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
3732 sal.pc = func_addr;
3733 if (gdbarch_skip_entrypoint_p (gdbarch))
3734 sal.pc = gdbarch_skip_entrypoint (gdbarch, sal.pc);
3735 return sal;
3738 /* We always should have a line for the function start address.
3739 If we don't, something is odd. Create a plain SAL referring
3740 just the PC and hope that skip_prologue_sal (if requested)
3741 can find a line number for after the prologue. */
3742 if (sal.pc < func_addr)
3744 sal = {};
3745 sal.pspace = current_program_space;
3746 sal.pc = func_addr;
3747 sal.section = section;
3750 if (funfirstline)
3751 skip_prologue_sal (&sal);
3753 return sal;
3756 /* See symtab.h. */
3758 symtab_and_line
3759 find_function_start_sal (CORE_ADDR func_addr, obj_section *section,
3760 bool funfirstline)
3762 symtab_and_line sal
3763 = find_function_start_sal_1 (func_addr, section, funfirstline);
3765 /* find_function_start_sal_1 does a linetable search, so it finds
3766 the symtab and linenumber, but not a symbol. Fill in the
3767 function symbol too. */
3768 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
3770 return sal;
3773 /* See symtab.h. */
3775 symtab_and_line
3776 find_function_start_sal (symbol *sym, bool funfirstline)
3778 symtab_and_line sal
3779 = find_function_start_sal_1 (sym->value_block ()->entry_pc (),
3780 sym->obj_section (sym->objfile ()),
3781 funfirstline);
3782 sal.symbol = sym;
3783 return sal;
3787 /* Given a function start address FUNC_ADDR and SYMTAB, find the first
3788 address for that function that has an entry in SYMTAB's line info
3789 table. If such an entry cannot be found, return FUNC_ADDR
3790 unaltered. */
3792 static CORE_ADDR
3793 skip_prologue_using_lineinfo (CORE_ADDR func_addr, struct symtab *symtab)
3795 CORE_ADDR func_start, func_end;
3796 const struct linetable *l;
3797 int i;
3799 /* Give up if this symbol has no lineinfo table. */
3800 l = symtab->linetable ();
3801 if (l == NULL)
3802 return func_addr;
3804 /* Get the range for the function's PC values, or give up if we
3805 cannot, for some reason. */
3806 if (!find_pc_partial_function (func_addr, NULL, &func_start, &func_end))
3807 return func_addr;
3809 struct objfile *objfile = symtab->compunit ()->objfile ();
3811 /* Linetable entries are ordered by PC values, see the commentary in
3812 symtab.h where `struct linetable' is defined. Thus, the first
3813 entry whose PC is in the range [FUNC_START..FUNC_END[ is the
3814 address we are looking for. */
3815 for (i = 0; i < l->nitems; i++)
3817 const linetable_entry *item = &(l->item[i]);
3818 CORE_ADDR item_pc = item->pc (objfile);
3820 /* Don't use line numbers of zero, they mark special entries in
3821 the table. See the commentary on symtab.h before the
3822 definition of struct linetable. */
3823 if (item->line > 0 && func_start <= item_pc && item_pc < func_end)
3824 return item_pc;
3827 return func_addr;
3830 /* Try to locate the address where a breakpoint should be placed past the
3831 prologue of function starting at FUNC_ADDR using the line table.
3833 Return the address associated with the first entry in the line-table for
3834 the function starting at FUNC_ADDR which has prologue_end set to true if
3835 such entry exist, otherwise return an empty optional. */
3837 static std::optional<CORE_ADDR>
3838 skip_prologue_using_linetable (CORE_ADDR func_addr)
3840 CORE_ADDR start_pc, end_pc;
3842 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
3843 return {};
3845 const struct symtab_and_line prologue_sal = find_pc_line (start_pc, 0);
3846 if (prologue_sal.symtab != nullptr
3847 && prologue_sal.symtab->language () != language_asm)
3849 const linetable *linetable = prologue_sal.symtab->linetable ();
3851 struct objfile *objfile = prologue_sal.symtab->compunit ()->objfile ();
3853 unrelocated_addr unrel_start
3854 = unrelocated_addr (start_pc - objfile->text_section_offset ());
3855 unrelocated_addr unrel_end
3856 = unrelocated_addr (end_pc - objfile->text_section_offset ());
3858 auto it = std::lower_bound
3859 (linetable->item, linetable->item + linetable->nitems, unrel_start,
3860 [] (const linetable_entry &lte, unrelocated_addr pc)
3862 return lte.unrelocated_pc () < pc;
3865 for (;
3866 (it < linetable->item + linetable->nitems
3867 && it->unrelocated_pc () < unrel_end);
3868 it++)
3869 if (it->prologue_end)
3870 return {it->pc (objfile)};
3873 return {};
3876 /* Adjust SAL to the first instruction past the function prologue.
3877 If the PC was explicitly specified, the SAL is not changed.
3878 If the line number was explicitly specified then the SAL can still be
3879 updated, unless the language for SAL is assembler, in which case the SAL
3880 will be left unchanged.
3881 If SAL is already past the prologue, then do nothing. */
3883 void
3884 skip_prologue_sal (struct symtab_and_line *sal)
3886 struct symbol *sym;
3887 struct symtab_and_line start_sal;
3888 CORE_ADDR pc, saved_pc;
3889 struct obj_section *section;
3890 const char *name;
3891 struct objfile *objfile;
3892 struct gdbarch *gdbarch;
3893 const struct block *b, *function_block;
3894 int force_skip, skip;
3896 /* Do not change the SAL if PC was specified explicitly. */
3897 if (sal->explicit_pc)
3898 return;
3900 /* In assembly code, if the user asks for a specific line then we should
3901 not adjust the SAL. The user already has instruction level
3902 visibility in this case, so selecting a line other than one requested
3903 is likely to be the wrong choice. */
3904 if (sal->symtab != nullptr
3905 && sal->explicit_line
3906 && sal->symtab->language () == language_asm)
3907 return;
3909 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3911 switch_to_program_space_and_thread (sal->pspace);
3913 sym = find_pc_sect_function (sal->pc, sal->section);
3914 if (sym != NULL)
3916 objfile = sym->objfile ();
3917 pc = sym->value_block ()->entry_pc ();
3918 section = sym->obj_section (objfile);
3919 name = sym->linkage_name ();
3921 else
3923 bound_minimal_symbol msymbol
3924 = lookup_minimal_symbol_by_pc_section (sal->pc, sal->section);
3926 if (msymbol.minsym == NULL)
3927 return;
3929 objfile = msymbol.objfile;
3930 pc = msymbol.value_address ();
3931 section = msymbol.minsym->obj_section (objfile);
3932 name = msymbol.minsym->linkage_name ();
3935 gdbarch = objfile->arch ();
3937 /* Process the prologue in two passes. In the first pass try to skip the
3938 prologue (SKIP is true) and verify there is a real need for it (indicated
3939 by FORCE_SKIP). If no such reason was found run a second pass where the
3940 prologue is not skipped (SKIP is false). */
3942 skip = 1;
3943 force_skip = 1;
3945 /* Be conservative - allow direct PC (without skipping prologue) only if we
3946 have proven the CU (Compilation Unit) supports it. sal->SYMTAB does not
3947 have to be set by the caller so we use SYM instead. */
3948 if (sym != NULL
3949 && sym->symtab ()->compunit ()->locations_valid ())
3950 force_skip = 0;
3952 saved_pc = pc;
3955 pc = saved_pc;
3957 /* Check if the compiler explicitly indicated where a breakpoint should
3958 be placed to skip the prologue. */
3959 if (!ignore_prologue_end_flag && skip)
3961 std::optional<CORE_ADDR> linetable_pc
3962 = skip_prologue_using_linetable (pc);
3963 if (linetable_pc)
3965 pc = *linetable_pc;
3966 start_sal = find_pc_sect_line (pc, section, 0);
3967 force_skip = 1;
3968 continue;
3972 /* If the function is in an unmapped overlay, use its unmapped LMA address,
3973 so that gdbarch_skip_prologue has something unique to work on. */
3974 if (section_is_overlay (section) && !section_is_mapped (section))
3975 pc = overlay_unmapped_address (pc, section);
3977 /* Skip "first line" of function (which is actually its prologue). */
3978 pc += gdbarch_deprecated_function_start_offset (gdbarch);
3979 if (gdbarch_skip_entrypoint_p (gdbarch))
3980 pc = gdbarch_skip_entrypoint (gdbarch, pc);
3981 if (skip)
3982 pc = gdbarch_skip_prologue_noexcept (gdbarch, pc);
3984 /* For overlays, map pc back into its mapped VMA range. */
3985 pc = overlay_mapped_address (pc, section);
3987 /* Calculate line number. */
3988 start_sal = find_pc_sect_line (pc, section, 0);
3990 /* Check if gdbarch_skip_prologue left us in mid-line, and the next
3991 line is still part of the same function. */
3992 if (skip && start_sal.pc != pc
3993 && (sym ? (sym->value_block ()->entry_pc () <= start_sal.end
3994 && start_sal.end < sym->value_block()->end ())
3995 : (lookup_minimal_symbol_by_pc_section (start_sal.end, section).minsym
3996 == lookup_minimal_symbol_by_pc_section (pc, section).minsym)))
3998 /* First pc of next line */
3999 pc = start_sal.end;
4000 /* Recalculate the line number (might not be N+1). */
4001 start_sal = find_pc_sect_line (pc, section, 0);
4004 /* On targets with executable formats that don't have a concept of
4005 constructors (ELF with .init has, PE doesn't), gcc emits a call
4006 to `__main' in `main' between the prologue and before user
4007 code. */
4008 if (gdbarch_skip_main_prologue_p (gdbarch)
4009 && name && strcmp_iw (name, "main") == 0)
4011 pc = gdbarch_skip_main_prologue (gdbarch, pc);
4012 /* Recalculate the line number (might not be N+1). */
4013 start_sal = find_pc_sect_line (pc, section, 0);
4014 force_skip = 1;
4017 while (!force_skip && skip--);
4019 /* If we still don't have a valid source line, try to find the first
4020 PC in the lineinfo table that belongs to the same function. This
4021 happens with COFF debug info, which does not seem to have an
4022 entry in lineinfo table for the code after the prologue which has
4023 no direct relation to source. For example, this was found to be
4024 the case with the DJGPP target using "gcc -gcoff" when the
4025 compiler inserted code after the prologue to make sure the stack
4026 is aligned. */
4027 if (!force_skip && sym && start_sal.symtab == NULL)
4029 pc = skip_prologue_using_lineinfo (pc, sym->symtab ());
4030 /* Recalculate the line number. */
4031 start_sal = find_pc_sect_line (pc, section, 0);
4034 /* If we're already past the prologue, leave SAL unchanged. Otherwise
4035 forward SAL to the end of the prologue. */
4036 if (sal->pc >= pc)
4037 return;
4039 sal->pc = pc;
4040 sal->section = section;
4041 sal->symtab = start_sal.symtab;
4042 sal->line = start_sal.line;
4043 sal->end = start_sal.end;
4045 /* Check if we are now inside an inlined function. If we can,
4046 use the call site of the function instead. */
4047 b = block_for_pc_sect (sal->pc, sal->section);
4048 function_block = NULL;
4049 while (b != NULL)
4051 if (b->function () != NULL && b->inlined_p ())
4052 function_block = b;
4053 else if (b->function () != NULL)
4054 break;
4055 b = b->superblock ();
4057 if (function_block != NULL
4058 && function_block->function ()->line () != 0)
4060 sal->line = function_block->function ()->line ();
4061 sal->symtab = function_block->function ()->symtab ();
4065 /* Given PC at the function's start address, attempt to find the
4066 prologue end using SAL information. Return zero if the skip fails.
4068 A non-optimized prologue traditionally has one SAL for the function
4069 and a second for the function body. A single line function has
4070 them both pointing at the same line.
4072 An optimized prologue is similar but the prologue may contain
4073 instructions (SALs) from the instruction body. Need to skip those
4074 while not getting into the function body.
4076 The functions end point and an increasing SAL line are used as
4077 indicators of the prologue's endpoint.
4079 This code is based on the function refine_prologue_limit
4080 (found in ia64). */
4082 CORE_ADDR
4083 skip_prologue_using_sal (struct gdbarch *gdbarch, CORE_ADDR func_addr)
4085 struct symtab_and_line prologue_sal;
4086 CORE_ADDR start_pc;
4087 CORE_ADDR end_pc;
4088 const struct block *bl;
4090 /* Get an initial range for the function. */
4091 find_pc_partial_function (func_addr, NULL, &start_pc, &end_pc);
4092 start_pc += gdbarch_deprecated_function_start_offset (gdbarch);
4094 prologue_sal = find_pc_line (start_pc, 0);
4095 if (prologue_sal.line != 0)
4097 /* For languages other than assembly, treat two consecutive line
4098 entries at the same address as a zero-instruction prologue.
4099 The GNU assembler emits separate line notes for each instruction
4100 in a multi-instruction macro, but compilers generally will not
4101 do this. */
4102 if (prologue_sal.symtab->language () != language_asm)
4104 struct objfile *objfile
4105 = prologue_sal.symtab->compunit ()->objfile ();
4106 const linetable *linetable = prologue_sal.symtab->linetable ();
4107 gdb_assert (linetable->nitems > 0);
4108 int idx = 0;
4110 /* Skip any earlier lines, and any end-of-sequence marker
4111 from a previous function. */
4112 while (idx + 1 < linetable->nitems
4113 && (linetable->item[idx].pc (objfile) != prologue_sal.pc
4114 || linetable->item[idx].line == 0))
4115 idx++;
4117 if (idx + 1 < linetable->nitems
4118 && linetable->item[idx+1].line != 0
4119 && linetable->item[idx+1].pc (objfile) == start_pc)
4120 return start_pc;
4123 /* If there is only one sal that covers the entire function,
4124 then it is probably a single line function, like
4125 "foo(){}". */
4126 if (prologue_sal.end >= end_pc)
4127 return 0;
4129 while (prologue_sal.end < end_pc)
4131 struct symtab_and_line sal;
4133 sal = find_pc_line (prologue_sal.end, 0);
4134 if (sal.line == 0)
4135 break;
4136 /* Assume that a consecutive SAL for the same (or larger)
4137 line mark the prologue -> body transition. */
4138 if (sal.line >= prologue_sal.line)
4139 break;
4140 /* Likewise if we are in a different symtab altogether
4141 (e.g. within a file included via #include).  */
4142 if (sal.symtab != prologue_sal.symtab)
4143 break;
4145 /* The line number is smaller. Check that it's from the
4146 same function, not something inlined. If it's inlined,
4147 then there is no point comparing the line numbers. */
4148 bl = block_for_pc (prologue_sal.end);
4149 while (bl)
4151 if (bl->inlined_p ())
4152 break;
4153 if (bl->function ())
4155 bl = NULL;
4156 break;
4158 bl = bl->superblock ();
4160 if (bl != NULL)
4161 break;
4163 /* The case in which compiler's optimizer/scheduler has
4164 moved instructions into the prologue. We look ahead in
4165 the function looking for address ranges whose
4166 corresponding line number is less the first one that we
4167 found for the function. This is more conservative then
4168 refine_prologue_limit which scans a large number of SALs
4169 looking for any in the prologue. */
4170 prologue_sal = sal;
4174 if (prologue_sal.end < end_pc)
4175 /* Return the end of this line, or zero if we could not find a
4176 line. */
4177 return prologue_sal.end;
4178 else
4179 /* Don't return END_PC, which is past the end of the function. */
4180 return prologue_sal.pc;
4183 /* See symtab.h. */
4185 std::optional<CORE_ADDR>
4186 find_epilogue_using_linetable (CORE_ADDR func_addr)
4188 CORE_ADDR start_pc, end_pc;
4190 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
4191 return {};
4193 /* While the standard allows for multiple points marked with epilogue_begin
4194 in the same function, for performance reasons, this function will only
4195 find the last address that sets this flag for a given block.
4197 The lines of a function can be described by several line tables in case
4198 there are different files involved. There's a corner case where a
4199 function epilogue is in a different file than a function start, and using
4200 start_pc as argument to find_pc_line will mean we won't find the
4201 epilogue. Instead, use "end_pc - 1" to maximize our chances of picking
4202 the line table containing an epilogue. */
4203 const struct symtab_and_line sal = find_pc_line (end_pc - 1, 0);
4204 if (sal.symtab != nullptr && sal.symtab->language () != language_asm)
4206 struct objfile *objfile = sal.symtab->compunit ()->objfile ();
4207 unrelocated_addr unrel_start
4208 = unrelocated_addr (start_pc - objfile->text_section_offset ());
4209 unrelocated_addr unrel_end
4210 = unrelocated_addr (end_pc - objfile->text_section_offset ());
4212 const linetable *linetable = sal.symtab->linetable ();
4213 if (linetable == nullptr || linetable->nitems == 0)
4215 /* Empty line table. */
4216 return {};
4219 /* Find the first linetable entry after the current function. Note that
4220 this also may be an end_sequence entry. */
4221 auto it = std::lower_bound
4222 (linetable->item, linetable->item + linetable->nitems, unrel_end,
4223 [] (const linetable_entry &lte, unrelocated_addr pc)
4225 return lte.unrelocated_pc () < pc;
4227 if (it == linetable->item + linetable->nitems)
4229 /* We couldn't find either:
4230 - a linetable entry starting the function after the current
4231 function, or
4232 - an end_sequence entry that terminates the current function
4233 at unrel_end.
4235 This can happen when the linetable doesn't describe the full
4236 extent of the function. This can be triggered with:
4237 - compiler-generated debug info, in the cornercase that the pc
4238 with which we call find_pc_line resides in a different file
4239 than unrel_end, or
4240 - invalid dwarf assembly debug info.
4241 In the former case, there's no point in iterating further, simply
4242 return "not found". In the latter case, there's no current
4243 incentive to attempt to support this, so handle this
4244 conservatively and do the same. */
4245 return {};
4248 if (unrel_end < it->unrelocated_pc ())
4250 /* We found a line entry that starts past the end of the
4251 function. This can happen if the previous entry straddles
4252 two functions, which shouldn't happen with compiler-generated
4253 debug info. Handle the corner case conservatively. */
4254 return {};
4256 gdb_assert (unrel_end == it->unrelocated_pc ());
4258 /* Move to the last linetable entry of the current function. */
4259 if (it == &linetable->item[0])
4261 /* Doing it-- would introduce undefined behaviour, avoid it by
4262 explicitly handling this case. */
4263 return {};
4265 it--;
4266 if (it->unrelocated_pc () < unrel_start)
4268 /* Not in the current function. */
4269 return {};
4271 gdb_assert (it->unrelocated_pc () < unrel_end);
4273 /* We're at the the last linetable entry of the current function. This
4274 is probably where the epilogue begins, but since the DWARF 5 spec
4275 doesn't guarantee it, we iterate backwards through the current
4276 function until we either find the epilogue beginning, or are sure
4277 that it doesn't exist. */
4278 for (; it >= &linetable->item[0]; it--)
4280 if (it->unrelocated_pc () < unrel_start)
4282 /* No longer in the current function. */
4283 break;
4286 if (it->epilogue_begin)
4288 /* Found the beginning of the epilogue. */
4289 return {it->pc (objfile)};
4292 if (it == &linetable->item[0])
4294 /* No more entries in the current function.
4295 Doing it-- would introduce undefined behaviour, avoid it by
4296 explicitly handling this case. */
4297 break;
4302 return {};
4305 /* See symtab.h. */
4307 symbol *
4308 find_function_alias_target (bound_minimal_symbol msymbol)
4310 CORE_ADDR func_addr;
4311 if (!msymbol_is_function (msymbol.objfile, msymbol.minsym, &func_addr))
4312 return NULL;
4314 symbol *sym = find_pc_function (func_addr);
4315 if (sym != NULL
4316 && sym->aclass () == LOC_BLOCK
4317 && sym->value_block ()->entry_pc () == func_addr)
4318 return sym;
4320 return NULL;
4324 /* If P is of the form "operator[ \t]+..." where `...' is
4325 some legitimate operator text, return a pointer to the
4326 beginning of the substring of the operator text.
4327 Otherwise, return "". */
4329 static const char *
4330 operator_chars (const char *p, const char **end)
4332 *end = "";
4333 if (!startswith (p, CP_OPERATOR_STR))
4334 return *end;
4335 p += CP_OPERATOR_LEN;
4337 /* Don't get faked out by `operator' being part of a longer
4338 identifier. */
4339 if (isalpha (*p) || *p == '_' || *p == '$' || *p == '\0')
4340 return *end;
4342 /* Allow some whitespace between `operator' and the operator symbol. */
4343 while (*p == ' ' || *p == '\t')
4344 p++;
4346 /* Recognize 'operator TYPENAME'. */
4348 if (isalpha (*p) || *p == '_' || *p == '$')
4350 const char *q = p + 1;
4352 while (isalnum (*q) || *q == '_' || *q == '$')
4353 q++;
4354 *end = q;
4355 return p;
4358 while (*p)
4359 switch (*p)
4361 case '\\': /* regexp quoting */
4362 if (p[1] == '*')
4364 if (p[2] == '=') /* 'operator\*=' */
4365 *end = p + 3;
4366 else /* 'operator\*' */
4367 *end = p + 2;
4368 return p;
4370 else if (p[1] == '[')
4372 if (p[2] == ']')
4373 error (_("mismatched quoting on brackets, "
4374 "try 'operator\\[\\]'"));
4375 else if (p[2] == '\\' && p[3] == ']')
4377 *end = p + 4; /* 'operator\[\]' */
4378 return p;
4380 else
4381 error (_("nothing is allowed between '[' and ']'"));
4383 else
4385 /* Gratuitous quote: skip it and move on. */
4386 p++;
4387 continue;
4389 break;
4390 case '!':
4391 case '=':
4392 case '*':
4393 case '/':
4394 case '%':
4395 case '^':
4396 if (p[1] == '=')
4397 *end = p + 2;
4398 else
4399 *end = p + 1;
4400 return p;
4401 case '<':
4402 case '>':
4403 case '+':
4404 case '-':
4405 case '&':
4406 case '|':
4407 if (p[0] == '-' && p[1] == '>')
4409 /* Struct pointer member operator 'operator->'. */
4410 if (p[2] == '*')
4412 *end = p + 3; /* 'operator->*' */
4413 return p;
4415 else if (p[2] == '\\')
4417 *end = p + 4; /* Hopefully 'operator->\*' */
4418 return p;
4420 else
4422 *end = p + 2; /* 'operator->' */
4423 return p;
4426 if (p[1] == '=' || p[1] == p[0])
4427 *end = p + 2;
4428 else
4429 *end = p + 1;
4430 return p;
4431 case '~':
4432 case ',':
4433 *end = p + 1;
4434 return p;
4435 case '(':
4436 if (p[1] != ')')
4437 error (_("`operator ()' must be specified "
4438 "without whitespace in `()'"));
4439 *end = p + 2;
4440 return p;
4441 case '?':
4442 if (p[1] != ':')
4443 error (_("`operator ?:' must be specified "
4444 "without whitespace in `?:'"));
4445 *end = p + 2;
4446 return p;
4447 case '[':
4448 if (p[1] != ']')
4449 error (_("`operator []' must be specified "
4450 "without whitespace in `[]'"));
4451 *end = p + 2;
4452 return p;
4453 default:
4454 error (_("`operator %s' not supported"), p);
4455 break;
4458 *end = "";
4459 return *end;
4463 /* See class declaration. */
4465 info_sources_filter::info_sources_filter (match_on match_type,
4466 const char *regexp)
4467 : m_match_type (match_type),
4468 m_regexp (regexp)
4470 /* Setup the compiled regular expression M_C_REGEXP based on M_REGEXP. */
4471 if (m_regexp != nullptr && *m_regexp != '\0')
4473 gdb_assert (m_regexp != nullptr);
4475 int cflags = REG_NOSUB;
4476 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
4477 cflags |= REG_ICASE;
4478 #endif
4479 m_c_regexp.emplace (m_regexp, cflags, _("Invalid regexp"));
4483 /* See class declaration. */
4485 bool
4486 info_sources_filter::matches (const char *fullname) const
4488 /* Does it match regexp? */
4489 if (m_c_regexp.has_value ())
4491 const char *to_match;
4492 std::string dirname;
4494 switch (m_match_type)
4496 case match_on::DIRNAME:
4497 dirname = ldirname (fullname);
4498 to_match = dirname.c_str ();
4499 break;
4500 case match_on::BASENAME:
4501 to_match = lbasename (fullname);
4502 break;
4503 case match_on::FULLNAME:
4504 to_match = fullname;
4505 break;
4506 default:
4507 gdb_assert_not_reached ("bad m_match_type");
4510 if (m_c_regexp->exec (to_match, 0, NULL, 0) != 0)
4511 return false;
4514 return true;
4517 /* Data structure to maintain the state used for printing the results of
4518 the 'info sources' command. */
4520 struct output_source_filename_data
4522 /* Create an object for displaying the results of the 'info sources'
4523 command to UIOUT. FILTER must remain valid and unchanged for the
4524 lifetime of this object as this object retains a reference to FILTER. */
4525 output_source_filename_data (struct ui_out *uiout,
4526 const info_sources_filter &filter)
4527 : m_filter (filter),
4528 m_uiout (uiout)
4529 { /* Nothing. */ }
4531 DISABLE_COPY_AND_ASSIGN (output_source_filename_data);
4533 /* Reset enough state of this object so we can match against a new set of
4534 files. The existing regular expression is retained though. */
4535 void reset_output ()
4537 m_first = true;
4538 m_filename_seen_cache.clear ();
4541 /* Worker for sources_info, outputs the file name formatted for either
4542 cli or mi (based on the current_uiout). In cli mode displays
4543 FULLNAME with a comma separating this name from any previously
4544 printed name (line breaks are added at the comma). In MI mode
4545 outputs a tuple containing DISP_NAME (the files display name),
4546 FULLNAME, and EXPANDED_P (true when this file is from a fully
4547 expanded symtab, otherwise false). */
4548 void output (const char *disp_name, const char *fullname, bool expanded_p);
4550 /* An overload suitable for use as a callback to
4551 quick_symbol_functions::map_symbol_filenames. */
4552 void operator() (const char *filename, const char *fullname)
4554 /* The false here indicates that this file is from an unexpanded
4555 symtab. */
4556 output (filename, fullname, false);
4559 /* Return true if at least one filename has been printed (after a call to
4560 output) since either this object was created, or the last call to
4561 reset_output. */
4562 bool printed_filename_p () const
4564 return !m_first;
4567 private:
4569 /* Flag of whether we're printing the first one. */
4570 bool m_first = true;
4572 /* Cache of what we've seen so far. */
4573 filename_seen_cache m_filename_seen_cache;
4575 /* How source filename should be filtered. */
4576 const info_sources_filter &m_filter;
4578 /* The object to which output is sent. */
4579 struct ui_out *m_uiout;
4582 /* See comment in class declaration above. */
4584 void
4585 output_source_filename_data::output (const char *disp_name,
4586 const char *fullname,
4587 bool expanded_p)
4589 /* Since a single source file can result in several partial symbol
4590 tables, we need to avoid printing it more than once. Note: if
4591 some of the psymtabs are read in and some are not, it gets
4592 printed both under "Source files for which symbols have been
4593 read" and "Source files for which symbols will be read in on
4594 demand". I consider this a reasonable way to deal with the
4595 situation. I'm not sure whether this can also happen for
4596 symtabs; it doesn't hurt to check. */
4598 /* Was NAME already seen? If so, then don't print it again. */
4599 if (m_filename_seen_cache.seen (fullname))
4600 return;
4602 /* If the filter rejects this file then don't print it. */
4603 if (!m_filter.matches (fullname))
4604 return;
4606 ui_out_emit_tuple ui_emitter (m_uiout, nullptr);
4608 /* Print it and reset *FIRST. */
4609 if (!m_first)
4610 m_uiout->text (", ");
4611 m_first = false;
4613 m_uiout->wrap_hint (0);
4614 if (m_uiout->is_mi_like_p ())
4616 m_uiout->field_string ("file", disp_name, file_name_style.style ());
4617 if (fullname != nullptr)
4618 m_uiout->field_string ("fullname", fullname,
4619 file_name_style.style ());
4620 m_uiout->field_string ("debug-fully-read",
4621 (expanded_p ? "true" : "false"));
4623 else
4625 if (fullname == nullptr)
4626 fullname = disp_name;
4627 m_uiout->field_string ("fullname", fullname,
4628 file_name_style.style ());
4632 /* For the 'info sources' command, what part of the file names should we be
4633 matching the user supplied regular expression against? */
4635 struct filename_partial_match_opts
4637 /* Only match the directory name part. */
4638 bool dirname = false;
4640 /* Only match the basename part. */
4641 bool basename = false;
4644 using isrc_flag_option_def
4645 = gdb::option::flag_option_def<filename_partial_match_opts>;
4647 static const gdb::option::option_def info_sources_option_defs[] = {
4649 isrc_flag_option_def {
4650 "dirname",
4651 [] (filename_partial_match_opts *opts) { return &opts->dirname; },
4652 N_("Show only the files having a dirname matching REGEXP."),
4655 isrc_flag_option_def {
4656 "basename",
4657 [] (filename_partial_match_opts *opts) { return &opts->basename; },
4658 N_("Show only the files having a basename matching REGEXP."),
4663 /* Create an option_def_group for the "info sources" options, with
4664 ISRC_OPTS as context. */
4666 static inline gdb::option::option_def_group
4667 make_info_sources_options_def_group (filename_partial_match_opts *isrc_opts)
4669 return {{info_sources_option_defs}, isrc_opts};
4672 /* Completer for "info sources". */
4674 static void
4675 info_sources_command_completer (cmd_list_element *ignore,
4676 completion_tracker &tracker,
4677 const char *text, const char *word)
4679 const auto group = make_info_sources_options_def_group (nullptr);
4680 if (gdb::option::complete_options
4681 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
4682 return;
4685 /* See symtab.h. */
4687 void
4688 info_sources_worker (struct ui_out *uiout,
4689 bool group_by_objfile,
4690 const info_sources_filter &filter)
4692 output_source_filename_data data (uiout, filter);
4694 ui_out_emit_list results_emitter (uiout, "files");
4695 std::optional<ui_out_emit_tuple> output_tuple;
4696 std::optional<ui_out_emit_list> sources_list;
4698 gdb_assert (group_by_objfile || uiout->is_mi_like_p ());
4700 for (objfile *objfile : current_program_space->objfiles ())
4702 if (group_by_objfile)
4704 output_tuple.emplace (uiout, nullptr);
4705 uiout->field_string ("filename", objfile_name (objfile),
4706 file_name_style.style ());
4707 uiout->text (":\n");
4708 bool debug_fully_readin = !objfile->has_unexpanded_symtabs ();
4709 if (uiout->is_mi_like_p ())
4711 const char *debug_info_state;
4712 if (objfile_has_symbols (objfile))
4714 if (debug_fully_readin)
4715 debug_info_state = "fully-read";
4716 else
4717 debug_info_state = "partially-read";
4719 else
4720 debug_info_state = "none";
4721 current_uiout->field_string ("debug-info", debug_info_state);
4723 else
4725 if (!debug_fully_readin)
4726 uiout->text ("(Full debug information has not yet been read "
4727 "for this file.)\n");
4728 if (!objfile_has_symbols (objfile))
4729 uiout->text ("(Objfile has no debug information.)\n");
4730 uiout->text ("\n");
4732 sources_list.emplace (uiout, "sources");
4735 for (compunit_symtab *cu : objfile->compunits ())
4737 for (symtab *s : cu->filetabs ())
4739 const char *file = symtab_to_filename_for_display (s);
4740 const char *fullname = symtab_to_fullname (s);
4741 data.output (file, fullname, true);
4745 if (group_by_objfile)
4747 objfile->map_symbol_filenames (data, true /* need_fullname */);
4748 if (data.printed_filename_p ())
4749 uiout->text ("\n\n");
4750 data.reset_output ();
4751 sources_list.reset ();
4752 output_tuple.reset ();
4756 if (!group_by_objfile)
4758 data.reset_output ();
4759 map_symbol_filenames (data, true /*need_fullname*/);
4763 /* Implement the 'info sources' command. */
4765 static void
4766 info_sources_command (const char *args, int from_tty)
4768 if (!have_full_symbols (current_program_space)
4769 && !have_partial_symbols (current_program_space))
4770 error (_ ("No symbol table is loaded. Use the \"file\" command."));
4772 filename_partial_match_opts match_opts;
4773 auto group = make_info_sources_options_def_group (&match_opts);
4774 gdb::option::process_options
4775 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
4777 if (match_opts.dirname && match_opts.basename)
4778 error (_("You cannot give both -basename and -dirname to 'info sources'."));
4780 const char *regex = nullptr;
4781 if (args != NULL && *args != '\000')
4782 regex = args;
4784 if ((match_opts.dirname || match_opts.basename) && regex == nullptr)
4785 error (_("Missing REGEXP for 'info sources'."));
4787 info_sources_filter::match_on match_type;
4788 if (match_opts.dirname)
4789 match_type = info_sources_filter::match_on::DIRNAME;
4790 else if (match_opts.basename)
4791 match_type = info_sources_filter::match_on::BASENAME;
4792 else
4793 match_type = info_sources_filter::match_on::FULLNAME;
4795 info_sources_filter filter (match_type, regex);
4796 info_sources_worker (current_uiout, true, filter);
4799 /* Compare FILE against all the entries of FILENAMES. If BASENAMES is
4800 true compare only lbasename of FILENAMES. */
4802 static bool
4803 file_matches (const char *file,
4804 const std::vector<gdb::unique_xmalloc_ptr<char>> &filenames,
4805 bool basenames)
4807 if (filenames.empty ())
4808 return true;
4810 for (const auto &name : filenames)
4812 const char *lname = (basenames ? lbasename (name.get ()) : name.get ());
4813 if (compare_filenames_for_search (file, lname))
4814 return true;
4817 return false;
4820 /* Helper function for std::sort on symbol_search objects. Can only sort
4821 symbols, not minimal symbols. */
4824 symbol_search::compare_search_syms (const symbol_search &sym_a,
4825 const symbol_search &sym_b)
4827 int c;
4829 c = FILENAME_CMP (sym_a.symbol->symtab ()->filename,
4830 sym_b.symbol->symtab ()->filename);
4831 if (c != 0)
4832 return c;
4834 if (sym_a.block != sym_b.block)
4835 return sym_a.block - sym_b.block;
4837 return strcmp (sym_a.symbol->print_name (), sym_b.symbol->print_name ());
4840 /* Returns true if the type_name of symbol_type of SYM matches TREG.
4841 If SYM has no symbol_type or symbol_name, returns false. */
4843 bool
4844 treg_matches_sym_type_name (const compiled_regex &treg,
4845 const struct symbol *sym)
4847 struct type *sym_type;
4848 std::string printed_sym_type_name;
4850 symbol_lookup_debug_printf_v ("treg_matches_sym_type_name, sym %s",
4851 sym->natural_name ());
4853 sym_type = sym->type ();
4854 if (sym_type == NULL)
4855 return false;
4858 scoped_switch_to_sym_language_if_auto l (sym);
4860 printed_sym_type_name = type_to_string (sym_type);
4863 symbol_lookup_debug_printf_v ("sym_type_name %s",
4864 printed_sym_type_name.c_str ());
4866 if (printed_sym_type_name.empty ())
4867 return false;
4869 return treg.exec (printed_sym_type_name.c_str (), 0, NULL, 0) == 0;
4872 /* See symtab.h. */
4874 bool
4875 global_symbol_searcher::is_suitable_msymbol
4876 (const domain_search_flags kind, const minimal_symbol *msymbol)
4878 switch (msymbol->type ())
4880 case mst_data:
4881 case mst_bss:
4882 case mst_file_data:
4883 case mst_file_bss:
4884 return (kind & SEARCH_VAR_DOMAIN) != 0;
4885 case mst_text:
4886 case mst_file_text:
4887 case mst_solib_trampoline:
4888 case mst_text_gnu_ifunc:
4889 return (kind & SEARCH_FUNCTION_DOMAIN) != 0;
4890 default:
4891 return false;
4895 /* See symtab.h. */
4897 bool
4898 global_symbol_searcher::expand_symtabs
4899 (objfile *objfile, const std::optional<compiled_regex> &preg) const
4901 domain_search_flags kind = m_kind;
4902 bool found_msymbol = false;
4904 auto do_file_match = [&] (const char *filename, bool basenames)
4906 return file_matches (filename, m_filenames, basenames);
4908 gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher = nullptr;
4909 if (!m_filenames.empty ())
4910 file_matcher = do_file_match;
4912 objfile->expand_symtabs_matching
4913 (file_matcher,
4914 &lookup_name_info::match_any (),
4915 [&] (const char *symname)
4917 return (!preg.has_value ()
4918 || preg->exec (symname, 0, NULL, 0) == 0);
4920 NULL,
4921 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
4922 kind);
4924 /* Here, we search through the minimal symbol tables for functions and
4925 variables that match, and force their symbols to be read. This is in
4926 particular necessary for demangled variable names, which are no longer
4927 put into the partial symbol tables. The symbol will then be found
4928 during the scan of symtabs later.
4930 For functions, find_pc_symtab should succeed if we have debug info for
4931 the function, for variables we have to call
4932 lookup_symbol_in_objfile_from_linkage_name to determine if the
4933 variable has debug info. If the lookup fails, set found_msymbol so
4934 that we will rescan to print any matching symbols without debug info.
4935 We only search the objfile the msymbol came from, we no longer search
4936 all objfiles. In large programs (1000s of shared libs) searching all
4937 objfiles is not worth the pain. */
4938 if (m_filenames.empty ()
4939 && (kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN)) != 0)
4941 for (minimal_symbol *msymbol : objfile->msymbols ())
4943 QUIT;
4945 if (msymbol->created_by_gdb)
4946 continue;
4948 if (is_suitable_msymbol (kind, msymbol))
4950 if (!preg.has_value ()
4951 || preg->exec (msymbol->natural_name (), 0,
4952 NULL, 0) == 0)
4954 /* An important side-effect of these lookup functions is
4955 to expand the symbol table if msymbol is found, later
4956 in the process we will add matching symbols or
4957 msymbols to the results list, and that requires that
4958 the symbols tables are expanded. */
4959 if ((kind & SEARCH_FUNCTION_DOMAIN) != 0
4960 ? (find_pc_compunit_symtab
4961 (msymbol->value_address (objfile)) == NULL)
4962 : (lookup_symbol_in_objfile_from_linkage_name
4963 (objfile, msymbol->linkage_name (),
4964 SEARCH_VFT)
4965 .symbol == NULL))
4966 found_msymbol = true;
4972 return found_msymbol;
4975 /* See symtab.h. */
4977 bool
4978 global_symbol_searcher::add_matching_symbols
4979 (objfile *objfile,
4980 const std::optional<compiled_regex> &preg,
4981 const std::optional<compiled_regex> &treg,
4982 std::set<symbol_search> *result_set) const
4984 domain_search_flags kind = m_kind;
4986 /* Add matching symbols (if not already present). */
4987 for (compunit_symtab *cust : objfile->compunits ())
4989 const struct blockvector *bv = cust->blockvector ();
4991 for (block_enum block : { GLOBAL_BLOCK, STATIC_BLOCK })
4993 const struct block *b = bv->block (block);
4995 for (struct symbol *sym : block_iterator_range (b))
4997 struct symtab *real_symtab = sym->symtab ();
4999 QUIT;
5001 /* Check first sole REAL_SYMTAB->FILENAME. It does
5002 not need to be a substring of symtab_to_fullname as
5003 it may contain "./" etc. */
5004 if (!(file_matches (real_symtab->filename, m_filenames, false)
5005 || ((basenames_may_differ
5006 || file_matches (lbasename (real_symtab->filename),
5007 m_filenames, true))
5008 && file_matches (symtab_to_fullname (real_symtab),
5009 m_filenames, false))))
5010 continue;
5012 if (!sym->matches (kind))
5013 continue;
5015 if (preg.has_value () && preg->exec (sym->natural_name (), 0,
5016 nullptr, 0) != 0)
5017 continue;
5019 if (((sym->domain () == VAR_DOMAIN
5020 || sym->domain () == FUNCTION_DOMAIN)
5021 && treg.has_value ()
5022 && !treg_matches_sym_type_name (*treg, sym)))
5023 continue;
5025 if ((kind & SEARCH_VAR_DOMAIN) != 0)
5027 if (sym->aclass () == LOC_UNRESOLVED
5028 /* LOC_CONST can be used for more than
5029 just enums, e.g., c++ static const
5030 members. We only want to skip enums
5031 here. */
5032 || (sym->aclass () == LOC_CONST
5033 && (sym->type ()->code () == TYPE_CODE_ENUM)))
5034 continue;
5036 if (sym->domain () == MODULE_DOMAIN && sym->line () == 0)
5037 continue;
5039 if (result_set->size () < m_max_search_results)
5041 /* Match, insert if not already in the results. */
5042 symbol_search ss (block, sym);
5043 if (result_set->find (ss) == result_set->end ())
5044 result_set->insert (ss);
5046 else
5047 return false;
5052 return true;
5055 /* See symtab.h. */
5057 bool
5058 global_symbol_searcher::add_matching_msymbols
5059 (objfile *objfile, const std::optional<compiled_regex> &preg,
5060 std::vector<symbol_search> *results) const
5062 domain_search_flags kind = m_kind;
5064 for (minimal_symbol *msymbol : objfile->msymbols ())
5066 QUIT;
5068 if (msymbol->created_by_gdb)
5069 continue;
5071 if (is_suitable_msymbol (kind, msymbol))
5073 if (!preg.has_value ()
5074 || preg->exec (msymbol->natural_name (), 0,
5075 NULL, 0) == 0)
5077 /* For functions we can do a quick check of whether the
5078 symbol might be found via find_pc_symtab. */
5079 if ((kind & SEARCH_FUNCTION_DOMAIN) == 0
5080 || (find_pc_compunit_symtab
5081 (msymbol->value_address (objfile)) == NULL))
5083 if (lookup_symbol_in_objfile_from_linkage_name
5084 (objfile, msymbol->linkage_name (),
5085 SEARCH_VFT).symbol == NULL)
5087 /* Matching msymbol, add it to the results list. */
5088 if (results->size () < m_max_search_results)
5089 results->emplace_back (GLOBAL_BLOCK, msymbol, objfile);
5090 else
5091 return false;
5098 return true;
5101 /* See symtab.h. */
5103 std::vector<symbol_search>
5104 global_symbol_searcher::search () const
5106 std::optional<compiled_regex> preg;
5107 std::optional<compiled_regex> treg;
5109 if (m_symbol_name_regexp != NULL)
5111 const char *symbol_name_regexp = m_symbol_name_regexp;
5112 std::string symbol_name_regexp_holder;
5114 /* Make sure spacing is right for C++ operators.
5115 This is just a courtesy to make the matching less sensitive
5116 to how many spaces the user leaves between 'operator'
5117 and <TYPENAME> or <OPERATOR>. */
5118 const char *opend;
5119 const char *opname = operator_chars (symbol_name_regexp, &opend);
5121 if (*opname)
5123 int fix = -1; /* -1 means ok; otherwise number of
5124 spaces needed. */
5126 if (isalpha (*opname) || *opname == '_' || *opname == '$')
5128 /* There should 1 space between 'operator' and 'TYPENAME'. */
5129 if (opname[-1] != ' ' || opname[-2] == ' ')
5130 fix = 1;
5132 else
5134 /* There should 0 spaces between 'operator' and 'OPERATOR'. */
5135 if (opname[-1] == ' ')
5136 fix = 0;
5138 /* If wrong number of spaces, fix it. */
5139 if (fix >= 0)
5141 symbol_name_regexp_holder
5142 = string_printf ("operator%.*s%s", fix, " ", opname);
5143 symbol_name_regexp = symbol_name_regexp_holder.c_str ();
5147 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5148 ? REG_ICASE : 0);
5149 preg.emplace (symbol_name_regexp, cflags,
5150 _("Invalid regexp"));
5153 if (m_symbol_type_regexp != NULL)
5155 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5156 ? REG_ICASE : 0);
5157 treg.emplace (m_symbol_type_regexp, cflags,
5158 _("Invalid regexp"));
5161 bool found_msymbol = false;
5162 std::set<symbol_search> result_set;
5163 for (objfile *objfile : current_program_space->objfiles ())
5165 /* Expand symtabs within objfile that possibly contain matching
5166 symbols. */
5167 found_msymbol |= expand_symtabs (objfile, preg);
5169 /* Find matching symbols within OBJFILE and add them in to the
5170 RESULT_SET set. Use a set here so that we can easily detect
5171 duplicates as we go, and can therefore track how many unique
5172 matches we have found so far. */
5173 if (!add_matching_symbols (objfile, preg, treg, &result_set))
5174 break;
5177 /* Convert the result set into a sorted result list, as std::set is
5178 defined to be sorted then no explicit call to std::sort is needed. */
5179 std::vector<symbol_search> result (result_set.begin (), result_set.end ());
5181 /* If there are no debug symbols, then add matching minsyms. But if the
5182 user wants to see symbols matching a type regexp, then never give a
5183 minimal symbol, as we assume that a minimal symbol does not have a
5184 type. */
5185 if ((found_msymbol
5186 || (m_filenames.empty () && (m_kind & SEARCH_VAR_DOMAIN) != 0))
5187 && !m_exclude_minsyms
5188 && !treg.has_value ())
5190 gdb_assert ((m_kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN))
5191 != 0);
5192 for (objfile *objfile : current_program_space->objfiles ())
5193 if (!add_matching_msymbols (objfile, preg, &result))
5194 break;
5197 return result;
5200 /* See symtab.h. */
5202 std::string
5203 symbol_to_info_string (struct symbol *sym, int block)
5205 std::string str;
5207 gdb_assert (block == GLOBAL_BLOCK || block == STATIC_BLOCK);
5209 if (block == STATIC_BLOCK
5210 && (sym->domain () == VAR_DOMAIN
5211 || sym->domain () == FUNCTION_DOMAIN))
5212 str += "static ";
5214 /* Typedef that is not a C++ class. */
5215 if (sym->domain () == TYPE_DOMAIN)
5217 string_file tmp_stream;
5219 /* FIXME: For C (and C++) we end up with a difference in output here
5220 between how a typedef is printed, and non-typedefs are printed.
5221 The TYPEDEF_PRINT code places a ";" at the end in an attempt to
5222 appear C-like, while TYPE_PRINT doesn't.
5224 For the struct printing case below, things are worse, we force
5225 printing of the ";" in this function, which is going to be wrong
5226 for languages that don't require a ";" between statements. */
5227 if (sym->type ()->code () == TYPE_CODE_TYPEDEF)
5228 typedef_print (sym->type (), sym, &tmp_stream);
5229 else
5230 type_print (sym->type (), "", &tmp_stream, -1);
5231 str += tmp_stream.string ();
5233 /* variable, func, or typedef-that-is-c++-class. */
5234 else if (sym->domain () == VAR_DOMAIN || sym->domain () == STRUCT_DOMAIN
5235 || sym->domain () == FUNCTION_DOMAIN)
5237 string_file tmp_stream;
5239 type_print (sym->type (),
5240 (sym->aclass () == LOC_TYPEDEF
5241 ? "" : sym->print_name ()),
5242 &tmp_stream, 0);
5244 str += tmp_stream.string ();
5245 str += ";";
5247 /* Printing of modules is currently done here, maybe at some future
5248 point we might want a language specific method to print the module
5249 symbol so that we can customise the output more. */
5250 else if (sym->domain () == MODULE_DOMAIN)
5251 str += sym->print_name ();
5253 return str;
5256 /* Helper function for symbol info commands, for example 'info
5257 functions', 'info variables', etc. BLOCK is the type of block the
5258 symbols was found in, either GLOBAL_BLOCK or STATIC_BLOCK. SYM is
5259 the symbol we found. If LAST is not NULL, print file and line
5260 number information for the symbol as well. Skip printing the
5261 filename if it matches LAST. */
5263 static void
5264 print_symbol_info (struct symbol *sym, int block, const char *last)
5266 scoped_switch_to_sym_language_if_auto l (sym);
5267 struct symtab *s = sym->symtab ();
5269 if (last != NULL)
5271 const char *s_filename = symtab_to_filename_for_display (s);
5273 if (filename_cmp (last, s_filename) != 0)
5275 gdb_printf (_("\nFile %ps:\n"),
5276 styled_string (file_name_style.style (),
5277 s_filename));
5280 if (sym->line () != 0)
5281 gdb_printf ("%d:\t", sym->line ());
5282 else
5283 gdb_puts ("\t");
5286 std::string str = symbol_to_info_string (sym, block);
5287 gdb_printf ("%s\n", str.c_str ());
5290 /* This help function for symtab_symbol_info() prints information
5291 for non-debugging symbols to gdb_stdout. */
5293 static void
5294 print_msymbol_info (bound_minimal_symbol msymbol)
5296 struct gdbarch *gdbarch = msymbol.objfile->arch ();
5297 const char *tmp;
5299 if (gdbarch_addr_bit (gdbarch) <= 32)
5300 tmp = hex_string_custom (msymbol.value_address ()
5301 & (CORE_ADDR) 0xffffffff,
5303 else
5304 tmp = hex_string_custom (msymbol.value_address (),
5305 16);
5307 ui_file_style sym_style = (msymbol.minsym->text_p ()
5308 ? function_name_style.style ()
5309 : ui_file_style ());
5311 gdb_printf (_("%ps %ps\n"),
5312 styled_string (address_style.style (), tmp),
5313 styled_string (sym_style, msymbol.minsym->print_name ()));
5316 /* This is the guts of the commands "info functions", "info types", and
5317 "info variables". It calls search_symbols to find all matches and then
5318 print_[m]symbol_info to print out some useful information about the
5319 matches. */
5321 static void
5322 symtab_symbol_info (bool quiet, bool exclude_minsyms,
5323 const char *regexp, domain_enum kind,
5324 const char *t_regexp, int from_tty)
5326 const char *last_filename = "";
5327 int first = 1;
5329 if (regexp != nullptr && *regexp == '\0')
5330 regexp = nullptr;
5332 domain_search_flags flags = to_search_flags (kind);
5333 if (kind == TYPE_DOMAIN)
5334 flags |= SEARCH_STRUCT_DOMAIN;
5336 global_symbol_searcher spec (flags, regexp);
5337 spec.set_symbol_type_regexp (t_regexp);
5338 spec.set_exclude_minsyms (exclude_minsyms);
5339 std::vector<symbol_search> symbols = spec.search ();
5341 if (!quiet)
5343 const char *classname;
5344 switch (kind)
5346 case VAR_DOMAIN:
5347 classname = "variable";
5348 break;
5349 case FUNCTION_DOMAIN:
5350 classname = "function";
5351 break;
5352 case TYPE_DOMAIN:
5353 classname = "type";
5354 break;
5355 case MODULE_DOMAIN:
5356 classname = "module";
5357 break;
5358 default:
5359 gdb_assert_not_reached ("invalid domain enum");
5362 if (regexp != NULL)
5364 if (t_regexp != NULL)
5365 gdb_printf
5366 (_("All %ss matching regular expression \"%s\""
5367 " with type matching regular expression \"%s\":\n"),
5368 classname, regexp, t_regexp);
5369 else
5370 gdb_printf (_("All %ss matching regular expression \"%s\":\n"),
5371 classname, regexp);
5373 else
5375 if (t_regexp != NULL)
5376 gdb_printf
5377 (_("All defined %ss"
5378 " with type matching regular expression \"%s\" :\n"),
5379 classname, t_regexp);
5380 else
5381 gdb_printf (_("All defined %ss:\n"), classname);
5385 for (const symbol_search &p : symbols)
5387 QUIT;
5389 if (p.msymbol.minsym != NULL)
5391 if (first)
5393 if (!quiet)
5394 gdb_printf (_("\nNon-debugging symbols:\n"));
5395 first = 0;
5397 print_msymbol_info (p.msymbol);
5399 else
5401 print_symbol_info (p.symbol, p.block, last_filename);
5402 last_filename
5403 = symtab_to_filename_for_display (p.symbol->symtab ());
5408 /* Structure to hold the values of the options used by the 'info variables'
5409 and 'info functions' commands. These correspond to the -q, -t, and -n
5410 options. */
5412 struct info_vars_funcs_options
5414 bool quiet = false;
5415 bool exclude_minsyms = false;
5416 std::string type_regexp;
5419 /* The options used by the 'info variables' and 'info functions'
5420 commands. */
5422 static const gdb::option::option_def info_vars_funcs_options_defs[] = {
5423 gdb::option::boolean_option_def<info_vars_funcs_options> {
5424 "q",
5425 [] (info_vars_funcs_options *opt) { return &opt->quiet; },
5426 nullptr, /* show_cmd_cb */
5427 nullptr /* set_doc */
5430 gdb::option::boolean_option_def<info_vars_funcs_options> {
5431 "n",
5432 [] (info_vars_funcs_options *opt) { return &opt->exclude_minsyms; },
5433 nullptr, /* show_cmd_cb */
5434 nullptr /* set_doc */
5437 gdb::option::string_option_def<info_vars_funcs_options> {
5438 "t",
5439 [] (info_vars_funcs_options *opt) { return &opt->type_regexp; },
5440 nullptr, /* show_cmd_cb */
5441 nullptr /* set_doc */
5445 /* Returns the option group used by 'info variables' and 'info
5446 functions'. */
5448 static gdb::option::option_def_group
5449 make_info_vars_funcs_options_def_group (info_vars_funcs_options *opts)
5451 return {{info_vars_funcs_options_defs}, opts};
5454 /* Command completer for 'info variables' and 'info functions'. */
5456 static void
5457 info_vars_funcs_command_completer (struct cmd_list_element *ignore,
5458 completion_tracker &tracker,
5459 const char *text, const char * /* word */)
5461 const auto group
5462 = make_info_vars_funcs_options_def_group (nullptr);
5463 if (gdb::option::complete_options
5464 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5465 return;
5467 const char *word = advance_to_expression_complete_word_point (tracker, text);
5468 symbol_completer (ignore, tracker, text, word);
5471 /* Implement the 'info variables' command. */
5473 static void
5474 info_variables_command (const char *args, int from_tty)
5476 info_vars_funcs_options opts;
5477 auto grp = make_info_vars_funcs_options_def_group (&opts);
5478 gdb::option::process_options
5479 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5480 if (args != nullptr && *args == '\0')
5481 args = nullptr;
5483 symtab_symbol_info
5484 (opts.quiet, opts.exclude_minsyms, args, VAR_DOMAIN,
5485 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5486 from_tty);
5489 /* Implement the 'info functions' command. */
5491 static void
5492 info_functions_command (const char *args, int from_tty)
5494 info_vars_funcs_options opts;
5496 auto grp = make_info_vars_funcs_options_def_group (&opts);
5497 gdb::option::process_options
5498 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5499 if (args != nullptr && *args == '\0')
5500 args = nullptr;
5502 symtab_symbol_info
5503 (opts.quiet, opts.exclude_minsyms, args, FUNCTION_DOMAIN,
5504 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5505 from_tty);
5508 /* Holds the -q option for the 'info types' command. */
5510 struct info_types_options
5512 bool quiet = false;
5515 /* The options used by the 'info types' command. */
5517 static const gdb::option::option_def info_types_options_defs[] = {
5518 gdb::option::boolean_option_def<info_types_options> {
5519 "q",
5520 [] (info_types_options *opt) { return &opt->quiet; },
5521 nullptr, /* show_cmd_cb */
5522 nullptr /* set_doc */
5526 /* Returns the option group used by 'info types'. */
5528 static gdb::option::option_def_group
5529 make_info_types_options_def_group (info_types_options *opts)
5531 return {{info_types_options_defs}, opts};
5534 /* Implement the 'info types' command. */
5536 static void
5537 info_types_command (const char *args, int from_tty)
5539 info_types_options opts;
5541 auto grp = make_info_types_options_def_group (&opts);
5542 gdb::option::process_options
5543 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5544 if (args != nullptr && *args == '\0')
5545 args = nullptr;
5546 symtab_symbol_info (opts.quiet, false, args, TYPE_DOMAIN, nullptr,
5547 from_tty);
5550 /* Command completer for 'info types' command. */
5552 static void
5553 info_types_command_completer (struct cmd_list_element *ignore,
5554 completion_tracker &tracker,
5555 const char *text, const char * /* word */)
5557 const auto group
5558 = make_info_types_options_def_group (nullptr);
5559 if (gdb::option::complete_options
5560 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5561 return;
5563 const char *word = advance_to_expression_complete_word_point (tracker, text);
5564 symbol_completer (ignore, tracker, text, word);
5567 /* Implement the 'info modules' command. */
5569 static void
5570 info_modules_command (const char *args, int from_tty)
5572 info_types_options opts;
5574 auto grp = make_info_types_options_def_group (&opts);
5575 gdb::option::process_options
5576 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5577 if (args != nullptr && *args == '\0')
5578 args = nullptr;
5579 symtab_symbol_info (opts.quiet, true, args, MODULE_DOMAIN, nullptr,
5580 from_tty);
5583 /* Implement the 'info main' command. */
5585 static void
5586 info_main_command (const char *args, int from_tty)
5588 gdb_printf ("%s\n", main_name ());
5591 static void
5592 rbreak_command (const char *regexp, int from_tty)
5594 std::string string;
5595 gdb::unique_xmalloc_ptr<char> file_name;
5597 if (regexp != nullptr)
5599 const char *colon = strchr (regexp, ':');
5601 /* Ignore the colon if it is part of a Windows drive. */
5602 if (HAS_DRIVE_SPEC (regexp)
5603 && (regexp[2] == '/' || regexp[2] == '\\'))
5604 colon = strchr (STRIP_DRIVE_SPEC (regexp), ':');
5606 if (colon && *(colon + 1) != ':')
5608 int colon_index = colon - regexp;
5609 while (colon_index > 0 && isspace (regexp[colon_index - 1]))
5610 --colon_index;
5612 file_name = make_unique_xstrndup (regexp, colon_index);
5613 regexp = skip_spaces (colon + 1);
5617 global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regexp);
5618 if (file_name != nullptr)
5619 spec.add_filename (std::move (file_name));
5620 std::vector<symbol_search> symbols = spec.search ();
5622 scoped_rbreak_breakpoints finalize;
5623 for (const symbol_search &p : symbols)
5625 if (p.msymbol.minsym == NULL)
5627 struct symtab *symtab = p.symbol->symtab ();
5628 const char *fullname = symtab_to_fullname (symtab);
5630 string = string_printf ("%s:'%s'", fullname,
5631 p.symbol->linkage_name ());
5632 break_command (&string[0], from_tty);
5633 print_symbol_info (p.symbol, p.block, nullptr);
5635 else
5637 string = string_printf ("'%s'",
5638 p.msymbol.minsym->linkage_name ());
5640 break_command (&string[0], from_tty);
5641 gdb_printf ("<function, no debug info> %s;\n",
5642 p.msymbol.minsym->print_name ());
5648 /* Evaluate if SYMNAME matches LOOKUP_NAME. */
5650 static int
5651 compare_symbol_name (const char *symbol_name, language symbol_language,
5652 const lookup_name_info &lookup_name,
5653 completion_match_result &match_res)
5655 const language_defn *lang = language_def (symbol_language);
5657 symbol_name_matcher_ftype *name_match
5658 = lang->get_symbol_name_matcher (lookup_name);
5660 return name_match (symbol_name, lookup_name, &match_res);
5663 /* See symtab.h. */
5665 bool
5666 completion_list_add_name (completion_tracker &tracker,
5667 language symbol_language,
5668 const char *symname,
5669 const lookup_name_info &lookup_name,
5670 const char *text, const char *word)
5672 completion_match_result &match_res
5673 = tracker.reset_completion_match_result ();
5675 /* Clip symbols that cannot match. */
5676 if (!compare_symbol_name (symname, symbol_language, lookup_name, match_res))
5677 return false;
5679 /* Refresh SYMNAME from the match string. It's potentially
5680 different depending on language. (E.g., on Ada, the match may be
5681 the encoded symbol name wrapped in "<>"). */
5682 symname = match_res.match.match ();
5683 gdb_assert (symname != NULL);
5685 /* We have a match for a completion, so add SYMNAME to the current list
5686 of matches. Note that the name is moved to freshly malloc'd space. */
5689 gdb::unique_xmalloc_ptr<char> completion
5690 = make_completion_match_str (symname, text, word);
5692 /* Here we pass the match-for-lcd object to add_completion. Some
5693 languages match the user text against substrings of symbol
5694 names in some cases. E.g., in C++, "b push_ba" completes to
5695 "std::vector::push_back", "std::string::push_back", etc., and
5696 in this case we want the completion lowest common denominator
5697 to be "push_back" instead of "std::". */
5698 tracker.add_completion (std::move (completion),
5699 &match_res.match_for_lcd, text, word);
5702 return true;
5705 /* completion_list_add_name wrapper for struct symbol. */
5707 static void
5708 completion_list_add_symbol (completion_tracker &tracker,
5709 symbol *sym,
5710 const lookup_name_info &lookup_name,
5711 const char *text, const char *word)
5713 if (!completion_list_add_name (tracker, sym->language (),
5714 sym->natural_name (),
5715 lookup_name, text, word))
5716 return;
5718 /* C++ function symbols include the parameters within both the msymbol
5719 name and the symbol name. The problem is that the msymbol name will
5720 describe the parameters in the most basic way, with typedefs stripped
5721 out, while the symbol name will represent the types as they appear in
5722 the program. This means we will see duplicate entries in the
5723 completion tracker. The following converts the symbol name back to
5724 the msymbol name and removes the msymbol name from the completion
5725 tracker. */
5726 if (sym->language () == language_cplus
5727 && sym->aclass () == LOC_BLOCK)
5729 /* The call to canonicalize returns the empty string if the input
5730 string is already in canonical form, thanks to this we don't
5731 remove the symbol we just added above. */
5732 gdb::unique_xmalloc_ptr<char> str
5733 = cp_canonicalize_string_no_typedefs (sym->natural_name ());
5734 if (str != nullptr)
5735 tracker.remove_completion (str.get ());
5739 /* completion_list_add_name wrapper for struct minimal_symbol. */
5741 static void
5742 completion_list_add_msymbol (completion_tracker &tracker,
5743 minimal_symbol *sym,
5744 const lookup_name_info &lookup_name,
5745 const char *text, const char *word)
5747 completion_list_add_name (tracker, sym->language (),
5748 sym->natural_name (),
5749 lookup_name, text, word);
5753 /* ObjC: In case we are completing on a selector, look as the msymbol
5754 again and feed all the selectors into the mill. */
5756 static void
5757 completion_list_objc_symbol (completion_tracker &tracker,
5758 struct minimal_symbol *msymbol,
5759 const lookup_name_info &lookup_name,
5760 const char *text, const char *word)
5762 static char *tmp = NULL;
5763 static unsigned int tmplen = 0;
5765 const char *method, *category, *selector;
5766 char *tmp2 = NULL;
5768 method = msymbol->natural_name ();
5770 /* Is it a method? */
5771 if ((method[0] != '-') && (method[0] != '+'))
5772 return;
5774 if (text[0] == '[')
5775 /* Complete on shortened method method. */
5776 completion_list_add_name (tracker, language_objc,
5777 method + 1,
5778 lookup_name,
5779 text, word);
5781 while ((strlen (method) + 1) >= tmplen)
5783 if (tmplen == 0)
5784 tmplen = 1024;
5785 else
5786 tmplen *= 2;
5787 tmp = (char *) xrealloc (tmp, tmplen);
5789 selector = strchr (method, ' ');
5790 if (selector != NULL)
5791 selector++;
5793 category = strchr (method, '(');
5795 if ((category != NULL) && (selector != NULL))
5797 memcpy (tmp, method, (category - method));
5798 tmp[category - method] = ' ';
5799 memcpy (tmp + (category - method) + 1, selector, strlen (selector) + 1);
5800 completion_list_add_name (tracker, language_objc, tmp,
5801 lookup_name, text, word);
5802 if (text[0] == '[')
5803 completion_list_add_name (tracker, language_objc, tmp + 1,
5804 lookup_name, text, word);
5807 if (selector != NULL)
5809 /* Complete on selector only. */
5810 strcpy (tmp, selector);
5811 tmp2 = strchr (tmp, ']');
5812 if (tmp2 != NULL)
5813 *tmp2 = '\0';
5815 completion_list_add_name (tracker, language_objc, tmp,
5816 lookup_name, text, word);
5820 /* Break the non-quoted text based on the characters which are in
5821 symbols. FIXME: This should probably be language-specific. */
5823 static const char *
5824 language_search_unquoted_string (const char *text, const char *p)
5826 for (; p > text; --p)
5828 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
5829 continue;
5830 else
5832 if ((current_language->la_language == language_objc))
5834 if (p[-1] == ':') /* Might be part of a method name. */
5835 continue;
5836 else if (p[-1] == '[' && (p[-2] == '-' || p[-2] == '+'))
5837 p -= 2; /* Beginning of a method name. */
5838 else if (p[-1] == ' ' || p[-1] == '(' || p[-1] == ')')
5839 { /* Might be part of a method name. */
5840 const char *t = p;
5842 /* Seeing a ' ' or a '(' is not conclusive evidence
5843 that we are in the middle of a method name. However,
5844 finding "-[" or "+[" should be pretty un-ambiguous.
5845 Unfortunately we have to find it now to decide. */
5847 while (t > text)
5848 if (isalnum (t[-1]) || t[-1] == '_' ||
5849 t[-1] == ' ' || t[-1] == ':' ||
5850 t[-1] == '(' || t[-1] == ')')
5851 --t;
5852 else
5853 break;
5855 if (t[-1] == '[' && (t[-2] == '-' || t[-2] == '+'))
5856 p = t - 2; /* Method name detected. */
5857 /* Else we leave with p unchanged. */
5860 break;
5863 return p;
5866 static void
5867 completion_list_add_fields (completion_tracker &tracker,
5868 struct symbol *sym,
5869 const lookup_name_info &lookup_name,
5870 const char *text, const char *word)
5872 if (sym->aclass () == LOC_TYPEDEF)
5874 struct type *t = sym->type ();
5875 enum type_code c = t->code ();
5876 int j;
5878 if (c == TYPE_CODE_UNION || c == TYPE_CODE_STRUCT)
5879 for (j = TYPE_N_BASECLASSES (t); j < t->num_fields (); j++)
5880 if (t->field (j).name ())
5881 completion_list_add_name (tracker, sym->language (),
5882 t->field (j).name (),
5883 lookup_name, text, word);
5887 /* See symtab.h. */
5889 bool
5890 symbol_is_function_or_method (symbol *sym)
5892 switch (sym->type ()->code ())
5894 case TYPE_CODE_FUNC:
5895 case TYPE_CODE_METHOD:
5896 return true;
5897 default:
5898 return false;
5902 /* See symtab.h. */
5904 bool
5905 symbol_is_function_or_method (minimal_symbol *msymbol)
5907 switch (msymbol->type ())
5909 case mst_text:
5910 case mst_text_gnu_ifunc:
5911 case mst_solib_trampoline:
5912 case mst_file_text:
5913 return true;
5914 default:
5915 return false;
5919 /* See symtab.h. */
5921 bound_minimal_symbol
5922 find_gnu_ifunc (const symbol *sym)
5924 if (sym->aclass () != LOC_BLOCK)
5925 return {};
5927 lookup_name_info lookup_name (sym->search_name (),
5928 symbol_name_match_type::SEARCH_NAME);
5929 struct objfile *objfile = sym->objfile ();
5931 CORE_ADDR address = sym->value_block ()->entry_pc ();
5932 minimal_symbol *ifunc = NULL;
5934 iterate_over_minimal_symbols (objfile, lookup_name,
5935 [&] (minimal_symbol *minsym)
5937 if (minsym->type () == mst_text_gnu_ifunc
5938 || minsym->type () == mst_data_gnu_ifunc)
5940 CORE_ADDR msym_addr = minsym->value_address (objfile);
5941 if (minsym->type () == mst_data_gnu_ifunc)
5943 struct gdbarch *gdbarch = objfile->arch ();
5944 msym_addr = gdbarch_convert_from_func_ptr_addr
5945 (gdbarch, msym_addr, current_inferior ()->top_target ());
5947 if (msym_addr == address)
5949 ifunc = minsym;
5950 return true;
5953 return false;
5956 if (ifunc != NULL)
5957 return {ifunc, objfile};
5958 return {};
5961 /* Add matching symbols from SYMTAB to the current completion list. */
5963 static void
5964 add_symtab_completions (struct compunit_symtab *cust,
5965 completion_tracker &tracker,
5966 complete_symbol_mode mode,
5967 const lookup_name_info &lookup_name,
5968 const char *text, const char *word,
5969 enum type_code code)
5971 int i;
5973 if (cust == NULL)
5974 return;
5976 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
5978 QUIT;
5980 const struct block *b = cust->blockvector ()->block (i);
5981 for (struct symbol *sym : block_iterator_range (b))
5983 if (completion_skip_symbol (mode, sym))
5984 continue;
5986 if (code == TYPE_CODE_UNDEF
5987 || (sym->domain () == STRUCT_DOMAIN
5988 && sym->type ()->code () == code))
5989 completion_list_add_symbol (tracker, sym,
5990 lookup_name,
5991 text, word);
5996 void
5997 default_collect_symbol_completion_matches_break_on
5998 (completion_tracker &tracker, complete_symbol_mode mode,
5999 symbol_name_match_type name_match_type,
6000 const char *text, const char *word,
6001 const char *break_on, enum type_code code)
6003 /* Problem: All of the symbols have to be copied because readline
6004 frees them. I'm not going to worry about this; hopefully there
6005 won't be that many. */
6007 const struct block *b;
6008 const struct block *surrounding_static_block, *surrounding_global_block;
6009 /* The symbol we are completing on. Points in same buffer as text. */
6010 const char *sym_text;
6012 /* Now look for the symbol we are supposed to complete on. */
6013 if (mode == complete_symbol_mode::LINESPEC)
6014 sym_text = text;
6015 else
6017 const char *p;
6018 char quote_found;
6019 const char *quote_pos = NULL;
6021 /* First see if this is a quoted string. */
6022 quote_found = '\0';
6023 for (p = text; *p != '\0'; ++p)
6025 if (quote_found != '\0')
6027 if (*p == quote_found)
6028 /* Found close quote. */
6029 quote_found = '\0';
6030 else if (*p == '\\' && p[1] == quote_found)
6031 /* A backslash followed by the quote character
6032 doesn't end the string. */
6033 ++p;
6035 else if (*p == '\'' || *p == '"')
6037 quote_found = *p;
6038 quote_pos = p;
6041 if (quote_found == '\'')
6042 /* A string within single quotes can be a symbol, so complete on it. */
6043 sym_text = quote_pos + 1;
6044 else if (quote_found == '"')
6045 /* A double-quoted string is never a symbol, nor does it make sense
6046 to complete it any other way. */
6048 return;
6050 else
6052 /* It is not a quoted string. Break it based on the characters
6053 which are in symbols. */
6054 while (p > text)
6056 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0'
6057 || p[-1] == ':' || strchr (break_on, p[-1]) != NULL)
6058 --p;
6059 else
6060 break;
6062 sym_text = p;
6066 lookup_name_info lookup_name (sym_text, name_match_type, true);
6068 /* At this point scan through the misc symbol vectors and add each
6069 symbol you find to the list. Eventually we want to ignore
6070 anything that isn't a text symbol (everything else will be
6071 handled by the psymtab code below). */
6073 if (code == TYPE_CODE_UNDEF)
6075 for (objfile *objfile : current_program_space->objfiles ())
6077 for (minimal_symbol *msymbol : objfile->msymbols ())
6079 QUIT;
6081 if (completion_skip_symbol (mode, msymbol))
6082 continue;
6084 completion_list_add_msymbol (tracker, msymbol, lookup_name,
6085 sym_text, word);
6087 completion_list_objc_symbol (tracker, msymbol, lookup_name,
6088 sym_text, word);
6093 /* Add completions for all currently loaded symbol tables. */
6094 for (objfile *objfile : current_program_space->objfiles ())
6096 for (compunit_symtab *cust : objfile->compunits ())
6097 add_symtab_completions (cust, tracker, mode, lookup_name,
6098 sym_text, word, code);
6101 /* Look through the partial symtabs for all symbols which begin by
6102 matching SYM_TEXT. Expand all CUs that you find to the list. */
6103 expand_symtabs_matching (NULL,
6104 lookup_name,
6105 NULL,
6106 [&] (compunit_symtab *symtab) /* expansion notify */
6108 add_symtab_completions (symtab,
6109 tracker, mode, lookup_name,
6110 sym_text, word, code);
6111 return true;
6113 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
6114 SEARCH_ALL_DOMAINS);
6116 /* Search upwards from currently selected frame (so that we can
6117 complete on local vars). Also catch fields of types defined in
6118 this places which match our text string. Only complete on types
6119 visible from current context. */
6121 b = get_selected_block (0);
6122 surrounding_static_block = b == nullptr ? nullptr : b->static_block ();
6123 surrounding_global_block = b == nullptr ? nullptr : b->global_block ();
6124 if (surrounding_static_block != NULL)
6125 while (b != surrounding_static_block)
6127 QUIT;
6129 for (struct symbol *sym : block_iterator_range (b))
6131 if (code == TYPE_CODE_UNDEF)
6133 completion_list_add_symbol (tracker, sym, lookup_name,
6134 sym_text, word);
6135 completion_list_add_fields (tracker, sym, lookup_name,
6136 sym_text, word);
6138 else if (sym->domain () == STRUCT_DOMAIN
6139 && sym->type ()->code () == code)
6140 completion_list_add_symbol (tracker, sym, lookup_name,
6141 sym_text, word);
6144 /* Stop when we encounter an enclosing function. Do not stop for
6145 non-inlined functions - the locals of the enclosing function
6146 are in scope for a nested function. */
6147 if (b->function () != NULL && b->inlined_p ())
6148 break;
6149 b = b->superblock ();
6152 /* Add fields from the file's types; symbols will be added below. */
6154 if (code == TYPE_CODE_UNDEF)
6156 if (surrounding_static_block != NULL)
6157 for (struct symbol *sym : block_iterator_range (surrounding_static_block))
6158 completion_list_add_fields (tracker, sym, lookup_name,
6159 sym_text, word);
6161 if (surrounding_global_block != NULL)
6162 for (struct symbol *sym : block_iterator_range (surrounding_global_block))
6163 completion_list_add_fields (tracker, sym, lookup_name,
6164 sym_text, word);
6167 /* Skip macros if we are completing a struct tag -- arguable but
6168 usually what is expected. */
6169 if (current_language->macro_expansion () == macro_expansion_c
6170 && code == TYPE_CODE_UNDEF)
6172 gdb::unique_xmalloc_ptr<struct macro_scope> scope;
6174 /* This adds a macro's name to the current completion list. */
6175 auto add_macro_name = [&] (const char *macro_name,
6176 const macro_definition *,
6177 macro_source_file *,
6178 int)
6180 completion_list_add_name (tracker, language_c, macro_name,
6181 lookup_name, sym_text, word);
6184 /* Add any macros visible in the default scope. Note that this
6185 may yield the occasional wrong result, because an expression
6186 might be evaluated in a scope other than the default. For
6187 example, if the user types "break file:line if <TAB>", the
6188 resulting expression will be evaluated at "file:line" -- but
6189 at there does not seem to be a way to detect this at
6190 completion time. */
6191 scope = default_macro_scope ();
6192 if (scope)
6193 macro_for_each_in_scope (scope->file, scope->line,
6194 add_macro_name);
6196 /* User-defined macros are always visible. */
6197 macro_for_each (macro_user_macros, add_macro_name);
6201 /* Collect all symbols (regardless of class) which begin by matching
6202 TEXT. */
6204 void
6205 collect_symbol_completion_matches (completion_tracker &tracker,
6206 complete_symbol_mode mode,
6207 symbol_name_match_type name_match_type,
6208 const char *text, const char *word)
6210 current_language->collect_symbol_completion_matches (tracker, mode,
6211 name_match_type,
6212 text, word,
6213 TYPE_CODE_UNDEF);
6216 /* Like collect_symbol_completion_matches, but only collect
6217 STRUCT_DOMAIN symbols whose type code is CODE. */
6219 void
6220 collect_symbol_completion_matches_type (completion_tracker &tracker,
6221 const char *text, const char *word,
6222 enum type_code code)
6224 complete_symbol_mode mode = complete_symbol_mode::EXPRESSION;
6225 symbol_name_match_type name_match_type = symbol_name_match_type::EXPRESSION;
6227 gdb_assert (code == TYPE_CODE_UNION
6228 || code == TYPE_CODE_STRUCT
6229 || code == TYPE_CODE_ENUM);
6230 current_language->collect_symbol_completion_matches (tracker, mode,
6231 name_match_type,
6232 text, word, code);
6235 /* Like collect_symbol_completion_matches, but collects a list of
6236 symbols defined in all source files named SRCFILE. */
6238 void
6239 collect_file_symbol_completion_matches (completion_tracker &tracker,
6240 complete_symbol_mode mode,
6241 symbol_name_match_type name_match_type,
6242 const char *text, const char *word,
6243 const char *srcfile)
6245 /* The symbol we are completing on. Points in same buffer as text. */
6246 const char *sym_text;
6248 /* Now look for the symbol we are supposed to complete on.
6249 FIXME: This should be language-specific. */
6250 if (mode == complete_symbol_mode::LINESPEC)
6251 sym_text = text;
6252 else
6254 const char *p;
6255 char quote_found;
6256 const char *quote_pos = NULL;
6258 /* First see if this is a quoted string. */
6259 quote_found = '\0';
6260 for (p = text; *p != '\0'; ++p)
6262 if (quote_found != '\0')
6264 if (*p == quote_found)
6265 /* Found close quote. */
6266 quote_found = '\0';
6267 else if (*p == '\\' && p[1] == quote_found)
6268 /* A backslash followed by the quote character
6269 doesn't end the string. */
6270 ++p;
6272 else if (*p == '\'' || *p == '"')
6274 quote_found = *p;
6275 quote_pos = p;
6278 if (quote_found == '\'')
6279 /* A string within single quotes can be a symbol, so complete on it. */
6280 sym_text = quote_pos + 1;
6281 else if (quote_found == '"')
6282 /* A double-quoted string is never a symbol, nor does it make sense
6283 to complete it any other way. */
6285 return;
6287 else
6289 /* Not a quoted string. */
6290 sym_text = language_search_unquoted_string (text, p);
6294 lookup_name_info lookup_name (sym_text, name_match_type, true);
6296 /* Go through symtabs for SRCFILE and check the externs and statics
6297 for symbols which match. */
6298 iterate_over_symtabs (current_program_space, srcfile, [&] (symtab *s)
6300 add_symtab_completions (s->compunit (),
6301 tracker, mode, lookup_name,
6302 sym_text, word, TYPE_CODE_UNDEF);
6303 return false;
6307 /* A helper function for make_source_files_completion_list. It adds
6308 another file name to a list of possible completions, growing the
6309 list as necessary. */
6311 static void
6312 add_filename_to_list (const char *fname, const char *text, const char *word,
6313 completion_list *list)
6315 list->emplace_back (make_completion_match_str (fname, text, word));
6318 static int
6319 not_interesting_fname (const char *fname)
6321 static const char *illegal_aliens[] = {
6322 "_globals_", /* inserted by coff_symtab_read */
6323 NULL
6325 int i;
6327 for (i = 0; illegal_aliens[i]; i++)
6329 if (filename_cmp (fname, illegal_aliens[i]) == 0)
6330 return 1;
6332 return 0;
6335 /* An object of this type is passed as the callback argument to
6336 map_partial_symbol_filenames. */
6337 struct add_partial_filename_data
6339 struct filename_seen_cache *filename_seen_cache;
6340 const char *text;
6341 const char *word;
6342 int text_len;
6343 completion_list *list;
6345 void operator() (const char *filename, const char *fullname);
6348 /* A callback for map_partial_symbol_filenames. */
6350 void
6351 add_partial_filename_data::operator() (const char *filename,
6352 const char *fullname)
6354 if (not_interesting_fname (filename))
6355 return;
6356 if (!filename_seen_cache->seen (filename)
6357 && filename_ncmp (filename, text, text_len) == 0)
6359 /* This file matches for a completion; add it to the
6360 current list of matches. */
6361 add_filename_to_list (filename, text, word, list);
6363 else
6365 const char *base_name = lbasename (filename);
6367 if (base_name != filename
6368 && !filename_seen_cache->seen (base_name)
6369 && filename_ncmp (base_name, text, text_len) == 0)
6370 add_filename_to_list (base_name, text, word, list);
6374 /* Return a list of all source files whose names begin with matching
6375 TEXT. The file names are looked up in the symbol tables of this
6376 program. */
6378 completion_list
6379 make_source_files_completion_list (const char *text, const char *word)
6381 size_t text_len = strlen (text);
6382 completion_list list;
6383 const char *base_name;
6384 struct add_partial_filename_data datum;
6386 if (!have_full_symbols (current_program_space)
6387 && !have_partial_symbols (current_program_space))
6388 return list;
6390 filename_seen_cache filenames_seen;
6392 for (objfile *objfile : current_program_space->objfiles ())
6394 for (compunit_symtab *cu : objfile->compunits ())
6396 for (symtab *s : cu->filetabs ())
6398 if (not_interesting_fname (s->filename))
6399 continue;
6400 if (!filenames_seen.seen (s->filename)
6401 && filename_ncmp (s->filename, text, text_len) == 0)
6403 /* This file matches for a completion; add it to the current
6404 list of matches. */
6405 add_filename_to_list (s->filename, text, word, &list);
6407 else
6409 /* NOTE: We allow the user to type a base name when the
6410 debug info records leading directories, but not the other
6411 way around. This is what subroutines of breakpoint
6412 command do when they parse file names. */
6413 base_name = lbasename (s->filename);
6414 if (base_name != s->filename
6415 && !filenames_seen.seen (base_name)
6416 && filename_ncmp (base_name, text, text_len) == 0)
6417 add_filename_to_list (base_name, text, word, &list);
6423 datum.filename_seen_cache = &filenames_seen;
6424 datum.text = text;
6425 datum.word = word;
6426 datum.text_len = text_len;
6427 datum.list = &list;
6428 map_symbol_filenames (datum, false /*need_fullname*/);
6430 return list;
6433 /* Track MAIN */
6435 /* Return the "main_info" object for the current program space. If
6436 the object has not yet been created, create it and fill in some
6437 default values. */
6439 static main_info *
6440 get_main_info (program_space *pspace)
6442 main_info *info = main_progspace_key.get (pspace);
6444 if (info == NULL)
6446 /* It may seem strange to store the main name in the progspace
6447 and also in whatever objfile happens to see a main name in
6448 its debug info. The reason for this is mainly historical:
6449 gdb returned "main" as the name even if no function named
6450 "main" was defined the program; and this approach lets us
6451 keep compatibility. */
6452 info = main_progspace_key.emplace (pspace);
6455 return info;
6458 static void
6459 set_main_name (program_space *pspace, const char *name, enum language lang)
6461 main_info *info = get_main_info (pspace);
6463 if (!info->name_of_main.empty ())
6465 info->name_of_main.clear ();
6466 info->language_of_main = language_unknown;
6468 if (name != NULL)
6470 info->name_of_main = name;
6471 info->language_of_main = lang;
6475 /* Deduce the name of the main procedure, and set NAME_OF_MAIN
6476 accordingly. */
6478 static void
6479 find_main_name (void)
6481 const char *new_main_name;
6482 program_space *pspace = current_program_space;
6484 /* First check the objfiles to see whether a debuginfo reader has
6485 picked up the appropriate main name. Historically the main name
6486 was found in a more or less random way; this approach instead
6487 relies on the order of objfile creation -- which still isn't
6488 guaranteed to get the correct answer, but is just probably more
6489 accurate. */
6490 for (objfile *objfile : current_program_space->objfiles ())
6492 objfile->compute_main_name ();
6494 if (objfile->per_bfd->name_of_main != NULL)
6496 set_main_name (pspace,
6497 objfile->per_bfd->name_of_main,
6498 objfile->per_bfd->language_of_main);
6499 return;
6503 /* Try to see if the main procedure is in Ada. */
6504 /* FIXME: brobecker/2005-03-07: Another way of doing this would
6505 be to add a new method in the language vector, and call this
6506 method for each language until one of them returns a non-empty
6507 name. This would allow us to remove this hard-coded call to
6508 an Ada function. It is not clear that this is a better approach
6509 at this point, because all methods need to be written in a way
6510 such that false positives never be returned. For instance, it is
6511 important that a method does not return a wrong name for the main
6512 procedure if the main procedure is actually written in a different
6513 language. It is easy to guaranty this with Ada, since we use a
6514 special symbol generated only when the main in Ada to find the name
6515 of the main procedure. It is difficult however to see how this can
6516 be guarantied for languages such as C, for instance. This suggests
6517 that order of call for these methods becomes important, which means
6518 a more complicated approach. */
6519 new_main_name = ada_main_name ();
6520 if (new_main_name != NULL)
6522 set_main_name (pspace, new_main_name, language_ada);
6523 return;
6526 new_main_name = d_main_name ();
6527 if (new_main_name != NULL)
6529 set_main_name (pspace, new_main_name, language_d);
6530 return;
6533 new_main_name = go_main_name ();
6534 if (new_main_name != NULL)
6536 set_main_name (pspace, new_main_name, language_go);
6537 return;
6540 new_main_name = pascal_main_name ();
6541 if (new_main_name != NULL)
6543 set_main_name (pspace, new_main_name, language_pascal);
6544 return;
6547 /* The languages above didn't identify the name of the main procedure.
6548 Fallback to "main". */
6550 /* Try to find language for main in psymtabs. */
6551 bool symbol_found_p = false;
6552 gdbarch_iterate_over_objfiles_in_search_order
6553 (current_inferior ()->arch (),
6554 [&symbol_found_p, pspace] (objfile *obj)
6556 language lang
6557 = obj->lookup_global_symbol_language ("main",
6558 SEARCH_FUNCTION_DOMAIN,
6559 &symbol_found_p);
6560 if (symbol_found_p)
6562 set_main_name (pspace, "main", lang);
6563 return 1;
6566 return 0;
6567 }, nullptr);
6569 if (symbol_found_p)
6570 return;
6572 set_main_name (pspace, "main", language_unknown);
6575 /* See symtab.h. */
6577 const char *
6578 main_name ()
6580 main_info *info = get_main_info (current_program_space);
6582 if (info->name_of_main.empty ())
6583 find_main_name ();
6585 return info->name_of_main.c_str ();
6588 /* Return the language of the main function. If it is not known,
6589 return language_unknown. */
6591 enum language
6592 main_language (void)
6594 main_info *info = get_main_info (current_program_space);
6596 if (info->name_of_main.empty ())
6597 find_main_name ();
6599 return info->language_of_main;
6602 /* Return 1 if the supplied producer string matches the ARM RealView
6603 compiler (armcc). */
6605 bool
6606 producer_is_realview (const char *producer)
6608 static const char *const arm_idents[] = {
6609 "ARM C Compiler, ADS",
6610 "Thumb C Compiler, ADS",
6611 "ARM C++ Compiler, ADS",
6612 "Thumb C++ Compiler, ADS",
6613 "ARM/Thumb C/C++ Compiler, RVCT",
6614 "ARM C/C++ Compiler, RVCT"
6617 if (producer == NULL)
6618 return false;
6620 for (const char *ident : arm_idents)
6621 if (startswith (producer, ident))
6622 return true;
6624 return false;
6629 /* The next index to hand out in response to a registration request. */
6631 static int next_aclass_value = LOC_FINAL_VALUE;
6633 /* The maximum number of "aclass" registrations we support. This is
6634 constant for convenience. */
6635 #define MAX_SYMBOL_IMPLS (LOC_FINAL_VALUE + 11)
6637 /* The objects representing the various "aclass" values. The elements
6638 from 0 up to LOC_FINAL_VALUE-1 represent themselves, and subsequent
6639 elements are those registered at gdb initialization time. */
6641 static struct symbol_impl symbol_impl[MAX_SYMBOL_IMPLS];
6643 /* The globally visible pointer. This is separate from 'symbol_impl'
6644 so that it can be const. */
6646 gdb::array_view<const struct symbol_impl> symbol_impls (symbol_impl);
6648 /* Make sure we saved enough room in struct symbol. */
6650 static_assert (MAX_SYMBOL_IMPLS <= (1 << SYMBOL_ACLASS_BITS));
6652 /* Register a computed symbol type. ACLASS must be LOC_COMPUTED. OPS
6653 is the ops vector associated with this index. This returns the new
6654 index, which should be used as the aclass_index field for symbols
6655 of this type. */
6658 register_symbol_computed_impl (enum address_class aclass,
6659 const struct symbol_computed_ops *ops)
6661 int result = next_aclass_value++;
6663 gdb_assert (aclass == LOC_COMPUTED);
6664 gdb_assert (result < MAX_SYMBOL_IMPLS);
6665 symbol_impl[result].aclass = aclass;
6666 symbol_impl[result].ops_computed = ops;
6668 /* Sanity check OPS. */
6669 gdb_assert (ops != NULL);
6670 gdb_assert (ops->tracepoint_var_ref != NULL);
6671 gdb_assert (ops->describe_location != NULL);
6672 gdb_assert (ops->get_symbol_read_needs != NULL);
6673 gdb_assert (ops->read_variable != NULL);
6675 return result;
6678 /* Register a function with frame base type. ACLASS must be LOC_BLOCK.
6679 OPS is the ops vector associated with this index. This returns the
6680 new index, which should be used as the aclass_index field for symbols
6681 of this type. */
6684 register_symbol_block_impl (enum address_class aclass,
6685 const struct symbol_block_ops *ops)
6687 int result = next_aclass_value++;
6689 gdb_assert (aclass == LOC_BLOCK);
6690 gdb_assert (result < MAX_SYMBOL_IMPLS);
6691 symbol_impl[result].aclass = aclass;
6692 symbol_impl[result].ops_block = ops;
6694 /* Sanity check OPS. */
6695 gdb_assert (ops != NULL);
6696 gdb_assert (ops->find_frame_base_location != nullptr
6697 || ops->get_block_value != nullptr);
6699 return result;
6702 /* Register a register symbol type. ACLASS must be LOC_REGISTER or
6703 LOC_REGPARM_ADDR. OPS is the register ops vector associated with
6704 this index. This returns the new index, which should be used as
6705 the aclass_index field for symbols of this type. */
6708 register_symbol_register_impl (enum address_class aclass,
6709 const struct symbol_register_ops *ops)
6711 int result = next_aclass_value++;
6713 gdb_assert (aclass == LOC_REGISTER || aclass == LOC_REGPARM_ADDR);
6714 gdb_assert (result < MAX_SYMBOL_IMPLS);
6715 symbol_impl[result].aclass = aclass;
6716 symbol_impl[result].ops_register = ops;
6718 return result;
6721 /* Initialize elements of 'symbol_impl' for the constants in enum
6722 address_class. */
6724 static void
6725 initialize_ordinary_address_classes (void)
6727 int i;
6729 for (i = 0; i < LOC_FINAL_VALUE; ++i)
6730 symbol_impl[i].aclass = (enum address_class) i;
6735 /* See symtab.h. */
6737 struct objfile *
6738 symbol::objfile () const
6740 gdb_assert (is_objfile_owned ());
6741 return owner.symtab->compunit ()->objfile ();
6744 /* See symtab.h. */
6746 struct gdbarch *
6747 symbol::arch () const
6749 if (!is_objfile_owned ())
6750 return owner.arch;
6751 return owner.symtab->compunit ()->objfile ()->arch ();
6754 /* See symtab.h. */
6756 struct symtab *
6757 symbol::symtab () const
6759 gdb_assert (is_objfile_owned ());
6760 return owner.symtab;
6763 /* See symtab.h. */
6765 void
6766 symbol::set_symtab (struct symtab *symtab)
6768 gdb_assert (is_objfile_owned ());
6769 owner.symtab = symtab;
6772 /* See symtab.h. */
6774 CORE_ADDR
6775 symbol::get_maybe_copied_address () const
6777 gdb_assert (this->maybe_copied);
6778 gdb_assert (this->aclass () == LOC_STATIC);
6780 const char *linkage_name = this->linkage_name ();
6781 bound_minimal_symbol minsym
6782 = lookup_minimal_symbol_linkage (this->objfile ()->pspace (), linkage_name,
6783 false);
6784 if (minsym.minsym != nullptr)
6785 return minsym.value_address ();
6787 return this->m_value.address;
6790 /* See symtab.h. */
6792 CORE_ADDR
6793 minimal_symbol::get_maybe_copied_address (objfile *objf) const
6795 gdb_assert (this->maybe_copied (objf));
6796 gdb_assert ((objf->flags & OBJF_MAINLINE) == 0);
6798 const char *linkage_name = this->linkage_name ();
6799 bound_minimal_symbol found
6800 = lookup_minimal_symbol_linkage (objf->pspace (), linkage_name, true);
6801 if (found.minsym != nullptr)
6802 return found.value_address ();
6804 return (this->m_value.address
6805 + objf->section_offsets[this->section_index ()]);
6810 /* Hold the sub-commands of 'info module'. */
6812 static struct cmd_list_element *info_module_cmdlist = NULL;
6814 /* See symtab.h. */
6816 std::vector<module_symbol_search>
6817 search_module_symbols (const char *module_regexp, const char *regexp,
6818 const char *type_regexp, domain_search_flags kind)
6820 std::vector<module_symbol_search> results;
6822 /* Search for all modules matching MODULE_REGEXP. */
6823 global_symbol_searcher spec1 (SEARCH_MODULE_DOMAIN, module_regexp);
6824 spec1.set_exclude_minsyms (true);
6825 std::vector<symbol_search> modules = spec1.search ();
6827 /* Now search for all symbols of the required KIND matching the required
6828 regular expressions. We figure out which ones are in which modules
6829 below. */
6830 global_symbol_searcher spec2 (kind, regexp);
6831 spec2.set_symbol_type_regexp (type_regexp);
6832 spec2.set_exclude_minsyms (true);
6833 std::vector<symbol_search> symbols = spec2.search ();
6835 /* Now iterate over all MODULES, checking to see which items from
6836 SYMBOLS are in each module. */
6837 for (const symbol_search &p : modules)
6839 QUIT;
6841 /* This is a module. */
6842 gdb_assert (p.symbol != nullptr);
6844 std::string prefix = p.symbol->print_name ();
6845 prefix += "::";
6847 for (const symbol_search &q : symbols)
6849 if (q.symbol == nullptr)
6850 continue;
6852 if (strncmp (q.symbol->print_name (), prefix.c_str (),
6853 prefix.size ()) != 0)
6854 continue;
6856 results.push_back ({p, q});
6860 return results;
6863 /* Implement the core of both 'info module functions' and 'info module
6864 variables'. */
6866 static void
6867 info_module_subcommand (bool quiet, const char *module_regexp,
6868 const char *regexp, const char *type_regexp,
6869 domain_search_flags kind)
6871 gdb_assert (kind == SEARCH_FUNCTION_DOMAIN || kind == SEARCH_VAR_DOMAIN);
6873 /* Print a header line. Don't build the header line bit by bit as this
6874 prevents internationalisation. */
6875 if (!quiet)
6877 if (module_regexp == nullptr)
6879 if (type_regexp == nullptr)
6881 if (regexp == nullptr)
6882 gdb_printf ((kind == SEARCH_VAR_DOMAIN
6883 ? _("All variables in all modules:")
6884 : _("All functions in all modules:")));
6885 else
6886 gdb_printf
6887 ((kind == SEARCH_VAR_DOMAIN
6888 ? _("All variables matching regular expression"
6889 " \"%s\" in all modules:")
6890 : _("All functions matching regular expression"
6891 " \"%s\" in all modules:")),
6892 regexp);
6894 else
6896 if (regexp == nullptr)
6897 gdb_printf
6898 ((kind == SEARCH_VAR_DOMAIN
6899 ? _("All variables with type matching regular "
6900 "expression \"%s\" in all modules:")
6901 : _("All functions with type matching regular "
6902 "expression \"%s\" in all modules:")),
6903 type_regexp);
6904 else
6905 gdb_printf
6906 ((kind == SEARCH_VAR_DOMAIN
6907 ? _("All variables matching regular expression "
6908 "\"%s\",\n\twith type matching regular "
6909 "expression \"%s\" in all modules:")
6910 : _("All functions matching regular expression "
6911 "\"%s\",\n\twith type matching regular "
6912 "expression \"%s\" in all modules:")),
6913 regexp, type_regexp);
6916 else
6918 if (type_regexp == nullptr)
6920 if (regexp == nullptr)
6921 gdb_printf
6922 ((kind == SEARCH_VAR_DOMAIN
6923 ? _("All variables in all modules matching regular "
6924 "expression \"%s\":")
6925 : _("All functions in all modules matching regular "
6926 "expression \"%s\":")),
6927 module_regexp);
6928 else
6929 gdb_printf
6930 ((kind == SEARCH_VAR_DOMAIN
6931 ? _("All variables matching regular expression "
6932 "\"%s\",\n\tin all modules matching regular "
6933 "expression \"%s\":")
6934 : _("All functions matching regular expression "
6935 "\"%s\",\n\tin all modules matching regular "
6936 "expression \"%s\":")),
6937 regexp, module_regexp);
6939 else
6941 if (regexp == nullptr)
6942 gdb_printf
6943 ((kind == SEARCH_VAR_DOMAIN
6944 ? _("All variables with type matching regular "
6945 "expression \"%s\"\n\tin all modules matching "
6946 "regular expression \"%s\":")
6947 : _("All functions with type matching regular "
6948 "expression \"%s\"\n\tin all modules matching "
6949 "regular expression \"%s\":")),
6950 type_regexp, module_regexp);
6951 else
6952 gdb_printf
6953 ((kind == SEARCH_VAR_DOMAIN
6954 ? _("All variables matching regular expression "
6955 "\"%s\",\n\twith type matching regular expression "
6956 "\"%s\",\n\tin all modules matching regular "
6957 "expression \"%s\":")
6958 : _("All functions matching regular expression "
6959 "\"%s\",\n\twith type matching regular expression "
6960 "\"%s\",\n\tin all modules matching regular "
6961 "expression \"%s\":")),
6962 regexp, type_regexp, module_regexp);
6965 gdb_printf ("\n");
6968 /* Find all symbols of type KIND matching the given regular expressions
6969 along with the symbols for the modules in which those symbols
6970 reside. */
6971 std::vector<module_symbol_search> module_symbols
6972 = search_module_symbols (module_regexp, regexp, type_regexp, kind);
6974 std::sort (module_symbols.begin (), module_symbols.end (),
6975 [] (const module_symbol_search &a, const module_symbol_search &b)
6977 if (a.first < b.first)
6978 return true;
6979 else if (a.first == b.first)
6980 return a.second < b.second;
6981 else
6982 return false;
6985 const char *last_filename = "";
6986 const symbol *last_module_symbol = nullptr;
6987 for (const module_symbol_search &ms : module_symbols)
6989 const symbol_search &p = ms.first;
6990 const symbol_search &q = ms.second;
6992 gdb_assert (q.symbol != nullptr);
6994 if (last_module_symbol != p.symbol)
6996 gdb_printf ("\n");
6997 gdb_printf (_("Module \"%s\":\n"), p.symbol->print_name ());
6998 last_module_symbol = p.symbol;
6999 last_filename = "";
7002 print_symbol_info (q.symbol, q.block, last_filename);
7003 last_filename
7004 = symtab_to_filename_for_display (q.symbol->symtab ());
7008 /* Hold the option values for the 'info module .....' sub-commands. */
7010 struct info_modules_var_func_options
7012 bool quiet = false;
7013 std::string type_regexp;
7014 std::string module_regexp;
7017 /* The options used by 'info module variables' and 'info module functions'
7018 commands. */
7020 static const gdb::option::option_def info_modules_var_func_options_defs [] = {
7021 gdb::option::boolean_option_def<info_modules_var_func_options> {
7022 "q",
7023 [] (info_modules_var_func_options *opt) { return &opt->quiet; },
7024 nullptr, /* show_cmd_cb */
7025 nullptr /* set_doc */
7028 gdb::option::string_option_def<info_modules_var_func_options> {
7029 "t",
7030 [] (info_modules_var_func_options *opt) { return &opt->type_regexp; },
7031 nullptr, /* show_cmd_cb */
7032 nullptr /* set_doc */
7035 gdb::option::string_option_def<info_modules_var_func_options> {
7036 "m",
7037 [] (info_modules_var_func_options *opt) { return &opt->module_regexp; },
7038 nullptr, /* show_cmd_cb */
7039 nullptr /* set_doc */
7043 /* Return the option group used by the 'info module ...' sub-commands. */
7045 static inline gdb::option::option_def_group
7046 make_info_modules_var_func_options_def_group
7047 (info_modules_var_func_options *opts)
7049 return {{info_modules_var_func_options_defs}, opts};
7052 /* Implements the 'info module functions' command. */
7054 static void
7055 info_module_functions_command (const char *args, int from_tty)
7057 info_modules_var_func_options opts;
7058 auto grp = make_info_modules_var_func_options_def_group (&opts);
7059 gdb::option::process_options
7060 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
7061 if (args != nullptr && *args == '\0')
7062 args = nullptr;
7064 info_module_subcommand
7065 (opts.quiet,
7066 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
7067 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
7068 SEARCH_FUNCTION_DOMAIN);
7071 /* Implements the 'info module variables' command. */
7073 static void
7074 info_module_variables_command (const char *args, int from_tty)
7076 info_modules_var_func_options opts;
7077 auto grp = make_info_modules_var_func_options_def_group (&opts);
7078 gdb::option::process_options
7079 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
7080 if (args != nullptr && *args == '\0')
7081 args = nullptr;
7083 info_module_subcommand
7084 (opts.quiet,
7085 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
7086 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
7087 SEARCH_VAR_DOMAIN);
7090 /* Command completer for 'info module ...' sub-commands. */
7092 static void
7093 info_module_var_func_command_completer (struct cmd_list_element *ignore,
7094 completion_tracker &tracker,
7095 const char *text,
7096 const char * /* word */)
7099 const auto group = make_info_modules_var_func_options_def_group (nullptr);
7100 if (gdb::option::complete_options
7101 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
7102 return;
7104 const char *word = advance_to_expression_complete_word_point (tracker, text);
7105 symbol_completer (ignore, tracker, text, word);
7110 void _initialize_symtab ();
7111 void
7112 _initialize_symtab ()
7114 cmd_list_element *c;
7116 initialize_ordinary_address_classes ();
7118 c = add_info ("variables", info_variables_command,
7119 info_print_args_help (_("\
7120 All global and static variable names or those matching REGEXPs.\n\
7121 Usage: info variables [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7122 Prints the global and static variables.\n"),
7123 _("global and static variables"),
7124 true));
7125 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7127 c = add_info ("functions", info_functions_command,
7128 info_print_args_help (_("\
7129 All function names or those matching REGEXPs.\n\
7130 Usage: info functions [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7131 Prints the functions.\n"),
7132 _("functions"),
7133 true));
7134 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7136 c = add_info ("types", info_types_command, _("\
7137 All type names, or those matching REGEXP.\n\
7138 Usage: info types [-q] [REGEXP]\n\
7139 Print information about all types matching REGEXP, or all types if no\n\
7140 REGEXP is given. The optional flag -q disables printing of headers."));
7141 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7143 const auto info_sources_opts
7144 = make_info_sources_options_def_group (nullptr);
7146 static std::string info_sources_help
7147 = gdb::option::build_help (_("\
7148 All source files in the program or those matching REGEXP.\n\
7149 Usage: info sources [OPTION]... [REGEXP]\n\
7150 By default, REGEXP is used to match anywhere in the filename.\n\
7152 Options:\n\
7153 %OPTIONS%"),
7154 info_sources_opts);
7156 c = add_info ("sources", info_sources_command, info_sources_help.c_str ());
7157 set_cmd_completer_handle_brkchars (c, info_sources_command_completer);
7159 c = add_info ("modules", info_modules_command,
7160 _("All module names, or those matching REGEXP."));
7161 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7163 add_info ("main", info_main_command,
7164 _("Get main symbol to identify entry point into program."));
7166 add_basic_prefix_cmd ("module", class_info, _("\
7167 Print information about modules."),
7168 &info_module_cmdlist, 0, &infolist);
7170 c = add_cmd ("functions", class_info, info_module_functions_command, _("\
7171 Display functions arranged by modules.\n\
7172 Usage: info module functions [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7173 Print a summary of all functions within each Fortran module, grouped by\n\
7174 module and file. For each function the line on which the function is\n\
7175 defined is given along with the type signature and name of the function.\n\
7177 If REGEXP is provided then only functions whose name matches REGEXP are\n\
7178 listed. If MODREGEXP is provided then only functions in modules matching\n\
7179 MODREGEXP are listed. If TYPEREGEXP is given then only functions whose\n\
7180 type signature matches TYPEREGEXP are listed.\n\
7182 The -q flag suppresses printing some header information."),
7183 &info_module_cmdlist);
7184 set_cmd_completer_handle_brkchars
7185 (c, info_module_var_func_command_completer);
7187 c = add_cmd ("variables", class_info, info_module_variables_command, _("\
7188 Display variables arranged by modules.\n\
7189 Usage: info module variables [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7190 Print a summary of all variables within each Fortran module, grouped by\n\
7191 module and file. For each variable the line on which the variable is\n\
7192 defined is given along with the type and name of the variable.\n\
7194 If REGEXP is provided then only variables whose name matches REGEXP are\n\
7195 listed. If MODREGEXP is provided then only variables in modules matching\n\
7196 MODREGEXP are listed. If TYPEREGEXP is given then only variables whose\n\
7197 type matches TYPEREGEXP are listed.\n\
7199 The -q flag suppresses printing some header information."),
7200 &info_module_cmdlist);
7201 set_cmd_completer_handle_brkchars
7202 (c, info_module_var_func_command_completer);
7204 add_com ("rbreak", class_breakpoint, rbreak_command,
7205 _("Set a breakpoint for all functions matching REGEXP."));
7207 add_setshow_enum_cmd ("multiple-symbols", no_class,
7208 multiple_symbols_modes, &multiple_symbols_mode,
7209 _("\
7210 Set how the debugger handles ambiguities in expressions."), _("\
7211 Show how the debugger handles ambiguities in expressions."), _("\
7212 Valid values are \"ask\", \"all\", \"cancel\", and the default is \"all\"."),
7213 NULL, NULL, &setlist, &showlist);
7215 add_setshow_boolean_cmd ("basenames-may-differ", class_obscure,
7216 &basenames_may_differ, _("\
7217 Set whether a source file may have multiple base names."), _("\
7218 Show whether a source file may have multiple base names."), _("\
7219 (A \"base name\" is the name of a file with the directory part removed.\n\
7220 Example: The base name of \"/home/user/hello.c\" is \"hello.c\".)\n\
7221 If set, GDB will canonicalize file names (e.g., expand symlinks)\n\
7222 before comparing them. Canonicalization is an expensive operation,\n\
7223 but it allows the same file be known by more than one base name.\n\
7224 If not set (the default), all source files are assumed to have just\n\
7225 one base name, and gdb will do file name comparisons more efficiently."),
7226 NULL, NULL,
7227 &setlist, &showlist);
7229 add_setshow_zuinteger_cmd ("symtab-create", no_class, &symtab_create_debug,
7230 _("Set debugging of symbol table creation."),
7231 _("Show debugging of symbol table creation."), _("\
7232 When enabled (non-zero), debugging messages are printed when building\n\
7233 symbol tables. A value of 1 (one) normally provides enough information.\n\
7234 A value greater than 1 provides more verbose information."),
7235 NULL,
7236 NULL,
7237 &setdebuglist, &showdebuglist);
7239 add_setshow_zuinteger_cmd ("symbol-lookup", no_class, &symbol_lookup_debug,
7240 _("\
7241 Set debugging of symbol lookup."), _("\
7242 Show debugging of symbol lookup."), _("\
7243 When enabled (non-zero), symbol lookups are logged."),
7244 NULL, NULL,
7245 &setdebuglist, &showdebuglist);
7247 add_setshow_zuinteger_cmd ("symbol-cache-size", no_class,
7248 &new_symbol_cache_size,
7249 _("Set the size of the symbol cache."),
7250 _("Show the size of the symbol cache."), _("\
7251 The size of the symbol cache.\n\
7252 If zero then the symbol cache is disabled."),
7253 set_symbol_cache_size_handler, NULL,
7254 &maintenance_set_cmdlist,
7255 &maintenance_show_cmdlist);
7257 add_setshow_boolean_cmd ("ignore-prologue-end-flag", no_class,
7258 &ignore_prologue_end_flag,
7259 _("Set if the PROLOGUE-END flag is ignored."),
7260 _("Show if the PROLOGUE-END flag is ignored."),
7261 _("\
7262 The PROLOGUE-END flag from the line-table entries is used to place \
7263 breakpoints past the prologue of functions. Disabling its use forces \
7264 the use of prologue scanners."),
7265 nullptr, nullptr,
7266 &maintenance_set_cmdlist,
7267 &maintenance_show_cmdlist);
7270 add_cmd ("symbol-cache", class_maintenance, maintenance_print_symbol_cache,
7271 _("Dump the symbol cache for each program space."),
7272 &maintenanceprintlist);
7274 add_cmd ("symbol-cache-statistics", class_maintenance,
7275 maintenance_print_symbol_cache_statistics,
7276 _("Print symbol cache statistics for each program space."),
7277 &maintenanceprintlist);
7279 cmd_list_element *maintenance_flush_symbol_cache_cmd
7280 = add_cmd ("symbol-cache", class_maintenance,
7281 maintenance_flush_symbol_cache,
7282 _("Flush the symbol cache for each program space."),
7283 &maintenanceflushlist);
7284 c = add_alias_cmd ("flush-symbol-cache", maintenance_flush_symbol_cache_cmd,
7285 class_maintenance, 0, &maintenancelist);
7286 deprecate_cmd (c, "maintenance flush symbol-cache");
7288 gdb::observers::new_objfile.attach (symtab_new_objfile_observer, "symtab");
7289 gdb::observers::all_objfiles_removed.attach (symtab_all_objfiles_removed,
7290 "symtab");
7291 gdb::observers::free_objfile.attach (symtab_free_objfile_observer, "symtab");