More updated translations
[binutils-gdb.git] / gdb / symtab.c
blobab29b59fe9c999177cc3c5c17b06fb8a74912099
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 "exceptions.h"
22 #include "symtab.h"
23 #include "event-top.h"
24 #include "gdbtypes.h"
25 #include "gdbcore.h"
26 #include "frame.h"
27 #include "target.h"
28 #include "value.h"
29 #include "symfile.h"
30 #include "objfiles.h"
31 #include "gdbsupport/gdb_regex.h"
32 #include "expression.h"
33 #include "language.h"
34 #include "demangle.h"
35 #include "inferior.h"
36 #include "source.h"
37 #include "filenames.h"
38 #include "objc-lang.h"
39 #include "d-lang.h"
40 #include "ada-lang.h"
41 #include "go-lang.h"
42 #include "p-lang.h"
43 #include "addrmap.h"
44 #include "cli/cli-utils.h"
45 #include "cli/cli-style.h"
46 #include "cli/cli-cmds.h"
47 #include "fnmatch.h"
48 #include "hashtab.h"
49 #include "typeprint.h"
50 #include "exceptions.h"
52 #include "gdbsupport/gdb_obstack.h"
53 #include "block.h"
54 #include "dictionary.h"
56 #include <sys/types.h>
57 #include <fcntl.h>
58 #include <sys/stat.h>
59 #include <ctype.h>
60 #include "cp-abi.h"
61 #include "cp-support.h"
62 #include "observable.h"
63 #include "solist.h"
64 #include "macrotab.h"
65 #include "macroscope.h"
67 #include "parser-defs.h"
68 #include "completer.h"
69 #include "progspace-and-thread.h"
70 #include <optional>
71 #include "filename-seen-cache.h"
72 #include "arch-utils.h"
73 #include <algorithm>
74 #include <string_view>
75 #include "gdbsupport/pathstuff.h"
76 #include "gdbsupport/common-utils.h"
77 #include <optional>
78 #include <unordered_set>
80 /* Forward declarations for local functions. */
82 static void rbreak_command (const char *, int);
84 static int find_line_common (const linetable *, int, int *, int);
86 static struct block_symbol
87 lookup_symbol_aux (const char *name,
88 symbol_name_match_type match_type,
89 const struct block *block,
90 const domain_search_flags domain,
91 enum language language,
92 struct field_of_this_result *);
94 static
95 struct block_symbol lookup_local_symbol (const char *name,
96 symbol_name_match_type match_type,
97 const struct block *block,
98 const domain_search_flags domain,
99 const struct language_defn *langdef);
101 static struct block_symbol
102 lookup_symbol_in_objfile (struct objfile *objfile,
103 enum block_enum block_index,
104 const char *name,
105 const domain_search_flags domain);
107 static void set_main_name (program_space *pspace, const char *name,
108 language lang);
110 /* Type of the data stored on the program space. */
112 struct main_info
114 /* Name of "main". */
116 std::string name_of_main;
118 /* Language of "main". */
120 enum language language_of_main = language_unknown;
123 /* Program space key for finding name and language of "main". */
125 static const registry<program_space>::key<main_info> main_progspace_key;
127 /* Symbol lookup is not reentrant (though this is not an intrinsic
128 restriction). Keep track of whether a symbol lookup is active, to be able
129 to detect reentrancy. */
130 static bool in_symbol_lookup;
132 /* Struct to mark that a symbol lookup is active for the duration of its
133 lifetime. */
135 struct enter_symbol_lookup
137 enter_symbol_lookup ()
139 /* Ensure that the current language has been set. Normally the
140 language is set lazily. However, when performing a symbol lookup,
141 this could result in a recursive call into the lookup code in some
142 cases. Set it now to ensure that this does not happen. */
143 get_current_language ();
145 /* Detect symbol lookup reentrance. */
146 gdb_assert (!in_symbol_lookup);
148 in_symbol_lookup = true;
151 ~enter_symbol_lookup ()
153 /* Sanity check. */
154 gdb_assert (in_symbol_lookup);
156 in_symbol_lookup = false;
159 DISABLE_COPY_AND_ASSIGN (enter_symbol_lookup);
162 /* The default symbol cache size.
163 There is no extra cpu cost for large N (except when flushing the cache,
164 which is rare). The value here is just a first attempt. A better default
165 value may be higher or lower. A prime number can make up for a bad hash
166 computation, so that's why the number is what it is. */
167 #define DEFAULT_SYMBOL_CACHE_SIZE 1021
169 /* The maximum symbol cache size.
170 There's no method to the decision of what value to use here, other than
171 there's no point in allowing a user typo to make gdb consume all memory. */
172 #define MAX_SYMBOL_CACHE_SIZE (1024*1024)
174 /* symbol_cache_lookup returns this if a previous lookup failed to find the
175 symbol in any objfile. */
176 #define SYMBOL_LOOKUP_FAILED \
177 ((struct block_symbol) {(struct symbol *) 1, NULL})
178 #define SYMBOL_LOOKUP_FAILED_P(SIB) (SIB.symbol == (struct symbol *) 1)
180 /* Recording lookups that don't find the symbol is just as important, if not
181 more so, than recording found symbols. */
183 enum symbol_cache_slot_state
185 SYMBOL_SLOT_UNUSED,
186 SYMBOL_SLOT_NOT_FOUND,
187 SYMBOL_SLOT_FOUND
190 struct symbol_cache_slot
192 enum symbol_cache_slot_state state;
194 /* The objfile that was current when the symbol was looked up.
195 This is only needed for global blocks, but for simplicity's sake
196 we allocate the space for both. If data shows the extra space used
197 for static blocks is a problem, we can split things up then.
199 Global blocks need cache lookup to include the objfile context because
200 we need to account for gdbarch_iterate_over_objfiles_in_search_order
201 which can traverse objfiles in, effectively, any order, depending on
202 the current objfile, thus affecting which symbol is found. Normally,
203 only the current objfile is searched first, and then the rest are
204 searched in recorded order; but putting cache lookup inside
205 gdbarch_iterate_over_objfiles_in_search_order would be awkward.
206 Instead we just make the current objfile part of the context of
207 cache lookup. This means we can record the same symbol multiple times,
208 each with a different "current objfile" that was in effect when the
209 lookup was saved in the cache, but cache space is pretty cheap. */
210 const struct objfile *objfile_context;
212 /* The domain that was searched for initially. This must exactly
213 match. */
214 domain_search_flags domain;
216 union
218 struct block_symbol found;
219 char *name;
220 } value;
223 /* Clear out SLOT. */
225 static void
226 symbol_cache_clear_slot (struct symbol_cache_slot *slot)
228 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
229 xfree (slot->value.name);
230 slot->state = SYMBOL_SLOT_UNUSED;
233 /* Symbols don't specify global vs static block.
234 So keep them in separate caches. */
236 struct block_symbol_cache
238 unsigned int hits;
239 unsigned int misses;
240 unsigned int collisions;
242 /* SYMBOLS is a variable length array of this size.
243 One can imagine that in general one cache (global/static) should be a
244 fraction of the size of the other, but there's no data at the moment
245 on which to decide. */
246 unsigned int size;
248 struct symbol_cache_slot symbols[1];
251 /* Clear all slots of BSC and free BSC. */
253 static void
254 destroy_block_symbol_cache (struct block_symbol_cache *bsc)
256 if (bsc != nullptr)
258 for (unsigned int i = 0; i < bsc->size; i++)
259 symbol_cache_clear_slot (&bsc->symbols[i]);
260 xfree (bsc);
264 /* The symbol cache.
266 Searching for symbols in the static and global blocks over multiple objfiles
267 again and again can be slow, as can searching very big objfiles. This is a
268 simple cache to improve symbol lookup performance, which is critical to
269 overall gdb performance.
271 Symbols are hashed on the name, its domain, and block.
272 They are also hashed on their objfile for objfile-specific lookups. */
274 struct symbol_cache
276 symbol_cache () = default;
278 ~symbol_cache ()
280 destroy_block_symbol_cache (global_symbols);
281 destroy_block_symbol_cache (static_symbols);
284 struct block_symbol_cache *global_symbols = nullptr;
285 struct block_symbol_cache *static_symbols = nullptr;
288 /* Program space key for finding its symbol cache. */
290 static const registry<program_space>::key<symbol_cache> symbol_cache_key;
292 /* When non-zero, print debugging messages related to symtab creation. */
293 unsigned int symtab_create_debug = 0;
295 /* When non-zero, print debugging messages related to symbol lookup. */
296 unsigned int symbol_lookup_debug = 0;
298 /* The size of the cache is staged here. */
299 static unsigned int new_symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
301 /* The current value of the symbol cache size.
302 This is saved so that if the user enters a value too big we can restore
303 the original value from here. */
304 static unsigned int symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
306 /* True if a file may be known by two different basenames.
307 This is the uncommon case, and significantly slows down gdb.
308 Default set to "off" to not slow down the common case. */
309 bool basenames_may_differ = false;
311 /* Allow the user to configure the debugger behavior with respect
312 to multiple-choice menus when more than one symbol matches during
313 a symbol lookup. */
315 const char multiple_symbols_ask[] = "ask";
316 const char multiple_symbols_all[] = "all";
317 const char multiple_symbols_cancel[] = "cancel";
318 static const char *const multiple_symbols_modes[] =
320 multiple_symbols_ask,
321 multiple_symbols_all,
322 multiple_symbols_cancel,
323 NULL
325 static const char *multiple_symbols_mode = multiple_symbols_all;
327 /* When TRUE, ignore the prologue-end flag in linetable_entry when searching
328 for the SAL past a function prologue. */
329 static bool ignore_prologue_end_flag = false;
331 /* Read-only accessor to AUTO_SELECT_MODE. */
333 const char *
334 multiple_symbols_select_mode (void)
336 return multiple_symbols_mode;
339 /* Return the name of a domain_enum. */
341 const char *
342 domain_name (domain_enum e)
344 switch (e)
346 #define SYM_DOMAIN(X) \
347 case X ## _DOMAIN: return #X "_DOMAIN";
348 #include "sym-domains.def"
349 #undef SYM_DOMAIN
350 default: gdb_assert_not_reached ("bad domain_enum");
354 /* See symtab.h. */
356 std::string
357 domain_name (domain_search_flags flags)
359 static constexpr domain_search_flags::string_mapping mapping[] = {
360 #define SYM_DOMAIN(X) \
361 MAP_ENUM_FLAG (SEARCH_ ## X ## _DOMAIN),
362 #include "sym-domains.def"
363 #undef SYM_DOMAIN
366 return flags.to_string (mapping);
369 /* See symtab.h. */
371 domain_search_flags
372 from_scripting_domain (int val)
374 if ((val & SCRIPTING_SEARCH_FLAG) == 0)
376 /* VAL should be one of the domain constants. Verify this and
377 convert it to a search constant. */
378 switch (val)
380 #define SYM_DOMAIN(X) \
381 case X ## _DOMAIN: break;
382 #include "sym-domains.def"
383 #undef SYM_DOMAIN
384 default:
385 error (_("unrecognized domain constant"));
387 domain_search_flags result = to_search_flags ((domain_enum) val);
388 if (val == VAR_DOMAIN)
390 /* This matches the historical practice. */
391 result |= SEARCH_TYPE_DOMAIN | SEARCH_FUNCTION_DOMAIN;
393 return result;
395 else
397 /* VAL is several search constants or'd together. Verify
398 this. */
399 val &= ~SCRIPTING_SEARCH_FLAG;
400 int check = val;
401 #define SYM_DOMAIN(X) \
402 check &= ~ (int) SEARCH_ ## X ## _DOMAIN;
403 #include "sym-domains.def"
404 #undef SYM_DOMAIN
405 if (check != 0)
406 error (_("unrecognized domain constant"));
407 return (domain_search_flag) val;
411 /* See symtab.h. */
413 struct symbol *
414 search_symbol_list (const char *name, int num, struct symbol **syms)
416 for (int i = 0; i < num; ++i)
418 if (strcmp (name, syms[i]->natural_name ()) == 0)
419 return syms[i];
421 return nullptr;
424 /* See symtab.h. */
426 CORE_ADDR
427 linetable_entry::pc (const struct objfile *objfile) const
429 return CORE_ADDR (m_pc) + objfile->text_section_offset ();
432 /* See symtab.h. */
434 call_site *
435 compunit_symtab::find_call_site (CORE_ADDR pc) const
437 if (m_call_site_htab == nullptr)
438 return nullptr;
440 CORE_ADDR delta = this->objfile ()->text_section_offset ();
442 if (auto it = m_call_site_htab->find (static_cast<unrelocated_addr> (pc - delta));
443 it != m_call_site_htab->end ())
444 return *it;
446 /* See if the arch knows another PC we should try. On some
447 platforms, GCC emits a DWARF call site that is offset from the
448 actual return location. */
449 struct gdbarch *arch = objfile ()->arch ();
450 CORE_ADDR new_pc = gdbarch_update_call_site_pc (arch, pc);
452 if (pc == new_pc)
453 return nullptr;
455 if (auto it = m_call_site_htab->find (static_cast<unrelocated_addr> (new_pc - delta));
456 it != m_call_site_htab->end ())
457 return *it;
459 return nullptr;
462 /* See symtab.h. */
464 void
465 compunit_symtab::set_call_site_htab (call_site_htab_t &&call_site_htab)
467 gdb_assert (m_call_site_htab == nullptr);
468 m_call_site_htab = new call_site_htab_t (std::move (call_site_htab));
471 /* See symtab.h. */
473 void
474 compunit_symtab::set_primary_filetab (symtab *primary_filetab)
476 symtab *prev_filetab = nullptr;
478 /* Move PRIMARY_FILETAB to the head of the filetab list. */
479 for (symtab *filetab : this->filetabs ())
481 if (filetab == primary_filetab)
483 if (prev_filetab != nullptr)
485 prev_filetab->next = primary_filetab->next;
486 primary_filetab->next = m_filetabs;
487 m_filetabs = primary_filetab;
490 break;
493 prev_filetab = filetab;
496 gdb_assert (primary_filetab == m_filetabs);
499 /* See symtab.h. */
501 struct symtab *
502 compunit_symtab::primary_filetab () const
504 gdb_assert (m_filetabs != nullptr);
506 /* The primary file symtab is the first one in the list. */
507 return m_filetabs;
510 /* See symtab.h. */
512 enum language
513 compunit_symtab::language () const
515 struct symtab *symtab = primary_filetab ();
517 /* The language of the compunit symtab is the language of its
518 primary source file. */
519 return symtab->language ();
522 /* See symtab.h. */
524 void
525 compunit_symtab::forget_cached_source_info ()
527 for (symtab *s : filetabs ())
528 s->release_fullname ();
531 /* See symtab.h. */
533 void
534 compunit_symtab::finalize ()
536 this->forget_cached_source_info ();
537 delete m_call_site_htab;
540 /* The relocated address of the minimal symbol, using the section
541 offsets from OBJFILE. */
543 CORE_ADDR
544 minimal_symbol::value_address (objfile *objfile) const
546 if (this->maybe_copied (objfile))
547 return this->get_maybe_copied_address (objfile);
548 else
549 return (CORE_ADDR (this->unrelocated_address ())
550 + objfile->section_offsets[this->section_index ()]);
553 /* See symtab.h. */
555 bool
556 minimal_symbol::data_p () const
558 return m_type == mst_data
559 || m_type == mst_bss
560 || m_type == mst_abs
561 || m_type == mst_file_data
562 || m_type == mst_file_bss;
565 /* See symtab.h. */
567 bool
568 minimal_symbol::text_p () const
570 return m_type == mst_text
571 || m_type == mst_text_gnu_ifunc
572 || m_type == mst_data_gnu_ifunc
573 || m_type == mst_slot_got_plt
574 || m_type == mst_solib_trampoline
575 || m_type == mst_file_text;
578 /* See symtab.h. */
580 bool
581 minimal_symbol::maybe_copied (objfile *objfile) const
583 return (objfile->object_format_has_copy_relocs
584 && (objfile->flags & OBJF_MAINLINE) == 0
585 && (m_type == mst_data || m_type == mst_bss));
588 /* See whether FILENAME matches SEARCH_NAME using the rule that we
589 advertise to the user. (The manual's description of linespecs
590 describes what we advertise). Returns true if they match, false
591 otherwise. */
593 bool
594 compare_filenames_for_search (const char *filename, const char *search_name)
596 int len = strlen (filename);
597 size_t search_len = strlen (search_name);
599 if (len < search_len)
600 return false;
602 /* The tail of FILENAME must match. */
603 if (FILENAME_CMP (filename + len - search_len, search_name) != 0)
604 return false;
606 /* Either the names must completely match, or the character
607 preceding the trailing SEARCH_NAME segment of FILENAME must be a
608 directory separator.
610 The check !IS_ABSOLUTE_PATH ensures SEARCH_NAME "/dir/file.c"
611 cannot match FILENAME "/path//dir/file.c" - as user has requested
612 absolute path. The sama applies for "c:\file.c" possibly
613 incorrectly hypothetically matching "d:\dir\c:\file.c".
615 The HAS_DRIVE_SPEC purpose is to make FILENAME "c:file.c"
616 compatible with SEARCH_NAME "file.c". In such case a compiler had
617 to put the "c:file.c" name into debug info. Such compatibility
618 works only on GDB built for DOS host. */
619 return (len == search_len
620 || (!IS_ABSOLUTE_PATH (search_name)
621 && IS_DIR_SEPARATOR (filename[len - search_len - 1]))
622 || (HAS_DRIVE_SPEC (filename)
623 && STRIP_DRIVE_SPEC (filename) == &filename[len - search_len]));
626 /* Check for a symtab of a specific name by searching some symtabs.
627 This is a helper function for callbacks of iterate_over_symtabs.
629 If NAME is not absolute, then REAL_PATH is NULL
630 If NAME is absolute, then REAL_PATH is the gdb_realpath form of NAME.
632 The return value, NAME, REAL_PATH and CALLBACK are identical to the
633 `map_symtabs_matching_filename' method of quick_symbol_functions.
635 FIRST and AFTER_LAST indicate the range of compunit symtabs to search.
636 Each symtab within the specified compunit symtab is also searched.
637 AFTER_LAST is one past the last compunit symtab to search; NULL means to
638 search until the end of the list. */
640 bool
641 iterate_over_some_symtabs (const char *name,
642 const char *real_path,
643 struct compunit_symtab *first,
644 struct compunit_symtab *after_last,
645 gdb::function_view<bool (symtab *)> callback)
647 struct compunit_symtab *cust;
648 const char* base_name = lbasename (name);
650 for (cust = first; cust != NULL && cust != after_last; cust = cust->next)
652 /* Skip included compunits. */
653 if (cust->user != nullptr)
654 continue;
656 for (symtab *s : cust->filetabs ())
658 if (compare_filenames_for_search (s->filename, name))
660 if (callback (s))
661 return true;
662 continue;
665 /* Before we invoke realpath, which can get expensive when many
666 files are involved, do a quick comparison of the basenames. */
667 if (! basenames_may_differ
668 && FILENAME_CMP (base_name, lbasename (s->filename)) != 0)
669 continue;
671 if (compare_filenames_for_search (symtab_to_fullname (s), name))
673 if (callback (s))
674 return true;
675 continue;
678 /* If the user gave us an absolute path, try to find the file in
679 this symtab and use its absolute path. */
680 if (real_path != NULL)
682 const char *fullname = symtab_to_fullname (s);
684 gdb_assert (IS_ABSOLUTE_PATH (real_path));
685 gdb_assert (IS_ABSOLUTE_PATH (name));
686 gdb::unique_xmalloc_ptr<char> fullname_real_path
687 = gdb_realpath (fullname);
688 fullname = fullname_real_path.get ();
689 if (FILENAME_CMP (real_path, fullname) == 0)
691 if (callback (s))
692 return true;
693 continue;
699 return false;
702 /* See symtab.h. */
704 void
705 iterate_over_symtabs (program_space *pspace, const char *name,
706 gdb::function_view<bool (symtab *)> callback)
708 gdb::unique_xmalloc_ptr<char> real_path;
710 /* Here we are interested in canonicalizing an absolute path, not
711 absolutizing a relative path. */
712 if (IS_ABSOLUTE_PATH (name))
714 real_path = gdb_realpath (name);
715 gdb_assert (IS_ABSOLUTE_PATH (real_path.get ()));
718 for (objfile *objfile : pspace->objfiles ())
719 if (iterate_over_some_symtabs (name, real_path.get (),
720 objfile->compunit_symtabs, nullptr,
721 callback))
722 return;
724 /* Same search rules as above apply here, but now we look through the
725 psymtabs. */
726 for (objfile *objfile : pspace->objfiles ())
727 if (objfile->map_symtabs_matching_filename (name, real_path.get (),
728 callback))
729 return;
732 /* See symtab.h. */
734 symtab *
735 lookup_symtab (program_space *pspace, const char *name)
737 struct symtab *result = NULL;
739 iterate_over_symtabs (pspace, name, [&] (symtab *symtab)
741 result = symtab;
742 return true;
745 return result;
749 /* Mangle a GDB method stub type. This actually reassembles the pieces of the
750 full method name, which consist of the class name (from T), the unadorned
751 method name from METHOD_ID, and the signature for the specific overload,
752 specified by SIGNATURE_ID. Note that this function is g++ specific. */
754 char *
755 gdb_mangle_name (struct type *type, int method_id, int signature_id)
757 int mangled_name_len;
758 char *mangled_name;
759 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
760 struct fn_field *method = &f[signature_id];
761 const char *field_name = TYPE_FN_FIELDLIST_NAME (type, method_id);
762 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, signature_id);
763 const char *newname = type->name ();
765 /* Does the form of physname indicate that it is the full mangled name
766 of a constructor (not just the args)? */
767 int is_full_physname_constructor;
769 int is_constructor;
770 int is_destructor = is_destructor_name (physname);
771 /* Need a new type prefix. */
772 const char *const_prefix = method->is_const ? "C" : "";
773 const char *volatile_prefix = method->is_volatile ? "V" : "";
774 char buf[20];
775 int len = (newname == NULL ? 0 : strlen (newname));
777 /* Nothing to do if physname already contains a fully mangled v3 abi name
778 or an operator name. */
779 if ((physname[0] == '_' && physname[1] == 'Z')
780 || is_operator_name (field_name))
781 return xstrdup (physname);
783 is_full_physname_constructor = is_constructor_name (physname);
785 is_constructor = is_full_physname_constructor
786 || (newname && strcmp (field_name, newname) == 0);
788 if (!is_destructor)
789 is_destructor = (startswith (physname, "__dt"));
791 if (is_destructor || is_full_physname_constructor)
793 mangled_name = (char *) xmalloc (strlen (physname) + 1);
794 strcpy (mangled_name, physname);
795 return mangled_name;
798 if (len == 0)
800 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
802 else if (physname[0] == 't' || physname[0] == 'Q')
804 /* The physname for template and qualified methods already includes
805 the class name. */
806 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
807 newname = NULL;
808 len = 0;
810 else
812 xsnprintf (buf, sizeof (buf), "__%s%s%d", const_prefix,
813 volatile_prefix, len);
815 mangled_name_len = ((is_constructor ? 0 : strlen (field_name))
816 + strlen (buf) + len + strlen (physname) + 1);
818 mangled_name = (char *) xmalloc (mangled_name_len);
819 if (is_constructor)
820 mangled_name[0] = '\0';
821 else
822 strcpy (mangled_name, field_name);
824 strcat (mangled_name, buf);
825 /* If the class doesn't have a name, i.e. newname NULL, then we just
826 mangle it using 0 for the length of the class. Thus it gets mangled
827 as something starting with `::' rather than `classname::'. */
828 if (newname != NULL)
829 strcat (mangled_name, newname);
831 strcat (mangled_name, physname);
832 return (mangled_name);
835 /* See symtab.h. */
837 void
838 general_symbol_info::set_demangled_name (const char *name,
839 struct obstack *obstack)
841 if (language () == language_ada)
843 if (name == NULL)
845 ada_mangled = 0;
846 language_specific.obstack = obstack;
848 else
850 ada_mangled = 1;
851 language_specific.demangled_name = name;
854 else
855 language_specific.demangled_name = name;
859 /* Initialize the language dependent portion of a symbol
860 depending upon the language for the symbol. */
862 void
863 general_symbol_info::set_language (enum language language,
864 struct obstack *obstack)
866 m_language = language;
867 if (language == language_cplus
868 || language == language_d
869 || language == language_go
870 || language == language_objc
871 || language == language_fortran)
873 set_demangled_name (NULL, obstack);
875 else if (language == language_ada)
877 gdb_assert (ada_mangled == 0);
878 language_specific.obstack = obstack;
880 else
882 memset (&language_specific, 0, sizeof (language_specific));
886 /* Functions to initialize a symbol's mangled name. */
888 /* Objects of this type are stored in the demangled name hash table. */
889 struct demangled_name_entry
891 demangled_name_entry (std::string_view mangled_name)
892 : mangled (mangled_name) {}
894 std::string_view mangled;
895 enum language language;
896 gdb::unique_xmalloc_ptr<char> demangled;
899 /* Hash function for the demangled name hash. */
901 static hashval_t
902 hash_demangled_name_entry (const void *data)
904 const struct demangled_name_entry *e
905 = (const struct demangled_name_entry *) data;
907 return gdb::string_view_hash () (e->mangled);
910 /* Equality function for the demangled name hash. */
912 static int
913 eq_demangled_name_entry (const void *a, const void *b)
915 const struct demangled_name_entry *da
916 = (const struct demangled_name_entry *) a;
917 const struct demangled_name_entry *db
918 = (const struct demangled_name_entry *) b;
920 return da->mangled == db->mangled;
923 static void
924 free_demangled_name_entry (void *data)
926 struct demangled_name_entry *e
927 = (struct demangled_name_entry *) data;
929 e->~demangled_name_entry();
932 /* Create the hash table used for demangled names. Each hash entry is
933 a pair of strings; one for the mangled name and one for the demangled
934 name. The entry is hashed via just the mangled name. */
936 static void
937 create_demangled_names_hash (struct objfile_per_bfd_storage *per_bfd)
939 /* Choose 256 as the starting size of the hash table, somewhat arbitrarily.
940 The hash table code will round this up to the next prime number.
941 Choosing a much larger table size wastes memory, and saves only about
942 1% in symbol reading. However, if the minsym count is already
943 initialized (e.g. because symbol name setting was deferred to
944 a background thread) we can initialize the hashtable with a count
945 based on that, because we will almost certainly have at least that
946 many entries. If we have a nonzero number but less than 256,
947 we still stay with 256 to have some space for psymbols, etc. */
949 /* htab will expand the table when it is 3/4th full, so we account for that
950 here. +2 to round up. */
951 int minsym_based_count = (per_bfd->minimal_symbol_count + 2) / 3 * 4;
952 int count = std::max (per_bfd->minimal_symbol_count, minsym_based_count);
954 per_bfd->demangled_names_hash.reset (htab_create_alloc
955 (count, hash_demangled_name_entry, eq_demangled_name_entry,
956 free_demangled_name_entry, xcalloc, xfree));
959 /* See symtab.h */
961 gdb::unique_xmalloc_ptr<char>
962 symbol_find_demangled_name (struct general_symbol_info *gsymbol,
963 const char *mangled)
965 gdb::unique_xmalloc_ptr<char> demangled;
966 int i;
968 if (gsymbol->language () != language_unknown)
970 const struct language_defn *lang = language_def (gsymbol->language ());
972 lang->sniff_from_mangled_name (mangled, &demangled);
973 return demangled;
976 for (i = language_unknown; i < nr_languages; ++i)
978 enum language l = (enum language) i;
979 const struct language_defn *lang = language_def (l);
981 if (lang->sniff_from_mangled_name (mangled, &demangled))
983 gsymbol->m_language = l;
984 return demangled;
988 return NULL;
991 /* Set both the mangled and demangled (if any) names for GSYMBOL based
992 on LINKAGE_NAME and LEN. Ordinarily, NAME is copied onto the
993 objfile's obstack; but if COPY_NAME is 0 and if NAME is
994 NUL-terminated, then this function assumes that NAME is already
995 correctly saved (either permanently or with a lifetime tied to the
996 objfile), and it will not be copied.
998 The hash table corresponding to OBJFILE is used, and the memory
999 comes from the per-BFD storage_obstack. LINKAGE_NAME is copied,
1000 so the pointer can be discarded after calling this function. */
1002 void
1003 general_symbol_info::compute_and_set_names (std::string_view linkage_name,
1004 bool copy_name,
1005 objfile_per_bfd_storage *per_bfd,
1006 std::optional<hashval_t> hash)
1008 struct demangled_name_entry **slot;
1010 if (language () == language_ada)
1012 /* In Ada, we do the symbol lookups using the mangled name, so
1013 we can save some space by not storing the demangled name. */
1014 if (!copy_name)
1015 m_name = linkage_name.data ();
1016 else
1017 m_name = obstack_strndup (&per_bfd->storage_obstack,
1018 linkage_name.data (),
1019 linkage_name.length ());
1020 set_demangled_name (NULL, &per_bfd->storage_obstack);
1022 return;
1025 if (per_bfd->demangled_names_hash == NULL)
1026 create_demangled_names_hash (per_bfd);
1028 struct demangled_name_entry entry (linkage_name);
1029 if (!hash.has_value ())
1030 hash = hash_demangled_name_entry (&entry);
1031 slot = ((struct demangled_name_entry **)
1032 htab_find_slot_with_hash (per_bfd->demangled_names_hash.get (),
1033 &entry, *hash, INSERT));
1035 /* The const_cast is safe because the only reason it is already
1036 initialized is if we purposefully set it from a background
1037 thread to avoid doing the work here. However, it is still
1038 allocated from the heap and needs to be freed by us, just
1039 like if we called symbol_find_demangled_name here. If this is
1040 nullptr, we call symbol_find_demangled_name below, but we put
1041 this smart pointer here to be sure that we don't leak this name. */
1042 gdb::unique_xmalloc_ptr<char> demangled_name
1043 (const_cast<char *> (language_specific.demangled_name));
1045 /* If this name is not in the hash table, add it. */
1046 if (*slot == NULL
1047 /* A C version of the symbol may have already snuck into the table.
1048 This happens to, e.g., main.init (__go_init_main). Cope. */
1049 || (language () == language_go && (*slot)->demangled == nullptr))
1051 /* A 0-terminated copy of the linkage name. Callers must set COPY_NAME
1052 to true if the string might not be nullterminated. We have to make
1053 this copy because demangling needs a nullterminated string. */
1054 std::string_view linkage_name_copy;
1055 if (copy_name)
1057 char *alloc_name = (char *) alloca (linkage_name.length () + 1);
1058 memcpy (alloc_name, linkage_name.data (), linkage_name.length ());
1059 alloc_name[linkage_name.length ()] = '\0';
1061 linkage_name_copy = std::string_view (alloc_name,
1062 linkage_name.length ());
1064 else
1065 linkage_name_copy = linkage_name;
1067 if (demangled_name.get () == nullptr)
1068 demangled_name
1069 = symbol_find_demangled_name (this, linkage_name_copy.data ());
1071 /* Suppose we have demangled_name==NULL, copy_name==0, and
1072 linkage_name_copy==linkage_name. In this case, we already have the
1073 mangled name saved, and we don't have a demangled name. So,
1074 you might think we could save a little space by not recording
1075 this in the hash table at all.
1077 It turns out that it is actually important to still save such
1078 an entry in the hash table, because storing this name gives
1079 us better bcache hit rates for partial symbols. */
1080 if (!copy_name)
1082 *slot
1083 = ((struct demangled_name_entry *)
1084 obstack_alloc (&per_bfd->storage_obstack,
1085 sizeof (demangled_name_entry)));
1086 new (*slot) demangled_name_entry (linkage_name);
1088 else
1090 /* If we must copy the mangled name, put it directly after
1091 the struct so we can have a single allocation. */
1092 *slot
1093 = ((struct demangled_name_entry *)
1094 obstack_alloc (&per_bfd->storage_obstack,
1095 sizeof (demangled_name_entry)
1096 + linkage_name.length () + 1));
1097 char *mangled_ptr = reinterpret_cast<char *> (*slot + 1);
1098 memcpy (mangled_ptr, linkage_name.data (), linkage_name.length ());
1099 mangled_ptr [linkage_name.length ()] = '\0';
1100 new (*slot) demangled_name_entry
1101 (std::string_view (mangled_ptr, linkage_name.length ()));
1103 (*slot)->demangled = std::move (demangled_name);
1104 (*slot)->language = language ();
1106 else if (language () == language_unknown)
1107 m_language = (*slot)->language;
1109 m_name = (*slot)->mangled.data ();
1110 set_demangled_name ((*slot)->demangled.get (), &per_bfd->storage_obstack);
1113 /* See symtab.h. */
1115 const char *
1116 general_symbol_info::natural_name () const
1118 switch (language ())
1120 case language_cplus:
1121 case language_d:
1122 case language_go:
1123 case language_objc:
1124 case language_fortran:
1125 case language_rust:
1126 if (language_specific.demangled_name != nullptr)
1127 return language_specific.demangled_name;
1128 break;
1129 case language_ada:
1130 return ada_decode_symbol (this);
1131 default:
1132 break;
1134 return linkage_name ();
1137 /* See symtab.h. */
1139 const char *
1140 general_symbol_info::demangled_name () const
1142 const char *dem_name = NULL;
1144 switch (language ())
1146 case language_cplus:
1147 case language_d:
1148 case language_go:
1149 case language_objc:
1150 case language_fortran:
1151 case language_rust:
1152 dem_name = language_specific.demangled_name;
1153 break;
1154 case language_ada:
1155 dem_name = ada_decode_symbol (this);
1156 break;
1157 default:
1158 break;
1160 return dem_name;
1163 /* See symtab.h. */
1165 const char *
1166 general_symbol_info::search_name () const
1168 if (language () == language_ada)
1169 return linkage_name ();
1170 else
1171 return natural_name ();
1174 /* See symtab.h. */
1176 struct obj_section *
1177 general_symbol_info::obj_section (const struct objfile *objfile) const
1179 if (section_index () >= 0)
1180 return &objfile->sections_start[section_index ()];
1181 return nullptr;
1184 /* See symtab.h. */
1186 bool
1187 symbol_matches_search_name (const struct general_symbol_info *gsymbol,
1188 const lookup_name_info &name)
1190 symbol_name_matcher_ftype *name_match
1191 = language_def (gsymbol->language ())->get_symbol_name_matcher (name);
1192 return name_match (gsymbol->search_name (), name, NULL);
1197 /* Return true if the two sections are the same, or if they could
1198 plausibly be copies of each other, one in an original object
1199 file and another in a separated debug file. */
1201 bool
1202 matching_obj_sections (struct obj_section *obj_first,
1203 struct obj_section *obj_second)
1205 asection *first = obj_first? obj_first->the_bfd_section : NULL;
1206 asection *second = obj_second? obj_second->the_bfd_section : NULL;
1208 /* If they're the same section, then they match. */
1209 if (first == second)
1210 return true;
1212 /* If either is NULL, give up. */
1213 if (first == NULL || second == NULL)
1214 return false;
1216 /* This doesn't apply to absolute symbols. */
1217 if (first->owner == NULL || second->owner == NULL)
1218 return false;
1220 /* If they're in the same object file, they must be different sections. */
1221 if (first->owner == second->owner)
1222 return false;
1224 /* Check whether the two sections are potentially corresponding. They must
1225 have the same size, address, and name. We can't compare section indexes,
1226 which would be more reliable, because some sections may have been
1227 stripped. */
1228 if (bfd_section_size (first) != bfd_section_size (second))
1229 return false;
1231 /* In-memory addresses may start at a different offset, relativize them. */
1232 if (bfd_section_vma (first) - bfd_get_start_address (first->owner)
1233 != bfd_section_vma (second) - bfd_get_start_address (second->owner))
1234 return false;
1236 if (bfd_section_name (first) == NULL
1237 || bfd_section_name (second) == NULL
1238 || strcmp (bfd_section_name (first), bfd_section_name (second)) != 0)
1239 return false;
1241 /* Otherwise check that they are in corresponding objfiles. */
1243 struct objfile *obj = NULL;
1244 for (objfile *objfile : current_program_space->objfiles ())
1245 if (objfile->obfd == first->owner)
1247 obj = objfile;
1248 break;
1250 gdb_assert (obj != NULL);
1252 if (obj->separate_debug_objfile != NULL
1253 && obj->separate_debug_objfile->obfd == second->owner)
1254 return true;
1255 if (obj->separate_debug_objfile_backlink != NULL
1256 && obj->separate_debug_objfile_backlink->obfd == second->owner)
1257 return true;
1259 return false;
1262 /* Hash function for the symbol cache. */
1264 static unsigned int
1265 hash_symbol_entry (const struct objfile *objfile_context,
1266 const char *name, domain_search_flags domain)
1268 unsigned int hash = (uintptr_t) objfile_context;
1270 if (name != NULL)
1271 hash += htab_hash_string (name);
1273 hash += domain * 7;
1275 return hash;
1278 /* Equality function for the symbol cache. */
1280 static int
1281 eq_symbol_entry (const struct symbol_cache_slot *slot,
1282 const struct objfile *objfile_context,
1283 const char *name, domain_search_flags domain)
1285 const char *slot_name;
1287 if (slot->state == SYMBOL_SLOT_UNUSED)
1288 return 0;
1290 if (slot->objfile_context != objfile_context)
1291 return 0;
1293 domain_search_flags slot_domain = slot->domain;
1294 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1295 slot_name = slot->value.name;
1296 else
1297 slot_name = slot->value.found.symbol->search_name ();
1299 /* NULL names match. */
1300 if (slot_name == NULL && name == NULL)
1302 /* But there's no point in calling symbol_matches_domain in the
1303 SYMBOL_SLOT_FOUND case. */
1304 if (slot_domain != domain)
1305 return 0;
1307 else if (slot_name != NULL && name != NULL)
1309 /* It's important that we use the same comparison that was done
1310 the first time through. If the slot records a found symbol,
1311 then this means using the symbol name comparison function of
1312 the symbol's language with symbol->search_name (). See
1313 dictionary.c.
1315 If the slot records a not-found symbol, then require a precise match.
1316 We could still be lax with whitespace like strcmp_iw though. */
1318 if (slot_domain != domain)
1319 return 0;
1321 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1323 if (strcmp (slot_name, name) != 0)
1324 return 0;
1326 else
1328 struct symbol *sym = slot->value.found.symbol;
1329 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1331 if (!symbol_matches_search_name (sym, lookup_name))
1332 return 0;
1335 else
1337 /* Only one name is NULL. */
1338 return 0;
1341 return 1;
1344 /* Given a cache of size SIZE, return the size of the struct (with variable
1345 length array) in bytes. */
1347 static size_t
1348 symbol_cache_byte_size (unsigned int size)
1350 return (sizeof (struct block_symbol_cache)
1351 + ((size - 1) * sizeof (struct symbol_cache_slot)));
1354 /* Resize CACHE. */
1356 static void
1357 resize_symbol_cache (struct symbol_cache *cache, unsigned int new_size)
1359 /* If there's no change in size, don't do anything.
1360 All caches have the same size, so we can just compare with the size
1361 of the global symbols cache. */
1362 if ((cache->global_symbols != NULL
1363 && cache->global_symbols->size == new_size)
1364 || (cache->global_symbols == NULL
1365 && new_size == 0))
1366 return;
1368 destroy_block_symbol_cache (cache->global_symbols);
1369 destroy_block_symbol_cache (cache->static_symbols);
1371 if (new_size == 0)
1373 cache->global_symbols = NULL;
1374 cache->static_symbols = NULL;
1376 else
1378 size_t total_size = symbol_cache_byte_size (new_size);
1380 cache->global_symbols
1381 = (struct block_symbol_cache *) xcalloc (1, total_size);
1382 cache->static_symbols
1383 = (struct block_symbol_cache *) xcalloc (1, total_size);
1384 cache->global_symbols->size = new_size;
1385 cache->static_symbols->size = new_size;
1389 /* Return the symbol cache of PSPACE.
1390 Create one if it doesn't exist yet. */
1392 static struct symbol_cache *
1393 get_symbol_cache (struct program_space *pspace)
1395 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1397 if (cache == NULL)
1399 cache = symbol_cache_key.emplace (pspace);
1400 resize_symbol_cache (cache, symbol_cache_size);
1403 return cache;
1406 /* Set the size of the symbol cache in all program spaces. */
1408 static void
1409 set_symbol_cache_size (unsigned int new_size)
1411 for (struct program_space *pspace : program_spaces)
1413 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1415 /* The pspace could have been created but not have a cache yet. */
1416 if (cache != NULL)
1417 resize_symbol_cache (cache, new_size);
1421 /* Called when symbol-cache-size is set. */
1423 static void
1424 set_symbol_cache_size_handler (const char *args, int from_tty,
1425 struct cmd_list_element *c)
1427 if (new_symbol_cache_size > MAX_SYMBOL_CACHE_SIZE)
1429 /* Restore the previous value.
1430 This is the value the "show" command prints. */
1431 new_symbol_cache_size = symbol_cache_size;
1433 error (_("Symbol cache size is too large, max is %u."),
1434 MAX_SYMBOL_CACHE_SIZE);
1436 symbol_cache_size = new_symbol_cache_size;
1438 set_symbol_cache_size (symbol_cache_size);
1441 /* Lookup symbol NAME,DOMAIN in BLOCK in the symbol cache of PSPACE.
1442 OBJFILE_CONTEXT is the current objfile, which may be NULL.
1443 The result is the symbol if found, SYMBOL_LOOKUP_FAILED if a previous lookup
1444 failed (and thus this one will too), or NULL if the symbol is not present
1445 in the cache.
1446 *BSC_PTR and *SLOT_PTR are set to the cache and slot of the symbol, which
1447 can be used to save the result of a full lookup attempt. */
1449 static struct block_symbol
1450 symbol_cache_lookup (struct symbol_cache *cache,
1451 struct objfile *objfile_context, enum block_enum block,
1452 const char *name, domain_search_flags domain,
1453 struct block_symbol_cache **bsc_ptr,
1454 struct symbol_cache_slot **slot_ptr)
1456 struct block_symbol_cache *bsc;
1457 unsigned int hash;
1458 struct symbol_cache_slot *slot;
1460 if (block == GLOBAL_BLOCK)
1461 bsc = cache->global_symbols;
1462 else
1463 bsc = cache->static_symbols;
1464 if (bsc == NULL)
1466 *bsc_ptr = NULL;
1467 *slot_ptr = NULL;
1468 return {};
1471 hash = hash_symbol_entry (objfile_context, name, domain);
1472 slot = bsc->symbols + hash % bsc->size;
1474 *bsc_ptr = bsc;
1475 *slot_ptr = slot;
1477 if (eq_symbol_entry (slot, objfile_context, name, domain))
1479 symbol_lookup_debug_printf ("%s block symbol cache hit%s for %s, %s",
1480 block == GLOBAL_BLOCK ? "Global" : "Static",
1481 slot->state == SYMBOL_SLOT_NOT_FOUND
1482 ? " (not found)" : "", name,
1483 domain_name (domain).c_str ());
1484 ++bsc->hits;
1485 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1486 return SYMBOL_LOOKUP_FAILED;
1487 return slot->value.found;
1490 /* Symbol is not present in the cache. */
1492 symbol_lookup_debug_printf ("%s block symbol cache miss for %s, %s",
1493 block == GLOBAL_BLOCK ? "Global" : "Static",
1494 name, domain_name (domain).c_str ());
1495 ++bsc->misses;
1496 return {};
1499 /* Mark SYMBOL as found in SLOT.
1500 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1501 if it's not needed to distinguish lookups (STATIC_BLOCK). It is *not*
1502 necessarily the objfile the symbol was found in. */
1504 static void
1505 symbol_cache_mark_found (struct block_symbol_cache *bsc,
1506 struct symbol_cache_slot *slot,
1507 struct objfile *objfile_context,
1508 struct symbol *symbol,
1509 const struct block *block,
1510 domain_search_flags domain)
1512 if (bsc == NULL)
1513 return;
1514 if (slot->state != SYMBOL_SLOT_UNUSED)
1516 ++bsc->collisions;
1517 symbol_cache_clear_slot (slot);
1519 slot->state = SYMBOL_SLOT_FOUND;
1520 slot->objfile_context = objfile_context;
1521 slot->value.found.symbol = symbol;
1522 slot->value.found.block = block;
1523 slot->domain = domain;
1526 /* Mark symbol NAME, DOMAIN as not found in SLOT.
1527 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1528 if it's not needed to distinguish lookups (STATIC_BLOCK). */
1530 static void
1531 symbol_cache_mark_not_found (struct block_symbol_cache *bsc,
1532 struct symbol_cache_slot *slot,
1533 struct objfile *objfile_context,
1534 const char *name, domain_search_flags domain)
1536 if (bsc == NULL)
1537 return;
1538 if (slot->state != SYMBOL_SLOT_UNUSED)
1540 ++bsc->collisions;
1541 symbol_cache_clear_slot (slot);
1543 slot->state = SYMBOL_SLOT_NOT_FOUND;
1544 slot->objfile_context = objfile_context;
1545 slot->value.name = xstrdup (name);
1546 slot->domain = domain;
1549 /* Flush the symbol cache of PSPACE. */
1551 static void
1552 symbol_cache_flush (struct program_space *pspace)
1554 ada_clear_symbol_cache (pspace);
1555 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1556 int pass;
1558 if (cache == NULL)
1559 return;
1560 if (cache->global_symbols == NULL)
1562 gdb_assert (symbol_cache_size == 0);
1563 gdb_assert (cache->static_symbols == NULL);
1564 return;
1567 /* If the cache is untouched since the last flush, early exit.
1568 This is important for performance during the startup of a program linked
1569 with 100s (or 1000s) of shared libraries. */
1570 if (cache->global_symbols->misses == 0
1571 && cache->static_symbols->misses == 0)
1572 return;
1574 gdb_assert (cache->global_symbols->size == symbol_cache_size);
1575 gdb_assert (cache->static_symbols->size == symbol_cache_size);
1577 for (pass = 0; pass < 2; ++pass)
1579 struct block_symbol_cache *bsc
1580 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1581 unsigned int i;
1583 for (i = 0; i < bsc->size; ++i)
1584 symbol_cache_clear_slot (&bsc->symbols[i]);
1587 cache->global_symbols->hits = 0;
1588 cache->global_symbols->misses = 0;
1589 cache->global_symbols->collisions = 0;
1590 cache->static_symbols->hits = 0;
1591 cache->static_symbols->misses = 0;
1592 cache->static_symbols->collisions = 0;
1595 /* Dump CACHE. */
1597 static void
1598 symbol_cache_dump (const struct symbol_cache *cache)
1600 int pass;
1602 if (cache->global_symbols == NULL)
1604 gdb_printf (" <disabled>\n");
1605 return;
1608 for (pass = 0; pass < 2; ++pass)
1610 const struct block_symbol_cache *bsc
1611 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1612 unsigned int i;
1614 if (pass == 0)
1615 gdb_printf ("Global symbols:\n");
1616 else
1617 gdb_printf ("Static symbols:\n");
1619 for (i = 0; i < bsc->size; ++i)
1621 const struct symbol_cache_slot *slot = &bsc->symbols[i];
1623 QUIT;
1625 switch (slot->state)
1627 case SYMBOL_SLOT_UNUSED:
1628 break;
1629 case SYMBOL_SLOT_NOT_FOUND:
1630 gdb_printf (" [%4u] = %s, %s %s (not found)\n", i,
1631 host_address_to_string (slot->objfile_context),
1632 slot->value.name,
1633 domain_name (slot->domain).c_str ());
1634 break;
1635 case SYMBOL_SLOT_FOUND:
1637 struct symbol *found = slot->value.found.symbol;
1638 const struct objfile *context = slot->objfile_context;
1640 gdb_printf (" [%4u] = %s, %s %s\n", i,
1641 host_address_to_string (context),
1642 found->print_name (),
1643 domain_name (found->domain ()));
1644 break;
1651 /* The "mt print symbol-cache" command. */
1653 static void
1654 maintenance_print_symbol_cache (const char *args, int from_tty)
1656 for (struct program_space *pspace : program_spaces)
1658 struct symbol_cache *cache;
1660 gdb_printf (_("Symbol cache for pspace %d\n%s:\n"),
1661 pspace->num,
1662 pspace->symfile_object_file != NULL
1663 ? objfile_name (pspace->symfile_object_file)
1664 : "(no object file)");
1666 /* If the cache hasn't been created yet, avoid creating one. */
1667 cache = symbol_cache_key.get (pspace);
1668 if (cache == NULL)
1669 gdb_printf (" <empty>\n");
1670 else
1671 symbol_cache_dump (cache);
1675 /* The "mt flush-symbol-cache" command. */
1677 static void
1678 maintenance_flush_symbol_cache (const char *args, int from_tty)
1680 for (struct program_space *pspace : program_spaces)
1682 symbol_cache_flush (pspace);
1686 /* Print usage statistics of CACHE. */
1688 static void
1689 symbol_cache_stats (struct symbol_cache *cache)
1691 int pass;
1693 if (cache->global_symbols == NULL)
1695 gdb_printf (" <disabled>\n");
1696 return;
1699 for (pass = 0; pass < 2; ++pass)
1701 const struct block_symbol_cache *bsc
1702 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1704 QUIT;
1706 if (pass == 0)
1707 gdb_printf ("Global block cache stats:\n");
1708 else
1709 gdb_printf ("Static block cache stats:\n");
1711 gdb_printf (" size: %u\n", bsc->size);
1712 gdb_printf (" hits: %u\n", bsc->hits);
1713 gdb_printf (" misses: %u\n", bsc->misses);
1714 gdb_printf (" collisions: %u\n", bsc->collisions);
1718 /* The "mt print symbol-cache-statistics" command. */
1720 static void
1721 maintenance_print_symbol_cache_statistics (const char *args, int from_tty)
1723 for (struct program_space *pspace : program_spaces)
1725 struct symbol_cache *cache;
1727 gdb_printf (_("Symbol cache statistics for pspace %d\n%s:\n"),
1728 pspace->num,
1729 pspace->symfile_object_file != NULL
1730 ? objfile_name (pspace->symfile_object_file)
1731 : "(no object file)");
1733 /* If the cache hasn't been created yet, avoid creating one. */
1734 cache = symbol_cache_key.get (pspace);
1735 if (cache == NULL)
1736 gdb_printf (" empty, no stats available\n");
1737 else
1738 symbol_cache_stats (cache);
1742 /* This module's 'new_objfile' observer. */
1744 static void
1745 symtab_new_objfile_observer (struct objfile *objfile)
1747 symbol_cache_flush (objfile->pspace ());
1750 /* This module's 'all_objfiles_removed' observer. */
1752 static void
1753 symtab_all_objfiles_removed (program_space *pspace)
1755 symbol_cache_flush (pspace);
1757 /* Forget everything we know about the main function. */
1758 main_progspace_key.clear (pspace);
1761 /* This module's 'free_objfile' observer. */
1763 static void
1764 symtab_free_objfile_observer (struct objfile *objfile)
1766 symbol_cache_flush (objfile->pspace ());
1769 /* See symtab.h. */
1771 void
1772 fixup_symbol_section (struct symbol *sym, struct objfile *objfile)
1774 gdb_assert (sym != nullptr);
1775 gdb_assert (sym->is_objfile_owned ());
1776 gdb_assert (objfile != nullptr);
1777 gdb_assert (sym->section_index () == -1);
1779 /* Note that if this ends up as -1, fixup_section will handle that
1780 reasonably well. So, it's fine to use the objfile's section
1781 index without doing the check that is done by the wrapper macros
1782 like SECT_OFF_TEXT. */
1783 int fallback;
1784 switch (sym->aclass ())
1786 case LOC_STATIC:
1787 fallback = objfile->sect_index_data;
1788 break;
1790 case LOC_LABEL:
1791 fallback = objfile->sect_index_text;
1792 break;
1794 default:
1795 /* Nothing else will be listed in the minsyms -- no use looking
1796 it up. */
1797 return;
1800 CORE_ADDR addr = sym->value_address ();
1802 struct minimal_symbol *msym;
1804 /* First, check whether a minimal symbol with the same name exists
1805 and points to the same address. The address check is required
1806 e.g. on PowerPC64, where the minimal symbol for a function will
1807 point to the function descriptor, while the debug symbol will
1808 point to the actual function code. */
1809 msym = lookup_minimal_symbol_by_pc_name (addr, sym->linkage_name (),
1810 objfile);
1811 if (msym)
1812 sym->set_section_index (msym->section_index ());
1813 else
1815 /* Static, function-local variables do appear in the linker
1816 (minimal) symbols, but are frequently given names that won't
1817 be found via lookup_minimal_symbol(). E.g., it has been
1818 observed in frv-uclinux (ELF) executables that a static,
1819 function-local variable named "foo" might appear in the
1820 linker symbols as "foo.6" or "foo.3". Thus, there is no
1821 point in attempting to extend the lookup-by-name mechanism to
1822 handle this case due to the fact that there can be multiple
1823 names.
1825 So, instead, search the section table when lookup by name has
1826 failed. The ``addr'' and ``endaddr'' fields may have already
1827 been relocated. If so, the relocation offset needs to be
1828 subtracted from these values when performing the comparison.
1829 We unconditionally subtract it, because, when no relocation
1830 has been performed, the value will simply be zero.
1832 The address of the symbol whose section we're fixing up HAS
1833 NOT BEEN adjusted (relocated) yet. It can't have been since
1834 the section isn't yet known and knowing the section is
1835 necessary in order to add the correct relocation value. In
1836 other words, we wouldn't even be in this function (attempting
1837 to compute the section) if it were already known.
1839 Note that it is possible to search the minimal symbols
1840 (subtracting the relocation value if necessary) to find the
1841 matching minimal symbol, but this is overkill and much less
1842 efficient. It is not necessary to find the matching minimal
1843 symbol, only its section.
1845 Note that this technique (of doing a section table search)
1846 can fail when unrelocated section addresses overlap. For
1847 this reason, we still attempt a lookup by name prior to doing
1848 a search of the section table. */
1850 for (obj_section *s : objfile->sections ())
1852 if ((bfd_section_flags (s->the_bfd_section) & SEC_ALLOC) == 0)
1853 continue;
1855 int idx = s - objfile->sections_start;
1856 CORE_ADDR offset = objfile->section_offsets[idx];
1858 if (fallback == -1)
1859 fallback = idx;
1861 if (s->addr () - offset <= addr && addr < s->endaddr () - offset)
1863 sym->set_section_index (idx);
1864 return;
1868 /* If we didn't find the section, assume it is in the first
1869 section. If there is no allocated section, then it hardly
1870 matters what we pick, so just pick zero. */
1871 if (fallback == -1)
1872 sym->set_section_index (0);
1873 else
1874 sym->set_section_index (fallback);
1878 /* See symtab.h. */
1880 demangle_for_lookup_info::demangle_for_lookup_info
1881 (const lookup_name_info &lookup_name, language lang)
1883 demangle_result_storage storage;
1885 if (lookup_name.ignore_parameters () && lang == language_cplus)
1887 gdb::unique_xmalloc_ptr<char> without_params
1888 = cp_remove_params_if_any (lookup_name.c_str (),
1889 lookup_name.completion_mode ());
1891 if (without_params != NULL)
1893 if (lookup_name.match_type () != symbol_name_match_type::SEARCH_NAME)
1894 m_demangled_name = demangle_for_lookup (without_params.get (),
1895 lang, storage);
1896 return;
1900 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
1901 m_demangled_name = lookup_name.c_str ();
1902 else
1903 m_demangled_name = demangle_for_lookup (lookup_name.c_str (),
1904 lang, storage);
1907 /* See symtab.h. */
1909 const lookup_name_info &
1910 lookup_name_info::match_any ()
1912 /* Lookup any symbol that "" would complete. I.e., this matches all
1913 symbol names. */
1914 static const lookup_name_info lookup_name ("", symbol_name_match_type::FULL,
1915 true);
1917 return lookup_name;
1920 /* See symtab.h. */
1922 unsigned int
1923 lookup_name_info::search_name_hash (language lang) const
1925 /* This works around an obscure problem. If currently in Ada mode,
1926 and the name is wrapped in '<...>' (indicating verbatim mode),
1927 force the use of the Ada language here so that the '<' and '>'
1928 will be removed. */
1929 if (current_language->la_language == language_ada && ada ().verbatim_p ())
1930 lang = language_ada;
1932 /* Only compute each language's hash once. */
1933 if (!m_demangled_hashes_p[lang])
1935 m_demangled_hashes[lang]
1936 = ::search_name_hash (lang, language_lookup_name (lang));
1937 m_demangled_hashes_p[lang] = true;
1939 return m_demangled_hashes[lang];
1942 /* Compute the demangled form of NAME as used by the various symbol
1943 lookup functions. The result can either be the input NAME
1944 directly, or a pointer to a buffer owned by the STORAGE object.
1946 For Ada, this function just returns NAME, unmodified.
1947 Normally, Ada symbol lookups are performed using the encoded name
1948 rather than the demangled name, and so it might seem to make sense
1949 for this function to return an encoded version of NAME.
1950 Unfortunately, we cannot do this, because this function is used in
1951 circumstances where it is not appropriate to try to encode NAME.
1952 For instance, when displaying the frame info, we demangle the name
1953 of each parameter, and then perform a symbol lookup inside our
1954 function using that demangled name. In Ada, certain functions
1955 have internally-generated parameters whose name contain uppercase
1956 characters. Encoding those name would result in those uppercase
1957 characters to become lowercase, and thus cause the symbol lookup
1958 to fail. */
1960 const char *
1961 demangle_for_lookup (const char *name, enum language lang,
1962 demangle_result_storage &storage)
1964 /* If we are using C++, D, or Go, demangle the name before doing a
1965 lookup, so we can always binary search. */
1966 if (lang == language_cplus)
1968 gdb::unique_xmalloc_ptr<char> demangled_name
1969 = gdb_demangle (name, DMGL_ANSI | DMGL_PARAMS);
1970 if (demangled_name != NULL)
1971 return storage.set_malloc_ptr (std::move (demangled_name));
1973 /* If we were given a non-mangled name, canonicalize it
1974 according to the language (so far only for C++). */
1975 gdb::unique_xmalloc_ptr<char> canon = cp_canonicalize_string (name);
1976 if (canon != nullptr)
1977 return storage.set_malloc_ptr (std::move (canon));
1979 else if (lang == language_d)
1981 gdb::unique_xmalloc_ptr<char> demangled_name = d_demangle (name, 0);
1982 if (demangled_name != NULL)
1983 return storage.set_malloc_ptr (std::move (demangled_name));
1985 else if (lang == language_go)
1987 gdb::unique_xmalloc_ptr<char> demangled_name
1988 = language_def (language_go)->demangle_symbol (name, 0);
1989 if (demangled_name != NULL)
1990 return storage.set_malloc_ptr (std::move (demangled_name));
1993 return name;
1996 /* See symtab.h. */
1998 unsigned int
1999 search_name_hash (enum language language, const char *search_name)
2001 return language_def (language)->search_name_hash (search_name);
2004 /* See symtab.h.
2006 This function (or rather its subordinates) have a bunch of loops and
2007 it would seem to be attractive to put in some QUIT's (though I'm not really
2008 sure whether it can run long enough to be really important). But there
2009 are a few calls for which it would appear to be bad news to quit
2010 out of here: e.g., find_proc_desc in alpha-mdebug-tdep.c. (Note
2011 that there is C++ code below which can error(), but that probably
2012 doesn't affect these calls since they are looking for a known
2013 variable and thus can probably assume it will never hit the C++
2014 code). */
2016 struct block_symbol
2017 lookup_symbol_in_language (const char *name, const struct block *block,
2018 const domain_search_flags domain,
2019 enum language lang,
2020 struct field_of_this_result *is_a_field_of_this)
2022 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2024 demangle_result_storage storage;
2025 const char *modified_name = demangle_for_lookup (name, lang, storage);
2027 return lookup_symbol_aux (modified_name,
2028 symbol_name_match_type::FULL,
2029 block, domain, lang,
2030 is_a_field_of_this);
2033 /* See symtab.h. */
2035 struct block_symbol
2036 lookup_symbol (const char *name, const struct block *block,
2037 domain_search_flags domain,
2038 struct field_of_this_result *is_a_field_of_this)
2040 return lookup_symbol_in_language (name, block, domain,
2041 current_language->la_language,
2042 is_a_field_of_this);
2045 /* See symtab.h. */
2047 struct block_symbol
2048 lookup_symbol_search_name (const char *search_name, const struct block *block,
2049 domain_search_flags domain)
2051 return lookup_symbol_aux (search_name, symbol_name_match_type::SEARCH_NAME,
2052 block, domain, language_asm, NULL);
2055 /* See symtab.h. */
2057 struct block_symbol
2058 lookup_language_this (const struct language_defn *lang,
2059 const struct block *block)
2061 if (lang->name_of_this () == NULL || block == NULL)
2062 return {};
2064 symbol_lookup_debug_printf_v ("lookup_language_this (%s, %s (objfile %s))",
2065 lang->name (), host_address_to_string (block),
2066 objfile_debug_name (block->objfile ()));
2068 lookup_name_info this_name (lang->name_of_this (),
2069 symbol_name_match_type::SEARCH_NAME);
2071 while (block)
2073 struct symbol *sym;
2075 sym = block_lookup_symbol (block, this_name, SEARCH_VFT);
2076 if (sym != NULL)
2078 symbol_lookup_debug_printf_v
2079 ("lookup_language_this (...) = %s (%s, block %s)",
2080 sym->print_name (), host_address_to_string (sym),
2081 host_address_to_string (block));
2082 return (struct block_symbol) {sym, block};
2084 if (block->function ())
2085 break;
2086 block = block->superblock ();
2089 symbol_lookup_debug_printf_v ("lookup_language_this (...) = NULL");
2090 return {};
2093 /* Given TYPE, a structure/union,
2094 return 1 if the component named NAME from the ultimate target
2095 structure/union is defined, otherwise, return 0. */
2097 static int
2098 check_field (struct type *type, const char *name,
2099 struct field_of_this_result *is_a_field_of_this)
2101 int i;
2103 /* The type may be a stub. */
2104 type = check_typedef (type);
2106 for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
2108 const char *t_field_name = type->field (i).name ();
2110 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2112 is_a_field_of_this->type = type;
2113 is_a_field_of_this->field = &type->field (i);
2114 return 1;
2118 /* C++: If it was not found as a data field, then try to return it
2119 as a pointer to a method. */
2121 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
2123 if (strcmp_iw (TYPE_FN_FIELDLIST_NAME (type, i), name) == 0)
2125 is_a_field_of_this->type = type;
2126 is_a_field_of_this->fn_field = &TYPE_FN_FIELDLIST (type, i);
2127 return 1;
2131 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2132 if (check_field (TYPE_BASECLASS (type, i), name, is_a_field_of_this))
2133 return 1;
2135 return 0;
2138 /* Behave like lookup_symbol except that NAME is the natural name
2139 (e.g., demangled name) of the symbol that we're looking for. */
2141 static struct block_symbol
2142 lookup_symbol_aux (const char *name, symbol_name_match_type match_type,
2143 const struct block *block,
2144 const domain_search_flags domain, enum language language,
2145 struct field_of_this_result *is_a_field_of_this)
2147 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2149 struct block_symbol result;
2150 const struct language_defn *langdef;
2152 if (symbol_lookup_debug)
2154 struct objfile *objfile = (block == nullptr
2155 ? nullptr : block->objfile ());
2157 symbol_lookup_debug_printf
2158 ("demangled symbol name = \"%s\", block @ %s (objfile %s)",
2159 name, host_address_to_string (block),
2160 objfile != NULL ? objfile_debug_name (objfile) : "NULL");
2161 symbol_lookup_debug_printf
2162 ("domain name = \"%s\", language = \"%s\")",
2163 domain_name (domain).c_str (), language_str (language));
2166 /* Make sure we do something sensible with is_a_field_of_this, since
2167 the callers that set this parameter to some non-null value will
2168 certainly use it later. If we don't set it, the contents of
2169 is_a_field_of_this are undefined. */
2170 if (is_a_field_of_this != NULL)
2171 memset (is_a_field_of_this, 0, sizeof (*is_a_field_of_this));
2173 langdef = language_def (language);
2175 /* Search specified block and its superiors. Don't search
2176 STATIC_BLOCK or GLOBAL_BLOCK. */
2178 result = lookup_local_symbol (name, match_type, block, domain, langdef);
2179 if (result.symbol != NULL)
2181 symbol_lookup_debug_printf
2182 ("found symbol @ %s (using lookup_local_symbol)",
2183 host_address_to_string (result.symbol));
2184 return result;
2187 /* If requested to do so by the caller and if appropriate for LANGUAGE,
2188 check to see if NAME is a field of `this'. */
2190 /* Don't do this check if we are searching for a struct. It will
2191 not be found by check_field, but will be found by other
2192 means. */
2193 if (is_a_field_of_this != NULL && (domain & SEARCH_STRUCT_DOMAIN) == 0)
2195 result = lookup_language_this (langdef, block);
2197 if (result.symbol)
2199 struct type *t = result.symbol->type ();
2201 /* I'm not really sure that type of this can ever
2202 be typedefed; just be safe. */
2203 t = check_typedef (t);
2204 if (t->is_pointer_or_reference ())
2205 t = t->target_type ();
2207 if (t->code () != TYPE_CODE_STRUCT
2208 && t->code () != TYPE_CODE_UNION)
2209 error (_("Internal error: `%s' is not an aggregate"),
2210 langdef->name_of_this ());
2212 if (check_field (t, name, is_a_field_of_this))
2214 symbol_lookup_debug_printf ("no symbol found");
2215 return {};
2220 /* Now do whatever is appropriate for LANGUAGE to look
2221 up static and global variables. */
2223 result = langdef->lookup_symbol_nonlocal (name, block, domain);
2224 if (result.symbol != NULL)
2226 symbol_lookup_debug_printf
2227 ("found symbol @ %s (using language lookup_symbol_nonlocal)",
2228 host_address_to_string (result.symbol));
2229 return result;
2232 /* Now search all static file-level symbols. Not strictly correct,
2233 but more useful than an error. */
2235 result = lookup_static_symbol (name, domain);
2236 symbol_lookup_debug_printf
2237 ("found symbol @ %s (using lookup_static_symbol)",
2238 result.symbol != NULL ? host_address_to_string (result.symbol) : "NULL");
2239 return result;
2242 /* Check to see if the symbol is defined in BLOCK or its superiors.
2243 Don't search STATIC_BLOCK or GLOBAL_BLOCK. */
2245 static struct block_symbol
2246 lookup_local_symbol (const char *name,
2247 symbol_name_match_type match_type,
2248 const struct block *block,
2249 const domain_search_flags domain,
2250 const struct language_defn *langdef)
2252 if (block == nullptr)
2253 return {};
2255 const char *scope = block->scope ();
2257 while (!block->is_global_block () && !block->is_static_block ())
2259 struct symbol *sym = lookup_symbol_in_block (name, match_type,
2260 block, domain);
2261 if (sym != NULL)
2262 return (struct block_symbol) {sym, block};
2264 struct symbol *function = block->function ();
2265 if (function != nullptr && function->is_template_function ())
2267 struct template_symbol *templ = (struct template_symbol *) function;
2268 sym = search_symbol_list (name,
2269 templ->n_template_arguments,
2270 templ->template_arguments);
2271 if (sym != nullptr)
2272 return (struct block_symbol) {sym, block};
2275 struct block_symbol blocksym
2276 = langdef->lookup_symbol_local (scope, name, block, domain);
2277 if (blocksym.symbol != nullptr)
2278 return blocksym;
2280 if (block->inlined_p ())
2281 break;
2282 block = block->superblock ();
2285 /* We've reached the end of the function without finding a result. */
2287 return {};
2290 /* See symtab.h. */
2292 struct symbol *
2293 lookup_symbol_in_block (const char *name, symbol_name_match_type match_type,
2294 const struct block *block,
2295 const domain_search_flags domain)
2297 enter_symbol_lookup tmp;
2299 struct symbol *sym;
2301 if (symbol_lookup_debug)
2303 struct objfile *objfile
2304 = block == nullptr ? nullptr : block->objfile ();
2306 symbol_lookup_debug_printf_v
2307 ("lookup_symbol_in_block (%s, %s (objfile %s), %s)",
2308 name, host_address_to_string (block),
2309 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2310 domain_name (domain).c_str ());
2313 lookup_name_info lookup_name (name, match_type);
2314 sym = block_lookup_symbol (block, lookup_name, domain);
2315 if (sym)
2317 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = %s",
2318 host_address_to_string (sym));
2319 return sym;
2322 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = NULL");
2323 return NULL;
2326 /* See symtab.h. */
2328 struct block_symbol
2329 lookup_global_symbol_from_objfile (struct objfile *main_objfile,
2330 enum block_enum block_index,
2331 const char *name,
2332 const domain_search_flags domain)
2334 enter_symbol_lookup tmp;
2336 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2338 for (objfile *objfile : main_objfile->separate_debug_objfiles ())
2340 struct block_symbol result
2341 = lookup_symbol_in_objfile (objfile, block_index, name, domain);
2343 if (result.symbol != nullptr)
2344 return result;
2347 return {};
2350 /* Check to see if the symbol is defined in one of the OBJFILE's
2351 symtabs. BLOCK_INDEX should be either GLOBAL_BLOCK or STATIC_BLOCK,
2352 depending on whether or not we want to search global symbols or
2353 static symbols. */
2355 static struct block_symbol
2356 lookup_symbol_in_objfile_symtabs (struct objfile *objfile,
2357 enum block_enum block_index, const char *name,
2358 const domain_search_flags domain)
2360 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2362 symbol_lookup_debug_printf_v
2363 ("lookup_symbol_in_objfile_symtabs (%s, %s, %s, %s)",
2364 objfile_debug_name (objfile),
2365 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2366 name, domain_name (domain).c_str ());
2368 struct block_symbol other;
2369 other.symbol = NULL;
2370 for (compunit_symtab *cust : objfile->compunits ())
2372 const struct blockvector *bv;
2373 const struct block *block;
2374 struct block_symbol result;
2376 bv = cust->blockvector ();
2377 block = bv->block (block_index);
2378 result.symbol = block_lookup_symbol_primary (block, name, domain);
2379 result.block = block;
2380 if (result.symbol == NULL)
2381 continue;
2382 if (best_symbol (result.symbol, domain))
2384 other = result;
2385 break;
2387 if (result.symbol->matches (domain))
2389 struct symbol *better
2390 = better_symbol (other.symbol, result.symbol, domain);
2391 if (better != other.symbol)
2393 other.symbol = better;
2394 other.block = block;
2399 if (other.symbol != NULL)
2401 symbol_lookup_debug_printf_v
2402 ("lookup_symbol_in_objfile_symtabs (...) = %s (block %s)",
2403 host_address_to_string (other.symbol),
2404 host_address_to_string (other.block));
2405 return other;
2408 symbol_lookup_debug_printf_v
2409 ("lookup_symbol_in_objfile_symtabs (...) = NULL");
2410 return {};
2413 /* Wrapper around lookup_symbol_in_objfile_symtabs for search_symbols.
2414 Look up LINKAGE_NAME in DOMAIN in the global and static blocks of OBJFILE
2415 and all associated separate debug objfiles.
2417 Normally we only look in OBJFILE, and not any separate debug objfiles
2418 because the outer loop will cause them to be searched too. This case is
2419 different. Here we're called from search_symbols where it will only
2420 call us for the objfile that contains a matching minsym. */
2422 static struct block_symbol
2423 lookup_symbol_in_objfile_from_linkage_name (struct objfile *objfile,
2424 const char *linkage_name,
2425 domain_search_flags domain)
2427 enum language lang = current_language->la_language;
2428 struct objfile *main_objfile;
2430 demangle_result_storage storage;
2431 const char *modified_name = demangle_for_lookup (linkage_name, lang, storage);
2433 if (objfile->separate_debug_objfile_backlink)
2434 main_objfile = objfile->separate_debug_objfile_backlink;
2435 else
2436 main_objfile = objfile;
2438 for (::objfile *cur_objfile : main_objfile->separate_debug_objfiles ())
2440 struct block_symbol result;
2442 result = lookup_symbol_in_objfile_symtabs (cur_objfile, GLOBAL_BLOCK,
2443 modified_name, domain);
2444 if (result.symbol == NULL)
2445 result = lookup_symbol_in_objfile_symtabs (cur_objfile, STATIC_BLOCK,
2446 modified_name, domain);
2447 if (result.symbol != NULL)
2448 return result;
2451 return {};
2454 /* A helper function that throws an exception when a symbol was found
2455 in a psymtab but not in a symtab. */
2457 [[noreturn]] static void
2458 error_in_psymtab_expansion (enum block_enum block_index, const char *name,
2459 struct compunit_symtab *cust)
2461 error (_("\
2462 Internal: %s symbol `%s' found in %s psymtab but not in symtab.\n\
2463 %s may be an inlined function, or may be a template function\n \
2464 (if a template, try specifying an instantiation: %s<type>)."),
2465 block_index == GLOBAL_BLOCK ? "global" : "static",
2466 name,
2467 symtab_to_filename_for_display (cust->primary_filetab ()),
2468 name, name);
2471 /* A helper function for various lookup routines that interfaces with
2472 the "quick" symbol table functions. */
2474 static struct block_symbol
2475 lookup_symbol_via_quick_fns (struct objfile *objfile,
2476 enum block_enum block_index, const char *name,
2477 const domain_search_flags domain)
2479 struct compunit_symtab *cust;
2480 const struct blockvector *bv;
2481 const struct block *block;
2482 struct block_symbol result;
2484 symbol_lookup_debug_printf_v
2485 ("lookup_symbol_via_quick_fns (%s, %s, %s, %s)",
2486 objfile_debug_name (objfile),
2487 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2488 name, domain_name (domain).c_str ());
2490 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2491 cust = objfile->lookup_symbol (block_index, lookup_name, domain);
2492 if (cust == NULL)
2494 symbol_lookup_debug_printf_v
2495 ("lookup_symbol_via_quick_fns (...) = NULL");
2496 return {};
2499 bv = cust->blockvector ();
2500 block = bv->block (block_index);
2501 result.symbol = block_lookup_symbol (block, lookup_name, domain);
2502 if (result.symbol == NULL)
2503 error_in_psymtab_expansion (block_index, name, cust);
2505 symbol_lookup_debug_printf_v
2506 ("lookup_symbol_via_quick_fns (...) = %s (block %s)",
2507 host_address_to_string (result.symbol),
2508 host_address_to_string (block));
2510 result.block = block;
2511 return result;
2514 /* See language.h. */
2516 struct block_symbol
2517 language_defn::lookup_symbol_nonlocal (const char *name,
2518 const struct block *block,
2519 const domain_search_flags domain) const
2521 struct block_symbol result;
2523 /* NOTE: dje/2014-10-26: The lookup in all objfiles search could skip
2524 the current objfile. Searching the current objfile first is useful
2525 for both matching user expectations as well as performance. */
2527 result = lookup_symbol_in_static_block (name, block, domain);
2528 if (result.symbol != NULL)
2529 return result;
2531 /* If we didn't find a definition for a builtin type in the static block,
2532 search for it now. This is actually the right thing to do and can be
2533 a massive performance win. E.g., when debugging a program with lots of
2534 shared libraries we could search all of them only to find out the
2535 builtin type isn't defined in any of them. This is common for types
2536 like "void". */
2537 if ((domain & SEARCH_TYPE_DOMAIN) != 0)
2539 struct gdbarch *gdbarch;
2541 if (block == NULL)
2542 gdbarch = current_inferior ()->arch ();
2543 else
2544 gdbarch = block->gdbarch ();
2545 result.symbol = language_lookup_primitive_type_as_symbol (this,
2546 gdbarch, name);
2547 result.block = NULL;
2548 if (result.symbol != NULL)
2549 return result;
2552 return lookup_global_symbol (name, block, domain);
2555 /* See symtab.h. */
2557 struct block_symbol
2558 lookup_symbol_in_static_block (const char *name,
2559 const struct block *block,
2560 const domain_search_flags domain)
2562 if (block == nullptr)
2563 return {};
2565 const struct block *static_block = block->static_block ();
2566 struct symbol *sym;
2568 if (static_block == NULL)
2569 return {};
2571 if (symbol_lookup_debug)
2573 struct objfile *objfile = (block == nullptr
2574 ? nullptr : block->objfile ());
2576 symbol_lookup_debug_printf
2577 ("lookup_symbol_in_static_block (%s, %s (objfile %s), %s)",
2578 name, host_address_to_string (block),
2579 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2580 domain_name (domain).c_str ());
2583 sym = lookup_symbol_in_block (name,
2584 symbol_name_match_type::FULL,
2585 static_block, domain);
2586 symbol_lookup_debug_printf ("lookup_symbol_in_static_block (...) = %s",
2587 sym != NULL
2588 ? host_address_to_string (sym) : "NULL");
2589 return (struct block_symbol) {sym, static_block};
2592 /* Perform the standard symbol lookup of NAME in OBJFILE:
2593 1) First search expanded symtabs, and if not found
2594 2) Search the "quick" symtabs (partial or .gdb_index).
2595 BLOCK_INDEX is one of GLOBAL_BLOCK or STATIC_BLOCK. */
2597 static struct block_symbol
2598 lookup_symbol_in_objfile (struct objfile *objfile, enum block_enum block_index,
2599 const char *name, const domain_search_flags domain)
2601 struct block_symbol result;
2603 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2605 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (%s, %s, %s, %s)",
2606 objfile_debug_name (objfile),
2607 block_index == GLOBAL_BLOCK
2608 ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2609 name, domain_name (domain).c_str ());
2611 result = lookup_symbol_in_objfile_symtabs (objfile, block_index,
2612 name, domain);
2613 if (result.symbol != NULL)
2615 symbol_lookup_debug_printf
2616 ("lookup_symbol_in_objfile (...) = %s (in symtabs)",
2617 host_address_to_string (result.symbol));
2618 return result;
2621 result = lookup_symbol_via_quick_fns (objfile, block_index,
2622 name, domain);
2623 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (...) = %s%s",
2624 result.symbol != NULL
2625 ? host_address_to_string (result.symbol)
2626 : "NULL",
2627 result.symbol != NULL ? " (via quick fns)"
2628 : "");
2629 return result;
2632 /* This function contains the common code of lookup_{global,static}_symbol.
2633 OBJFILE is only used if BLOCK_INDEX is GLOBAL_SCOPE, in which case it is
2634 the objfile to start the lookup in. */
2636 static struct block_symbol
2637 lookup_global_or_static_symbol (const char *name,
2638 enum block_enum block_index,
2639 struct objfile *objfile,
2640 const domain_search_flags domain)
2642 struct symbol_cache *cache = get_symbol_cache (current_program_space);
2643 struct block_symbol result;
2644 struct block_symbol_cache *bsc;
2645 struct symbol_cache_slot *slot;
2647 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2648 gdb_assert (objfile == nullptr || block_index == GLOBAL_BLOCK);
2650 /* First see if we can find the symbol in the cache.
2651 This works because we use the current objfile to qualify the lookup. */
2652 result = symbol_cache_lookup (cache, objfile, block_index, name, domain,
2653 &bsc, &slot);
2654 if (result.symbol != NULL)
2656 if (SYMBOL_LOOKUP_FAILED_P (result))
2657 return {};
2658 return result;
2661 enter_symbol_lookup tmp;
2663 /* Do a global search (of global blocks, heh). */
2664 if (result.symbol == NULL)
2665 gdbarch_iterate_over_objfiles_in_search_order
2666 (objfile != NULL ? objfile->arch () : current_inferior ()->arch (),
2667 [&result, block_index, name, domain] (struct objfile *objfile_iter)
2669 result = lookup_symbol_in_objfile (objfile_iter, block_index,
2670 name, domain);
2671 return result.symbol != nullptr;
2673 objfile);
2675 if (result.symbol != NULL)
2676 symbol_cache_mark_found (bsc, slot, objfile, result.symbol, result.block,
2677 domain);
2678 else
2679 symbol_cache_mark_not_found (bsc, slot, objfile, name, domain);
2681 return result;
2684 /* See symtab.h. */
2686 struct block_symbol
2687 lookup_static_symbol (const char *name, const domain_search_flags domain)
2689 return lookup_global_or_static_symbol (name, STATIC_BLOCK, nullptr, domain);
2692 /* See symtab.h. */
2694 struct block_symbol
2695 lookup_global_symbol (const char *name,
2696 const struct block *block,
2697 const domain_search_flags domain)
2699 /* If a block was passed in, we want to search the corresponding
2700 global block first. This yields "more expected" behavior, and is
2701 needed to support 'FILENAME'::VARIABLE lookups. */
2702 const struct block *global_block
2703 = block == nullptr ? nullptr : block->global_block ();
2704 symbol *sym = NULL;
2705 if (global_block != nullptr)
2707 sym = lookup_symbol_in_block (name,
2708 symbol_name_match_type::FULL,
2709 global_block, domain);
2710 if (sym != NULL && best_symbol (sym, domain))
2711 return { sym, global_block };
2714 struct objfile *objfile = nullptr;
2715 if (block != nullptr)
2717 objfile = block->objfile ();
2718 if (objfile->separate_debug_objfile_backlink != nullptr)
2719 objfile = objfile->separate_debug_objfile_backlink;
2722 block_symbol bs
2723 = lookup_global_or_static_symbol (name, GLOBAL_BLOCK, objfile, domain);
2724 if (better_symbol (sym, bs.symbol, domain) == sym)
2725 return { sym, global_block };
2726 else
2727 return bs;
2730 /* See symtab.h. */
2732 bool
2733 symbol::matches (domain_search_flags flags) const
2735 /* C++ has a typedef for every tag, and the types are in the struct
2736 domain. */
2737 if (language () == language_cplus && (flags & SEARCH_TYPE_DOMAIN) != 0)
2738 flags |= SEARCH_STRUCT_DOMAIN;
2740 return search_flags_matches (flags, m_domain);
2743 /* See symtab.h. */
2745 struct type *
2746 lookup_transparent_type (const char *name, domain_search_flags flags)
2748 return current_language->lookup_transparent_type (name, flags);
2751 /* A helper for basic_lookup_transparent_type that interfaces with the
2752 "quick" symbol table functions. */
2754 static struct type *
2755 basic_lookup_transparent_type_quick (struct objfile *objfile,
2756 enum block_enum block_index,
2757 domain_search_flags flags,
2758 const lookup_name_info &name)
2760 struct compunit_symtab *cust;
2761 const struct blockvector *bv;
2762 const struct block *block;
2763 struct symbol *sym;
2765 cust = objfile->lookup_symbol (block_index, name, flags);
2766 if (cust == NULL)
2767 return NULL;
2769 bv = cust->blockvector ();
2770 block = bv->block (block_index);
2772 sym = block_find_symbol (block, name, flags, nullptr);
2773 if (sym == nullptr)
2774 error_in_psymtab_expansion (block_index, name.c_str (), cust);
2775 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2776 return sym->type ();
2779 /* Subroutine of basic_lookup_transparent_type to simplify it.
2780 Look up the non-opaque definition of NAME in BLOCK_INDEX of OBJFILE.
2781 BLOCK_INDEX is either GLOBAL_BLOCK or STATIC_BLOCK. */
2783 static struct type *
2784 basic_lookup_transparent_type_1 (struct objfile *objfile,
2785 enum block_enum block_index,
2786 domain_search_flags flags,
2787 const lookup_name_info &name)
2789 const struct blockvector *bv;
2790 const struct block *block;
2791 const struct symbol *sym;
2793 for (compunit_symtab *cust : objfile->compunits ())
2795 bv = cust->blockvector ();
2796 block = bv->block (block_index);
2797 sym = block_find_symbol (block, name, flags, nullptr);
2798 if (sym != nullptr)
2800 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2801 return sym->type ();
2805 return NULL;
2808 /* The standard implementation of lookup_transparent_type. This code
2809 was modeled on lookup_symbol -- the parts not relevant to looking
2810 up types were just left out. In particular it's assumed here that
2811 types are available in STRUCT_DOMAIN and only in file-static or
2812 global blocks. */
2814 struct type *
2815 basic_lookup_transparent_type (const char *name, domain_search_flags flags)
2817 struct type *t;
2819 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
2821 /* Now search all the global symbols. Do the symtab's first, then
2822 check the psymtab's. If a psymtab indicates the existence
2823 of the desired name as a global, then do psymtab-to-symtab
2824 conversion on the fly and return the found symbol. */
2826 for (objfile *objfile : current_program_space->objfiles ())
2828 t = basic_lookup_transparent_type_1 (objfile, GLOBAL_BLOCK,
2829 flags, lookup_name);
2830 if (t)
2831 return t;
2834 for (objfile *objfile : current_program_space->objfiles ())
2836 t = basic_lookup_transparent_type_quick (objfile, GLOBAL_BLOCK,
2837 flags, lookup_name);
2838 if (t)
2839 return t;
2842 /* Now search the static file-level symbols.
2843 Not strictly correct, but more useful than an error.
2844 Do the symtab's first, then
2845 check the psymtab's. If a psymtab indicates the existence
2846 of the desired name as a file-level static, then do psymtab-to-symtab
2847 conversion on the fly and return the found symbol. */
2849 for (objfile *objfile : current_program_space->objfiles ())
2851 t = basic_lookup_transparent_type_1 (objfile, STATIC_BLOCK,
2852 flags, lookup_name);
2853 if (t)
2854 return t;
2857 for (objfile *objfile : current_program_space->objfiles ())
2859 t = basic_lookup_transparent_type_quick (objfile, STATIC_BLOCK,
2860 flags, lookup_name);
2861 if (t)
2862 return t;
2865 return (struct type *) 0;
2868 /* See symtab.h. */
2870 bool
2871 iterate_over_symbols (const struct block *block,
2872 const lookup_name_info &name,
2873 const domain_search_flags domain,
2874 gdb::function_view<symbol_found_callback_ftype> callback)
2876 for (struct symbol *sym : block_iterator_range (block, &name))
2878 if (sym->matches (domain))
2880 struct block_symbol block_sym = {sym, block};
2882 if (!callback (&block_sym))
2883 return false;
2886 return true;
2889 /* See symtab.h. */
2891 bool
2892 iterate_over_symbols_terminated
2893 (const struct block *block,
2894 const lookup_name_info &name,
2895 const domain_search_flags domain,
2896 gdb::function_view<symbol_found_callback_ftype> callback)
2898 if (!iterate_over_symbols (block, name, domain, callback))
2899 return false;
2900 struct block_symbol block_sym = {nullptr, block};
2901 return callback (&block_sym);
2904 /* Find the compunit symtab associated with PC and SECTION.
2905 This will read in debug info as necessary. */
2907 struct compunit_symtab *
2908 find_pc_sect_compunit_symtab (CORE_ADDR pc, struct obj_section *section)
2910 struct compunit_symtab *best_cust = NULL;
2911 CORE_ADDR best_cust_range = 0;
2913 /* If we know that this is not a text address, return failure. This is
2914 necessary because we loop based on the block's high and low code
2915 addresses, which do not include the data ranges, and because
2916 we call find_pc_sect_psymtab which has a similar restriction based
2917 on the partial_symtab's texthigh and textlow. */
2918 bound_minimal_symbol msymbol
2919 = lookup_minimal_symbol_by_pc_section (pc, section);
2920 if (msymbol.minsym && msymbol.minsym->data_p ())
2921 return NULL;
2923 /* Search all symtabs for the one whose file contains our address, and which
2924 is the smallest of all the ones containing the address. This is designed
2925 to deal with a case like symtab a is at 0x1000-0x2000 and 0x3000-0x4000
2926 and symtab b is at 0x2000-0x3000. So the GLOBAL_BLOCK for a is from
2927 0x1000-0x4000, but for address 0x2345 we want to return symtab b.
2929 This happens for native ecoff format, where code from included files
2930 gets its own symtab. The symtab for the included file should have
2931 been read in already via the dependency mechanism.
2932 It might be swifter to create several symtabs with the same name
2933 like xcoff does (I'm not sure).
2935 It also happens for objfiles that have their functions reordered.
2936 For these, the symtab we are looking for is not necessarily read in. */
2938 for (objfile *obj_file : current_program_space->objfiles ())
2940 for (compunit_symtab *cust : obj_file->compunits ())
2942 const struct blockvector *bv = cust->blockvector ();
2943 const struct block *global_block = bv->global_block ();
2944 CORE_ADDR start = global_block->start ();
2945 CORE_ADDR end = global_block->end ();
2946 bool in_range_p = start <= pc && pc < end;
2947 if (!in_range_p)
2948 continue;
2950 if (bv->map () != nullptr)
2952 if (bv->map ()->find (pc) == nullptr)
2953 continue;
2955 return cust;
2958 CORE_ADDR range = end - start;
2959 if (best_cust != nullptr
2960 && range >= best_cust_range)
2961 /* Cust doesn't have a smaller range than best_cust, skip it. */
2962 continue;
2964 /* For an objfile that has its functions reordered,
2965 find_pc_psymtab will find the proper partial symbol table
2966 and we simply return its corresponding symtab. */
2967 /* In order to better support objfiles that contain both
2968 stabs and coff debugging info, we continue on if a psymtab
2969 can't be found. */
2970 struct compunit_symtab *result
2971 = obj_file->find_pc_sect_compunit_symtab (msymbol, pc,
2972 section, 0);
2973 if (result != nullptr)
2974 return result;
2976 if (section != 0)
2978 struct symbol *found_sym = nullptr;
2980 for (int b_index = GLOBAL_BLOCK;
2981 b_index <= STATIC_BLOCK && found_sym == nullptr;
2982 ++b_index)
2984 const struct block *b = bv->block (b_index);
2985 for (struct symbol *sym : block_iterator_range (b))
2987 if (matching_obj_sections (sym->obj_section (obj_file),
2988 section))
2990 found_sym = sym;
2991 break;
2995 if (found_sym == nullptr)
2996 continue; /* No symbol in this symtab matches
2997 section. */
3000 /* Cust is best found so far, save it. */
3001 best_cust = cust;
3002 best_cust_range = range;
3006 if (best_cust != NULL)
3007 return best_cust;
3009 /* Not found in symtabs, search the "quick" symtabs (e.g. psymtabs). */
3011 for (objfile *objf : current_program_space->objfiles ())
3013 struct compunit_symtab *result
3014 = objf->find_pc_sect_compunit_symtab (msymbol, pc, section, 1);
3015 if (result != NULL)
3016 return result;
3019 return NULL;
3022 /* Find the compunit symtab associated with PC.
3023 This will read in debug info as necessary.
3024 Backward compatibility, no section. */
3026 struct compunit_symtab *
3027 find_pc_compunit_symtab (CORE_ADDR pc)
3029 return find_pc_sect_compunit_symtab (pc, find_pc_mapped_section (pc));
3032 /* See symtab.h. */
3034 struct symbol *
3035 find_symbol_at_address (CORE_ADDR address)
3037 /* A helper function to search a given symtab for a symbol matching
3038 ADDR. */
3039 auto search_symtab = [] (compunit_symtab *symtab, CORE_ADDR addr) -> symbol *
3041 const struct blockvector *bv = symtab->blockvector ();
3043 for (int i = GLOBAL_BLOCK; i <= STATIC_BLOCK; ++i)
3045 const struct block *b = bv->block (i);
3047 for (struct symbol *sym : block_iterator_range (b))
3049 if (sym->aclass () == LOC_STATIC
3050 && sym->value_address () == addr)
3051 return sym;
3054 return nullptr;
3057 for (objfile *objfile : current_program_space->objfiles ())
3059 /* If this objfile was read with -readnow, then we need to
3060 search the symtabs directly. */
3061 if ((objfile->flags & OBJF_READNOW) != 0)
3063 for (compunit_symtab *symtab : objfile->compunits ())
3065 struct symbol *sym = search_symtab (symtab, address);
3066 if (sym != nullptr)
3067 return sym;
3070 else
3072 struct compunit_symtab *symtab
3073 = objfile->find_compunit_symtab_by_address (address);
3074 if (symtab != NULL)
3076 struct symbol *sym = search_symtab (symtab, address);
3077 if (sym != nullptr)
3078 return sym;
3083 return NULL;
3088 /* Find the source file and line number for a given PC value and SECTION.
3089 Return a structure containing a symtab pointer, a line number,
3090 and a pc range for the entire source line.
3091 The value's .pc field is NOT the specified pc.
3092 NOTCURRENT nonzero means, if specified pc is on a line boundary,
3093 use the line that ends there. Otherwise, in that case, the line
3094 that begins there is used. */
3096 /* The big complication here is that a line may start in one file, and end just
3097 before the start of another file. This usually occurs when you #include
3098 code in the middle of a subroutine. To properly find the end of a line's PC
3099 range, we must search all symtabs associated with this compilation unit, and
3100 find the one whose first PC is closer than that of the next line in this
3101 symtab. */
3103 struct symtab_and_line
3104 find_pc_sect_line (CORE_ADDR pc, struct obj_section *section, int notcurrent)
3106 struct compunit_symtab *cust;
3107 const linetable *l;
3108 int len;
3109 const linetable_entry *item;
3110 const struct blockvector *bv;
3112 /* Info on best line seen so far, and where it starts, and its file. */
3114 const linetable_entry *best = NULL;
3115 CORE_ADDR best_end = 0;
3116 struct symtab *best_symtab = 0;
3118 /* Store here the first line number
3119 of a file which contains the line at the smallest pc after PC.
3120 If we don't find a line whose range contains PC,
3121 we will use a line one less than this,
3122 with a range from the start of that file to the first line's pc. */
3123 const linetable_entry *alt = NULL;
3125 /* Info on best line seen in this file. */
3127 const linetable_entry *prev;
3129 /* If this pc is not from the current frame,
3130 it is the address of the end of a call instruction.
3131 Quite likely that is the start of the following statement.
3132 But what we want is the statement containing the instruction.
3133 Fudge the pc to make sure we get that. */
3135 /* It's tempting to assume that, if we can't find debugging info for
3136 any function enclosing PC, that we shouldn't search for line
3137 number info, either. However, GAS can emit line number info for
3138 assembly files --- very helpful when debugging hand-written
3139 assembly code. In such a case, we'd have no debug info for the
3140 function, but we would have line info. */
3142 if (notcurrent)
3143 pc -= 1;
3145 /* elz: added this because this function returned the wrong
3146 information if the pc belongs to a stub (import/export)
3147 to call a shlib function. This stub would be anywhere between
3148 two functions in the target, and the line info was erroneously
3149 taken to be the one of the line before the pc. */
3151 /* RT: Further explanation:
3153 * We have stubs (trampolines) inserted between procedures.
3155 * Example: "shr1" exists in a shared library, and a "shr1" stub also
3156 * exists in the main image.
3158 * In the minimal symbol table, we have a bunch of symbols
3159 * sorted by start address. The stubs are marked as "trampoline",
3160 * the others appear as text. E.g.:
3162 * Minimal symbol table for main image
3163 * main: code for main (text symbol)
3164 * shr1: stub (trampoline symbol)
3165 * foo: code for foo (text symbol)
3166 * ...
3167 * Minimal symbol table for "shr1" image:
3168 * ...
3169 * shr1: code for shr1 (text symbol)
3170 * ...
3172 * So the code below is trying to detect if we are in the stub
3173 * ("shr1" stub), and if so, find the real code ("shr1" trampoline),
3174 * and if found, do the symbolization from the real-code address
3175 * rather than the stub address.
3177 * Assumptions being made about the minimal symbol table:
3178 * 1. lookup_minimal_symbol_by_pc() will return a trampoline only
3179 * if we're really in the trampoline.s If we're beyond it (say
3180 * we're in "foo" in the above example), it'll have a closer
3181 * symbol (the "foo" text symbol for example) and will not
3182 * return the trampoline.
3183 * 2. lookup_minimal_symbol_text() will find a real text symbol
3184 * corresponding to the trampoline, and whose address will
3185 * be different than the trampoline address. I put in a sanity
3186 * check for the address being the same, to avoid an
3187 * infinite recursion.
3189 bound_minimal_symbol msymbol = lookup_minimal_symbol_by_pc (pc);
3190 if (msymbol.minsym != NULL)
3191 if (msymbol.minsym->type () == mst_solib_trampoline)
3193 bound_minimal_symbol mfunsym
3194 = lookup_minimal_symbol_text (current_program_space,
3195 msymbol.minsym->linkage_name (),
3196 nullptr);
3198 if (mfunsym.minsym == NULL)
3199 /* I eliminated this warning since it is coming out
3200 * in the following situation:
3201 * gdb shmain // test program with shared libraries
3202 * (gdb) break shr1 // function in shared lib
3203 * Warning: In stub for ...
3204 * In the above situation, the shared lib is not loaded yet,
3205 * so of course we can't find the real func/line info,
3206 * but the "break" still works, and the warning is annoying.
3207 * So I commented out the warning. RT */
3208 /* warning ("In stub for %s; unable to find real function/line info",
3209 msymbol->linkage_name ()); */
3211 /* fall through */
3212 else if (mfunsym.value_address ()
3213 == msymbol.value_address ())
3214 /* Avoid infinite recursion */
3215 /* See above comment about why warning is commented out. */
3216 /* warning ("In stub for %s; unable to find real function/line info",
3217 msymbol->linkage_name ()); */
3219 /* fall through */
3220 else
3222 /* Detect an obvious case of infinite recursion. If this
3223 should occur, we'd like to know about it, so error out,
3224 fatally. */
3225 if (mfunsym.value_address () == pc)
3226 internal_error (_("Infinite recursion detected in find_pc_sect_line;"
3227 "please file a bug report"));
3229 return find_pc_line (mfunsym.value_address (), 0);
3233 symtab_and_line val;
3234 val.pspace = current_program_space;
3236 cust = find_pc_sect_compunit_symtab (pc, section);
3237 if (cust == NULL)
3239 /* If no symbol information, return previous pc. */
3240 if (notcurrent)
3241 pc++;
3242 val.pc = pc;
3243 return val;
3246 bv = cust->blockvector ();
3247 struct objfile *objfile = cust->objfile ();
3249 /* Look at all the symtabs that share this blockvector.
3250 They all have the same apriori range, that we found was right;
3251 but they have different line tables. */
3253 for (symtab *iter_s : cust->filetabs ())
3255 /* Find the best line in this symtab. */
3256 l = iter_s->linetable ();
3257 if (!l)
3258 continue;
3259 len = l->nitems;
3260 if (len <= 0)
3262 /* I think len can be zero if the symtab lacks line numbers
3263 (e.g. gcc -g1). (Either that or the LINETABLE is NULL;
3264 I'm not sure which, and maybe it depends on the symbol
3265 reader). */
3266 continue;
3269 prev = NULL;
3270 item = l->item; /* Get first line info. */
3272 /* Is this file's first line closer than the first lines of other files?
3273 If so, record this file, and its first line, as best alternate. */
3274 if (item->pc (objfile) > pc
3275 && (!alt || item->unrelocated_pc () < alt->unrelocated_pc ()))
3276 alt = item;
3278 auto pc_compare = [] (const unrelocated_addr &comp_pc,
3279 const struct linetable_entry & lhs)
3281 return comp_pc < lhs.unrelocated_pc ();
3284 const linetable_entry *first = item;
3285 const linetable_entry *last = item + len;
3286 item = (std::upper_bound
3287 (first, last,
3288 unrelocated_addr (pc - objfile->text_section_offset ()),
3289 pc_compare));
3290 if (item != first)
3292 prev = item - 1; /* Found a matching item. */
3293 /* At this point, prev is a line whose address is <= pc. However, we
3294 don't know if ITEM is pointing to the same statement or not. */
3295 while (item != last && prev->line == item->line && !item->is_stmt)
3296 item++;
3299 /* At this point, prev points at the line whose start addr is <= pc, and
3300 item points at the next statement. If we ran off the end of the linetable
3301 (pc >= start of the last line), then prev == item. If pc < start of
3302 the first line, prev will not be set. */
3304 /* Is this file's best line closer than the best in the other files?
3305 If so, record this file, and its best line, as best so far. Don't
3306 save prev if it represents the end of a function (i.e. line number
3307 0) instead of a real line. */
3309 if (prev && prev->line
3310 && (!best || prev->unrelocated_pc () > best->unrelocated_pc ()))
3312 best = prev;
3313 best_symtab = iter_s;
3315 /* If during the binary search we land on a non-statement entry,
3316 scan backward through entries at the same address to see if
3317 there is an entry marked as is-statement. In theory this
3318 duplication should have been removed from the line table
3319 during construction, this is just a double check. If the line
3320 table has had the duplication removed then this should be
3321 pretty cheap. */
3322 if (!best->is_stmt)
3324 const linetable_entry *tmp = best;
3325 while (tmp > first
3326 && (tmp - 1)->unrelocated_pc () == tmp->unrelocated_pc ()
3327 && (tmp - 1)->line != 0 && !tmp->is_stmt)
3328 --tmp;
3329 if (tmp->is_stmt)
3330 best = tmp;
3333 /* Discard BEST_END if it's before the PC of the current BEST. */
3334 if (best_end <= best->pc (objfile))
3335 best_end = 0;
3338 /* If another line (denoted by ITEM) is in the linetable and its
3339 PC is after BEST's PC, but before the current BEST_END, then
3340 use ITEM's PC as the new best_end. */
3341 if (best && item < last
3342 && item->unrelocated_pc () > best->unrelocated_pc ()
3343 && (best_end == 0 || best_end > item->pc (objfile)))
3344 best_end = item->pc (objfile);
3347 if (!best_symtab)
3349 /* If we didn't find any line number info, just return zeros.
3350 We used to return alt->line - 1 here, but that could be
3351 anywhere; if we don't have line number info for this PC,
3352 don't make some up. */
3353 val.pc = pc;
3355 else if (best->line == 0)
3357 /* If our best fit is in a range of PC's for which no line
3358 number info is available (line number is zero) then we didn't
3359 find any valid line information. */
3360 val.pc = pc;
3362 else
3364 val.is_stmt = best->is_stmt;
3365 val.symtab = best_symtab;
3366 val.line = best->line;
3367 val.pc = best->pc (objfile);
3368 if (best_end && (!alt || best_end < alt->pc (objfile)))
3369 val.end = best_end;
3370 else if (alt)
3371 val.end = alt->pc (objfile);
3372 else
3373 val.end = bv->global_block ()->end ();
3375 val.section = section;
3376 return val;
3379 /* Backward compatibility (no section). */
3381 struct symtab_and_line
3382 find_pc_line (CORE_ADDR pc, int notcurrent)
3384 struct obj_section *section;
3386 section = find_pc_overlay (pc);
3387 if (!pc_in_unmapped_range (pc, section))
3388 return find_pc_sect_line (pc, section, notcurrent);
3390 /* If the original PC was an unmapped address then we translate this to a
3391 mapped address in order to lookup the sal. However, as the user
3392 passed us an unmapped address it makes more sense to return a result
3393 that has the pc and end fields translated to unmapped addresses. */
3394 pc = overlay_mapped_address (pc, section);
3395 symtab_and_line sal = find_pc_sect_line (pc, section, notcurrent);
3396 sal.pc = overlay_unmapped_address (sal.pc, section);
3397 sal.end = overlay_unmapped_address (sal.end, section);
3398 return sal;
3401 /* Compare two symtab_and_line entries. Return true if both have
3402 the same line number and the same symtab pointer. That means we
3403 are dealing with two entries from the same line and from the same
3404 source file.
3406 Return false otherwise. */
3408 static bool
3409 sal_line_symtab_matches_p (const symtab_and_line &sal1,
3410 const symtab_and_line &sal2)
3412 return sal1.line == sal2.line && sal1.symtab == sal2.symtab;
3415 /* See symtah.h. */
3417 std::optional<CORE_ADDR>
3418 find_line_range_start (CORE_ADDR pc)
3420 struct symtab_and_line current_sal = find_pc_line (pc, 0);
3422 if (current_sal.line == 0)
3423 return {};
3425 struct symtab_and_line prev_sal = find_pc_line (current_sal.pc - 1, 0);
3427 /* If the previous entry is for a different line, that means we are already
3428 at the entry with the start PC for this line. */
3429 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3430 return current_sal.pc;
3432 /* Otherwise, keep looking for entries for the same line but with
3433 smaller PC's. */
3434 bool done = false;
3435 CORE_ADDR prev_pc;
3436 while (!done)
3438 prev_pc = prev_sal.pc;
3440 prev_sal = find_pc_line (prev_pc - 1, 0);
3442 /* Did we notice a line change? If so, we are done searching. */
3443 if (!sal_line_symtab_matches_p (prev_sal, current_sal))
3444 done = true;
3447 return prev_pc;
3450 /* See symtab.h. */
3452 struct symtab *
3453 find_pc_line_symtab (CORE_ADDR pc)
3455 struct symtab_and_line sal;
3457 /* This always passes zero for NOTCURRENT to find_pc_line.
3458 There are currently no callers that ever pass non-zero. */
3459 sal = find_pc_line (pc, 0);
3460 return sal.symtab;
3463 /* See symtab.h. */
3465 symtab *
3466 find_line_symtab (symtab *sym_tab, int line, int *index)
3468 int exact = 0; /* Initialized here to avoid a compiler warning. */
3470 /* BEST_INDEX and BEST_LINETABLE identify the smallest linenumber > LINE
3471 so far seen. */
3473 int best_index;
3474 const struct linetable *best_linetable;
3475 struct symtab *best_symtab;
3477 /* First try looking it up in the given symtab. */
3478 best_linetable = sym_tab->linetable ();
3479 best_symtab = sym_tab;
3480 best_index = find_line_common (best_linetable, line, &exact, 0);
3481 if (best_index < 0 || !exact)
3483 /* Didn't find an exact match. So we better keep looking for
3484 another symtab with the same name. In the case of xcoff,
3485 multiple csects for one source file (produced by IBM's FORTRAN
3486 compiler) produce multiple symtabs (this is unavoidable
3487 assuming csects can be at arbitrary places in memory and that
3488 the GLOBAL_BLOCK of a symtab has a begin and end address). */
3490 /* BEST is the smallest linenumber > LINE so far seen,
3491 or 0 if none has been seen so far.
3492 BEST_INDEX and BEST_LINETABLE identify the item for it. */
3493 int best;
3495 if (best_index >= 0)
3496 best = best_linetable->item[best_index].line;
3497 else
3498 best = 0;
3500 for (objfile *objfile : current_program_space->objfiles ())
3501 objfile->expand_symtabs_with_fullname (symtab_to_fullname (sym_tab));
3503 for (objfile *objfile : current_program_space->objfiles ())
3505 for (compunit_symtab *cu : objfile->compunits ())
3507 for (symtab *s : cu->filetabs ())
3509 const struct linetable *l;
3510 int ind;
3512 if (FILENAME_CMP (sym_tab->filename, s->filename) != 0)
3513 continue;
3514 if (FILENAME_CMP (symtab_to_fullname (sym_tab),
3515 symtab_to_fullname (s)) != 0)
3516 continue;
3517 l = s->linetable ();
3518 ind = find_line_common (l, line, &exact, 0);
3519 if (ind >= 0)
3521 if (exact)
3523 best_index = ind;
3524 best_linetable = l;
3525 best_symtab = s;
3526 goto done;
3528 if (best == 0 || l->item[ind].line < best)
3530 best = l->item[ind].line;
3531 best_index = ind;
3532 best_linetable = l;
3533 best_symtab = s;
3540 done:
3541 if (best_index < 0)
3542 return NULL;
3544 if (index)
3545 *index = best_index;
3547 return best_symtab;
3550 /* Given SYMTAB, returns all the PCs function in the symtab that
3551 exactly match LINE. Returns an empty vector if there are no exact
3552 matches, but updates BEST_ITEM in this case. */
3554 std::vector<CORE_ADDR>
3555 find_pcs_for_symtab_line (struct symtab *symtab, int line,
3556 const linetable_entry **best_item)
3558 int start = 0;
3559 std::vector<CORE_ADDR> result;
3560 struct objfile *objfile = symtab->compunit ()->objfile ();
3562 /* First, collect all the PCs that are at this line. */
3563 while (1)
3565 int was_exact;
3566 int idx;
3568 idx = find_line_common (symtab->linetable (), line, &was_exact,
3569 start);
3570 if (idx < 0)
3571 break;
3573 if (!was_exact)
3575 const linetable_entry *item = &symtab->linetable ()->item[idx];
3577 if (*best_item == NULL
3578 || (item->line < (*best_item)->line && item->is_stmt))
3579 *best_item = item;
3581 break;
3584 result.push_back (symtab->linetable ()->item[idx].pc (objfile));
3585 start = idx + 1;
3588 return result;
3592 /* Set the PC value for a given source file and line number and return true.
3593 Returns false for invalid line number (and sets the PC to 0).
3594 The source file is specified with a struct symtab. */
3596 bool
3597 find_line_pc (struct symtab *symtab, int line, CORE_ADDR *pc)
3599 const struct linetable *l;
3600 int ind;
3602 *pc = 0;
3603 if (symtab == 0)
3604 return false;
3606 symtab = find_line_symtab (symtab, line, &ind);
3607 if (symtab != NULL)
3609 l = symtab->linetable ();
3610 *pc = l->item[ind].pc (symtab->compunit ()->objfile ());
3611 return true;
3613 else
3614 return false;
3617 /* Find the range of pc values in a line.
3618 Store the starting pc of the line into *STARTPTR
3619 and the ending pc (start of next line) into *ENDPTR.
3620 Returns true to indicate success.
3621 Returns false if could not find the specified line. */
3623 bool
3624 find_line_pc_range (struct symtab_and_line sal, CORE_ADDR *startptr,
3625 CORE_ADDR *endptr)
3627 CORE_ADDR startaddr;
3628 struct symtab_and_line found_sal;
3630 startaddr = sal.pc;
3631 if (startaddr == 0 && !find_line_pc (sal.symtab, sal.line, &startaddr))
3632 return false;
3634 /* This whole function is based on address. For example, if line 10 has
3635 two parts, one from 0x100 to 0x200 and one from 0x300 to 0x400, then
3636 "info line *0x123" should say the line goes from 0x100 to 0x200
3637 and "info line *0x355" should say the line goes from 0x300 to 0x400.
3638 This also insures that we never give a range like "starts at 0x134
3639 and ends at 0x12c". */
3641 found_sal = find_pc_sect_line (startaddr, sal.section, 0);
3642 if (found_sal.line != sal.line)
3644 /* The specified line (sal) has zero bytes. */
3645 *startptr = found_sal.pc;
3646 *endptr = found_sal.pc;
3648 else
3650 *startptr = found_sal.pc;
3651 *endptr = found_sal.end;
3653 return true;
3656 /* Given a line table and a line number, return the index into the line
3657 table for the pc of the nearest line whose number is >= the specified one.
3658 Return -1 if none is found. The value is >= 0 if it is an index.
3659 START is the index at which to start searching the line table.
3661 Set *EXACT_MATCH nonzero if the value returned is an exact match. */
3663 static int
3664 find_line_common (const linetable *l, int lineno,
3665 int *exact_match, int start)
3667 int i;
3668 int len;
3670 /* BEST is the smallest linenumber > LINENO so far seen,
3671 or 0 if none has been seen so far.
3672 BEST_INDEX identifies the item for it. */
3674 int best_index = -1;
3675 int best = 0;
3677 *exact_match = 0;
3679 if (lineno <= 0)
3680 return -1;
3681 if (l == 0)
3682 return -1;
3684 len = l->nitems;
3685 for (i = start; i < len; i++)
3687 const linetable_entry *item = &(l->item[i]);
3689 /* Ignore non-statements. */
3690 if (!item->is_stmt)
3691 continue;
3693 if (item->line == lineno)
3695 /* Return the first (lowest address) entry which matches. */
3696 *exact_match = 1;
3697 return i;
3700 if (item->line > lineno && (best == 0 || item->line < best))
3702 best = item->line;
3703 best_index = i;
3707 /* If we got here, we didn't get an exact match. */
3708 return best_index;
3711 bool
3712 find_pc_line_pc_range (CORE_ADDR pc, CORE_ADDR *startptr, CORE_ADDR *endptr)
3714 struct symtab_and_line sal;
3716 sal = find_pc_line (pc, 0);
3717 *startptr = sal.pc;
3718 *endptr = sal.end;
3719 return sal.symtab != 0;
3722 /* Helper for find_function_start_sal. Does most of the work, except
3723 setting the sal's symbol. */
3725 static symtab_and_line
3726 find_function_start_sal_1 (CORE_ADDR func_addr, obj_section *section,
3727 bool funfirstline)
3729 symtab_and_line sal = find_pc_sect_line (func_addr, section, 0);
3731 if (funfirstline && sal.symtab != NULL
3732 && (sal.symtab->compunit ()->locations_valid ()
3733 || sal.symtab->language () == language_asm))
3735 struct gdbarch *gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
3737 sal.pc = func_addr;
3738 if (gdbarch_skip_entrypoint_p (gdbarch))
3739 sal.pc = gdbarch_skip_entrypoint (gdbarch, sal.pc);
3740 return sal;
3743 /* We always should have a line for the function start address.
3744 If we don't, something is odd. Create a plain SAL referring
3745 just the PC and hope that skip_prologue_sal (if requested)
3746 can find a line number for after the prologue. */
3747 if (sal.pc < func_addr)
3749 sal = {};
3750 sal.pspace = current_program_space;
3751 sal.pc = func_addr;
3752 sal.section = section;
3755 if (funfirstline)
3756 skip_prologue_sal (&sal);
3758 return sal;
3761 /* See symtab.h. */
3763 symtab_and_line
3764 find_function_start_sal (CORE_ADDR func_addr, obj_section *section,
3765 bool funfirstline)
3767 symtab_and_line sal
3768 = find_function_start_sal_1 (func_addr, section, funfirstline);
3770 /* find_function_start_sal_1 does a linetable search, so it finds
3771 the symtab and linenumber, but not a symbol. Fill in the
3772 function symbol too. */
3773 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
3775 return sal;
3778 /* See symtab.h. */
3780 symtab_and_line
3781 find_function_start_sal (symbol *sym, bool funfirstline)
3783 symtab_and_line sal
3784 = find_function_start_sal_1 (sym->value_block ()->entry_pc (),
3785 sym->obj_section (sym->objfile ()),
3786 funfirstline);
3787 sal.symbol = sym;
3788 return sal;
3792 /* Given a function start address FUNC_ADDR and SYMTAB, find the first
3793 address for that function that has an entry in SYMTAB's line info
3794 table. If such an entry cannot be found, return FUNC_ADDR
3795 unaltered. */
3797 static CORE_ADDR
3798 skip_prologue_using_lineinfo (CORE_ADDR func_addr, struct symtab *symtab)
3800 CORE_ADDR func_start, func_end;
3801 const struct linetable *l;
3802 int i;
3804 /* Give up if this symbol has no lineinfo table. */
3805 l = symtab->linetable ();
3806 if (l == NULL)
3807 return func_addr;
3809 /* Get the range for the function's PC values, or give up if we
3810 cannot, for some reason. */
3811 if (!find_pc_partial_function (func_addr, NULL, &func_start, &func_end))
3812 return func_addr;
3814 struct objfile *objfile = symtab->compunit ()->objfile ();
3816 /* Linetable entries are ordered by PC values, see the commentary in
3817 symtab.h where `struct linetable' is defined. Thus, the first
3818 entry whose PC is in the range [FUNC_START..FUNC_END[ is the
3819 address we are looking for. */
3820 for (i = 0; i < l->nitems; i++)
3822 const linetable_entry *item = &(l->item[i]);
3823 CORE_ADDR item_pc = item->pc (objfile);
3825 /* Don't use line numbers of zero, they mark special entries in
3826 the table. See the commentary on symtab.h before the
3827 definition of struct linetable. */
3828 if (item->line > 0 && func_start <= item_pc && item_pc < func_end)
3829 return item_pc;
3832 return func_addr;
3835 /* Try to locate the address where a breakpoint should be placed past the
3836 prologue of function starting at FUNC_ADDR using the line table.
3838 Return the address associated with the first entry in the line-table for
3839 the function starting at FUNC_ADDR which has prologue_end set to true if
3840 such entry exist, otherwise return an empty optional. */
3842 static std::optional<CORE_ADDR>
3843 skip_prologue_using_linetable (CORE_ADDR func_addr)
3845 CORE_ADDR start_pc, end_pc;
3847 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
3848 return {};
3850 const struct symtab_and_line prologue_sal = find_pc_line (start_pc, 0);
3851 if (prologue_sal.symtab != nullptr
3852 && prologue_sal.symtab->language () != language_asm)
3854 const linetable *linetable = prologue_sal.symtab->linetable ();
3856 struct objfile *objfile = prologue_sal.symtab->compunit ()->objfile ();
3858 unrelocated_addr unrel_start
3859 = unrelocated_addr (start_pc - objfile->text_section_offset ());
3860 unrelocated_addr unrel_end
3861 = unrelocated_addr (end_pc - objfile->text_section_offset ());
3863 auto it = std::lower_bound
3864 (linetable->item, linetable->item + linetable->nitems, unrel_start,
3865 [] (const linetable_entry &lte, unrelocated_addr pc)
3867 return lte.unrelocated_pc () < pc;
3870 for (;
3871 (it < linetable->item + linetable->nitems
3872 && it->unrelocated_pc () < unrel_end);
3873 it++)
3874 if (it->prologue_end)
3875 return {it->pc (objfile)};
3878 return {};
3881 /* Adjust SAL to the first instruction past the function prologue.
3882 If the PC was explicitly specified, the SAL is not changed.
3883 If the line number was explicitly specified then the SAL can still be
3884 updated, unless the language for SAL is assembler, in which case the SAL
3885 will be left unchanged.
3886 If SAL is already past the prologue, then do nothing. */
3888 void
3889 skip_prologue_sal (struct symtab_and_line *sal)
3891 struct symbol *sym;
3892 struct symtab_and_line start_sal;
3893 CORE_ADDR pc, saved_pc;
3894 struct obj_section *section;
3895 const char *name;
3896 struct objfile *objfile;
3897 struct gdbarch *gdbarch;
3898 const struct block *b, *function_block;
3899 int force_skip, skip;
3901 /* Do not change the SAL if PC was specified explicitly. */
3902 if (sal->explicit_pc)
3903 return;
3905 /* In assembly code, if the user asks for a specific line then we should
3906 not adjust the SAL. The user already has instruction level
3907 visibility in this case, so selecting a line other than one requested
3908 is likely to be the wrong choice. */
3909 if (sal->symtab != nullptr
3910 && sal->explicit_line
3911 && sal->symtab->language () == language_asm)
3912 return;
3914 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3916 switch_to_program_space_and_thread (sal->pspace);
3918 sym = find_pc_sect_function (sal->pc, sal->section);
3919 if (sym != NULL)
3921 objfile = sym->objfile ();
3922 pc = sym->value_block ()->entry_pc ();
3923 section = sym->obj_section (objfile);
3924 name = sym->linkage_name ();
3926 else
3928 bound_minimal_symbol msymbol
3929 = lookup_minimal_symbol_by_pc_section (sal->pc, sal->section);
3931 if (msymbol.minsym == NULL)
3932 return;
3934 objfile = msymbol.objfile;
3935 pc = msymbol.value_address ();
3936 section = msymbol.minsym->obj_section (objfile);
3937 name = msymbol.minsym->linkage_name ();
3940 gdbarch = objfile->arch ();
3942 /* Process the prologue in two passes. In the first pass try to skip the
3943 prologue (SKIP is true) and verify there is a real need for it (indicated
3944 by FORCE_SKIP). If no such reason was found run a second pass where the
3945 prologue is not skipped (SKIP is false). */
3947 skip = 1;
3948 force_skip = 1;
3950 /* Be conservative - allow direct PC (without skipping prologue) only if we
3951 have proven the CU (Compilation Unit) supports it. sal->SYMTAB does not
3952 have to be set by the caller so we use SYM instead. */
3953 if (sym != NULL
3954 && sym->symtab ()->compunit ()->locations_valid ())
3955 force_skip = 0;
3957 saved_pc = pc;
3960 pc = saved_pc;
3962 /* Check if the compiler explicitly indicated where a breakpoint should
3963 be placed to skip the prologue. */
3964 if (!ignore_prologue_end_flag && skip)
3966 std::optional<CORE_ADDR> linetable_pc
3967 = skip_prologue_using_linetable (pc);
3968 if (linetable_pc)
3970 pc = *linetable_pc;
3971 start_sal = find_pc_sect_line (pc, section, 0);
3972 force_skip = 1;
3973 continue;
3977 /* If the function is in an unmapped overlay, use its unmapped LMA address,
3978 so that gdbarch_skip_prologue has something unique to work on. */
3979 if (section_is_overlay (section) && !section_is_mapped (section))
3980 pc = overlay_unmapped_address (pc, section);
3982 /* Skip "first line" of function (which is actually its prologue). */
3983 pc += gdbarch_deprecated_function_start_offset (gdbarch);
3984 if (gdbarch_skip_entrypoint_p (gdbarch))
3985 pc = gdbarch_skip_entrypoint (gdbarch, pc);
3986 if (skip)
3987 pc = gdbarch_skip_prologue_noexcept (gdbarch, pc);
3989 /* For overlays, map pc back into its mapped VMA range. */
3990 pc = overlay_mapped_address (pc, section);
3992 /* Calculate line number. */
3993 start_sal = find_pc_sect_line (pc, section, 0);
3995 /* Check if gdbarch_skip_prologue left us in mid-line, and the next
3996 line is still part of the same function. */
3997 if (skip && start_sal.pc != pc
3998 && (sym ? (sym->value_block ()->entry_pc () <= start_sal.end
3999 && start_sal.end < sym->value_block()->end ())
4000 : (lookup_minimal_symbol_by_pc_section (start_sal.end, section).minsym
4001 == lookup_minimal_symbol_by_pc_section (pc, section).minsym)))
4003 /* First pc of next line */
4004 pc = start_sal.end;
4005 /* Recalculate the line number (might not be N+1). */
4006 start_sal = find_pc_sect_line (pc, section, 0);
4009 /* On targets with executable formats that don't have a concept of
4010 constructors (ELF with .init has, PE doesn't), gcc emits a call
4011 to `__main' in `main' between the prologue and before user
4012 code. */
4013 if (gdbarch_skip_main_prologue_p (gdbarch)
4014 && name && strcmp_iw (name, "main") == 0)
4016 pc = gdbarch_skip_main_prologue (gdbarch, pc);
4017 /* Recalculate the line number (might not be N+1). */
4018 start_sal = find_pc_sect_line (pc, section, 0);
4019 force_skip = 1;
4022 while (!force_skip && skip--);
4024 /* If we still don't have a valid source line, try to find the first
4025 PC in the lineinfo table that belongs to the same function. This
4026 happens with COFF debug info, which does not seem to have an
4027 entry in lineinfo table for the code after the prologue which has
4028 no direct relation to source. For example, this was found to be
4029 the case with the DJGPP target using "gcc -gcoff" when the
4030 compiler inserted code after the prologue to make sure the stack
4031 is aligned. */
4032 if (!force_skip && sym && start_sal.symtab == NULL)
4034 pc = skip_prologue_using_lineinfo (pc, sym->symtab ());
4035 /* Recalculate the line number. */
4036 start_sal = find_pc_sect_line (pc, section, 0);
4039 /* If we're already past the prologue, leave SAL unchanged. Otherwise
4040 forward SAL to the end of the prologue. */
4041 if (sal->pc >= pc)
4042 return;
4044 sal->pc = pc;
4045 sal->section = section;
4046 sal->symtab = start_sal.symtab;
4047 sal->line = start_sal.line;
4048 sal->end = start_sal.end;
4050 /* Check if we are now inside an inlined function. If we can,
4051 use the call site of the function instead. */
4052 b = block_for_pc_sect (sal->pc, sal->section);
4053 function_block = NULL;
4054 while (b != NULL)
4056 if (b->function () != NULL && b->inlined_p ())
4057 function_block = b;
4058 else if (b->function () != NULL)
4059 break;
4060 b = b->superblock ();
4062 if (function_block != NULL
4063 && function_block->function ()->line () != 0)
4065 sal->line = function_block->function ()->line ();
4066 sal->symtab = function_block->function ()->symtab ();
4070 /* Given PC at the function's start address, attempt to find the
4071 prologue end using SAL information. Return zero if the skip fails.
4073 A non-optimized prologue traditionally has one SAL for the function
4074 and a second for the function body. A single line function has
4075 them both pointing at the same line.
4077 An optimized prologue is similar but the prologue may contain
4078 instructions (SALs) from the instruction body. Need to skip those
4079 while not getting into the function body.
4081 The functions end point and an increasing SAL line are used as
4082 indicators of the prologue's endpoint.
4084 This code is based on the function refine_prologue_limit
4085 (found in ia64). */
4087 CORE_ADDR
4088 skip_prologue_using_sal (struct gdbarch *gdbarch, CORE_ADDR func_addr)
4090 struct symtab_and_line prologue_sal;
4091 CORE_ADDR start_pc;
4092 CORE_ADDR end_pc;
4093 const struct block *bl;
4095 /* Get an initial range for the function. */
4096 find_pc_partial_function (func_addr, NULL, &start_pc, &end_pc);
4097 start_pc += gdbarch_deprecated_function_start_offset (gdbarch);
4099 prologue_sal = find_pc_line (start_pc, 0);
4100 if (prologue_sal.line != 0)
4102 /* For languages other than assembly, treat two consecutive line
4103 entries at the same address as a zero-instruction prologue.
4104 The GNU assembler emits separate line notes for each instruction
4105 in a multi-instruction macro, but compilers generally will not
4106 do this. */
4107 if (prologue_sal.symtab->language () != language_asm)
4109 struct objfile *objfile
4110 = prologue_sal.symtab->compunit ()->objfile ();
4111 const linetable *linetable = prologue_sal.symtab->linetable ();
4112 gdb_assert (linetable->nitems > 0);
4113 int idx = 0;
4115 /* Skip any earlier lines, and any end-of-sequence marker
4116 from a previous function. */
4117 while (idx + 1 < linetable->nitems
4118 && (linetable->item[idx].pc (objfile) != prologue_sal.pc
4119 || linetable->item[idx].line == 0))
4120 idx++;
4122 if (idx + 1 < linetable->nitems
4123 && linetable->item[idx+1].line != 0
4124 && linetable->item[idx+1].pc (objfile) == start_pc)
4125 return start_pc;
4128 /* If there is only one sal that covers the entire function,
4129 then it is probably a single line function, like
4130 "foo(){}". */
4131 if (prologue_sal.end >= end_pc)
4132 return 0;
4134 while (prologue_sal.end < end_pc)
4136 struct symtab_and_line sal;
4138 sal = find_pc_line (prologue_sal.end, 0);
4139 if (sal.line == 0)
4140 break;
4141 /* Assume that a consecutive SAL for the same (or larger)
4142 line mark the prologue -> body transition. */
4143 if (sal.line >= prologue_sal.line)
4144 break;
4145 /* Likewise if we are in a different symtab altogether
4146 (e.g. within a file included via #include).  */
4147 if (sal.symtab != prologue_sal.symtab)
4148 break;
4150 /* The line number is smaller. Check that it's from the
4151 same function, not something inlined. If it's inlined,
4152 then there is no point comparing the line numbers. */
4153 bl = block_for_pc (prologue_sal.end);
4154 while (bl)
4156 if (bl->inlined_p ())
4157 break;
4158 if (bl->function ())
4160 bl = NULL;
4161 break;
4163 bl = bl->superblock ();
4165 if (bl != NULL)
4166 break;
4168 /* The case in which compiler's optimizer/scheduler has
4169 moved instructions into the prologue. We look ahead in
4170 the function looking for address ranges whose
4171 corresponding line number is less the first one that we
4172 found for the function. This is more conservative then
4173 refine_prologue_limit which scans a large number of SALs
4174 looking for any in the prologue. */
4175 prologue_sal = sal;
4179 if (prologue_sal.end < end_pc)
4180 /* Return the end of this line, or zero if we could not find a
4181 line. */
4182 return prologue_sal.end;
4183 else
4184 /* Don't return END_PC, which is past the end of the function. */
4185 return prologue_sal.pc;
4188 /* See symtab.h. */
4190 std::optional<CORE_ADDR>
4191 find_epilogue_using_linetable (CORE_ADDR func_addr)
4193 CORE_ADDR start_pc, end_pc;
4195 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
4196 return {};
4198 /* While the standard allows for multiple points marked with epilogue_begin
4199 in the same function, for performance reasons, this function will only
4200 find the last address that sets this flag for a given block.
4202 The lines of a function can be described by several line tables in case
4203 there are different files involved. There's a corner case where a
4204 function epilogue is in a different file than a function start, and using
4205 start_pc as argument to find_pc_line will mean we won't find the
4206 epilogue. Instead, use "end_pc - 1" to maximize our chances of picking
4207 the line table containing an epilogue. */
4208 const struct symtab_and_line sal = find_pc_line (end_pc - 1, 0);
4209 if (sal.symtab != nullptr && sal.symtab->language () != language_asm)
4211 struct objfile *objfile = sal.symtab->compunit ()->objfile ();
4212 unrelocated_addr unrel_start
4213 = unrelocated_addr (start_pc - objfile->text_section_offset ());
4214 unrelocated_addr unrel_end
4215 = unrelocated_addr (end_pc - objfile->text_section_offset ());
4217 const linetable *linetable = sal.symtab->linetable ();
4218 if (linetable == nullptr || linetable->nitems == 0)
4220 /* Empty line table. */
4221 return {};
4224 /* Find the first linetable entry after the current function. Note that
4225 this also may be an end_sequence entry. */
4226 auto it = std::lower_bound
4227 (linetable->item, linetable->item + linetable->nitems, unrel_end,
4228 [] (const linetable_entry &lte, unrelocated_addr pc)
4230 return lte.unrelocated_pc () < pc;
4232 if (it == linetable->item + linetable->nitems)
4234 /* We couldn't find either:
4235 - a linetable entry starting the function after the current
4236 function, or
4237 - an end_sequence entry that terminates the current function
4238 at unrel_end.
4240 This can happen when the linetable doesn't describe the full
4241 extent of the function. This can be triggered with:
4242 - compiler-generated debug info, in the cornercase that the pc
4243 with which we call find_pc_line resides in a different file
4244 than unrel_end, or
4245 - invalid dwarf assembly debug info.
4246 In the former case, there's no point in iterating further, simply
4247 return "not found". In the latter case, there's no current
4248 incentive to attempt to support this, so handle this
4249 conservatively and do the same. */
4250 return {};
4253 if (unrel_end < it->unrelocated_pc ())
4255 /* We found a line entry that starts past the end of the
4256 function. This can happen if the previous entry straddles
4257 two functions, which shouldn't happen with compiler-generated
4258 debug info. Handle the corner case conservatively. */
4259 return {};
4261 gdb_assert (unrel_end == it->unrelocated_pc ());
4263 /* Move to the last linetable entry of the current function. */
4264 if (it == &linetable->item[0])
4266 /* Doing it-- would introduce undefined behavior, avoid it by
4267 explicitly handling this case. */
4268 return {};
4270 it--;
4271 if (it->unrelocated_pc () < unrel_start)
4273 /* Not in the current function. */
4274 return {};
4276 gdb_assert (it->unrelocated_pc () < unrel_end);
4278 /* We're at the the last linetable entry of the current function. This
4279 is probably where the epilogue begins, but since the DWARF 5 spec
4280 doesn't guarantee it, we iterate backwards through the current
4281 function until we either find the epilogue beginning, or are sure
4282 that it doesn't exist. */
4283 for (; it >= &linetable->item[0]; it--)
4285 if (it->unrelocated_pc () < unrel_start)
4287 /* No longer in the current function. */
4288 break;
4291 if (it->epilogue_begin)
4293 /* Found the beginning of the epilogue. */
4294 return {it->pc (objfile)};
4297 if (it == &linetable->item[0])
4299 /* No more entries in the current function.
4300 Doing it-- would introduce undefined behavior, avoid it by
4301 explicitly handling this case. */
4302 break;
4307 return {};
4310 /* See symtab.h. */
4312 symbol *
4313 find_function_alias_target (bound_minimal_symbol msymbol)
4315 CORE_ADDR func_addr;
4316 if (!msymbol_is_function (msymbol.objfile, msymbol.minsym, &func_addr))
4317 return NULL;
4319 symbol *sym = find_pc_function (func_addr);
4320 if (sym != NULL
4321 && sym->aclass () == LOC_BLOCK
4322 && sym->value_block ()->entry_pc () == func_addr)
4323 return sym;
4325 return NULL;
4329 /* If P is of the form "operator[ \t]+..." where `...' is
4330 some legitimate operator text, return a pointer to the
4331 beginning of the substring of the operator text.
4332 Otherwise, return "". */
4334 static const char *
4335 operator_chars (const char *p, const char **end)
4337 *end = "";
4338 if (!startswith (p, CP_OPERATOR_STR))
4339 return *end;
4340 p += CP_OPERATOR_LEN;
4342 /* Don't get faked out by `operator' being part of a longer
4343 identifier. */
4344 if (isalpha (*p) || *p == '_' || *p == '$' || *p == '\0')
4345 return *end;
4347 /* Allow some whitespace between `operator' and the operator symbol. */
4348 while (*p == ' ' || *p == '\t')
4349 p++;
4351 /* Recognize 'operator TYPENAME'. */
4353 if (isalpha (*p) || *p == '_' || *p == '$')
4355 const char *q = p + 1;
4357 while (isalnum (*q) || *q == '_' || *q == '$')
4358 q++;
4359 *end = q;
4360 return p;
4363 while (*p)
4364 switch (*p)
4366 case '\\': /* regexp quoting */
4367 if (p[1] == '*')
4369 if (p[2] == '=') /* 'operator\*=' */
4370 *end = p + 3;
4371 else /* 'operator\*' */
4372 *end = p + 2;
4373 return p;
4375 else if (p[1] == '[')
4377 if (p[2] == ']')
4378 error (_("mismatched quoting on brackets, "
4379 "try 'operator\\[\\]'"));
4380 else if (p[2] == '\\' && p[3] == ']')
4382 *end = p + 4; /* 'operator\[\]' */
4383 return p;
4385 else
4386 error (_("nothing is allowed between '[' and ']'"));
4388 else
4390 /* Gratuitous quote: skip it and move on. */
4391 p++;
4392 continue;
4394 break;
4395 case '!':
4396 case '=':
4397 case '*':
4398 case '/':
4399 case '%':
4400 case '^':
4401 if (p[1] == '=')
4402 *end = p + 2;
4403 else
4404 *end = p + 1;
4405 return p;
4406 case '<':
4407 case '>':
4408 case '+':
4409 case '-':
4410 case '&':
4411 case '|':
4412 if (p[0] == '-' && p[1] == '>')
4414 /* Struct pointer member operator 'operator->'. */
4415 if (p[2] == '*')
4417 *end = p + 3; /* 'operator->*' */
4418 return p;
4420 else if (p[2] == '\\')
4422 *end = p + 4; /* Hopefully 'operator->\*' */
4423 return p;
4425 else
4427 *end = p + 2; /* 'operator->' */
4428 return p;
4431 if (p[1] == '=' || p[1] == p[0])
4432 *end = p + 2;
4433 else
4434 *end = p + 1;
4435 return p;
4436 case '~':
4437 case ',':
4438 *end = p + 1;
4439 return p;
4440 case '(':
4441 if (p[1] != ')')
4442 error (_("`operator ()' must be specified "
4443 "without whitespace in `()'"));
4444 *end = p + 2;
4445 return p;
4446 case '?':
4447 if (p[1] != ':')
4448 error (_("`operator ?:' must be specified "
4449 "without whitespace in `?:'"));
4450 *end = p + 2;
4451 return p;
4452 case '[':
4453 if (p[1] != ']')
4454 error (_("`operator []' must be specified "
4455 "without whitespace in `[]'"));
4456 *end = p + 2;
4457 return p;
4458 default:
4459 error (_("`operator %s' not supported"), p);
4460 break;
4463 *end = "";
4464 return *end;
4468 /* See class declaration. */
4470 info_sources_filter::info_sources_filter (match_on match_type,
4471 const char *regexp)
4472 : m_match_type (match_type),
4473 m_regexp (regexp)
4475 /* Setup the compiled regular expression M_C_REGEXP based on M_REGEXP. */
4476 if (m_regexp != nullptr && *m_regexp != '\0')
4478 gdb_assert (m_regexp != nullptr);
4480 int cflags = REG_NOSUB;
4481 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
4482 cflags |= REG_ICASE;
4483 #endif
4484 m_c_regexp.emplace (m_regexp, cflags, _("Invalid regexp"));
4488 /* See class declaration. */
4490 bool
4491 info_sources_filter::matches (const char *fullname) const
4493 /* Does it match regexp? */
4494 if (m_c_regexp.has_value ())
4496 const char *to_match;
4497 std::string dirname;
4499 switch (m_match_type)
4501 case match_on::DIRNAME:
4502 dirname = ldirname (fullname);
4503 to_match = dirname.c_str ();
4504 break;
4505 case match_on::BASENAME:
4506 to_match = lbasename (fullname);
4507 break;
4508 case match_on::FULLNAME:
4509 to_match = fullname;
4510 break;
4511 default:
4512 gdb_assert_not_reached ("bad m_match_type");
4515 if (m_c_regexp->exec (to_match, 0, NULL, 0) != 0)
4516 return false;
4519 return true;
4522 /* Data structure to maintain the state used for printing the results of
4523 the 'info sources' command. */
4525 struct output_source_filename_data
4527 /* Create an object for displaying the results of the 'info sources'
4528 command to UIOUT. FILTER must remain valid and unchanged for the
4529 lifetime of this object as this object retains a reference to FILTER. */
4530 output_source_filename_data (struct ui_out *uiout,
4531 const info_sources_filter &filter)
4532 : m_filter (filter),
4533 m_uiout (uiout)
4534 { /* Nothing. */ }
4536 DISABLE_COPY_AND_ASSIGN (output_source_filename_data);
4538 /* Reset enough state of this object so we can match against a new set of
4539 files. The existing regular expression is retained though. */
4540 void reset_output ()
4542 m_first = true;
4543 m_filename_seen_cache.clear ();
4546 /* Worker for sources_info, outputs the file name formatted for either
4547 cli or mi (based on the current_uiout). In cli mode displays
4548 FULLNAME with a comma separating this name from any previously
4549 printed name (line breaks are added at the comma). In MI mode
4550 outputs a tuple containing DISP_NAME (the files display name),
4551 FULLNAME, and EXPANDED_P (true when this file is from a fully
4552 expanded symtab, otherwise false). */
4553 void output (const char *disp_name, const char *fullname, bool expanded_p);
4555 /* An overload suitable for use as a callback to
4556 quick_symbol_functions::map_symbol_filenames. */
4557 void operator() (const char *filename, const char *fullname)
4559 /* The false here indicates that this file is from an unexpanded
4560 symtab. */
4561 output (filename, fullname, false);
4564 /* Return true if at least one filename has been printed (after a call to
4565 output) since either this object was created, or the last call to
4566 reset_output. */
4567 bool printed_filename_p () const
4569 return !m_first;
4572 private:
4574 /* Flag of whether we're printing the first one. */
4575 bool m_first = true;
4577 /* Cache of what we've seen so far. */
4578 filename_seen_cache m_filename_seen_cache;
4580 /* How source filename should be filtered. */
4581 const info_sources_filter &m_filter;
4583 /* The object to which output is sent. */
4584 struct ui_out *m_uiout;
4587 /* See comment in class declaration above. */
4589 void
4590 output_source_filename_data::output (const char *disp_name,
4591 const char *fullname,
4592 bool expanded_p)
4594 /* Since a single source file can result in several partial symbol
4595 tables, we need to avoid printing it more than once. Note: if
4596 some of the psymtabs are read in and some are not, it gets
4597 printed both under "Source files for which symbols have been
4598 read" and "Source files for which symbols will be read in on
4599 demand". I consider this a reasonable way to deal with the
4600 situation. I'm not sure whether this can also happen for
4601 symtabs; it doesn't hurt to check. */
4603 /* Was NAME already seen? If so, then don't print it again. */
4604 if (m_filename_seen_cache.seen (fullname))
4605 return;
4607 /* If the filter rejects this file then don't print it. */
4608 if (!m_filter.matches (fullname))
4609 return;
4611 ui_out_emit_tuple ui_emitter (m_uiout, nullptr);
4613 /* Print it and reset *FIRST. */
4614 if (!m_first)
4615 m_uiout->text (", ");
4616 m_first = false;
4618 m_uiout->wrap_hint (0);
4619 if (m_uiout->is_mi_like_p ())
4621 m_uiout->field_string ("file", disp_name, file_name_style.style ());
4622 if (fullname != nullptr)
4623 m_uiout->field_string ("fullname", fullname,
4624 file_name_style.style ());
4625 m_uiout->field_string ("debug-fully-read",
4626 (expanded_p ? "true" : "false"));
4628 else
4630 if (fullname == nullptr)
4631 fullname = disp_name;
4632 m_uiout->field_string ("fullname", fullname,
4633 file_name_style.style ());
4637 /* For the 'info sources' command, what part of the file names should we be
4638 matching the user supplied regular expression against? */
4640 struct filename_partial_match_opts
4642 /* Only match the directory name part. */
4643 bool dirname = false;
4645 /* Only match the basename part. */
4646 bool basename = false;
4649 using isrc_flag_option_def
4650 = gdb::option::flag_option_def<filename_partial_match_opts>;
4652 static const gdb::option::option_def info_sources_option_defs[] = {
4654 isrc_flag_option_def {
4655 "dirname",
4656 [] (filename_partial_match_opts *opts) { return &opts->dirname; },
4657 N_("Show only the files having a dirname matching REGEXP."),
4660 isrc_flag_option_def {
4661 "basename",
4662 [] (filename_partial_match_opts *opts) { return &opts->basename; },
4663 N_("Show only the files having a basename matching REGEXP."),
4668 /* Create an option_def_group for the "info sources" options, with
4669 ISRC_OPTS as context. */
4671 static inline gdb::option::option_def_group
4672 make_info_sources_options_def_group (filename_partial_match_opts *isrc_opts)
4674 return {{info_sources_option_defs}, isrc_opts};
4677 /* Completer for "info sources". */
4679 static void
4680 info_sources_command_completer (cmd_list_element *ignore,
4681 completion_tracker &tracker,
4682 const char *text, const char *word)
4684 const auto group = make_info_sources_options_def_group (nullptr);
4685 if (gdb::option::complete_options
4686 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
4687 return;
4690 /* See symtab.h. */
4692 void
4693 info_sources_worker (struct ui_out *uiout,
4694 bool group_by_objfile,
4695 const info_sources_filter &filter)
4697 output_source_filename_data data (uiout, filter);
4699 ui_out_emit_list results_emitter (uiout, "files");
4700 std::optional<ui_out_emit_tuple> output_tuple;
4701 std::optional<ui_out_emit_list> sources_list;
4703 gdb_assert (group_by_objfile || uiout->is_mi_like_p ());
4705 for (objfile *objfile : current_program_space->objfiles ())
4707 if (group_by_objfile)
4709 output_tuple.emplace (uiout, nullptr);
4710 uiout->field_string ("filename", objfile_name (objfile),
4711 file_name_style.style ());
4712 uiout->text (":\n");
4713 bool debug_fully_readin = !objfile->has_unexpanded_symtabs ();
4714 if (uiout->is_mi_like_p ())
4716 const char *debug_info_state;
4717 if (objfile_has_symbols (objfile))
4719 if (debug_fully_readin)
4720 debug_info_state = "fully-read";
4721 else
4722 debug_info_state = "partially-read";
4724 else
4725 debug_info_state = "none";
4726 current_uiout->field_string ("debug-info", debug_info_state);
4728 else
4730 if (!debug_fully_readin)
4731 uiout->text ("(Full debug information has not yet been read "
4732 "for this file.)\n");
4733 if (!objfile_has_symbols (objfile))
4734 uiout->text ("(Objfile has no debug information.)\n");
4735 uiout->text ("\n");
4737 sources_list.emplace (uiout, "sources");
4740 for (compunit_symtab *cu : objfile->compunits ())
4742 for (symtab *s : cu->filetabs ())
4744 const char *file = symtab_to_filename_for_display (s);
4745 const char *fullname = symtab_to_fullname (s);
4746 data.output (file, fullname, true);
4750 if (group_by_objfile)
4752 objfile->map_symbol_filenames (data, true /* need_fullname */);
4753 if (data.printed_filename_p ())
4754 uiout->text ("\n\n");
4755 data.reset_output ();
4756 sources_list.reset ();
4757 output_tuple.reset ();
4761 if (!group_by_objfile)
4763 data.reset_output ();
4764 map_symbol_filenames (data, true /*need_fullname*/);
4768 /* Implement the 'info sources' command. */
4770 static void
4771 info_sources_command (const char *args, int from_tty)
4773 if (!have_full_symbols (current_program_space)
4774 && !have_partial_symbols (current_program_space))
4775 error (_ ("No symbol table is loaded. Use the \"file\" command."));
4777 filename_partial_match_opts match_opts;
4778 auto group = make_info_sources_options_def_group (&match_opts);
4779 gdb::option::process_options
4780 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
4782 if (match_opts.dirname && match_opts.basename)
4783 error (_("You cannot give both -basename and -dirname to 'info sources'."));
4785 const char *regex = nullptr;
4786 if (args != NULL && *args != '\000')
4787 regex = args;
4789 if ((match_opts.dirname || match_opts.basename) && regex == nullptr)
4790 error (_("Missing REGEXP for 'info sources'."));
4792 info_sources_filter::match_on match_type;
4793 if (match_opts.dirname)
4794 match_type = info_sources_filter::match_on::DIRNAME;
4795 else if (match_opts.basename)
4796 match_type = info_sources_filter::match_on::BASENAME;
4797 else
4798 match_type = info_sources_filter::match_on::FULLNAME;
4800 info_sources_filter filter (match_type, regex);
4801 info_sources_worker (current_uiout, true, filter);
4804 /* Compare FILE against all the entries of FILENAMES. If BASENAMES is
4805 true compare only lbasename of FILENAMES. */
4807 static bool
4808 file_matches (const char *file,
4809 const std::vector<gdb::unique_xmalloc_ptr<char>> &filenames,
4810 bool basenames)
4812 if (filenames.empty ())
4813 return true;
4815 for (const auto &name : filenames)
4817 const char *lname = (basenames ? lbasename (name.get ()) : name.get ());
4818 if (compare_filenames_for_search (file, lname))
4819 return true;
4822 return false;
4825 /* Helper function for std::sort on symbol_search objects. Can only sort
4826 symbols, not minimal symbols. */
4829 symbol_search::compare_search_syms (const symbol_search &sym_a,
4830 const symbol_search &sym_b)
4832 int c;
4834 c = FILENAME_CMP (sym_a.symbol->symtab ()->filename,
4835 sym_b.symbol->symtab ()->filename);
4836 if (c != 0)
4837 return c;
4839 if (sym_a.block != sym_b.block)
4840 return sym_a.block - sym_b.block;
4842 return strcmp (sym_a.symbol->print_name (), sym_b.symbol->print_name ());
4845 /* Returns true if the type_name of symbol_type of SYM matches TREG.
4846 If SYM has no symbol_type or symbol_name, returns false. */
4848 bool
4849 treg_matches_sym_type_name (const compiled_regex &treg,
4850 const struct symbol *sym)
4852 struct type *sym_type;
4853 std::string printed_sym_type_name;
4855 symbol_lookup_debug_printf_v ("treg_matches_sym_type_name, sym %s",
4856 sym->natural_name ());
4858 sym_type = sym->type ();
4859 if (sym_type == NULL)
4860 return false;
4863 scoped_switch_to_sym_language_if_auto l (sym);
4865 printed_sym_type_name = type_to_string (sym_type);
4868 symbol_lookup_debug_printf_v ("sym_type_name %s",
4869 printed_sym_type_name.c_str ());
4871 if (printed_sym_type_name.empty ())
4872 return false;
4874 return treg.exec (printed_sym_type_name.c_str (), 0, NULL, 0) == 0;
4877 /* See symtab.h. */
4879 bool
4880 global_symbol_searcher::is_suitable_msymbol
4881 (const domain_search_flags kind, const minimal_symbol *msymbol)
4883 switch (msymbol->type ())
4885 case mst_data:
4886 case mst_bss:
4887 case mst_file_data:
4888 case mst_file_bss:
4889 return (kind & SEARCH_VAR_DOMAIN) != 0;
4890 case mst_text:
4891 case mst_file_text:
4892 case mst_solib_trampoline:
4893 case mst_text_gnu_ifunc:
4894 return (kind & SEARCH_FUNCTION_DOMAIN) != 0;
4895 default:
4896 return false;
4900 /* See symtab.h. */
4902 bool
4903 global_symbol_searcher::expand_symtabs
4904 (objfile *objfile, const std::optional<compiled_regex> &preg) const
4906 domain_search_flags kind = m_kind;
4907 bool found_msymbol = false;
4909 auto do_file_match = [&] (const char *filename, bool basenames)
4911 return file_matches (filename, m_filenames, basenames);
4913 gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher = nullptr;
4914 if (!m_filenames.empty ())
4915 file_matcher = do_file_match;
4917 objfile->expand_symtabs_matching
4918 (file_matcher,
4919 &lookup_name_info::match_any (),
4920 [&] (const char *symname)
4922 return (!preg.has_value ()
4923 || preg->exec (symname, 0, NULL, 0) == 0);
4925 NULL,
4926 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
4927 kind);
4929 /* Here, we search through the minimal symbol tables for functions and
4930 variables that match, and force their symbols to be read. This is in
4931 particular necessary for demangled variable names, which are no longer
4932 put into the partial symbol tables. The symbol will then be found
4933 during the scan of symtabs later.
4935 For functions, find_pc_symtab should succeed if we have debug info for
4936 the function, for variables we have to call
4937 lookup_symbol_in_objfile_from_linkage_name to determine if the
4938 variable has debug info. If the lookup fails, set found_msymbol so
4939 that we will rescan to print any matching symbols without debug info.
4940 We only search the objfile the msymbol came from, we no longer search
4941 all objfiles. In large programs (1000s of shared libs) searching all
4942 objfiles is not worth the pain. */
4943 if (m_filenames.empty ()
4944 && (kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN)) != 0)
4946 for (minimal_symbol *msymbol : objfile->msymbols ())
4948 QUIT;
4950 if (msymbol->created_by_gdb)
4951 continue;
4953 if (is_suitable_msymbol (kind, msymbol))
4955 if (!preg.has_value ()
4956 || preg->exec (msymbol->natural_name (), 0,
4957 NULL, 0) == 0)
4959 /* An important side-effect of these lookup functions is
4960 to expand the symbol table if msymbol is found, later
4961 in the process we will add matching symbols or
4962 msymbols to the results list, and that requires that
4963 the symbols tables are expanded. */
4964 if ((kind & SEARCH_FUNCTION_DOMAIN) != 0
4965 ? (find_pc_compunit_symtab
4966 (msymbol->value_address (objfile)) == NULL)
4967 : (lookup_symbol_in_objfile_from_linkage_name
4968 (objfile, msymbol->linkage_name (),
4969 SEARCH_VFT)
4970 .symbol == NULL))
4971 found_msymbol = true;
4977 return found_msymbol;
4980 /* See symtab.h. */
4982 bool
4983 global_symbol_searcher::add_matching_symbols
4984 (objfile *objfile,
4985 const std::optional<compiled_regex> &preg,
4986 const std::optional<compiled_regex> &treg,
4987 std::set<symbol_search> *result_set) const
4989 domain_search_flags kind = m_kind;
4991 /* Add matching symbols (if not already present). */
4992 for (compunit_symtab *cust : objfile->compunits ())
4994 const struct blockvector *bv = cust->blockvector ();
4996 for (block_enum block : { GLOBAL_BLOCK, STATIC_BLOCK })
4998 const struct block *b = bv->block (block);
5000 for (struct symbol *sym : block_iterator_range (b))
5002 struct symtab *real_symtab = sym->symtab ();
5004 QUIT;
5006 /* Check first sole REAL_SYMTAB->FILENAME. It does
5007 not need to be a substring of symtab_to_fullname as
5008 it may contain "./" etc. */
5009 if (!(file_matches (real_symtab->filename, m_filenames, false)
5010 || ((basenames_may_differ
5011 || file_matches (lbasename (real_symtab->filename),
5012 m_filenames, true))
5013 && file_matches (symtab_to_fullname (real_symtab),
5014 m_filenames, false))))
5015 continue;
5017 if (!sym->matches (kind))
5018 continue;
5020 if (preg.has_value () && preg->exec (sym->natural_name (), 0,
5021 nullptr, 0) != 0)
5022 continue;
5024 if (((sym->domain () == VAR_DOMAIN
5025 || sym->domain () == FUNCTION_DOMAIN)
5026 && treg.has_value ()
5027 && !treg_matches_sym_type_name (*treg, sym)))
5028 continue;
5030 if ((kind & SEARCH_VAR_DOMAIN) != 0)
5032 if (sym->aclass () == LOC_UNRESOLVED
5033 /* LOC_CONST can be used for more than
5034 just enums, e.g., c++ static const
5035 members. We only want to skip enums
5036 here. */
5037 || (sym->aclass () == LOC_CONST
5038 && (sym->type ()->code () == TYPE_CODE_ENUM)))
5039 continue;
5041 if (sym->domain () == MODULE_DOMAIN && sym->line () == 0)
5042 continue;
5044 if (result_set->size () < m_max_search_results)
5046 /* Match, insert if not already in the results. */
5047 symbol_search ss (block, sym);
5048 if (result_set->find (ss) == result_set->end ())
5049 result_set->insert (ss);
5051 else
5052 return false;
5057 return true;
5060 /* See symtab.h. */
5062 bool
5063 global_symbol_searcher::add_matching_msymbols
5064 (objfile *objfile, const std::optional<compiled_regex> &preg,
5065 std::vector<symbol_search> *results) const
5067 domain_search_flags kind = m_kind;
5069 for (minimal_symbol *msymbol : objfile->msymbols ())
5071 QUIT;
5073 if (msymbol->created_by_gdb)
5074 continue;
5076 if (is_suitable_msymbol (kind, msymbol))
5078 if (!preg.has_value ()
5079 || preg->exec (msymbol->natural_name (), 0,
5080 NULL, 0) == 0)
5082 /* For functions we can do a quick check of whether the
5083 symbol might be found via find_pc_symtab. */
5084 if ((kind & SEARCH_FUNCTION_DOMAIN) == 0
5085 || (find_pc_compunit_symtab
5086 (msymbol->value_address (objfile)) == NULL))
5088 if (lookup_symbol_in_objfile_from_linkage_name
5089 (objfile, msymbol->linkage_name (),
5090 SEARCH_VFT).symbol == NULL)
5092 /* Matching msymbol, add it to the results list. */
5093 if (results->size () < m_max_search_results)
5094 results->emplace_back (GLOBAL_BLOCK, msymbol, objfile);
5095 else
5096 return false;
5103 return true;
5106 /* See symtab.h. */
5108 std::vector<symbol_search>
5109 global_symbol_searcher::search () const
5111 std::optional<compiled_regex> preg;
5112 std::optional<compiled_regex> treg;
5114 if (m_symbol_name_regexp != NULL)
5116 const char *symbol_name_regexp = m_symbol_name_regexp;
5117 std::string symbol_name_regexp_holder;
5119 /* Make sure spacing is right for C++ operators.
5120 This is just a courtesy to make the matching less sensitive
5121 to how many spaces the user leaves between 'operator'
5122 and <TYPENAME> or <OPERATOR>. */
5123 const char *opend;
5124 const char *opname = operator_chars (symbol_name_regexp, &opend);
5126 if (*opname)
5128 int fix = -1; /* -1 means ok; otherwise number of
5129 spaces needed. */
5131 if (isalpha (*opname) || *opname == '_' || *opname == '$')
5133 /* There should 1 space between 'operator' and 'TYPENAME'. */
5134 if (opname[-1] != ' ' || opname[-2] == ' ')
5135 fix = 1;
5137 else
5139 /* There should 0 spaces between 'operator' and 'OPERATOR'. */
5140 if (opname[-1] == ' ')
5141 fix = 0;
5143 /* If wrong number of spaces, fix it. */
5144 if (fix >= 0)
5146 symbol_name_regexp_holder
5147 = string_printf ("operator%.*s%s", fix, " ", opname);
5148 symbol_name_regexp = symbol_name_regexp_holder.c_str ();
5152 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5153 ? REG_ICASE : 0);
5154 preg.emplace (symbol_name_regexp, cflags,
5155 _("Invalid regexp"));
5158 if (m_symbol_type_regexp != NULL)
5160 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
5161 ? REG_ICASE : 0);
5162 treg.emplace (m_symbol_type_regexp, cflags,
5163 _("Invalid regexp"));
5166 bool found_msymbol = false;
5167 std::set<symbol_search> result_set;
5168 for (objfile *objfile : current_program_space->objfiles ())
5170 /* Expand symtabs within objfile that possibly contain matching
5171 symbols. */
5172 found_msymbol |= expand_symtabs (objfile, preg);
5174 /* Find matching symbols within OBJFILE and add them in to the
5175 RESULT_SET set. Use a set here so that we can easily detect
5176 duplicates as we go, and can therefore track how many unique
5177 matches we have found so far. */
5178 if (!add_matching_symbols (objfile, preg, treg, &result_set))
5179 break;
5182 /* Convert the result set into a sorted result list, as std::set is
5183 defined to be sorted then no explicit call to std::sort is needed. */
5184 std::vector<symbol_search> result (result_set.begin (), result_set.end ());
5186 /* If there are no debug symbols, then add matching minsyms. But if the
5187 user wants to see symbols matching a type regexp, then never give a
5188 minimal symbol, as we assume that a minimal symbol does not have a
5189 type. */
5190 if ((found_msymbol
5191 || (m_filenames.empty () && (m_kind & SEARCH_VAR_DOMAIN) != 0))
5192 && !m_exclude_minsyms
5193 && !treg.has_value ())
5195 gdb_assert ((m_kind & (SEARCH_VAR_DOMAIN | SEARCH_FUNCTION_DOMAIN))
5196 != 0);
5197 for (objfile *objfile : current_program_space->objfiles ())
5198 if (!add_matching_msymbols (objfile, preg, &result))
5199 break;
5202 return result;
5205 /* See symtab.h. */
5207 std::string
5208 symbol_to_info_string (struct symbol *sym, int block)
5210 std::string str;
5212 gdb_assert (block == GLOBAL_BLOCK || block == STATIC_BLOCK);
5214 if (block == STATIC_BLOCK
5215 && (sym->domain () == VAR_DOMAIN
5216 || sym->domain () == FUNCTION_DOMAIN))
5217 str += "static ";
5219 /* Typedef that is not a C++ class. */
5220 if (sym->domain () == TYPE_DOMAIN)
5222 string_file tmp_stream;
5224 /* FIXME: For C (and C++) we end up with a difference in output here
5225 between how a typedef is printed, and non-typedefs are printed.
5226 The TYPEDEF_PRINT code places a ";" at the end in an attempt to
5227 appear C-like, while TYPE_PRINT doesn't.
5229 For the struct printing case below, things are worse, we force
5230 printing of the ";" in this function, which is going to be wrong
5231 for languages that don't require a ";" between statements. */
5232 if (sym->type ()->code () == TYPE_CODE_TYPEDEF)
5233 typedef_print (sym->type (), sym, &tmp_stream);
5234 else
5235 type_print (sym->type (), "", &tmp_stream, -1);
5236 str += tmp_stream.string ();
5238 /* variable, func, or typedef-that-is-c++-class. */
5239 else if (sym->domain () == VAR_DOMAIN || sym->domain () == STRUCT_DOMAIN
5240 || sym->domain () == FUNCTION_DOMAIN)
5242 string_file tmp_stream;
5244 type_print (sym->type (),
5245 (sym->aclass () == LOC_TYPEDEF
5246 ? "" : sym->print_name ()),
5247 &tmp_stream, 0);
5249 str += tmp_stream.string ();
5250 str += ";";
5252 /* Printing of modules is currently done here, maybe at some future
5253 point we might want a language specific method to print the module
5254 symbol so that we can customise the output more. */
5255 else if (sym->domain () == MODULE_DOMAIN)
5256 str += sym->print_name ();
5258 return str;
5261 /* Helper function for symbol info commands, for example 'info
5262 functions', 'info variables', etc. BLOCK is the type of block the
5263 symbols was found in, either GLOBAL_BLOCK or STATIC_BLOCK. SYM is
5264 the symbol we found. If LAST is not NULL, print file and line
5265 number information for the symbol as well. Skip printing the
5266 filename if it matches LAST. */
5268 static void
5269 print_symbol_info (struct symbol *sym, int block, const char *last)
5271 scoped_switch_to_sym_language_if_auto l (sym);
5272 struct symtab *s = sym->symtab ();
5274 if (last != NULL)
5276 const char *s_filename = symtab_to_filename_for_display (s);
5278 if (filename_cmp (last, s_filename) != 0)
5280 gdb_printf (_("\nFile %ps:\n"),
5281 styled_string (file_name_style.style (),
5282 s_filename));
5285 if (sym->line () != 0)
5286 gdb_printf ("%d:\t", sym->line ());
5287 else
5288 gdb_puts ("\t");
5291 std::string str = symbol_to_info_string (sym, block);
5292 gdb_printf ("%s\n", str.c_str ());
5295 /* This help function for symtab_symbol_info() prints information
5296 for non-debugging symbols to gdb_stdout. */
5298 static void
5299 print_msymbol_info (bound_minimal_symbol msymbol)
5301 struct gdbarch *gdbarch = msymbol.objfile->arch ();
5302 const char *tmp;
5304 if (gdbarch_addr_bit (gdbarch) <= 32)
5305 tmp = hex_string_custom (msymbol.value_address ()
5306 & (CORE_ADDR) 0xffffffff,
5308 else
5309 tmp = hex_string_custom (msymbol.value_address (),
5310 16);
5312 ui_file_style sym_style = (msymbol.minsym->text_p ()
5313 ? function_name_style.style ()
5314 : ui_file_style ());
5316 gdb_printf (_("%ps %ps\n"),
5317 styled_string (address_style.style (), tmp),
5318 styled_string (sym_style, msymbol.minsym->print_name ()));
5321 /* This is the guts of the commands "info functions", "info types", and
5322 "info variables". It calls search_symbols to find all matches and then
5323 print_[m]symbol_info to print out some useful information about the
5324 matches. */
5326 static void
5327 symtab_symbol_info (bool quiet, bool exclude_minsyms,
5328 const char *regexp, domain_enum kind,
5329 const char *t_regexp, int from_tty)
5331 const char *last_filename = "";
5332 int first = 1;
5334 if (regexp != nullptr && *regexp == '\0')
5335 regexp = nullptr;
5337 domain_search_flags flags = to_search_flags (kind);
5338 if (kind == TYPE_DOMAIN)
5339 flags |= SEARCH_STRUCT_DOMAIN;
5341 global_symbol_searcher spec (flags, regexp);
5342 spec.set_symbol_type_regexp (t_regexp);
5343 spec.set_exclude_minsyms (exclude_minsyms);
5344 std::vector<symbol_search> symbols = spec.search ();
5346 if (!quiet)
5348 const char *classname;
5349 switch (kind)
5351 case VAR_DOMAIN:
5352 classname = "variable";
5353 break;
5354 case FUNCTION_DOMAIN:
5355 classname = "function";
5356 break;
5357 case TYPE_DOMAIN:
5358 classname = "type";
5359 break;
5360 case MODULE_DOMAIN:
5361 classname = "module";
5362 break;
5363 default:
5364 gdb_assert_not_reached ("invalid domain enum");
5367 if (regexp != NULL)
5369 if (t_regexp != NULL)
5370 gdb_printf
5371 (_("All %ss matching regular expression \"%s\""
5372 " with type matching regular expression \"%s\":\n"),
5373 classname, regexp, t_regexp);
5374 else
5375 gdb_printf (_("All %ss matching regular expression \"%s\":\n"),
5376 classname, regexp);
5378 else
5380 if (t_regexp != NULL)
5381 gdb_printf
5382 (_("All defined %ss"
5383 " with type matching regular expression \"%s\" :\n"),
5384 classname, t_regexp);
5385 else
5386 gdb_printf (_("All defined %ss:\n"), classname);
5390 for (const symbol_search &p : symbols)
5392 QUIT;
5394 if (p.msymbol.minsym != NULL)
5396 if (first)
5398 if (!quiet)
5399 gdb_printf (_("\nNon-debugging symbols:\n"));
5400 first = 0;
5402 print_msymbol_info (p.msymbol);
5404 else
5406 print_symbol_info (p.symbol, p.block, last_filename);
5407 last_filename
5408 = symtab_to_filename_for_display (p.symbol->symtab ());
5413 /* Structure to hold the values of the options used by the 'info variables'
5414 and 'info functions' commands. These correspond to the -q, -t, and -n
5415 options. */
5417 struct info_vars_funcs_options
5419 bool quiet = false;
5420 bool exclude_minsyms = false;
5421 std::string type_regexp;
5424 /* The options used by the 'info variables' and 'info functions'
5425 commands. */
5427 static const gdb::option::option_def info_vars_funcs_options_defs[] = {
5428 gdb::option::boolean_option_def<info_vars_funcs_options> {
5429 "q",
5430 [] (info_vars_funcs_options *opt) { return &opt->quiet; },
5431 nullptr, /* show_cmd_cb */
5432 nullptr /* set_doc */
5435 gdb::option::boolean_option_def<info_vars_funcs_options> {
5436 "n",
5437 [] (info_vars_funcs_options *opt) { return &opt->exclude_minsyms; },
5438 nullptr, /* show_cmd_cb */
5439 nullptr /* set_doc */
5442 gdb::option::string_option_def<info_vars_funcs_options> {
5443 "t",
5444 [] (info_vars_funcs_options *opt) { return &opt->type_regexp; },
5445 nullptr, /* show_cmd_cb */
5446 nullptr /* set_doc */
5450 /* Returns the option group used by 'info variables' and 'info
5451 functions'. */
5453 static gdb::option::option_def_group
5454 make_info_vars_funcs_options_def_group (info_vars_funcs_options *opts)
5456 return {{info_vars_funcs_options_defs}, opts};
5459 /* Command completer for 'info variables' and 'info functions'. */
5461 static void
5462 info_vars_funcs_command_completer (struct cmd_list_element *ignore,
5463 completion_tracker &tracker,
5464 const char *text, const char * /* word */)
5466 const auto group
5467 = make_info_vars_funcs_options_def_group (nullptr);
5468 if (gdb::option::complete_options
5469 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5470 return;
5472 const char *word = advance_to_expression_complete_word_point (tracker, text);
5473 symbol_completer (ignore, tracker, text, word);
5476 /* Implement the 'info variables' command. */
5478 static void
5479 info_variables_command (const char *args, int from_tty)
5481 info_vars_funcs_options opts;
5482 auto grp = make_info_vars_funcs_options_def_group (&opts);
5483 gdb::option::process_options
5484 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5485 if (args != nullptr && *args == '\0')
5486 args = nullptr;
5488 symtab_symbol_info
5489 (opts.quiet, opts.exclude_minsyms, args, VAR_DOMAIN,
5490 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5491 from_tty);
5494 /* Implement the 'info functions' command. */
5496 static void
5497 info_functions_command (const char *args, int from_tty)
5499 info_vars_funcs_options opts;
5501 auto grp = make_info_vars_funcs_options_def_group (&opts);
5502 gdb::option::process_options
5503 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5504 if (args != nullptr && *args == '\0')
5505 args = nullptr;
5507 symtab_symbol_info
5508 (opts.quiet, opts.exclude_minsyms, args, FUNCTION_DOMAIN,
5509 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5510 from_tty);
5513 /* Holds the -q option for the 'info types' command. */
5515 struct info_types_options
5517 bool quiet = false;
5520 /* The options used by the 'info types' command. */
5522 static const gdb::option::option_def info_types_options_defs[] = {
5523 gdb::option::boolean_option_def<info_types_options> {
5524 "q",
5525 [] (info_types_options *opt) { return &opt->quiet; },
5526 nullptr, /* show_cmd_cb */
5527 nullptr /* set_doc */
5531 /* Returns the option group used by 'info types'. */
5533 static gdb::option::option_def_group
5534 make_info_types_options_def_group (info_types_options *opts)
5536 return {{info_types_options_defs}, opts};
5539 /* Implement the 'info types' command. */
5541 static void
5542 info_types_command (const char *args, int from_tty)
5544 info_types_options opts;
5546 auto grp = make_info_types_options_def_group (&opts);
5547 gdb::option::process_options
5548 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5549 if (args != nullptr && *args == '\0')
5550 args = nullptr;
5551 symtab_symbol_info (opts.quiet, false, args, TYPE_DOMAIN, nullptr,
5552 from_tty);
5555 /* Command completer for 'info types' command. */
5557 static void
5558 info_types_command_completer (struct cmd_list_element *ignore,
5559 completion_tracker &tracker,
5560 const char *text, const char * /* word */)
5562 const auto group
5563 = make_info_types_options_def_group (nullptr);
5564 if (gdb::option::complete_options
5565 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5566 return;
5568 const char *word = advance_to_expression_complete_word_point (tracker, text);
5569 symbol_completer (ignore, tracker, text, word);
5572 /* Implement the 'info modules' command. */
5574 static void
5575 info_modules_command (const char *args, int from_tty)
5577 info_types_options opts;
5579 auto grp = make_info_types_options_def_group (&opts);
5580 gdb::option::process_options
5581 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5582 if (args != nullptr && *args == '\0')
5583 args = nullptr;
5584 symtab_symbol_info (opts.quiet, true, args, MODULE_DOMAIN, nullptr,
5585 from_tty);
5588 /* Implement the 'info main' command. */
5590 static void
5591 info_main_command (const char *args, int from_tty)
5593 gdb_printf ("%s\n", main_name ());
5596 static void
5597 rbreak_command (const char *regexp, int from_tty)
5599 gdb::unique_xmalloc_ptr<char> file_name;
5601 if (regexp != nullptr)
5603 const char *colon = strchr (regexp, ':');
5605 /* Ignore the colon if it is part of a Windows drive. */
5606 if (HAS_DRIVE_SPEC (regexp)
5607 && (regexp[2] == '/' || regexp[2] == '\\'))
5608 colon = strchr (STRIP_DRIVE_SPEC (regexp), ':');
5610 if (colon && *(colon + 1) != ':')
5612 int colon_index = colon - regexp;
5613 while (colon_index > 0 && isspace (regexp[colon_index - 1]))
5614 --colon_index;
5616 file_name = make_unique_xstrndup (regexp, colon_index);
5617 regexp = skip_spaces (colon + 1);
5621 global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regexp);
5622 if (file_name != nullptr)
5623 spec.add_filename (std::move (file_name));
5624 std::vector<symbol_search> symbols = spec.search ();
5626 std::unordered_set<std::string> seen_names;
5627 scoped_rbreak_breakpoints finalize;
5628 int err_count = 0;
5630 for (const symbol_search &p : symbols)
5632 std::string name;
5633 if (p.msymbol.minsym == nullptr)
5635 if (file_name != nullptr)
5637 struct symtab *symtab = p.symbol->symtab ();
5638 const char *fullname = symtab_to_fullname (symtab);
5639 name = string_printf ("%s:'%s'", fullname,
5640 p.symbol->linkage_name ());
5642 else
5643 name = p.symbol->linkage_name ();
5645 else
5646 name = p.msymbol.minsym->linkage_name ();
5648 if (!seen_names.insert (name).second)
5649 continue;
5653 break_command (name.c_str (), from_tty);
5655 catch (const gdb_exception_error &ex)
5657 exception_print (gdb_stderr, ex);
5658 ++err_count;
5659 continue;
5662 if (p.msymbol.minsym == nullptr)
5663 print_symbol_info (p.symbol, p.block, nullptr);
5664 else
5665 gdb_printf ("<function, no debug info> %s;\n", name.c_str ());
5668 int first_bp = finalize.first_breakpoint ();
5669 int last_bp = finalize.last_breakpoint ();
5671 if (last_bp == -1)
5672 gdb_printf (_("No breakpoints made.\n"));
5673 else if (first_bp == last_bp)
5674 gdb_printf (_("Successfully created breakpoint %d.\n"), first_bp);
5675 else
5676 gdb_printf (_("Successfully created breakpoints %d-%d.\n"),
5677 first_bp, last_bp);
5679 if (err_count > 0)
5680 gdb_printf (_("%d breakpoints failed due to errors, see above.\n"),
5681 err_count);
5685 /* Evaluate if SYMNAME matches LOOKUP_NAME. */
5687 static int
5688 compare_symbol_name (const char *symbol_name, language symbol_language,
5689 const lookup_name_info &lookup_name,
5690 completion_match_result &match_res)
5692 const language_defn *lang = language_def (symbol_language);
5694 symbol_name_matcher_ftype *name_match
5695 = lang->get_symbol_name_matcher (lookup_name);
5697 return name_match (symbol_name, lookup_name, &match_res);
5700 /* See symtab.h. */
5702 bool
5703 completion_list_add_name (completion_tracker &tracker,
5704 language symbol_language,
5705 const char *symname,
5706 const lookup_name_info &lookup_name,
5707 const char *text, const char *word)
5709 completion_match_result &match_res
5710 = tracker.reset_completion_match_result ();
5712 /* Clip symbols that cannot match. */
5713 if (!compare_symbol_name (symname, symbol_language, lookup_name, match_res))
5714 return false;
5716 /* Refresh SYMNAME from the match string. It's potentially
5717 different depending on language. (E.g., on Ada, the match may be
5718 the encoded symbol name wrapped in "<>"). */
5719 symname = match_res.match.match ();
5720 gdb_assert (symname != NULL);
5722 /* We have a match for a completion, so add SYMNAME to the current list
5723 of matches. Note that the name is moved to freshly malloc'd space. */
5726 gdb::unique_xmalloc_ptr<char> completion
5727 = make_completion_match_str (symname, text, word);
5729 /* Here we pass the match-for-lcd object to add_completion. Some
5730 languages match the user text against substrings of symbol
5731 names in some cases. E.g., in C++, "b push_ba" completes to
5732 "std::vector::push_back", "std::string::push_back", etc., and
5733 in this case we want the completion lowest common denominator
5734 to be "push_back" instead of "std::". */
5735 tracker.add_completion (std::move (completion),
5736 &match_res.match_for_lcd, text, word);
5739 return true;
5742 /* completion_list_add_name wrapper for struct symbol. */
5744 static void
5745 completion_list_add_symbol (completion_tracker &tracker,
5746 symbol *sym,
5747 const lookup_name_info &lookup_name,
5748 const char *text, const char *word)
5750 if (!completion_list_add_name (tracker, sym->language (),
5751 sym->natural_name (),
5752 lookup_name, text, word))
5753 return;
5755 /* C++ function symbols include the parameters within both the msymbol
5756 name and the symbol name. The problem is that the msymbol name will
5757 describe the parameters in the most basic way, with typedefs stripped
5758 out, while the symbol name will represent the types as they appear in
5759 the program. This means we will see duplicate entries in the
5760 completion tracker. The following converts the symbol name back to
5761 the msymbol name and removes the msymbol name from the completion
5762 tracker. */
5763 if (sym->language () == language_cplus
5764 && sym->aclass () == LOC_BLOCK)
5766 /* The call to canonicalize returns the empty string if the input
5767 string is already in canonical form, thanks to this we don't
5768 remove the symbol we just added above. */
5769 gdb::unique_xmalloc_ptr<char> str
5770 = cp_canonicalize_string_no_typedefs (sym->natural_name ());
5771 if (str != nullptr)
5772 tracker.remove_completion (str.get ());
5776 /* completion_list_add_name wrapper for struct minimal_symbol. */
5778 static void
5779 completion_list_add_msymbol (completion_tracker &tracker,
5780 minimal_symbol *sym,
5781 const lookup_name_info &lookup_name,
5782 const char *text, const char *word)
5784 completion_list_add_name (tracker, sym->language (),
5785 sym->natural_name (),
5786 lookup_name, text, word);
5790 /* ObjC: In case we are completing on a selector, look as the msymbol
5791 again and feed all the selectors into the mill. */
5793 static void
5794 completion_list_objc_symbol (completion_tracker &tracker,
5795 struct minimal_symbol *msymbol,
5796 const lookup_name_info &lookup_name,
5797 const char *text, const char *word)
5799 static char *tmp = NULL;
5800 static unsigned int tmplen = 0;
5802 const char *method, *category, *selector;
5803 char *tmp2 = NULL;
5805 method = msymbol->natural_name ();
5807 /* Is it a method? */
5808 if ((method[0] != '-') && (method[0] != '+'))
5809 return;
5811 if (text[0] == '[')
5812 /* Complete on shortened method method. */
5813 completion_list_add_name (tracker, language_objc,
5814 method + 1,
5815 lookup_name,
5816 text, word);
5818 while ((strlen (method) + 1) >= tmplen)
5820 if (tmplen == 0)
5821 tmplen = 1024;
5822 else
5823 tmplen *= 2;
5824 tmp = (char *) xrealloc (tmp, tmplen);
5826 selector = strchr (method, ' ');
5827 if (selector != NULL)
5828 selector++;
5830 category = strchr (method, '(');
5832 if ((category != NULL) && (selector != NULL))
5834 memcpy (tmp, method, (category - method));
5835 tmp[category - method] = ' ';
5836 memcpy (tmp + (category - method) + 1, selector, strlen (selector) + 1);
5837 completion_list_add_name (tracker, language_objc, tmp,
5838 lookup_name, text, word);
5839 if (text[0] == '[')
5840 completion_list_add_name (tracker, language_objc, tmp + 1,
5841 lookup_name, text, word);
5844 if (selector != NULL)
5846 /* Complete on selector only. */
5847 strcpy (tmp, selector);
5848 tmp2 = strchr (tmp, ']');
5849 if (tmp2 != NULL)
5850 *tmp2 = '\0';
5852 completion_list_add_name (tracker, language_objc, tmp,
5853 lookup_name, text, word);
5857 /* Break the non-quoted text based on the characters which are in
5858 symbols. FIXME: This should probably be language-specific. */
5860 static const char *
5861 language_search_unquoted_string (const char *text, const char *p)
5863 for (; p > text; --p)
5865 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
5866 continue;
5867 else
5869 if ((current_language->la_language == language_objc))
5871 if (p[-1] == ':') /* Might be part of a method name. */
5872 continue;
5873 else if (p[-1] == '[' && (p[-2] == '-' || p[-2] == '+'))
5874 p -= 2; /* Beginning of a method name. */
5875 else if (p[-1] == ' ' || p[-1] == '(' || p[-1] == ')')
5876 { /* Might be part of a method name. */
5877 const char *t = p;
5879 /* Seeing a ' ' or a '(' is not conclusive evidence
5880 that we are in the middle of a method name. However,
5881 finding "-[" or "+[" should be pretty un-ambiguous.
5882 Unfortunately we have to find it now to decide. */
5884 while (t > text)
5885 if (isalnum (t[-1]) || t[-1] == '_' ||
5886 t[-1] == ' ' || t[-1] == ':' ||
5887 t[-1] == '(' || t[-1] == ')')
5888 --t;
5889 else
5890 break;
5892 if (t[-1] == '[' && (t[-2] == '-' || t[-2] == '+'))
5893 p = t - 2; /* Method name detected. */
5894 /* Else we leave with p unchanged. */
5897 break;
5900 return p;
5903 static void
5904 completion_list_add_fields (completion_tracker &tracker,
5905 struct symbol *sym,
5906 const lookup_name_info &lookup_name,
5907 const char *text, const char *word)
5909 if (sym->aclass () == LOC_TYPEDEF)
5911 struct type *t = sym->type ();
5912 enum type_code c = t->code ();
5913 int j;
5915 if (c == TYPE_CODE_UNION || c == TYPE_CODE_STRUCT)
5916 for (j = TYPE_N_BASECLASSES (t); j < t->num_fields (); j++)
5917 if (t->field (j).name ())
5918 completion_list_add_name (tracker, sym->language (),
5919 t->field (j).name (),
5920 lookup_name, text, word);
5924 /* See symtab.h. */
5926 bool
5927 symbol_is_function_or_method (symbol *sym)
5929 switch (sym->type ()->code ())
5931 case TYPE_CODE_FUNC:
5932 case TYPE_CODE_METHOD:
5933 return true;
5934 default:
5935 return false;
5939 /* See symtab.h. */
5941 bool
5942 symbol_is_function_or_method (minimal_symbol *msymbol)
5944 switch (msymbol->type ())
5946 case mst_text:
5947 case mst_text_gnu_ifunc:
5948 case mst_solib_trampoline:
5949 case mst_file_text:
5950 return true;
5951 default:
5952 return false;
5956 /* See symtab.h. */
5958 bound_minimal_symbol
5959 find_gnu_ifunc (const symbol *sym)
5961 if (sym->aclass () != LOC_BLOCK)
5962 return {};
5964 lookup_name_info lookup_name (sym->search_name (),
5965 symbol_name_match_type::SEARCH_NAME);
5966 struct objfile *objfile = sym->objfile ();
5968 CORE_ADDR address = sym->value_block ()->entry_pc ();
5969 minimal_symbol *ifunc = NULL;
5971 iterate_over_minimal_symbols (objfile, lookup_name,
5972 [&] (minimal_symbol *minsym)
5974 if (minsym->type () == mst_text_gnu_ifunc
5975 || minsym->type () == mst_data_gnu_ifunc)
5977 CORE_ADDR msym_addr = minsym->value_address (objfile);
5978 if (minsym->type () == mst_data_gnu_ifunc)
5980 struct gdbarch *gdbarch = objfile->arch ();
5981 msym_addr = gdbarch_convert_from_func_ptr_addr
5982 (gdbarch, msym_addr, current_inferior ()->top_target ());
5984 if (msym_addr == address)
5986 ifunc = minsym;
5987 return true;
5990 return false;
5993 if (ifunc != NULL)
5994 return {ifunc, objfile};
5995 return {};
5998 /* Add matching symbols from SYMTAB to the current completion list. */
6000 static void
6001 add_symtab_completions (struct compunit_symtab *cust,
6002 completion_tracker &tracker,
6003 complete_symbol_mode mode,
6004 const lookup_name_info &lookup_name,
6005 const char *text, const char *word,
6006 enum type_code code)
6008 int i;
6010 if (cust == NULL)
6011 return;
6013 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
6015 QUIT;
6017 const struct block *b = cust->blockvector ()->block (i);
6018 for (struct symbol *sym : block_iterator_range (b))
6020 if (completion_skip_symbol (mode, sym))
6021 continue;
6023 if (code == TYPE_CODE_UNDEF
6024 || (sym->domain () == STRUCT_DOMAIN
6025 && sym->type ()->code () == code))
6026 completion_list_add_symbol (tracker, sym,
6027 lookup_name,
6028 text, word);
6033 void
6034 default_collect_symbol_completion_matches_break_on
6035 (completion_tracker &tracker, complete_symbol_mode mode,
6036 symbol_name_match_type name_match_type,
6037 const char *text, const char *word,
6038 const char *break_on, enum type_code code)
6040 /* Problem: All of the symbols have to be copied because readline
6041 frees them. I'm not going to worry about this; hopefully there
6042 won't be that many. */
6044 const struct block *b;
6045 const struct block *surrounding_static_block, *surrounding_global_block;
6046 /* The symbol we are completing on. Points in same buffer as text. */
6047 const char *sym_text;
6049 /* Now look for the symbol we are supposed to complete on. */
6050 if (mode == complete_symbol_mode::LINESPEC)
6051 sym_text = text;
6052 else
6054 const char *p;
6055 char quote_found;
6056 const char *quote_pos = NULL;
6058 /* First see if this is a quoted string. */
6059 quote_found = '\0';
6060 for (p = text; *p != '\0'; ++p)
6062 if (quote_found != '\0')
6064 if (*p == quote_found)
6065 /* Found close quote. */
6066 quote_found = '\0';
6067 else if (*p == '\\' && p[1] == quote_found)
6068 /* A backslash followed by the quote character
6069 doesn't end the string. */
6070 ++p;
6072 else if (*p == '\'' || *p == '"')
6074 quote_found = *p;
6075 quote_pos = p;
6078 if (quote_found == '\'')
6079 /* A string within single quotes can be a symbol, so complete on it. */
6080 sym_text = quote_pos + 1;
6081 else if (quote_found == '"')
6082 /* A double-quoted string is never a symbol, nor does it make sense
6083 to complete it any other way. */
6085 return;
6087 else
6089 /* It is not a quoted string. Break it based on the characters
6090 which are in symbols. */
6091 while (p > text)
6093 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0'
6094 || p[-1] == ':' || strchr (break_on, p[-1]) != NULL)
6095 --p;
6096 else
6097 break;
6099 sym_text = p;
6103 lookup_name_info lookup_name (sym_text, name_match_type, true);
6105 /* At this point scan through the misc symbol vectors and add each
6106 symbol you find to the list. Eventually we want to ignore
6107 anything that isn't a text symbol (everything else will be
6108 handled by the psymtab code below). */
6110 if (code == TYPE_CODE_UNDEF)
6112 for (objfile *objfile : current_program_space->objfiles ())
6114 for (minimal_symbol *msymbol : objfile->msymbols ())
6116 QUIT;
6118 if (completion_skip_symbol (mode, msymbol))
6119 continue;
6121 completion_list_add_msymbol (tracker, msymbol, lookup_name,
6122 sym_text, word);
6124 completion_list_objc_symbol (tracker, msymbol, lookup_name,
6125 sym_text, word);
6130 /* Add completions for all currently loaded symbol tables. */
6131 for (objfile *objfile : current_program_space->objfiles ())
6133 for (compunit_symtab *cust : objfile->compunits ())
6134 add_symtab_completions (cust, tracker, mode, lookup_name,
6135 sym_text, word, code);
6138 /* Look through the partial symtabs for all symbols which begin by
6139 matching SYM_TEXT. Expand all CUs that you find to the list. */
6140 expand_symtabs_matching (NULL,
6141 lookup_name,
6142 NULL,
6143 [&] (compunit_symtab *symtab) /* expansion notify */
6145 add_symtab_completions (symtab,
6146 tracker, mode, lookup_name,
6147 sym_text, word, code);
6148 return true;
6150 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
6151 SEARCH_ALL_DOMAINS);
6153 /* Search upwards from currently selected frame (so that we can
6154 complete on local vars). Also catch fields of types defined in
6155 this places which match our text string. Only complete on types
6156 visible from current context. */
6158 b = get_selected_block (0);
6159 surrounding_static_block = b == nullptr ? nullptr : b->static_block ();
6160 surrounding_global_block = b == nullptr ? nullptr : b->global_block ();
6161 if (surrounding_static_block != NULL)
6162 while (b != surrounding_static_block)
6164 QUIT;
6166 for (struct symbol *sym : block_iterator_range (b))
6168 if (code == TYPE_CODE_UNDEF)
6170 completion_list_add_symbol (tracker, sym, lookup_name,
6171 sym_text, word);
6172 completion_list_add_fields (tracker, sym, lookup_name,
6173 sym_text, word);
6175 else if (sym->domain () == STRUCT_DOMAIN
6176 && sym->type ()->code () == code)
6177 completion_list_add_symbol (tracker, sym, lookup_name,
6178 sym_text, word);
6181 /* Stop when we encounter an enclosing function. Do not stop for
6182 non-inlined functions - the locals of the enclosing function
6183 are in scope for a nested function. */
6184 if (b->function () != NULL && b->inlined_p ())
6185 break;
6186 b = b->superblock ();
6189 /* Add fields from the file's types; symbols will be added below. */
6191 if (code == TYPE_CODE_UNDEF)
6193 if (surrounding_static_block != NULL)
6194 for (struct symbol *sym : block_iterator_range (surrounding_static_block))
6195 completion_list_add_fields (tracker, sym, lookup_name,
6196 sym_text, word);
6198 if (surrounding_global_block != NULL)
6199 for (struct symbol *sym : block_iterator_range (surrounding_global_block))
6200 completion_list_add_fields (tracker, sym, lookup_name,
6201 sym_text, word);
6204 /* Skip macros if we are completing a struct tag -- arguable but
6205 usually what is expected. */
6206 if (current_language->macro_expansion () == macro_expansion_c
6207 && code == TYPE_CODE_UNDEF)
6209 gdb::unique_xmalloc_ptr<struct macro_scope> scope;
6211 /* This adds a macro's name to the current completion list. */
6212 auto add_macro_name = [&] (const char *macro_name,
6213 const macro_definition *,
6214 macro_source_file *,
6215 int)
6217 completion_list_add_name (tracker, language_c, macro_name,
6218 lookup_name, sym_text, word);
6221 /* Add any macros visible in the default scope. Note that this
6222 may yield the occasional wrong result, because an expression
6223 might be evaluated in a scope other than the default. For
6224 example, if the user types "break file:line if <TAB>", the
6225 resulting expression will be evaluated at "file:line" -- but
6226 at there does not seem to be a way to detect this at
6227 completion time. */
6228 scope = default_macro_scope ();
6229 if (scope)
6230 macro_for_each_in_scope (scope->file, scope->line,
6231 add_macro_name);
6233 /* User-defined macros are always visible. */
6234 macro_for_each (macro_user_macros, add_macro_name);
6238 /* Collect all symbols (regardless of class) which begin by matching
6239 TEXT. */
6241 void
6242 collect_symbol_completion_matches (completion_tracker &tracker,
6243 complete_symbol_mode mode,
6244 symbol_name_match_type name_match_type,
6245 const char *text, const char *word)
6247 current_language->collect_symbol_completion_matches (tracker, mode,
6248 name_match_type,
6249 text, word,
6250 TYPE_CODE_UNDEF);
6253 /* Like collect_symbol_completion_matches, but only collect
6254 STRUCT_DOMAIN symbols whose type code is CODE. */
6256 void
6257 collect_symbol_completion_matches_type (completion_tracker &tracker,
6258 const char *text, const char *word,
6259 enum type_code code)
6261 complete_symbol_mode mode = complete_symbol_mode::EXPRESSION;
6262 symbol_name_match_type name_match_type = symbol_name_match_type::EXPRESSION;
6264 gdb_assert (code == TYPE_CODE_UNION
6265 || code == TYPE_CODE_STRUCT
6266 || code == TYPE_CODE_ENUM);
6267 current_language->collect_symbol_completion_matches (tracker, mode,
6268 name_match_type,
6269 text, word, code);
6272 /* Like collect_symbol_completion_matches, but collects a list of
6273 symbols defined in all source files named SRCFILE. */
6275 void
6276 collect_file_symbol_completion_matches (completion_tracker &tracker,
6277 complete_symbol_mode mode,
6278 symbol_name_match_type name_match_type,
6279 const char *text, const char *word,
6280 const char *srcfile)
6282 /* The symbol we are completing on. Points in same buffer as text. */
6283 const char *sym_text;
6285 /* Now look for the symbol we are supposed to complete on.
6286 FIXME: This should be language-specific. */
6287 if (mode == complete_symbol_mode::LINESPEC)
6288 sym_text = text;
6289 else
6291 const char *p;
6292 char quote_found;
6293 const char *quote_pos = NULL;
6295 /* First see if this is a quoted string. */
6296 quote_found = '\0';
6297 for (p = text; *p != '\0'; ++p)
6299 if (quote_found != '\0')
6301 if (*p == quote_found)
6302 /* Found close quote. */
6303 quote_found = '\0';
6304 else if (*p == '\\' && p[1] == quote_found)
6305 /* A backslash followed by the quote character
6306 doesn't end the string. */
6307 ++p;
6309 else if (*p == '\'' || *p == '"')
6311 quote_found = *p;
6312 quote_pos = p;
6315 if (quote_found == '\'')
6316 /* A string within single quotes can be a symbol, so complete on it. */
6317 sym_text = quote_pos + 1;
6318 else if (quote_found == '"')
6319 /* A double-quoted string is never a symbol, nor does it make sense
6320 to complete it any other way. */
6322 return;
6324 else
6326 /* Not a quoted string. */
6327 sym_text = language_search_unquoted_string (text, p);
6331 lookup_name_info lookup_name (sym_text, name_match_type, true);
6333 /* Go through symtabs for SRCFILE and check the externs and statics
6334 for symbols which match. */
6335 iterate_over_symtabs (current_program_space, srcfile, [&] (symtab *s)
6337 add_symtab_completions (s->compunit (),
6338 tracker, mode, lookup_name,
6339 sym_text, word, TYPE_CODE_UNDEF);
6340 return false;
6344 /* A helper function for make_source_files_completion_list. It adds
6345 another file name to a list of possible completions, growing the
6346 list as necessary. */
6348 static void
6349 add_filename_to_list (const char *fname, const char *text, const char *word,
6350 completion_list *list)
6352 list->emplace_back (make_completion_match_str (fname, text, word));
6355 static int
6356 not_interesting_fname (const char *fname)
6358 static const char *illegal_aliens[] = {
6359 "_globals_", /* inserted by coff_symtab_read */
6360 NULL
6362 int i;
6364 for (i = 0; illegal_aliens[i]; i++)
6366 if (filename_cmp (fname, illegal_aliens[i]) == 0)
6367 return 1;
6369 return 0;
6372 /* An object of this type is passed as the callback argument to
6373 map_partial_symbol_filenames. */
6374 struct add_partial_filename_data
6376 struct filename_seen_cache *filename_seen_cache;
6377 const char *text;
6378 const char *word;
6379 int text_len;
6380 completion_list *list;
6382 void operator() (const char *filename, const char *fullname);
6385 /* A callback for map_partial_symbol_filenames. */
6387 void
6388 add_partial_filename_data::operator() (const char *filename,
6389 const char *fullname)
6391 if (not_interesting_fname (filename))
6392 return;
6393 if (!filename_seen_cache->seen (filename)
6394 && filename_ncmp (filename, text, text_len) == 0)
6396 /* This file matches for a completion; add it to the
6397 current list of matches. */
6398 add_filename_to_list (filename, text, word, list);
6400 else
6402 const char *base_name = lbasename (filename);
6404 if (base_name != filename
6405 && !filename_seen_cache->seen (base_name)
6406 && filename_ncmp (base_name, text, text_len) == 0)
6407 add_filename_to_list (base_name, text, word, list);
6411 /* Return a list of all source files whose names begin with matching
6412 TEXT. The file names are looked up in the symbol tables of this
6413 program. */
6415 completion_list
6416 make_source_files_completion_list (const char *text, const char *word)
6418 size_t text_len = strlen (text);
6419 completion_list list;
6420 const char *base_name;
6421 struct add_partial_filename_data datum;
6423 if (!have_full_symbols (current_program_space)
6424 && !have_partial_symbols (current_program_space))
6425 return list;
6427 filename_seen_cache filenames_seen;
6429 for (objfile *objfile : current_program_space->objfiles ())
6431 for (compunit_symtab *cu : objfile->compunits ())
6433 for (symtab *s : cu->filetabs ())
6435 if (not_interesting_fname (s->filename))
6436 continue;
6437 if (!filenames_seen.seen (s->filename)
6438 && filename_ncmp (s->filename, text, text_len) == 0)
6440 /* This file matches for a completion; add it to the current
6441 list of matches. */
6442 add_filename_to_list (s->filename, text, word, &list);
6444 else
6446 /* NOTE: We allow the user to type a base name when the
6447 debug info records leading directories, but not the other
6448 way around. This is what subroutines of breakpoint
6449 command do when they parse file names. */
6450 base_name = lbasename (s->filename);
6451 if (base_name != s->filename
6452 && !filenames_seen.seen (base_name)
6453 && filename_ncmp (base_name, text, text_len) == 0)
6454 add_filename_to_list (base_name, text, word, &list);
6460 datum.filename_seen_cache = &filenames_seen;
6461 datum.text = text;
6462 datum.word = word;
6463 datum.text_len = text_len;
6464 datum.list = &list;
6465 map_symbol_filenames (datum, false /*need_fullname*/);
6467 return list;
6470 /* Track MAIN */
6472 /* Return the "main_info" object for the current program space. If
6473 the object has not yet been created, create it and fill in some
6474 default values. */
6476 static main_info *
6477 get_main_info (program_space *pspace)
6479 main_info *info = main_progspace_key.get (pspace);
6481 if (info == NULL)
6483 /* It may seem strange to store the main name in the progspace
6484 and also in whatever objfile happens to see a main name in
6485 its debug info. The reason for this is mainly historical:
6486 gdb returned "main" as the name even if no function named
6487 "main" was defined the program; and this approach lets us
6488 keep compatibility. */
6489 info = main_progspace_key.emplace (pspace);
6492 return info;
6495 static void
6496 set_main_name (program_space *pspace, const char *name, enum language lang)
6498 main_info *info = get_main_info (pspace);
6500 if (!info->name_of_main.empty ())
6502 info->name_of_main.clear ();
6503 info->language_of_main = language_unknown;
6505 if (name != NULL)
6507 info->name_of_main = name;
6508 info->language_of_main = lang;
6512 /* Deduce the name of the main procedure, and set NAME_OF_MAIN
6513 accordingly. */
6515 static void
6516 find_main_name (void)
6518 const char *new_main_name;
6519 program_space *pspace = current_program_space;
6521 /* First check the objfiles to see whether a debuginfo reader has
6522 picked up the appropriate main name. Historically the main name
6523 was found in a more or less random way; this approach instead
6524 relies on the order of objfile creation -- which still isn't
6525 guaranteed to get the correct answer, but is just probably more
6526 accurate. */
6527 for (objfile *objfile : current_program_space->objfiles ())
6529 objfile->compute_main_name ();
6531 if (objfile->per_bfd->name_of_main != NULL)
6533 set_main_name (pspace,
6534 objfile->per_bfd->name_of_main,
6535 objfile->per_bfd->language_of_main);
6536 return;
6540 /* Try to see if the main procedure is in Ada. */
6541 /* FIXME: brobecker/2005-03-07: Another way of doing this would
6542 be to add a new method in the language vector, and call this
6543 method for each language until one of them returns a non-empty
6544 name. This would allow us to remove this hard-coded call to
6545 an Ada function. It is not clear that this is a better approach
6546 at this point, because all methods need to be written in a way
6547 such that false positives never be returned. For instance, it is
6548 important that a method does not return a wrong name for the main
6549 procedure if the main procedure is actually written in a different
6550 language. It is easy to guaranty this with Ada, since we use a
6551 special symbol generated only when the main in Ada to find the name
6552 of the main procedure. It is difficult however to see how this can
6553 be guarantied for languages such as C, for instance. This suggests
6554 that order of call for these methods becomes important, which means
6555 a more complicated approach. */
6556 new_main_name = ada_main_name ();
6557 if (new_main_name != NULL)
6559 set_main_name (pspace, new_main_name, language_ada);
6560 return;
6563 new_main_name = d_main_name ();
6564 if (new_main_name != NULL)
6566 set_main_name (pspace, new_main_name, language_d);
6567 return;
6570 new_main_name = go_main_name ();
6571 if (new_main_name != NULL)
6573 set_main_name (pspace, new_main_name, language_go);
6574 return;
6577 new_main_name = pascal_main_name ();
6578 if (new_main_name != NULL)
6580 set_main_name (pspace, new_main_name, language_pascal);
6581 return;
6584 /* The languages above didn't identify the name of the main procedure.
6585 Fallback to "main". */
6587 /* Try to find language for main in psymtabs. */
6588 bool symbol_found_p = false;
6589 gdbarch_iterate_over_objfiles_in_search_order
6590 (current_inferior ()->arch (),
6591 [&symbol_found_p, pspace] (objfile *obj)
6593 language lang
6594 = obj->lookup_global_symbol_language ("main",
6595 SEARCH_FUNCTION_DOMAIN,
6596 &symbol_found_p);
6597 if (symbol_found_p)
6599 set_main_name (pspace, "main", lang);
6600 return 1;
6603 return 0;
6604 }, nullptr);
6606 if (symbol_found_p)
6607 return;
6609 set_main_name (pspace, "main", language_unknown);
6612 /* See symtab.h. */
6614 const char *
6615 main_name ()
6617 main_info *info = get_main_info (current_program_space);
6619 if (info->name_of_main.empty ())
6620 find_main_name ();
6622 return info->name_of_main.c_str ();
6625 /* Return the language of the main function. If it is not known,
6626 return language_unknown. */
6628 enum language
6629 main_language (void)
6631 main_info *info = get_main_info (current_program_space);
6633 if (info->name_of_main.empty ())
6634 find_main_name ();
6636 return info->language_of_main;
6639 /* Return 1 if the supplied producer string matches the ARM RealView
6640 compiler (armcc). */
6642 bool
6643 producer_is_realview (const char *producer)
6645 static const char *const arm_idents[] = {
6646 "ARM C Compiler, ADS",
6647 "Thumb C Compiler, ADS",
6648 "ARM C++ Compiler, ADS",
6649 "Thumb C++ Compiler, ADS",
6650 "ARM/Thumb C/C++ Compiler, RVCT",
6651 "ARM C/C++ Compiler, RVCT"
6654 if (producer == NULL)
6655 return false;
6657 for (const char *ident : arm_idents)
6658 if (startswith (producer, ident))
6659 return true;
6661 return false;
6666 /* The next index to hand out in response to a registration request. */
6668 static int next_aclass_value = LOC_FINAL_VALUE;
6670 /* The maximum number of "aclass" registrations we support. This is
6671 constant for convenience. */
6672 #define MAX_SYMBOL_IMPLS (LOC_FINAL_VALUE + 11)
6674 /* The objects representing the various "aclass" values. The elements
6675 from 0 up to LOC_FINAL_VALUE-1 represent themselves, and subsequent
6676 elements are those registered at gdb initialization time. */
6678 static struct symbol_impl symbol_impl[MAX_SYMBOL_IMPLS];
6680 /* The globally visible pointer. This is separate from 'symbol_impl'
6681 so that it can be const. */
6683 gdb::array_view<const struct symbol_impl> symbol_impls (symbol_impl);
6685 /* Make sure we saved enough room in struct symbol. */
6687 static_assert (MAX_SYMBOL_IMPLS <= (1 << SYMBOL_ACLASS_BITS));
6689 /* Register a computed symbol type. ACLASS must be LOC_COMPUTED. OPS
6690 is the ops vector associated with this index. This returns the new
6691 index, which should be used as the aclass_index field for symbols
6692 of this type. */
6695 register_symbol_computed_impl (enum address_class aclass,
6696 const struct symbol_computed_ops *ops)
6698 int result = next_aclass_value++;
6700 gdb_assert (aclass == LOC_COMPUTED);
6701 gdb_assert (result < MAX_SYMBOL_IMPLS);
6702 symbol_impl[result].aclass = aclass;
6703 symbol_impl[result].ops_computed = ops;
6705 /* Sanity check OPS. */
6706 gdb_assert (ops != NULL);
6707 gdb_assert (ops->tracepoint_var_ref != NULL);
6708 gdb_assert (ops->describe_location != NULL);
6709 gdb_assert (ops->get_symbol_read_needs != NULL);
6710 gdb_assert (ops->read_variable != NULL);
6712 return result;
6715 /* Register a function with frame base type. ACLASS must be LOC_BLOCK.
6716 OPS is the ops vector associated with this index. This returns the
6717 new index, which should be used as the aclass_index field for symbols
6718 of this type. */
6721 register_symbol_block_impl (enum address_class aclass,
6722 const struct symbol_block_ops *ops)
6724 int result = next_aclass_value++;
6726 gdb_assert (aclass == LOC_BLOCK);
6727 gdb_assert (result < MAX_SYMBOL_IMPLS);
6728 symbol_impl[result].aclass = aclass;
6729 symbol_impl[result].ops_block = ops;
6731 /* Sanity check OPS. */
6732 gdb_assert (ops != NULL);
6733 gdb_assert (ops->find_frame_base_location != nullptr
6734 || ops->get_block_value != nullptr);
6736 return result;
6739 /* Register a register symbol type. ACLASS must be LOC_REGISTER or
6740 LOC_REGPARM_ADDR. OPS is the register ops vector associated with
6741 this index. This returns the new index, which should be used as
6742 the aclass_index field for symbols of this type. */
6745 register_symbol_register_impl (enum address_class aclass,
6746 const struct symbol_register_ops *ops)
6748 int result = next_aclass_value++;
6750 gdb_assert (aclass == LOC_REGISTER || aclass == LOC_REGPARM_ADDR);
6751 gdb_assert (result < MAX_SYMBOL_IMPLS);
6752 symbol_impl[result].aclass = aclass;
6753 symbol_impl[result].ops_register = ops;
6755 return result;
6758 /* Initialize elements of 'symbol_impl' for the constants in enum
6759 address_class. */
6761 static void
6762 initialize_ordinary_address_classes (void)
6764 int i;
6766 for (i = 0; i < LOC_FINAL_VALUE; ++i)
6767 symbol_impl[i].aclass = (enum address_class) i;
6772 /* See symtab.h. */
6774 struct objfile *
6775 symbol::objfile () const
6777 gdb_assert (is_objfile_owned ());
6778 return owner.symtab->compunit ()->objfile ();
6781 /* See symtab.h. */
6783 struct gdbarch *
6784 symbol::arch () const
6786 if (!is_objfile_owned ())
6787 return owner.arch;
6788 return owner.symtab->compunit ()->objfile ()->arch ();
6791 /* See symtab.h. */
6793 struct symtab *
6794 symbol::symtab () const
6796 gdb_assert (is_objfile_owned ());
6797 return owner.symtab;
6800 /* See symtab.h. */
6802 void
6803 symbol::set_symtab (struct symtab *symtab)
6805 gdb_assert (is_objfile_owned ());
6806 owner.symtab = symtab;
6809 /* See symtab.h. */
6811 CORE_ADDR
6812 symbol::get_maybe_copied_address () const
6814 gdb_assert (this->maybe_copied);
6815 gdb_assert (this->aclass () == LOC_STATIC);
6817 const char *linkage_name = this->linkage_name ();
6818 bound_minimal_symbol minsym
6819 = lookup_minimal_symbol_linkage (this->objfile ()->pspace (), linkage_name,
6820 false);
6821 if (minsym.minsym != nullptr)
6822 return minsym.value_address ();
6824 return this->m_value.address;
6827 /* See symtab.h. */
6829 CORE_ADDR
6830 minimal_symbol::get_maybe_copied_address (objfile *objf) const
6832 gdb_assert (this->maybe_copied (objf));
6833 gdb_assert ((objf->flags & OBJF_MAINLINE) == 0);
6835 const char *linkage_name = this->linkage_name ();
6836 bound_minimal_symbol found
6837 = lookup_minimal_symbol_linkage (objf->pspace (), linkage_name, true);
6838 if (found.minsym != nullptr)
6839 return found.value_address ();
6841 return (this->m_value.address
6842 + objf->section_offsets[this->section_index ()]);
6847 /* Hold the sub-commands of 'info module'. */
6849 static struct cmd_list_element *info_module_cmdlist = NULL;
6851 /* See symtab.h. */
6853 std::vector<module_symbol_search>
6854 search_module_symbols (const char *module_regexp, const char *regexp,
6855 const char *type_regexp, domain_search_flags kind)
6857 std::vector<module_symbol_search> results;
6859 /* Search for all modules matching MODULE_REGEXP. */
6860 global_symbol_searcher spec1 (SEARCH_MODULE_DOMAIN, module_regexp);
6861 spec1.set_exclude_minsyms (true);
6862 std::vector<symbol_search> modules = spec1.search ();
6864 /* Now search for all symbols of the required KIND matching the required
6865 regular expressions. We figure out which ones are in which modules
6866 below. */
6867 global_symbol_searcher spec2 (kind, regexp);
6868 spec2.set_symbol_type_regexp (type_regexp);
6869 spec2.set_exclude_minsyms (true);
6870 std::vector<symbol_search> symbols = spec2.search ();
6872 /* Now iterate over all MODULES, checking to see which items from
6873 SYMBOLS are in each module. */
6874 for (const symbol_search &p : modules)
6876 QUIT;
6878 /* This is a module. */
6879 gdb_assert (p.symbol != nullptr);
6881 std::string prefix = p.symbol->print_name ();
6882 prefix += "::";
6884 for (const symbol_search &q : symbols)
6886 if (q.symbol == nullptr)
6887 continue;
6889 if (strncmp (q.symbol->print_name (), prefix.c_str (),
6890 prefix.size ()) != 0)
6891 continue;
6893 results.push_back ({p, q});
6897 return results;
6900 /* Implement the core of both 'info module functions' and 'info module
6901 variables'. */
6903 static void
6904 info_module_subcommand (bool quiet, const char *module_regexp,
6905 const char *regexp, const char *type_regexp,
6906 domain_search_flags kind)
6908 gdb_assert (kind == SEARCH_FUNCTION_DOMAIN || kind == SEARCH_VAR_DOMAIN);
6910 /* Print a header line. Don't build the header line bit by bit as this
6911 prevents internationalisation. */
6912 if (!quiet)
6914 if (module_regexp == nullptr)
6916 if (type_regexp == nullptr)
6918 if (regexp == nullptr)
6919 gdb_printf ((kind == SEARCH_VAR_DOMAIN
6920 ? _("All variables in all modules:")
6921 : _("All functions in all modules:")));
6922 else
6923 gdb_printf
6924 ((kind == SEARCH_VAR_DOMAIN
6925 ? _("All variables matching regular expression"
6926 " \"%s\" in all modules:")
6927 : _("All functions matching regular expression"
6928 " \"%s\" in all modules:")),
6929 regexp);
6931 else
6933 if (regexp == nullptr)
6934 gdb_printf
6935 ((kind == SEARCH_VAR_DOMAIN
6936 ? _("All variables with type matching regular "
6937 "expression \"%s\" in all modules:")
6938 : _("All functions with type matching regular "
6939 "expression \"%s\" in all modules:")),
6940 type_regexp);
6941 else
6942 gdb_printf
6943 ((kind == SEARCH_VAR_DOMAIN
6944 ? _("All variables matching regular expression "
6945 "\"%s\",\n\twith type matching regular "
6946 "expression \"%s\" in all modules:")
6947 : _("All functions matching regular expression "
6948 "\"%s\",\n\twith type matching regular "
6949 "expression \"%s\" in all modules:")),
6950 regexp, type_regexp);
6953 else
6955 if (type_regexp == nullptr)
6957 if (regexp == nullptr)
6958 gdb_printf
6959 ((kind == SEARCH_VAR_DOMAIN
6960 ? _("All variables in all modules matching regular "
6961 "expression \"%s\":")
6962 : _("All functions in all modules matching regular "
6963 "expression \"%s\":")),
6964 module_regexp);
6965 else
6966 gdb_printf
6967 ((kind == SEARCH_VAR_DOMAIN
6968 ? _("All variables matching regular expression "
6969 "\"%s\",\n\tin all modules matching regular "
6970 "expression \"%s\":")
6971 : _("All functions matching regular expression "
6972 "\"%s\",\n\tin all modules matching regular "
6973 "expression \"%s\":")),
6974 regexp, module_regexp);
6976 else
6978 if (regexp == nullptr)
6979 gdb_printf
6980 ((kind == SEARCH_VAR_DOMAIN
6981 ? _("All variables with type matching regular "
6982 "expression \"%s\"\n\tin all modules matching "
6983 "regular expression \"%s\":")
6984 : _("All functions with type matching regular "
6985 "expression \"%s\"\n\tin all modules matching "
6986 "regular expression \"%s\":")),
6987 type_regexp, module_regexp);
6988 else
6989 gdb_printf
6990 ((kind == SEARCH_VAR_DOMAIN
6991 ? _("All variables matching regular expression "
6992 "\"%s\",\n\twith type matching regular expression "
6993 "\"%s\",\n\tin all modules matching regular "
6994 "expression \"%s\":")
6995 : _("All functions matching regular expression "
6996 "\"%s\",\n\twith type matching regular expression "
6997 "\"%s\",\n\tin all modules matching regular "
6998 "expression \"%s\":")),
6999 regexp, type_regexp, module_regexp);
7002 gdb_printf ("\n");
7005 /* Find all symbols of type KIND matching the given regular expressions
7006 along with the symbols for the modules in which those symbols
7007 reside. */
7008 std::vector<module_symbol_search> module_symbols
7009 = search_module_symbols (module_regexp, regexp, type_regexp, kind);
7011 std::sort (module_symbols.begin (), module_symbols.end (),
7012 [] (const module_symbol_search &a, const module_symbol_search &b)
7014 if (a.first < b.first)
7015 return true;
7016 else if (a.first == b.first)
7017 return a.second < b.second;
7018 else
7019 return false;
7022 const char *last_filename = "";
7023 const symbol *last_module_symbol = nullptr;
7024 for (const module_symbol_search &ms : module_symbols)
7026 const symbol_search &p = ms.first;
7027 const symbol_search &q = ms.second;
7029 gdb_assert (q.symbol != nullptr);
7031 if (last_module_symbol != p.symbol)
7033 gdb_printf ("\n");
7034 gdb_printf (_("Module \"%s\":\n"), p.symbol->print_name ());
7035 last_module_symbol = p.symbol;
7036 last_filename = "";
7039 print_symbol_info (q.symbol, q.block, last_filename);
7040 last_filename
7041 = symtab_to_filename_for_display (q.symbol->symtab ());
7045 /* Hold the option values for the 'info module .....' sub-commands. */
7047 struct info_modules_var_func_options
7049 bool quiet = false;
7050 std::string type_regexp;
7051 std::string module_regexp;
7054 /* The options used by 'info module variables' and 'info module functions'
7055 commands. */
7057 static const gdb::option::option_def info_modules_var_func_options_defs [] = {
7058 gdb::option::boolean_option_def<info_modules_var_func_options> {
7059 "q",
7060 [] (info_modules_var_func_options *opt) { return &opt->quiet; },
7061 nullptr, /* show_cmd_cb */
7062 nullptr /* set_doc */
7065 gdb::option::string_option_def<info_modules_var_func_options> {
7066 "t",
7067 [] (info_modules_var_func_options *opt) { return &opt->type_regexp; },
7068 nullptr, /* show_cmd_cb */
7069 nullptr /* set_doc */
7072 gdb::option::string_option_def<info_modules_var_func_options> {
7073 "m",
7074 [] (info_modules_var_func_options *opt) { return &opt->module_regexp; },
7075 nullptr, /* show_cmd_cb */
7076 nullptr /* set_doc */
7080 /* Return the option group used by the 'info module ...' sub-commands. */
7082 static inline gdb::option::option_def_group
7083 make_info_modules_var_func_options_def_group
7084 (info_modules_var_func_options *opts)
7086 return {{info_modules_var_func_options_defs}, opts};
7089 /* Implements the 'info module functions' command. */
7091 static void
7092 info_module_functions_command (const char *args, int from_tty)
7094 info_modules_var_func_options opts;
7095 auto grp = make_info_modules_var_func_options_def_group (&opts);
7096 gdb::option::process_options
7097 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
7098 if (args != nullptr && *args == '\0')
7099 args = nullptr;
7101 info_module_subcommand
7102 (opts.quiet,
7103 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
7104 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
7105 SEARCH_FUNCTION_DOMAIN);
7108 /* Implements the 'info module variables' command. */
7110 static void
7111 info_module_variables_command (const char *args, int from_tty)
7113 info_modules_var_func_options opts;
7114 auto grp = make_info_modules_var_func_options_def_group (&opts);
7115 gdb::option::process_options
7116 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
7117 if (args != nullptr && *args == '\0')
7118 args = nullptr;
7120 info_module_subcommand
7121 (opts.quiet,
7122 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
7123 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
7124 SEARCH_VAR_DOMAIN);
7127 /* Command completer for 'info module ...' sub-commands. */
7129 static void
7130 info_module_var_func_command_completer (struct cmd_list_element *ignore,
7131 completion_tracker &tracker,
7132 const char *text,
7133 const char * /* word */)
7136 const auto group = make_info_modules_var_func_options_def_group (nullptr);
7137 if (gdb::option::complete_options
7138 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
7139 return;
7141 const char *word = advance_to_expression_complete_word_point (tracker, text);
7142 symbol_completer (ignore, tracker, text, word);
7147 void _initialize_symtab ();
7148 void
7149 _initialize_symtab ()
7151 cmd_list_element *c;
7153 initialize_ordinary_address_classes ();
7155 c = add_info ("variables", info_variables_command,
7156 info_print_args_help (_("\
7157 All global and static variable names or those matching REGEXPs.\n\
7158 Usage: info variables [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7159 Prints the global and static variables.\n"),
7160 _("global and static variables"),
7161 true));
7162 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7164 c = add_info ("functions", info_functions_command,
7165 info_print_args_help (_("\
7166 All function names or those matching REGEXPs.\n\
7167 Usage: info functions [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
7168 Prints the functions.\n"),
7169 _("functions"),
7170 true));
7171 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
7173 c = add_info ("types", info_types_command, _("\
7174 All type names, or those matching REGEXP.\n\
7175 Usage: info types [-q] [REGEXP]\n\
7176 Print information about all types matching REGEXP, or all types if no\n\
7177 REGEXP is given. The optional flag -q disables printing of headers."));
7178 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7180 const auto info_sources_opts
7181 = make_info_sources_options_def_group (nullptr);
7183 static std::string info_sources_help
7184 = gdb::option::build_help (_("\
7185 All source files in the program or those matching REGEXP.\n\
7186 Usage: info sources [OPTION]... [REGEXP]\n\
7187 By default, REGEXP is used to match anywhere in the filename.\n\
7189 Options:\n\
7190 %OPTIONS%"),
7191 info_sources_opts);
7193 c = add_info ("sources", info_sources_command, info_sources_help.c_str ());
7194 set_cmd_completer_handle_brkchars (c, info_sources_command_completer);
7196 c = add_info ("modules", info_modules_command,
7197 _("All module names, or those matching REGEXP."));
7198 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
7200 add_info ("main", info_main_command,
7201 _("Get main symbol to identify entry point into program."));
7203 add_basic_prefix_cmd ("module", class_info, _("\
7204 Print information about modules."),
7205 &info_module_cmdlist, 0, &infolist);
7207 c = add_cmd ("functions", class_info, info_module_functions_command, _("\
7208 Display functions arranged by modules.\n\
7209 Usage: info module functions [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7210 Print a summary of all functions within each Fortran module, grouped by\n\
7211 module and file. For each function the line on which the function is\n\
7212 defined is given along with the type signature and name of the function.\n\
7214 If REGEXP is provided then only functions whose name matches REGEXP are\n\
7215 listed. If MODREGEXP is provided then only functions in modules matching\n\
7216 MODREGEXP are listed. If TYPEREGEXP is given then only functions whose\n\
7217 type signature matches TYPEREGEXP are listed.\n\
7219 The -q flag suppresses printing some header information."),
7220 &info_module_cmdlist);
7221 set_cmd_completer_handle_brkchars
7222 (c, info_module_var_func_command_completer);
7224 c = add_cmd ("variables", class_info, info_module_variables_command, _("\
7225 Display variables arranged by modules.\n\
7226 Usage: info module variables [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
7227 Print a summary of all variables within each Fortran module, grouped by\n\
7228 module and file. For each variable the line on which the variable is\n\
7229 defined is given along with the type and name of the variable.\n\
7231 If REGEXP is provided then only variables whose name matches REGEXP are\n\
7232 listed. If MODREGEXP is provided then only variables in modules matching\n\
7233 MODREGEXP are listed. If TYPEREGEXP is given then only variables whose\n\
7234 type matches TYPEREGEXP are listed.\n\
7236 The -q flag suppresses printing some header information."),
7237 &info_module_cmdlist);
7238 set_cmd_completer_handle_brkchars
7239 (c, info_module_var_func_command_completer);
7241 add_com ("rbreak", class_breakpoint, rbreak_command,
7242 _("Set a breakpoint for all functions matching REGEXP."));
7244 add_setshow_enum_cmd ("multiple-symbols", no_class,
7245 multiple_symbols_modes, &multiple_symbols_mode,
7246 _("\
7247 Set how the debugger handles ambiguities in expressions."), _("\
7248 Show how the debugger handles ambiguities in expressions."), _("\
7249 Valid values are \"ask\", \"all\", \"cancel\", and the default is \"all\"."),
7250 NULL, NULL, &setlist, &showlist);
7252 add_setshow_boolean_cmd ("basenames-may-differ", class_obscure,
7253 &basenames_may_differ, _("\
7254 Set whether a source file may have multiple base names."), _("\
7255 Show whether a source file may have multiple base names."), _("\
7256 (A \"base name\" is the name of a file with the directory part removed.\n\
7257 Example: The base name of \"/home/user/hello.c\" is \"hello.c\".)\n\
7258 If set, GDB will canonicalize file names (e.g., expand symlinks)\n\
7259 before comparing them. Canonicalization is an expensive operation,\n\
7260 but it allows the same file be known by more than one base name.\n\
7261 If not set (the default), all source files are assumed to have just\n\
7262 one base name, and gdb will do file name comparisons more efficiently."),
7263 NULL, NULL,
7264 &setlist, &showlist);
7266 add_setshow_zuinteger_cmd ("symtab-create", no_class, &symtab_create_debug,
7267 _("Set debugging of symbol table creation."),
7268 _("Show debugging of symbol table creation."), _("\
7269 When enabled (non-zero), debugging messages are printed when building\n\
7270 symbol tables. A value of 1 (one) normally provides enough information.\n\
7271 A value greater than 1 provides more verbose information."),
7272 NULL,
7273 NULL,
7274 &setdebuglist, &showdebuglist);
7276 add_setshow_zuinteger_cmd ("symbol-lookup", no_class, &symbol_lookup_debug,
7277 _("\
7278 Set debugging of symbol lookup."), _("\
7279 Show debugging of symbol lookup."), _("\
7280 When enabled (non-zero), symbol lookups are logged."),
7281 NULL, NULL,
7282 &setdebuglist, &showdebuglist);
7284 add_setshow_zuinteger_cmd ("symbol-cache-size", no_class,
7285 &new_symbol_cache_size,
7286 _("Set the size of the symbol cache."),
7287 _("Show the size of the symbol cache."), _("\
7288 The size of the symbol cache.\n\
7289 If zero then the symbol cache is disabled."),
7290 set_symbol_cache_size_handler, NULL,
7291 &maintenance_set_cmdlist,
7292 &maintenance_show_cmdlist);
7294 add_setshow_boolean_cmd ("ignore-prologue-end-flag", no_class,
7295 &ignore_prologue_end_flag,
7296 _("Set if the PROLOGUE-END flag is ignored."),
7297 _("Show if the PROLOGUE-END flag is ignored."),
7298 _("\
7299 The PROLOGUE-END flag from the line-table entries is used to place\n\
7300 breakpoints past the prologue of functions. Disabling its use forces\n\
7301 the use of prologue scanners."),
7302 nullptr, nullptr,
7303 &maintenance_set_cmdlist,
7304 &maintenance_show_cmdlist);
7307 add_cmd ("symbol-cache", class_maintenance, maintenance_print_symbol_cache,
7308 _("Dump the symbol cache for each program space."),
7309 &maintenanceprintlist);
7311 add_cmd ("symbol-cache-statistics", class_maintenance,
7312 maintenance_print_symbol_cache_statistics,
7313 _("Print symbol cache statistics for each program space."),
7314 &maintenanceprintlist);
7316 cmd_list_element *maintenance_flush_symbol_cache_cmd
7317 = add_cmd ("symbol-cache", class_maintenance,
7318 maintenance_flush_symbol_cache,
7319 _("Flush the symbol cache for each program space."),
7320 &maintenanceflushlist);
7321 c = add_alias_cmd ("flush-symbol-cache", maintenance_flush_symbol_cache_cmd,
7322 class_maintenance, 0, &maintenancelist);
7323 deprecate_cmd (c, "maintenance flush symbol-cache");
7325 gdb::observers::new_objfile.attach (symtab_new_objfile_observer, "symtab");
7326 gdb::observers::all_objfiles_removed.attach (symtab_all_objfiles_removed,
7327 "symtab");
7328 gdb::observers::free_objfile.attach (symtab_free_objfile_observer, "symtab");