* source.c: Make global variables current_source_symtab and
[platform/upstream/binutils.git] / gdb / symtab.c
1 /* Symbol table lookup for the GNU debugger, GDB.
2
3    Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
4    1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002 Free Software
5    Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24 #include "defs.h"
25 #include "symtab.h"
26 #include "gdbtypes.h"
27 #include "gdbcore.h"
28 #include "frame.h"
29 #include "target.h"
30 #include "value.h"
31 #include "symfile.h"
32 #include "objfiles.h"
33 #include "gdbcmd.h"
34 #include "call-cmds.h"
35 #include "gdb_regex.h"
36 #include "expression.h"
37 #include "language.h"
38 #include "demangle.h"
39 #include "inferior.h"
40 #include "linespec.h"
41 #include "source.h"
42 #include "filenames.h"          /* for FILENAME_CMP */
43
44 #include "gdb_obstack.h"
45
46 #include <sys/types.h>
47 #include <fcntl.h>
48 #include "gdb_string.h"
49 #include "gdb_stat.h"
50 #include <ctype.h>
51 #include "cp-abi.h"
52
53 /* Prototype for one function in parser-defs.h,
54    instead of including that entire file. */
55
56 extern char *find_template_name_end (char *);
57
58 /* Prototypes for local functions */
59
60 static void completion_list_add_name (char *, char *, int, char *, char *);
61
62 static void rbreak_command (char *, int);
63
64 static void types_info (char *, int);
65
66 static void functions_info (char *, int);
67
68 static void variables_info (char *, int);
69
70 static void sources_info (char *, int);
71
72 static void output_source_filename (char *, int *);
73
74 static int find_line_common (struct linetable *, int, int *);
75
76 /* This one is used by linespec.c */
77
78 char *operator_chars (char *p, char **end);
79
80 static struct partial_symbol *lookup_partial_symbol (struct partial_symtab *,
81                                                      const char *, int,
82                                                      namespace_enum);
83
84 static struct symbol *lookup_symbol_aux (const char *name,
85                                          const char *mangled_name,
86                                          const struct block *block,
87                                          const namespace_enum namespace,
88                                          int *is_a_field_of_this,
89                                          struct symtab **symtab);
90
91
92 static struct symbol *find_active_alias (struct symbol *sym, CORE_ADDR addr);
93
94 /* This flag is used in hppa-tdep.c, and set in hp-symtab-read.c */
95 /* Signals the presence of objects compiled by HP compilers */
96 int hp_som_som_object_present = 0;
97
98 static void fixup_section (struct general_symbol_info *, struct objfile *);
99
100 static int file_matches (char *, char **, int);
101
102 static void print_symbol_info (namespace_enum,
103                                struct symtab *, struct symbol *, int, char *);
104
105 static void print_msymbol_info (struct minimal_symbol *);
106
107 static void symtab_symbol_info (char *, namespace_enum, int);
108
109 static void overload_list_add_symbol (struct symbol *sym, char *oload_name);
110
111 void _initialize_symtab (void);
112
113 /* */
114
115 /* The single non-language-specific builtin type */
116 struct type *builtin_type_error;
117
118 /* Block in which the most recently searched-for symbol was found.
119    Might be better to make this a parameter to lookup_symbol and 
120    value_of_this. */
121
122 const struct block *block_found;
123
124 /* While the C++ support is still in flux, issue a possibly helpful hint on
125    using the new command completion feature on single quoted demangled C++
126    symbols.  Remove when loose ends are cleaned up.   FIXME -fnf */
127
128 static void
129 cplusplus_hint (char *name)
130 {
131   while (*name == '\'')
132     name++;
133   printf_filtered ("Hint: try '%s<TAB> or '%s<ESC-?>\n", name, name);
134   printf_filtered ("(Note leading single quote.)\n");
135 }
136
137 /* Check for a symtab of a specific name; first in symtabs, then in
138    psymtabs.  *If* there is no '/' in the name, a match after a '/'
139    in the symtab filename will also work.  */
140
141 struct symtab *
142 lookup_symtab (const char *name)
143 {
144   register struct symtab *s;
145   register struct partial_symtab *ps;
146   register struct objfile *objfile;
147   char *real_path = NULL;
148   char *full_path = NULL;
149
150   /* Here we are interested in canonicalizing an absolute path, not
151      absolutizing a relative path.  */
152   if (IS_ABSOLUTE_PATH (name))
153     {
154       full_path = xfullpath (name);
155       make_cleanup (xfree, full_path);
156       real_path = gdb_realpath (name);
157       make_cleanup (xfree, real_path);
158     }
159
160 got_symtab:
161
162   /* First, search for an exact match */
163
164   ALL_SYMTABS (objfile, s)
165   {
166     if (FILENAME_CMP (name, s->filename) == 0)
167       {
168         return s;
169       }
170       
171     /* If the user gave us an absolute path, try to find the file in
172        this symtab and use its absolute path.  */
173     
174     if (full_path != NULL)
175       {
176         const char *fp = symtab_to_filename (s);
177         if (FILENAME_CMP (full_path, fp) == 0)
178           {
179             return s;
180           }
181       }
182
183     if (real_path != NULL)
184       {
185         char *rp = gdb_realpath (symtab_to_filename (s));
186         make_cleanup (xfree, rp);
187         if (FILENAME_CMP (real_path, rp) == 0)
188           {
189             return s;
190           }
191       }
192   }
193
194   /* Now, search for a matching tail (only if name doesn't have any dirs) */
195
196   if (lbasename (name) == name)
197     ALL_SYMTABS (objfile, s)
198     {
199       if (FILENAME_CMP (lbasename (s->filename), name) == 0)
200         return s;
201     }
202
203   /* Same search rules as above apply here, but now we look thru the
204      psymtabs.  */
205
206   ps = lookup_partial_symtab (name);
207   if (!ps)
208     return (NULL);
209
210   if (ps->readin)
211     error ("Internal: readin %s pst for `%s' found when no symtab found.",
212            ps->filename, name);
213
214   s = PSYMTAB_TO_SYMTAB (ps);
215
216   if (s)
217     return s;
218
219   /* At this point, we have located the psymtab for this file, but
220      the conversion to a symtab has failed.  This usually happens
221      when we are looking up an include file.  In this case,
222      PSYMTAB_TO_SYMTAB doesn't return a symtab, even though one has
223      been created.  So, we need to run through the symtabs again in
224      order to find the file.
225      XXX - This is a crock, and should be fixed inside of the the
226      symbol parsing routines. */
227   goto got_symtab;
228 }
229
230 /* Lookup the partial symbol table of a source file named NAME.
231    *If* there is no '/' in the name, a match after a '/'
232    in the psymtab filename will also work.  */
233
234 struct partial_symtab *
235 lookup_partial_symtab (const char *name)
236 {
237   register struct partial_symtab *pst;
238   register struct objfile *objfile;
239   char *full_path = NULL;
240   char *real_path = NULL;
241
242   /* Here we are interested in canonicalizing an absolute path, not
243      absolutizing a relative path.  */
244   if (IS_ABSOLUTE_PATH (name))
245     {
246       full_path = xfullpath (name);
247       make_cleanup (xfree, full_path);
248       real_path = gdb_realpath (name);
249       make_cleanup (xfree, real_path);
250     }
251
252   ALL_PSYMTABS (objfile, pst)
253   {
254     if (FILENAME_CMP (name, pst->filename) == 0)
255       {
256         return (pst);
257       }
258
259     /* If the user gave us an absolute path, try to find the file in
260        this symtab and use its absolute path.  */
261     if (full_path != NULL)
262       {
263         if (pst->fullname == NULL)
264           source_full_path_of (pst->filename, &pst->fullname);
265         if (pst->fullname != NULL
266             && FILENAME_CMP (full_path, pst->fullname) == 0)
267           {
268             return pst;
269           }
270       }
271
272     if (real_path != NULL)
273       {
274         char *rp = NULL;
275         if (pst->fullname == NULL)
276           source_full_path_of (pst->filename, &pst->fullname);
277         if (pst->fullname != NULL)
278           {
279             rp = gdb_realpath (pst->fullname);
280             make_cleanup (xfree, rp);
281           }
282         if (rp != NULL && FILENAME_CMP (real_path, rp) == 0)
283           {
284             return pst;
285           }
286       }
287   }
288
289   /* Now, search for a matching tail (only if name doesn't have any dirs) */
290
291   if (lbasename (name) == name)
292     ALL_PSYMTABS (objfile, pst)
293     {
294       if (FILENAME_CMP (lbasename (pst->filename), name) == 0)
295         return (pst);
296     }
297
298   return (NULL);
299 }
300 \f
301 /* Mangle a GDB method stub type.  This actually reassembles the pieces of the
302    full method name, which consist of the class name (from T), the unadorned
303    method name from METHOD_ID, and the signature for the specific overload,
304    specified by SIGNATURE_ID.  Note that this function is g++ specific. */
305
306 char *
307 gdb_mangle_name (struct type *type, int method_id, int signature_id)
308 {
309   int mangled_name_len;
310   char *mangled_name;
311   struct fn_field *f = TYPE_FN_FIELDLIST1 (type, method_id);
312   struct fn_field *method = &f[signature_id];
313   char *field_name = TYPE_FN_FIELDLIST_NAME (type, method_id);
314   char *physname = TYPE_FN_FIELD_PHYSNAME (f, signature_id);
315   char *newname = type_name_no_tag (type);
316
317   /* Does the form of physname indicate that it is the full mangled name
318      of a constructor (not just the args)?  */
319   int is_full_physname_constructor;
320
321   int is_constructor;
322   int is_destructor = is_destructor_name (physname);
323   /* Need a new type prefix.  */
324   char *const_prefix = method->is_const ? "C" : "";
325   char *volatile_prefix = method->is_volatile ? "V" : "";
326   char buf[20];
327   int len = (newname == NULL ? 0 : strlen (newname));
328
329   /* Nothing to do if physname already contains a fully mangled v3 abi name
330      or an operator name.  */
331   if ((physname[0] == '_' && physname[1] == 'Z')
332       || is_operator_name (field_name))
333     return xstrdup (physname);
334
335   is_full_physname_constructor = is_constructor_name (physname);
336
337   is_constructor =
338     is_full_physname_constructor || (newname && STREQ (field_name, newname));
339
340   if (!is_destructor)
341     is_destructor = (strncmp (physname, "__dt", 4) == 0);
342
343   if (is_destructor || is_full_physname_constructor)
344     {
345       mangled_name = (char *) xmalloc (strlen (physname) + 1);
346       strcpy (mangled_name, physname);
347       return mangled_name;
348     }
349
350   if (len == 0)
351     {
352       sprintf (buf, "__%s%s", const_prefix, volatile_prefix);
353     }
354   else if (physname[0] == 't' || physname[0] == 'Q')
355     {
356       /* The physname for template and qualified methods already includes
357          the class name.  */
358       sprintf (buf, "__%s%s", const_prefix, volatile_prefix);
359       newname = NULL;
360       len = 0;
361     }
362   else
363     {
364       sprintf (buf, "__%s%s%d", const_prefix, volatile_prefix, len);
365     }
366   mangled_name_len = ((is_constructor ? 0 : strlen (field_name))
367                       + strlen (buf) + len + strlen (physname) + 1);
368
369     {
370       mangled_name = (char *) xmalloc (mangled_name_len);
371       if (is_constructor)
372         mangled_name[0] = '\0';
373       else
374         strcpy (mangled_name, field_name);
375     }
376   strcat (mangled_name, buf);
377   /* If the class doesn't have a name, i.e. newname NULL, then we just
378      mangle it using 0 for the length of the class.  Thus it gets mangled
379      as something starting with `::' rather than `classname::'. */
380   if (newname != NULL)
381     strcat (mangled_name, newname);
382
383   strcat (mangled_name, physname);
384   return (mangled_name);
385 }
386
387 \f
388 /* Initialize a symbol's mangled name.  */
389
390 /* Try to initialize the demangled name for a symbol, based on the
391    language of that symbol.  If the language is set to language_auto,
392    it will attempt to find any demangling algorithm that works and
393    then set the language appropriately.  If no demangling of any kind
394    is found, the language is set back to language_unknown, so we can
395    avoid doing this work again the next time we encounter the symbol.
396    Any required space to store the name is obtained from the specified
397    obstack. */
398
399 void
400 symbol_init_demangled_name (struct general_symbol_info *gsymbol,
401                             struct obstack *obstack)
402 {
403   char *mangled = gsymbol->name;
404   char *demangled = NULL;
405
406   if (gsymbol->language == language_unknown)
407     gsymbol->language = language_auto;
408   if (gsymbol->language == language_cplus
409       || gsymbol->language == language_auto)
410     {
411       demangled =
412         cplus_demangle (gsymbol->name, DMGL_PARAMS | DMGL_ANSI);
413       if (demangled != NULL)
414         {
415           gsymbol->language = language_cplus;
416           gsymbol->language_specific.cplus_specific.demangled_name =
417             obsavestring (demangled, strlen (demangled), obstack);
418           xfree (demangled);
419         }
420       else
421         {
422           gsymbol->language_specific.cplus_specific.demangled_name = NULL;
423         }
424     }
425   if (gsymbol->language == language_java)
426     {
427       demangled =
428         cplus_demangle (gsymbol->name,
429                         DMGL_PARAMS | DMGL_ANSI | DMGL_JAVA);
430       if (demangled != NULL)
431         {
432           gsymbol->language = language_java;
433           gsymbol->language_specific.cplus_specific.demangled_name =
434             obsavestring (demangled, strlen (demangled), obstack);
435           xfree (demangled);
436         }
437       else
438         {
439           gsymbol->language_specific.cplus_specific.demangled_name = NULL;
440         }
441     }
442 #if 0
443   /* OBSOLETE if (demangled == NULL */
444   /* OBSOLETE     && (gsymbol->language == language_chill */
445   /* OBSOLETE         || gsymbol->language == language_auto)) */
446   /* OBSOLETE   { */
447   /* OBSOLETE     demangled = */
448   /* OBSOLETE       chill_demangle (gsymbol->name); */
449   /* OBSOLETE     if (demangled != NULL) */
450   /* OBSOLETE       { */
451   /* OBSOLETE         gsymbol->language = language_chill; */
452   /* OBSOLETE         gsymbol->language_specific.chill_specific.demangled_name = */
453   /* OBSOLETE           obsavestring (demangled, strlen (demangled), obstack); */
454   /* OBSOLETE         xfree (demangled); */
455   /* OBSOLETE       } */
456   /* OBSOLETE     else */
457   /* OBSOLETE       { */
458   /* OBSOLETE         gsymbol->language_specific.chill_specific.demangled_name = NULL; */
459   /* OBSOLETE       } */
460   /* OBSOLETE   } */
461 #endif
462 }
463
464
465 \f
466
467
468 /* Find which partial symtab on contains PC and SECTION.  Return 0 if none.  */
469
470 struct partial_symtab *
471 find_pc_sect_psymtab (CORE_ADDR pc, asection *section)
472 {
473   register struct partial_symtab *pst;
474   register struct objfile *objfile;
475   struct minimal_symbol *msymbol;
476
477   /* If we know that this is not a text address, return failure.  This is
478      necessary because we loop based on texthigh and textlow, which do
479      not include the data ranges.  */
480   msymbol = lookup_minimal_symbol_by_pc_section (pc, section);
481   if (msymbol
482       && (msymbol->type == mst_data
483           || msymbol->type == mst_bss
484           || msymbol->type == mst_abs
485           || msymbol->type == mst_file_data
486           || msymbol->type == mst_file_bss))
487     return NULL;
488
489   ALL_PSYMTABS (objfile, pst)
490   {
491     if (pc >= pst->textlow && pc < pst->texthigh)
492       {
493         struct partial_symtab *tpst;
494
495         /* An objfile that has its functions reordered might have
496            many partial symbol tables containing the PC, but
497            we want the partial symbol table that contains the
498            function containing the PC.  */
499         if (!(objfile->flags & OBJF_REORDERED) &&
500             section == 0)       /* can't validate section this way */
501           return (pst);
502
503         if (msymbol == NULL)
504           return (pst);
505
506         for (tpst = pst; tpst != NULL; tpst = tpst->next)
507           {
508             if (pc >= tpst->textlow && pc < tpst->texthigh)
509               {
510                 struct partial_symbol *p;
511
512                 p = find_pc_sect_psymbol (tpst, pc, section);
513                 if (p != NULL
514                     && SYMBOL_VALUE_ADDRESS (p)
515                     == SYMBOL_VALUE_ADDRESS (msymbol))
516                   return (tpst);
517               }
518           }
519         return (pst);
520       }
521   }
522   return (NULL);
523 }
524
525 /* Find which partial symtab contains PC.  Return 0 if none. 
526    Backward compatibility, no section */
527
528 struct partial_symtab *
529 find_pc_psymtab (CORE_ADDR pc)
530 {
531   return find_pc_sect_psymtab (pc, find_pc_mapped_section (pc));
532 }
533
534 /* Find which partial symbol within a psymtab matches PC and SECTION.  
535    Return 0 if none.  Check all psymtabs if PSYMTAB is 0.  */
536
537 struct partial_symbol *
538 find_pc_sect_psymbol (struct partial_symtab *psymtab, CORE_ADDR pc,
539                       asection *section)
540 {
541   struct partial_symbol *best = NULL, *p, **pp;
542   CORE_ADDR best_pc;
543
544   if (!psymtab)
545     psymtab = find_pc_sect_psymtab (pc, section);
546   if (!psymtab)
547     return 0;
548
549   /* Cope with programs that start at address 0 */
550   best_pc = (psymtab->textlow != 0) ? psymtab->textlow - 1 : 0;
551
552   /* Search the global symbols as well as the static symbols, so that
553      find_pc_partial_function doesn't use a minimal symbol and thus
554      cache a bad endaddr.  */
555   for (pp = psymtab->objfile->global_psymbols.list + psymtab->globals_offset;
556     (pp - (psymtab->objfile->global_psymbols.list + psymtab->globals_offset)
557      < psymtab->n_global_syms);
558        pp++)
559     {
560       p = *pp;
561       if (SYMBOL_NAMESPACE (p) == VAR_NAMESPACE
562           && SYMBOL_CLASS (p) == LOC_BLOCK
563           && pc >= SYMBOL_VALUE_ADDRESS (p)
564           && (SYMBOL_VALUE_ADDRESS (p) > best_pc
565               || (psymtab->textlow == 0
566                   && best_pc == 0 && SYMBOL_VALUE_ADDRESS (p) == 0)))
567         {
568           if (section)          /* match on a specific section */
569             {
570               fixup_psymbol_section (p, psymtab->objfile);
571               if (SYMBOL_BFD_SECTION (p) != section)
572                 continue;
573             }
574           best_pc = SYMBOL_VALUE_ADDRESS (p);
575           best = p;
576         }
577     }
578
579   for (pp = psymtab->objfile->static_psymbols.list + psymtab->statics_offset;
580     (pp - (psymtab->objfile->static_psymbols.list + psymtab->statics_offset)
581      < psymtab->n_static_syms);
582        pp++)
583     {
584       p = *pp;
585       if (SYMBOL_NAMESPACE (p) == VAR_NAMESPACE
586           && SYMBOL_CLASS (p) == LOC_BLOCK
587           && pc >= SYMBOL_VALUE_ADDRESS (p)
588           && (SYMBOL_VALUE_ADDRESS (p) > best_pc
589               || (psymtab->textlow == 0
590                   && best_pc == 0 && SYMBOL_VALUE_ADDRESS (p) == 0)))
591         {
592           if (section)          /* match on a specific section */
593             {
594               fixup_psymbol_section (p, psymtab->objfile);
595               if (SYMBOL_BFD_SECTION (p) != section)
596                 continue;
597             }
598           best_pc = SYMBOL_VALUE_ADDRESS (p);
599           best = p;
600         }
601     }
602
603   return best;
604 }
605
606 /* Find which partial symbol within a psymtab matches PC.  Return 0 if none.  
607    Check all psymtabs if PSYMTAB is 0.  Backwards compatibility, no section. */
608
609 struct partial_symbol *
610 find_pc_psymbol (struct partial_symtab *psymtab, CORE_ADDR pc)
611 {
612   return find_pc_sect_psymbol (psymtab, pc, find_pc_mapped_section (pc));
613 }
614 \f
615 /* Debug symbols usually don't have section information.  We need to dig that
616    out of the minimal symbols and stash that in the debug symbol.  */
617
618 static void
619 fixup_section (struct general_symbol_info *ginfo, struct objfile *objfile)
620 {
621   struct minimal_symbol *msym;
622   msym = lookup_minimal_symbol (ginfo->name, NULL, objfile);
623
624   if (msym)
625     {
626       ginfo->bfd_section = SYMBOL_BFD_SECTION (msym);
627       ginfo->section = SYMBOL_SECTION (msym);
628     }
629 }
630
631 struct symbol *
632 fixup_symbol_section (struct symbol *sym, struct objfile *objfile)
633 {
634   if (!sym)
635     return NULL;
636
637   if (SYMBOL_BFD_SECTION (sym))
638     return sym;
639
640   fixup_section (&sym->ginfo, objfile);
641
642   return sym;
643 }
644
645 struct partial_symbol *
646 fixup_psymbol_section (struct partial_symbol *psym, struct objfile *objfile)
647 {
648   if (!psym)
649     return NULL;
650
651   if (SYMBOL_BFD_SECTION (psym))
652     return psym;
653
654   fixup_section (&psym->ginfo, objfile);
655
656   return psym;
657 }
658
659 /* Find the definition for a specified symbol name NAME
660    in namespace NAMESPACE, visible from lexical block BLOCK.
661    Returns the struct symbol pointer, or zero if no symbol is found.
662    If SYMTAB is non-NULL, store the symbol table in which the
663    symbol was found there, or NULL if not found.
664    C++: if IS_A_FIELD_OF_THIS is nonzero on entry, check to see if
665    NAME is a field of the current implied argument `this'.  If so set
666    *IS_A_FIELD_OF_THIS to 1, otherwise set it to zero. 
667    BLOCK_FOUND is set to the block in which NAME is found (in the case of
668    a field of `this', value_of_this sets BLOCK_FOUND to the proper value.) */
669
670 /* This function has a bunch of loops in it and it would seem to be
671    attractive to put in some QUIT's (though I'm not really sure
672    whether it can run long enough to be really important).  But there
673    are a few calls for which it would appear to be bad news to quit
674    out of here: find_proc_desc in alpha-tdep.c and mips-tdep.c, and
675    nindy_frame_chain_valid in nindy-tdep.c.  (Note that there is C++
676    code below which can error(), but that probably doesn't affect
677    these calls since they are looking for a known variable and thus
678    can probably assume it will never hit the C++ code).  */
679
680 struct symbol *
681 lookup_symbol (const char *name, const struct block *block,
682                const namespace_enum namespace, int *is_a_field_of_this,
683                struct symtab **symtab)
684 {
685   char *demangled_name = NULL;
686   const char *modified_name = NULL;
687   const char *mangled_name = NULL;
688   int needtofreename = 0;
689   struct symbol *returnval;
690
691   modified_name = name;
692
693   /* If we are using C++ language, demangle the name before doing a lookup, so
694      we can always binary search. */
695   if (current_language->la_language == language_cplus)
696     {
697       demangled_name = cplus_demangle (name, DMGL_ANSI | DMGL_PARAMS);
698       if (demangled_name)
699         {
700           mangled_name = name;
701           modified_name = demangled_name;
702           needtofreename = 1;
703         }
704     }
705
706   if (case_sensitivity == case_sensitive_off)
707     {
708       char *copy;
709       int len, i;
710
711       len = strlen (name);
712       copy = (char *) alloca (len + 1);
713       for (i= 0; i < len; i++)
714         copy[i] = tolower (name[i]);
715       copy[len] = 0;
716       modified_name = copy;
717     }
718
719   returnval = lookup_symbol_aux (modified_name, mangled_name, block,
720                                  namespace, is_a_field_of_this, symtab);
721   if (needtofreename)
722     xfree (demangled_name);
723
724   return returnval;      
725 }
726
727 static struct symbol *
728 lookup_symbol_aux (const char *name, const char *mangled_name,
729                    const struct block *block, const namespace_enum namespace,
730                    int *is_a_field_of_this, struct symtab **symtab)
731 {
732   register struct symbol *sym;
733   register struct symtab *s = NULL;
734   register struct partial_symtab *ps;
735   register struct blockvector *bv;
736   register struct objfile *objfile = NULL;
737   register struct block *b;
738   register struct minimal_symbol *msymbol;
739
740
741   /* Search specified block and its superiors.  */
742
743   while (block != 0)
744     {
745       sym = lookup_block_symbol (block, name, mangled_name, namespace);
746       if (sym)
747         {
748           block_found = block;
749           if (symtab != NULL)
750             {
751               /* Search the list of symtabs for one which contains the
752                  address of the start of this block.  */
753               ALL_SYMTABS (objfile, s)
754               {
755                 bv = BLOCKVECTOR (s);
756                 b = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
757                 if (BLOCK_START (b) <= BLOCK_START (block)
758                     && BLOCK_END (b) > BLOCK_START (block))
759                   goto found;
760               }
761             found:
762               *symtab = s;
763             }
764
765           return fixup_symbol_section (sym, objfile);
766         }
767       block = BLOCK_SUPERBLOCK (block);
768     }
769
770   /* FIXME: this code is never executed--block is always NULL at this
771      point.  What is it trying to do, anyway?  We already should have
772      checked the STATIC_BLOCK above (it is the superblock of top-level
773      blocks).  Why is VAR_NAMESPACE special-cased?  */
774   /* Don't need to mess with the psymtabs; if we have a block,
775      that file is read in.  If we don't, then we deal later with
776      all the psymtab stuff that needs checking.  */
777   /* Note (RT): The following never-executed code looks unnecessary to me also.
778    * If we change the code to use the original (passed-in)
779    * value of 'block', we could cause it to execute, but then what
780    * would it do? The STATIC_BLOCK of the symtab containing the passed-in
781    * 'block' was already searched by the above code. And the STATIC_BLOCK's
782    * of *other* symtabs (those files not containing 'block' lexically)
783    * should not contain 'block' address-wise. So we wouldn't expect this
784    * code to find any 'sym''s that were not found above. I vote for 
785    * deleting the following paragraph of code.
786    */
787   if (namespace == VAR_NAMESPACE && block != NULL)
788     {
789       struct block *b;
790       /* Find the right symtab.  */
791       ALL_SYMTABS (objfile, s)
792       {
793         bv = BLOCKVECTOR (s);
794         b = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
795         if (BLOCK_START (b) <= BLOCK_START (block)
796             && BLOCK_END (b) > BLOCK_START (block))
797           {
798             sym = lookup_block_symbol (b, name, mangled_name, VAR_NAMESPACE);
799             if (sym)
800               {
801                 block_found = b;
802                 if (symtab != NULL)
803                   *symtab = s;
804                 return fixup_symbol_section (sym, objfile);
805               }
806           }
807       }
808     }
809
810
811   /* C++: If requested to do so by the caller, 
812      check to see if NAME is a field of `this'. */
813   if (is_a_field_of_this)
814     {
815       struct value *v = value_of_this (0);
816
817       *is_a_field_of_this = 0;
818       if (v && check_field (v, name))
819         {
820           *is_a_field_of_this = 1;
821           if (symtab != NULL)
822             *symtab = NULL;
823           return NULL;
824         }
825     }
826
827   /* Now search all global blocks.  Do the symtab's first, then
828      check the psymtab's. If a psymtab indicates the existence
829      of the desired name as a global, then do psymtab-to-symtab
830      conversion on the fly and return the found symbol. */
831
832   ALL_SYMTABS (objfile, s)
833   {
834     bv = BLOCKVECTOR (s);
835     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
836     sym = lookup_block_symbol (block, name, mangled_name, namespace);
837     if (sym)
838       {
839         block_found = block;
840         if (symtab != NULL)
841           *symtab = s;
842         return fixup_symbol_section (sym, objfile);
843       }
844   }
845
846 #ifndef HPUXHPPA
847
848   /* Check for the possibility of the symbol being a function or
849      a mangled variable that is stored in one of the minimal symbol tables.
850      Eventually, all global symbols might be resolved in this way.  */
851
852   if (namespace == VAR_NAMESPACE)
853     {
854       msymbol = lookup_minimal_symbol (name, NULL, NULL);
855       if (msymbol != NULL)
856         {
857           s = find_pc_sect_symtab (SYMBOL_VALUE_ADDRESS (msymbol),
858                                    SYMBOL_BFD_SECTION (msymbol));
859           if (s != NULL)
860             {
861               /* This is a function which has a symtab for its address.  */
862               bv = BLOCKVECTOR (s);
863               block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
864
865               /* This call used to pass `SYMBOL_NAME (msymbol)' as the
866                  `name' argument to lookup_block_symbol.  But the name
867                  of a minimal symbol is always mangled, so that seems
868                  to be clearly the wrong thing to pass as the
869                  unmangled name.  */
870               sym = lookup_block_symbol (block, name, mangled_name, namespace);
871               /* We kept static functions in minimal symbol table as well as
872                  in static scope. We want to find them in the symbol table. */
873               if (!sym)
874                 {
875                   block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
876                   sym = lookup_block_symbol (block, name,
877                                              mangled_name, namespace);
878                 }
879
880               /* sym == 0 if symbol was found in the minimal symbol table
881                  but not in the symtab.
882                  Return 0 to use the msymbol definition of "foo_".
883
884                  This happens for Fortran  "foo_" symbols,
885                  which are "foo" in the symtab.
886
887                  This can also happen if "asm" is used to make a
888                  regular symbol but not a debugging symbol, e.g.
889                  asm(".globl _main");
890                  asm("_main:");
891                */
892
893               if (symtab != NULL)
894                 *symtab = s;
895               return fixup_symbol_section (sym, objfile);
896             }
897           else if (MSYMBOL_TYPE (msymbol) != mst_text
898                    && MSYMBOL_TYPE (msymbol) != mst_file_text
899                    && !STREQ (name, SYMBOL_NAME (msymbol)))
900             {
901               /* This is a mangled variable, look it up by its
902                  mangled name.  */
903               return lookup_symbol_aux (SYMBOL_NAME (msymbol), mangled_name, block,
904                                         namespace, is_a_field_of_this, symtab);
905             }
906           /* There are no debug symbols for this file, or we are looking
907              for an unmangled variable.
908              Try to find a matching static symbol below. */
909         }
910     }
911
912 #endif
913
914   ALL_PSYMTABS (objfile, ps)
915   {
916     if (!ps->readin && lookup_partial_symbol (ps, name, 1, namespace))
917       {
918         s = PSYMTAB_TO_SYMTAB (ps);
919         bv = BLOCKVECTOR (s);
920         block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
921         sym = lookup_block_symbol (block, name, mangled_name, namespace);
922         if (!sym)
923           {
924             /* This shouldn't be necessary, but as a last resort
925              * try looking in the statics even though the psymtab
926              * claimed the symbol was global. It's possible that
927              * the psymtab gets it wrong in some cases.
928              */
929             block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
930             sym = lookup_block_symbol (block, name, mangled_name, namespace);
931             if (!sym)
932               error ("Internal: global symbol `%s' found in %s psymtab but not in symtab.\n\
933 %s may be an inlined function, or may be a template function\n\
934 (if a template, try specifying an instantiation: %s<type>).",
935                      name, ps->filename, name, name);
936           }
937         if (symtab != NULL)
938           *symtab = s;
939         return fixup_symbol_section (sym, objfile);
940       }
941   }
942
943   /* Now search all static file-level symbols.
944      Not strictly correct, but more useful than an error.
945      Do the symtabs first, then check the psymtabs.
946      If a psymtab indicates the existence
947      of the desired name as a file-level static, then do psymtab-to-symtab
948      conversion on the fly and return the found symbol. */
949
950   ALL_SYMTABS (objfile, s)
951   {
952     bv = BLOCKVECTOR (s);
953     block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
954     sym = lookup_block_symbol (block, name, mangled_name, namespace);
955     if (sym)
956       {
957         block_found = block;
958         if (symtab != NULL)
959           *symtab = s;
960         return fixup_symbol_section (sym, objfile);
961       }
962   }
963
964   ALL_PSYMTABS (objfile, ps)
965   {
966     if (!ps->readin && lookup_partial_symbol (ps, name, 0, namespace))
967       {
968         s = PSYMTAB_TO_SYMTAB (ps);
969         bv = BLOCKVECTOR (s);
970         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
971         sym = lookup_block_symbol (block, name, mangled_name, namespace);
972         if (!sym)
973           {
974             /* This shouldn't be necessary, but as a last resort
975              * try looking in the globals even though the psymtab
976              * claimed the symbol was static. It's possible that
977              * the psymtab gets it wrong in some cases.
978              */
979             block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
980             sym = lookup_block_symbol (block, name, mangled_name, namespace);
981             if (!sym)
982               error ("Internal: static symbol `%s' found in %s psymtab but not in symtab.\n\
983 %s may be an inlined function, or may be a template function\n\
984 (if a template, try specifying an instantiation: %s<type>).",
985                      name, ps->filename, name, name);
986           }
987         if (symtab != NULL)
988           *symtab = s;
989         return fixup_symbol_section (sym, objfile);
990       }
991   }
992
993 #ifdef HPUXHPPA
994
995   /* Check for the possibility of the symbol being a function or
996      a global variable that is stored in one of the minimal symbol tables.
997      The "minimal symbol table" is built from linker-supplied info.
998
999      RT: I moved this check to last, after the complete search of
1000      the global (p)symtab's and static (p)symtab's. For HP-generated
1001      symbol tables, this check was causing a premature exit from
1002      lookup_symbol with NULL return, and thus messing up symbol lookups
1003      of things like "c::f". It seems to me a check of the minimal
1004      symbol table ought to be a last resort in any case. I'm vaguely
1005      worried about the comment below which talks about FORTRAN routines "foo_"
1006      though... is it saying we need to do the "minsym" check before
1007      the static check in this case? 
1008    */
1009
1010   if (namespace == VAR_NAMESPACE)
1011     {
1012       msymbol = lookup_minimal_symbol (name, NULL, NULL);
1013       if (msymbol != NULL)
1014         {
1015           /* OK, we found a minimal symbol in spite of not
1016            * finding any symbol. There are various possible
1017            * explanations for this. One possibility is the symbol
1018            * exists in code not compiled -g. Another possibility
1019            * is that the 'psymtab' isn't doing its job.
1020            * A third possibility, related to #2, is that we were confused 
1021            * by name-mangling. For instance, maybe the psymtab isn't
1022            * doing its job because it only know about demangled
1023            * names, but we were given a mangled name...
1024            */
1025
1026           /* We first use the address in the msymbol to try to
1027            * locate the appropriate symtab. Note that find_pc_symtab()
1028            * has a side-effect of doing psymtab-to-symtab expansion,
1029            * for the found symtab.
1030            */
1031           s = find_pc_symtab (SYMBOL_VALUE_ADDRESS (msymbol));
1032           if (s != NULL)
1033             {
1034               bv = BLOCKVECTOR (s);
1035               block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
1036               /* This call used to pass `SYMBOL_NAME (msymbol)' as the
1037                  `name' argument to lookup_block_symbol.  But the name
1038                  of a minimal symbol is always mangled, so that seems
1039                  to be clearly the wrong thing to pass as the
1040                  unmangled name.  */
1041               sym = lookup_block_symbol (block, name, mangled_name, namespace);
1042               /* We kept static functions in minimal symbol table as well as
1043                  in static scope. We want to find them in the symbol table. */
1044               if (!sym)
1045                 {
1046                   block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
1047                   sym = lookup_block_symbol (block, name,
1048                                              mangled_name, namespace);
1049                 }
1050               /* If we found one, return it */
1051               if (sym)
1052                 {
1053                   if (symtab != NULL)
1054                     *symtab = s;
1055                   return sym;
1056                 }
1057
1058               /* If we get here with sym == 0, the symbol was 
1059                  found in the minimal symbol table
1060                  but not in the symtab.
1061                  Fall through and return 0 to use the msymbol 
1062                  definition of "foo_".
1063                  (Note that outer code generally follows up a call
1064                  to this routine with a call to lookup_minimal_symbol(),
1065                  so a 0 return means we'll just flow into that other routine).
1066
1067                  This happens for Fortran  "foo_" symbols,
1068                  which are "foo" in the symtab.
1069
1070                  This can also happen if "asm" is used to make a
1071                  regular symbol but not a debugging symbol, e.g.
1072                  asm(".globl _main");
1073                  asm("_main:");
1074                */
1075             }
1076
1077           /* If the lookup-by-address fails, try repeating the
1078            * entire lookup process with the symbol name from
1079            * the msymbol (if different from the original symbol name).
1080            */
1081           else if (MSYMBOL_TYPE (msymbol) != mst_text
1082                    && MSYMBOL_TYPE (msymbol) != mst_file_text
1083                    && !STREQ (name, SYMBOL_NAME (msymbol)))
1084             {
1085               return lookup_symbol_aux (SYMBOL_NAME (msymbol), mangled_name,
1086                                         block, namespace, is_a_field_of_this,
1087                                         symtab);
1088             }
1089         }
1090     }
1091
1092 #endif
1093
1094   if (symtab != NULL)
1095     *symtab = NULL;
1096   return 0;
1097 }
1098                                                                 
1099 /* Look, in partial_symtab PST, for symbol NAME.  Check the global
1100    symbols if GLOBAL, the static symbols if not */
1101
1102 static struct partial_symbol *
1103 lookup_partial_symbol (struct partial_symtab *pst, const char *name, int global,
1104                        namespace_enum namespace)
1105 {
1106   struct partial_symbol *temp;
1107   struct partial_symbol **start, **psym;
1108   struct partial_symbol **top, **bottom, **center;
1109   int length = (global ? pst->n_global_syms : pst->n_static_syms);
1110   int do_linear_search = 1;
1111   
1112   if (length == 0)
1113     {
1114       return (NULL);
1115     }
1116   start = (global ?
1117            pst->objfile->global_psymbols.list + pst->globals_offset :
1118            pst->objfile->static_psymbols.list + pst->statics_offset);
1119   
1120   if (global)                   /* This means we can use a binary search. */
1121     {
1122       do_linear_search = 0;
1123
1124       /* Binary search.  This search is guaranteed to end with center
1125          pointing at the earliest partial symbol with the correct
1126          name.  At that point *all* partial symbols with that name
1127          will be checked against the correct namespace. */
1128
1129       bottom = start;
1130       top = start + length - 1;
1131       while (top > bottom)
1132         {
1133           center = bottom + (top - bottom) / 2;
1134           if (!(center < top))
1135             internal_error (__FILE__, __LINE__, "failed internal consistency check");
1136           if (!do_linear_search
1137               && (SYMBOL_LANGUAGE (*center) == language_java))
1138             {
1139               do_linear_search = 1;
1140             }
1141           if (strcmp (SYMBOL_SOURCE_NAME (*center), name) >= 0)
1142             {
1143               top = center;
1144             }
1145           else
1146             {
1147               bottom = center + 1;
1148             }
1149         }
1150       if (!(top == bottom))
1151         internal_error (__FILE__, __LINE__, "failed internal consistency check");
1152
1153       /* djb - 2000-06-03 - Use SYMBOL_MATCHES_NAME, not a strcmp, so
1154          we don't have to force a linear search on C++. Probably holds true
1155          for JAVA as well, no way to check.*/
1156       while (SYMBOL_MATCHES_NAME (*top,name))
1157         {
1158           if (SYMBOL_NAMESPACE (*top) == namespace)
1159             {
1160                   return (*top);
1161             }
1162           top++;
1163         }
1164     }
1165
1166   /* Can't use a binary search or else we found during the binary search that
1167      we should also do a linear search. */
1168
1169   if (do_linear_search)
1170     {                   
1171       for (psym = start; psym < start + length; psym++)
1172         {
1173           if (namespace == SYMBOL_NAMESPACE (*psym))
1174             {
1175               if (SYMBOL_MATCHES_NAME (*psym, name))
1176                 {
1177                   return (*psym);
1178                 }
1179             }
1180         }
1181     }
1182
1183   return (NULL);
1184 }
1185
1186 /* Look up a type named NAME in the struct_namespace.  The type returned
1187    must not be opaque -- i.e., must have at least one field defined
1188
1189    This code was modelled on lookup_symbol -- the parts not relevant to looking
1190    up types were just left out.  In particular it's assumed here that types
1191    are available in struct_namespace and only at file-static or global blocks. */
1192
1193
1194 struct type *
1195 lookup_transparent_type (const char *name)
1196 {
1197   register struct symbol *sym;
1198   register struct symtab *s = NULL;
1199   register struct partial_symtab *ps;
1200   struct blockvector *bv;
1201   register struct objfile *objfile;
1202   register struct block *block;
1203
1204   /* Now search all the global symbols.  Do the symtab's first, then
1205      check the psymtab's. If a psymtab indicates the existence
1206      of the desired name as a global, then do psymtab-to-symtab
1207      conversion on the fly and return the found symbol.  */
1208
1209   ALL_SYMTABS (objfile, s)
1210   {
1211     bv = BLOCKVECTOR (s);
1212     block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
1213     sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1214     if (sym && !TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
1215       {
1216         return SYMBOL_TYPE (sym);
1217       }
1218   }
1219
1220   ALL_PSYMTABS (objfile, ps)
1221   {
1222     if (!ps->readin && lookup_partial_symbol (ps, name, 1, STRUCT_NAMESPACE))
1223       {
1224         s = PSYMTAB_TO_SYMTAB (ps);
1225         bv = BLOCKVECTOR (s);
1226         block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
1227         sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1228         if (!sym)
1229           {
1230             /* This shouldn't be necessary, but as a last resort
1231              * try looking in the statics even though the psymtab
1232              * claimed the symbol was global. It's possible that
1233              * the psymtab gets it wrong in some cases.
1234              */
1235             block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
1236             sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1237             if (!sym)
1238               error ("Internal: global symbol `%s' found in %s psymtab but not in symtab.\n\
1239 %s may be an inlined function, or may be a template function\n\
1240 (if a template, try specifying an instantiation: %s<type>).",
1241                      name, ps->filename, name, name);
1242           }
1243         if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
1244           return SYMBOL_TYPE (sym);
1245       }
1246   }
1247
1248   /* Now search the static file-level symbols.
1249      Not strictly correct, but more useful than an error.
1250      Do the symtab's first, then
1251      check the psymtab's. If a psymtab indicates the existence
1252      of the desired name as a file-level static, then do psymtab-to-symtab
1253      conversion on the fly and return the found symbol.
1254    */
1255
1256   ALL_SYMTABS (objfile, s)
1257   {
1258     bv = BLOCKVECTOR (s);
1259     block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
1260     sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1261     if (sym && !TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
1262       {
1263         return SYMBOL_TYPE (sym);
1264       }
1265   }
1266
1267   ALL_PSYMTABS (objfile, ps)
1268   {
1269     if (!ps->readin && lookup_partial_symbol (ps, name, 0, STRUCT_NAMESPACE))
1270       {
1271         s = PSYMTAB_TO_SYMTAB (ps);
1272         bv = BLOCKVECTOR (s);
1273         block = BLOCKVECTOR_BLOCK (bv, STATIC_BLOCK);
1274         sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1275         if (!sym)
1276           {
1277             /* This shouldn't be necessary, but as a last resort
1278              * try looking in the globals even though the psymtab
1279              * claimed the symbol was static. It's possible that
1280              * the psymtab gets it wrong in some cases.
1281              */
1282             block = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
1283             sym = lookup_block_symbol (block, name, NULL, STRUCT_NAMESPACE);
1284             if (!sym)
1285               error ("Internal: static symbol `%s' found in %s psymtab but not in symtab.\n\
1286 %s may be an inlined function, or may be a template function\n\
1287 (if a template, try specifying an instantiation: %s<type>).",
1288                      name, ps->filename, name, name);
1289           }
1290         if (!TYPE_IS_OPAQUE (SYMBOL_TYPE (sym)))
1291           return SYMBOL_TYPE (sym);
1292       }
1293   }
1294   return (struct type *) 0;
1295 }
1296
1297
1298 /* Find the psymtab containing main(). */
1299 /* FIXME:  What about languages without main() or specially linked
1300    executables that have no main() ? */
1301
1302 struct partial_symtab *
1303 find_main_psymtab (void)
1304 {
1305   register struct partial_symtab *pst;
1306   register struct objfile *objfile;
1307
1308   ALL_PSYMTABS (objfile, pst)
1309   {
1310     if (lookup_partial_symbol (pst, main_name (), 1, VAR_NAMESPACE))
1311       {
1312         return (pst);
1313       }
1314   }
1315   return (NULL);
1316 }
1317
1318 /* Search BLOCK for symbol NAME in NAMESPACE.
1319
1320    Note that if NAME is the demangled form of a C++ symbol, we will fail
1321    to find a match during the binary search of the non-encoded names, but
1322    for now we don't worry about the slight inefficiency of looking for
1323    a match we'll never find, since it will go pretty quick.  Once the
1324    binary search terminates, we drop through and do a straight linear
1325    search on the symbols.  Each symbol which is marked as being a C++
1326    symbol (language_cplus set) has both the encoded and non-encoded names
1327    tested for a match.
1328
1329    If MANGLED_NAME is non-NULL, verify that any symbol we find has this
1330    particular mangled name.
1331 */
1332
1333 struct symbol *
1334 lookup_block_symbol (register const struct block *block, const char *name,
1335                      const char *mangled_name,
1336                      const namespace_enum namespace)
1337 {
1338   register int bot, top, inc;
1339   register struct symbol *sym;
1340   register struct symbol *sym_found = NULL;
1341   register int do_linear_search = 1;
1342
1343   if (BLOCK_HASHTABLE (block))
1344     {
1345       unsigned int hash_index;
1346       hash_index = msymbol_hash_iw (name);
1347       hash_index = hash_index % BLOCK_BUCKETS (block);
1348       for (sym = BLOCK_BUCKET (block, hash_index); sym; sym = sym->hash_next)
1349         {
1350           if (SYMBOL_NAMESPACE (sym) == namespace 
1351               && (mangled_name
1352                   ? strcmp (SYMBOL_NAME (sym), mangled_name) == 0
1353                   : SYMBOL_MATCHES_NAME (sym, name)))
1354             return sym;
1355         }
1356       return NULL;
1357     }
1358
1359   /* If the blocks's symbols were sorted, start with a binary search.  */
1360
1361   if (BLOCK_SHOULD_SORT (block))
1362     {
1363       /* Reset the linear search flag so if the binary search fails, we
1364          won't do the linear search once unless we find some reason to
1365          do so */
1366
1367       do_linear_search = 0;
1368       top = BLOCK_NSYMS (block);
1369       bot = 0;
1370
1371       /* Advance BOT to not far before the first symbol whose name is NAME. */
1372
1373       while (1)
1374         {
1375           inc = (top - bot + 1);
1376           /* No need to keep binary searching for the last few bits worth.  */
1377           if (inc < 4)
1378             {
1379               break;
1380             }
1381           inc = (inc >> 1) + bot;
1382           sym = BLOCK_SYM (block, inc);
1383           if (!do_linear_search && (SYMBOL_LANGUAGE (sym) == language_java))
1384             {
1385               do_linear_search = 1;
1386             }
1387           if (SYMBOL_SOURCE_NAME (sym)[0] < name[0])
1388             {
1389               bot = inc;
1390             }
1391           else if (SYMBOL_SOURCE_NAME (sym)[0] > name[0])
1392             {
1393               top = inc;
1394             }
1395           else if (strcmp (SYMBOL_SOURCE_NAME (sym), name) < 0)
1396             {
1397               bot = inc;
1398             }
1399           else
1400             {
1401               top = inc;
1402             }
1403         }
1404
1405       /* Now scan forward until we run out of symbols, find one whose
1406          name is greater than NAME, or find one we want.  If there is
1407          more than one symbol with the right name and namespace, we
1408          return the first one; I believe it is now impossible for us
1409          to encounter two symbols with the same name and namespace
1410          here, because blocks containing argument symbols are no
1411          longer sorted.  The exception is for C++, where multiple functions
1412          (cloned constructors / destructors, in particular) can have
1413          the same demangled name.  So if we have a particular
1414          mangled name to match, try to do so.  */
1415
1416       top = BLOCK_NSYMS (block);
1417       while (bot < top)
1418         {
1419           sym = BLOCK_SYM (block, bot);
1420           if (SYMBOL_NAMESPACE (sym) == namespace
1421               && (mangled_name
1422                   ? strcmp (SYMBOL_NAME (sym), mangled_name) == 0
1423                   : SYMBOL_MATCHES_NAME (sym, name)))
1424             {
1425               return sym;
1426             }
1427           if (SYMBOL_SOURCE_NAME (sym)[0] > name[0])
1428             {
1429               break;
1430             }
1431           bot++;
1432         }
1433     }
1434
1435   /* Here if block isn't sorted, or we fail to find a match during the
1436      binary search above.  If during the binary search above, we find a
1437      symbol which is a Java symbol, then we have re-enabled the linear
1438      search flag which was reset when starting the binary search.
1439
1440      This loop is equivalent to the loop above, but hacked greatly for speed.
1441
1442      Note that parameter symbols do not always show up last in the
1443      list; this loop makes sure to take anything else other than
1444      parameter symbols first; it only uses parameter symbols as a
1445      last resort.  Note that this only takes up extra computation
1446      time on a match.  */
1447
1448   if (do_linear_search)
1449     {
1450       top = BLOCK_NSYMS (block);
1451       bot = 0;
1452       while (bot < top)
1453         {
1454           sym = BLOCK_SYM (block, bot);
1455           if (SYMBOL_NAMESPACE (sym) == namespace
1456               && (mangled_name
1457                   ? strcmp (SYMBOL_NAME (sym), mangled_name) == 0
1458                   : SYMBOL_MATCHES_NAME (sym, name)))
1459             {
1460               /* If SYM has aliases, then use any alias that is active
1461                  at the current PC.  If no alias is active at the current
1462                  PC, then use the main symbol.
1463
1464                  ?!? Is checking the current pc correct?  Is this routine
1465                  ever called to look up a symbol from another context?
1466
1467                  FIXME: No, it's not correct.  If someone sets a
1468                  conditional breakpoint at an address, then the
1469                  breakpoint's `struct expression' should refer to the
1470                  `struct symbol' appropriate for the breakpoint's
1471                  address, which may not be the PC.
1472
1473                  Even if it were never called from another context,
1474                  it's totally bizarre for lookup_symbol's behavior to
1475                  depend on the value of the inferior's current PC.  We
1476                  should pass in the appropriate PC as well as the
1477                  block.  The interface to lookup_symbol should change
1478                  to require the caller to provide a PC.  */
1479
1480               if (SYMBOL_ALIASES (sym))
1481                 sym = find_active_alias (sym, read_pc ());
1482
1483               sym_found = sym;
1484               if (SYMBOL_CLASS (sym) != LOC_ARG &&
1485                   SYMBOL_CLASS (sym) != LOC_LOCAL_ARG &&
1486                   SYMBOL_CLASS (sym) != LOC_REF_ARG &&
1487                   SYMBOL_CLASS (sym) != LOC_REGPARM &&
1488                   SYMBOL_CLASS (sym) != LOC_REGPARM_ADDR &&
1489                   SYMBOL_CLASS (sym) != LOC_BASEREG_ARG)
1490                 {
1491                   break;
1492                 }
1493             }
1494           bot++;
1495         }
1496     }
1497   return (sym_found);           /* Will be NULL if not found. */
1498 }
1499
1500 /* Given a main symbol SYM and ADDR, search through the alias
1501    list to determine if an alias is active at ADDR and return
1502    the active alias.
1503
1504    If no alias is active, then return SYM.  */
1505
1506 static struct symbol *
1507 find_active_alias (struct symbol *sym, CORE_ADDR addr)
1508 {
1509   struct range_list *r;
1510   struct alias_list *aliases;
1511
1512   /* If we have aliases, check them first.  */
1513   aliases = SYMBOL_ALIASES (sym);
1514
1515   while (aliases)
1516     {
1517       if (!SYMBOL_RANGES (aliases->sym))
1518         return aliases->sym;
1519       for (r = SYMBOL_RANGES (aliases->sym); r; r = r->next)
1520         {
1521           if (r->start <= addr && r->end > addr)
1522             return aliases->sym;
1523         }
1524       aliases = aliases->next;
1525     }
1526
1527   /* Nothing found, return the main symbol.  */
1528   return sym;
1529 }
1530 \f
1531
1532 /* Return the symbol for the function which contains a specified
1533    lexical block, described by a struct block BL.  */
1534
1535 struct symbol *
1536 block_function (struct block *bl)
1537 {
1538   while (BLOCK_FUNCTION (bl) == 0 && BLOCK_SUPERBLOCK (bl) != 0)
1539     bl = BLOCK_SUPERBLOCK (bl);
1540
1541   return BLOCK_FUNCTION (bl);
1542 }
1543
1544 /* Find the symtab associated with PC and SECTION.  Look through the
1545    psymtabs and read in another symtab if necessary. */
1546
1547 struct symtab *
1548 find_pc_sect_symtab (CORE_ADDR pc, asection *section)
1549 {
1550   register struct block *b;
1551   struct blockvector *bv;
1552   register struct symtab *s = NULL;
1553   register struct symtab *best_s = NULL;
1554   register struct partial_symtab *ps;
1555   register struct objfile *objfile;
1556   CORE_ADDR distance = 0;
1557   struct minimal_symbol *msymbol;
1558
1559   /* If we know that this is not a text address, return failure.  This is
1560      necessary because we loop based on the block's high and low code
1561      addresses, which do not include the data ranges, and because
1562      we call find_pc_sect_psymtab which has a similar restriction based
1563      on the partial_symtab's texthigh and textlow.  */
1564   msymbol = lookup_minimal_symbol_by_pc_section (pc, section);
1565   if (msymbol
1566       && (msymbol->type == mst_data
1567           || msymbol->type == mst_bss
1568           || msymbol->type == mst_abs
1569           || msymbol->type == mst_file_data
1570           || msymbol->type == mst_file_bss))
1571     return NULL;
1572
1573   /* Search all symtabs for the one whose file contains our address, and which
1574      is the smallest of all the ones containing the address.  This is designed
1575      to deal with a case like symtab a is at 0x1000-0x2000 and 0x3000-0x4000
1576      and symtab b is at 0x2000-0x3000.  So the GLOBAL_BLOCK for a is from
1577      0x1000-0x4000, but for address 0x2345 we want to return symtab b.
1578
1579      This happens for native ecoff format, where code from included files
1580      gets its own symtab. The symtab for the included file should have
1581      been read in already via the dependency mechanism.
1582      It might be swifter to create several symtabs with the same name
1583      like xcoff does (I'm not sure).
1584
1585      It also happens for objfiles that have their functions reordered.
1586      For these, the symtab we are looking for is not necessarily read in.  */
1587
1588   ALL_SYMTABS (objfile, s)
1589   {
1590     bv = BLOCKVECTOR (s);
1591     b = BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK);
1592
1593     if (BLOCK_START (b) <= pc
1594         && BLOCK_END (b) > pc
1595         && (distance == 0
1596             || BLOCK_END (b) - BLOCK_START (b) < distance))
1597       {
1598         /* For an objfile that has its functions reordered,
1599            find_pc_psymtab will find the proper partial symbol table
1600            and we simply return its corresponding symtab.  */
1601         /* In order to better support objfiles that contain both
1602            stabs and coff debugging info, we continue on if a psymtab
1603            can't be found. */
1604         if ((objfile->flags & OBJF_REORDERED) && objfile->psymtabs)
1605           {
1606             ps = find_pc_sect_psymtab (pc, section);
1607             if (ps)
1608               return PSYMTAB_TO_SYMTAB (ps);
1609           }
1610         if (section != 0)
1611           {
1612             int i;
1613             struct symbol *sym = NULL;
1614
1615             ALL_BLOCK_SYMBOLS (b, i, sym)
1616               {
1617                 fixup_symbol_section (sym, objfile);
1618                 if (section == SYMBOL_BFD_SECTION (sym))
1619                   break;
1620               }
1621             if ((i >= BLOCK_BUCKETS (b)) && (sym == NULL))
1622               continue;         /* no symbol in this symtab matches section */
1623           }
1624         distance = BLOCK_END (b) - BLOCK_START (b);
1625         best_s = s;
1626       }
1627   }
1628
1629   if (best_s != NULL)
1630     return (best_s);
1631
1632   s = NULL;
1633   ps = find_pc_sect_psymtab (pc, section);
1634   if (ps)
1635     {
1636       if (ps->readin)
1637         /* Might want to error() here (in case symtab is corrupt and
1638            will cause a core dump), but maybe we can successfully
1639            continue, so let's not.  */
1640         warning ("\
1641 (Internal error: pc 0x%s in read in psymtab, but not in symtab.)\n",
1642                  paddr_nz (pc));
1643       s = PSYMTAB_TO_SYMTAB (ps);
1644     }
1645   return (s);
1646 }
1647
1648 /* Find the symtab associated with PC.  Look through the psymtabs and
1649    read in another symtab if necessary.  Backward compatibility, no section */
1650
1651 struct symtab *
1652 find_pc_symtab (CORE_ADDR pc)
1653 {
1654   return find_pc_sect_symtab (pc, find_pc_mapped_section (pc));
1655 }
1656 \f
1657
1658 #if 0
1659
1660 /* Find the closest symbol value (of any sort -- function or variable)
1661    for a given address value.  Slow but complete.  (currently unused,
1662    mainly because it is too slow.  We could fix it if each symtab and
1663    psymtab had contained in it the addresses ranges of each of its
1664    sections, which also would be required to make things like "info
1665    line *0x2345" cause psymtabs to be converted to symtabs).  */
1666
1667 struct symbol *
1668 find_addr_symbol (CORE_ADDR addr, struct symtab **symtabp, CORE_ADDR *symaddrp)
1669 {
1670   struct symtab *symtab, *best_symtab;
1671   struct objfile *objfile;
1672   register int bot, top;
1673   register struct symbol *sym;
1674   register CORE_ADDR sym_addr;
1675   struct block *block;
1676   int blocknum;
1677
1678   /* Info on best symbol seen so far */
1679
1680   register CORE_ADDR best_sym_addr = 0;
1681   struct symbol *best_sym = 0;
1682
1683   /* FIXME -- we should pull in all the psymtabs, too!  */
1684   ALL_SYMTABS (objfile, symtab)
1685   {
1686     /* Search the global and static blocks in this symtab for
1687        the closest symbol-address to the desired address.  */
1688
1689     for (blocknum = GLOBAL_BLOCK; blocknum <= STATIC_BLOCK; blocknum++)
1690       {
1691         QUIT;
1692         block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), blocknum);
1693         ALL_BLOCK_SYMBOLS (block, bot, sym)
1694           {
1695             switch (SYMBOL_CLASS (sym))
1696               {
1697               case LOC_STATIC:
1698               case LOC_LABEL:
1699                 sym_addr = SYMBOL_VALUE_ADDRESS (sym);
1700                 break;
1701
1702               case LOC_INDIRECT:
1703                 sym_addr = SYMBOL_VALUE_ADDRESS (sym);
1704                 /* An indirect symbol really lives at *sym_addr,
1705                  * so an indirection needs to be done.
1706                  * However, I am leaving this commented out because it's
1707                  * expensive, and it's possible that symbolization
1708                  * could be done without an active process (in
1709                  * case this read_memory will fail). RT
1710                  sym_addr = read_memory_unsigned_integer
1711                  (sym_addr, TARGET_PTR_BIT / TARGET_CHAR_BIT);
1712                  */
1713                 break;
1714
1715               case LOC_BLOCK:
1716                 sym_addr = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
1717                 break;
1718
1719               default:
1720                 continue;
1721               }
1722
1723             if (sym_addr <= addr)
1724               if (sym_addr > best_sym_addr)
1725                 {
1726                   /* Quit if we found an exact match.  */
1727                   best_sym = sym;
1728                   best_sym_addr = sym_addr;
1729                   best_symtab = symtab;
1730                   if (sym_addr == addr)
1731                     goto done;
1732                 }
1733           }
1734       }
1735   }
1736
1737 done:
1738   if (symtabp)
1739     *symtabp = best_symtab;
1740   if (symaddrp)
1741     *symaddrp = best_sym_addr;
1742   return best_sym;
1743 }
1744 #endif /* 0 */
1745
1746 /* Find the source file and line number for a given PC value and SECTION.
1747    Return a structure containing a symtab pointer, a line number,
1748    and a pc range for the entire source line.
1749    The value's .pc field is NOT the specified pc.
1750    NOTCURRENT nonzero means, if specified pc is on a line boundary,
1751    use the line that ends there.  Otherwise, in that case, the line
1752    that begins there is used.  */
1753
1754 /* The big complication here is that a line may start in one file, and end just
1755    before the start of another file.  This usually occurs when you #include
1756    code in the middle of a subroutine.  To properly find the end of a line's PC
1757    range, we must search all symtabs associated with this compilation unit, and
1758    find the one whose first PC is closer than that of the next line in this
1759    symtab.  */
1760
1761 /* If it's worth the effort, we could be using a binary search.  */
1762
1763 struct symtab_and_line
1764 find_pc_sect_line (CORE_ADDR pc, struct sec *section, int notcurrent)
1765 {
1766   struct symtab *s;
1767   register struct linetable *l;
1768   register int len;
1769   register int i;
1770   register struct linetable_entry *item;
1771   struct symtab_and_line val;
1772   struct blockvector *bv;
1773   struct minimal_symbol *msymbol;
1774   struct minimal_symbol *mfunsym;
1775
1776   /* Info on best line seen so far, and where it starts, and its file.  */
1777
1778   struct linetable_entry *best = NULL;
1779   CORE_ADDR best_end = 0;
1780   struct symtab *best_symtab = 0;
1781
1782   /* Store here the first line number
1783      of a file which contains the line at the smallest pc after PC.
1784      If we don't find a line whose range contains PC,
1785      we will use a line one less than this,
1786      with a range from the start of that file to the first line's pc.  */
1787   struct linetable_entry *alt = NULL;
1788   struct symtab *alt_symtab = 0;
1789
1790   /* Info on best line seen in this file.  */
1791
1792   struct linetable_entry *prev;
1793
1794   /* If this pc is not from the current frame,
1795      it is the address of the end of a call instruction.
1796      Quite likely that is the start of the following statement.
1797      But what we want is the statement containing the instruction.
1798      Fudge the pc to make sure we get that.  */
1799
1800   INIT_SAL (&val);              /* initialize to zeroes */
1801
1802   /* It's tempting to assume that, if we can't find debugging info for
1803      any function enclosing PC, that we shouldn't search for line
1804      number info, either.  However, GAS can emit line number info for
1805      assembly files --- very helpful when debugging hand-written
1806      assembly code.  In such a case, we'd have no debug info for the
1807      function, but we would have line info.  */
1808
1809   if (notcurrent)
1810     pc -= 1;
1811
1812   /* elz: added this because this function returned the wrong
1813      information if the pc belongs to a stub (import/export)
1814      to call a shlib function. This stub would be anywhere between
1815      two functions in the target, and the line info was erroneously 
1816      taken to be the one of the line before the pc. 
1817    */
1818   /* RT: Further explanation:
1819
1820    * We have stubs (trampolines) inserted between procedures.
1821    *
1822    * Example: "shr1" exists in a shared library, and a "shr1" stub also
1823    * exists in the main image.
1824    *
1825    * In the minimal symbol table, we have a bunch of symbols
1826    * sorted by start address. The stubs are marked as "trampoline",
1827    * the others appear as text. E.g.:
1828    *
1829    *  Minimal symbol table for main image 
1830    *     main:  code for main (text symbol)
1831    *     shr1: stub  (trampoline symbol)
1832    *     foo:   code for foo (text symbol)
1833    *     ...
1834    *  Minimal symbol table for "shr1" image:
1835    *     ...
1836    *     shr1: code for shr1 (text symbol)
1837    *     ...
1838    *
1839    * So the code below is trying to detect if we are in the stub
1840    * ("shr1" stub), and if so, find the real code ("shr1" trampoline),
1841    * and if found,  do the symbolization from the real-code address
1842    * rather than the stub address.
1843    *
1844    * Assumptions being made about the minimal symbol table:
1845    *   1. lookup_minimal_symbol_by_pc() will return a trampoline only
1846    *      if we're really in the trampoline. If we're beyond it (say
1847    *      we're in "foo" in the above example), it'll have a closer 
1848    *      symbol (the "foo" text symbol for example) and will not
1849    *      return the trampoline.
1850    *   2. lookup_minimal_symbol_text() will find a real text symbol
1851    *      corresponding to the trampoline, and whose address will
1852    *      be different than the trampoline address. I put in a sanity
1853    *      check for the address being the same, to avoid an
1854    *      infinite recursion.
1855    */
1856   msymbol = lookup_minimal_symbol_by_pc (pc);
1857   if (msymbol != NULL)
1858     if (MSYMBOL_TYPE (msymbol) == mst_solib_trampoline)
1859       {
1860         mfunsym = lookup_minimal_symbol_text (SYMBOL_NAME (msymbol), NULL, NULL);
1861         if (mfunsym == NULL)
1862           /* I eliminated this warning since it is coming out
1863            * in the following situation:
1864            * gdb shmain // test program with shared libraries
1865            * (gdb) break shr1  // function in shared lib
1866            * Warning: In stub for ...
1867            * In the above situation, the shared lib is not loaded yet, 
1868            * so of course we can't find the real func/line info,
1869            * but the "break" still works, and the warning is annoying.
1870            * So I commented out the warning. RT */
1871           /* warning ("In stub for %s; unable to find real function/line info", SYMBOL_NAME(msymbol)) */ ;
1872         /* fall through */
1873         else if (SYMBOL_VALUE (mfunsym) == SYMBOL_VALUE (msymbol))
1874           /* Avoid infinite recursion */
1875           /* See above comment about why warning is commented out */
1876           /* warning ("In stub for %s; unable to find real function/line info", SYMBOL_NAME(msymbol)) */ ;
1877         /* fall through */
1878         else
1879           return find_pc_line (SYMBOL_VALUE (mfunsym), 0);
1880       }
1881
1882
1883   s = find_pc_sect_symtab (pc, section);
1884   if (!s)
1885     {
1886       /* if no symbol information, return previous pc */
1887       if (notcurrent)
1888         pc++;
1889       val.pc = pc;
1890       return val;
1891     }
1892
1893   bv = BLOCKVECTOR (s);
1894
1895   /* Look at all the symtabs that share this blockvector.
1896      They all have the same apriori range, that we found was right;
1897      but they have different line tables.  */
1898
1899   for (; s && BLOCKVECTOR (s) == bv; s = s->next)
1900     {
1901       /* Find the best line in this symtab.  */
1902       l = LINETABLE (s);
1903       if (!l)
1904         continue;
1905       len = l->nitems;
1906       if (len <= 0)
1907         {
1908           /* I think len can be zero if the symtab lacks line numbers
1909              (e.g. gcc -g1).  (Either that or the LINETABLE is NULL;
1910              I'm not sure which, and maybe it depends on the symbol
1911              reader).  */
1912           continue;
1913         }
1914
1915       prev = NULL;
1916       item = l->item;           /* Get first line info */
1917
1918       /* Is this file's first line closer than the first lines of other files?
1919          If so, record this file, and its first line, as best alternate.  */
1920       if (item->pc > pc && (!alt || item->pc < alt->pc))
1921         {
1922           alt = item;
1923           alt_symtab = s;
1924         }
1925
1926       for (i = 0; i < len; i++, item++)
1927         {
1928           /* Leave prev pointing to the linetable entry for the last line
1929              that started at or before PC.  */
1930           if (item->pc > pc)
1931             break;
1932
1933           prev = item;
1934         }
1935
1936       /* At this point, prev points at the line whose start addr is <= pc, and
1937          item points at the next line.  If we ran off the end of the linetable
1938          (pc >= start of the last line), then prev == item.  If pc < start of
1939          the first line, prev will not be set.  */
1940
1941       /* Is this file's best line closer than the best in the other files?
1942          If so, record this file, and its best line, as best so far.  */
1943
1944       if (prev && (!best || prev->pc > best->pc))
1945         {
1946           best = prev;
1947           best_symtab = s;
1948
1949           /* Discard BEST_END if it's before the PC of the current BEST.  */
1950           if (best_end <= best->pc)
1951             best_end = 0;
1952         }
1953
1954       /* If another line (denoted by ITEM) is in the linetable and its
1955          PC is after BEST's PC, but before the current BEST_END, then
1956          use ITEM's PC as the new best_end.  */
1957       if (best && i < len && item->pc > best->pc
1958           && (best_end == 0 || best_end > item->pc))
1959         best_end = item->pc;
1960     }
1961
1962   if (!best_symtab)
1963     {
1964       if (!alt_symtab)
1965         {                       /* If we didn't find any line # info, just
1966                                    return zeros.  */
1967           val.pc = pc;
1968         }
1969       else
1970         {
1971           val.symtab = alt_symtab;
1972           val.line = alt->line - 1;
1973
1974           /* Don't return line 0, that means that we didn't find the line.  */
1975           if (val.line == 0)
1976             ++val.line;
1977
1978           val.pc = BLOCK_END (BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK));
1979           val.end = alt->pc;
1980         }
1981     }
1982   else if (best->line == 0)
1983     {
1984       /* If our best fit is in a range of PC's for which no line
1985          number info is available (line number is zero) then we didn't
1986          find any valid line information. */
1987       val.pc = pc;
1988     }
1989   else
1990     {
1991       val.symtab = best_symtab;
1992       val.line = best->line;
1993       val.pc = best->pc;
1994       if (best_end && (!alt || best_end < alt->pc))
1995         val.end = best_end;
1996       else if (alt)
1997         val.end = alt->pc;
1998       else
1999         val.end = BLOCK_END (BLOCKVECTOR_BLOCK (bv, GLOBAL_BLOCK));
2000     }
2001   val.section = section;
2002   return val;
2003 }
2004
2005 /* Backward compatibility (no section) */
2006
2007 struct symtab_and_line
2008 find_pc_line (CORE_ADDR pc, int notcurrent)
2009 {
2010   asection *section;
2011
2012   section = find_pc_overlay (pc);
2013   if (pc_in_unmapped_range (pc, section))
2014     pc = overlay_mapped_address (pc, section);
2015   return find_pc_sect_line (pc, section, notcurrent);
2016 }
2017 \f
2018 /* Find line number LINE in any symtab whose name is the same as
2019    SYMTAB.
2020
2021    If found, return the symtab that contains the linetable in which it was
2022    found, set *INDEX to the index in the linetable of the best entry
2023    found, and set *EXACT_MATCH nonzero if the value returned is an
2024    exact match.
2025
2026    If not found, return NULL.  */
2027
2028 struct symtab *
2029 find_line_symtab (struct symtab *symtab, int line, int *index, int *exact_match)
2030 {
2031   int exact;
2032
2033   /* BEST_INDEX and BEST_LINETABLE identify the smallest linenumber > LINE
2034      so far seen.  */
2035
2036   int best_index;
2037   struct linetable *best_linetable;
2038   struct symtab *best_symtab;
2039
2040   /* First try looking it up in the given symtab.  */
2041   best_linetable = LINETABLE (symtab);
2042   best_symtab = symtab;
2043   best_index = find_line_common (best_linetable, line, &exact);
2044   if (best_index < 0 || !exact)
2045     {
2046       /* Didn't find an exact match.  So we better keep looking for
2047          another symtab with the same name.  In the case of xcoff,
2048          multiple csects for one source file (produced by IBM's FORTRAN
2049          compiler) produce multiple symtabs (this is unavoidable
2050          assuming csects can be at arbitrary places in memory and that
2051          the GLOBAL_BLOCK of a symtab has a begin and end address).  */
2052
2053       /* BEST is the smallest linenumber > LINE so far seen,
2054          or 0 if none has been seen so far.
2055          BEST_INDEX and BEST_LINETABLE identify the item for it.  */
2056       int best;
2057
2058       struct objfile *objfile;
2059       struct symtab *s;
2060
2061       if (best_index >= 0)
2062         best = best_linetable->item[best_index].line;
2063       else
2064         best = 0;
2065
2066       ALL_SYMTABS (objfile, s)
2067       {
2068         struct linetable *l;
2069         int ind;
2070
2071         if (!STREQ (symtab->filename, s->filename))
2072           continue;
2073         l = LINETABLE (s);
2074         ind = find_line_common (l, line, &exact);
2075         if (ind >= 0)
2076           {
2077             if (exact)
2078               {
2079                 best_index = ind;
2080                 best_linetable = l;
2081                 best_symtab = s;
2082                 goto done;
2083               }
2084             if (best == 0 || l->item[ind].line < best)
2085               {
2086                 best = l->item[ind].line;
2087                 best_index = ind;
2088                 best_linetable = l;
2089                 best_symtab = s;
2090               }
2091           }
2092       }
2093     }
2094 done:
2095   if (best_index < 0)
2096     return NULL;
2097
2098   if (index)
2099     *index = best_index;
2100   if (exact_match)
2101     *exact_match = exact;
2102
2103   return best_symtab;
2104 }
2105 \f
2106 /* Set the PC value for a given source file and line number and return true.
2107    Returns zero for invalid line number (and sets the PC to 0).
2108    The source file is specified with a struct symtab.  */
2109
2110 int
2111 find_line_pc (struct symtab *symtab, int line, CORE_ADDR *pc)
2112 {
2113   struct linetable *l;
2114   int ind;
2115
2116   *pc = 0;
2117   if (symtab == 0)
2118     return 0;
2119
2120   symtab = find_line_symtab (symtab, line, &ind, NULL);
2121   if (symtab != NULL)
2122     {
2123       l = LINETABLE (symtab);
2124       *pc = l->item[ind].pc;
2125       return 1;
2126     }
2127   else
2128     return 0;
2129 }
2130
2131 /* Find the range of pc values in a line.
2132    Store the starting pc of the line into *STARTPTR
2133    and the ending pc (start of next line) into *ENDPTR.
2134    Returns 1 to indicate success.
2135    Returns 0 if could not find the specified line.  */
2136
2137 int
2138 find_line_pc_range (struct symtab_and_line sal, CORE_ADDR *startptr,
2139                     CORE_ADDR *endptr)
2140 {
2141   CORE_ADDR startaddr;
2142   struct symtab_and_line found_sal;
2143
2144   startaddr = sal.pc;
2145   if (startaddr == 0 && !find_line_pc (sal.symtab, sal.line, &startaddr))
2146     return 0;
2147
2148   /* This whole function is based on address.  For example, if line 10 has
2149      two parts, one from 0x100 to 0x200 and one from 0x300 to 0x400, then
2150      "info line *0x123" should say the line goes from 0x100 to 0x200
2151      and "info line *0x355" should say the line goes from 0x300 to 0x400.
2152      This also insures that we never give a range like "starts at 0x134
2153      and ends at 0x12c".  */
2154
2155   found_sal = find_pc_sect_line (startaddr, sal.section, 0);
2156   if (found_sal.line != sal.line)
2157     {
2158       /* The specified line (sal) has zero bytes.  */
2159       *startptr = found_sal.pc;
2160       *endptr = found_sal.pc;
2161     }
2162   else
2163     {
2164       *startptr = found_sal.pc;
2165       *endptr = found_sal.end;
2166     }
2167   return 1;
2168 }
2169
2170 /* Given a line table and a line number, return the index into the line
2171    table for the pc of the nearest line whose number is >= the specified one.
2172    Return -1 if none is found.  The value is >= 0 if it is an index.
2173
2174    Set *EXACT_MATCH nonzero if the value returned is an exact match.  */
2175
2176 static int
2177 find_line_common (register struct linetable *l, register int lineno,
2178                   int *exact_match)
2179 {
2180   register int i;
2181   register int len;
2182
2183   /* BEST is the smallest linenumber > LINENO so far seen,
2184      or 0 if none has been seen so far.
2185      BEST_INDEX identifies the item for it.  */
2186
2187   int best_index = -1;
2188   int best = 0;
2189
2190   if (lineno <= 0)
2191     return -1;
2192   if (l == 0)
2193     return -1;
2194
2195   len = l->nitems;
2196   for (i = 0; i < len; i++)
2197     {
2198       register struct linetable_entry *item = &(l->item[i]);
2199
2200       if (item->line == lineno)
2201         {
2202           /* Return the first (lowest address) entry which matches.  */
2203           *exact_match = 1;
2204           return i;
2205         }
2206
2207       if (item->line > lineno && (best == 0 || item->line < best))
2208         {
2209           best = item->line;
2210           best_index = i;
2211         }
2212     }
2213
2214   /* If we got here, we didn't get an exact match.  */
2215
2216   *exact_match = 0;
2217   return best_index;
2218 }
2219
2220 int
2221 find_pc_line_pc_range (CORE_ADDR pc, CORE_ADDR *startptr, CORE_ADDR *endptr)
2222 {
2223   struct symtab_and_line sal;
2224   sal = find_pc_line (pc, 0);
2225   *startptr = sal.pc;
2226   *endptr = sal.end;
2227   return sal.symtab != 0;
2228 }
2229
2230 /* Given a function symbol SYM, find the symtab and line for the start
2231    of the function.
2232    If the argument FUNFIRSTLINE is nonzero, we want the first line
2233    of real code inside the function.  */
2234
2235 struct symtab_and_line
2236 find_function_start_sal (struct symbol *sym, int funfirstline)
2237 {
2238   CORE_ADDR pc;
2239   struct symtab_and_line sal;
2240
2241   pc = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
2242   fixup_symbol_section (sym, NULL);
2243   if (funfirstline)
2244     {                           /* skip "first line" of function (which is actually its prologue) */
2245       asection *section = SYMBOL_BFD_SECTION (sym);
2246       /* If function is in an unmapped overlay, use its unmapped LMA
2247          address, so that SKIP_PROLOGUE has something unique to work on */
2248       if (section_is_overlay (section) &&
2249           !section_is_mapped (section))
2250         pc = overlay_unmapped_address (pc, section);
2251
2252       pc += FUNCTION_START_OFFSET;
2253       pc = SKIP_PROLOGUE (pc);
2254
2255       /* For overlays, map pc back into its mapped VMA range */
2256       pc = overlay_mapped_address (pc, section);
2257     }
2258   sal = find_pc_sect_line (pc, SYMBOL_BFD_SECTION (sym), 0);
2259
2260 #ifdef PROLOGUE_FIRSTLINE_OVERLAP
2261   /* Convex: no need to suppress code on first line, if any */
2262   sal.pc = pc;
2263 #else
2264   /* Check if SKIP_PROLOGUE left us in mid-line, and the next
2265      line is still part of the same function.  */
2266   if (sal.pc != pc
2267       && BLOCK_START (SYMBOL_BLOCK_VALUE (sym)) <= sal.end
2268       && sal.end < BLOCK_END (SYMBOL_BLOCK_VALUE (sym)))
2269     {
2270       /* First pc of next line */
2271       pc = sal.end;
2272       /* Recalculate the line number (might not be N+1).  */
2273       sal = find_pc_sect_line (pc, SYMBOL_BFD_SECTION (sym), 0);
2274     }
2275   sal.pc = pc;
2276 #endif
2277
2278   return sal;
2279 }
2280
2281 /* If P is of the form "operator[ \t]+..." where `...' is
2282    some legitimate operator text, return a pointer to the
2283    beginning of the substring of the operator text.
2284    Otherwise, return "".  */
2285 char *
2286 operator_chars (char *p, char **end)
2287 {
2288   *end = "";
2289   if (strncmp (p, "operator", 8))
2290     return *end;
2291   p += 8;
2292
2293   /* Don't get faked out by `operator' being part of a longer
2294      identifier.  */
2295   if (isalpha (*p) || *p == '_' || *p == '$' || *p == '\0')
2296     return *end;
2297
2298   /* Allow some whitespace between `operator' and the operator symbol.  */
2299   while (*p == ' ' || *p == '\t')
2300     p++;
2301
2302   /* Recognize 'operator TYPENAME'. */
2303
2304   if (isalpha (*p) || *p == '_' || *p == '$')
2305     {
2306       register char *q = p + 1;
2307       while (isalnum (*q) || *q == '_' || *q == '$')
2308         q++;
2309       *end = q;
2310       return p;
2311     }
2312
2313   while (*p)
2314     switch (*p)
2315       {
2316       case '\\':                        /* regexp quoting */
2317         if (p[1] == '*')
2318           {
2319             if (p[2] == '=')    /* 'operator\*=' */
2320               *end = p + 3;
2321             else                        /* 'operator\*'  */
2322               *end = p + 2;
2323             return p;
2324           }
2325         else if (p[1] == '[')
2326           {
2327             if (p[2] == ']')
2328               error ("mismatched quoting on brackets, try 'operator\\[\\]'");
2329             else if (p[2] == '\\' && p[3] == ']')
2330               {
2331                 *end = p + 4;   /* 'operator\[\]' */
2332                 return p;
2333               }
2334             else
2335               error ("nothing is allowed between '[' and ']'");
2336           }
2337         else 
2338           {
2339             /* Gratuitous qoute: skip it and move on. */
2340             p++;
2341             continue;
2342           }
2343         break;
2344       case '!':
2345       case '=':
2346       case '*':
2347       case '/':
2348       case '%':
2349       case '^':
2350         if (p[1] == '=')
2351           *end = p + 2;
2352         else
2353           *end = p + 1;
2354         return p;
2355       case '<':
2356       case '>':
2357       case '+':
2358       case '-':
2359       case '&':
2360       case '|':
2361         if (p[0] == '-' && p[1] == '>')
2362           {
2363             /* Struct pointer member operator 'operator->'. */
2364             if (p[2] == '*')
2365               {
2366                 *end = p + 3;   /* 'operator->*' */
2367                 return p;
2368               }
2369             else if (p[2] == '\\')
2370               {
2371                 *end = p + 4;   /* Hopefully 'operator->\*' */
2372                 return p;
2373               }
2374             else
2375               {
2376                 *end = p + 2;   /* 'operator->' */
2377                 return p;
2378               }
2379           }
2380         if (p[1] == '=' || p[1] == p[0])
2381           *end = p + 2;
2382         else
2383           *end = p + 1;
2384         return p;
2385       case '~':
2386       case ',':
2387         *end = p + 1;
2388         return p;
2389       case '(':
2390         if (p[1] != ')')
2391           error ("`operator ()' must be specified without whitespace in `()'");
2392         *end = p + 2;
2393         return p;
2394       case '?':
2395         if (p[1] != ':')
2396           error ("`operator ?:' must be specified without whitespace in `?:'");
2397         *end = p + 2;
2398         return p;
2399       case '[':
2400         if (p[1] != ']')
2401           error ("`operator []' must be specified without whitespace in `[]'");
2402         *end = p + 2;
2403         return p;
2404       default:
2405         error ("`operator %s' not supported", p);
2406         break;
2407       }
2408
2409   *end = "";
2410   return *end;
2411 }
2412 \f
2413
2414 /* If FILE is not already in the table of files, return zero;
2415    otherwise return non-zero.  Optionally add FILE to the table if ADD
2416    is non-zero.  If *FIRST is non-zero, forget the old table
2417    contents.  */
2418 static int
2419 filename_seen (const char *file, int add, int *first)
2420 {
2421   /* Table of files seen so far.  */
2422   static const char **tab = NULL;
2423   /* Allocated size of tab in elements.
2424      Start with one 256-byte block (when using GNU malloc.c).
2425      24 is the malloc overhead when range checking is in effect.  */
2426   static int tab_alloc_size = (256 - 24) / sizeof (char *);
2427   /* Current size of tab in elements.  */
2428   static int tab_cur_size;
2429   const char **p;
2430
2431   if (*first)
2432     {
2433       if (tab == NULL)
2434         tab = (const char **) xmalloc (tab_alloc_size * sizeof (*tab));
2435       tab_cur_size = 0;
2436     }
2437
2438   /* Is FILE in tab?  */
2439   for (p = tab; p < tab + tab_cur_size; p++)
2440     if (strcmp (*p, file) == 0)
2441       return 1;
2442
2443   /* No; maybe add it to tab.  */
2444   if (add)
2445     {
2446       if (tab_cur_size == tab_alloc_size)
2447         {
2448           tab_alloc_size *= 2;
2449           tab = (const char **) xrealloc ((char *) tab,
2450                                           tab_alloc_size * sizeof (*tab));
2451         }
2452       tab[tab_cur_size++] = file;
2453     }
2454
2455   return 0;
2456 }
2457
2458 /* Slave routine for sources_info.  Force line breaks at ,'s.
2459    NAME is the name to print and *FIRST is nonzero if this is the first
2460    name printed.  Set *FIRST to zero.  */
2461 static void
2462 output_source_filename (char *name, int *first)
2463 {
2464   /* Since a single source file can result in several partial symbol
2465      tables, we need to avoid printing it more than once.  Note: if
2466      some of the psymtabs are read in and some are not, it gets
2467      printed both under "Source files for which symbols have been
2468      read" and "Source files for which symbols will be read in on
2469      demand".  I consider this a reasonable way to deal with the
2470      situation.  I'm not sure whether this can also happen for
2471      symtabs; it doesn't hurt to check.  */
2472
2473   /* Was NAME already seen?  */
2474   if (filename_seen (name, 1, first))
2475     {
2476       /* Yes; don't print it again.  */
2477       return;
2478     }
2479   /* No; print it and reset *FIRST.  */
2480   if (*first)
2481     {
2482       *first = 0;
2483     }
2484   else
2485     {
2486       printf_filtered (", ");
2487     }
2488
2489   wrap_here ("");
2490   fputs_filtered (name, gdb_stdout);
2491 }
2492
2493 static void
2494 sources_info (char *ignore, int from_tty)
2495 {
2496   register struct symtab *s;
2497   register struct partial_symtab *ps;
2498   register struct objfile *objfile;
2499   int first;
2500
2501   if (!have_full_symbols () && !have_partial_symbols ())
2502     {
2503       error ("No symbol table is loaded.  Use the \"file\" command.");
2504     }
2505
2506   printf_filtered ("Source files for which symbols have been read in:\n\n");
2507
2508   first = 1;
2509   ALL_SYMTABS (objfile, s)
2510   {
2511     output_source_filename (s->filename, &first);
2512   }
2513   printf_filtered ("\n\n");
2514
2515   printf_filtered ("Source files for which symbols will be read in on demand:\n\n");
2516
2517   first = 1;
2518   ALL_PSYMTABS (objfile, ps)
2519   {
2520     if (!ps->readin)
2521       {
2522         output_source_filename (ps->filename, &first);
2523       }
2524   }
2525   printf_filtered ("\n");
2526 }
2527
2528 static int
2529 file_matches (char *file, char *files[], int nfiles)
2530 {
2531   int i;
2532
2533   if (file != NULL && nfiles != 0)
2534     {
2535       for (i = 0; i < nfiles; i++)
2536         {
2537           if (strcmp (files[i], lbasename (file)) == 0)
2538             return 1;
2539         }
2540     }
2541   else if (nfiles == 0)
2542     return 1;
2543   return 0;
2544 }
2545
2546 /* Free any memory associated with a search. */
2547 void
2548 free_search_symbols (struct symbol_search *symbols)
2549 {
2550   struct symbol_search *p;
2551   struct symbol_search *next;
2552
2553   for (p = symbols; p != NULL; p = next)
2554     {
2555       next = p->next;
2556       xfree (p);
2557     }
2558 }
2559
2560 static void
2561 do_free_search_symbols_cleanup (void *symbols)
2562 {
2563   free_search_symbols (symbols);
2564 }
2565
2566 struct cleanup *
2567 make_cleanup_free_search_symbols (struct symbol_search *symbols)
2568 {
2569   return make_cleanup (do_free_search_symbols_cleanup, symbols);
2570 }
2571
2572 /* Helper function for sort_search_symbols and qsort.  Can only
2573    sort symbols, not minimal symbols.  */
2574 static int
2575 compare_search_syms (const void *sa, const void *sb)
2576 {
2577   struct symbol_search **sym_a = (struct symbol_search **) sa;
2578   struct symbol_search **sym_b = (struct symbol_search **) sb;
2579
2580   return strcmp (SYMBOL_SOURCE_NAME ((*sym_a)->symbol),
2581                  SYMBOL_SOURCE_NAME ((*sym_b)->symbol));
2582 }
2583
2584 /* Sort the ``nfound'' symbols in the list after prevtail.  Leave
2585    prevtail where it is, but update its next pointer to point to
2586    the first of the sorted symbols.  */
2587 static struct symbol_search *
2588 sort_search_symbols (struct symbol_search *prevtail, int nfound)
2589 {
2590   struct symbol_search **symbols, *symp, *old_next;
2591   int i;
2592
2593   symbols = (struct symbol_search **) xmalloc (sizeof (struct symbol_search *)
2594                                                * nfound);
2595   symp = prevtail->next;
2596   for (i = 0; i < nfound; i++)
2597     {
2598       symbols[i] = symp;
2599       symp = symp->next;
2600     }
2601   /* Generally NULL.  */
2602   old_next = symp;
2603
2604   qsort (symbols, nfound, sizeof (struct symbol_search *),
2605          compare_search_syms);
2606
2607   symp = prevtail;
2608   for (i = 0; i < nfound; i++)
2609     {
2610       symp->next = symbols[i];
2611       symp = symp->next;
2612     }
2613   symp->next = old_next;
2614
2615   xfree (symbols);
2616   return symp;
2617 }
2618
2619 /* Search the symbol table for matches to the regular expression REGEXP,
2620    returning the results in *MATCHES.
2621
2622    Only symbols of KIND are searched:
2623    FUNCTIONS_NAMESPACE - search all functions
2624    TYPES_NAMESPACE     - search all type names
2625    METHODS_NAMESPACE   - search all methods NOT IMPLEMENTED
2626    VARIABLES_NAMESPACE - search all symbols, excluding functions, type names,
2627    and constants (enums)
2628
2629    free_search_symbols should be called when *MATCHES is no longer needed.
2630
2631    The results are sorted locally; each symtab's global and static blocks are
2632    separately alphabetized.
2633  */
2634 void
2635 search_symbols (char *regexp, namespace_enum kind, int nfiles, char *files[],
2636                 struct symbol_search **matches)
2637 {
2638   register struct symtab *s;
2639   register struct partial_symtab *ps;
2640   register struct blockvector *bv;
2641   struct blockvector *prev_bv = 0;
2642   register struct block *b;
2643   register int i = 0;
2644   register int j;
2645   register struct symbol *sym;
2646   struct partial_symbol **psym;
2647   struct objfile *objfile;
2648   struct minimal_symbol *msymbol;
2649   char *val;
2650   int found_misc = 0;
2651   static enum minimal_symbol_type types[]
2652   =
2653   {mst_data, mst_text, mst_abs, mst_unknown};
2654   static enum minimal_symbol_type types2[]
2655   =
2656   {mst_bss, mst_file_text, mst_abs, mst_unknown};
2657   static enum minimal_symbol_type types3[]
2658   =
2659   {mst_file_data, mst_solib_trampoline, mst_abs, mst_unknown};
2660   static enum minimal_symbol_type types4[]
2661   =
2662   {mst_file_bss, mst_text, mst_abs, mst_unknown};
2663   enum minimal_symbol_type ourtype;
2664   enum minimal_symbol_type ourtype2;
2665   enum minimal_symbol_type ourtype3;
2666   enum minimal_symbol_type ourtype4;
2667   struct symbol_search *sr;
2668   struct symbol_search *psr;
2669   struct symbol_search *tail;
2670   struct cleanup *old_chain = NULL;
2671
2672   if (kind < VARIABLES_NAMESPACE)
2673     error ("must search on specific namespace");
2674
2675   ourtype = types[(int) (kind - VARIABLES_NAMESPACE)];
2676   ourtype2 = types2[(int) (kind - VARIABLES_NAMESPACE)];
2677   ourtype3 = types3[(int) (kind - VARIABLES_NAMESPACE)];
2678   ourtype4 = types4[(int) (kind - VARIABLES_NAMESPACE)];
2679
2680   sr = *matches = NULL;
2681   tail = NULL;
2682
2683   if (regexp != NULL)
2684     {
2685       /* Make sure spacing is right for C++ operators.
2686          This is just a courtesy to make the matching less sensitive
2687          to how many spaces the user leaves between 'operator'
2688          and <TYPENAME> or <OPERATOR>. */
2689       char *opend;
2690       char *opname = operator_chars (regexp, &opend);
2691       if (*opname)
2692         {
2693           int fix = -1;         /* -1 means ok; otherwise number of spaces needed. */
2694           if (isalpha (*opname) || *opname == '_' || *opname == '$')
2695             {
2696               /* There should 1 space between 'operator' and 'TYPENAME'. */
2697               if (opname[-1] != ' ' || opname[-2] == ' ')
2698                 fix = 1;
2699             }
2700           else
2701             {
2702               /* There should 0 spaces between 'operator' and 'OPERATOR'. */
2703               if (opname[-1] == ' ')
2704                 fix = 0;
2705             }
2706           /* If wrong number of spaces, fix it. */
2707           if (fix >= 0)
2708             {
2709               char *tmp = (char *) alloca (8 + fix + strlen (opname) + 1);
2710               sprintf (tmp, "operator%.*s%s", fix, " ", opname);
2711               regexp = tmp;
2712             }
2713         }
2714
2715       if (0 != (val = re_comp (regexp)))
2716         error ("Invalid regexp (%s): %s", val, regexp);
2717     }
2718
2719   /* Search through the partial symtabs *first* for all symbols
2720      matching the regexp.  That way we don't have to reproduce all of
2721      the machinery below. */
2722
2723   ALL_PSYMTABS (objfile, ps)
2724   {
2725     struct partial_symbol **bound, **gbound, **sbound;
2726     int keep_going = 1;
2727
2728     if (ps->readin)
2729       continue;
2730
2731     gbound = objfile->global_psymbols.list + ps->globals_offset + ps->n_global_syms;
2732     sbound = objfile->static_psymbols.list + ps->statics_offset + ps->n_static_syms;
2733     bound = gbound;
2734
2735     /* Go through all of the symbols stored in a partial
2736        symtab in one loop. */
2737     psym = objfile->global_psymbols.list + ps->globals_offset;
2738     while (keep_going)
2739       {
2740         if (psym >= bound)
2741           {
2742             if (bound == gbound && ps->n_static_syms != 0)
2743               {
2744                 psym = objfile->static_psymbols.list + ps->statics_offset;
2745                 bound = sbound;
2746               }
2747             else
2748               keep_going = 0;
2749             continue;
2750           }
2751         else
2752           {
2753             QUIT;
2754
2755             /* If it would match (logic taken from loop below)
2756                load the file and go on to the next one */
2757             if (file_matches (ps->filename, files, nfiles)
2758                 && ((regexp == NULL || SYMBOL_MATCHES_REGEXP (*psym))
2759                     && ((kind == VARIABLES_NAMESPACE && SYMBOL_CLASS (*psym) != LOC_TYPEDEF
2760                          && SYMBOL_CLASS (*psym) != LOC_BLOCK)
2761                         || (kind == FUNCTIONS_NAMESPACE && SYMBOL_CLASS (*psym) == LOC_BLOCK)
2762                         || (kind == TYPES_NAMESPACE && SYMBOL_CLASS (*psym) == LOC_TYPEDEF)
2763                         || (kind == METHODS_NAMESPACE && SYMBOL_CLASS (*psym) == LOC_BLOCK))))
2764               {
2765                 PSYMTAB_TO_SYMTAB (ps);
2766                 keep_going = 0;
2767               }
2768           }
2769         psym++;
2770       }
2771   }
2772
2773   /* Here, we search through the minimal symbol tables for functions
2774      and variables that match, and force their symbols to be read.
2775      This is in particular necessary for demangled variable names,
2776      which are no longer put into the partial symbol tables.
2777      The symbol will then be found during the scan of symtabs below.
2778
2779      For functions, find_pc_symtab should succeed if we have debug info
2780      for the function, for variables we have to call lookup_symbol
2781      to determine if the variable has debug info.
2782      If the lookup fails, set found_misc so that we will rescan to print
2783      any matching symbols without debug info.
2784    */
2785
2786   if (nfiles == 0 && (kind == VARIABLES_NAMESPACE || kind == FUNCTIONS_NAMESPACE))
2787     {
2788       ALL_MSYMBOLS (objfile, msymbol)
2789       {
2790         if (MSYMBOL_TYPE (msymbol) == ourtype ||
2791             MSYMBOL_TYPE (msymbol) == ourtype2 ||
2792             MSYMBOL_TYPE (msymbol) == ourtype3 ||
2793             MSYMBOL_TYPE (msymbol) == ourtype4)
2794           {
2795             if (regexp == NULL || SYMBOL_MATCHES_REGEXP (msymbol))
2796               {
2797                 if (0 == find_pc_symtab (SYMBOL_VALUE_ADDRESS (msymbol)))
2798                   {
2799                     if (kind == FUNCTIONS_NAMESPACE
2800                         || lookup_symbol (SYMBOL_NAME (msymbol),
2801                                           (struct block *) NULL,
2802                                           VAR_NAMESPACE,
2803                                         0, (struct symtab **) NULL) == NULL)
2804                       found_misc = 1;
2805                   }
2806               }
2807           }
2808       }
2809     }
2810
2811   ALL_SYMTABS (objfile, s)
2812   {
2813     bv = BLOCKVECTOR (s);
2814     /* Often many files share a blockvector.
2815        Scan each blockvector only once so that
2816        we don't get every symbol many times.
2817        It happens that the first symtab in the list
2818        for any given blockvector is the main file.  */
2819     if (bv != prev_bv)
2820       for (i = GLOBAL_BLOCK; i <= STATIC_BLOCK; i++)
2821         {
2822           struct symbol_search *prevtail = tail;
2823           int nfound = 0;
2824           b = BLOCKVECTOR_BLOCK (bv, i);
2825           ALL_BLOCK_SYMBOLS (b, j, sym)
2826             {
2827               QUIT;
2828               if (file_matches (s->filename, files, nfiles)
2829                   && ((regexp == NULL || SYMBOL_MATCHES_REGEXP (sym))
2830                       && ((kind == VARIABLES_NAMESPACE && SYMBOL_CLASS (sym) != LOC_TYPEDEF
2831                            && SYMBOL_CLASS (sym) != LOC_BLOCK
2832                            && SYMBOL_CLASS (sym) != LOC_CONST)
2833                           || (kind == FUNCTIONS_NAMESPACE && SYMBOL_CLASS (sym) == LOC_BLOCK)
2834                           || (kind == TYPES_NAMESPACE && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
2835                           || (kind == METHODS_NAMESPACE && SYMBOL_CLASS (sym) == LOC_BLOCK))))
2836                 {
2837                   /* match */
2838                   psr = (struct symbol_search *) xmalloc (sizeof (struct symbol_search));
2839                   psr->block = i;
2840                   psr->symtab = s;
2841                   psr->symbol = sym;
2842                   psr->msymbol = NULL;
2843                   psr->next = NULL;
2844                   if (tail == NULL)
2845                     sr = psr;
2846                   else
2847                     tail->next = psr;
2848                   tail = psr;
2849                   nfound ++;
2850                 }
2851             }
2852           if (nfound > 0)
2853             {
2854               if (prevtail == NULL)
2855                 {
2856                   struct symbol_search dummy;
2857
2858                   dummy.next = sr;
2859                   tail = sort_search_symbols (&dummy, nfound);
2860                   sr = dummy.next;
2861
2862                   old_chain = make_cleanup_free_search_symbols (sr);
2863                 }
2864               else
2865                 tail = sort_search_symbols (prevtail, nfound);
2866             }
2867         }
2868     prev_bv = bv;
2869   }
2870
2871   /* If there are no eyes, avoid all contact.  I mean, if there are
2872      no debug symbols, then print directly from the msymbol_vector.  */
2873
2874   if (found_misc || kind != FUNCTIONS_NAMESPACE)
2875     {
2876       ALL_MSYMBOLS (objfile, msymbol)
2877       {
2878         if (MSYMBOL_TYPE (msymbol) == ourtype ||
2879             MSYMBOL_TYPE (msymbol) == ourtype2 ||
2880             MSYMBOL_TYPE (msymbol) == ourtype3 ||
2881             MSYMBOL_TYPE (msymbol) == ourtype4)
2882           {
2883             if (regexp == NULL || SYMBOL_MATCHES_REGEXP (msymbol))
2884               {
2885                 /* Functions:  Look up by address. */
2886                 if (kind != FUNCTIONS_NAMESPACE ||
2887                     (0 == find_pc_symtab (SYMBOL_VALUE_ADDRESS (msymbol))))
2888                   {
2889                     /* Variables/Absolutes:  Look up by name */
2890                     if (lookup_symbol (SYMBOL_NAME (msymbol),
2891                                        (struct block *) NULL, VAR_NAMESPACE,
2892                                        0, (struct symtab **) NULL) == NULL)
2893                       {
2894                         /* match */
2895                         psr = (struct symbol_search *) xmalloc (sizeof (struct symbol_search));
2896                         psr->block = i;
2897                         psr->msymbol = msymbol;
2898                         psr->symtab = NULL;
2899                         psr->symbol = NULL;
2900                         psr->next = NULL;
2901                         if (tail == NULL)
2902                           {
2903                             sr = psr;
2904                             old_chain = make_cleanup_free_search_symbols (sr);
2905                           }
2906                         else
2907                           tail->next = psr;
2908                         tail = psr;
2909                       }
2910                   }
2911               }
2912           }
2913       }
2914     }
2915
2916   *matches = sr;
2917   if (sr != NULL)
2918     discard_cleanups (old_chain);
2919 }
2920
2921 /* Helper function for symtab_symbol_info, this function uses
2922    the data returned from search_symbols() to print information
2923    regarding the match to gdb_stdout.
2924  */
2925 static void
2926 print_symbol_info (namespace_enum kind, struct symtab *s, struct symbol *sym,
2927                    int block, char *last)
2928 {
2929   if (last == NULL || strcmp (last, s->filename) != 0)
2930     {
2931       fputs_filtered ("\nFile ", gdb_stdout);
2932       fputs_filtered (s->filename, gdb_stdout);
2933       fputs_filtered (":\n", gdb_stdout);
2934     }
2935
2936   if (kind != TYPES_NAMESPACE && block == STATIC_BLOCK)
2937     printf_filtered ("static ");
2938
2939   /* Typedef that is not a C++ class */
2940   if (kind == TYPES_NAMESPACE
2941       && SYMBOL_NAMESPACE (sym) != STRUCT_NAMESPACE)
2942     typedef_print (SYMBOL_TYPE (sym), sym, gdb_stdout);
2943   /* variable, func, or typedef-that-is-c++-class */
2944   else if (kind < TYPES_NAMESPACE ||
2945            (kind == TYPES_NAMESPACE &&
2946             SYMBOL_NAMESPACE (sym) == STRUCT_NAMESPACE))
2947     {
2948       type_print (SYMBOL_TYPE (sym),
2949                   (SYMBOL_CLASS (sym) == LOC_TYPEDEF
2950                    ? "" : SYMBOL_SOURCE_NAME (sym)),
2951                   gdb_stdout, 0);
2952
2953       printf_filtered (";\n");
2954     }
2955   else
2956     {
2957 #if 0
2958       /* Tiemann says: "info methods was never implemented."  */
2959       char *demangled_name;
2960       c_type_print_base (TYPE_FN_FIELD_TYPE (t, block),
2961                          gdb_stdout, 0, 0);
2962       c_type_print_varspec_prefix (TYPE_FN_FIELD_TYPE (t, block),
2963                                    gdb_stdout, 0);
2964       if (TYPE_FN_FIELD_STUB (t, block))
2965         check_stub_method (TYPE_DOMAIN_TYPE (type), j, block);
2966       demangled_name =
2967         cplus_demangle (TYPE_FN_FIELD_PHYSNAME (t, block),
2968                         DMGL_ANSI | DMGL_PARAMS);
2969       if (demangled_name == NULL)
2970         fprintf_filtered (stream, "<badly mangled name %s>",
2971                           TYPE_FN_FIELD_PHYSNAME (t, block));
2972       else
2973         {
2974           fputs_filtered (demangled_name, stream);
2975           xfree (demangled_name);
2976         }
2977 #endif
2978     }
2979 }
2980
2981 /* This help function for symtab_symbol_info() prints information
2982    for non-debugging symbols to gdb_stdout.
2983  */
2984 static void
2985 print_msymbol_info (struct minimal_symbol *msymbol)
2986 {
2987   char *tmp;
2988
2989   if (TARGET_ADDR_BIT <= 32)
2990     tmp = local_hex_string_custom (SYMBOL_VALUE_ADDRESS (msymbol)
2991                                    & (CORE_ADDR) 0xffffffff,
2992                                    "08l");
2993   else
2994     tmp = local_hex_string_custom (SYMBOL_VALUE_ADDRESS (msymbol),
2995                                    "016l");
2996   printf_filtered ("%s  %s\n",
2997                    tmp, SYMBOL_SOURCE_NAME (msymbol));
2998 }
2999
3000 /* This is the guts of the commands "info functions", "info types", and
3001    "info variables". It calls search_symbols to find all matches and then
3002    print_[m]symbol_info to print out some useful information about the
3003    matches.
3004  */
3005 static void
3006 symtab_symbol_info (char *regexp, namespace_enum kind, int from_tty)
3007 {
3008   static char *classnames[]
3009   =
3010   {"variable", "function", "type", "method"};
3011   struct symbol_search *symbols;
3012   struct symbol_search *p;
3013   struct cleanup *old_chain;
3014   char *last_filename = NULL;
3015   int first = 1;
3016
3017   /* must make sure that if we're interrupted, symbols gets freed */
3018   search_symbols (regexp, kind, 0, (char **) NULL, &symbols);
3019   old_chain = make_cleanup_free_search_symbols (symbols);
3020
3021   printf_filtered (regexp
3022                    ? "All %ss matching regular expression \"%s\":\n"
3023                    : "All defined %ss:\n",
3024                    classnames[(int) (kind - VARIABLES_NAMESPACE)], regexp);
3025
3026   for (p = symbols; p != NULL; p = p->next)
3027     {
3028       QUIT;
3029
3030       if (p->msymbol != NULL)
3031         {
3032           if (first)
3033             {
3034               printf_filtered ("\nNon-debugging symbols:\n");
3035               first = 0;
3036             }
3037           print_msymbol_info (p->msymbol);
3038         }
3039       else
3040         {
3041           print_symbol_info (kind,
3042                              p->symtab,
3043                              p->symbol,
3044                              p->block,
3045                              last_filename);
3046           last_filename = p->symtab->filename;
3047         }
3048     }
3049
3050   do_cleanups (old_chain);
3051 }
3052
3053 static void
3054 variables_info (char *regexp, int from_tty)
3055 {
3056   symtab_symbol_info (regexp, VARIABLES_NAMESPACE, from_tty);
3057 }
3058
3059 static void
3060 functions_info (char *regexp, int from_tty)
3061 {
3062   symtab_symbol_info (regexp, FUNCTIONS_NAMESPACE, from_tty);
3063 }
3064
3065
3066 static void
3067 types_info (char *regexp, int from_tty)
3068 {
3069   symtab_symbol_info (regexp, TYPES_NAMESPACE, from_tty);
3070 }
3071
3072 #if 0
3073 /* Tiemann says: "info methods was never implemented."  */
3074 static void
3075 methods_info (char *regexp)
3076 {
3077   symtab_symbol_info (regexp, METHODS_NAMESPACE, 0, from_tty);
3078 }
3079 #endif /* 0 */
3080
3081 /* Breakpoint all functions matching regular expression. */
3082
3083 void
3084 rbreak_command_wrapper (char *regexp, int from_tty)
3085 {
3086   rbreak_command (regexp, from_tty);
3087 }
3088
3089 static void
3090 rbreak_command (char *regexp, int from_tty)
3091 {
3092   struct symbol_search *ss;
3093   struct symbol_search *p;
3094   struct cleanup *old_chain;
3095
3096   search_symbols (regexp, FUNCTIONS_NAMESPACE, 0, (char **) NULL, &ss);
3097   old_chain = make_cleanup_free_search_symbols (ss);
3098
3099   for (p = ss; p != NULL; p = p->next)
3100     {
3101       if (p->msymbol == NULL)
3102         {
3103           char *string = (char *) alloca (strlen (p->symtab->filename)
3104                                           + strlen (SYMBOL_NAME (p->symbol))
3105                                           + 4);
3106           strcpy (string, p->symtab->filename);
3107           strcat (string, ":'");
3108           strcat (string, SYMBOL_NAME (p->symbol));
3109           strcat (string, "'");
3110           break_command (string, from_tty);
3111           print_symbol_info (FUNCTIONS_NAMESPACE,
3112                              p->symtab,
3113                              p->symbol,
3114                              p->block,
3115                              p->symtab->filename);
3116         }
3117       else
3118         {
3119           break_command (SYMBOL_NAME (p->msymbol), from_tty);
3120           printf_filtered ("<function, no debug info> %s;\n",
3121                            SYMBOL_SOURCE_NAME (p->msymbol));
3122         }
3123     }
3124
3125   do_cleanups (old_chain);
3126 }
3127 \f
3128
3129 /* Return Nonzero if block a is lexically nested within block b,
3130    or if a and b have the same pc range.
3131    Return zero otherwise. */
3132 int
3133 contained_in (struct block *a, struct block *b)
3134 {
3135   if (!a || !b)
3136     return 0;
3137   return BLOCK_START (a) >= BLOCK_START (b)
3138     && BLOCK_END (a) <= BLOCK_END (b);
3139 }
3140 \f
3141
3142 /* Helper routine for make_symbol_completion_list.  */
3143
3144 static int return_val_size;
3145 static int return_val_index;
3146 static char **return_val;
3147
3148 #define COMPLETION_LIST_ADD_SYMBOL(symbol, sym_text, len, text, word) \
3149   do { \
3150     if (SYMBOL_DEMANGLED_NAME (symbol) != NULL) \
3151       /* Put only the mangled name on the list.  */ \
3152       /* Advantage:  "b foo<TAB>" completes to "b foo(int, int)" */ \
3153       /* Disadvantage:  "b foo__i<TAB>" doesn't complete.  */ \
3154       completion_list_add_name \
3155         (SYMBOL_DEMANGLED_NAME (symbol), (sym_text), (len), (text), (word)); \
3156     else \
3157       completion_list_add_name \
3158         (SYMBOL_NAME (symbol), (sym_text), (len), (text), (word)); \
3159   } while (0)
3160
3161 /*  Test to see if the symbol specified by SYMNAME (which is already
3162    demangled for C++ symbols) matches SYM_TEXT in the first SYM_TEXT_LEN
3163    characters.  If so, add it to the current completion list. */
3164
3165 static void
3166 completion_list_add_name (char *symname, char *sym_text, int sym_text_len,
3167                           char *text, char *word)
3168 {
3169   int newsize;
3170   int i;
3171
3172   /* clip symbols that cannot match */
3173
3174   if (strncmp (symname, sym_text, sym_text_len) != 0)
3175     {
3176       return;
3177     }
3178
3179   /* We have a match for a completion, so add SYMNAME to the current list
3180      of matches. Note that the name is moved to freshly malloc'd space. */
3181
3182   {
3183     char *new;
3184     if (word == sym_text)
3185       {
3186         new = xmalloc (strlen (symname) + 5);
3187         strcpy (new, symname);
3188       }
3189     else if (word > sym_text)
3190       {
3191         /* Return some portion of symname.  */
3192         new = xmalloc (strlen (symname) + 5);
3193         strcpy (new, symname + (word - sym_text));
3194       }
3195     else
3196       {
3197         /* Return some of SYM_TEXT plus symname.  */
3198         new = xmalloc (strlen (symname) + (sym_text - word) + 5);
3199         strncpy (new, word, sym_text - word);
3200         new[sym_text - word] = '\0';
3201         strcat (new, symname);
3202       }
3203
3204     if (return_val_index + 3 > return_val_size)
3205       {
3206         newsize = (return_val_size *= 2) * sizeof (char *);
3207         return_val = (char **) xrealloc ((char *) return_val, newsize);
3208       }
3209     return_val[return_val_index++] = new;
3210     return_val[return_val_index] = NULL;
3211   }
3212 }
3213
3214 /* Return a NULL terminated array of all symbols (regardless of class)
3215    which begin by matching TEXT.  If the answer is no symbols, then
3216    the return value is an array which contains only a NULL pointer.
3217
3218    Problem: All of the symbols have to be copied because readline frees them.
3219    I'm not going to worry about this; hopefully there won't be that many.  */
3220
3221 char **
3222 make_symbol_completion_list (char *text, char *word)
3223 {
3224   register struct symbol *sym;
3225   register struct symtab *s;
3226   register struct partial_symtab *ps;
3227   register struct minimal_symbol *msymbol;
3228   register struct objfile *objfile;
3229   register struct block *b, *surrounding_static_block = 0;
3230   register int i, j;
3231   struct partial_symbol **psym;
3232   /* The symbol we are completing on.  Points in same buffer as text.  */
3233   char *sym_text;
3234   /* Length of sym_text.  */
3235   int sym_text_len;
3236
3237   /* Now look for the symbol we are supposed to complete on.
3238      FIXME: This should be language-specific.  */
3239   {
3240     char *p;
3241     char quote_found;
3242     char *quote_pos = NULL;
3243
3244     /* First see if this is a quoted string.  */
3245     quote_found = '\0';
3246     for (p = text; *p != '\0'; ++p)
3247       {
3248         if (quote_found != '\0')
3249           {
3250             if (*p == quote_found)
3251               /* Found close quote.  */
3252               quote_found = '\0';
3253             else if (*p == '\\' && p[1] == quote_found)
3254               /* A backslash followed by the quote character
3255                  doesn't end the string.  */
3256               ++p;
3257           }
3258         else if (*p == '\'' || *p == '"')
3259           {
3260             quote_found = *p;
3261             quote_pos = p;
3262           }
3263       }
3264     if (quote_found == '\'')
3265       /* A string within single quotes can be a symbol, so complete on it.  */
3266       sym_text = quote_pos + 1;
3267     else if (quote_found == '"')
3268       /* A double-quoted string is never a symbol, nor does it make sense
3269          to complete it any other way.  */
3270       {
3271         return_val = (char **) xmalloc (sizeof (char *));
3272         return_val[0] = NULL;
3273         return return_val;
3274       }
3275     else
3276       {
3277         /* It is not a quoted string.  Break it based on the characters
3278            which are in symbols.  */
3279         while (p > text)
3280           {
3281             if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
3282               --p;
3283             else
3284               break;
3285           }
3286         sym_text = p;
3287       }
3288   }
3289
3290   sym_text_len = strlen (sym_text);
3291
3292   return_val_size = 100;
3293   return_val_index = 0;
3294   return_val = (char **) xmalloc ((return_val_size + 1) * sizeof (char *));
3295   return_val[0] = NULL;
3296
3297   /* Look through the partial symtabs for all symbols which begin
3298      by matching SYM_TEXT.  Add each one that you find to the list.  */
3299
3300   ALL_PSYMTABS (objfile, ps)
3301   {
3302     /* If the psymtab's been read in we'll get it when we search
3303        through the blockvector.  */
3304     if (ps->readin)
3305       continue;
3306
3307     for (psym = objfile->global_psymbols.list + ps->globals_offset;
3308          psym < (objfile->global_psymbols.list + ps->globals_offset
3309                  + ps->n_global_syms);
3310          psym++)
3311       {
3312         /* If interrupted, then quit. */
3313         QUIT;
3314         COMPLETION_LIST_ADD_SYMBOL (*psym, sym_text, sym_text_len, text, word);
3315       }
3316
3317     for (psym = objfile->static_psymbols.list + ps->statics_offset;
3318          psym < (objfile->static_psymbols.list + ps->statics_offset
3319                  + ps->n_static_syms);
3320          psym++)
3321       {
3322         QUIT;
3323         COMPLETION_LIST_ADD_SYMBOL (*psym, sym_text, sym_text_len, text, word);
3324       }
3325   }
3326
3327   /* At this point scan through the misc symbol vectors and add each
3328      symbol you find to the list.  Eventually we want to ignore
3329      anything that isn't a text symbol (everything else will be
3330      handled by the psymtab code above).  */
3331
3332   ALL_MSYMBOLS (objfile, msymbol)
3333   {
3334     QUIT;
3335     COMPLETION_LIST_ADD_SYMBOL (msymbol, sym_text, sym_text_len, text, word);
3336   }
3337
3338   /* Search upwards from currently selected frame (so that we can
3339      complete on local vars.  */
3340
3341   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
3342     {
3343       if (!BLOCK_SUPERBLOCK (b))
3344         {
3345           surrounding_static_block = b;         /* For elmin of dups */
3346         }
3347
3348       /* Also catch fields of types defined in this places which match our
3349          text string.  Only complete on types visible from current context. */
3350
3351       ALL_BLOCK_SYMBOLS (b, i, sym)
3352         {
3353           COMPLETION_LIST_ADD_SYMBOL (sym, sym_text, sym_text_len, text, word);
3354           if (SYMBOL_CLASS (sym) == LOC_TYPEDEF)
3355             {
3356               struct type *t = SYMBOL_TYPE (sym);
3357               enum type_code c = TYPE_CODE (t);
3358
3359               if (c == TYPE_CODE_UNION || c == TYPE_CODE_STRUCT)
3360                 {
3361                   for (j = TYPE_N_BASECLASSES (t); j < TYPE_NFIELDS (t); j++)
3362                     {
3363                       if (TYPE_FIELD_NAME (t, j))
3364                         {
3365                           completion_list_add_name (TYPE_FIELD_NAME (t, j),
3366                                         sym_text, sym_text_len, text, word);
3367                         }
3368                     }
3369                 }
3370             }
3371         }
3372     }
3373
3374   /* Go through the symtabs and check the externs and statics for
3375      symbols which match.  */
3376
3377   ALL_SYMTABS (objfile, s)
3378   {
3379     QUIT;
3380     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
3381     ALL_BLOCK_SYMBOLS (b, i, sym)
3382       {
3383         COMPLETION_LIST_ADD_SYMBOL (sym, sym_text, sym_text_len, text, word);
3384       }
3385   }
3386
3387   ALL_SYMTABS (objfile, s)
3388   {
3389     QUIT;
3390     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
3391     /* Don't do this block twice.  */
3392     if (b == surrounding_static_block)
3393       continue;
3394     ALL_BLOCK_SYMBOLS (b, i, sym)
3395       {
3396         COMPLETION_LIST_ADD_SYMBOL (sym, sym_text, sym_text_len, text, word);
3397       }
3398   }
3399
3400   return (return_val);
3401 }
3402
3403 /* Like make_symbol_completion_list, but returns a list of symbols
3404    defined in a source file FILE.  */
3405
3406 char **
3407 make_file_symbol_completion_list (char *text, char *word, char *srcfile)
3408 {
3409   register struct symbol *sym;
3410   register struct symtab *s;
3411   register struct block *b;
3412   register int i;
3413   /* The symbol we are completing on.  Points in same buffer as text.  */
3414   char *sym_text;
3415   /* Length of sym_text.  */
3416   int sym_text_len;
3417
3418   /* Now look for the symbol we are supposed to complete on.
3419      FIXME: This should be language-specific.  */
3420   {
3421     char *p;
3422     char quote_found;
3423     char *quote_pos = NULL;
3424
3425     /* First see if this is a quoted string.  */
3426     quote_found = '\0';
3427     for (p = text; *p != '\0'; ++p)
3428       {
3429         if (quote_found != '\0')
3430           {
3431             if (*p == quote_found)
3432               /* Found close quote.  */
3433               quote_found = '\0';
3434             else if (*p == '\\' && p[1] == quote_found)
3435               /* A backslash followed by the quote character
3436                  doesn't end the string.  */
3437               ++p;
3438           }
3439         else if (*p == '\'' || *p == '"')
3440           {
3441             quote_found = *p;
3442             quote_pos = p;
3443           }
3444       }
3445     if (quote_found == '\'')
3446       /* A string within single quotes can be a symbol, so complete on it.  */
3447       sym_text = quote_pos + 1;
3448     else if (quote_found == '"')
3449       /* A double-quoted string is never a symbol, nor does it make sense
3450          to complete it any other way.  */
3451       {
3452         return_val = (char **) xmalloc (sizeof (char *));
3453         return_val[0] = NULL;
3454         return return_val;
3455       }
3456     else
3457       {
3458         /* It is not a quoted string.  Break it based on the characters
3459            which are in symbols.  */
3460         while (p > text)
3461           {
3462             if (isalnum (p[-1]) || p[-1] == '_' || p[-1] == '\0')
3463               --p;
3464             else
3465               break;
3466           }
3467         sym_text = p;
3468       }
3469   }
3470
3471   sym_text_len = strlen (sym_text);
3472
3473   return_val_size = 10;
3474   return_val_index = 0;
3475   return_val = (char **) xmalloc ((return_val_size + 1) * sizeof (char *));
3476   return_val[0] = NULL;
3477
3478   /* Find the symtab for SRCFILE (this loads it if it was not yet read
3479      in).  */
3480   s = lookup_symtab (srcfile);
3481   if (s == NULL)
3482     {
3483       /* Maybe they typed the file with leading directories, while the
3484          symbol tables record only its basename.  */
3485       const char *tail = lbasename (srcfile);
3486
3487       if (tail > srcfile)
3488         s = lookup_symtab (tail);
3489     }
3490
3491   /* If we have no symtab for that file, return an empty list.  */
3492   if (s == NULL)
3493     return (return_val);
3494
3495   /* Go through this symtab and check the externs and statics for
3496      symbols which match.  */
3497
3498   b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
3499   ALL_BLOCK_SYMBOLS (b, i, sym)
3500     {
3501       COMPLETION_LIST_ADD_SYMBOL (sym, sym_text, sym_text_len, text, word);
3502     }
3503
3504   b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
3505   ALL_BLOCK_SYMBOLS (b, i, sym)
3506     {
3507       COMPLETION_LIST_ADD_SYMBOL (sym, sym_text, sym_text_len, text, word);
3508     }
3509
3510   return (return_val);
3511 }
3512
3513 /* A helper function for make_source_files_completion_list.  It adds
3514    another file name to a list of possible completions, growing the
3515    list as necessary.  */
3516
3517 static void
3518 add_filename_to_list (const char *fname, char *text, char *word,
3519                       char ***list, int *list_used, int *list_alloced)
3520 {
3521   char *new;
3522   size_t fnlen = strlen (fname);
3523
3524   if (*list_used + 1 >= *list_alloced)
3525     {
3526       *list_alloced *= 2;
3527       *list = (char **) xrealloc ((char *) *list,
3528                                   *list_alloced * sizeof (char *));
3529     }
3530
3531   if (word == text)
3532     {
3533       /* Return exactly fname.  */
3534       new = xmalloc (fnlen + 5);
3535       strcpy (new, fname);
3536     }
3537   else if (word > text)
3538     {
3539       /* Return some portion of fname.  */
3540       new = xmalloc (fnlen + 5);
3541       strcpy (new, fname + (word - text));
3542     }
3543   else
3544     {
3545       /* Return some of TEXT plus fname.  */
3546       new = xmalloc (fnlen + (text - word) + 5);
3547       strncpy (new, word, text - word);
3548       new[text - word] = '\0';
3549       strcat (new, fname);
3550     }
3551   (*list)[*list_used] = new;
3552   (*list)[++*list_used] = NULL;
3553 }
3554
3555 static int
3556 not_interesting_fname (const char *fname)
3557 {
3558   static const char *illegal_aliens[] = {
3559     "_globals_",        /* inserted by coff_symtab_read */
3560     NULL
3561   };
3562   int i;
3563
3564   for (i = 0; illegal_aliens[i]; i++)
3565     {
3566       if (strcmp (fname, illegal_aliens[i]) == 0)
3567         return 1;
3568     }
3569   return 0;
3570 }
3571
3572 /* Return a NULL terminated array of all source files whose names
3573    begin with matching TEXT.  The file names are looked up in the
3574    symbol tables of this program.  If the answer is no matchess, then
3575    the return value is an array which contains only a NULL pointer.  */
3576
3577 char **
3578 make_source_files_completion_list (char *text, char *word)
3579 {
3580   register struct symtab *s;
3581   register struct partial_symtab *ps;
3582   register struct objfile *objfile;
3583   int first = 1;
3584   int list_alloced = 1;
3585   int list_used = 0;
3586   size_t text_len = strlen (text);
3587   char **list = (char **) xmalloc (list_alloced * sizeof (char *));
3588   const char *base_name;
3589
3590   list[0] = NULL;
3591
3592   if (!have_full_symbols () && !have_partial_symbols ())
3593     return list;
3594
3595   ALL_SYMTABS (objfile, s)
3596     {
3597       if (not_interesting_fname (s->filename))
3598         continue;
3599       if (!filename_seen (s->filename, 1, &first)
3600 #if HAVE_DOS_BASED_FILE_SYSTEM
3601           && strncasecmp (s->filename, text, text_len) == 0
3602 #else
3603           && strncmp (s->filename, text, text_len) == 0
3604 #endif
3605           )
3606         {
3607           /* This file matches for a completion; add it to the current
3608              list of matches.  */
3609           add_filename_to_list (s->filename, text, word,
3610                                 &list, &list_used, &list_alloced);
3611         }
3612       else
3613         {
3614           /* NOTE: We allow the user to type a base name when the
3615              debug info records leading directories, but not the other
3616              way around.  This is what subroutines of breakpoint
3617              command do when they parse file names.  */
3618           base_name = lbasename (s->filename);
3619           if (base_name != s->filename
3620               && !filename_seen (base_name, 1, &first)
3621 #if HAVE_DOS_BASED_FILE_SYSTEM
3622               && strncasecmp (base_name, text, text_len) == 0
3623 #else
3624               && strncmp (base_name, text, text_len) == 0
3625 #endif
3626               )
3627             add_filename_to_list (base_name, text, word,
3628                                   &list, &list_used, &list_alloced);
3629         }
3630     }
3631
3632   ALL_PSYMTABS (objfile, ps)
3633     {
3634       if (not_interesting_fname (ps->filename))
3635         continue;
3636       if (!ps->readin)
3637         {
3638           if (!filename_seen (ps->filename, 1, &first)
3639 #if HAVE_DOS_BASED_FILE_SYSTEM
3640               && strncasecmp (ps->filename, text, text_len) == 0
3641 #else
3642               && strncmp (ps->filename, text, text_len) == 0
3643 #endif
3644               )
3645             {
3646               /* This file matches for a completion; add it to the
3647                  current list of matches.  */
3648               add_filename_to_list (ps->filename, text, word,
3649                                     &list, &list_used, &list_alloced);
3650
3651             }
3652           else
3653             {
3654               base_name = lbasename (ps->filename);
3655               if (base_name != ps->filename
3656                   && !filename_seen (base_name, 1, &first)
3657 #if HAVE_DOS_BASED_FILE_SYSTEM
3658                   && strncasecmp (base_name, text, text_len) == 0
3659 #else
3660                   && strncmp (base_name, text, text_len) == 0
3661 #endif
3662                   )
3663                 add_filename_to_list (base_name, text, word,
3664                                       &list, &list_used, &list_alloced);
3665             }
3666         }
3667     }
3668
3669   return list;
3670 }
3671
3672 /* Determine if PC is in the prologue of a function.  The prologue is the area
3673    between the first instruction of a function, and the first executable line.
3674    Returns 1 if PC *might* be in prologue, 0 if definately *not* in prologue.
3675
3676    If non-zero, func_start is where we think the prologue starts, possibly
3677    by previous examination of symbol table information.
3678  */
3679
3680 int
3681 in_prologue (CORE_ADDR pc, CORE_ADDR func_start)
3682 {
3683   struct symtab_and_line sal;
3684   CORE_ADDR func_addr, func_end;
3685
3686   /* We have several sources of information we can consult to figure
3687      this out.
3688      - Compilers usually emit line number info that marks the prologue
3689        as its own "source line".  So the ending address of that "line"
3690        is the end of the prologue.  If available, this is the most
3691        reliable method.
3692      - The minimal symbols and partial symbols, which can usually tell
3693        us the starting and ending addresses of a function.
3694      - If we know the function's start address, we can call the
3695        architecture-defined SKIP_PROLOGUE function to analyze the
3696        instruction stream and guess where the prologue ends.
3697      - Our `func_start' argument; if non-zero, this is the caller's
3698        best guess as to the function's entry point.  At the time of
3699        this writing, handle_inferior_event doesn't get this right, so
3700        it should be our last resort.  */
3701
3702   /* Consult the partial symbol table, to find which function
3703      the PC is in.  */
3704   if (! find_pc_partial_function (pc, NULL, &func_addr, &func_end))
3705     {
3706       CORE_ADDR prologue_end;
3707
3708       /* We don't even have minsym information, so fall back to using
3709          func_start, if given.  */
3710       if (! func_start)
3711         return 1;               /* We *might* be in a prologue.  */
3712
3713       prologue_end = SKIP_PROLOGUE (func_start);
3714
3715       return func_start <= pc && pc < prologue_end;
3716     }
3717
3718   /* If we have line number information for the function, that's
3719      usually pretty reliable.  */
3720   sal = find_pc_line (func_addr, 0);
3721
3722   /* Now sal describes the source line at the function's entry point,
3723      which (by convention) is the prologue.  The end of that "line",
3724      sal.end, is the end of the prologue.
3725
3726      Note that, for functions whose source code is all on a single
3727      line, the line number information doesn't always end up this way.
3728      So we must verify that our purported end-of-prologue address is
3729      *within* the function, not at its start or end.  */
3730   if (sal.line == 0
3731       || sal.end <= func_addr
3732       || func_end <= sal.end)
3733     {
3734       /* We don't have any good line number info, so use the minsym
3735          information, together with the architecture-specific prologue
3736          scanning code.  */
3737       CORE_ADDR prologue_end = SKIP_PROLOGUE (func_addr);
3738
3739       return func_addr <= pc && pc < prologue_end;
3740     }
3741
3742   /* We have line number info, and it looks good.  */
3743   return func_addr <= pc && pc < sal.end;
3744 }
3745
3746
3747 /* Begin overload resolution functions */
3748
3749 static char *
3750 remove_params (const char *demangled_name)
3751 {
3752   const char *argp;
3753   char *new_name;
3754   int depth;
3755
3756   if (demangled_name == NULL)
3757     return NULL;
3758
3759   /* First find the end of the arg list.  */
3760   argp = strrchr (demangled_name, ')');
3761   if (argp == NULL)
3762     return NULL;
3763
3764   /* Back up to the beginning.  */
3765   depth = 1;
3766
3767   while (argp-- > demangled_name)
3768     {
3769       if (*argp == ')')
3770         depth ++;
3771       else if (*argp == '(')
3772         {
3773           depth --;
3774
3775           if (depth == 0)
3776             break;
3777         }
3778     }
3779   if (depth != 0)
3780     internal_error (__FILE__, __LINE__,
3781                     "bad demangled name %s\n", demangled_name);
3782   while (argp[-1] == ' ' && argp > demangled_name)
3783     argp --;
3784
3785   new_name = xmalloc (argp - demangled_name + 1);
3786   memcpy (new_name, demangled_name, argp - demangled_name);
3787   new_name[argp - demangled_name] = '\0';
3788   return new_name;
3789 }
3790
3791 /* Helper routine for make_symbol_completion_list.  */
3792
3793 static int sym_return_val_size;
3794 static int sym_return_val_index;
3795 static struct symbol **sym_return_val;
3796
3797 /*  Test to see if the symbol specified by SYMNAME (which is already
3798    demangled for C++ symbols) matches SYM_TEXT in the first SYM_TEXT_LEN
3799    characters.  If so, add it to the current completion list. */
3800
3801 static void
3802 overload_list_add_symbol (struct symbol *sym, char *oload_name)
3803 {
3804   int newsize;
3805   int i;
3806   char *sym_name;
3807
3808   /* If there is no type information, we can't do anything, so skip */
3809   if (SYMBOL_TYPE (sym) == NULL)
3810     return;
3811
3812   /* skip any symbols that we've already considered. */
3813   for (i = 0; i < sym_return_val_index; ++i)
3814     if (!strcmp (SYMBOL_NAME (sym), SYMBOL_NAME (sym_return_val[i])))
3815       return;
3816
3817   /* Get the demangled name without parameters */
3818   sym_name = remove_params (SYMBOL_DEMANGLED_NAME (sym));
3819   if (!sym_name)
3820     return;
3821
3822   /* skip symbols that cannot match */
3823   if (strcmp (sym_name, oload_name) != 0)
3824     {
3825       xfree (sym_name);
3826       return;
3827     }
3828
3829   xfree (sym_name);
3830
3831   /* We have a match for an overload instance, so add SYM to the current list
3832    * of overload instances */
3833   if (sym_return_val_index + 3 > sym_return_val_size)
3834     {
3835       newsize = (sym_return_val_size *= 2) * sizeof (struct symbol *);
3836       sym_return_val = (struct symbol **) xrealloc ((char *) sym_return_val, newsize);
3837     }
3838   sym_return_val[sym_return_val_index++] = sym;
3839   sym_return_val[sym_return_val_index] = NULL;
3840 }
3841
3842 /* Return a null-terminated list of pointers to function symbols that
3843  * match name of the supplied symbol FSYM.
3844  * This is used in finding all overloaded instances of a function name.
3845  * This has been modified from make_symbol_completion_list.  */
3846
3847
3848 struct symbol **
3849 make_symbol_overload_list (struct symbol *fsym)
3850 {
3851   register struct symbol *sym;
3852   register struct symtab *s;
3853   register struct partial_symtab *ps;
3854   register struct objfile *objfile;
3855   register struct block *b, *surrounding_static_block = 0;
3856   register int i;
3857   /* The name we are completing on. */
3858   char *oload_name = NULL;
3859   /* Length of name.  */
3860   int oload_name_len = 0;
3861
3862   /* Look for the symbol we are supposed to complete on.  */
3863
3864   oload_name = remove_params (SYMBOL_DEMANGLED_NAME (fsym));
3865   if (!oload_name)
3866     {
3867       sym_return_val_size = 1;
3868       sym_return_val = (struct symbol **) xmalloc (2 * sizeof (struct symbol *));
3869       sym_return_val[0] = fsym;
3870       sym_return_val[1] = NULL;
3871
3872       return sym_return_val;
3873     }
3874   oload_name_len = strlen (oload_name);
3875
3876   sym_return_val_size = 100;
3877   sym_return_val_index = 0;
3878   sym_return_val = (struct symbol **) xmalloc ((sym_return_val_size + 1) * sizeof (struct symbol *));
3879   sym_return_val[0] = NULL;
3880
3881   /* Look through the partial symtabs for all symbols which begin
3882      by matching OLOAD_NAME.  Make sure we read that symbol table in. */
3883
3884   ALL_PSYMTABS (objfile, ps)
3885   {
3886     struct partial_symbol **psym;
3887
3888     /* If the psymtab's been read in we'll get it when we search
3889        through the blockvector.  */
3890     if (ps->readin)
3891       continue;
3892
3893     for (psym = objfile->global_psymbols.list + ps->globals_offset;
3894          psym < (objfile->global_psymbols.list + ps->globals_offset
3895                  + ps->n_global_syms);
3896          psym++)
3897       {
3898         /* If interrupted, then quit. */
3899         QUIT;
3900         /* This will cause the symbol table to be read if it has not yet been */
3901         s = PSYMTAB_TO_SYMTAB (ps);
3902       }
3903
3904     for (psym = objfile->static_psymbols.list + ps->statics_offset;
3905          psym < (objfile->static_psymbols.list + ps->statics_offset
3906                  + ps->n_static_syms);
3907          psym++)
3908       {
3909         QUIT;
3910         /* This will cause the symbol table to be read if it has not yet been */
3911         s = PSYMTAB_TO_SYMTAB (ps);
3912       }
3913   }
3914
3915   /* Search upwards from currently selected frame (so that we can
3916      complete on local vars.  */
3917
3918   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
3919     {
3920       if (!BLOCK_SUPERBLOCK (b))
3921         {
3922           surrounding_static_block = b;         /* For elimination of dups */
3923         }
3924
3925       /* Also catch fields of types defined in this places which match our
3926          text string.  Only complete on types visible from current context. */
3927
3928       ALL_BLOCK_SYMBOLS (b, i, sym)
3929         {
3930           overload_list_add_symbol (sym, oload_name);
3931         }
3932     }
3933
3934   /* Go through the symtabs and check the externs and statics for
3935      symbols which match.  */
3936
3937   ALL_SYMTABS (objfile, s)
3938   {
3939     QUIT;
3940     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
3941     ALL_BLOCK_SYMBOLS (b, i, sym)
3942       {
3943         overload_list_add_symbol (sym, oload_name);
3944       }
3945   }
3946
3947   ALL_SYMTABS (objfile, s)
3948   {
3949     QUIT;
3950     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
3951     /* Don't do this block twice.  */
3952     if (b == surrounding_static_block)
3953       continue;
3954     ALL_BLOCK_SYMBOLS (b, i, sym)
3955       {
3956         overload_list_add_symbol (sym, oload_name);
3957       }
3958   }
3959
3960   xfree (oload_name);
3961
3962   return (sym_return_val);
3963 }
3964
3965 /* End of overload resolution functions */
3966 \f
3967 struct symtabs_and_lines
3968 decode_line_spec (char *string, int funfirstline)
3969 {
3970   struct symtabs_and_lines sals;
3971   struct symtab_and_line cursal;
3972   
3973   if (string == 0)
3974     error ("Empty line specification.");
3975     
3976   /* We use whatever is set as the current source line. We do not try
3977      and get a default  or it will recursively call us! */  
3978   cursal = get_current_source_symtab_and_line ();
3979   
3980   sals = decode_line_1 (&string, funfirstline,
3981                         cursal.symtab, cursal.line,
3982                         (char ***) NULL);
3983
3984   if (*string)
3985     error ("Junk at end of line specification: %s", string);
3986   return sals;
3987 }
3988
3989 /* Track MAIN */
3990 static char *name_of_main;
3991
3992 void
3993 set_main_name (const char *name)
3994 {
3995   if (name_of_main != NULL)
3996     {
3997       xfree (name_of_main);
3998       name_of_main = NULL;
3999     }
4000   if (name != NULL)
4001     {
4002       name_of_main = xstrdup (name);
4003     }
4004 }
4005
4006 char *
4007 main_name (void)
4008 {
4009   if (name_of_main != NULL)
4010     return name_of_main;
4011   else
4012     return "main";
4013 }
4014
4015
4016 void
4017 _initialize_symtab (void)
4018 {
4019   add_info ("variables", variables_info,
4020          "All global and static variable names, or those matching REGEXP.");
4021   if (dbx_commands)
4022     add_com ("whereis", class_info, variables_info,
4023          "All global and static variable names, or those matching REGEXP.");
4024
4025   add_info ("functions", functions_info,
4026             "All function names, or those matching REGEXP.");
4027
4028   
4029   /* FIXME:  This command has at least the following problems:
4030      1.  It prints builtin types (in a very strange and confusing fashion).
4031      2.  It doesn't print right, e.g. with
4032      typedef struct foo *FOO
4033      type_print prints "FOO" when we want to make it (in this situation)
4034      print "struct foo *".
4035      I also think "ptype" or "whatis" is more likely to be useful (but if
4036      there is much disagreement "info types" can be fixed).  */
4037   add_info ("types", types_info,
4038             "All type names, or those matching REGEXP.");
4039
4040 #if 0
4041   add_info ("methods", methods_info,
4042             "All method names, or those matching REGEXP::REGEXP.\n\
4043 If the class qualifier is omitted, it is assumed to be the current scope.\n\
4044 If the first REGEXP is omitted, then all methods matching the second REGEXP\n\
4045 are listed.");
4046 #endif
4047   add_info ("sources", sources_info,
4048             "Source files in the program.");
4049
4050   add_com ("rbreak", class_breakpoint, rbreak_command,
4051            "Set a breakpoint for all functions matching REGEXP.");
4052
4053   if (xdb_commands)
4054     {
4055       add_com ("lf", class_info, sources_info, "Source files in the program");
4056       add_com ("lg", class_info, variables_info,
4057          "All global and static variable names, or those matching REGEXP.");
4058     }
4059
4060   /* Initialize the one built-in type that isn't language dependent... */
4061   builtin_type_error = init_type (TYPE_CODE_ERROR, 0, 0,
4062                                   "<unknown type>", (struct objfile *) NULL);
4063 }