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