]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/symtab.c
gdb: remove TYPE_FIELD_PACKED
[thirdparty/binutils-gdb.git] / gdb / symtab.c
... / ...
CommitLineData
1/* Symbol table lookup for the GNU debugger, GDB.
2
3 Copyright (C) 1986-2023 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20#include "defs.h"
21#include "dwarf2/call-site.h"
22#include "symtab.h"
23#include "gdbtypes.h"
24#include "gdbcore.h"
25#include "frame.h"
26#include "target.h"
27#include "value.h"
28#include "symfile.h"
29#include "objfiles.h"
30#include "gdbcmd.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" /* for FILENAME_CMP */
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
51#include "gdbsupport/gdb_obstack.h"
52#include "block.h"
53#include "dictionary.h"
54
55#include <sys/types.h>
56#include <fcntl.h>
57#include <sys/stat.h>
58#include <ctype.h>
59#include "cp-abi.h"
60#include "cp-support.h"
61#include "observable.h"
62#include "solist.h"
63#include "macrotab.h"
64#include "macroscope.h"
65
66#include "parser-defs.h"
67#include "completer.h"
68#include "progspace-and-thread.h"
69#include "gdbsupport/gdb_optional.h"
70#include "filename-seen-cache.h"
71#include "arch-utils.h"
72#include <algorithm>
73#include "gdbsupport/gdb_string_view.h"
74#include "gdbsupport/pathstuff.h"
75#include "gdbsupport/common-utils.h"
76
77/* Forward declarations for local functions. */
78
79static void rbreak_command (const char *, int);
80
81static int find_line_common (const linetable *, int, int *, int);
82
83static struct block_symbol
84 lookup_symbol_aux (const char *name,
85 symbol_name_match_type match_type,
86 const struct block *block,
87 const domain_enum domain,
88 enum language language,
89 struct field_of_this_result *);
90
91static
92struct block_symbol lookup_local_symbol (const char *name,
93 symbol_name_match_type match_type,
94 const struct block *block,
95 const domain_enum domain,
96 enum language language);
97
98static struct block_symbol
99 lookup_symbol_in_objfile (struct objfile *objfile,
100 enum block_enum block_index,
101 const char *name, const domain_enum domain);
102
103/* Type of the data stored on the program space. */
104
105struct main_info
106{
107 /* Name of "main". */
108
109 std::string name_of_main;
110
111 /* Language of "main". */
112
113 enum language language_of_main = language_unknown;
114};
115
116/* Program space key for finding name and language of "main". */
117
118static const registry<program_space>::key<main_info> main_progspace_key;
119
120/* The default symbol cache size.
121 There is no extra cpu cost for large N (except when flushing the cache,
122 which is rare). The value here is just a first attempt. A better default
123 value may be higher or lower. A prime number can make up for a bad hash
124 computation, so that's why the number is what it is. */
125#define DEFAULT_SYMBOL_CACHE_SIZE 1021
126
127/* The maximum symbol cache size.
128 There's no method to the decision of what value to use here, other than
129 there's no point in allowing a user typo to make gdb consume all memory. */
130#define MAX_SYMBOL_CACHE_SIZE (1024*1024)
131
132/* symbol_cache_lookup returns this if a previous lookup failed to find the
133 symbol in any objfile. */
134#define SYMBOL_LOOKUP_FAILED \
135 ((struct block_symbol) {(struct symbol *) 1, NULL})
136#define SYMBOL_LOOKUP_FAILED_P(SIB) (SIB.symbol == (struct symbol *) 1)
137
138/* Recording lookups that don't find the symbol is just as important, if not
139 more so, than recording found symbols. */
140
141enum symbol_cache_slot_state
142{
143 SYMBOL_SLOT_UNUSED,
144 SYMBOL_SLOT_NOT_FOUND,
145 SYMBOL_SLOT_FOUND
146};
147
148struct symbol_cache_slot
149{
150 enum symbol_cache_slot_state state;
151
152 /* The objfile that was current when the symbol was looked up.
153 This is only needed for global blocks, but for simplicity's sake
154 we allocate the space for both. If data shows the extra space used
155 for static blocks is a problem, we can split things up then.
156
157 Global blocks need cache lookup to include the objfile context because
158 we need to account for gdbarch_iterate_over_objfiles_in_search_order
159 which can traverse objfiles in, effectively, any order, depending on
160 the current objfile, thus affecting which symbol is found. Normally,
161 only the current objfile is searched first, and then the rest are
162 searched in recorded order; but putting cache lookup inside
163 gdbarch_iterate_over_objfiles_in_search_order would be awkward.
164 Instead we just make the current objfile part of the context of
165 cache lookup. This means we can record the same symbol multiple times,
166 each with a different "current objfile" that was in effect when the
167 lookup was saved in the cache, but cache space is pretty cheap. */
168 const struct objfile *objfile_context;
169
170 union
171 {
172 struct block_symbol found;
173 struct
174 {
175 char *name;
176 domain_enum domain;
177 } not_found;
178 } value;
179};
180
181/* Clear out SLOT. */
182
183static void
184symbol_cache_clear_slot (struct symbol_cache_slot *slot)
185{
186 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
187 xfree (slot->value.not_found.name);
188 slot->state = SYMBOL_SLOT_UNUSED;
189}
190
191/* Symbols don't specify global vs static block.
192 So keep them in separate caches. */
193
194struct block_symbol_cache
195{
196 unsigned int hits;
197 unsigned int misses;
198 unsigned int collisions;
199
200 /* SYMBOLS is a variable length array of this size.
201 One can imagine that in general one cache (global/static) should be a
202 fraction of the size of the other, but there's no data at the moment
203 on which to decide. */
204 unsigned int size;
205
206 struct symbol_cache_slot symbols[1];
207};
208
209/* Clear all slots of BSC and free BSC. */
210
211static void
212destroy_block_symbol_cache (struct block_symbol_cache *bsc)
213{
214 if (bsc != nullptr)
215 {
216 for (unsigned int i = 0; i < bsc->size; i++)
217 symbol_cache_clear_slot (&bsc->symbols[i]);
218 xfree (bsc);
219 }
220}
221
222/* The symbol cache.
223
224 Searching for symbols in the static and global blocks over multiple objfiles
225 again and again can be slow, as can searching very big objfiles. This is a
226 simple cache to improve symbol lookup performance, which is critical to
227 overall gdb performance.
228
229 Symbols are hashed on the name, its domain, and block.
230 They are also hashed on their objfile for objfile-specific lookups. */
231
232struct symbol_cache
233{
234 symbol_cache () = default;
235
236 ~symbol_cache ()
237 {
238 destroy_block_symbol_cache (global_symbols);
239 destroy_block_symbol_cache (static_symbols);
240 }
241
242 struct block_symbol_cache *global_symbols = nullptr;
243 struct block_symbol_cache *static_symbols = nullptr;
244};
245
246/* Program space key for finding its symbol cache. */
247
248static const registry<program_space>::key<symbol_cache> symbol_cache_key;
249
250/* When non-zero, print debugging messages related to symtab creation. */
251unsigned int symtab_create_debug = 0;
252
253/* When non-zero, print debugging messages related to symbol lookup. */
254unsigned int symbol_lookup_debug = 0;
255
256/* The size of the cache is staged here. */
257static unsigned int new_symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
258
259/* The current value of the symbol cache size.
260 This is saved so that if the user enters a value too big we can restore
261 the original value from here. */
262static unsigned int symbol_cache_size = DEFAULT_SYMBOL_CACHE_SIZE;
263
264/* True if a file may be known by two different basenames.
265 This is the uncommon case, and significantly slows down gdb.
266 Default set to "off" to not slow down the common case. */
267bool basenames_may_differ = false;
268
269/* Allow the user to configure the debugger behavior with respect
270 to multiple-choice menus when more than one symbol matches during
271 a symbol lookup. */
272
273const char multiple_symbols_ask[] = "ask";
274const char multiple_symbols_all[] = "all";
275const char multiple_symbols_cancel[] = "cancel";
276static const char *const multiple_symbols_modes[] =
277{
278 multiple_symbols_ask,
279 multiple_symbols_all,
280 multiple_symbols_cancel,
281 NULL
282};
283static const char *multiple_symbols_mode = multiple_symbols_all;
284
285/* When TRUE, ignore the prologue-end flag in linetable_entry when searching
286 for the SAL past a function prologue. */
287static bool ignore_prologue_end_flag = false;
288
289/* Read-only accessor to AUTO_SELECT_MODE. */
290
291const char *
292multiple_symbols_select_mode (void)
293{
294 return multiple_symbols_mode;
295}
296
297/* Return the name of a domain_enum. */
298
299const char *
300domain_name (domain_enum e)
301{
302 switch (e)
303 {
304 case UNDEF_DOMAIN: return "UNDEF_DOMAIN";
305 case VAR_DOMAIN: return "VAR_DOMAIN";
306 case STRUCT_DOMAIN: return "STRUCT_DOMAIN";
307 case MODULE_DOMAIN: return "MODULE_DOMAIN";
308 case LABEL_DOMAIN: return "LABEL_DOMAIN";
309 case COMMON_BLOCK_DOMAIN: return "COMMON_BLOCK_DOMAIN";
310 default: gdb_assert_not_reached ("bad domain_enum");
311 }
312}
313
314/* Return the name of a search_domain . */
315
316const char *
317search_domain_name (enum search_domain e)
318{
319 switch (e)
320 {
321 case VARIABLES_DOMAIN: return "VARIABLES_DOMAIN";
322 case FUNCTIONS_DOMAIN: return "FUNCTIONS_DOMAIN";
323 case TYPES_DOMAIN: return "TYPES_DOMAIN";
324 case MODULES_DOMAIN: return "MODULES_DOMAIN";
325 case ALL_DOMAIN: return "ALL_DOMAIN";
326 default: gdb_assert_not_reached ("bad search_domain");
327 }
328}
329
330/* See symtab.h. */
331
332CORE_ADDR
333linetable_entry::pc (const struct objfile *objfile) const
334{
335 return CORE_ADDR (m_pc) + objfile->text_section_offset ();
336}
337
338/* See symtab.h. */
339
340call_site *
341compunit_symtab::find_call_site (CORE_ADDR pc) const
342{
343 if (m_call_site_htab == nullptr)
344 return nullptr;
345
346 CORE_ADDR delta = this->objfile ()->text_section_offset ();
347 unrelocated_addr unrelocated_pc = (unrelocated_addr) (pc - delta);
348
349 struct call_site call_site_local (unrelocated_pc, nullptr, nullptr);
350 void **slot
351 = htab_find_slot (m_call_site_htab, &call_site_local, NO_INSERT);
352 if (slot != nullptr)
353 return (call_site *) *slot;
354
355 /* See if the arch knows another PC we should try. On some
356 platforms, GCC emits a DWARF call site that is offset from the
357 actual return location. */
358 struct gdbarch *arch = objfile ()->arch ();
359 CORE_ADDR new_pc = gdbarch_update_call_site_pc (arch, pc);
360 if (pc == new_pc)
361 return nullptr;
362
363 unrelocated_pc = (unrelocated_addr) (new_pc - delta);
364 call_site new_call_site_local (unrelocated_pc, nullptr, nullptr);
365 slot = htab_find_slot (m_call_site_htab, &new_call_site_local, NO_INSERT);
366 if (slot == nullptr)
367 return nullptr;
368
369 return (call_site *) *slot;
370}
371
372/* See symtab.h. */
373
374void
375compunit_symtab::set_call_site_htab (htab_t call_site_htab)
376{
377 gdb_assert (m_call_site_htab == nullptr);
378 m_call_site_htab = call_site_htab;
379}
380
381/* See symtab.h. */
382
383void
384compunit_symtab::set_primary_filetab (symtab *primary_filetab)
385{
386 symtab *prev_filetab = nullptr;
387
388 /* Move PRIMARY_FILETAB to the head of the filetab list. */
389 for (symtab *filetab : this->filetabs ())
390 {
391 if (filetab == primary_filetab)
392 {
393 if (prev_filetab != nullptr)
394 {
395 prev_filetab->next = primary_filetab->next;
396 primary_filetab->next = m_filetabs;
397 m_filetabs = primary_filetab;
398 }
399
400 break;
401 }
402
403 prev_filetab = filetab;
404 }
405
406 gdb_assert (primary_filetab == m_filetabs);
407}
408
409/* See symtab.h. */
410
411struct symtab *
412compunit_symtab::primary_filetab () const
413{
414 gdb_assert (m_filetabs != nullptr);
415
416 /* The primary file symtab is the first one in the list. */
417 return m_filetabs;
418}
419
420/* See symtab.h. */
421
422enum language
423compunit_symtab::language () const
424{
425 struct symtab *symtab = primary_filetab ();
426
427 /* The language of the compunit symtab is the language of its
428 primary source file. */
429 return symtab->language ();
430}
431
432/* The relocated address of the minimal symbol, using the section
433 offsets from OBJFILE. */
434
435CORE_ADDR
436minimal_symbol::value_address (objfile *objfile) const
437{
438 if (this->maybe_copied (objfile))
439 return get_msymbol_address (objfile, this);
440 else
441 return (CORE_ADDR (this->unrelocated_address ())
442 + objfile->section_offsets[this->section_index ()]);
443}
444
445/* See symtab.h. */
446
447bool
448minimal_symbol::data_p () const
449{
450 return m_type == mst_data
451 || m_type == mst_bss
452 || m_type == mst_abs
453 || m_type == mst_file_data
454 || m_type == mst_file_bss;
455}
456
457/* See symtab.h. */
458
459bool
460minimal_symbol::text_p () const
461{
462 return m_type == mst_text
463 || m_type == mst_text_gnu_ifunc
464 || m_type == mst_data_gnu_ifunc
465 || m_type == mst_slot_got_plt
466 || m_type == mst_solib_trampoline
467 || m_type == mst_file_text;
468}
469
470/* See symtab.h. */
471
472bool
473minimal_symbol::maybe_copied (objfile *objfile) const
474{
475 return (objfile->object_format_has_copy_relocs
476 && (objfile->flags & OBJF_MAINLINE) == 0
477 && (m_type == mst_data || m_type == mst_bss));
478}
479
480/* See whether FILENAME matches SEARCH_NAME using the rule that we
481 advertise to the user. (The manual's description of linespecs
482 describes what we advertise). Returns true if they match, false
483 otherwise. */
484
485bool
486compare_filenames_for_search (const char *filename, const char *search_name)
487{
488 int len = strlen (filename);
489 size_t search_len = strlen (search_name);
490
491 if (len < search_len)
492 return false;
493
494 /* The tail of FILENAME must match. */
495 if (FILENAME_CMP (filename + len - search_len, search_name) != 0)
496 return false;
497
498 /* Either the names must completely match, or the character
499 preceding the trailing SEARCH_NAME segment of FILENAME must be a
500 directory separator.
501
502 The check !IS_ABSOLUTE_PATH ensures SEARCH_NAME "/dir/file.c"
503 cannot match FILENAME "/path//dir/file.c" - as user has requested
504 absolute path. The sama applies for "c:\file.c" possibly
505 incorrectly hypothetically matching "d:\dir\c:\file.c".
506
507 The HAS_DRIVE_SPEC purpose is to make FILENAME "c:file.c"
508 compatible with SEARCH_NAME "file.c". In such case a compiler had
509 to put the "c:file.c" name into debug info. Such compatibility
510 works only on GDB built for DOS host. */
511 return (len == search_len
512 || (!IS_ABSOLUTE_PATH (search_name)
513 && IS_DIR_SEPARATOR (filename[len - search_len - 1]))
514 || (HAS_DRIVE_SPEC (filename)
515 && STRIP_DRIVE_SPEC (filename) == &filename[len - search_len]));
516}
517
518/* Same as compare_filenames_for_search, but for glob-style patterns.
519 Heads up on the order of the arguments. They match the order of
520 compare_filenames_for_search, but it's the opposite of the order of
521 arguments to gdb_filename_fnmatch. */
522
523bool
524compare_glob_filenames_for_search (const char *filename,
525 const char *search_name)
526{
527 /* We rely on the property of glob-style patterns with FNM_FILE_NAME that
528 all /s have to be explicitly specified. */
529 int file_path_elements = count_path_elements (filename);
530 int search_path_elements = count_path_elements (search_name);
531
532 if (search_path_elements > file_path_elements)
533 return false;
534
535 if (IS_ABSOLUTE_PATH (search_name))
536 {
537 return (search_path_elements == file_path_elements
538 && gdb_filename_fnmatch (search_name, filename,
539 FNM_FILE_NAME | FNM_NOESCAPE) == 0);
540 }
541
542 {
543 const char *file_to_compare
544 = strip_leading_path_elements (filename,
545 file_path_elements - search_path_elements);
546
547 return gdb_filename_fnmatch (search_name, file_to_compare,
548 FNM_FILE_NAME | FNM_NOESCAPE) == 0;
549 }
550}
551
552/* Check for a symtab of a specific name by searching some symtabs.
553 This is a helper function for callbacks of iterate_over_symtabs.
554
555 If NAME is not absolute, then REAL_PATH is NULL
556 If NAME is absolute, then REAL_PATH is the gdb_realpath form of NAME.
557
558 The return value, NAME, REAL_PATH and CALLBACK are identical to the
559 `map_symtabs_matching_filename' method of quick_symbol_functions.
560
561 FIRST and AFTER_LAST indicate the range of compunit symtabs to search.
562 Each symtab within the specified compunit symtab is also searched.
563 AFTER_LAST is one past the last compunit symtab to search; NULL means to
564 search until the end of the list. */
565
566bool
567iterate_over_some_symtabs (const char *name,
568 const char *real_path,
569 struct compunit_symtab *first,
570 struct compunit_symtab *after_last,
571 gdb::function_view<bool (symtab *)> callback)
572{
573 struct compunit_symtab *cust;
574 const char* base_name = lbasename (name);
575
576 for (cust = first; cust != NULL && cust != after_last; cust = cust->next)
577 {
578 for (symtab *s : cust->filetabs ())
579 {
580 if (compare_filenames_for_search (s->filename, name))
581 {
582 if (callback (s))
583 return true;
584 continue;
585 }
586
587 /* Before we invoke realpath, which can get expensive when many
588 files are involved, do a quick comparison of the basenames. */
589 if (! basenames_may_differ
590 && FILENAME_CMP (base_name, lbasename (s->filename)) != 0)
591 continue;
592
593 if (compare_filenames_for_search (symtab_to_fullname (s), name))
594 {
595 if (callback (s))
596 return true;
597 continue;
598 }
599
600 /* If the user gave us an absolute path, try to find the file in
601 this symtab and use its absolute path. */
602 if (real_path != NULL)
603 {
604 const char *fullname = symtab_to_fullname (s);
605
606 gdb_assert (IS_ABSOLUTE_PATH (real_path));
607 gdb_assert (IS_ABSOLUTE_PATH (name));
608 gdb::unique_xmalloc_ptr<char> fullname_real_path
609 = gdb_realpath (fullname);
610 fullname = fullname_real_path.get ();
611 if (FILENAME_CMP (real_path, fullname) == 0)
612 {
613 if (callback (s))
614 return true;
615 continue;
616 }
617 }
618 }
619 }
620
621 return false;
622}
623
624/* Check for a symtab of a specific name; first in symtabs, then in
625 psymtabs. *If* there is no '/' in the name, a match after a '/'
626 in the symtab filename will also work.
627
628 Calls CALLBACK with each symtab that is found. If CALLBACK returns
629 true, the search stops. */
630
631void
632iterate_over_symtabs (const char *name,
633 gdb::function_view<bool (symtab *)> callback)
634{
635 gdb::unique_xmalloc_ptr<char> real_path;
636
637 /* Here we are interested in canonicalizing an absolute path, not
638 absolutizing a relative path. */
639 if (IS_ABSOLUTE_PATH (name))
640 {
641 real_path = gdb_realpath (name);
642 gdb_assert (IS_ABSOLUTE_PATH (real_path.get ()));
643 }
644
645 for (objfile *objfile : current_program_space->objfiles ())
646 {
647 if (iterate_over_some_symtabs (name, real_path.get (),
648 objfile->compunit_symtabs, NULL,
649 callback))
650 return;
651 }
652
653 /* Same search rules as above apply here, but now we look thru the
654 psymtabs. */
655
656 for (objfile *objfile : current_program_space->objfiles ())
657 {
658 if (objfile->map_symtabs_matching_filename (name, real_path.get (),
659 callback))
660 return;
661 }
662}
663
664/* A wrapper for iterate_over_symtabs that returns the first matching
665 symtab, or NULL. */
666
667struct symtab *
668lookup_symtab (const char *name)
669{
670 struct symtab *result = NULL;
671
672 iterate_over_symtabs (name, [&] (symtab *symtab)
673 {
674 result = symtab;
675 return true;
676 });
677
678 return result;
679}
680
681\f
682/* Mangle a GDB method stub type. This actually reassembles the pieces of the
683 full method name, which consist of the class name (from T), the unadorned
684 method name from METHOD_ID, and the signature for the specific overload,
685 specified by SIGNATURE_ID. Note that this function is g++ specific. */
686
687char *
688gdb_mangle_name (struct type *type, int method_id, int signature_id)
689{
690 int mangled_name_len;
691 char *mangled_name;
692 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
693 struct fn_field *method = &f[signature_id];
694 const char *field_name = TYPE_FN_FIELDLIST_NAME (type, method_id);
695 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, signature_id);
696 const char *newname = type->name ();
697
698 /* Does the form of physname indicate that it is the full mangled name
699 of a constructor (not just the args)? */
700 int is_full_physname_constructor;
701
702 int is_constructor;
703 int is_destructor = is_destructor_name (physname);
704 /* Need a new type prefix. */
705 const char *const_prefix = method->is_const ? "C" : "";
706 const char *volatile_prefix = method->is_volatile ? "V" : "";
707 char buf[20];
708 int len = (newname == NULL ? 0 : strlen (newname));
709
710 /* Nothing to do if physname already contains a fully mangled v3 abi name
711 or an operator name. */
712 if ((physname[0] == '_' && physname[1] == 'Z')
713 || is_operator_name (field_name))
714 return xstrdup (physname);
715
716 is_full_physname_constructor = is_constructor_name (physname);
717
718 is_constructor = is_full_physname_constructor
719 || (newname && strcmp (field_name, newname) == 0);
720
721 if (!is_destructor)
722 is_destructor = (startswith (physname, "__dt"));
723
724 if (is_destructor || is_full_physname_constructor)
725 {
726 mangled_name = (char *) xmalloc (strlen (physname) + 1);
727 strcpy (mangled_name, physname);
728 return mangled_name;
729 }
730
731 if (len == 0)
732 {
733 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
734 }
735 else if (physname[0] == 't' || physname[0] == 'Q')
736 {
737 /* The physname for template and qualified methods already includes
738 the class name. */
739 xsnprintf (buf, sizeof (buf), "__%s%s", const_prefix, volatile_prefix);
740 newname = NULL;
741 len = 0;
742 }
743 else
744 {
745 xsnprintf (buf, sizeof (buf), "__%s%s%d", const_prefix,
746 volatile_prefix, len);
747 }
748 mangled_name_len = ((is_constructor ? 0 : strlen (field_name))
749 + strlen (buf) + len + strlen (physname) + 1);
750
751 mangled_name = (char *) xmalloc (mangled_name_len);
752 if (is_constructor)
753 mangled_name[0] = '\0';
754 else
755 strcpy (mangled_name, field_name);
756
757 strcat (mangled_name, buf);
758 /* If the class doesn't have a name, i.e. newname NULL, then we just
759 mangle it using 0 for the length of the class. Thus it gets mangled
760 as something starting with `::' rather than `classname::'. */
761 if (newname != NULL)
762 strcat (mangled_name, newname);
763
764 strcat (mangled_name, physname);
765 return (mangled_name);
766}
767
768/* See symtab.h. */
769
770void
771general_symbol_info::set_demangled_name (const char *name,
772 struct obstack *obstack)
773{
774 if (language () == language_ada)
775 {
776 if (name == NULL)
777 {
778 ada_mangled = 0;
779 language_specific.obstack = obstack;
780 }
781 else
782 {
783 ada_mangled = 1;
784 language_specific.demangled_name = name;
785 }
786 }
787 else
788 language_specific.demangled_name = name;
789}
790
791\f
792/* Initialize the language dependent portion of a symbol
793 depending upon the language for the symbol. */
794
795void
796general_symbol_info::set_language (enum language language,
797 struct obstack *obstack)
798{
799 m_language = language;
800 if (language == language_cplus
801 || language == language_d
802 || language == language_go
803 || language == language_objc
804 || language == language_fortran)
805 {
806 set_demangled_name (NULL, obstack);
807 }
808 else if (language == language_ada)
809 {
810 gdb_assert (ada_mangled == 0);
811 language_specific.obstack = obstack;
812 }
813 else
814 {
815 memset (&language_specific, 0, sizeof (language_specific));
816 }
817}
818
819/* Functions to initialize a symbol's mangled name. */
820
821/* Objects of this type are stored in the demangled name hash table. */
822struct demangled_name_entry
823{
824 demangled_name_entry (gdb::string_view mangled_name)
825 : mangled (mangled_name) {}
826
827 gdb::string_view mangled;
828 enum language language;
829 gdb::unique_xmalloc_ptr<char> demangled;
830};
831
832/* Hash function for the demangled name hash. */
833
834static hashval_t
835hash_demangled_name_entry (const void *data)
836{
837 const struct demangled_name_entry *e
838 = (const struct demangled_name_entry *) data;
839
840 return gdb::string_view_hash () (e->mangled);
841}
842
843/* Equality function for the demangled name hash. */
844
845static int
846eq_demangled_name_entry (const void *a, const void *b)
847{
848 const struct demangled_name_entry *da
849 = (const struct demangled_name_entry *) a;
850 const struct demangled_name_entry *db
851 = (const struct demangled_name_entry *) b;
852
853 return da->mangled == db->mangled;
854}
855
856static void
857free_demangled_name_entry (void *data)
858{
859 struct demangled_name_entry *e
860 = (struct demangled_name_entry *) data;
861
862 e->~demangled_name_entry();
863}
864
865/* Create the hash table used for demangled names. Each hash entry is
866 a pair of strings; one for the mangled name and one for the demangled
867 name. The entry is hashed via just the mangled name. */
868
869static void
870create_demangled_names_hash (struct objfile_per_bfd_storage *per_bfd)
871{
872 /* Choose 256 as the starting size of the hash table, somewhat arbitrarily.
873 The hash table code will round this up to the next prime number.
874 Choosing a much larger table size wastes memory, and saves only about
875 1% in symbol reading. However, if the minsym count is already
876 initialized (e.g. because symbol name setting was deferred to
877 a background thread) we can initialize the hashtable with a count
878 based on that, because we will almost certainly have at least that
879 many entries. If we have a nonzero number but less than 256,
880 we still stay with 256 to have some space for psymbols, etc. */
881
882 /* htab will expand the table when it is 3/4th full, so we account for that
883 here. +2 to round up. */
884 int minsym_based_count = (per_bfd->minimal_symbol_count + 2) / 3 * 4;
885 int count = std::max (per_bfd->minimal_symbol_count, minsym_based_count);
886
887 per_bfd->demangled_names_hash.reset (htab_create_alloc
888 (count, hash_demangled_name_entry, eq_demangled_name_entry,
889 free_demangled_name_entry, xcalloc, xfree));
890}
891
892/* See symtab.h */
893
894gdb::unique_xmalloc_ptr<char>
895symbol_find_demangled_name (struct general_symbol_info *gsymbol,
896 const char *mangled)
897{
898 gdb::unique_xmalloc_ptr<char> demangled;
899 int i;
900
901 if (gsymbol->language () != language_unknown)
902 {
903 const struct language_defn *lang = language_def (gsymbol->language ());
904
905 lang->sniff_from_mangled_name (mangled, &demangled);
906 return demangled;
907 }
908
909 for (i = language_unknown; i < nr_languages; ++i)
910 {
911 enum language l = (enum language) i;
912 const struct language_defn *lang = language_def (l);
913
914 if (lang->sniff_from_mangled_name (mangled, &demangled))
915 {
916 gsymbol->m_language = l;
917 return demangled;
918 }
919 }
920
921 return NULL;
922}
923
924/* Set both the mangled and demangled (if any) names for GSYMBOL based
925 on LINKAGE_NAME and LEN. Ordinarily, NAME is copied onto the
926 objfile's obstack; but if COPY_NAME is 0 and if NAME is
927 NUL-terminated, then this function assumes that NAME is already
928 correctly saved (either permanently or with a lifetime tied to the
929 objfile), and it will not be copied.
930
931 The hash table corresponding to OBJFILE is used, and the memory
932 comes from the per-BFD storage_obstack. LINKAGE_NAME is copied,
933 so the pointer can be discarded after calling this function. */
934
935void
936general_symbol_info::compute_and_set_names (gdb::string_view linkage_name,
937 bool copy_name,
938 objfile_per_bfd_storage *per_bfd,
939 gdb::optional<hashval_t> hash)
940{
941 struct demangled_name_entry **slot;
942
943 if (language () == language_ada)
944 {
945 /* In Ada, we do the symbol lookups using the mangled name, so
946 we can save some space by not storing the demangled name. */
947 if (!copy_name)
948 m_name = linkage_name.data ();
949 else
950 m_name = obstack_strndup (&per_bfd->storage_obstack,
951 linkage_name.data (),
952 linkage_name.length ());
953 set_demangled_name (NULL, &per_bfd->storage_obstack);
954
955 return;
956 }
957
958 if (per_bfd->demangled_names_hash == NULL)
959 create_demangled_names_hash (per_bfd);
960
961 struct demangled_name_entry entry (linkage_name);
962 if (!hash.has_value ())
963 hash = hash_demangled_name_entry (&entry);
964 slot = ((struct demangled_name_entry **)
965 htab_find_slot_with_hash (per_bfd->demangled_names_hash.get (),
966 &entry, *hash, INSERT));
967
968 /* The const_cast is safe because the only reason it is already
969 initialized is if we purposefully set it from a background
970 thread to avoid doing the work here. However, it is still
971 allocated from the heap and needs to be freed by us, just
972 like if we called symbol_find_demangled_name here. If this is
973 nullptr, we call symbol_find_demangled_name below, but we put
974 this smart pointer here to be sure that we don't leak this name. */
975 gdb::unique_xmalloc_ptr<char> demangled_name
976 (const_cast<char *> (language_specific.demangled_name));
977
978 /* If this name is not in the hash table, add it. */
979 if (*slot == NULL
980 /* A C version of the symbol may have already snuck into the table.
981 This happens to, e.g., main.init (__go_init_main). Cope. */
982 || (language () == language_go && (*slot)->demangled == nullptr))
983 {
984 /* A 0-terminated copy of the linkage name. Callers must set COPY_NAME
985 to true if the string might not be nullterminated. We have to make
986 this copy because demangling needs a nullterminated string. */
987 gdb::string_view linkage_name_copy;
988 if (copy_name)
989 {
990 char *alloc_name = (char *) alloca (linkage_name.length () + 1);
991 memcpy (alloc_name, linkage_name.data (), linkage_name.length ());
992 alloc_name[linkage_name.length ()] = '\0';
993
994 linkage_name_copy = gdb::string_view (alloc_name,
995 linkage_name.length ());
996 }
997 else
998 linkage_name_copy = linkage_name;
999
1000 if (demangled_name.get () == nullptr)
1001 demangled_name
1002 = symbol_find_demangled_name (this, linkage_name_copy.data ());
1003
1004 /* Suppose we have demangled_name==NULL, copy_name==0, and
1005 linkage_name_copy==linkage_name. In this case, we already have the
1006 mangled name saved, and we don't have a demangled name. So,
1007 you might think we could save a little space by not recording
1008 this in the hash table at all.
1009
1010 It turns out that it is actually important to still save such
1011 an entry in the hash table, because storing this name gives
1012 us better bcache hit rates for partial symbols. */
1013 if (!copy_name)
1014 {
1015 *slot
1016 = ((struct demangled_name_entry *)
1017 obstack_alloc (&per_bfd->storage_obstack,
1018 sizeof (demangled_name_entry)));
1019 new (*slot) demangled_name_entry (linkage_name);
1020 }
1021 else
1022 {
1023 /* If we must copy the mangled name, put it directly after
1024 the struct so we can have a single allocation. */
1025 *slot
1026 = ((struct demangled_name_entry *)
1027 obstack_alloc (&per_bfd->storage_obstack,
1028 sizeof (demangled_name_entry)
1029 + linkage_name.length () + 1));
1030 char *mangled_ptr = reinterpret_cast<char *> (*slot + 1);
1031 memcpy (mangled_ptr, linkage_name.data (), linkage_name.length ());
1032 mangled_ptr [linkage_name.length ()] = '\0';
1033 new (*slot) demangled_name_entry
1034 (gdb::string_view (mangled_ptr, linkage_name.length ()));
1035 }
1036 (*slot)->demangled = std::move (demangled_name);
1037 (*slot)->language = language ();
1038 }
1039 else if (language () == language_unknown)
1040 m_language = (*slot)->language;
1041
1042 m_name = (*slot)->mangled.data ();
1043 set_demangled_name ((*slot)->demangled.get (), &per_bfd->storage_obstack);
1044}
1045
1046/* See symtab.h. */
1047
1048const char *
1049general_symbol_info::natural_name () const
1050{
1051 switch (language ())
1052 {
1053 case language_cplus:
1054 case language_d:
1055 case language_go:
1056 case language_objc:
1057 case language_fortran:
1058 case language_rust:
1059 if (language_specific.demangled_name != nullptr)
1060 return language_specific.demangled_name;
1061 break;
1062 case language_ada:
1063 return ada_decode_symbol (this);
1064 default:
1065 break;
1066 }
1067 return linkage_name ();
1068}
1069
1070/* See symtab.h. */
1071
1072const char *
1073general_symbol_info::demangled_name () const
1074{
1075 const char *dem_name = NULL;
1076
1077 switch (language ())
1078 {
1079 case language_cplus:
1080 case language_d:
1081 case language_go:
1082 case language_objc:
1083 case language_fortran:
1084 case language_rust:
1085 dem_name = language_specific.demangled_name;
1086 break;
1087 case language_ada:
1088 dem_name = ada_decode_symbol (this);
1089 break;
1090 default:
1091 break;
1092 }
1093 return dem_name;
1094}
1095
1096/* See symtab.h. */
1097
1098const char *
1099general_symbol_info::search_name () const
1100{
1101 if (language () == language_ada)
1102 return linkage_name ();
1103 else
1104 return natural_name ();
1105}
1106
1107/* See symtab.h. */
1108
1109struct obj_section *
1110general_symbol_info::obj_section (const struct objfile *objfile) const
1111{
1112 if (section_index () >= 0)
1113 return &objfile->sections_start[section_index ()];
1114 return nullptr;
1115}
1116
1117/* See symtab.h. */
1118
1119bool
1120symbol_matches_search_name (const struct general_symbol_info *gsymbol,
1121 const lookup_name_info &name)
1122{
1123 symbol_name_matcher_ftype *name_match
1124 = language_def (gsymbol->language ())->get_symbol_name_matcher (name);
1125 return name_match (gsymbol->search_name (), name, NULL);
1126}
1127
1128\f
1129
1130/* Return true if the two sections are the same, or if they could
1131 plausibly be copies of each other, one in an original object
1132 file and another in a separated debug file. */
1133
1134bool
1135matching_obj_sections (struct obj_section *obj_first,
1136 struct obj_section *obj_second)
1137{
1138 asection *first = obj_first? obj_first->the_bfd_section : NULL;
1139 asection *second = obj_second? obj_second->the_bfd_section : NULL;
1140
1141 /* If they're the same section, then they match. */
1142 if (first == second)
1143 return true;
1144
1145 /* If either is NULL, give up. */
1146 if (first == NULL || second == NULL)
1147 return false;
1148
1149 /* This doesn't apply to absolute symbols. */
1150 if (first->owner == NULL || second->owner == NULL)
1151 return false;
1152
1153 /* If they're in the same object file, they must be different sections. */
1154 if (first->owner == second->owner)
1155 return false;
1156
1157 /* Check whether the two sections are potentially corresponding. They must
1158 have the same size, address, and name. We can't compare section indexes,
1159 which would be more reliable, because some sections may have been
1160 stripped. */
1161 if (bfd_section_size (first) != bfd_section_size (second))
1162 return false;
1163
1164 /* In-memory addresses may start at a different offset, relativize them. */
1165 if (bfd_section_vma (first) - bfd_get_start_address (first->owner)
1166 != bfd_section_vma (second) - bfd_get_start_address (second->owner))
1167 return false;
1168
1169 if (bfd_section_name (first) == NULL
1170 || bfd_section_name (second) == NULL
1171 || strcmp (bfd_section_name (first), bfd_section_name (second)) != 0)
1172 return false;
1173
1174 /* Otherwise check that they are in corresponding objfiles. */
1175
1176 struct objfile *obj = NULL;
1177 for (objfile *objfile : current_program_space->objfiles ())
1178 if (objfile->obfd == first->owner)
1179 {
1180 obj = objfile;
1181 break;
1182 }
1183 gdb_assert (obj != NULL);
1184
1185 if (obj->separate_debug_objfile != NULL
1186 && obj->separate_debug_objfile->obfd == second->owner)
1187 return true;
1188 if (obj->separate_debug_objfile_backlink != NULL
1189 && obj->separate_debug_objfile_backlink->obfd == second->owner)
1190 return true;
1191
1192 return false;
1193}
1194\f
1195/* Hash function for the symbol cache. */
1196
1197static unsigned int
1198hash_symbol_entry (const struct objfile *objfile_context,
1199 const char *name, domain_enum domain)
1200{
1201 unsigned int hash = (uintptr_t) objfile_context;
1202
1203 if (name != NULL)
1204 hash += htab_hash_string (name);
1205
1206 /* Because of symbol_matches_domain we need VAR_DOMAIN and STRUCT_DOMAIN
1207 to map to the same slot. */
1208 if (domain == STRUCT_DOMAIN)
1209 hash += VAR_DOMAIN * 7;
1210 else
1211 hash += domain * 7;
1212
1213 return hash;
1214}
1215
1216/* Equality function for the symbol cache. */
1217
1218static int
1219eq_symbol_entry (const struct symbol_cache_slot *slot,
1220 const struct objfile *objfile_context,
1221 const char *name, domain_enum domain)
1222{
1223 const char *slot_name;
1224 domain_enum slot_domain;
1225
1226 if (slot->state == SYMBOL_SLOT_UNUSED)
1227 return 0;
1228
1229 if (slot->objfile_context != objfile_context)
1230 return 0;
1231
1232 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1233 {
1234 slot_name = slot->value.not_found.name;
1235 slot_domain = slot->value.not_found.domain;
1236 }
1237 else
1238 {
1239 slot_name = slot->value.found.symbol->search_name ();
1240 slot_domain = slot->value.found.symbol->domain ();
1241 }
1242
1243 /* NULL names match. */
1244 if (slot_name == NULL && name == NULL)
1245 {
1246 /* But there's no point in calling symbol_matches_domain in the
1247 SYMBOL_SLOT_FOUND case. */
1248 if (slot_domain != domain)
1249 return 0;
1250 }
1251 else if (slot_name != NULL && name != NULL)
1252 {
1253 /* It's important that we use the same comparison that was done
1254 the first time through. If the slot records a found symbol,
1255 then this means using the symbol name comparison function of
1256 the symbol's language with symbol->search_name (). See
1257 dictionary.c. It also means using symbol_matches_domain for
1258 found symbols. See block.c.
1259
1260 If the slot records a not-found symbol, then require a precise match.
1261 We could still be lax with whitespace like strcmp_iw though. */
1262
1263 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1264 {
1265 if (strcmp (slot_name, name) != 0)
1266 return 0;
1267 if (slot_domain != domain)
1268 return 0;
1269 }
1270 else
1271 {
1272 struct symbol *sym = slot->value.found.symbol;
1273 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1274
1275 if (!symbol_matches_search_name (sym, lookup_name))
1276 return 0;
1277
1278 if (!symbol_matches_domain (sym->language (), slot_domain, domain))
1279 return 0;
1280 }
1281 }
1282 else
1283 {
1284 /* Only one name is NULL. */
1285 return 0;
1286 }
1287
1288 return 1;
1289}
1290
1291/* Given a cache of size SIZE, return the size of the struct (with variable
1292 length array) in bytes. */
1293
1294static size_t
1295symbol_cache_byte_size (unsigned int size)
1296{
1297 return (sizeof (struct block_symbol_cache)
1298 + ((size - 1) * sizeof (struct symbol_cache_slot)));
1299}
1300
1301/* Resize CACHE. */
1302
1303static void
1304resize_symbol_cache (struct symbol_cache *cache, unsigned int new_size)
1305{
1306 /* If there's no change in size, don't do anything.
1307 All caches have the same size, so we can just compare with the size
1308 of the global symbols cache. */
1309 if ((cache->global_symbols != NULL
1310 && cache->global_symbols->size == new_size)
1311 || (cache->global_symbols == NULL
1312 && new_size == 0))
1313 return;
1314
1315 destroy_block_symbol_cache (cache->global_symbols);
1316 destroy_block_symbol_cache (cache->static_symbols);
1317
1318 if (new_size == 0)
1319 {
1320 cache->global_symbols = NULL;
1321 cache->static_symbols = NULL;
1322 }
1323 else
1324 {
1325 size_t total_size = symbol_cache_byte_size (new_size);
1326
1327 cache->global_symbols
1328 = (struct block_symbol_cache *) xcalloc (1, total_size);
1329 cache->static_symbols
1330 = (struct block_symbol_cache *) xcalloc (1, total_size);
1331 cache->global_symbols->size = new_size;
1332 cache->static_symbols->size = new_size;
1333 }
1334}
1335
1336/* Return the symbol cache of PSPACE.
1337 Create one if it doesn't exist yet. */
1338
1339static struct symbol_cache *
1340get_symbol_cache (struct program_space *pspace)
1341{
1342 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1343
1344 if (cache == NULL)
1345 {
1346 cache = symbol_cache_key.emplace (pspace);
1347 resize_symbol_cache (cache, symbol_cache_size);
1348 }
1349
1350 return cache;
1351}
1352
1353/* Set the size of the symbol cache in all program spaces. */
1354
1355static void
1356set_symbol_cache_size (unsigned int new_size)
1357{
1358 for (struct program_space *pspace : program_spaces)
1359 {
1360 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1361
1362 /* The pspace could have been created but not have a cache yet. */
1363 if (cache != NULL)
1364 resize_symbol_cache (cache, new_size);
1365 }
1366}
1367
1368/* Called when symbol-cache-size is set. */
1369
1370static void
1371set_symbol_cache_size_handler (const char *args, int from_tty,
1372 struct cmd_list_element *c)
1373{
1374 if (new_symbol_cache_size > MAX_SYMBOL_CACHE_SIZE)
1375 {
1376 /* Restore the previous value.
1377 This is the value the "show" command prints. */
1378 new_symbol_cache_size = symbol_cache_size;
1379
1380 error (_("Symbol cache size is too large, max is %u."),
1381 MAX_SYMBOL_CACHE_SIZE);
1382 }
1383 symbol_cache_size = new_symbol_cache_size;
1384
1385 set_symbol_cache_size (symbol_cache_size);
1386}
1387
1388/* Lookup symbol NAME,DOMAIN in BLOCK in the symbol cache of PSPACE.
1389 OBJFILE_CONTEXT is the current objfile, which may be NULL.
1390 The result is the symbol if found, SYMBOL_LOOKUP_FAILED if a previous lookup
1391 failed (and thus this one will too), or NULL if the symbol is not present
1392 in the cache.
1393 *BSC_PTR and *SLOT_PTR are set to the cache and slot of the symbol, which
1394 can be used to save the result of a full lookup attempt. */
1395
1396static struct block_symbol
1397symbol_cache_lookup (struct symbol_cache *cache,
1398 struct objfile *objfile_context, enum block_enum block,
1399 const char *name, domain_enum domain,
1400 struct block_symbol_cache **bsc_ptr,
1401 struct symbol_cache_slot **slot_ptr)
1402{
1403 struct block_symbol_cache *bsc;
1404 unsigned int hash;
1405 struct symbol_cache_slot *slot;
1406
1407 if (block == GLOBAL_BLOCK)
1408 bsc = cache->global_symbols;
1409 else
1410 bsc = cache->static_symbols;
1411 if (bsc == NULL)
1412 {
1413 *bsc_ptr = NULL;
1414 *slot_ptr = NULL;
1415 return {};
1416 }
1417
1418 hash = hash_symbol_entry (objfile_context, name, domain);
1419 slot = bsc->symbols + hash % bsc->size;
1420
1421 *bsc_ptr = bsc;
1422 *slot_ptr = slot;
1423
1424 if (eq_symbol_entry (slot, objfile_context, name, domain))
1425 {
1426 symbol_lookup_debug_printf ("%s block symbol cache hit%s for %s, %s",
1427 block == GLOBAL_BLOCK ? "Global" : "Static",
1428 slot->state == SYMBOL_SLOT_NOT_FOUND
1429 ? " (not found)" : "", name,
1430 domain_name (domain));
1431 ++bsc->hits;
1432 if (slot->state == SYMBOL_SLOT_NOT_FOUND)
1433 return SYMBOL_LOOKUP_FAILED;
1434 return slot->value.found;
1435 }
1436
1437 /* Symbol is not present in the cache. */
1438
1439 symbol_lookup_debug_printf ("%s block symbol cache miss for %s, %s",
1440 block == GLOBAL_BLOCK ? "Global" : "Static",
1441 name, domain_name (domain));
1442 ++bsc->misses;
1443 return {};
1444}
1445
1446/* Mark SYMBOL as found in SLOT.
1447 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1448 if it's not needed to distinguish lookups (STATIC_BLOCK). It is *not*
1449 necessarily the objfile the symbol was found in. */
1450
1451static void
1452symbol_cache_mark_found (struct block_symbol_cache *bsc,
1453 struct symbol_cache_slot *slot,
1454 struct objfile *objfile_context,
1455 struct symbol *symbol,
1456 const struct block *block)
1457{
1458 if (bsc == NULL)
1459 return;
1460 if (slot->state != SYMBOL_SLOT_UNUSED)
1461 {
1462 ++bsc->collisions;
1463 symbol_cache_clear_slot (slot);
1464 }
1465 slot->state = SYMBOL_SLOT_FOUND;
1466 slot->objfile_context = objfile_context;
1467 slot->value.found.symbol = symbol;
1468 slot->value.found.block = block;
1469}
1470
1471/* Mark symbol NAME, DOMAIN as not found in SLOT.
1472 OBJFILE_CONTEXT is the current objfile when the lookup was done, or NULL
1473 if it's not needed to distinguish lookups (STATIC_BLOCK). */
1474
1475static void
1476symbol_cache_mark_not_found (struct block_symbol_cache *bsc,
1477 struct symbol_cache_slot *slot,
1478 struct objfile *objfile_context,
1479 const char *name, domain_enum domain)
1480{
1481 if (bsc == NULL)
1482 return;
1483 if (slot->state != SYMBOL_SLOT_UNUSED)
1484 {
1485 ++bsc->collisions;
1486 symbol_cache_clear_slot (slot);
1487 }
1488 slot->state = SYMBOL_SLOT_NOT_FOUND;
1489 slot->objfile_context = objfile_context;
1490 slot->value.not_found.name = xstrdup (name);
1491 slot->value.not_found.domain = domain;
1492}
1493
1494/* Flush the symbol cache of PSPACE. */
1495
1496static void
1497symbol_cache_flush (struct program_space *pspace)
1498{
1499 struct symbol_cache *cache = symbol_cache_key.get (pspace);
1500 int pass;
1501
1502 if (cache == NULL)
1503 return;
1504 if (cache->global_symbols == NULL)
1505 {
1506 gdb_assert (symbol_cache_size == 0);
1507 gdb_assert (cache->static_symbols == NULL);
1508 return;
1509 }
1510
1511 /* If the cache is untouched since the last flush, early exit.
1512 This is important for performance during the startup of a program linked
1513 with 100s (or 1000s) of shared libraries. */
1514 if (cache->global_symbols->misses == 0
1515 && cache->static_symbols->misses == 0)
1516 return;
1517
1518 gdb_assert (cache->global_symbols->size == symbol_cache_size);
1519 gdb_assert (cache->static_symbols->size == symbol_cache_size);
1520
1521 for (pass = 0; pass < 2; ++pass)
1522 {
1523 struct block_symbol_cache *bsc
1524 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1525 unsigned int i;
1526
1527 for (i = 0; i < bsc->size; ++i)
1528 symbol_cache_clear_slot (&bsc->symbols[i]);
1529 }
1530
1531 cache->global_symbols->hits = 0;
1532 cache->global_symbols->misses = 0;
1533 cache->global_symbols->collisions = 0;
1534 cache->static_symbols->hits = 0;
1535 cache->static_symbols->misses = 0;
1536 cache->static_symbols->collisions = 0;
1537}
1538
1539/* Dump CACHE. */
1540
1541static void
1542symbol_cache_dump (const struct symbol_cache *cache)
1543{
1544 int pass;
1545
1546 if (cache->global_symbols == NULL)
1547 {
1548 gdb_printf (" <disabled>\n");
1549 return;
1550 }
1551
1552 for (pass = 0; pass < 2; ++pass)
1553 {
1554 const struct block_symbol_cache *bsc
1555 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1556 unsigned int i;
1557
1558 if (pass == 0)
1559 gdb_printf ("Global symbols:\n");
1560 else
1561 gdb_printf ("Static symbols:\n");
1562
1563 for (i = 0; i < bsc->size; ++i)
1564 {
1565 const struct symbol_cache_slot *slot = &bsc->symbols[i];
1566
1567 QUIT;
1568
1569 switch (slot->state)
1570 {
1571 case SYMBOL_SLOT_UNUSED:
1572 break;
1573 case SYMBOL_SLOT_NOT_FOUND:
1574 gdb_printf (" [%4u] = %s, %s %s (not found)\n", i,
1575 host_address_to_string (slot->objfile_context),
1576 slot->value.not_found.name,
1577 domain_name (slot->value.not_found.domain));
1578 break;
1579 case SYMBOL_SLOT_FOUND:
1580 {
1581 struct symbol *found = slot->value.found.symbol;
1582 const struct objfile *context = slot->objfile_context;
1583
1584 gdb_printf (" [%4u] = %s, %s %s\n", i,
1585 host_address_to_string (context),
1586 found->print_name (),
1587 domain_name (found->domain ()));
1588 break;
1589 }
1590 }
1591 }
1592 }
1593}
1594
1595/* The "mt print symbol-cache" command. */
1596
1597static void
1598maintenance_print_symbol_cache (const char *args, int from_tty)
1599{
1600 for (struct program_space *pspace : program_spaces)
1601 {
1602 struct symbol_cache *cache;
1603
1604 gdb_printf (_("Symbol cache for pspace %d\n%s:\n"),
1605 pspace->num,
1606 pspace->symfile_object_file != NULL
1607 ? objfile_name (pspace->symfile_object_file)
1608 : "(no object file)");
1609
1610 /* If the cache hasn't been created yet, avoid creating one. */
1611 cache = symbol_cache_key.get (pspace);
1612 if (cache == NULL)
1613 gdb_printf (" <empty>\n");
1614 else
1615 symbol_cache_dump (cache);
1616 }
1617}
1618
1619/* The "mt flush-symbol-cache" command. */
1620
1621static void
1622maintenance_flush_symbol_cache (const char *args, int from_tty)
1623{
1624 for (struct program_space *pspace : program_spaces)
1625 {
1626 symbol_cache_flush (pspace);
1627 }
1628}
1629
1630/* Print usage statistics of CACHE. */
1631
1632static void
1633symbol_cache_stats (struct symbol_cache *cache)
1634{
1635 int pass;
1636
1637 if (cache->global_symbols == NULL)
1638 {
1639 gdb_printf (" <disabled>\n");
1640 return;
1641 }
1642
1643 for (pass = 0; pass < 2; ++pass)
1644 {
1645 const struct block_symbol_cache *bsc
1646 = pass == 0 ? cache->global_symbols : cache->static_symbols;
1647
1648 QUIT;
1649
1650 if (pass == 0)
1651 gdb_printf ("Global block cache stats:\n");
1652 else
1653 gdb_printf ("Static block cache stats:\n");
1654
1655 gdb_printf (" size: %u\n", bsc->size);
1656 gdb_printf (" hits: %u\n", bsc->hits);
1657 gdb_printf (" misses: %u\n", bsc->misses);
1658 gdb_printf (" collisions: %u\n", bsc->collisions);
1659 }
1660}
1661
1662/* The "mt print symbol-cache-statistics" command. */
1663
1664static void
1665maintenance_print_symbol_cache_statistics (const char *args, int from_tty)
1666{
1667 for (struct program_space *pspace : program_spaces)
1668 {
1669 struct symbol_cache *cache;
1670
1671 gdb_printf (_("Symbol cache statistics for pspace %d\n%s:\n"),
1672 pspace->num,
1673 pspace->symfile_object_file != NULL
1674 ? objfile_name (pspace->symfile_object_file)
1675 : "(no object file)");
1676
1677 /* If the cache hasn't been created yet, avoid creating one. */
1678 cache = symbol_cache_key.get (pspace);
1679 if (cache == NULL)
1680 gdb_printf (" empty, no stats available\n");
1681 else
1682 symbol_cache_stats (cache);
1683 }
1684}
1685
1686/* This module's 'new_objfile' observer. */
1687
1688static void
1689symtab_new_objfile_observer (struct objfile *objfile)
1690{
1691 /* Ideally we'd use OBJFILE->pspace, but OBJFILE may be NULL. */
1692 symbol_cache_flush (current_program_space);
1693}
1694
1695/* This module's 'free_objfile' observer. */
1696
1697static void
1698symtab_free_objfile_observer (struct objfile *objfile)
1699{
1700 symbol_cache_flush (objfile->pspace);
1701}
1702\f
1703/* See symtab.h. */
1704
1705void
1706fixup_symbol_section (struct symbol *sym, struct objfile *objfile)
1707{
1708 gdb_assert (sym != nullptr);
1709 gdb_assert (sym->is_objfile_owned ());
1710 gdb_assert (objfile != nullptr);
1711 gdb_assert (sym->section_index () == -1);
1712
1713 /* Note that if this ends up as -1, fixup_section will handle that
1714 reasonably well. So, it's fine to use the objfile's section
1715 index without doing the check that is done by the wrapper macros
1716 like SECT_OFF_TEXT. */
1717 int fallback;
1718 switch (sym->aclass ())
1719 {
1720 case LOC_STATIC:
1721 fallback = objfile->sect_index_data;
1722 break;
1723
1724 case LOC_LABEL:
1725 fallback = objfile->sect_index_text;
1726 break;
1727
1728 default:
1729 /* Nothing else will be listed in the minsyms -- no use looking
1730 it up. */
1731 return;
1732 }
1733
1734 CORE_ADDR addr = sym->value_address ();
1735
1736 struct minimal_symbol *msym;
1737
1738 /* First, check whether a minimal symbol with the same name exists
1739 and points to the same address. The address check is required
1740 e.g. on PowerPC64, where the minimal symbol for a function will
1741 point to the function descriptor, while the debug symbol will
1742 point to the actual function code. */
1743 msym = lookup_minimal_symbol_by_pc_name (addr, sym->linkage_name (),
1744 objfile);
1745 if (msym)
1746 sym->set_section_index (msym->section_index ());
1747 else
1748 {
1749 /* Static, function-local variables do appear in the linker
1750 (minimal) symbols, but are frequently given names that won't
1751 be found via lookup_minimal_symbol(). E.g., it has been
1752 observed in frv-uclinux (ELF) executables that a static,
1753 function-local variable named "foo" might appear in the
1754 linker symbols as "foo.6" or "foo.3". Thus, there is no
1755 point in attempting to extend the lookup-by-name mechanism to
1756 handle this case due to the fact that there can be multiple
1757 names.
1758
1759 So, instead, search the section table when lookup by name has
1760 failed. The ``addr'' and ``endaddr'' fields may have already
1761 been relocated. If so, the relocation offset needs to be
1762 subtracted from these values when performing the comparison.
1763 We unconditionally subtract it, because, when no relocation
1764 has been performed, the value will simply be zero.
1765
1766 The address of the symbol whose section we're fixing up HAS
1767 NOT BEEN adjusted (relocated) yet. It can't have been since
1768 the section isn't yet known and knowing the section is
1769 necessary in order to add the correct relocation value. In
1770 other words, we wouldn't even be in this function (attempting
1771 to compute the section) if it were already known.
1772
1773 Note that it is possible to search the minimal symbols
1774 (subtracting the relocation value if necessary) to find the
1775 matching minimal symbol, but this is overkill and much less
1776 efficient. It is not necessary to find the matching minimal
1777 symbol, only its section.
1778
1779 Note that this technique (of doing a section table search)
1780 can fail when unrelocated section addresses overlap. For
1781 this reason, we still attempt a lookup by name prior to doing
1782 a search of the section table. */
1783
1784 for (obj_section *s : objfile->sections ())
1785 {
1786 if ((bfd_section_flags (s->the_bfd_section) & SEC_ALLOC) == 0)
1787 continue;
1788
1789 int idx = s - objfile->sections_start;
1790 CORE_ADDR offset = objfile->section_offsets[idx];
1791
1792 if (fallback == -1)
1793 fallback = idx;
1794
1795 if (s->addr () - offset <= addr && addr < s->endaddr () - offset)
1796 {
1797 sym->set_section_index (idx);
1798 return;
1799 }
1800 }
1801
1802 /* If we didn't find the section, assume it is in the first
1803 section. If there is no allocated section, then it hardly
1804 matters what we pick, so just pick zero. */
1805 if (fallback == -1)
1806 sym->set_section_index (0);
1807 else
1808 sym->set_section_index (fallback);
1809 }
1810}
1811
1812/* See symtab.h. */
1813
1814demangle_for_lookup_info::demangle_for_lookup_info
1815 (const lookup_name_info &lookup_name, language lang)
1816{
1817 demangle_result_storage storage;
1818
1819 if (lookup_name.ignore_parameters () && lang == language_cplus)
1820 {
1821 gdb::unique_xmalloc_ptr<char> without_params
1822 = cp_remove_params_if_any (lookup_name.c_str (),
1823 lookup_name.completion_mode ());
1824
1825 if (without_params != NULL)
1826 {
1827 if (lookup_name.match_type () != symbol_name_match_type::SEARCH_NAME)
1828 m_demangled_name = demangle_for_lookup (without_params.get (),
1829 lang, storage);
1830 return;
1831 }
1832 }
1833
1834 if (lookup_name.match_type () == symbol_name_match_type::SEARCH_NAME)
1835 m_demangled_name = lookup_name.c_str ();
1836 else
1837 m_demangled_name = demangle_for_lookup (lookup_name.c_str (),
1838 lang, storage);
1839}
1840
1841/* See symtab.h. */
1842
1843const lookup_name_info &
1844lookup_name_info::match_any ()
1845{
1846 /* Lookup any symbol that "" would complete. I.e., this matches all
1847 symbol names. */
1848 static const lookup_name_info lookup_name ("", symbol_name_match_type::FULL,
1849 true);
1850
1851 return lookup_name;
1852}
1853
1854/* Compute the demangled form of NAME as used by the various symbol
1855 lookup functions. The result can either be the input NAME
1856 directly, or a pointer to a buffer owned by the STORAGE object.
1857
1858 For Ada, this function just returns NAME, unmodified.
1859 Normally, Ada symbol lookups are performed using the encoded name
1860 rather than the demangled name, and so it might seem to make sense
1861 for this function to return an encoded version of NAME.
1862 Unfortunately, we cannot do this, because this function is used in
1863 circumstances where it is not appropriate to try to encode NAME.
1864 For instance, when displaying the frame info, we demangle the name
1865 of each parameter, and then perform a symbol lookup inside our
1866 function using that demangled name. In Ada, certain functions
1867 have internally-generated parameters whose name contain uppercase
1868 characters. Encoding those name would result in those uppercase
1869 characters to become lowercase, and thus cause the symbol lookup
1870 to fail. */
1871
1872const char *
1873demangle_for_lookup (const char *name, enum language lang,
1874 demangle_result_storage &storage)
1875{
1876 /* If we are using C++, D, or Go, demangle the name before doing a
1877 lookup, so we can always binary search. */
1878 if (lang == language_cplus)
1879 {
1880 gdb::unique_xmalloc_ptr<char> demangled_name
1881 = gdb_demangle (name, DMGL_ANSI | DMGL_PARAMS);
1882 if (demangled_name != NULL)
1883 return storage.set_malloc_ptr (std::move (demangled_name));
1884
1885 /* If we were given a non-mangled name, canonicalize it
1886 according to the language (so far only for C++). */
1887 gdb::unique_xmalloc_ptr<char> canon = cp_canonicalize_string (name);
1888 if (canon != nullptr)
1889 return storage.set_malloc_ptr (std::move (canon));
1890 }
1891 else if (lang == language_d)
1892 {
1893 gdb::unique_xmalloc_ptr<char> demangled_name = d_demangle (name, 0);
1894 if (demangled_name != NULL)
1895 return storage.set_malloc_ptr (std::move (demangled_name));
1896 }
1897 else if (lang == language_go)
1898 {
1899 gdb::unique_xmalloc_ptr<char> demangled_name
1900 = language_def (language_go)->demangle_symbol (name, 0);
1901 if (demangled_name != NULL)
1902 return storage.set_malloc_ptr (std::move (demangled_name));
1903 }
1904
1905 return name;
1906}
1907
1908/* See symtab.h. */
1909
1910unsigned int
1911search_name_hash (enum language language, const char *search_name)
1912{
1913 return language_def (language)->search_name_hash (search_name);
1914}
1915
1916/* See symtab.h.
1917
1918 This function (or rather its subordinates) have a bunch of loops and
1919 it would seem to be attractive to put in some QUIT's (though I'm not really
1920 sure whether it can run long enough to be really important). But there
1921 are a few calls for which it would appear to be bad news to quit
1922 out of here: e.g., find_proc_desc in alpha-mdebug-tdep.c. (Note
1923 that there is C++ code below which can error(), but that probably
1924 doesn't affect these calls since they are looking for a known
1925 variable and thus can probably assume it will never hit the C++
1926 code). */
1927
1928struct block_symbol
1929lookup_symbol_in_language (const char *name, const struct block *block,
1930 const domain_enum domain, enum language lang,
1931 struct field_of_this_result *is_a_field_of_this)
1932{
1933 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
1934
1935 demangle_result_storage storage;
1936 const char *modified_name = demangle_for_lookup (name, lang, storage);
1937
1938 return lookup_symbol_aux (modified_name,
1939 symbol_name_match_type::FULL,
1940 block, domain, lang,
1941 is_a_field_of_this);
1942}
1943
1944/* See symtab.h. */
1945
1946struct block_symbol
1947lookup_symbol (const char *name, const struct block *block,
1948 domain_enum domain,
1949 struct field_of_this_result *is_a_field_of_this)
1950{
1951 return lookup_symbol_in_language (name, block, domain,
1952 current_language->la_language,
1953 is_a_field_of_this);
1954}
1955
1956/* See symtab.h. */
1957
1958struct block_symbol
1959lookup_symbol_search_name (const char *search_name, const struct block *block,
1960 domain_enum domain)
1961{
1962 return lookup_symbol_aux (search_name, symbol_name_match_type::SEARCH_NAME,
1963 block, domain, language_asm, NULL);
1964}
1965
1966/* See symtab.h. */
1967
1968struct block_symbol
1969lookup_language_this (const struct language_defn *lang,
1970 const struct block *block)
1971{
1972 if (lang->name_of_this () == NULL || block == NULL)
1973 return {};
1974
1975 symbol_lookup_debug_printf_v ("lookup_language_this (%s, %s (objfile %s))",
1976 lang->name (), host_address_to_string (block),
1977 objfile_debug_name (block->objfile ()));
1978
1979 while (block)
1980 {
1981 struct symbol *sym;
1982
1983 sym = block_lookup_symbol (block, lang->name_of_this (),
1984 symbol_name_match_type::SEARCH_NAME,
1985 VAR_DOMAIN);
1986 if (sym != NULL)
1987 {
1988 symbol_lookup_debug_printf_v
1989 ("lookup_language_this (...) = %s (%s, block %s)",
1990 sym->print_name (), host_address_to_string (sym),
1991 host_address_to_string (block));
1992 return (struct block_symbol) {sym, block};
1993 }
1994 if (block->function ())
1995 break;
1996 block = block->superblock ();
1997 }
1998
1999 symbol_lookup_debug_printf_v ("lookup_language_this (...) = NULL");
2000 return {};
2001}
2002
2003/* Given TYPE, a structure/union,
2004 return 1 if the component named NAME from the ultimate target
2005 structure/union is defined, otherwise, return 0. */
2006
2007static int
2008check_field (struct type *type, const char *name,
2009 struct field_of_this_result *is_a_field_of_this)
2010{
2011 int i;
2012
2013 /* The type may be a stub. */
2014 type = check_typedef (type);
2015
2016 for (i = type->num_fields () - 1; i >= TYPE_N_BASECLASSES (type); i--)
2017 {
2018 const char *t_field_name = type->field (i).name ();
2019
2020 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2021 {
2022 is_a_field_of_this->type = type;
2023 is_a_field_of_this->field = &type->field (i);
2024 return 1;
2025 }
2026 }
2027
2028 /* C++: If it was not found as a data field, then try to return it
2029 as a pointer to a method. */
2030
2031 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
2032 {
2033 if (strcmp_iw (TYPE_FN_FIELDLIST_NAME (type, i), name) == 0)
2034 {
2035 is_a_field_of_this->type = type;
2036 is_a_field_of_this->fn_field = &TYPE_FN_FIELDLIST (type, i);
2037 return 1;
2038 }
2039 }
2040
2041 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2042 if (check_field (TYPE_BASECLASS (type, i), name, is_a_field_of_this))
2043 return 1;
2044
2045 return 0;
2046}
2047
2048/* Behave like lookup_symbol except that NAME is the natural name
2049 (e.g., demangled name) of the symbol that we're looking for. */
2050
2051static struct block_symbol
2052lookup_symbol_aux (const char *name, symbol_name_match_type match_type,
2053 const struct block *block,
2054 const domain_enum domain, enum language language,
2055 struct field_of_this_result *is_a_field_of_this)
2056{
2057 SYMBOL_LOOKUP_SCOPED_DEBUG_ENTER_EXIT;
2058
2059 struct block_symbol result;
2060 const struct language_defn *langdef;
2061
2062 if (symbol_lookup_debug)
2063 {
2064 struct objfile *objfile = (block == nullptr
2065 ? nullptr : block->objfile ());
2066
2067 symbol_lookup_debug_printf
2068 ("demangled symbol name = \"%s\", block @ %s (objfile %s)",
2069 name, host_address_to_string (block),
2070 objfile != NULL ? objfile_debug_name (objfile) : "NULL");
2071 symbol_lookup_debug_printf
2072 ("domain name = \"%s\", language = \"%s\")",
2073 domain_name (domain), language_str (language));
2074 }
2075
2076 /* Make sure we do something sensible with is_a_field_of_this, since
2077 the callers that set this parameter to some non-null value will
2078 certainly use it later. If we don't set it, the contents of
2079 is_a_field_of_this are undefined. */
2080 if (is_a_field_of_this != NULL)
2081 memset (is_a_field_of_this, 0, sizeof (*is_a_field_of_this));
2082
2083 /* Search specified block and its superiors. Don't search
2084 STATIC_BLOCK or GLOBAL_BLOCK. */
2085
2086 result = lookup_local_symbol (name, match_type, block, domain, language);
2087 if (result.symbol != NULL)
2088 {
2089 symbol_lookup_debug_printf
2090 ("found symbol @ %s (using lookup_local_symbol)",
2091 host_address_to_string (result.symbol));
2092 return result;
2093 }
2094
2095 /* If requested to do so by the caller and if appropriate for LANGUAGE,
2096 check to see if NAME is a field of `this'. */
2097
2098 langdef = language_def (language);
2099
2100 /* Don't do this check if we are searching for a struct. It will
2101 not be found by check_field, but will be found by other
2102 means. */
2103 if (is_a_field_of_this != NULL && domain != STRUCT_DOMAIN)
2104 {
2105 result = lookup_language_this (langdef, block);
2106
2107 if (result.symbol)
2108 {
2109 struct type *t = result.symbol->type ();
2110
2111 /* I'm not really sure that type of this can ever
2112 be typedefed; just be safe. */
2113 t = check_typedef (t);
2114 if (t->is_pointer_or_reference ())
2115 t = t->target_type ();
2116
2117 if (t->code () != TYPE_CODE_STRUCT
2118 && t->code () != TYPE_CODE_UNION)
2119 error (_("Internal error: `%s' is not an aggregate"),
2120 langdef->name_of_this ());
2121
2122 if (check_field (t, name, is_a_field_of_this))
2123 {
2124 symbol_lookup_debug_printf ("no symbol found");
2125 return {};
2126 }
2127 }
2128 }
2129
2130 /* Now do whatever is appropriate for LANGUAGE to look
2131 up static and global variables. */
2132
2133 result = langdef->lookup_symbol_nonlocal (name, block, domain);
2134 if (result.symbol != NULL)
2135 {
2136 symbol_lookup_debug_printf
2137 ("found symbol @ %s (using language lookup_symbol_nonlocal)",
2138 host_address_to_string (result.symbol));
2139 return result;
2140 }
2141
2142 /* Now search all static file-level symbols. Not strictly correct,
2143 but more useful than an error. */
2144
2145 result = lookup_static_symbol (name, domain);
2146 symbol_lookup_debug_printf
2147 ("found symbol @ %s (using lookup_static_symbol)",
2148 result.symbol != NULL ? host_address_to_string (result.symbol) : "NULL");
2149 return result;
2150}
2151
2152/* Check to see if the symbol is defined in BLOCK or its superiors.
2153 Don't search STATIC_BLOCK or GLOBAL_BLOCK. */
2154
2155static struct block_symbol
2156lookup_local_symbol (const char *name,
2157 symbol_name_match_type match_type,
2158 const struct block *block,
2159 const domain_enum domain,
2160 enum language language)
2161{
2162 if (block == nullptr)
2163 return {};
2164
2165 struct symbol *sym;
2166 const struct block *static_block = block->static_block ();
2167 const char *scope = block->scope ();
2168
2169 /* Check if it's a global block. */
2170 if (static_block == nullptr)
2171 return {};
2172
2173 while (block != static_block)
2174 {
2175 sym = lookup_symbol_in_block (name, match_type, block, domain);
2176 if (sym != NULL)
2177 return (struct block_symbol) {sym, block};
2178
2179 if (language == language_cplus || language == language_fortran)
2180 {
2181 struct block_symbol blocksym
2182 = cp_lookup_symbol_imports_or_template (scope, name, block,
2183 domain);
2184
2185 if (blocksym.symbol != NULL)
2186 return blocksym;
2187 }
2188
2189 if (block->function () != NULL && block->inlined_p ())
2190 break;
2191 block = block->superblock ();
2192 }
2193
2194 /* We've reached the end of the function without finding a result. */
2195
2196 return {};
2197}
2198
2199/* See symtab.h. */
2200
2201struct symbol *
2202lookup_symbol_in_block (const char *name, symbol_name_match_type match_type,
2203 const struct block *block,
2204 const domain_enum domain)
2205{
2206 struct symbol *sym;
2207
2208 if (symbol_lookup_debug)
2209 {
2210 struct objfile *objfile
2211 = block == nullptr ? nullptr : block->objfile ();
2212
2213 symbol_lookup_debug_printf_v
2214 ("lookup_symbol_in_block (%s, %s (objfile %s), %s)",
2215 name, host_address_to_string (block),
2216 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2217 domain_name (domain));
2218 }
2219
2220 sym = block_lookup_symbol (block, name, match_type, domain);
2221 if (sym)
2222 {
2223 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = %s",
2224 host_address_to_string (sym));
2225 return sym;
2226 }
2227
2228 symbol_lookup_debug_printf_v ("lookup_symbol_in_block (...) = NULL");
2229 return NULL;
2230}
2231
2232/* See symtab.h. */
2233
2234struct block_symbol
2235lookup_global_symbol_from_objfile (struct objfile *main_objfile,
2236 enum block_enum block_index,
2237 const char *name,
2238 const domain_enum domain)
2239{
2240 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2241
2242 for (objfile *objfile : main_objfile->separate_debug_objfiles ())
2243 {
2244 struct block_symbol result
2245 = lookup_symbol_in_objfile (objfile, block_index, name, domain);
2246
2247 if (result.symbol != nullptr)
2248 return result;
2249 }
2250
2251 return {};
2252}
2253
2254/* Check to see if the symbol is defined in one of the OBJFILE's
2255 symtabs. BLOCK_INDEX should be either GLOBAL_BLOCK or STATIC_BLOCK,
2256 depending on whether or not we want to search global symbols or
2257 static symbols. */
2258
2259static struct block_symbol
2260lookup_symbol_in_objfile_symtabs (struct objfile *objfile,
2261 enum block_enum block_index, const char *name,
2262 const domain_enum domain)
2263{
2264 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2265
2266 symbol_lookup_debug_printf_v
2267 ("lookup_symbol_in_objfile_symtabs (%s, %s, %s, %s)",
2268 objfile_debug_name (objfile),
2269 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2270 name, domain_name (domain));
2271
2272 struct block_symbol other;
2273 other.symbol = NULL;
2274 for (compunit_symtab *cust : objfile->compunits ())
2275 {
2276 const struct blockvector *bv;
2277 const struct block *block;
2278 struct block_symbol result;
2279
2280 bv = cust->blockvector ();
2281 block = bv->block (block_index);
2282 result.symbol = block_lookup_symbol_primary (block, name, domain);
2283 result.block = block;
2284 if (result.symbol == NULL)
2285 continue;
2286 if (best_symbol (result.symbol, domain))
2287 {
2288 other = result;
2289 break;
2290 }
2291 if (symbol_matches_domain (result.symbol->language (),
2292 result.symbol->domain (), domain))
2293 {
2294 struct symbol *better
2295 = better_symbol (other.symbol, result.symbol, domain);
2296 if (better != other.symbol)
2297 {
2298 other.symbol = better;
2299 other.block = block;
2300 }
2301 }
2302 }
2303
2304 if (other.symbol != NULL)
2305 {
2306 symbol_lookup_debug_printf_v
2307 ("lookup_symbol_in_objfile_symtabs (...) = %s (block %s)",
2308 host_address_to_string (other.symbol),
2309 host_address_to_string (other.block));
2310 return other;
2311 }
2312
2313 symbol_lookup_debug_printf_v
2314 ("lookup_symbol_in_objfile_symtabs (...) = NULL");
2315 return {};
2316}
2317
2318/* Wrapper around lookup_symbol_in_objfile_symtabs for search_symbols.
2319 Look up LINKAGE_NAME in DOMAIN in the global and static blocks of OBJFILE
2320 and all associated separate debug objfiles.
2321
2322 Normally we only look in OBJFILE, and not any separate debug objfiles
2323 because the outer loop will cause them to be searched too. This case is
2324 different. Here we're called from search_symbols where it will only
2325 call us for the objfile that contains a matching minsym. */
2326
2327static struct block_symbol
2328lookup_symbol_in_objfile_from_linkage_name (struct objfile *objfile,
2329 const char *linkage_name,
2330 domain_enum domain)
2331{
2332 enum language lang = current_language->la_language;
2333 struct objfile *main_objfile;
2334
2335 demangle_result_storage storage;
2336 const char *modified_name = demangle_for_lookup (linkage_name, lang, storage);
2337
2338 if (objfile->separate_debug_objfile_backlink)
2339 main_objfile = objfile->separate_debug_objfile_backlink;
2340 else
2341 main_objfile = objfile;
2342
2343 for (::objfile *cur_objfile : main_objfile->separate_debug_objfiles ())
2344 {
2345 struct block_symbol result;
2346
2347 result = lookup_symbol_in_objfile_symtabs (cur_objfile, GLOBAL_BLOCK,
2348 modified_name, domain);
2349 if (result.symbol == NULL)
2350 result = lookup_symbol_in_objfile_symtabs (cur_objfile, STATIC_BLOCK,
2351 modified_name, domain);
2352 if (result.symbol != NULL)
2353 return result;
2354 }
2355
2356 return {};
2357}
2358
2359/* A helper function that throws an exception when a symbol was found
2360 in a psymtab but not in a symtab. */
2361
2362static void ATTRIBUTE_NORETURN
2363error_in_psymtab_expansion (enum block_enum block_index, const char *name,
2364 struct compunit_symtab *cust)
2365{
2366 error (_("\
2367Internal: %s symbol `%s' found in %s psymtab but not in symtab.\n\
2368%s may be an inlined function, or may be a template function\n \
2369(if a template, try specifying an instantiation: %s<type>)."),
2370 block_index == GLOBAL_BLOCK ? "global" : "static",
2371 name,
2372 symtab_to_filename_for_display (cust->primary_filetab ()),
2373 name, name);
2374}
2375
2376/* A helper function for various lookup routines that interfaces with
2377 the "quick" symbol table functions. */
2378
2379static struct block_symbol
2380lookup_symbol_via_quick_fns (struct objfile *objfile,
2381 enum block_enum block_index, const char *name,
2382 const domain_enum domain)
2383{
2384 struct compunit_symtab *cust;
2385 const struct blockvector *bv;
2386 const struct block *block;
2387 struct block_symbol result;
2388
2389 symbol_lookup_debug_printf_v
2390 ("lookup_symbol_via_quick_fns (%s, %s, %s, %s)",
2391 objfile_debug_name (objfile),
2392 block_index == GLOBAL_BLOCK ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2393 name, domain_name (domain));
2394
2395 cust = objfile->lookup_symbol (block_index, name, domain);
2396 if (cust == NULL)
2397 {
2398 symbol_lookup_debug_printf_v
2399 ("lookup_symbol_via_quick_fns (...) = NULL");
2400 return {};
2401 }
2402
2403 bv = cust->blockvector ();
2404 block = bv->block (block_index);
2405 result.symbol = block_lookup_symbol (block, name,
2406 symbol_name_match_type::FULL, domain);
2407 if (result.symbol == NULL)
2408 error_in_psymtab_expansion (block_index, name, cust);
2409
2410 symbol_lookup_debug_printf_v
2411 ("lookup_symbol_via_quick_fns (...) = %s (block %s)",
2412 host_address_to_string (result.symbol),
2413 host_address_to_string (block));
2414
2415 result.block = block;
2416 return result;
2417}
2418
2419/* See language.h. */
2420
2421struct block_symbol
2422language_defn::lookup_symbol_nonlocal (const char *name,
2423 const struct block *block,
2424 const domain_enum domain) const
2425{
2426 struct block_symbol result;
2427
2428 /* NOTE: dje/2014-10-26: The lookup in all objfiles search could skip
2429 the current objfile. Searching the current objfile first is useful
2430 for both matching user expectations as well as performance. */
2431
2432 result = lookup_symbol_in_static_block (name, block, domain);
2433 if (result.symbol != NULL)
2434 return result;
2435
2436 /* If we didn't find a definition for a builtin type in the static block,
2437 search for it now. This is actually the right thing to do and can be
2438 a massive performance win. E.g., when debugging a program with lots of
2439 shared libraries we could search all of them only to find out the
2440 builtin type isn't defined in any of them. This is common for types
2441 like "void". */
2442 if (domain == VAR_DOMAIN)
2443 {
2444 struct gdbarch *gdbarch;
2445
2446 if (block == NULL)
2447 gdbarch = target_gdbarch ();
2448 else
2449 gdbarch = block->gdbarch ();
2450 result.symbol = language_lookup_primitive_type_as_symbol (this,
2451 gdbarch, name);
2452 result.block = NULL;
2453 if (result.symbol != NULL)
2454 return result;
2455 }
2456
2457 return lookup_global_symbol (name, block, domain);
2458}
2459
2460/* See symtab.h. */
2461
2462struct block_symbol
2463lookup_symbol_in_static_block (const char *name,
2464 const struct block *block,
2465 const domain_enum domain)
2466{
2467 if (block == nullptr)
2468 return {};
2469
2470 const struct block *static_block = block->static_block ();
2471 struct symbol *sym;
2472
2473 if (static_block == NULL)
2474 return {};
2475
2476 if (symbol_lookup_debug)
2477 {
2478 struct objfile *objfile = (block == nullptr
2479 ? nullptr : block->objfile ());
2480
2481 symbol_lookup_debug_printf
2482 ("lookup_symbol_in_static_block (%s, %s (objfile %s), %s)",
2483 name, host_address_to_string (block),
2484 objfile != nullptr ? objfile_debug_name (objfile) : "NULL",
2485 domain_name (domain));
2486 }
2487
2488 sym = lookup_symbol_in_block (name,
2489 symbol_name_match_type::FULL,
2490 static_block, domain);
2491 symbol_lookup_debug_printf ("lookup_symbol_in_static_block (...) = %s",
2492 sym != NULL
2493 ? host_address_to_string (sym) : "NULL");
2494 return (struct block_symbol) {sym, static_block};
2495}
2496
2497/* Perform the standard symbol lookup of NAME in OBJFILE:
2498 1) First search expanded symtabs, and if not found
2499 2) Search the "quick" symtabs (partial or .gdb_index).
2500 BLOCK_INDEX is one of GLOBAL_BLOCK or STATIC_BLOCK. */
2501
2502static struct block_symbol
2503lookup_symbol_in_objfile (struct objfile *objfile, enum block_enum block_index,
2504 const char *name, const domain_enum domain)
2505{
2506 struct block_symbol result;
2507
2508 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2509
2510 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (%s, %s, %s, %s)",
2511 objfile_debug_name (objfile),
2512 block_index == GLOBAL_BLOCK
2513 ? "GLOBAL_BLOCK" : "STATIC_BLOCK",
2514 name, domain_name (domain));
2515
2516 result = lookup_symbol_in_objfile_symtabs (objfile, block_index,
2517 name, domain);
2518 if (result.symbol != NULL)
2519 {
2520 symbol_lookup_debug_printf
2521 ("lookup_symbol_in_objfile (...) = %s (in symtabs)",
2522 host_address_to_string (result.symbol));
2523 return result;
2524 }
2525
2526 result = lookup_symbol_via_quick_fns (objfile, block_index,
2527 name, domain);
2528 symbol_lookup_debug_printf ("lookup_symbol_in_objfile (...) = %s%s",
2529 result.symbol != NULL
2530 ? host_address_to_string (result.symbol)
2531 : "NULL",
2532 result.symbol != NULL ? " (via quick fns)"
2533 : "");
2534 return result;
2535}
2536
2537/* This function contains the common code of lookup_{global,static}_symbol.
2538 OBJFILE is only used if BLOCK_INDEX is GLOBAL_SCOPE, in which case it is
2539 the objfile to start the lookup in. */
2540
2541static struct block_symbol
2542lookup_global_or_static_symbol (const char *name,
2543 enum block_enum block_index,
2544 struct objfile *objfile,
2545 const domain_enum domain)
2546{
2547 struct symbol_cache *cache = get_symbol_cache (current_program_space);
2548 struct block_symbol result;
2549 struct block_symbol_cache *bsc;
2550 struct symbol_cache_slot *slot;
2551
2552 gdb_assert (block_index == GLOBAL_BLOCK || block_index == STATIC_BLOCK);
2553 gdb_assert (objfile == nullptr || block_index == GLOBAL_BLOCK);
2554
2555 /* First see if we can find the symbol in the cache.
2556 This works because we use the current objfile to qualify the lookup. */
2557 result = symbol_cache_lookup (cache, objfile, block_index, name, domain,
2558 &bsc, &slot);
2559 if (result.symbol != NULL)
2560 {
2561 if (SYMBOL_LOOKUP_FAILED_P (result))
2562 return {};
2563 return result;
2564 }
2565
2566 /* Do a global search (of global blocks, heh). */
2567 if (result.symbol == NULL)
2568 gdbarch_iterate_over_objfiles_in_search_order
2569 (objfile != NULL ? objfile->arch () : target_gdbarch (),
2570 [&result, block_index, name, domain] (struct objfile *objfile_iter)
2571 {
2572 result = lookup_symbol_in_objfile (objfile_iter, block_index,
2573 name, domain);
2574 return result.symbol != nullptr;
2575 },
2576 objfile);
2577
2578 if (result.symbol != NULL)
2579 symbol_cache_mark_found (bsc, slot, objfile, result.symbol, result.block);
2580 else
2581 symbol_cache_mark_not_found (bsc, slot, objfile, name, domain);
2582
2583 return result;
2584}
2585
2586/* See symtab.h. */
2587
2588struct block_symbol
2589lookup_static_symbol (const char *name, const domain_enum domain)
2590{
2591 return lookup_global_or_static_symbol (name, STATIC_BLOCK, nullptr, domain);
2592}
2593
2594/* See symtab.h. */
2595
2596struct block_symbol
2597lookup_global_symbol (const char *name,
2598 const struct block *block,
2599 const domain_enum domain)
2600{
2601 /* If a block was passed in, we want to search the corresponding
2602 global block first. This yields "more expected" behavior, and is
2603 needed to support 'FILENAME'::VARIABLE lookups. */
2604 const struct block *global_block
2605 = block == nullptr ? nullptr : block->global_block ();
2606 symbol *sym = NULL;
2607 if (global_block != nullptr)
2608 {
2609 sym = lookup_symbol_in_block (name,
2610 symbol_name_match_type::FULL,
2611 global_block, domain);
2612 if (sym != NULL && best_symbol (sym, domain))
2613 return { sym, global_block };
2614 }
2615
2616 struct objfile *objfile = nullptr;
2617 if (block != nullptr)
2618 {
2619 objfile = block->objfile ();
2620 if (objfile->separate_debug_objfile_backlink != nullptr)
2621 objfile = objfile->separate_debug_objfile_backlink;
2622 }
2623
2624 block_symbol bs
2625 = lookup_global_or_static_symbol (name, GLOBAL_BLOCK, objfile, domain);
2626 if (better_symbol (sym, bs.symbol, domain) == sym)
2627 return { sym, global_block };
2628 else
2629 return bs;
2630}
2631
2632bool
2633symbol_matches_domain (enum language symbol_language,
2634 domain_enum symbol_domain,
2635 domain_enum domain)
2636{
2637 /* For C++ "struct foo { ... }" also defines a typedef for "foo".
2638 Similarly, any Ada type declaration implicitly defines a typedef. */
2639 if (symbol_language == language_cplus
2640 || symbol_language == language_d
2641 || symbol_language == language_ada
2642 || symbol_language == language_rust)
2643 {
2644 if ((domain == VAR_DOMAIN || domain == STRUCT_DOMAIN)
2645 && symbol_domain == STRUCT_DOMAIN)
2646 return true;
2647 }
2648 /* For all other languages, strict match is required. */
2649 return (symbol_domain == domain);
2650}
2651
2652/* See symtab.h. */
2653
2654struct type *
2655lookup_transparent_type (const char *name)
2656{
2657 return current_language->lookup_transparent_type (name);
2658}
2659
2660/* A helper for basic_lookup_transparent_type that interfaces with the
2661 "quick" symbol table functions. */
2662
2663static struct type *
2664basic_lookup_transparent_type_quick (struct objfile *objfile,
2665 enum block_enum block_index,
2666 const char *name)
2667{
2668 struct compunit_symtab *cust;
2669 const struct blockvector *bv;
2670 const struct block *block;
2671 struct symbol *sym;
2672
2673 cust = objfile->lookup_symbol (block_index, name, STRUCT_DOMAIN);
2674 if (cust == NULL)
2675 return NULL;
2676
2677 bv = cust->blockvector ();
2678 block = bv->block (block_index);
2679 sym = block_find_symbol (block, name, STRUCT_DOMAIN,
2680 block_find_non_opaque_type, NULL);
2681 if (sym == NULL)
2682 error_in_psymtab_expansion (block_index, name, cust);
2683 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2684 return sym->type ();
2685}
2686
2687/* Subroutine of basic_lookup_transparent_type to simplify it.
2688 Look up the non-opaque definition of NAME in BLOCK_INDEX of OBJFILE.
2689 BLOCK_INDEX is either GLOBAL_BLOCK or STATIC_BLOCK. */
2690
2691static struct type *
2692basic_lookup_transparent_type_1 (struct objfile *objfile,
2693 enum block_enum block_index,
2694 const char *name)
2695{
2696 const struct blockvector *bv;
2697 const struct block *block;
2698 const struct symbol *sym;
2699
2700 for (compunit_symtab *cust : objfile->compunits ())
2701 {
2702 bv = cust->blockvector ();
2703 block = bv->block (block_index);
2704 sym = block_find_symbol (block, name, STRUCT_DOMAIN,
2705 block_find_non_opaque_type, NULL);
2706 if (sym != NULL)
2707 {
2708 gdb_assert (!TYPE_IS_OPAQUE (sym->type ()));
2709 return sym->type ();
2710 }
2711 }
2712
2713 return NULL;
2714}
2715
2716/* The standard implementation of lookup_transparent_type. This code
2717 was modeled on lookup_symbol -- the parts not relevant to looking
2718 up types were just left out. In particular it's assumed here that
2719 types are available in STRUCT_DOMAIN and only in file-static or
2720 global blocks. */
2721
2722struct type *
2723basic_lookup_transparent_type (const char *name)
2724{
2725 struct type *t;
2726
2727 /* Now search all the global symbols. Do the symtab's first, then
2728 check the psymtab's. If a psymtab indicates the existence
2729 of the desired name as a global, then do psymtab-to-symtab
2730 conversion on the fly and return the found symbol. */
2731
2732 for (objfile *objfile : current_program_space->objfiles ())
2733 {
2734 t = basic_lookup_transparent_type_1 (objfile, GLOBAL_BLOCK, name);
2735 if (t)
2736 return t;
2737 }
2738
2739 for (objfile *objfile : current_program_space->objfiles ())
2740 {
2741 t = basic_lookup_transparent_type_quick (objfile, GLOBAL_BLOCK, name);
2742 if (t)
2743 return t;
2744 }
2745
2746 /* Now search the static file-level symbols.
2747 Not strictly correct, but more useful than an error.
2748 Do the symtab's first, then
2749 check the psymtab's. If a psymtab indicates the existence
2750 of the desired name as a file-level static, then do psymtab-to-symtab
2751 conversion on the fly and return the found symbol. */
2752
2753 for (objfile *objfile : current_program_space->objfiles ())
2754 {
2755 t = basic_lookup_transparent_type_1 (objfile, STATIC_BLOCK, name);
2756 if (t)
2757 return t;
2758 }
2759
2760 for (objfile *objfile : current_program_space->objfiles ())
2761 {
2762 t = basic_lookup_transparent_type_quick (objfile, STATIC_BLOCK, name);
2763 if (t)
2764 return t;
2765 }
2766
2767 return (struct type *) 0;
2768}
2769
2770/* See symtab.h. */
2771
2772bool
2773iterate_over_symbols (const struct block *block,
2774 const lookup_name_info &name,
2775 const domain_enum domain,
2776 gdb::function_view<symbol_found_callback_ftype> callback)
2777{
2778 for (struct symbol *sym : block_iterator_range (block, &name))
2779 {
2780 if (symbol_matches_domain (sym->language (), sym->domain (), domain))
2781 {
2782 struct block_symbol block_sym = {sym, block};
2783
2784 if (!callback (&block_sym))
2785 return false;
2786 }
2787 }
2788 return true;
2789}
2790
2791/* See symtab.h. */
2792
2793bool
2794iterate_over_symbols_terminated
2795 (const struct block *block,
2796 const lookup_name_info &name,
2797 const domain_enum domain,
2798 gdb::function_view<symbol_found_callback_ftype> callback)
2799{
2800 if (!iterate_over_symbols (block, name, domain, callback))
2801 return false;
2802 struct block_symbol block_sym = {nullptr, block};
2803 return callback (&block_sym);
2804}
2805
2806/* Find the compunit symtab associated with PC and SECTION.
2807 This will read in debug info as necessary. */
2808
2809struct compunit_symtab *
2810find_pc_sect_compunit_symtab (CORE_ADDR pc, struct obj_section *section)
2811{
2812 struct compunit_symtab *best_cust = NULL;
2813 CORE_ADDR best_cust_range = 0;
2814 struct bound_minimal_symbol msymbol;
2815
2816 /* If we know that this is not a text address, return failure. This is
2817 necessary because we loop based on the block's high and low code
2818 addresses, which do not include the data ranges, and because
2819 we call find_pc_sect_psymtab which has a similar restriction based
2820 on the partial_symtab's texthigh and textlow. */
2821 msymbol = lookup_minimal_symbol_by_pc_section (pc, section);
2822 if (msymbol.minsym && msymbol.minsym->data_p ())
2823 return NULL;
2824
2825 /* Search all symtabs for the one whose file contains our address, and which
2826 is the smallest of all the ones containing the address. This is designed
2827 to deal with a case like symtab a is at 0x1000-0x2000 and 0x3000-0x4000
2828 and symtab b is at 0x2000-0x3000. So the GLOBAL_BLOCK for a is from
2829 0x1000-0x4000, but for address 0x2345 we want to return symtab b.
2830
2831 This happens for native ecoff format, where code from included files
2832 gets its own symtab. The symtab for the included file should have
2833 been read in already via the dependency mechanism.
2834 It might be swifter to create several symtabs with the same name
2835 like xcoff does (I'm not sure).
2836
2837 It also happens for objfiles that have their functions reordered.
2838 For these, the symtab we are looking for is not necessarily read in. */
2839
2840 for (objfile *obj_file : current_program_space->objfiles ())
2841 {
2842 for (compunit_symtab *cust : obj_file->compunits ())
2843 {
2844 const struct blockvector *bv = cust->blockvector ();
2845 const struct block *global_block = bv->global_block ();
2846 CORE_ADDR start = global_block->start ();
2847 CORE_ADDR end = global_block->end ();
2848 bool in_range_p = start <= pc && pc < end;
2849 if (!in_range_p)
2850 continue;
2851
2852 if (bv->map () != nullptr)
2853 {
2854 if (bv->map ()->find (pc) == nullptr)
2855 continue;
2856
2857 return cust;
2858 }
2859
2860 CORE_ADDR range = end - start;
2861 if (best_cust != nullptr
2862 && range >= best_cust_range)
2863 /* Cust doesn't have a smaller range than best_cust, skip it. */
2864 continue;
2865
2866 /* For an objfile that has its functions reordered,
2867 find_pc_psymtab will find the proper partial symbol table
2868 and we simply return its corresponding symtab. */
2869 /* In order to better support objfiles that contain both
2870 stabs and coff debugging info, we continue on if a psymtab
2871 can't be found. */
2872 struct compunit_symtab *result
2873 = obj_file->find_pc_sect_compunit_symtab (msymbol, pc,
2874 section, 0);
2875 if (result != nullptr)
2876 return result;
2877
2878 if (section != 0)
2879 {
2880 struct symbol *found_sym = nullptr;
2881
2882 for (int b_index = GLOBAL_BLOCK;
2883 b_index <= STATIC_BLOCK && found_sym == nullptr;
2884 ++b_index)
2885 {
2886 const struct block *b = bv->block (b_index);
2887 for (struct symbol *sym : block_iterator_range (b))
2888 {
2889 if (matching_obj_sections (sym->obj_section (obj_file),
2890 section))
2891 {
2892 found_sym = sym;
2893 break;
2894 }
2895 }
2896 }
2897 if (found_sym == nullptr)
2898 continue; /* No symbol in this symtab matches
2899 section. */
2900 }
2901
2902 /* Cust is best found sofar, save it. */
2903 best_cust = cust;
2904 best_cust_range = range;
2905 }
2906 }
2907
2908 if (best_cust != NULL)
2909 return best_cust;
2910
2911 /* Not found in symtabs, search the "quick" symtabs (e.g. psymtabs). */
2912
2913 for (objfile *objf : current_program_space->objfiles ())
2914 {
2915 struct compunit_symtab *result
2916 = objf->find_pc_sect_compunit_symtab (msymbol, pc, section, 1);
2917 if (result != NULL)
2918 return result;
2919 }
2920
2921 return NULL;
2922}
2923
2924/* Find the compunit symtab associated with PC.
2925 This will read in debug info as necessary.
2926 Backward compatibility, no section. */
2927
2928struct compunit_symtab *
2929find_pc_compunit_symtab (CORE_ADDR pc)
2930{
2931 return find_pc_sect_compunit_symtab (pc, find_pc_mapped_section (pc));
2932}
2933
2934/* See symtab.h. */
2935
2936struct symbol *
2937find_symbol_at_address (CORE_ADDR address)
2938{
2939 /* A helper function to search a given symtab for a symbol matching
2940 ADDR. */
2941 auto search_symtab = [] (compunit_symtab *symtab, CORE_ADDR addr) -> symbol *
2942 {
2943 const struct blockvector *bv = symtab->blockvector ();
2944
2945 for (int i = GLOBAL_BLOCK; i <= STATIC_BLOCK; ++i)
2946 {
2947 const struct block *b = bv->block (i);
2948
2949 for (struct symbol *sym : block_iterator_range (b))
2950 {
2951 if (sym->aclass () == LOC_STATIC
2952 && sym->value_address () == addr)
2953 return sym;
2954 }
2955 }
2956 return nullptr;
2957 };
2958
2959 for (objfile *objfile : current_program_space->objfiles ())
2960 {
2961 /* If this objfile was read with -readnow, then we need to
2962 search the symtabs directly. */
2963 if ((objfile->flags & OBJF_READNOW) != 0)
2964 {
2965 for (compunit_symtab *symtab : objfile->compunits ())
2966 {
2967 struct symbol *sym = search_symtab (symtab, address);
2968 if (sym != nullptr)
2969 return sym;
2970 }
2971 }
2972 else
2973 {
2974 struct compunit_symtab *symtab
2975 = objfile->find_compunit_symtab_by_address (address);
2976 if (symtab != NULL)
2977 {
2978 struct symbol *sym = search_symtab (symtab, address);
2979 if (sym != nullptr)
2980 return sym;
2981 }
2982 }
2983 }
2984
2985 return NULL;
2986}
2987
2988\f
2989
2990/* Find the source file and line number for a given PC value and SECTION.
2991 Return a structure containing a symtab pointer, a line number,
2992 and a pc range for the entire source line.
2993 The value's .pc field is NOT the specified pc.
2994 NOTCURRENT nonzero means, if specified pc is on a line boundary,
2995 use the line that ends there. Otherwise, in that case, the line
2996 that begins there is used. */
2997
2998/* The big complication here is that a line may start in one file, and end just
2999 before the start of another file. This usually occurs when you #include
3000 code in the middle of a subroutine. To properly find the end of a line's PC
3001 range, we must search all symtabs associated with this compilation unit, and
3002 find the one whose first PC is closer than that of the next line in this
3003 symtab. */
3004
3005struct symtab_and_line
3006find_pc_sect_line (CORE_ADDR pc, struct obj_section *section, int notcurrent)
3007{
3008 struct compunit_symtab *cust;
3009 const linetable *l;
3010 int len;
3011 const linetable_entry *item;
3012 const struct blockvector *bv;
3013 struct bound_minimal_symbol msymbol;
3014
3015 /* Info on best line seen so far, and where it starts, and its file. */
3016
3017 const linetable_entry *best = NULL;
3018 CORE_ADDR best_end = 0;
3019 struct symtab *best_symtab = 0;
3020
3021 /* Store here the first line number
3022 of a file which contains the line at the smallest pc after PC.
3023 If we don't find a line whose range contains PC,
3024 we will use a line one less than this,
3025 with a range from the start of that file to the first line's pc. */
3026 const linetable_entry *alt = NULL;
3027
3028 /* Info on best line seen in this file. */
3029
3030 const linetable_entry *prev;
3031
3032 /* If this pc is not from the current frame,
3033 it is the address of the end of a call instruction.
3034 Quite likely that is the start of the following statement.
3035 But what we want is the statement containing the instruction.
3036 Fudge the pc to make sure we get that. */
3037
3038 /* It's tempting to assume that, if we can't find debugging info for
3039 any function enclosing PC, that we shouldn't search for line
3040 number info, either. However, GAS can emit line number info for
3041 assembly files --- very helpful when debugging hand-written
3042 assembly code. In such a case, we'd have no debug info for the
3043 function, but we would have line info. */
3044
3045 if (notcurrent)
3046 pc -= 1;
3047
3048 /* elz: added this because this function returned the wrong
3049 information if the pc belongs to a stub (import/export)
3050 to call a shlib function. This stub would be anywhere between
3051 two functions in the target, and the line info was erroneously
3052 taken to be the one of the line before the pc. */
3053
3054 /* RT: Further explanation:
3055
3056 * We have stubs (trampolines) inserted between procedures.
3057 *
3058 * Example: "shr1" exists in a shared library, and a "shr1" stub also
3059 * exists in the main image.
3060 *
3061 * In the minimal symbol table, we have a bunch of symbols
3062 * sorted by start address. The stubs are marked as "trampoline",
3063 * the others appear as text. E.g.:
3064 *
3065 * Minimal symbol table for main image
3066 * main: code for main (text symbol)
3067 * shr1: stub (trampoline symbol)
3068 * foo: code for foo (text symbol)
3069 * ...
3070 * Minimal symbol table for "shr1" image:
3071 * ...
3072 * shr1: code for shr1 (text symbol)
3073 * ...
3074 *
3075 * So the code below is trying to detect if we are in the stub
3076 * ("shr1" stub), and if so, find the real code ("shr1" trampoline),
3077 * and if found, do the symbolization from the real-code address
3078 * rather than the stub address.
3079 *
3080 * Assumptions being made about the minimal symbol table:
3081 * 1. lookup_minimal_symbol_by_pc() will return a trampoline only
3082 * if we're really in the trampoline.s If we're beyond it (say
3083 * we're in "foo" in the above example), it'll have a closer
3084 * symbol (the "foo" text symbol for example) and will not
3085 * return the trampoline.
3086 * 2. lookup_minimal_symbol_text() will find a real text symbol
3087 * corresponding to the trampoline, and whose address will
3088 * be different than the trampoline address. I put in a sanity
3089 * check for the address being the same, to avoid an
3090 * infinite recursion.
3091 */
3092 msymbol = lookup_minimal_symbol_by_pc (pc);
3093 if (msymbol.minsym != NULL)
3094 if (msymbol.minsym->type () == mst_solib_trampoline)
3095 {
3096 struct bound_minimal_symbol mfunsym
3097 = lookup_minimal_symbol_text (msymbol.minsym->linkage_name (),
3098 NULL);
3099
3100 if (mfunsym.minsym == NULL)
3101 /* I eliminated this warning since it is coming out
3102 * in the following situation:
3103 * gdb shmain // test program with shared libraries
3104 * (gdb) break shr1 // function in shared lib
3105 * Warning: In stub for ...
3106 * In the above situation, the shared lib is not loaded yet,
3107 * so of course we can't find the real func/line info,
3108 * but the "break" still works, and the warning is annoying.
3109 * So I commented out the warning. RT */
3110 /* warning ("In stub for %s; unable to find real function/line info",
3111 msymbol->linkage_name ()); */
3112 ;
3113 /* fall through */
3114 else if (mfunsym.value_address ()
3115 == msymbol.value_address ())
3116 /* Avoid infinite recursion */
3117 /* See above comment about why warning is commented out. */
3118 /* warning ("In stub for %s; unable to find real function/line info",
3119 msymbol->linkage_name ()); */
3120 ;
3121 /* fall through */
3122 else
3123 {
3124 /* Detect an obvious case of infinite recursion. If this
3125 should occur, we'd like to know about it, so error out,
3126 fatally. */
3127 if (mfunsym.value_address () == pc)
3128 internal_error (_("Infinite recursion detected in find_pc_sect_line;"
3129 "please file a bug report"));
3130
3131 return find_pc_line (mfunsym.value_address (), 0);
3132 }
3133 }
3134
3135 symtab_and_line val;
3136 val.pspace = current_program_space;
3137
3138 cust = find_pc_sect_compunit_symtab (pc, section);
3139 if (cust == NULL)
3140 {
3141 /* If no symbol information, return previous pc. */
3142 if (notcurrent)
3143 pc++;
3144 val.pc = pc;
3145 return val;
3146 }
3147
3148 bv = cust->blockvector ();
3149 struct objfile *objfile = cust->objfile ();
3150
3151 /* Look at all the symtabs that share this blockvector.
3152 They all have the same apriori range, that we found was right;
3153 but they have different line tables. */
3154
3155 for (symtab *iter_s : cust->filetabs ())
3156 {
3157 /* Find the best line in this symtab. */
3158 l = iter_s->linetable ();
3159 if (!l)
3160 continue;
3161 len = l->nitems;
3162 if (len <= 0)
3163 {
3164 /* I think len can be zero if the symtab lacks line numbers
3165 (e.g. gcc -g1). (Either that or the LINETABLE is NULL;
3166 I'm not sure which, and maybe it depends on the symbol
3167 reader). */
3168 continue;
3169 }
3170
3171 prev = NULL;
3172 item = l->item; /* Get first line info. */
3173
3174 /* Is this file's first line closer than the first lines of other files?
3175 If so, record this file, and its first line, as best alternate. */
3176 if (item->pc (objfile) > pc
3177 && (!alt || item->unrelocated_pc () < alt->unrelocated_pc ()))
3178 alt = item;
3179
3180 auto pc_compare = [] (const unrelocated_addr &comp_pc,
3181 const struct linetable_entry & lhs)
3182 {
3183 return comp_pc < lhs.unrelocated_pc ();
3184 };
3185
3186 const linetable_entry *first = item;
3187 const linetable_entry *last = item + len;
3188 item = (std::upper_bound
3189 (first, last,
3190 unrelocated_addr (pc - objfile->text_section_offset ()),
3191 pc_compare));
3192 if (item != first)
3193 prev = item - 1; /* Found a matching item. */
3194
3195 /* At this point, prev points at the line whose start addr is <= pc, and
3196 item points at the next line. If we ran off the end of the linetable
3197 (pc >= start of the last line), then prev == item. If pc < start of
3198 the first line, prev will not be set. */
3199
3200 /* Is this file's best line closer than the best in the other files?
3201 If so, record this file, and its best line, as best so far. Don't
3202 save prev if it represents the end of a function (i.e. line number
3203 0) instead of a real line. */
3204
3205 if (prev && prev->line
3206 && (!best || prev->unrelocated_pc () > best->unrelocated_pc ()))
3207 {
3208 best = prev;
3209 best_symtab = iter_s;
3210
3211 /* If during the binary search we land on a non-statement entry,
3212 scan backward through entries at the same address to see if
3213 there is an entry marked as is-statement. In theory this
3214 duplication should have been removed from the line table
3215 during construction, this is just a double check. If the line
3216 table has had the duplication removed then this should be
3217 pretty cheap. */
3218 if (!best->is_stmt)
3219 {
3220 const linetable_entry *tmp = best;
3221 while (tmp > first
3222 && (tmp - 1)->unrelocated_pc () == tmp->unrelocated_pc ()
3223 && (tmp - 1)->line != 0 && !tmp->is_stmt)
3224 --tmp;
3225 if (tmp->is_stmt)
3226 best = tmp;
3227 }
3228
3229 /* Discard BEST_END if it's before the PC of the current BEST. */
3230 if (best_end <= best->pc (objfile))
3231 best_end = 0;
3232 }
3233
3234 /* If another line (denoted by ITEM) is in the linetable and its
3235 PC is after BEST's PC, but before the current BEST_END, then
3236 use ITEM's PC as the new best_end. */
3237 if (best && item < last
3238 && item->unrelocated_pc () > best->unrelocated_pc ()
3239 && (best_end == 0 || best_end > item->pc (objfile)))
3240 best_end = item->pc (objfile);
3241 }
3242
3243 if (!best_symtab)
3244 {
3245 /* If we didn't find any line number info, just return zeros.
3246 We used to return alt->line - 1 here, but that could be
3247 anywhere; if we don't have line number info for this PC,
3248 don't make some up. */
3249 val.pc = pc;
3250 }
3251 else if (best->line == 0)
3252 {
3253 /* If our best fit is in a range of PC's for which no line
3254 number info is available (line number is zero) then we didn't
3255 find any valid line information. */
3256 val.pc = pc;
3257 }
3258 else
3259 {
3260 val.is_stmt = best->is_stmt;
3261 val.symtab = best_symtab;
3262 val.line = best->line;
3263 val.pc = best->pc (objfile);
3264 if (best_end && (!alt || best_end < alt->pc (objfile)))
3265 val.end = best_end;
3266 else if (alt)
3267 val.end = alt->pc (objfile);
3268 else
3269 val.end = bv->global_block ()->end ();
3270 }
3271 val.section = section;
3272 return val;
3273}
3274
3275/* Backward compatibility (no section). */
3276
3277struct symtab_and_line
3278find_pc_line (CORE_ADDR pc, int notcurrent)
3279{
3280 struct obj_section *section;
3281
3282 section = find_pc_overlay (pc);
3283 if (!pc_in_unmapped_range (pc, section))
3284 return find_pc_sect_line (pc, section, notcurrent);
3285
3286 /* If the original PC was an unmapped address then we translate this to a
3287 mapped address in order to lookup the sal. However, as the user
3288 passed us an unmapped address it makes more sense to return a result
3289 that has the pc and end fields translated to unmapped addresses. */
3290 pc = overlay_mapped_address (pc, section);
3291 symtab_and_line sal = find_pc_sect_line (pc, section, notcurrent);
3292 sal.pc = overlay_unmapped_address (sal.pc, section);
3293 sal.end = overlay_unmapped_address (sal.end, section);
3294 return sal;
3295}
3296
3297/* See symtab.h. */
3298
3299struct symtab *
3300find_pc_line_symtab (CORE_ADDR pc)
3301{
3302 struct symtab_and_line sal;
3303
3304 /* This always passes zero for NOTCURRENT to find_pc_line.
3305 There are currently no callers that ever pass non-zero. */
3306 sal = find_pc_line (pc, 0);
3307 return sal.symtab;
3308}
3309\f
3310/* Find line number LINE in any symtab whose name is the same as
3311 SYMTAB.
3312
3313 If found, return the symtab that contains the linetable in which it was
3314 found, set *INDEX to the index in the linetable of the best entry
3315 found, and set *EXACT_MATCH to true if the value returned is an
3316 exact match.
3317
3318 If not found, return NULL. */
3319
3320struct symtab *
3321find_line_symtab (struct symtab *sym_tab, int line,
3322 int *index, bool *exact_match)
3323{
3324 int exact = 0; /* Initialized here to avoid a compiler warning. */
3325
3326 /* BEST_INDEX and BEST_LINETABLE identify the smallest linenumber > LINE
3327 so far seen. */
3328
3329 int best_index;
3330 const struct linetable *best_linetable;
3331 struct symtab *best_symtab;
3332
3333 /* First try looking it up in the given symtab. */
3334 best_linetable = sym_tab->linetable ();
3335 best_symtab = sym_tab;
3336 best_index = find_line_common (best_linetable, line, &exact, 0);
3337 if (best_index < 0 || !exact)
3338 {
3339 /* Didn't find an exact match. So we better keep looking for
3340 another symtab with the same name. In the case of xcoff,
3341 multiple csects for one source file (produced by IBM's FORTRAN
3342 compiler) produce multiple symtabs (this is unavoidable
3343 assuming csects can be at arbitrary places in memory and that
3344 the GLOBAL_BLOCK of a symtab has a begin and end address). */
3345
3346 /* BEST is the smallest linenumber > LINE so far seen,
3347 or 0 if none has been seen so far.
3348 BEST_INDEX and BEST_LINETABLE identify the item for it. */
3349 int best;
3350
3351 if (best_index >= 0)
3352 best = best_linetable->item[best_index].line;
3353 else
3354 best = 0;
3355
3356 for (objfile *objfile : current_program_space->objfiles ())
3357 objfile->expand_symtabs_with_fullname (symtab_to_fullname (sym_tab));
3358
3359 for (objfile *objfile : current_program_space->objfiles ())
3360 {
3361 for (compunit_symtab *cu : objfile->compunits ())
3362 {
3363 for (symtab *s : cu->filetabs ())
3364 {
3365 const struct linetable *l;
3366 int ind;
3367
3368 if (FILENAME_CMP (sym_tab->filename, s->filename) != 0)
3369 continue;
3370 if (FILENAME_CMP (symtab_to_fullname (sym_tab),
3371 symtab_to_fullname (s)) != 0)
3372 continue;
3373 l = s->linetable ();
3374 ind = find_line_common (l, line, &exact, 0);
3375 if (ind >= 0)
3376 {
3377 if (exact)
3378 {
3379 best_index = ind;
3380 best_linetable = l;
3381 best_symtab = s;
3382 goto done;
3383 }
3384 if (best == 0 || l->item[ind].line < best)
3385 {
3386 best = l->item[ind].line;
3387 best_index = ind;
3388 best_linetable = l;
3389 best_symtab = s;
3390 }
3391 }
3392 }
3393 }
3394 }
3395 }
3396done:
3397 if (best_index < 0)
3398 return NULL;
3399
3400 if (index)
3401 *index = best_index;
3402 if (exact_match)
3403 *exact_match = (exact != 0);
3404
3405 return best_symtab;
3406}
3407
3408/* Given SYMTAB, returns all the PCs function in the symtab that
3409 exactly match LINE. Returns an empty vector if there are no exact
3410 matches, but updates BEST_ITEM in this case. */
3411
3412std::vector<CORE_ADDR>
3413find_pcs_for_symtab_line (struct symtab *symtab, int line,
3414 const linetable_entry **best_item)
3415{
3416 int start = 0;
3417 std::vector<CORE_ADDR> result;
3418 struct objfile *objfile = symtab->compunit ()->objfile ();
3419
3420 /* First, collect all the PCs that are at this line. */
3421 while (1)
3422 {
3423 int was_exact;
3424 int idx;
3425
3426 idx = find_line_common (symtab->linetable (), line, &was_exact,
3427 start);
3428 if (idx < 0)
3429 break;
3430
3431 if (!was_exact)
3432 {
3433 const linetable_entry *item = &symtab->linetable ()->item[idx];
3434
3435 if (*best_item == NULL
3436 || (item->line < (*best_item)->line && item->is_stmt))
3437 *best_item = item;
3438
3439 break;
3440 }
3441
3442 result.push_back (symtab->linetable ()->item[idx].pc (objfile));
3443 start = idx + 1;
3444 }
3445
3446 return result;
3447}
3448
3449\f
3450/* Set the PC value for a given source file and line number and return true.
3451 Returns false for invalid line number (and sets the PC to 0).
3452 The source file is specified with a struct symtab. */
3453
3454bool
3455find_line_pc (struct symtab *symtab, int line, CORE_ADDR *pc)
3456{
3457 const struct linetable *l;
3458 int ind;
3459
3460 *pc = 0;
3461 if (symtab == 0)
3462 return false;
3463
3464 symtab = find_line_symtab (symtab, line, &ind, NULL);
3465 if (symtab != NULL)
3466 {
3467 l = symtab->linetable ();
3468 *pc = l->item[ind].pc (symtab->compunit ()->objfile ());
3469 return true;
3470 }
3471 else
3472 return false;
3473}
3474
3475/* Find the range of pc values in a line.
3476 Store the starting pc of the line into *STARTPTR
3477 and the ending pc (start of next line) into *ENDPTR.
3478 Returns true to indicate success.
3479 Returns false if could not find the specified line. */
3480
3481bool
3482find_line_pc_range (struct symtab_and_line sal, CORE_ADDR *startptr,
3483 CORE_ADDR *endptr)
3484{
3485 CORE_ADDR startaddr;
3486 struct symtab_and_line found_sal;
3487
3488 startaddr = sal.pc;
3489 if (startaddr == 0 && !find_line_pc (sal.symtab, sal.line, &startaddr))
3490 return false;
3491
3492 /* This whole function is based on address. For example, if line 10 has
3493 two parts, one from 0x100 to 0x200 and one from 0x300 to 0x400, then
3494 "info line *0x123" should say the line goes from 0x100 to 0x200
3495 and "info line *0x355" should say the line goes from 0x300 to 0x400.
3496 This also insures that we never give a range like "starts at 0x134
3497 and ends at 0x12c". */
3498
3499 found_sal = find_pc_sect_line (startaddr, sal.section, 0);
3500 if (found_sal.line != sal.line)
3501 {
3502 /* The specified line (sal) has zero bytes. */
3503 *startptr = found_sal.pc;
3504 *endptr = found_sal.pc;
3505 }
3506 else
3507 {
3508 *startptr = found_sal.pc;
3509 *endptr = found_sal.end;
3510 }
3511 return true;
3512}
3513
3514/* Given a line table and a line number, return the index into the line
3515 table for the pc of the nearest line whose number is >= the specified one.
3516 Return -1 if none is found. The value is >= 0 if it is an index.
3517 START is the index at which to start searching the line table.
3518
3519 Set *EXACT_MATCH nonzero if the value returned is an exact match. */
3520
3521static int
3522find_line_common (const linetable *l, int lineno,
3523 int *exact_match, int start)
3524{
3525 int i;
3526 int len;
3527
3528 /* BEST is the smallest linenumber > LINENO so far seen,
3529 or 0 if none has been seen so far.
3530 BEST_INDEX identifies the item for it. */
3531
3532 int best_index = -1;
3533 int best = 0;
3534
3535 *exact_match = 0;
3536
3537 if (lineno <= 0)
3538 return -1;
3539 if (l == 0)
3540 return -1;
3541
3542 len = l->nitems;
3543 for (i = start; i < len; i++)
3544 {
3545 const linetable_entry *item = &(l->item[i]);
3546
3547 /* Ignore non-statements. */
3548 if (!item->is_stmt)
3549 continue;
3550
3551 if (item->line == lineno)
3552 {
3553 /* Return the first (lowest address) entry which matches. */
3554 *exact_match = 1;
3555 return i;
3556 }
3557
3558 if (item->line > lineno && (best == 0 || item->line < best))
3559 {
3560 best = item->line;
3561 best_index = i;
3562 }
3563 }
3564
3565 /* If we got here, we didn't get an exact match. */
3566 return best_index;
3567}
3568
3569bool
3570find_pc_line_pc_range (CORE_ADDR pc, CORE_ADDR *startptr, CORE_ADDR *endptr)
3571{
3572 struct symtab_and_line sal;
3573
3574 sal = find_pc_line (pc, 0);
3575 *startptr = sal.pc;
3576 *endptr = sal.end;
3577 return sal.symtab != 0;
3578}
3579
3580/* Helper for find_function_start_sal. Does most of the work, except
3581 setting the sal's symbol. */
3582
3583static symtab_and_line
3584find_function_start_sal_1 (CORE_ADDR func_addr, obj_section *section,
3585 bool funfirstline)
3586{
3587 symtab_and_line sal = find_pc_sect_line (func_addr, section, 0);
3588
3589 if (funfirstline && sal.symtab != NULL
3590 && (sal.symtab->compunit ()->locations_valid ()
3591 || sal.symtab->language () == language_asm))
3592 {
3593 struct gdbarch *gdbarch = sal.symtab->compunit ()->objfile ()->arch ();
3594
3595 sal.pc = func_addr;
3596 if (gdbarch_skip_entrypoint_p (gdbarch))
3597 sal.pc = gdbarch_skip_entrypoint (gdbarch, sal.pc);
3598 return sal;
3599 }
3600
3601 /* We always should have a line for the function start address.
3602 If we don't, something is odd. Create a plain SAL referring
3603 just the PC and hope that skip_prologue_sal (if requested)
3604 can find a line number for after the prologue. */
3605 if (sal.pc < func_addr)
3606 {
3607 sal = {};
3608 sal.pspace = current_program_space;
3609 sal.pc = func_addr;
3610 sal.section = section;
3611 }
3612
3613 if (funfirstline)
3614 skip_prologue_sal (&sal);
3615
3616 return sal;
3617}
3618
3619/* See symtab.h. */
3620
3621symtab_and_line
3622find_function_start_sal (CORE_ADDR func_addr, obj_section *section,
3623 bool funfirstline)
3624{
3625 symtab_and_line sal
3626 = find_function_start_sal_1 (func_addr, section, funfirstline);
3627
3628 /* find_function_start_sal_1 does a linetable search, so it finds
3629 the symtab and linenumber, but not a symbol. Fill in the
3630 function symbol too. */
3631 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
3632
3633 return sal;
3634}
3635
3636/* See symtab.h. */
3637
3638symtab_and_line
3639find_function_start_sal (symbol *sym, bool funfirstline)
3640{
3641 symtab_and_line sal
3642 = find_function_start_sal_1 (sym->value_block ()->entry_pc (),
3643 sym->obj_section (sym->objfile ()),
3644 funfirstline);
3645 sal.symbol = sym;
3646 return sal;
3647}
3648
3649
3650/* Given a function start address FUNC_ADDR and SYMTAB, find the first
3651 address for that function that has an entry in SYMTAB's line info
3652 table. If such an entry cannot be found, return FUNC_ADDR
3653 unaltered. */
3654
3655static CORE_ADDR
3656skip_prologue_using_lineinfo (CORE_ADDR func_addr, struct symtab *symtab)
3657{
3658 CORE_ADDR func_start, func_end;
3659 const struct linetable *l;
3660 int i;
3661
3662 /* Give up if this symbol has no lineinfo table. */
3663 l = symtab->linetable ();
3664 if (l == NULL)
3665 return func_addr;
3666
3667 /* Get the range for the function's PC values, or give up if we
3668 cannot, for some reason. */
3669 if (!find_pc_partial_function (func_addr, NULL, &func_start, &func_end))
3670 return func_addr;
3671
3672 struct objfile *objfile = symtab->compunit ()->objfile ();
3673
3674 /* Linetable entries are ordered by PC values, see the commentary in
3675 symtab.h where `struct linetable' is defined. Thus, the first
3676 entry whose PC is in the range [FUNC_START..FUNC_END[ is the
3677 address we are looking for. */
3678 for (i = 0; i < l->nitems; i++)
3679 {
3680 const linetable_entry *item = &(l->item[i]);
3681 CORE_ADDR item_pc = item->pc (objfile);
3682
3683 /* Don't use line numbers of zero, they mark special entries in
3684 the table. See the commentary on symtab.h before the
3685 definition of struct linetable. */
3686 if (item->line > 0 && func_start <= item_pc && item_pc < func_end)
3687 return item_pc;
3688 }
3689
3690 return func_addr;
3691}
3692
3693/* Try to locate the address where a breakpoint should be placed past the
3694 prologue of function starting at FUNC_ADDR using the line table.
3695
3696 Return the address associated with the first entry in the line-table for
3697 the function starting at FUNC_ADDR which has prologue_end set to true if
3698 such entry exist, otherwise return an empty optional. */
3699
3700static gdb::optional<CORE_ADDR>
3701skip_prologue_using_linetable (CORE_ADDR func_addr)
3702{
3703 CORE_ADDR start_pc, end_pc;
3704
3705 if (!find_pc_partial_function (func_addr, nullptr, &start_pc, &end_pc))
3706 return {};
3707
3708 const struct symtab_and_line prologue_sal = find_pc_line (start_pc, 0);
3709 if (prologue_sal.symtab != nullptr
3710 && prologue_sal.symtab->language () != language_asm)
3711 {
3712 const linetable *linetable = prologue_sal.symtab->linetable ();
3713
3714 struct objfile *objfile = prologue_sal.symtab->compunit ()->objfile ();
3715
3716 unrelocated_addr unrel_start
3717 = unrelocated_addr (start_pc - objfile->text_section_offset ());
3718 unrelocated_addr unrel_end
3719 = unrelocated_addr (end_pc - objfile->text_section_offset ());
3720
3721 auto it = std::lower_bound
3722 (linetable->item, linetable->item + linetable->nitems, unrel_start,
3723 [] (const linetable_entry &lte, unrelocated_addr pc)
3724 {
3725 return lte.unrelocated_pc () < pc;
3726 });
3727
3728 for (;
3729 (it < linetable->item + linetable->nitems
3730 && it->unrelocated_pc () < unrel_end);
3731 it++)
3732 if (it->prologue_end)
3733 return {it->pc (objfile)};
3734 }
3735
3736 return {};
3737}
3738
3739/* Adjust SAL to the first instruction past the function prologue.
3740 If the PC was explicitly specified, the SAL is not changed.
3741 If the line number was explicitly specified then the SAL can still be
3742 updated, unless the language for SAL is assembler, in which case the SAL
3743 will be left unchanged.
3744 If SAL is already past the prologue, then do nothing. */
3745
3746void
3747skip_prologue_sal (struct symtab_and_line *sal)
3748{
3749 struct symbol *sym;
3750 struct symtab_and_line start_sal;
3751 CORE_ADDR pc, saved_pc;
3752 struct obj_section *section;
3753 const char *name;
3754 struct objfile *objfile;
3755 struct gdbarch *gdbarch;
3756 const struct block *b, *function_block;
3757 int force_skip, skip;
3758
3759 /* Do not change the SAL if PC was specified explicitly. */
3760 if (sal->explicit_pc)
3761 return;
3762
3763 /* In assembly code, if the user asks for a specific line then we should
3764 not adjust the SAL. The user already has instruction level
3765 visibility in this case, so selecting a line other than one requested
3766 is likely to be the wrong choice. */
3767 if (sal->symtab != nullptr
3768 && sal->explicit_line
3769 && sal->symtab->language () == language_asm)
3770 return;
3771
3772 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3773
3774 switch_to_program_space_and_thread (sal->pspace);
3775
3776 sym = find_pc_sect_function (sal->pc, sal->section);
3777 if (sym != NULL)
3778 {
3779 objfile = sym->objfile ();
3780 pc = sym->value_block ()->entry_pc ();
3781 section = sym->obj_section (objfile);
3782 name = sym->linkage_name ();
3783 }
3784 else
3785 {
3786 struct bound_minimal_symbol msymbol
3787 = lookup_minimal_symbol_by_pc_section (sal->pc, sal->section);
3788
3789 if (msymbol.minsym == NULL)
3790 return;
3791
3792 objfile = msymbol.objfile;
3793 pc = msymbol.value_address ();
3794 section = msymbol.minsym->obj_section (objfile);
3795 name = msymbol.minsym->linkage_name ();
3796 }
3797
3798 gdbarch = objfile->arch ();
3799
3800 /* Process the prologue in two passes. In the first pass try to skip the
3801 prologue (SKIP is true) and verify there is a real need for it (indicated
3802 by FORCE_SKIP). If no such reason was found run a second pass where the
3803 prologue is not skipped (SKIP is false). */
3804
3805 skip = 1;
3806 force_skip = 1;
3807
3808 /* Be conservative - allow direct PC (without skipping prologue) only if we
3809 have proven the CU (Compilation Unit) supports it. sal->SYMTAB does not
3810 have to be set by the caller so we use SYM instead. */
3811 if (sym != NULL
3812 && sym->symtab ()->compunit ()->locations_valid ())
3813 force_skip = 0;
3814
3815 saved_pc = pc;
3816 do
3817 {
3818 pc = saved_pc;
3819
3820 /* Check if the compiler explicitly indicated where a breakpoint should
3821 be placed to skip the prologue. */
3822 if (!ignore_prologue_end_flag && skip)
3823 {
3824 gdb::optional<CORE_ADDR> linetable_pc
3825 = skip_prologue_using_linetable (pc);
3826 if (linetable_pc)
3827 {
3828 pc = *linetable_pc;
3829 start_sal = find_pc_sect_line (pc, section, 0);
3830 force_skip = 1;
3831 continue;
3832 }
3833 }
3834
3835 /* If the function is in an unmapped overlay, use its unmapped LMA address,
3836 so that gdbarch_skip_prologue has something unique to work on. */
3837 if (section_is_overlay (section) && !section_is_mapped (section))
3838 pc = overlay_unmapped_address (pc, section);
3839
3840 /* Skip "first line" of function (which is actually its prologue). */
3841 pc += gdbarch_deprecated_function_start_offset (gdbarch);
3842 if (gdbarch_skip_entrypoint_p (gdbarch))
3843 pc = gdbarch_skip_entrypoint (gdbarch, pc);
3844 if (skip)
3845 pc = gdbarch_skip_prologue_noexcept (gdbarch, pc);
3846
3847 /* For overlays, map pc back into its mapped VMA range. */
3848 pc = overlay_mapped_address (pc, section);
3849
3850 /* Calculate line number. */
3851 start_sal = find_pc_sect_line (pc, section, 0);
3852
3853 /* Check if gdbarch_skip_prologue left us in mid-line, and the next
3854 line is still part of the same function. */
3855 if (skip && start_sal.pc != pc
3856 && (sym ? (sym->value_block ()->entry_pc () <= start_sal.end
3857 && start_sal.end < sym->value_block()->end ())
3858 : (lookup_minimal_symbol_by_pc_section (start_sal.end, section).minsym
3859 == lookup_minimal_symbol_by_pc_section (pc, section).minsym)))
3860 {
3861 /* First pc of next line */
3862 pc = start_sal.end;
3863 /* Recalculate the line number (might not be N+1). */
3864 start_sal = find_pc_sect_line (pc, section, 0);
3865 }
3866
3867 /* On targets with executable formats that don't have a concept of
3868 constructors (ELF with .init has, PE doesn't), gcc emits a call
3869 to `__main' in `main' between the prologue and before user
3870 code. */
3871 if (gdbarch_skip_main_prologue_p (gdbarch)
3872 && name && strcmp_iw (name, "main") == 0)
3873 {
3874 pc = gdbarch_skip_main_prologue (gdbarch, pc);
3875 /* Recalculate the line number (might not be N+1). */
3876 start_sal = find_pc_sect_line (pc, section, 0);
3877 force_skip = 1;
3878 }
3879 }
3880 while (!force_skip && skip--);
3881
3882 /* If we still don't have a valid source line, try to find the first
3883 PC in the lineinfo table that belongs to the same function. This
3884 happens with COFF debug info, which does not seem to have an
3885 entry in lineinfo table for the code after the prologue which has
3886 no direct relation to source. For example, this was found to be
3887 the case with the DJGPP target using "gcc -gcoff" when the
3888 compiler inserted code after the prologue to make sure the stack
3889 is aligned. */
3890 if (!force_skip && sym && start_sal.symtab == NULL)
3891 {
3892 pc = skip_prologue_using_lineinfo (pc, sym->symtab ());
3893 /* Recalculate the line number. */
3894 start_sal = find_pc_sect_line (pc, section, 0);
3895 }
3896
3897 /* If we're already past the prologue, leave SAL unchanged. Otherwise
3898 forward SAL to the end of the prologue. */
3899 if (sal->pc >= pc)
3900 return;
3901
3902 sal->pc = pc;
3903 sal->section = section;
3904 sal->symtab = start_sal.symtab;
3905 sal->line = start_sal.line;
3906 sal->end = start_sal.end;
3907
3908 /* Check if we are now inside an inlined function. If we can,
3909 use the call site of the function instead. */
3910 b = block_for_pc_sect (sal->pc, sal->section);
3911 function_block = NULL;
3912 while (b != NULL)
3913 {
3914 if (b->function () != NULL && b->inlined_p ())
3915 function_block = b;
3916 else if (b->function () != NULL)
3917 break;
3918 b = b->superblock ();
3919 }
3920 if (function_block != NULL
3921 && function_block->function ()->line () != 0)
3922 {
3923 sal->line = function_block->function ()->line ();
3924 sal->symtab = function_block->function ()->symtab ();
3925 }
3926}
3927
3928/* Given PC at the function's start address, attempt to find the
3929 prologue end using SAL information. Return zero if the skip fails.
3930
3931 A non-optimized prologue traditionally has one SAL for the function
3932 and a second for the function body. A single line function has
3933 them both pointing at the same line.
3934
3935 An optimized prologue is similar but the prologue may contain
3936 instructions (SALs) from the instruction body. Need to skip those
3937 while not getting into the function body.
3938
3939 The functions end point and an increasing SAL line are used as
3940 indicators of the prologue's endpoint.
3941
3942 This code is based on the function refine_prologue_limit
3943 (found in ia64). */
3944
3945CORE_ADDR
3946skip_prologue_using_sal (struct gdbarch *gdbarch, CORE_ADDR func_addr)
3947{
3948 struct symtab_and_line prologue_sal;
3949 CORE_ADDR start_pc;
3950 CORE_ADDR end_pc;
3951 const struct block *bl;
3952
3953 /* Get an initial range for the function. */
3954 find_pc_partial_function (func_addr, NULL, &start_pc, &end_pc);
3955 start_pc += gdbarch_deprecated_function_start_offset (gdbarch);
3956
3957 prologue_sal = find_pc_line (start_pc, 0);
3958 if (prologue_sal.line != 0)
3959 {
3960 /* For languages other than assembly, treat two consecutive line
3961 entries at the same address as a zero-instruction prologue.
3962 The GNU assembler emits separate line notes for each instruction
3963 in a multi-instruction macro, but compilers generally will not
3964 do this. */
3965 if (prologue_sal.symtab->language () != language_asm)
3966 {
3967 struct objfile *objfile
3968 = prologue_sal.symtab->compunit ()->objfile ();
3969 const linetable *linetable = prologue_sal.symtab->linetable ();
3970 gdb_assert (linetable->nitems > 0);
3971 int idx = 0;
3972
3973 /* Skip any earlier lines, and any end-of-sequence marker
3974 from a previous function. */
3975 while (idx + 1 < linetable->nitems
3976 && (linetable->item[idx].pc (objfile) != prologue_sal.pc
3977 || linetable->item[idx].line == 0))
3978 idx++;
3979
3980 if (idx + 1 < linetable->nitems
3981 && linetable->item[idx+1].line != 0
3982 && linetable->item[idx+1].pc (objfile) == start_pc)
3983 return start_pc;
3984 }
3985
3986 /* If there is only one sal that covers the entire function,
3987 then it is probably a single line function, like
3988 "foo(){}". */
3989 if (prologue_sal.end >= end_pc)
3990 return 0;
3991
3992 while (prologue_sal.end < end_pc)
3993 {
3994 struct symtab_and_line sal;
3995
3996 sal = find_pc_line (prologue_sal.end, 0);
3997 if (sal.line == 0)
3998 break;
3999 /* Assume that a consecutive SAL for the same (or larger)
4000 line mark the prologue -> body transition. */
4001 if (sal.line >= prologue_sal.line)
4002 break;
4003 /* Likewise if we are in a different symtab altogether
4004 (e.g. within a file included via #include).  */
4005 if (sal.symtab != prologue_sal.symtab)
4006 break;
4007
4008 /* The line number is smaller. Check that it's from the
4009 same function, not something inlined. If it's inlined,
4010 then there is no point comparing the line numbers. */
4011 bl = block_for_pc (prologue_sal.end);
4012 while (bl)
4013 {
4014 if (bl->inlined_p ())
4015 break;
4016 if (bl->function ())
4017 {
4018 bl = NULL;
4019 break;
4020 }
4021 bl = bl->superblock ();
4022 }
4023 if (bl != NULL)
4024 break;
4025
4026 /* The case in which compiler's optimizer/scheduler has
4027 moved instructions into the prologue. We look ahead in
4028 the function looking for address ranges whose
4029 corresponding line number is less the first one that we
4030 found for the function. This is more conservative then
4031 refine_prologue_limit which scans a large number of SALs
4032 looking for any in the prologue. */
4033 prologue_sal = sal;
4034 }
4035 }
4036
4037 if (prologue_sal.end < end_pc)
4038 /* Return the end of this line, or zero if we could not find a
4039 line. */
4040 return prologue_sal.end;
4041 else
4042 /* Don't return END_PC, which is past the end of the function. */
4043 return prologue_sal.pc;
4044}
4045
4046/* See symtab.h. */
4047
4048symbol *
4049find_function_alias_target (bound_minimal_symbol msymbol)
4050{
4051 CORE_ADDR func_addr;
4052 if (!msymbol_is_function (msymbol.objfile, msymbol.minsym, &func_addr))
4053 return NULL;
4054
4055 symbol *sym = find_pc_function (func_addr);
4056 if (sym != NULL
4057 && sym->aclass () == LOC_BLOCK
4058 && sym->value_block ()->entry_pc () == func_addr)
4059 return sym;
4060
4061 return NULL;
4062}
4063
4064\f
4065/* If P is of the form "operator[ \t]+..." where `...' is
4066 some legitimate operator text, return a pointer to the
4067 beginning of the substring of the operator text.
4068 Otherwise, return "". */
4069
4070static const char *
4071operator_chars (const char *p, const char **end)
4072{
4073 *end = "";
4074 if (!startswith (p, CP_OPERATOR_STR))
4075 return *end;
4076 p += CP_OPERATOR_LEN;
4077
4078 /* Don't get faked out by `operator' being part of a longer
4079 identifier. */
4080 if (isalpha (*p) || *p == '_' || *p == '$' || *p == '\0')
4081 return *end;
4082
4083 /* Allow some whitespace between `operator' and the operator symbol. */
4084 while (*p == ' ' || *p == '\t')
4085 p++;
4086
4087 /* Recognize 'operator TYPENAME'. */
4088
4089 if (isalpha (*p) || *p == '_' || *p == '$')
4090 {
4091 const char *q = p + 1;
4092
4093 while (isalnum (*q) || *q == '_' || *q == '$')
4094 q++;
4095 *end = q;
4096 return p;
4097 }
4098
4099 while (*p)
4100 switch (*p)
4101 {
4102 case '\\': /* regexp quoting */
4103 if (p[1] == '*')
4104 {
4105 if (p[2] == '=') /* 'operator\*=' */
4106 *end = p + 3;
4107 else /* 'operator\*' */
4108 *end = p + 2;
4109 return p;
4110 }
4111 else if (p[1] == '[')
4112 {
4113 if (p[2] == ']')
4114 error (_("mismatched quoting on brackets, "
4115 "try 'operator\\[\\]'"));
4116 else if (p[2] == '\\' && p[3] == ']')
4117 {
4118 *end = p + 4; /* 'operator\[\]' */
4119 return p;
4120 }
4121 else
4122 error (_("nothing is allowed between '[' and ']'"));
4123 }
4124 else
4125 {
4126 /* Gratuitous quote: skip it and move on. */
4127 p++;
4128 continue;
4129 }
4130 break;
4131 case '!':
4132 case '=':
4133 case '*':
4134 case '/':
4135 case '%':
4136 case '^':
4137 if (p[1] == '=')
4138 *end = p + 2;
4139 else
4140 *end = p + 1;
4141 return p;
4142 case '<':
4143 case '>':
4144 case '+':
4145 case '-':
4146 case '&':
4147 case '|':
4148 if (p[0] == '-' && p[1] == '>')
4149 {
4150 /* Struct pointer member operator 'operator->'. */
4151 if (p[2] == '*')
4152 {
4153 *end = p + 3; /* 'operator->*' */
4154 return p;
4155 }
4156 else if (p[2] == '\\')
4157 {
4158 *end = p + 4; /* Hopefully 'operator->\*' */
4159 return p;
4160 }
4161 else
4162 {
4163 *end = p + 2; /* 'operator->' */
4164 return p;
4165 }
4166 }
4167 if (p[1] == '=' || p[1] == p[0])
4168 *end = p + 2;
4169 else
4170 *end = p + 1;
4171 return p;
4172 case '~':
4173 case ',':
4174 *end = p + 1;
4175 return p;
4176 case '(':
4177 if (p[1] != ')')
4178 error (_("`operator ()' must be specified "
4179 "without whitespace in `()'"));
4180 *end = p + 2;
4181 return p;
4182 case '?':
4183 if (p[1] != ':')
4184 error (_("`operator ?:' must be specified "
4185 "without whitespace in `?:'"));
4186 *end = p + 2;
4187 return p;
4188 case '[':
4189 if (p[1] != ']')
4190 error (_("`operator []' must be specified "
4191 "without whitespace in `[]'"));
4192 *end = p + 2;
4193 return p;
4194 default:
4195 error (_("`operator %s' not supported"), p);
4196 break;
4197 }
4198
4199 *end = "";
4200 return *end;
4201}
4202\f
4203
4204/* See class declaration. */
4205
4206info_sources_filter::info_sources_filter (match_on match_type,
4207 const char *regexp)
4208 : m_match_type (match_type),
4209 m_regexp (regexp)
4210{
4211 /* Setup the compiled regular expression M_C_REGEXP based on M_REGEXP. */
4212 if (m_regexp != nullptr && *m_regexp != '\0')
4213 {
4214 gdb_assert (m_regexp != nullptr);
4215
4216 int cflags = REG_NOSUB;
4217#ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
4218 cflags |= REG_ICASE;
4219#endif
4220 m_c_regexp.emplace (m_regexp, cflags, _("Invalid regexp"));
4221 }
4222}
4223
4224/* See class declaration. */
4225
4226bool
4227info_sources_filter::matches (const char *fullname) const
4228{
4229 /* Does it match regexp? */
4230 if (m_c_regexp.has_value ())
4231 {
4232 const char *to_match;
4233 std::string dirname;
4234
4235 switch (m_match_type)
4236 {
4237 case match_on::DIRNAME:
4238 dirname = ldirname (fullname);
4239 to_match = dirname.c_str ();
4240 break;
4241 case match_on::BASENAME:
4242 to_match = lbasename (fullname);
4243 break;
4244 case match_on::FULLNAME:
4245 to_match = fullname;
4246 break;
4247 default:
4248 gdb_assert_not_reached ("bad m_match_type");
4249 }
4250
4251 if (m_c_regexp->exec (to_match, 0, NULL, 0) != 0)
4252 return false;
4253 }
4254
4255 return true;
4256}
4257
4258/* Data structure to maintain the state used for printing the results of
4259 the 'info sources' command. */
4260
4261struct output_source_filename_data
4262{
4263 /* Create an object for displaying the results of the 'info sources'
4264 command to UIOUT. FILTER must remain valid and unchanged for the
4265 lifetime of this object as this object retains a reference to FILTER. */
4266 output_source_filename_data (struct ui_out *uiout,
4267 const info_sources_filter &filter)
4268 : m_filter (filter),
4269 m_uiout (uiout)
4270 { /* Nothing. */ }
4271
4272 DISABLE_COPY_AND_ASSIGN (output_source_filename_data);
4273
4274 /* Reset enough state of this object so we can match against a new set of
4275 files. The existing regular expression is retained though. */
4276 void reset_output ()
4277 {
4278 m_first = true;
4279 m_filename_seen_cache.clear ();
4280 }
4281
4282 /* Worker for sources_info, outputs the file name formatted for either
4283 cli or mi (based on the current_uiout). In cli mode displays
4284 FULLNAME with a comma separating this name from any previously
4285 printed name (line breaks are added at the comma). In MI mode
4286 outputs a tuple containing DISP_NAME (the files display name),
4287 FULLNAME, and EXPANDED_P (true when this file is from a fully
4288 expanded symtab, otherwise false). */
4289 void output (const char *disp_name, const char *fullname, bool expanded_p);
4290
4291 /* An overload suitable for use as a callback to
4292 quick_symbol_functions::map_symbol_filenames. */
4293 void operator() (const char *filename, const char *fullname)
4294 {
4295 /* The false here indicates that this file is from an unexpanded
4296 symtab. */
4297 output (filename, fullname, false);
4298 }
4299
4300 /* Return true if at least one filename has been printed (after a call to
4301 output) since either this object was created, or the last call to
4302 reset_output. */
4303 bool printed_filename_p () const
4304 {
4305 return !m_first;
4306 }
4307
4308private:
4309
4310 /* Flag of whether we're printing the first one. */
4311 bool m_first = true;
4312
4313 /* Cache of what we've seen so far. */
4314 filename_seen_cache m_filename_seen_cache;
4315
4316 /* How source filename should be filtered. */
4317 const info_sources_filter &m_filter;
4318
4319 /* The object to which output is sent. */
4320 struct ui_out *m_uiout;
4321};
4322
4323/* See comment in class declaration above. */
4324
4325void
4326output_source_filename_data::output (const char *disp_name,
4327 const char *fullname,
4328 bool expanded_p)
4329{
4330 /* Since a single source file can result in several partial symbol
4331 tables, we need to avoid printing it more than once. Note: if
4332 some of the psymtabs are read in and some are not, it gets
4333 printed both under "Source files for which symbols have been
4334 read" and "Source files for which symbols will be read in on
4335 demand". I consider this a reasonable way to deal with the
4336 situation. I'm not sure whether this can also happen for
4337 symtabs; it doesn't hurt to check. */
4338
4339 /* Was NAME already seen? If so, then don't print it again. */
4340 if (m_filename_seen_cache.seen (fullname))
4341 return;
4342
4343 /* If the filter rejects this file then don't print it. */
4344 if (!m_filter.matches (fullname))
4345 return;
4346
4347 ui_out_emit_tuple ui_emitter (m_uiout, nullptr);
4348
4349 /* Print it and reset *FIRST. */
4350 if (!m_first)
4351 m_uiout->text (", ");
4352 m_first = false;
4353
4354 m_uiout->wrap_hint (0);
4355 if (m_uiout->is_mi_like_p ())
4356 {
4357 m_uiout->field_string ("file", disp_name, file_name_style.style ());
4358 if (fullname != nullptr)
4359 m_uiout->field_string ("fullname", fullname,
4360 file_name_style.style ());
4361 m_uiout->field_string ("debug-fully-read",
4362 (expanded_p ? "true" : "false"));
4363 }
4364 else
4365 {
4366 if (fullname == nullptr)
4367 fullname = disp_name;
4368 m_uiout->field_string ("fullname", fullname,
4369 file_name_style.style ());
4370 }
4371}
4372
4373/* For the 'info sources' command, what part of the file names should we be
4374 matching the user supplied regular expression against? */
4375
4376struct filename_partial_match_opts
4377{
4378 /* Only match the directory name part. */
4379 bool dirname = false;
4380
4381 /* Only match the basename part. */
4382 bool basename = false;
4383};
4384
4385using isrc_flag_option_def
4386 = gdb::option::flag_option_def<filename_partial_match_opts>;
4387
4388static const gdb::option::option_def info_sources_option_defs[] = {
4389
4390 isrc_flag_option_def {
4391 "dirname",
4392 [] (filename_partial_match_opts *opts) { return &opts->dirname; },
4393 N_("Show only the files having a dirname matching REGEXP."),
4394 },
4395
4396 isrc_flag_option_def {
4397 "basename",
4398 [] (filename_partial_match_opts *opts) { return &opts->basename; },
4399 N_("Show only the files having a basename matching REGEXP."),
4400 },
4401
4402};
4403
4404/* Create an option_def_group for the "info sources" options, with
4405 ISRC_OPTS as context. */
4406
4407static inline gdb::option::option_def_group
4408make_info_sources_options_def_group (filename_partial_match_opts *isrc_opts)
4409{
4410 return {{info_sources_option_defs}, isrc_opts};
4411}
4412
4413/* Completer for "info sources". */
4414
4415static void
4416info_sources_command_completer (cmd_list_element *ignore,
4417 completion_tracker &tracker,
4418 const char *text, const char *word)
4419{
4420 const auto group = make_info_sources_options_def_group (nullptr);
4421 if (gdb::option::complete_options
4422 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
4423 return;
4424}
4425
4426/* See symtab.h. */
4427
4428void
4429info_sources_worker (struct ui_out *uiout,
4430 bool group_by_objfile,
4431 const info_sources_filter &filter)
4432{
4433 output_source_filename_data data (uiout, filter);
4434
4435 ui_out_emit_list results_emitter (uiout, "files");
4436 gdb::optional<ui_out_emit_tuple> output_tuple;
4437 gdb::optional<ui_out_emit_list> sources_list;
4438
4439 gdb_assert (group_by_objfile || uiout->is_mi_like_p ());
4440
4441 for (objfile *objfile : current_program_space->objfiles ())
4442 {
4443 if (group_by_objfile)
4444 {
4445 output_tuple.emplace (uiout, nullptr);
4446 uiout->field_string ("filename", objfile_name (objfile),
4447 file_name_style.style ());
4448 uiout->text (":\n");
4449 bool debug_fully_readin = !objfile->has_unexpanded_symtabs ();
4450 if (uiout->is_mi_like_p ())
4451 {
4452 const char *debug_info_state;
4453 if (objfile_has_symbols (objfile))
4454 {
4455 if (debug_fully_readin)
4456 debug_info_state = "fully-read";
4457 else
4458 debug_info_state = "partially-read";
4459 }
4460 else
4461 debug_info_state = "none";
4462 current_uiout->field_string ("debug-info", debug_info_state);
4463 }
4464 else
4465 {
4466 if (!debug_fully_readin)
4467 uiout->text ("(Full debug information has not yet been read "
4468 "for this file.)\n");
4469 if (!objfile_has_symbols (objfile))
4470 uiout->text ("(Objfile has no debug information.)\n");
4471 uiout->text ("\n");
4472 }
4473 sources_list.emplace (uiout, "sources");
4474 }
4475
4476 for (compunit_symtab *cu : objfile->compunits ())
4477 {
4478 for (symtab *s : cu->filetabs ())
4479 {
4480 const char *file = symtab_to_filename_for_display (s);
4481 const char *fullname = symtab_to_fullname (s);
4482 data.output (file, fullname, true);
4483 }
4484 }
4485
4486 if (group_by_objfile)
4487 {
4488 objfile->map_symbol_filenames (data, true /* need_fullname */);
4489 if (data.printed_filename_p ())
4490 uiout->text ("\n\n");
4491 data.reset_output ();
4492 sources_list.reset ();
4493 output_tuple.reset ();
4494 }
4495 }
4496
4497 if (!group_by_objfile)
4498 {
4499 data.reset_output ();
4500 map_symbol_filenames (data, true /*need_fullname*/);
4501 }
4502}
4503
4504/* Implement the 'info sources' command. */
4505
4506static void
4507info_sources_command (const char *args, int from_tty)
4508{
4509 if (!have_full_symbols () && !have_partial_symbols ())
4510 error (_("No symbol table is loaded. Use the \"file\" command."));
4511
4512 filename_partial_match_opts match_opts;
4513 auto group = make_info_sources_options_def_group (&match_opts);
4514 gdb::option::process_options
4515 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
4516
4517 if (match_opts.dirname && match_opts.basename)
4518 error (_("You cannot give both -basename and -dirname to 'info sources'."));
4519
4520 const char *regex = nullptr;
4521 if (args != NULL && *args != '\000')
4522 regex = args;
4523
4524 if ((match_opts.dirname || match_opts.basename) && regex == nullptr)
4525 error (_("Missing REGEXP for 'info sources'."));
4526
4527 info_sources_filter::match_on match_type;
4528 if (match_opts.dirname)
4529 match_type = info_sources_filter::match_on::DIRNAME;
4530 else if (match_opts.basename)
4531 match_type = info_sources_filter::match_on::BASENAME;
4532 else
4533 match_type = info_sources_filter::match_on::FULLNAME;
4534
4535 info_sources_filter filter (match_type, regex);
4536 info_sources_worker (current_uiout, true, filter);
4537}
4538
4539/* Compare FILE against all the entries of FILENAMES. If BASENAMES is
4540 true compare only lbasename of FILENAMES. */
4541
4542static bool
4543file_matches (const char *file, const std::vector<const char *> &filenames,
4544 bool basenames)
4545{
4546 if (filenames.empty ())
4547 return true;
4548
4549 for (const char *name : filenames)
4550 {
4551 name = (basenames ? lbasename (name) : name);
4552 if (compare_filenames_for_search (file, name))
4553 return true;
4554 }
4555
4556 return false;
4557}
4558
4559/* Helper function for std::sort on symbol_search objects. Can only sort
4560 symbols, not minimal symbols. */
4561
4562int
4563symbol_search::compare_search_syms (const symbol_search &sym_a,
4564 const symbol_search &sym_b)
4565{
4566 int c;
4567
4568 c = FILENAME_CMP (sym_a.symbol->symtab ()->filename,
4569 sym_b.symbol->symtab ()->filename);
4570 if (c != 0)
4571 return c;
4572
4573 if (sym_a.block != sym_b.block)
4574 return sym_a.block - sym_b.block;
4575
4576 return strcmp (sym_a.symbol->print_name (), sym_b.symbol->print_name ());
4577}
4578
4579/* Returns true if the type_name of symbol_type of SYM matches TREG.
4580 If SYM has no symbol_type or symbol_name, returns false. */
4581
4582bool
4583treg_matches_sym_type_name (const compiled_regex &treg,
4584 const struct symbol *sym)
4585{
4586 struct type *sym_type;
4587 std::string printed_sym_type_name;
4588
4589 symbol_lookup_debug_printf_v ("treg_matches_sym_type_name, sym %s",
4590 sym->natural_name ());
4591
4592 sym_type = sym->type ();
4593 if (sym_type == NULL)
4594 return false;
4595
4596 {
4597 scoped_switch_to_sym_language_if_auto l (sym);
4598
4599 printed_sym_type_name = type_to_string (sym_type);
4600 }
4601
4602 symbol_lookup_debug_printf_v ("sym_type_name %s",
4603 printed_sym_type_name.c_str ());
4604
4605 if (printed_sym_type_name.empty ())
4606 return false;
4607
4608 return treg.exec (printed_sym_type_name.c_str (), 0, NULL, 0) == 0;
4609}
4610
4611/* See symtab.h. */
4612
4613bool
4614global_symbol_searcher::is_suitable_msymbol
4615 (const enum search_domain kind, const minimal_symbol *msymbol)
4616{
4617 switch (msymbol->type ())
4618 {
4619 case mst_data:
4620 case mst_bss:
4621 case mst_file_data:
4622 case mst_file_bss:
4623 return kind == VARIABLES_DOMAIN;
4624 case mst_text:
4625 case mst_file_text:
4626 case mst_solib_trampoline:
4627 case mst_text_gnu_ifunc:
4628 return kind == FUNCTIONS_DOMAIN;
4629 default:
4630 return false;
4631 }
4632}
4633
4634/* See symtab.h. */
4635
4636bool
4637global_symbol_searcher::expand_symtabs
4638 (objfile *objfile, const gdb::optional<compiled_regex> &preg) const
4639{
4640 enum search_domain kind = m_kind;
4641 bool found_msymbol = false;
4642
4643 auto do_file_match = [&] (const char *filename, bool basenames)
4644 {
4645 return file_matches (filename, filenames, basenames);
4646 };
4647 gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher = nullptr;
4648 if (!filenames.empty ())
4649 file_matcher = do_file_match;
4650
4651 objfile->expand_symtabs_matching
4652 (file_matcher,
4653 &lookup_name_info::match_any (),
4654 [&] (const char *symname)
4655 {
4656 return (!preg.has_value ()
4657 || preg->exec (symname, 0, NULL, 0) == 0);
4658 },
4659 NULL,
4660 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
4661 UNDEF_DOMAIN,
4662 kind);
4663
4664 /* Here, we search through the minimal symbol tables for functions and
4665 variables that match, and force their symbols to be read. This is in
4666 particular necessary for demangled variable names, which are no longer
4667 put into the partial symbol tables. The symbol will then be found
4668 during the scan of symtabs later.
4669
4670 For functions, find_pc_symtab should succeed if we have debug info for
4671 the function, for variables we have to call
4672 lookup_symbol_in_objfile_from_linkage_name to determine if the
4673 variable has debug info. If the lookup fails, set found_msymbol so
4674 that we will rescan to print any matching symbols without debug info.
4675 We only search the objfile the msymbol came from, we no longer search
4676 all objfiles. In large programs (1000s of shared libs) searching all
4677 objfiles is not worth the pain. */
4678 if (filenames.empty ()
4679 && (kind == VARIABLES_DOMAIN || kind == FUNCTIONS_DOMAIN))
4680 {
4681 for (minimal_symbol *msymbol : objfile->msymbols ())
4682 {
4683 QUIT;
4684
4685 if (msymbol->created_by_gdb)
4686 continue;
4687
4688 if (is_suitable_msymbol (kind, msymbol))
4689 {
4690 if (!preg.has_value ()
4691 || preg->exec (msymbol->natural_name (), 0,
4692 NULL, 0) == 0)
4693 {
4694 /* An important side-effect of these lookup functions is
4695 to expand the symbol table if msymbol is found, later
4696 in the process we will add matching symbols or
4697 msymbols to the results list, and that requires that
4698 the symbols tables are expanded. */
4699 if (kind == FUNCTIONS_DOMAIN
4700 ? (find_pc_compunit_symtab
4701 (msymbol->value_address (objfile)) == NULL)
4702 : (lookup_symbol_in_objfile_from_linkage_name
4703 (objfile, msymbol->linkage_name (),
4704 VAR_DOMAIN)
4705 .symbol == NULL))
4706 found_msymbol = true;
4707 }
4708 }
4709 }
4710 }
4711
4712 return found_msymbol;
4713}
4714
4715/* See symtab.h. */
4716
4717bool
4718global_symbol_searcher::add_matching_symbols
4719 (objfile *objfile,
4720 const gdb::optional<compiled_regex> &preg,
4721 const gdb::optional<compiled_regex> &treg,
4722 std::set<symbol_search> *result_set) const
4723{
4724 enum search_domain kind = m_kind;
4725
4726 /* Add matching symbols (if not already present). */
4727 for (compunit_symtab *cust : objfile->compunits ())
4728 {
4729 const struct blockvector *bv = cust->blockvector ();
4730
4731 for (block_enum block : { GLOBAL_BLOCK, STATIC_BLOCK })
4732 {
4733 const struct block *b = bv->block (block);
4734
4735 for (struct symbol *sym : block_iterator_range (b))
4736 {
4737 struct symtab *real_symtab = sym->symtab ();
4738
4739 QUIT;
4740
4741 /* Check first sole REAL_SYMTAB->FILENAME. It does
4742 not need to be a substring of symtab_to_fullname as
4743 it may contain "./" etc. */
4744 if ((file_matches (real_symtab->filename, filenames, false)
4745 || ((basenames_may_differ
4746 || file_matches (lbasename (real_symtab->filename),
4747 filenames, true))
4748 && file_matches (symtab_to_fullname (real_symtab),
4749 filenames, false)))
4750 && ((!preg.has_value ()
4751 || preg->exec (sym->natural_name (), 0,
4752 NULL, 0) == 0)
4753 && ((kind == VARIABLES_DOMAIN
4754 && sym->aclass () != LOC_TYPEDEF
4755 && sym->aclass () != LOC_UNRESOLVED
4756 && sym->aclass () != LOC_BLOCK
4757 /* LOC_CONST can be used for more than
4758 just enums, e.g., c++ static const
4759 members. We only want to skip enums
4760 here. */
4761 && !(sym->aclass () == LOC_CONST
4762 && (sym->type ()->code ()
4763 == TYPE_CODE_ENUM))
4764 && (!treg.has_value ()
4765 || treg_matches_sym_type_name (*treg, sym)))
4766 || (kind == FUNCTIONS_DOMAIN
4767 && sym->aclass () == LOC_BLOCK
4768 && (!treg.has_value ()
4769 || treg_matches_sym_type_name (*treg,
4770 sym)))
4771 || (kind == TYPES_DOMAIN
4772 && sym->aclass () == LOC_TYPEDEF
4773 && sym->domain () != MODULE_DOMAIN)
4774 || (kind == MODULES_DOMAIN
4775 && sym->domain () == MODULE_DOMAIN
4776 && sym->line () != 0))))
4777 {
4778 if (result_set->size () < m_max_search_results)
4779 {
4780 /* Match, insert if not already in the results. */
4781 symbol_search ss (block, sym);
4782 if (result_set->find (ss) == result_set->end ())
4783 result_set->insert (ss);
4784 }
4785 else
4786 return false;
4787 }
4788 }
4789 }
4790 }
4791
4792 return true;
4793}
4794
4795/* See symtab.h. */
4796
4797bool
4798global_symbol_searcher::add_matching_msymbols
4799 (objfile *objfile, const gdb::optional<compiled_regex> &preg,
4800 std::vector<symbol_search> *results) const
4801{
4802 enum search_domain kind = m_kind;
4803
4804 for (minimal_symbol *msymbol : objfile->msymbols ())
4805 {
4806 QUIT;
4807
4808 if (msymbol->created_by_gdb)
4809 continue;
4810
4811 if (is_suitable_msymbol (kind, msymbol))
4812 {
4813 if (!preg.has_value ()
4814 || preg->exec (msymbol->natural_name (), 0,
4815 NULL, 0) == 0)
4816 {
4817 /* For functions we can do a quick check of whether the
4818 symbol might be found via find_pc_symtab. */
4819 if (kind != FUNCTIONS_DOMAIN
4820 || (find_pc_compunit_symtab
4821 (msymbol->value_address (objfile)) == NULL))
4822 {
4823 if (lookup_symbol_in_objfile_from_linkage_name
4824 (objfile, msymbol->linkage_name (),
4825 VAR_DOMAIN).symbol == NULL)
4826 {
4827 /* Matching msymbol, add it to the results list. */
4828 if (results->size () < m_max_search_results)
4829 results->emplace_back (GLOBAL_BLOCK, msymbol, objfile);
4830 else
4831 return false;
4832 }
4833 }
4834 }
4835 }
4836 }
4837
4838 return true;
4839}
4840
4841/* See symtab.h. */
4842
4843std::vector<symbol_search>
4844global_symbol_searcher::search () const
4845{
4846 gdb::optional<compiled_regex> preg;
4847 gdb::optional<compiled_regex> treg;
4848
4849 gdb_assert (m_kind != ALL_DOMAIN);
4850
4851 if (m_symbol_name_regexp != NULL)
4852 {
4853 const char *symbol_name_regexp = m_symbol_name_regexp;
4854 std::string symbol_name_regexp_holder;
4855
4856 /* Make sure spacing is right for C++ operators.
4857 This is just a courtesy to make the matching less sensitive
4858 to how many spaces the user leaves between 'operator'
4859 and <TYPENAME> or <OPERATOR>. */
4860 const char *opend;
4861 const char *opname = operator_chars (symbol_name_regexp, &opend);
4862
4863 if (*opname)
4864 {
4865 int fix = -1; /* -1 means ok; otherwise number of
4866 spaces needed. */
4867
4868 if (isalpha (*opname) || *opname == '_' || *opname == '$')
4869 {
4870 /* There should 1 space between 'operator' and 'TYPENAME'. */
4871 if (opname[-1] != ' ' || opname[-2] == ' ')
4872 fix = 1;
4873 }
4874 else
4875 {
4876 /* There should 0 spaces between 'operator' and 'OPERATOR'. */
4877 if (opname[-1] == ' ')
4878 fix = 0;
4879 }
4880 /* If wrong number of spaces, fix it. */
4881 if (fix >= 0)
4882 {
4883 symbol_name_regexp_holder
4884 = string_printf ("operator%.*s%s", fix, " ", opname);
4885 symbol_name_regexp = symbol_name_regexp_holder.c_str ();
4886 }
4887 }
4888
4889 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
4890 ? REG_ICASE : 0);
4891 preg.emplace (symbol_name_regexp, cflags,
4892 _("Invalid regexp"));
4893 }
4894
4895 if (m_symbol_type_regexp != NULL)
4896 {
4897 int cflags = REG_NOSUB | (case_sensitivity == case_sensitive_off
4898 ? REG_ICASE : 0);
4899 treg.emplace (m_symbol_type_regexp, cflags,
4900 _("Invalid regexp"));
4901 }
4902
4903 bool found_msymbol = false;
4904 std::set<symbol_search> result_set;
4905 for (objfile *objfile : current_program_space->objfiles ())
4906 {
4907 /* Expand symtabs within objfile that possibly contain matching
4908 symbols. */
4909 found_msymbol |= expand_symtabs (objfile, preg);
4910
4911 /* Find matching symbols within OBJFILE and add them in to the
4912 RESULT_SET set. Use a set here so that we can easily detect
4913 duplicates as we go, and can therefore track how many unique
4914 matches we have found so far. */
4915 if (!add_matching_symbols (objfile, preg, treg, &result_set))
4916 break;
4917 }
4918
4919 /* Convert the result set into a sorted result list, as std::set is
4920 defined to be sorted then no explicit call to std::sort is needed. */
4921 std::vector<symbol_search> result (result_set.begin (), result_set.end ());
4922
4923 /* If there are no debug symbols, then add matching minsyms. But if the
4924 user wants to see symbols matching a type regexp, then never give a
4925 minimal symbol, as we assume that a minimal symbol does not have a
4926 type. */
4927 if ((found_msymbol || (filenames.empty () && m_kind == VARIABLES_DOMAIN))
4928 && !m_exclude_minsyms
4929 && !treg.has_value ())
4930 {
4931 gdb_assert (m_kind == VARIABLES_DOMAIN || m_kind == FUNCTIONS_DOMAIN);
4932 for (objfile *objfile : current_program_space->objfiles ())
4933 if (!add_matching_msymbols (objfile, preg, &result))
4934 break;
4935 }
4936
4937 return result;
4938}
4939
4940/* See symtab.h. */
4941
4942std::string
4943symbol_to_info_string (struct symbol *sym, int block,
4944 enum search_domain kind)
4945{
4946 std::string str;
4947
4948 gdb_assert (block == GLOBAL_BLOCK || block == STATIC_BLOCK);
4949
4950 if (kind != TYPES_DOMAIN && block == STATIC_BLOCK)
4951 str += "static ";
4952
4953 /* Typedef that is not a C++ class. */
4954 if (kind == TYPES_DOMAIN
4955 && sym->domain () != STRUCT_DOMAIN)
4956 {
4957 string_file tmp_stream;
4958
4959 /* FIXME: For C (and C++) we end up with a difference in output here
4960 between how a typedef is printed, and non-typedefs are printed.
4961 The TYPEDEF_PRINT code places a ";" at the end in an attempt to
4962 appear C-like, while TYPE_PRINT doesn't.
4963
4964 For the struct printing case below, things are worse, we force
4965 printing of the ";" in this function, which is going to be wrong
4966 for languages that don't require a ";" between statements. */
4967 if (sym->type ()->code () == TYPE_CODE_TYPEDEF)
4968 typedef_print (sym->type (), sym, &tmp_stream);
4969 else
4970 type_print (sym->type (), "", &tmp_stream, -1);
4971 str += tmp_stream.string ();
4972 }
4973 /* variable, func, or typedef-that-is-c++-class. */
4974 else if (kind < TYPES_DOMAIN
4975 || (kind == TYPES_DOMAIN
4976 && sym->domain () == STRUCT_DOMAIN))
4977 {
4978 string_file tmp_stream;
4979
4980 type_print (sym->type (),
4981 (sym->aclass () == LOC_TYPEDEF
4982 ? "" : sym->print_name ()),
4983 &tmp_stream, 0);
4984
4985 str += tmp_stream.string ();
4986 str += ";";
4987 }
4988 /* Printing of modules is currently done here, maybe at some future
4989 point we might want a language specific method to print the module
4990 symbol so that we can customise the output more. */
4991 else if (kind == MODULES_DOMAIN)
4992 str += sym->print_name ();
4993
4994 return str;
4995}
4996
4997/* Helper function for symbol info commands, for example 'info functions',
4998 'info variables', etc. KIND is the kind of symbol we searched for, and
4999 BLOCK is the type of block the symbols was found in, either GLOBAL_BLOCK
5000 or STATIC_BLOCK. SYM is the symbol we found. If LAST is not NULL,
5001 print file and line number information for the symbol as well. Skip
5002 printing the filename if it matches LAST. */
5003
5004static void
5005print_symbol_info (enum search_domain kind,
5006 struct symbol *sym,
5007 int block, const char *last)
5008{
5009 scoped_switch_to_sym_language_if_auto l (sym);
5010 struct symtab *s = sym->symtab ();
5011
5012 if (last != NULL)
5013 {
5014 const char *s_filename = symtab_to_filename_for_display (s);
5015
5016 if (filename_cmp (last, s_filename) != 0)
5017 {
5018 gdb_printf (_("\nFile %ps:\n"),
5019 styled_string (file_name_style.style (),
5020 s_filename));
5021 }
5022
5023 if (sym->line () != 0)
5024 gdb_printf ("%d:\t", sym->line ());
5025 else
5026 gdb_puts ("\t");
5027 }
5028
5029 std::string str = symbol_to_info_string (sym, block, kind);
5030 gdb_printf ("%s\n", str.c_str ());
5031}
5032
5033/* This help function for symtab_symbol_info() prints information
5034 for non-debugging symbols to gdb_stdout. */
5035
5036static void
5037print_msymbol_info (struct bound_minimal_symbol msymbol)
5038{
5039 struct gdbarch *gdbarch = msymbol.objfile->arch ();
5040 char *tmp;
5041
5042 if (gdbarch_addr_bit (gdbarch) <= 32)
5043 tmp = hex_string_custom (msymbol.value_address ()
5044 & (CORE_ADDR) 0xffffffff,
5045 8);
5046 else
5047 tmp = hex_string_custom (msymbol.value_address (),
5048 16);
5049
5050 ui_file_style sym_style = (msymbol.minsym->text_p ()
5051 ? function_name_style.style ()
5052 : ui_file_style ());
5053
5054 gdb_printf (_("%ps %ps\n"),
5055 styled_string (address_style.style (), tmp),
5056 styled_string (sym_style, msymbol.minsym->print_name ()));
5057}
5058
5059/* This is the guts of the commands "info functions", "info types", and
5060 "info variables". It calls search_symbols to find all matches and then
5061 print_[m]symbol_info to print out some useful information about the
5062 matches. */
5063
5064static void
5065symtab_symbol_info (bool quiet, bool exclude_minsyms,
5066 const char *regexp, enum search_domain kind,
5067 const char *t_regexp, int from_tty)
5068{
5069 static const char * const classnames[] =
5070 {"variable", "function", "type", "module"};
5071 const char *last_filename = "";
5072 int first = 1;
5073
5074 gdb_assert (kind != ALL_DOMAIN);
5075
5076 if (regexp != nullptr && *regexp == '\0')
5077 regexp = nullptr;
5078
5079 global_symbol_searcher spec (kind, regexp);
5080 spec.set_symbol_type_regexp (t_regexp);
5081 spec.set_exclude_minsyms (exclude_minsyms);
5082 std::vector<symbol_search> symbols = spec.search ();
5083
5084 if (!quiet)
5085 {
5086 if (regexp != NULL)
5087 {
5088 if (t_regexp != NULL)
5089 gdb_printf
5090 (_("All %ss matching regular expression \"%s\""
5091 " with type matching regular expression \"%s\":\n"),
5092 classnames[kind], regexp, t_regexp);
5093 else
5094 gdb_printf (_("All %ss matching regular expression \"%s\":\n"),
5095 classnames[kind], regexp);
5096 }
5097 else
5098 {
5099 if (t_regexp != NULL)
5100 gdb_printf
5101 (_("All defined %ss"
5102 " with type matching regular expression \"%s\" :\n"),
5103 classnames[kind], t_regexp);
5104 else
5105 gdb_printf (_("All defined %ss:\n"), classnames[kind]);
5106 }
5107 }
5108
5109 for (const symbol_search &p : symbols)
5110 {
5111 QUIT;
5112
5113 if (p.msymbol.minsym != NULL)
5114 {
5115 if (first)
5116 {
5117 if (!quiet)
5118 gdb_printf (_("\nNon-debugging symbols:\n"));
5119 first = 0;
5120 }
5121 print_msymbol_info (p.msymbol);
5122 }
5123 else
5124 {
5125 print_symbol_info (kind,
5126 p.symbol,
5127 p.block,
5128 last_filename);
5129 last_filename
5130 = symtab_to_filename_for_display (p.symbol->symtab ());
5131 }
5132 }
5133}
5134
5135/* Structure to hold the values of the options used by the 'info variables'
5136 and 'info functions' commands. These correspond to the -q, -t, and -n
5137 options. */
5138
5139struct info_vars_funcs_options
5140{
5141 bool quiet = false;
5142 bool exclude_minsyms = false;
5143 std::string type_regexp;
5144};
5145
5146/* The options used by the 'info variables' and 'info functions'
5147 commands. */
5148
5149static const gdb::option::option_def info_vars_funcs_options_defs[] = {
5150 gdb::option::boolean_option_def<info_vars_funcs_options> {
5151 "q",
5152 [] (info_vars_funcs_options *opt) { return &opt->quiet; },
5153 nullptr, /* show_cmd_cb */
5154 nullptr /* set_doc */
5155 },
5156
5157 gdb::option::boolean_option_def<info_vars_funcs_options> {
5158 "n",
5159 [] (info_vars_funcs_options *opt) { return &opt->exclude_minsyms; },
5160 nullptr, /* show_cmd_cb */
5161 nullptr /* set_doc */
5162 },
5163
5164 gdb::option::string_option_def<info_vars_funcs_options> {
5165 "t",
5166 [] (info_vars_funcs_options *opt) { return &opt->type_regexp; },
5167 nullptr, /* show_cmd_cb */
5168 nullptr /* set_doc */
5169 }
5170};
5171
5172/* Returns the option group used by 'info variables' and 'info
5173 functions'. */
5174
5175static gdb::option::option_def_group
5176make_info_vars_funcs_options_def_group (info_vars_funcs_options *opts)
5177{
5178 return {{info_vars_funcs_options_defs}, opts};
5179}
5180
5181/* Command completer for 'info variables' and 'info functions'. */
5182
5183static void
5184info_vars_funcs_command_completer (struct cmd_list_element *ignore,
5185 completion_tracker &tracker,
5186 const char *text, const char * /* word */)
5187{
5188 const auto group
5189 = make_info_vars_funcs_options_def_group (nullptr);
5190 if (gdb::option::complete_options
5191 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5192 return;
5193
5194 const char *word = advance_to_expression_complete_word_point (tracker, text);
5195 symbol_completer (ignore, tracker, text, word);
5196}
5197
5198/* Implement the 'info variables' command. */
5199
5200static void
5201info_variables_command (const char *args, int from_tty)
5202{
5203 info_vars_funcs_options opts;
5204 auto grp = make_info_vars_funcs_options_def_group (&opts);
5205 gdb::option::process_options
5206 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5207 if (args != nullptr && *args == '\0')
5208 args = nullptr;
5209
5210 symtab_symbol_info
5211 (opts.quiet, opts.exclude_minsyms, args, VARIABLES_DOMAIN,
5212 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5213 from_tty);
5214}
5215
5216/* Implement the 'info functions' command. */
5217
5218static void
5219info_functions_command (const char *args, int from_tty)
5220{
5221 info_vars_funcs_options opts;
5222
5223 auto grp = make_info_vars_funcs_options_def_group (&opts);
5224 gdb::option::process_options
5225 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5226 if (args != nullptr && *args == '\0')
5227 args = nullptr;
5228
5229 symtab_symbol_info
5230 (opts.quiet, opts.exclude_minsyms, args, FUNCTIONS_DOMAIN,
5231 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
5232 from_tty);
5233}
5234
5235/* Holds the -q option for the 'info types' command. */
5236
5237struct info_types_options
5238{
5239 bool quiet = false;
5240};
5241
5242/* The options used by the 'info types' command. */
5243
5244static const gdb::option::option_def info_types_options_defs[] = {
5245 gdb::option::boolean_option_def<info_types_options> {
5246 "q",
5247 [] (info_types_options *opt) { return &opt->quiet; },
5248 nullptr, /* show_cmd_cb */
5249 nullptr /* set_doc */
5250 }
5251};
5252
5253/* Returns the option group used by 'info types'. */
5254
5255static gdb::option::option_def_group
5256make_info_types_options_def_group (info_types_options *opts)
5257{
5258 return {{info_types_options_defs}, opts};
5259}
5260
5261/* Implement the 'info types' command. */
5262
5263static void
5264info_types_command (const char *args, int from_tty)
5265{
5266 info_types_options opts;
5267
5268 auto grp = make_info_types_options_def_group (&opts);
5269 gdb::option::process_options
5270 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5271 if (args != nullptr && *args == '\0')
5272 args = nullptr;
5273 symtab_symbol_info (opts.quiet, false, args, TYPES_DOMAIN, NULL, from_tty);
5274}
5275
5276/* Command completer for 'info types' command. */
5277
5278static void
5279info_types_command_completer (struct cmd_list_element *ignore,
5280 completion_tracker &tracker,
5281 const char *text, const char * /* word */)
5282{
5283 const auto group
5284 = make_info_types_options_def_group (nullptr);
5285 if (gdb::option::complete_options
5286 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
5287 return;
5288
5289 const char *word = advance_to_expression_complete_word_point (tracker, text);
5290 symbol_completer (ignore, tracker, text, word);
5291}
5292
5293/* Implement the 'info modules' command. */
5294
5295static void
5296info_modules_command (const char *args, int from_tty)
5297{
5298 info_types_options opts;
5299
5300 auto grp = make_info_types_options_def_group (&opts);
5301 gdb::option::process_options
5302 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
5303 if (args != nullptr && *args == '\0')
5304 args = nullptr;
5305 symtab_symbol_info (opts.quiet, true, args, MODULES_DOMAIN, NULL,
5306 from_tty);
5307}
5308
5309/* Implement the 'info main' command. */
5310
5311static void
5312info_main_command (const char *args, int from_tty)
5313{
5314 gdb_printf ("%s\n", main_name ());
5315}
5316
5317static void
5318rbreak_command (const char *regexp, int from_tty)
5319{
5320 std::string string;
5321 const char *file_name = nullptr;
5322
5323 if (regexp != nullptr)
5324 {
5325 const char *colon = strchr (regexp, ':');
5326
5327 /* Ignore the colon if it is part of a Windows drive. */
5328 if (HAS_DRIVE_SPEC (regexp)
5329 && (regexp[2] == '/' || regexp[2] == '\\'))
5330 colon = strchr (STRIP_DRIVE_SPEC (regexp), ':');
5331
5332 if (colon && *(colon + 1) != ':')
5333 {
5334 int colon_index;
5335 char *local_name;
5336
5337 colon_index = colon - regexp;
5338 local_name = (char *) alloca (colon_index + 1);
5339 memcpy (local_name, regexp, colon_index);
5340 local_name[colon_index--] = 0;
5341 while (isspace (local_name[colon_index]))
5342 local_name[colon_index--] = 0;
5343 file_name = local_name;
5344 regexp = skip_spaces (colon + 1);
5345 }
5346 }
5347
5348 global_symbol_searcher spec (FUNCTIONS_DOMAIN, regexp);
5349 if (file_name != nullptr)
5350 spec.filenames.push_back (file_name);
5351 std::vector<symbol_search> symbols = spec.search ();
5352
5353 scoped_rbreak_breakpoints finalize;
5354 for (const symbol_search &p : symbols)
5355 {
5356 if (p.msymbol.minsym == NULL)
5357 {
5358 struct symtab *symtab = p.symbol->symtab ();
5359 const char *fullname = symtab_to_fullname (symtab);
5360
5361 string = string_printf ("%s:'%s'", fullname,
5362 p.symbol->linkage_name ());
5363 break_command (&string[0], from_tty);
5364 print_symbol_info (FUNCTIONS_DOMAIN, p.symbol, p.block, NULL);
5365 }
5366 else
5367 {
5368 string = string_printf ("'%s'",
5369 p.msymbol.minsym->linkage_name ());
5370
5371 break_command (&string[0], from_tty);
5372 gdb_printf ("<function, no debug info> %s;\n",
5373 p.msymbol.minsym->print_name ());
5374 }
5375 }
5376}
5377\f
5378
5379/* Evaluate if SYMNAME matches LOOKUP_NAME. */
5380
5381static int
5382compare_symbol_name (const char *symbol_name, language symbol_language,
5383 const lookup_name_info &lookup_name,
5384 completion_match_result &match_res)
5385{
5386 const language_defn *lang = language_def (symbol_language);
5387
5388 symbol_name_matcher_ftype *name_match
5389 = lang->get_symbol_name_matcher (lookup_name);
5390
5391 return name_match (symbol_name, lookup_name, &match_res);
5392}
5393
5394/* See symtab.h. */
5395
5396bool
5397completion_list_add_name (completion_tracker &tracker,
5398 language symbol_language,
5399 const char *symname,
5400 const lookup_name_info &lookup_name,
5401 const char *text, const char *word)
5402{
5403 completion_match_result &match_res
5404 = tracker.reset_completion_match_result ();
5405
5406 /* Clip symbols that cannot match. */
5407 if (!compare_symbol_name (symname, symbol_language, lookup_name, match_res))
5408 return false;
5409
5410 /* Refresh SYMNAME from the match string. It's potentially
5411 different depending on language. (E.g., on Ada, the match may be
5412 the encoded symbol name wrapped in "<>"). */
5413 symname = match_res.match.match ();
5414 gdb_assert (symname != NULL);
5415
5416 /* We have a match for a completion, so add SYMNAME to the current list
5417 of matches. Note that the name is moved to freshly malloc'd space. */
5418
5419 {
5420 gdb::unique_xmalloc_ptr<char> completion
5421 = make_completion_match_str (symname, text, word);
5422
5423 /* Here we pass the match-for-lcd object to add_completion. Some
5424 languages match the user text against substrings of symbol
5425 names in some cases. E.g., in C++, "b push_ba" completes to
5426 "std::vector::push_back", "std::string::push_back", etc., and
5427 in this case we want the completion lowest common denominator
5428 to be "push_back" instead of "std::". */
5429 tracker.add_completion (std::move (completion),
5430 &match_res.match_for_lcd, text, word);
5431 }
5432
5433 return true;
5434}
5435
5436/* completion_list_add_name wrapper for struct symbol. */
5437
5438static void
5439completion_list_add_symbol (completion_tracker &tracker,
5440 symbol *sym,
5441 const lookup_name_info &lookup_name,
5442 const char *text, const char *word)
5443{
5444 if (!completion_list_add_name (tracker, sym->language (),
5445 sym->natural_name (),
5446 lookup_name, text, word))
5447 return;
5448
5449 /* C++ function symbols include the parameters within both the msymbol
5450 name and the symbol name. The problem is that the msymbol name will
5451 describe the parameters in the most basic way, with typedefs stripped
5452 out, while the symbol name will represent the types as they appear in
5453 the program. This means we will see duplicate entries in the
5454 completion tracker. The following converts the symbol name back to
5455 the msymbol name and removes the msymbol name from the completion
5456 tracker. */
5457 if (sym->language () == language_cplus
5458 && sym->domain () == VAR_DOMAIN
5459 && sym->aclass () == LOC_BLOCK)
5460 {
5461 /* The call to canonicalize returns the empty string if the input
5462 string is already in canonical form, thanks to this we don't
5463 remove the symbol we just added above. */
5464 gdb::unique_xmalloc_ptr<char> str
5465 = cp_canonicalize_string_no_typedefs (sym->natural_name ());
5466 if (str != nullptr)
5467 tracker.remove_completion (str.get ());
5468 }
5469}
5470
5471/* completion_list_add_name wrapper for struct minimal_symbol. */
5472
5473static void
5474completion_list_add_msymbol (completion_tracker &tracker,
5475 minimal_symbol *sym,
5476 const lookup_name_info &lookup_name,
5477 const char *text, const char *word)
5478{
5479 completion_list_add_name (tracker, sym->language (),
5480 sym->natural_name (),
5481 lookup_name, text, word);
5482}
5483
5484
5485/* ObjC: In case we are completing on a selector, look as the msymbol
5486 again and feed all the selectors into the mill. */
5487
5488static void
5489completion_list_objc_symbol (completion_tracker &tracker,
5490 struct minimal_symbol *msymbol,
5491 const lookup_name_info &lookup_name,
5492 const char *text, const char *word)
5493{
5494 static char *tmp = NULL;
5495 static unsigned int tmplen = 0;
5496
5497 const char *method, *category, *selector;
5498 char *tmp2 = NULL;
5499
5500 method = msymbol->natural_name ();
5501
5502 /* Is it a method? */
5503 if ((method[0] != '-') && (method[0] != '+'))
5504 return;
5505
5506 if (text[0] == '[')
5507 /* Complete on shortened method method. */
5508 completion_list_add_name (tracker, language_objc,
5509 method + 1,
5510 lookup_name,
5511 text, word);
5512
5513 while ((strlen (method) + 1) >= tmplen)
5514 {
5515 if (tmplen == 0)
5516 tmplen = 1024;
5517 else
5518 tmplen *= 2;
5519 tmp = (char *) xrealloc (tmp, tmplen);
5520 }
5521 selector = strchr (method, ' ');
5522 if (selector != NULL)
5523 selector++;
5524
5525 category = strchr (method, '(');
5526
5527 if ((category != NULL) && (selector != NULL))
5528 {
5529 memcpy (tmp, method, (category - method));
5530 tmp[category - method] = ' ';
5531 memcpy (tmp + (category - method) + 1, selector, strlen (selector) + 1);
5532 completion_list_add_name (tracker, language_objc, tmp,
5533 lookup_name, text, word);
5534 if (text[0] == '[')
5535 completion_list_add_name (tracker, language_objc, tmp + 1,
5536 lookup_name, text, word);
5537 }
5538
5539 if (selector != NULL)
5540 {
5541 /* Complete on selector only. */
5542 strcpy (tmp, selector);
5543 tmp2 = strchr (tmp, ']');
5544 if (tmp2 != NULL)
5545 *tmp2 = '\0';
5546
5547 completion_list_add_name (tracker, language_objc, tmp,
5548 lookup_name, text, word);
5549 }
5550}
5551
5552/* Break the non-quoted text based on the characters which are in
5553 symbols. FIXME: This should probably be language-specific. */
5554
5555static const char *
5556language_search_unquoted_string (const char *text, const char *p)
5557{
5558 for (; p > text; --p)
5559 {
5560 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
5561 continue;
5562 else
5563 {
5564 if ((current_language->la_language == language_objc))
5565 {
5566 if (p[-1] == ':') /* Might be part of a method name. */
5567 continue;
5568 else if (p[-1] == '[' && (p[-2] == '-' || p[-2] == '+'))
5569 p -= 2; /* Beginning of a method name. */
5570 else if (p[-1] == ' ' || p[-1] == '(' || p[-1] == ')')
5571 { /* Might be part of a method name. */
5572 const char *t = p;
5573
5574 /* Seeing a ' ' or a '(' is not conclusive evidence
5575 that we are in the middle of a method name. However,
5576 finding "-[" or "+[" should be pretty un-ambiguous.
5577 Unfortunately we have to find it now to decide. */
5578
5579 while (t > text)
5580 if (isalnum (t[-1]) || t[-1] == '_' ||
5581 t[-1] == ' ' || t[-1] == ':' ||
5582 t[-1] == '(' || t[-1] == ')')
5583 --t;
5584 else
5585 break;
5586
5587 if (t[-1] == '[' && (t[-2] == '-' || t[-2] == '+'))
5588 p = t - 2; /* Method name detected. */
5589 /* Else we leave with p unchanged. */
5590 }
5591 }
5592 break;
5593 }
5594 }
5595 return p;
5596}
5597
5598static void
5599completion_list_add_fields (completion_tracker &tracker,
5600 struct symbol *sym,
5601 const lookup_name_info &lookup_name,
5602 const char *text, const char *word)
5603{
5604 if (sym->aclass () == LOC_TYPEDEF)
5605 {
5606 struct type *t = sym->type ();
5607 enum type_code c = t->code ();
5608 int j;
5609
5610 if (c == TYPE_CODE_UNION || c == TYPE_CODE_STRUCT)
5611 for (j = TYPE_N_BASECLASSES (t); j < t->num_fields (); j++)
5612 if (t->field (j).name ())
5613 completion_list_add_name (tracker, sym->language (),
5614 t->field (j).name (),
5615 lookup_name, text, word);
5616 }
5617}
5618
5619/* See symtab.h. */
5620
5621bool
5622symbol_is_function_or_method (symbol *sym)
5623{
5624 switch (sym->type ()->code ())
5625 {
5626 case TYPE_CODE_FUNC:
5627 case TYPE_CODE_METHOD:
5628 return true;
5629 default:
5630 return false;
5631 }
5632}
5633
5634/* See symtab.h. */
5635
5636bool
5637symbol_is_function_or_method (minimal_symbol *msymbol)
5638{
5639 switch (msymbol->type ())
5640 {
5641 case mst_text:
5642 case mst_text_gnu_ifunc:
5643 case mst_solib_trampoline:
5644 case mst_file_text:
5645 return true;
5646 default:
5647 return false;
5648 }
5649}
5650
5651/* See symtab.h. */
5652
5653bound_minimal_symbol
5654find_gnu_ifunc (const symbol *sym)
5655{
5656 if (sym->aclass () != LOC_BLOCK)
5657 return {};
5658
5659 lookup_name_info lookup_name (sym->search_name (),
5660 symbol_name_match_type::SEARCH_NAME);
5661 struct objfile *objfile = sym->objfile ();
5662
5663 CORE_ADDR address = sym->value_block ()->entry_pc ();
5664 minimal_symbol *ifunc = NULL;
5665
5666 iterate_over_minimal_symbols (objfile, lookup_name,
5667 [&] (minimal_symbol *minsym)
5668 {
5669 if (minsym->type () == mst_text_gnu_ifunc
5670 || minsym->type () == mst_data_gnu_ifunc)
5671 {
5672 CORE_ADDR msym_addr = minsym->value_address (objfile);
5673 if (minsym->type () == mst_data_gnu_ifunc)
5674 {
5675 struct gdbarch *gdbarch = objfile->arch ();
5676 msym_addr = gdbarch_convert_from_func_ptr_addr
5677 (gdbarch, msym_addr, current_inferior ()->top_target ());
5678 }
5679 if (msym_addr == address)
5680 {
5681 ifunc = minsym;
5682 return true;
5683 }
5684 }
5685 return false;
5686 });
5687
5688 if (ifunc != NULL)
5689 return {ifunc, objfile};
5690 return {};
5691}
5692
5693/* Add matching symbols from SYMTAB to the current completion list. */
5694
5695static void
5696add_symtab_completions (struct compunit_symtab *cust,
5697 completion_tracker &tracker,
5698 complete_symbol_mode mode,
5699 const lookup_name_info &lookup_name,
5700 const char *text, const char *word,
5701 enum type_code code)
5702{
5703 int i;
5704
5705 if (cust == NULL)
5706 return;
5707
5708 for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
5709 {
5710 QUIT;
5711
5712 const struct block *b = cust->blockvector ()->block (i);
5713 for (struct symbol *sym : block_iterator_range (b))
5714 {
5715 if (completion_skip_symbol (mode, sym))
5716 continue;
5717
5718 if (code == TYPE_CODE_UNDEF
5719 || (sym->domain () == STRUCT_DOMAIN
5720 && sym->type ()->code () == code))
5721 completion_list_add_symbol (tracker, sym,
5722 lookup_name,
5723 text, word);
5724 }
5725 }
5726}
5727
5728void
5729default_collect_symbol_completion_matches_break_on
5730 (completion_tracker &tracker, complete_symbol_mode mode,
5731 symbol_name_match_type name_match_type,
5732 const char *text, const char *word,
5733 const char *break_on, enum type_code code)
5734{
5735 /* Problem: All of the symbols have to be copied because readline
5736 frees them. I'm not going to worry about this; hopefully there
5737 won't be that many. */
5738
5739 const struct block *b;
5740 const struct block *surrounding_static_block, *surrounding_global_block;
5741 /* The symbol we are completing on. Points in same buffer as text. */
5742 const char *sym_text;
5743
5744 /* Now look for the symbol we are supposed to complete on. */
5745 if (mode == complete_symbol_mode::LINESPEC)
5746 sym_text = text;
5747 else
5748 {
5749 const char *p;
5750 char quote_found;
5751 const char *quote_pos = NULL;
5752
5753 /* First see if this is a quoted string. */
5754 quote_found = '\0';
5755 for (p = text; *p != '\0'; ++p)
5756 {
5757 if (quote_found != '\0')
5758 {
5759 if (*p == quote_found)
5760 /* Found close quote. */
5761 quote_found = '\0';
5762 else if (*p == '\\' && p[1] == quote_found)
5763 /* A backslash followed by the quote character
5764 doesn't end the string. */
5765 ++p;
5766 }
5767 else if (*p == '\'' || *p == '"')
5768 {
5769 quote_found = *p;
5770 quote_pos = p;
5771 }
5772 }
5773 if (quote_found == '\'')
5774 /* A string within single quotes can be a symbol, so complete on it. */
5775 sym_text = quote_pos + 1;
5776 else if (quote_found == '"')
5777 /* A double-quoted string is never a symbol, nor does it make sense
5778 to complete it any other way. */
5779 {
5780 return;
5781 }
5782 else
5783 {
5784 /* It is not a quoted string. Break it based on the characters
5785 which are in symbols. */
5786 while (p > text)
5787 {
5788 if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0'
5789 || p[-1] == ':' || strchr (break_on, p[-1]) != NULL)
5790 --p;
5791 else
5792 break;
5793 }
5794 sym_text = p;
5795 }
5796 }
5797
5798 lookup_name_info lookup_name (sym_text, name_match_type, true);
5799
5800 /* At this point scan through the misc symbol vectors and add each
5801 symbol you find to the list. Eventually we want to ignore
5802 anything that isn't a text symbol (everything else will be
5803 handled by the psymtab code below). */
5804
5805 if (code == TYPE_CODE_UNDEF)
5806 {
5807 for (objfile *objfile : current_program_space->objfiles ())
5808 {
5809 for (minimal_symbol *msymbol : objfile->msymbols ())
5810 {
5811 QUIT;
5812
5813 if (completion_skip_symbol (mode, msymbol))
5814 continue;
5815
5816 completion_list_add_msymbol (tracker, msymbol, lookup_name,
5817 sym_text, word);
5818
5819 completion_list_objc_symbol (tracker, msymbol, lookup_name,
5820 sym_text, word);
5821 }
5822 }
5823 }
5824
5825 /* Add completions for all currently loaded symbol tables. */
5826 for (objfile *objfile : current_program_space->objfiles ())
5827 {
5828 for (compunit_symtab *cust : objfile->compunits ())
5829 add_symtab_completions (cust, tracker, mode, lookup_name,
5830 sym_text, word, code);
5831 }
5832
5833 /* Look through the partial symtabs for all symbols which begin by
5834 matching SYM_TEXT. Expand all CUs that you find to the list. */
5835 expand_symtabs_matching (NULL,
5836 lookup_name,
5837 NULL,
5838 [&] (compunit_symtab *symtab) /* expansion notify */
5839 {
5840 add_symtab_completions (symtab,
5841 tracker, mode, lookup_name,
5842 sym_text, word, code);
5843 return true;
5844 },
5845 SEARCH_GLOBAL_BLOCK | SEARCH_STATIC_BLOCK,
5846 ALL_DOMAIN);
5847
5848 /* Search upwards from currently selected frame (so that we can
5849 complete on local vars). Also catch fields of types defined in
5850 this places which match our text string. Only complete on types
5851 visible from current context. */
5852
5853 b = get_selected_block (0);
5854 surrounding_static_block = b == nullptr ? nullptr : b->static_block ();
5855 surrounding_global_block = b == nullptr ? nullptr : b->global_block ();
5856 if (surrounding_static_block != NULL)
5857 while (b != surrounding_static_block)
5858 {
5859 QUIT;
5860
5861 for (struct symbol *sym : block_iterator_range (b))
5862 {
5863 if (code == TYPE_CODE_UNDEF)
5864 {
5865 completion_list_add_symbol (tracker, sym, lookup_name,
5866 sym_text, word);
5867 completion_list_add_fields (tracker, sym, lookup_name,
5868 sym_text, word);
5869 }
5870 else if (sym->domain () == STRUCT_DOMAIN
5871 && sym->type ()->code () == code)
5872 completion_list_add_symbol (tracker, sym, lookup_name,
5873 sym_text, word);
5874 }
5875
5876 /* Stop when we encounter an enclosing function. Do not stop for
5877 non-inlined functions - the locals of the enclosing function
5878 are in scope for a nested function. */
5879 if (b->function () != NULL && b->inlined_p ())
5880 break;
5881 b = b->superblock ();
5882 }
5883
5884 /* Add fields from the file's types; symbols will be added below. */
5885
5886 if (code == TYPE_CODE_UNDEF)
5887 {
5888 if (surrounding_static_block != NULL)
5889 for (struct symbol *sym : block_iterator_range (surrounding_static_block))
5890 completion_list_add_fields (tracker, sym, lookup_name,
5891 sym_text, word);
5892
5893 if (surrounding_global_block != NULL)
5894 for (struct symbol *sym : block_iterator_range (surrounding_global_block))
5895 completion_list_add_fields (tracker, sym, lookup_name,
5896 sym_text, word);
5897 }
5898
5899 /* Skip macros if we are completing a struct tag -- arguable but
5900 usually what is expected. */
5901 if (current_language->macro_expansion () == macro_expansion_c
5902 && code == TYPE_CODE_UNDEF)
5903 {
5904 gdb::unique_xmalloc_ptr<struct macro_scope> scope;
5905
5906 /* This adds a macro's name to the current completion list. */
5907 auto add_macro_name = [&] (const char *macro_name,
5908 const macro_definition *,
5909 macro_source_file *,
5910 int)
5911 {
5912 completion_list_add_name (tracker, language_c, macro_name,
5913 lookup_name, sym_text, word);
5914 };
5915
5916 /* Add any macros visible in the default scope. Note that this
5917 may yield the occasional wrong result, because an expression
5918 might be evaluated in a scope other than the default. For
5919 example, if the user types "break file:line if <TAB>", the
5920 resulting expression will be evaluated at "file:line" -- but
5921 at there does not seem to be a way to detect this at
5922 completion time. */
5923 scope = default_macro_scope ();
5924 if (scope)
5925 macro_for_each_in_scope (scope->file, scope->line,
5926 add_macro_name);
5927
5928 /* User-defined macros are always visible. */
5929 macro_for_each (macro_user_macros, add_macro_name);
5930 }
5931}
5932
5933/* Collect all symbols (regardless of class) which begin by matching
5934 TEXT. */
5935
5936void
5937collect_symbol_completion_matches (completion_tracker &tracker,
5938 complete_symbol_mode mode,
5939 symbol_name_match_type name_match_type,
5940 const char *text, const char *word)
5941{
5942 current_language->collect_symbol_completion_matches (tracker, mode,
5943 name_match_type,
5944 text, word,
5945 TYPE_CODE_UNDEF);
5946}
5947
5948/* Like collect_symbol_completion_matches, but only collect
5949 STRUCT_DOMAIN symbols whose type code is CODE. */
5950
5951void
5952collect_symbol_completion_matches_type (completion_tracker &tracker,
5953 const char *text, const char *word,
5954 enum type_code code)
5955{
5956 complete_symbol_mode mode = complete_symbol_mode::EXPRESSION;
5957 symbol_name_match_type name_match_type = symbol_name_match_type::EXPRESSION;
5958
5959 gdb_assert (code == TYPE_CODE_UNION
5960 || code == TYPE_CODE_STRUCT
5961 || code == TYPE_CODE_ENUM);
5962 current_language->collect_symbol_completion_matches (tracker, mode,
5963 name_match_type,
5964 text, word, code);
5965}
5966
5967/* Like collect_symbol_completion_matches, but collects a list of
5968 symbols defined in all source files named SRCFILE. */
5969
5970void
5971collect_file_symbol_completion_matches (completion_tracker &tracker,
5972 complete_symbol_mode mode,
5973 symbol_name_match_type name_match_type,
5974 const char *text, const char *word,
5975 const char *srcfile)
5976{
5977 /* The symbol we are completing on. Points in same buffer as text. */
5978 const char *sym_text;
5979
5980 /* Now look for the symbol we are supposed to complete on.
5981 FIXME: This should be language-specific. */
5982 if (mode == complete_symbol_mode::LINESPEC)
5983 sym_text = text;
5984 else
5985 {
5986 const char *p;
5987 char quote_found;
5988 const char *quote_pos = NULL;
5989
5990 /* First see if this is a quoted string. */
5991 quote_found = '\0';
5992 for (p = text; *p != '\0'; ++p)
5993 {
5994 if (quote_found != '\0')
5995 {
5996 if (*p == quote_found)
5997 /* Found close quote. */
5998 quote_found = '\0';
5999 else if (*p == '\\' && p[1] == quote_found)
6000 /* A backslash followed by the quote character
6001 doesn't end the string. */
6002 ++p;
6003 }
6004 else if (*p == '\'' || *p == '"')
6005 {
6006 quote_found = *p;
6007 quote_pos = p;
6008 }
6009 }
6010 if (quote_found == '\'')
6011 /* A string within single quotes can be a symbol, so complete on it. */
6012 sym_text = quote_pos + 1;
6013 else if (quote_found == '"')
6014 /* A double-quoted string is never a symbol, nor does it make sense
6015 to complete it any other way. */
6016 {
6017 return;
6018 }
6019 else
6020 {
6021 /* Not a quoted string. */
6022 sym_text = language_search_unquoted_string (text, p);
6023 }
6024 }
6025
6026 lookup_name_info lookup_name (sym_text, name_match_type, true);
6027
6028 /* Go through symtabs for SRCFILE and check the externs and statics
6029 for symbols which match. */
6030 iterate_over_symtabs (srcfile, [&] (symtab *s)
6031 {
6032 add_symtab_completions (s->compunit (),
6033 tracker, mode, lookup_name,
6034 sym_text, word, TYPE_CODE_UNDEF);
6035 return false;
6036 });
6037}
6038
6039/* A helper function for make_source_files_completion_list. It adds
6040 another file name to a list of possible completions, growing the
6041 list as necessary. */
6042
6043static void
6044add_filename_to_list (const char *fname, const char *text, const char *word,
6045 completion_list *list)
6046{
6047 list->emplace_back (make_completion_match_str (fname, text, word));
6048}
6049
6050static int
6051not_interesting_fname (const char *fname)
6052{
6053 static const char *illegal_aliens[] = {
6054 "_globals_", /* inserted by coff_symtab_read */
6055 NULL
6056 };
6057 int i;
6058
6059 for (i = 0; illegal_aliens[i]; i++)
6060 {
6061 if (filename_cmp (fname, illegal_aliens[i]) == 0)
6062 return 1;
6063 }
6064 return 0;
6065}
6066
6067/* An object of this type is passed as the callback argument to
6068 map_partial_symbol_filenames. */
6069struct add_partial_filename_data
6070{
6071 struct filename_seen_cache *filename_seen_cache;
6072 const char *text;
6073 const char *word;
6074 int text_len;
6075 completion_list *list;
6076
6077 void operator() (const char *filename, const char *fullname);
6078};
6079
6080/* A callback for map_partial_symbol_filenames. */
6081
6082void
6083add_partial_filename_data::operator() (const char *filename,
6084 const char *fullname)
6085{
6086 if (not_interesting_fname (filename))
6087 return;
6088 if (!filename_seen_cache->seen (filename)
6089 && filename_ncmp (filename, text, text_len) == 0)
6090 {
6091 /* This file matches for a completion; add it to the
6092 current list of matches. */
6093 add_filename_to_list (filename, text, word, list);
6094 }
6095 else
6096 {
6097 const char *base_name = lbasename (filename);
6098
6099 if (base_name != filename
6100 && !filename_seen_cache->seen (base_name)
6101 && filename_ncmp (base_name, text, text_len) == 0)
6102 add_filename_to_list (base_name, text, word, list);
6103 }
6104}
6105
6106/* Return a list of all source files whose names begin with matching
6107 TEXT. The file names are looked up in the symbol tables of this
6108 program. */
6109
6110completion_list
6111make_source_files_completion_list (const char *text, const char *word)
6112{
6113 size_t text_len = strlen (text);
6114 completion_list list;
6115 const char *base_name;
6116 struct add_partial_filename_data datum;
6117
6118 if (!have_full_symbols () && !have_partial_symbols ())
6119 return list;
6120
6121 filename_seen_cache filenames_seen;
6122
6123 for (objfile *objfile : current_program_space->objfiles ())
6124 {
6125 for (compunit_symtab *cu : objfile->compunits ())
6126 {
6127 for (symtab *s : cu->filetabs ())
6128 {
6129 if (not_interesting_fname (s->filename))
6130 continue;
6131 if (!filenames_seen.seen (s->filename)
6132 && filename_ncmp (s->filename, text, text_len) == 0)
6133 {
6134 /* This file matches for a completion; add it to the current
6135 list of matches. */
6136 add_filename_to_list (s->filename, text, word, &list);
6137 }
6138 else
6139 {
6140 /* NOTE: We allow the user to type a base name when the
6141 debug info records leading directories, but not the other
6142 way around. This is what subroutines of breakpoint
6143 command do when they parse file names. */
6144 base_name = lbasename (s->filename);
6145 if (base_name != s->filename
6146 && !filenames_seen.seen (base_name)
6147 && filename_ncmp (base_name, text, text_len) == 0)
6148 add_filename_to_list (base_name, text, word, &list);
6149 }
6150 }
6151 }
6152 }
6153
6154 datum.filename_seen_cache = &filenames_seen;
6155 datum.text = text;
6156 datum.word = word;
6157 datum.text_len = text_len;
6158 datum.list = &list;
6159 map_symbol_filenames (datum, false /*need_fullname*/);
6160
6161 return list;
6162}
6163\f
6164/* Track MAIN */
6165
6166/* Return the "main_info" object for the current program space. If
6167 the object has not yet been created, create it and fill in some
6168 default values. */
6169
6170static struct main_info *
6171get_main_info (void)
6172{
6173 struct main_info *info = main_progspace_key.get (current_program_space);
6174
6175 if (info == NULL)
6176 {
6177 /* It may seem strange to store the main name in the progspace
6178 and also in whatever objfile happens to see a main name in
6179 its debug info. The reason for this is mainly historical:
6180 gdb returned "main" as the name even if no function named
6181 "main" was defined the program; and this approach lets us
6182 keep compatibility. */
6183 info = main_progspace_key.emplace (current_program_space);
6184 }
6185
6186 return info;
6187}
6188
6189static void
6190set_main_name (const char *name, enum language lang)
6191{
6192 struct main_info *info = get_main_info ();
6193
6194 if (!info->name_of_main.empty ())
6195 {
6196 info->name_of_main.clear ();
6197 info->language_of_main = language_unknown;
6198 }
6199 if (name != NULL)
6200 {
6201 info->name_of_main = name;
6202 info->language_of_main = lang;
6203 }
6204}
6205
6206/* Deduce the name of the main procedure, and set NAME_OF_MAIN
6207 accordingly. */
6208
6209static void
6210find_main_name (void)
6211{
6212 const char *new_main_name;
6213
6214 /* First check the objfiles to see whether a debuginfo reader has
6215 picked up the appropriate main name. Historically the main name
6216 was found in a more or less random way; this approach instead
6217 relies on the order of objfile creation -- which still isn't
6218 guaranteed to get the correct answer, but is just probably more
6219 accurate. */
6220 for (objfile *objfile : current_program_space->objfiles ())
6221 {
6222 if (objfile->per_bfd->name_of_main != NULL)
6223 {
6224 set_main_name (objfile->per_bfd->name_of_main,
6225 objfile->per_bfd->language_of_main);
6226 return;
6227 }
6228 }
6229
6230 /* Try to see if the main procedure is in Ada. */
6231 /* FIXME: brobecker/2005-03-07: Another way of doing this would
6232 be to add a new method in the language vector, and call this
6233 method for each language until one of them returns a non-empty
6234 name. This would allow us to remove this hard-coded call to
6235 an Ada function. It is not clear that this is a better approach
6236 at this point, because all methods need to be written in a way
6237 such that false positives never be returned. For instance, it is
6238 important that a method does not return a wrong name for the main
6239 procedure if the main procedure is actually written in a different
6240 language. It is easy to guaranty this with Ada, since we use a
6241 special symbol generated only when the main in Ada to find the name
6242 of the main procedure. It is difficult however to see how this can
6243 be guarantied for languages such as C, for instance. This suggests
6244 that order of call for these methods becomes important, which means
6245 a more complicated approach. */
6246 new_main_name = ada_main_name ();
6247 if (new_main_name != NULL)
6248 {
6249 set_main_name (new_main_name, language_ada);
6250 return;
6251 }
6252
6253 new_main_name = d_main_name ();
6254 if (new_main_name != NULL)
6255 {
6256 set_main_name (new_main_name, language_d);
6257 return;
6258 }
6259
6260 new_main_name = go_main_name ();
6261 if (new_main_name != NULL)
6262 {
6263 set_main_name (new_main_name, language_go);
6264 return;
6265 }
6266
6267 new_main_name = pascal_main_name ();
6268 if (new_main_name != NULL)
6269 {
6270 set_main_name (new_main_name, language_pascal);
6271 return;
6272 }
6273
6274 /* The languages above didn't identify the name of the main procedure.
6275 Fallback to "main". */
6276
6277 /* Try to find language for main in psymtabs. */
6278 bool symbol_found_p = false;
6279 gdbarch_iterate_over_objfiles_in_search_order
6280 (target_gdbarch (),
6281 [&symbol_found_p] (objfile *obj)
6282 {
6283 language lang
6284 = obj->lookup_global_symbol_language ("main", VAR_DOMAIN,
6285 &symbol_found_p);
6286 if (symbol_found_p)
6287 {
6288 set_main_name ("main", lang);
6289 return 1;
6290 }
6291
6292 return 0;
6293 }, nullptr);
6294
6295 if (symbol_found_p)
6296 return;
6297
6298 set_main_name ("main", language_unknown);
6299}
6300
6301/* See symtab.h. */
6302
6303const char *
6304main_name ()
6305{
6306 struct main_info *info = get_main_info ();
6307
6308 if (info->name_of_main.empty ())
6309 find_main_name ();
6310
6311 return info->name_of_main.c_str ();
6312}
6313
6314/* Return the language of the main function. If it is not known,
6315 return language_unknown. */
6316
6317enum language
6318main_language (void)
6319{
6320 struct main_info *info = get_main_info ();
6321
6322 if (info->name_of_main.empty ())
6323 find_main_name ();
6324
6325 return info->language_of_main;
6326}
6327
6328/* Handle ``executable_changed'' events for the symtab module. */
6329
6330static void
6331symtab_observer_executable_changed (void)
6332{
6333 /* NAME_OF_MAIN may no longer be the same, so reset it for now. */
6334 set_main_name (NULL, language_unknown);
6335}
6336
6337/* Return 1 if the supplied producer string matches the ARM RealView
6338 compiler (armcc). */
6339
6340bool
6341producer_is_realview (const char *producer)
6342{
6343 static const char *const arm_idents[] = {
6344 "ARM C Compiler, ADS",
6345 "Thumb C Compiler, ADS",
6346 "ARM C++ Compiler, ADS",
6347 "Thumb C++ Compiler, ADS",
6348 "ARM/Thumb C/C++ Compiler, RVCT",
6349 "ARM C/C++ Compiler, RVCT"
6350 };
6351
6352 if (producer == NULL)
6353 return false;
6354
6355 for (const char *ident : arm_idents)
6356 if (startswith (producer, ident))
6357 return true;
6358
6359 return false;
6360}
6361
6362\f
6363
6364/* The next index to hand out in response to a registration request. */
6365
6366static int next_aclass_value = LOC_FINAL_VALUE;
6367
6368/* The maximum number of "aclass" registrations we support. This is
6369 constant for convenience. */
6370#define MAX_SYMBOL_IMPLS (LOC_FINAL_VALUE + 11)
6371
6372/* The objects representing the various "aclass" values. The elements
6373 from 0 up to LOC_FINAL_VALUE-1 represent themselves, and subsequent
6374 elements are those registered at gdb initialization time. */
6375
6376static struct symbol_impl symbol_impl[MAX_SYMBOL_IMPLS];
6377
6378/* The globally visible pointer. This is separate from 'symbol_impl'
6379 so that it can be const. */
6380
6381gdb::array_view<const struct symbol_impl> symbol_impls (symbol_impl);
6382
6383/* Make sure we saved enough room in struct symbol. */
6384
6385gdb_static_assert (MAX_SYMBOL_IMPLS <= (1 << SYMBOL_ACLASS_BITS));
6386
6387/* Register a computed symbol type. ACLASS must be LOC_COMPUTED. OPS
6388 is the ops vector associated with this index. This returns the new
6389 index, which should be used as the aclass_index field for symbols
6390 of this type. */
6391
6392int
6393register_symbol_computed_impl (enum address_class aclass,
6394 const struct symbol_computed_ops *ops)
6395{
6396 int result = next_aclass_value++;
6397
6398 gdb_assert (aclass == LOC_COMPUTED);
6399 gdb_assert (result < MAX_SYMBOL_IMPLS);
6400 symbol_impl[result].aclass = aclass;
6401 symbol_impl[result].ops_computed = ops;
6402
6403 /* Sanity check OPS. */
6404 gdb_assert (ops != NULL);
6405 gdb_assert (ops->tracepoint_var_ref != NULL);
6406 gdb_assert (ops->describe_location != NULL);
6407 gdb_assert (ops->get_symbol_read_needs != NULL);
6408 gdb_assert (ops->read_variable != NULL);
6409
6410 return result;
6411}
6412
6413/* Register a function with frame base type. ACLASS must be LOC_BLOCK.
6414 OPS is the ops vector associated with this index. This returns the
6415 new index, which should be used as the aclass_index field for symbols
6416 of this type. */
6417
6418int
6419register_symbol_block_impl (enum address_class aclass,
6420 const struct symbol_block_ops *ops)
6421{
6422 int result = next_aclass_value++;
6423
6424 gdb_assert (aclass == LOC_BLOCK);
6425 gdb_assert (result < MAX_SYMBOL_IMPLS);
6426 symbol_impl[result].aclass = aclass;
6427 symbol_impl[result].ops_block = ops;
6428
6429 /* Sanity check OPS. */
6430 gdb_assert (ops != NULL);
6431 gdb_assert (ops->find_frame_base_location != nullptr
6432 || ops->get_block_value != nullptr);
6433
6434 return result;
6435}
6436
6437/* Register a register symbol type. ACLASS must be LOC_REGISTER or
6438 LOC_REGPARM_ADDR. OPS is the register ops vector associated with
6439 this index. This returns the new index, which should be used as
6440 the aclass_index field for symbols of this type. */
6441
6442int
6443register_symbol_register_impl (enum address_class aclass,
6444 const struct symbol_register_ops *ops)
6445{
6446 int result = next_aclass_value++;
6447
6448 gdb_assert (aclass == LOC_REGISTER || aclass == LOC_REGPARM_ADDR);
6449 gdb_assert (result < MAX_SYMBOL_IMPLS);
6450 symbol_impl[result].aclass = aclass;
6451 symbol_impl[result].ops_register = ops;
6452
6453 return result;
6454}
6455
6456/* Initialize elements of 'symbol_impl' for the constants in enum
6457 address_class. */
6458
6459static void
6460initialize_ordinary_address_classes (void)
6461{
6462 int i;
6463
6464 for (i = 0; i < LOC_FINAL_VALUE; ++i)
6465 symbol_impl[i].aclass = (enum address_class) i;
6466}
6467
6468\f
6469
6470/* See symtab.h. */
6471
6472struct objfile *
6473symbol::objfile () const
6474{
6475 gdb_assert (is_objfile_owned ());
6476 return owner.symtab->compunit ()->objfile ();
6477}
6478
6479/* See symtab.h. */
6480
6481struct gdbarch *
6482symbol::arch () const
6483{
6484 if (!is_objfile_owned ())
6485 return owner.arch;
6486 return owner.symtab->compunit ()->objfile ()->arch ();
6487}
6488
6489/* See symtab.h. */
6490
6491struct symtab *
6492symbol::symtab () const
6493{
6494 gdb_assert (is_objfile_owned ());
6495 return owner.symtab;
6496}
6497
6498/* See symtab.h. */
6499
6500void
6501symbol::set_symtab (struct symtab *symtab)
6502{
6503 gdb_assert (is_objfile_owned ());
6504 owner.symtab = symtab;
6505}
6506
6507/* See symtab.h. */
6508
6509CORE_ADDR
6510get_symbol_address (const struct symbol *sym)
6511{
6512 gdb_assert (sym->maybe_copied);
6513 gdb_assert (sym->aclass () == LOC_STATIC);
6514
6515 const char *linkage_name = sym->linkage_name ();
6516 bound_minimal_symbol minsym = lookup_minimal_symbol_linkage (linkage_name,
6517 false);
6518 if (minsym.minsym != nullptr)
6519 return minsym.value_address ();
6520 return sym->m_value.address;
6521}
6522
6523/* See symtab.h. */
6524
6525CORE_ADDR
6526get_msymbol_address (struct objfile *objf, const struct minimal_symbol *minsym)
6527{
6528 gdb_assert (minsym->maybe_copied (objf));
6529 gdb_assert ((objf->flags & OBJF_MAINLINE) == 0);
6530
6531 const char *linkage_name = minsym->linkage_name ();
6532 bound_minimal_symbol found = lookup_minimal_symbol_linkage (linkage_name,
6533 true);
6534 if (found.minsym != nullptr)
6535 return found.value_address ();
6536 return (minsym->m_value.address
6537 + objf->section_offsets[minsym->section_index ()]);
6538}
6539
6540\f
6541
6542/* Hold the sub-commands of 'info module'. */
6543
6544static struct cmd_list_element *info_module_cmdlist = NULL;
6545
6546/* See symtab.h. */
6547
6548std::vector<module_symbol_search>
6549search_module_symbols (const char *module_regexp, const char *regexp,
6550 const char *type_regexp, search_domain kind)
6551{
6552 std::vector<module_symbol_search> results;
6553
6554 /* Search for all modules matching MODULE_REGEXP. */
6555 global_symbol_searcher spec1 (MODULES_DOMAIN, module_regexp);
6556 spec1.set_exclude_minsyms (true);
6557 std::vector<symbol_search> modules = spec1.search ();
6558
6559 /* Now search for all symbols of the required KIND matching the required
6560 regular expressions. We figure out which ones are in which modules
6561 below. */
6562 global_symbol_searcher spec2 (kind, regexp);
6563 spec2.set_symbol_type_regexp (type_regexp);
6564 spec2.set_exclude_minsyms (true);
6565 std::vector<symbol_search> symbols = spec2.search ();
6566
6567 /* Now iterate over all MODULES, checking to see which items from
6568 SYMBOLS are in each module. */
6569 for (const symbol_search &p : modules)
6570 {
6571 QUIT;
6572
6573 /* This is a module. */
6574 gdb_assert (p.symbol != nullptr);
6575
6576 std::string prefix = p.symbol->print_name ();
6577 prefix += "::";
6578
6579 for (const symbol_search &q : symbols)
6580 {
6581 if (q.symbol == nullptr)
6582 continue;
6583
6584 if (strncmp (q.symbol->print_name (), prefix.c_str (),
6585 prefix.size ()) != 0)
6586 continue;
6587
6588 results.push_back ({p, q});
6589 }
6590 }
6591
6592 return results;
6593}
6594
6595/* Implement the core of both 'info module functions' and 'info module
6596 variables'. */
6597
6598static void
6599info_module_subcommand (bool quiet, const char *module_regexp,
6600 const char *regexp, const char *type_regexp,
6601 search_domain kind)
6602{
6603 /* Print a header line. Don't build the header line bit by bit as this
6604 prevents internationalisation. */
6605 if (!quiet)
6606 {
6607 if (module_regexp == nullptr)
6608 {
6609 if (type_regexp == nullptr)
6610 {
6611 if (regexp == nullptr)
6612 gdb_printf ((kind == VARIABLES_DOMAIN
6613 ? _("All variables in all modules:")
6614 : _("All functions in all modules:")));
6615 else
6616 gdb_printf
6617 ((kind == VARIABLES_DOMAIN
6618 ? _("All variables matching regular expression"
6619 " \"%s\" in all modules:")
6620 : _("All functions matching regular expression"
6621 " \"%s\" in all modules:")),
6622 regexp);
6623 }
6624 else
6625 {
6626 if (regexp == nullptr)
6627 gdb_printf
6628 ((kind == VARIABLES_DOMAIN
6629 ? _("All variables with type matching regular "
6630 "expression \"%s\" in all modules:")
6631 : _("All functions with type matching regular "
6632 "expression \"%s\" in all modules:")),
6633 type_regexp);
6634 else
6635 gdb_printf
6636 ((kind == VARIABLES_DOMAIN
6637 ? _("All variables matching regular expression "
6638 "\"%s\",\n\twith type matching regular "
6639 "expression \"%s\" in all modules:")
6640 : _("All functions matching regular expression "
6641 "\"%s\",\n\twith type matching regular "
6642 "expression \"%s\" in all modules:")),
6643 regexp, type_regexp);
6644 }
6645 }
6646 else
6647 {
6648 if (type_regexp == nullptr)
6649 {
6650 if (regexp == nullptr)
6651 gdb_printf
6652 ((kind == VARIABLES_DOMAIN
6653 ? _("All variables in all modules matching regular "
6654 "expression \"%s\":")
6655 : _("All functions in all modules matching regular "
6656 "expression \"%s\":")),
6657 module_regexp);
6658 else
6659 gdb_printf
6660 ((kind == VARIABLES_DOMAIN
6661 ? _("All variables matching regular expression "
6662 "\"%s\",\n\tin all modules matching regular "
6663 "expression \"%s\":")
6664 : _("All functions matching regular expression "
6665 "\"%s\",\n\tin all modules matching regular "
6666 "expression \"%s\":")),
6667 regexp, module_regexp);
6668 }
6669 else
6670 {
6671 if (regexp == nullptr)
6672 gdb_printf
6673 ((kind == VARIABLES_DOMAIN
6674 ? _("All variables with type matching regular "
6675 "expression \"%s\"\n\tin all modules matching "
6676 "regular expression \"%s\":")
6677 : _("All functions with type matching regular "
6678 "expression \"%s\"\n\tin all modules matching "
6679 "regular expression \"%s\":")),
6680 type_regexp, module_regexp);
6681 else
6682 gdb_printf
6683 ((kind == VARIABLES_DOMAIN
6684 ? _("All variables matching regular expression "
6685 "\"%s\",\n\twith type matching regular expression "
6686 "\"%s\",\n\tin all modules matching regular "
6687 "expression \"%s\":")
6688 : _("All functions matching regular expression "
6689 "\"%s\",\n\twith type matching regular expression "
6690 "\"%s\",\n\tin all modules matching regular "
6691 "expression \"%s\":")),
6692 regexp, type_regexp, module_regexp);
6693 }
6694 }
6695 gdb_printf ("\n");
6696 }
6697
6698 /* Find all symbols of type KIND matching the given regular expressions
6699 along with the symbols for the modules in which those symbols
6700 reside. */
6701 std::vector<module_symbol_search> module_symbols
6702 = search_module_symbols (module_regexp, regexp, type_regexp, kind);
6703
6704 std::sort (module_symbols.begin (), module_symbols.end (),
6705 [] (const module_symbol_search &a, const module_symbol_search &b)
6706 {
6707 if (a.first < b.first)
6708 return true;
6709 else if (a.first == b.first)
6710 return a.second < b.second;
6711 else
6712 return false;
6713 });
6714
6715 const char *last_filename = "";
6716 const symbol *last_module_symbol = nullptr;
6717 for (const module_symbol_search &ms : module_symbols)
6718 {
6719 const symbol_search &p = ms.first;
6720 const symbol_search &q = ms.second;
6721
6722 gdb_assert (q.symbol != nullptr);
6723
6724 if (last_module_symbol != p.symbol)
6725 {
6726 gdb_printf ("\n");
6727 gdb_printf (_("Module \"%s\":\n"), p.symbol->print_name ());
6728 last_module_symbol = p.symbol;
6729 last_filename = "";
6730 }
6731
6732 print_symbol_info (FUNCTIONS_DOMAIN, q.symbol, q.block,
6733 last_filename);
6734 last_filename
6735 = symtab_to_filename_for_display (q.symbol->symtab ());
6736 }
6737}
6738
6739/* Hold the option values for the 'info module .....' sub-commands. */
6740
6741struct info_modules_var_func_options
6742{
6743 bool quiet = false;
6744 std::string type_regexp;
6745 std::string module_regexp;
6746};
6747
6748/* The options used by 'info module variables' and 'info module functions'
6749 commands. */
6750
6751static const gdb::option::option_def info_modules_var_func_options_defs [] = {
6752 gdb::option::boolean_option_def<info_modules_var_func_options> {
6753 "q",
6754 [] (info_modules_var_func_options *opt) { return &opt->quiet; },
6755 nullptr, /* show_cmd_cb */
6756 nullptr /* set_doc */
6757 },
6758
6759 gdb::option::string_option_def<info_modules_var_func_options> {
6760 "t",
6761 [] (info_modules_var_func_options *opt) { return &opt->type_regexp; },
6762 nullptr, /* show_cmd_cb */
6763 nullptr /* set_doc */
6764 },
6765
6766 gdb::option::string_option_def<info_modules_var_func_options> {
6767 "m",
6768 [] (info_modules_var_func_options *opt) { return &opt->module_regexp; },
6769 nullptr, /* show_cmd_cb */
6770 nullptr /* set_doc */
6771 }
6772};
6773
6774/* Return the option group used by the 'info module ...' sub-commands. */
6775
6776static inline gdb::option::option_def_group
6777make_info_modules_var_func_options_def_group
6778 (info_modules_var_func_options *opts)
6779{
6780 return {{info_modules_var_func_options_defs}, opts};
6781}
6782
6783/* Implements the 'info module functions' command. */
6784
6785static void
6786info_module_functions_command (const char *args, int from_tty)
6787{
6788 info_modules_var_func_options opts;
6789 auto grp = make_info_modules_var_func_options_def_group (&opts);
6790 gdb::option::process_options
6791 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
6792 if (args != nullptr && *args == '\0')
6793 args = nullptr;
6794
6795 info_module_subcommand
6796 (opts.quiet,
6797 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
6798 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
6799 FUNCTIONS_DOMAIN);
6800}
6801
6802/* Implements the 'info module variables' command. */
6803
6804static void
6805info_module_variables_command (const char *args, int from_tty)
6806{
6807 info_modules_var_func_options opts;
6808 auto grp = make_info_modules_var_func_options_def_group (&opts);
6809 gdb::option::process_options
6810 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
6811 if (args != nullptr && *args == '\0')
6812 args = nullptr;
6813
6814 info_module_subcommand
6815 (opts.quiet,
6816 opts.module_regexp.empty () ? nullptr : opts.module_regexp.c_str (), args,
6817 opts.type_regexp.empty () ? nullptr : opts.type_regexp.c_str (),
6818 VARIABLES_DOMAIN);
6819}
6820
6821/* Command completer for 'info module ...' sub-commands. */
6822
6823static void
6824info_module_var_func_command_completer (struct cmd_list_element *ignore,
6825 completion_tracker &tracker,
6826 const char *text,
6827 const char * /* word */)
6828{
6829
6830 const auto group = make_info_modules_var_func_options_def_group (nullptr);
6831 if (gdb::option::complete_options
6832 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
6833 return;
6834
6835 const char *word = advance_to_expression_complete_word_point (tracker, text);
6836 symbol_completer (ignore, tracker, text, word);
6837}
6838
6839\f
6840
6841void _initialize_symtab ();
6842void
6843_initialize_symtab ()
6844{
6845 cmd_list_element *c;
6846
6847 initialize_ordinary_address_classes ();
6848
6849 c = add_info ("variables", info_variables_command,
6850 info_print_args_help (_("\
6851All global and static variable names or those matching REGEXPs.\n\
6852Usage: info variables [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
6853Prints the global and static variables.\n"),
6854 _("global and static variables"),
6855 true));
6856 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
6857
6858 c = add_info ("functions", info_functions_command,
6859 info_print_args_help (_("\
6860All function names or those matching REGEXPs.\n\
6861Usage: info functions [-q] [-n] [-t TYPEREGEXP] [NAMEREGEXP]\n\
6862Prints the functions.\n"),
6863 _("functions"),
6864 true));
6865 set_cmd_completer_handle_brkchars (c, info_vars_funcs_command_completer);
6866
6867 c = add_info ("types", info_types_command, _("\
6868All type names, or those matching REGEXP.\n\
6869Usage: info types [-q] [REGEXP]\n\
6870Print information about all types matching REGEXP, or all types if no\n\
6871REGEXP is given. The optional flag -q disables printing of headers."));
6872 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
6873
6874 const auto info_sources_opts
6875 = make_info_sources_options_def_group (nullptr);
6876
6877 static std::string info_sources_help
6878 = gdb::option::build_help (_("\
6879All source files in the program or those matching REGEXP.\n\
6880Usage: info sources [OPTION]... [REGEXP]\n\
6881By default, REGEXP is used to match anywhere in the filename.\n\
6882\n\
6883Options:\n\
6884%OPTIONS%"),
6885 info_sources_opts);
6886
6887 c = add_info ("sources", info_sources_command, info_sources_help.c_str ());
6888 set_cmd_completer_handle_brkchars (c, info_sources_command_completer);
6889
6890 c = add_info ("modules", info_modules_command,
6891 _("All module names, or those matching REGEXP."));
6892 set_cmd_completer_handle_brkchars (c, info_types_command_completer);
6893
6894 add_info ("main", info_main_command,
6895 _("Get main symbol to identify entry point into program."));
6896
6897 add_basic_prefix_cmd ("module", class_info, _("\
6898Print information about modules."),
6899 &info_module_cmdlist, 0, &infolist);
6900
6901 c = add_cmd ("functions", class_info, info_module_functions_command, _("\
6902Display functions arranged by modules.\n\
6903Usage: info module functions [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
6904Print a summary of all functions within each Fortran module, grouped by\n\
6905module and file. For each function the line on which the function is\n\
6906defined is given along with the type signature and name of the function.\n\
6907\n\
6908If REGEXP is provided then only functions whose name matches REGEXP are\n\
6909listed. If MODREGEXP is provided then only functions in modules matching\n\
6910MODREGEXP are listed. If TYPEREGEXP is given then only functions whose\n\
6911type signature matches TYPEREGEXP are listed.\n\
6912\n\
6913The -q flag suppresses printing some header information."),
6914 &info_module_cmdlist);
6915 set_cmd_completer_handle_brkchars
6916 (c, info_module_var_func_command_completer);
6917
6918 c = add_cmd ("variables", class_info, info_module_variables_command, _("\
6919Display variables arranged by modules.\n\
6920Usage: info module variables [-q] [-m MODREGEXP] [-t TYPEREGEXP] [REGEXP]\n\
6921Print a summary of all variables within each Fortran module, grouped by\n\
6922module and file. For each variable the line on which the variable is\n\
6923defined is given along with the type and name of the variable.\n\
6924\n\
6925If REGEXP is provided then only variables whose name matches REGEXP are\n\
6926listed. If MODREGEXP is provided then only variables in modules matching\n\
6927MODREGEXP are listed. If TYPEREGEXP is given then only variables whose\n\
6928type matches TYPEREGEXP are listed.\n\
6929\n\
6930The -q flag suppresses printing some header information."),
6931 &info_module_cmdlist);
6932 set_cmd_completer_handle_brkchars
6933 (c, info_module_var_func_command_completer);
6934
6935 add_com ("rbreak", class_breakpoint, rbreak_command,
6936 _("Set a breakpoint for all functions matching REGEXP."));
6937
6938 add_setshow_enum_cmd ("multiple-symbols", no_class,
6939 multiple_symbols_modes, &multiple_symbols_mode,
6940 _("\
6941Set how the debugger handles ambiguities in expressions."), _("\
6942Show how the debugger handles ambiguities in expressions."), _("\
6943Valid values are \"ask\", \"all\", \"cancel\", and the default is \"all\"."),
6944 NULL, NULL, &setlist, &showlist);
6945
6946 add_setshow_boolean_cmd ("basenames-may-differ", class_obscure,
6947 &basenames_may_differ, _("\
6948Set whether a source file may have multiple base names."), _("\
6949Show whether a source file may have multiple base names."), _("\
6950(A \"base name\" is the name of a file with the directory part removed.\n\
6951Example: The base name of \"/home/user/hello.c\" is \"hello.c\".)\n\
6952If set, GDB will canonicalize file names (e.g., expand symlinks)\n\
6953before comparing them. Canonicalization is an expensive operation,\n\
6954but it allows the same file be known by more than one base name.\n\
6955If not set (the default), all source files are assumed to have just\n\
6956one base name, and gdb will do file name comparisons more efficiently."),
6957 NULL, NULL,
6958 &setlist, &showlist);
6959
6960 add_setshow_zuinteger_cmd ("symtab-create", no_class, &symtab_create_debug,
6961 _("Set debugging of symbol table creation."),
6962 _("Show debugging of symbol table creation."), _("\
6963When enabled (non-zero), debugging messages are printed when building\n\
6964symbol tables. A value of 1 (one) normally provides enough information.\n\
6965A value greater than 1 provides more verbose information."),
6966 NULL,
6967 NULL,
6968 &setdebuglist, &showdebuglist);
6969
6970 add_setshow_zuinteger_cmd ("symbol-lookup", no_class, &symbol_lookup_debug,
6971 _("\
6972Set debugging of symbol lookup."), _("\
6973Show debugging of symbol lookup."), _("\
6974When enabled (non-zero), symbol lookups are logged."),
6975 NULL, NULL,
6976 &setdebuglist, &showdebuglist);
6977
6978 add_setshow_zuinteger_cmd ("symbol-cache-size", no_class,
6979 &new_symbol_cache_size,
6980 _("Set the size of the symbol cache."),
6981 _("Show the size of the symbol cache."), _("\
6982The size of the symbol cache.\n\
6983If zero then the symbol cache is disabled."),
6984 set_symbol_cache_size_handler, NULL,
6985 &maintenance_set_cmdlist,
6986 &maintenance_show_cmdlist);
6987
6988 add_setshow_boolean_cmd ("ignore-prologue-end-flag", no_class,
6989 &ignore_prologue_end_flag,
6990 _("Set if the PROLOGUE-END flag is ignored."),
6991 _("Show if the PROLOGUE-END flag is ignored."),
6992 _("\
6993The PROLOGUE-END flag from the line-table entries is used to place \
6994breakpoints past the prologue of functions. Disabling its use forces \
6995the use of prologue scanners."),
6996 nullptr, nullptr,
6997 &maintenance_set_cmdlist,
6998 &maintenance_show_cmdlist);
6999
7000
7001 add_cmd ("symbol-cache", class_maintenance, maintenance_print_symbol_cache,
7002 _("Dump the symbol cache for each program space."),
7003 &maintenanceprintlist);
7004
7005 add_cmd ("symbol-cache-statistics", class_maintenance,
7006 maintenance_print_symbol_cache_statistics,
7007 _("Print symbol cache statistics for each program space."),
7008 &maintenanceprintlist);
7009
7010 cmd_list_element *maintenance_flush_symbol_cache_cmd
7011 = add_cmd ("symbol-cache", class_maintenance,
7012 maintenance_flush_symbol_cache,
7013 _("Flush the symbol cache for each program space."),
7014 &maintenanceflushlist);
7015 c = add_alias_cmd ("flush-symbol-cache", maintenance_flush_symbol_cache_cmd,
7016 class_maintenance, 0, &maintenancelist);
7017 deprecate_cmd (c, "maintenancelist flush symbol-cache");
7018
7019 gdb::observers::executable_changed.attach (symtab_observer_executable_changed,
7020 "symtab");
7021 gdb::observers::new_objfile.attach (symtab_new_objfile_observer, "symtab");
7022 gdb::observers::free_objfile.attach (symtab_free_objfile_observer, "symtab");
7023}