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