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