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