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