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