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