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