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