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