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