gdb:
[external/binutils.git] / gdb / linespec.c
1 /* Parser for linespec for the GNU debugger, GDB.
2
3    Copyright (C) 1986-2005, 2007-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "symtab.h"
22 #include "frame.h"
23 #include "command.h"
24 #include "symfile.h"
25 #include "objfiles.h"
26 #include "source.h"
27 #include "demangle.h"
28 #include "value.h"
29 #include "completer.h"
30 #include "cp-abi.h"
31 #include "cp-support.h"
32 #include "parser-defs.h"
33 #include "block.h"
34 #include "objc-lang.h"
35 #include "linespec.h"
36 #include "exceptions.h"
37 #include "language.h"
38 #include "interps.h"
39 #include "mi/mi-cmds.h"
40 #include "target.h"
41 #include "arch-utils.h"
42 #include <ctype.h>
43 #include "cli/cli-utils.h"
44 #include "filenames.h"
45 #include "ada-lang.h"
46
47 typedef struct symtab *symtab_p;
48 DEF_VEC_P (symtab_p);
49
50 typedef struct symbol *symbolp;
51 DEF_VEC_P (symbolp);
52
53 typedef struct type *typep;
54 DEF_VEC_P (typep);
55
56 /* An address entry is used to ensure that any given location is only
57    added to the result a single time.  It holds an address and the
58    program space from which the address came.  */
59
60 struct address_entry
61 {
62   struct program_space *pspace;
63   CORE_ADDR addr;
64 };
65
66 /* An instance of this is used to keep all state while linespec
67    operates.  This instance is passed around as a 'this' pointer to
68    the various implementation methods.  */
69
70 struct linespec_state
71 {
72   /* The program space as seen when the module was entered.  */
73   struct program_space *program_space;
74
75   /* The default symtab to use, if no other symtab is specified.  */
76   struct symtab *default_symtab;
77
78   /* The default line to use.  */
79   int default_line;
80
81   /* If the linespec started with "FILE:", this holds all the matching
82      symtabs.  Otherwise, it will hold a single NULL entry, meaning
83      that the default symtab should be used.  */
84   VEC (symtab_p) *file_symtabs;
85
86   /* If the linespec started with "FILE:", this holds an xmalloc'd
87      copy of "FILE".  */
88   char *user_filename;
89
90   /* If the linespec is "FUNCTION:LABEL", this holds an xmalloc'd copy
91      of "FUNCTION".  */
92   char *user_function;
93
94   /* The 'funfirstline' value that was passed in to decode_line_1 or
95      decode_line_full.  */
96   int funfirstline;
97
98   /* Nonzero if we are running in 'list' mode; see decode_line_list.  */
99   int list_mode;
100
101   /* The 'canonical' value passed to decode_line_full, or NULL.  */
102   struct linespec_result *canonical;
103
104   /* Canonical strings that mirror the symtabs_and_lines result.  */
105   char **canonical_names;
106
107   /* This is a set of address_entry objects which is used to prevent
108      duplicate symbols from being entered into the result.  */
109   htab_t addr_set;
110 };
111
112 /* This is a helper object that is used when collecting symbols into a
113    result.  */
114
115 struct collect_info
116 {
117   /* The linespec object in use.  */
118   struct linespec_state *state;
119
120   /* The result being accumulated.  */
121   struct symtabs_and_lines result;
122 };
123
124 /* Prototypes for local functions.  */
125
126 static void initialize_defaults (struct symtab **default_symtab,
127                                  int *default_line);
128
129 static struct symtabs_and_lines decode_indirect (struct linespec_state *self,
130                                                  char **argptr);
131
132 static char *locate_first_half (char **argptr, int *is_quote_enclosed);
133
134 static struct symtabs_and_lines decode_objc (struct linespec_state *self,
135                                              char **argptr);
136
137 static struct symtabs_and_lines decode_compound (struct linespec_state *self,
138                                                  char **argptr,
139                                                  char *saved_arg,
140                                                  char *p);
141
142 static VEC (symbolp) *lookup_prefix_sym (char **argptr, char *p,
143                                          VEC (symtab_p) *,
144                                          char **);
145
146 static struct symtabs_and_lines find_method (struct linespec_state *self,
147                                              char *saved_arg,
148                                              char *copy,
149                                              const char *class_name,
150                                              VEC (symbolp) *sym_classes);
151
152 static void cplusplus_error (const char *name, const char *fmt, ...)
153      ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (2, 3);
154
155 static char *find_toplevel_char (char *s, char c);
156
157 static int is_objc_method_format (const char *s);
158
159 static VEC (symtab_p) *symtabs_from_filename (char **argptr,
160                                               char *p, int is_quote_enclosed,
161                                               char **user_filename);
162
163 static VEC (symbolp) *find_function_symbols (char **argptr, char *p,
164                                              int is_quote_enclosed,
165                                              char **user_function);
166
167 static struct symtabs_and_lines decode_all_digits (struct linespec_state *self,
168                                                    char **argptr,
169                                                    char *q);
170
171 static struct symtabs_and_lines decode_dollar (struct linespec_state *self,
172                                                char *copy);
173
174 static int decode_label (struct linespec_state *self,
175                          VEC (symbolp) *function_symbols,
176                          char *copy,
177                          struct symtabs_and_lines *result);
178
179 static struct symtabs_and_lines decode_variable (struct linespec_state *self,
180                                                  char *copy);
181
182 static int symbol_to_sal (struct symtab_and_line *result,
183                           int funfirstline, struct symbol *sym);
184
185 static void add_matching_symbols_to_info (const char *name,
186                                           struct collect_info *info,
187                                           struct program_space *pspace);
188
189 static void add_all_symbol_names_from_pspace (struct collect_info *info,
190                                               struct program_space *pspace,
191                                               VEC (const_char_ptr) *names);
192
193 /* Helper functions.  */
194
195 /* Add SAL to SALS.  */
196
197 static void
198 add_sal_to_sals_basic (struct symtabs_and_lines *sals,
199                        struct symtab_and_line *sal)
200 {
201   ++sals->nelts;
202   sals->sals = xrealloc (sals->sals, sals->nelts * sizeof (sals->sals[0]));
203   sals->sals[sals->nelts - 1] = *sal;
204 }
205
206 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
207    the new sal, if needed.  If not NULL, SYMNAME is the name of the
208    symbol to use when constructing the new canonical name.  */
209
210 static void
211 add_sal_to_sals (struct linespec_state *self,
212                  struct symtabs_and_lines *sals,
213                  struct symtab_and_line *sal,
214                  const char *symname)
215 {
216   add_sal_to_sals_basic (sals, sal);
217
218   if (self->canonical)
219     {
220       char *canonical_name = NULL;
221
222       self->canonical_names = xrealloc (self->canonical_names,
223                                         sals->nelts * sizeof (char *));
224       if (sal->symtab && sal->symtab->filename)
225         {
226           char *filename = sal->symtab->filename;
227
228           /* Note that the filter doesn't have to be a valid linespec
229              input.  We only apply the ":LINE" treatment to Ada for
230              the time being.  */
231           if (symname != NULL && sal->line != 0
232               && current_language->la_language == language_ada)
233             canonical_name = xstrprintf ("%s:%s:%d", filename, symname,
234                                          sal->line);
235           else if (symname != NULL)
236             canonical_name = xstrprintf ("%s:%s", filename, symname);
237           else
238             canonical_name = xstrprintf ("%s:%d", filename, sal->line);
239         }
240
241       self->canonical_names[sals->nelts - 1] = canonical_name;
242     }
243 }
244
245 /* A hash function for address_entry.  */
246
247 static hashval_t
248 hash_address_entry (const void *p)
249 {
250   const struct address_entry *aep = p;
251   hashval_t hash;
252
253   hash = iterative_hash_object (aep->pspace, 0);
254   return iterative_hash_object (aep->addr, hash);
255 }
256
257 /* An equality function for address_entry.  */
258
259 static int
260 eq_address_entry (const void *a, const void *b)
261 {
262   const struct address_entry *aea = a;
263   const struct address_entry *aeb = b;
264
265   return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
266 }
267
268 /* Check whether the address, represented by PSPACE and ADDR, is
269    already in the set.  If so, return 0.  Otherwise, add it and return
270    1.  */
271
272 static int
273 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
274 {
275   struct address_entry e, *p;
276   void **slot;
277
278   e.pspace = pspace;
279   e.addr = addr;
280   slot = htab_find_slot (set, &e, INSERT);
281   if (*slot)
282     return 0;
283
284   p = XNEW (struct address_entry);
285   memcpy (p, &e, sizeof (struct address_entry));
286   *slot = p;
287
288   return 1;
289 }
290
291 /* Issue a helpful hint on using the command completion feature on
292    single quoted demangled C++ symbols as part of the completion
293    error.  */
294
295 static void
296 cplusplus_error (const char *name, const char *fmt, ...)
297 {
298   struct ui_file *tmp_stream;
299   char *message;
300
301   tmp_stream = mem_fileopen ();
302   make_cleanup_ui_file_delete (tmp_stream);
303
304   {
305     va_list args;
306
307     va_start (args, fmt);
308     vfprintf_unfiltered (tmp_stream, fmt, args);
309     va_end (args);
310   }
311
312   while (*name == '\'')
313     name++;
314   fprintf_unfiltered (tmp_stream,
315                       ("Hint: try '%s<TAB> or '%s<ESC-?>\n"
316                        "(Note leading single quote.)"),
317                       name, name);
318
319   message = ui_file_xstrdup (tmp_stream, NULL);
320   make_cleanup (xfree, message);
321   throw_error (NOT_FOUND_ERROR, "%s", message);
322 }
323
324 /* A callback function and the additional data to call it with.  */
325
326 struct symbol_and_data_callback
327 {
328   /* The callback to use.  */
329   symbol_found_callback_ftype *callback;
330
331   /* Data to be passed to the callback.  */
332   void *data;
333 };
334
335 /* A helper for iterate_over_all_matching_symtabs that is used to
336    restrict calls to another callback to symbols representing inline
337    symbols only.  */
338
339 static int
340 iterate_inline_only (struct symbol *sym, void *d)
341 {
342   if (SYMBOL_INLINED (sym))
343     {
344       struct symbol_and_data_callback *cad = d;
345
346       return cad->callback (sym, cad->data);
347     }
348   return 1; /* Continue iterating.  */
349 }
350
351 /* Some data for the expand_symtabs_matching callback.  */
352
353 struct symbol_matcher_data
354 {
355   /* The lookup name against which symbol name should be compared.  */
356   const char *lookup_name;
357
358   /* The routine to be used for comparison.  */
359   symbol_name_cmp_ftype symbol_name_cmp;
360 };
361
362 /* A helper for iterate_over_all_matching_symtabs that is passed as a
363    callback to the expand_symtabs_matching method.  */
364
365 static int
366 iterate_name_matcher (const char *name, void *d)
367 {
368   const struct symbol_matcher_data *data = d;
369
370   if (data->symbol_name_cmp (name, data->lookup_name) == 0)
371     return 1; /* Expand this symbol's symbol table.  */
372   return 0; /* Skip this symbol.  */
373 }
374
375 /* A helper that walks over all matching symtabs in all objfiles and
376    calls CALLBACK for each symbol matching NAME.  If SEARCH_PSPACE is
377    not NULL, then the search is restricted to just that program
378    space.  If INCLUDE_INLINE is nonzero then symbols representing
379    inlined instances of functions will be included in the result.  */
380
381 static void
382 iterate_over_all_matching_symtabs (const char *name,
383                                    const domain_enum domain,
384                                    symbol_found_callback_ftype *callback,
385                                    void *data,
386                                    struct program_space *search_pspace,
387                                    int include_inline)
388 {
389   struct objfile *objfile;
390   struct program_space *pspace;
391   struct symbol_matcher_data matcher_data;
392
393   matcher_data.lookup_name = name;
394   matcher_data.symbol_name_cmp =
395     current_language->la_get_symbol_name_cmp != NULL
396     ? current_language->la_get_symbol_name_cmp (name)
397     : strcmp_iw;
398
399   ALL_PSPACES (pspace)
400   {
401     if (search_pspace != NULL && search_pspace != pspace)
402       continue;
403     if (pspace->executing_startup)
404       continue;
405
406     set_current_program_space (pspace);
407
408     ALL_OBJFILES (objfile)
409     {
410       struct symtab *symtab;
411
412       if (objfile->sf)
413         objfile->sf->qf->expand_symtabs_matching (objfile, NULL,
414                                                   iterate_name_matcher,
415                                                   ALL_DOMAIN,
416                                                   &matcher_data);
417
418       ALL_OBJFILE_SYMTABS (objfile, symtab)
419         {
420           if (symtab->primary)
421             {
422               struct block *block;
423
424               block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), STATIC_BLOCK);
425               LA_ITERATE_OVER_SYMBOLS (block, name, domain, callback, data);
426
427               if (include_inline)
428                 {
429                   struct symbol_and_data_callback cad = { callback, data };
430                   int i;
431
432                   for (i = FIRST_LOCAL_BLOCK;
433                        i < BLOCKVECTOR_NBLOCKS (BLOCKVECTOR (symtab)); i++)
434                     {
435                       block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), i);
436                       LA_ITERATE_OVER_SYMBOLS (block, name, domain,
437                                                iterate_inline_only, &cad);
438                     }
439                 }
440             }
441         }
442     }
443   }
444 }
445
446 /* Returns the block to be used for symbol searches for the given SYMTAB,
447    which may be NULL.  */
448
449 static struct block *
450 get_search_block (struct symtab *symtab)
451 {
452   struct block *block;
453
454   if (symtab != NULL)
455     block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), STATIC_BLOCK);
456   else
457     {
458       enum language save_language;
459
460       /* get_selected_block can change the current language when there is
461          no selected frame yet.  */
462       save_language = current_language->la_language;
463       block = get_selected_block (0);
464       set_language (save_language);
465     }
466
467   return block;
468 }
469
470 /* A helper for find_method.  This finds all methods in type T which
471    match NAME.  It adds resulting symbol names to RESULT_NAMES, and
472    adds T's direct superclasses to SUPERCLASSES.  */
473
474 static void
475 find_methods (struct type *t, const char *name,
476               VEC (const_char_ptr) **result_names,
477               VEC (typep) **superclasses)
478 {
479   int i1 = 0;
480   int ibase;
481   const char *class_name = type_name_no_tag (t);
482
483   /* Ignore this class if it doesn't have a name.  This is ugly, but
484      unless we figure out how to get the physname without the name of
485      the class, then the loop can't do any good.  */
486   if (class_name)
487     {
488       int method_counter;
489       int name_len = strlen (name);
490
491       CHECK_TYPEDEF (t);
492
493       /* Loop over each method name.  At this level, all overloads of a name
494          are counted as a single name.  There is an inner loop which loops over
495          each overload.  */
496
497       for (method_counter = TYPE_NFN_FIELDS (t) - 1;
498            method_counter >= 0;
499            --method_counter)
500         {
501           const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
502           char dem_opname[64];
503
504           if (strncmp (method_name, "__", 2) == 0 ||
505               strncmp (method_name, "op", 2) == 0 ||
506               strncmp (method_name, "type", 4) == 0)
507             {
508               if (cplus_demangle_opname (method_name, dem_opname, DMGL_ANSI))
509                 method_name = dem_opname;
510               else if (cplus_demangle_opname (method_name, dem_opname, 0))
511                 method_name = dem_opname;
512             }
513
514           if (strcmp_iw (method_name, name) == 0)
515             {
516               int field_counter;
517
518               for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
519                                     - 1);
520                    field_counter >= 0;
521                    --field_counter)
522                 {
523                   struct fn_field *f;
524                   const char *phys_name;
525
526                   f = TYPE_FN_FIELDLIST1 (t, method_counter);
527                   if (TYPE_FN_FIELD_STUB (f, field_counter))
528                     continue;
529                   phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
530                   VEC_safe_push (const_char_ptr, *result_names, phys_name);
531                 }
532             }
533         }
534     }
535
536   for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
537     VEC_safe_push (typep, *superclasses, TYPE_BASECLASS (t, ibase));
538 }
539
540 /* Find an instance of the character C in the string S that is outside
541    of all parenthesis pairs, single-quoted strings, and double-quoted
542    strings.  Also, ignore the char within a template name, like a ','
543    within foo<int, int>.  */
544
545 static char *
546 find_toplevel_char (char *s, char c)
547 {
548   int quoted = 0;               /* zero if we're not in quotes;
549                                    '"' if we're in a double-quoted string;
550                                    '\'' if we're in a single-quoted string.  */
551   int depth = 0;                /* Number of unclosed parens we've seen.  */
552   char *scan;
553
554   for (scan = s; *scan; scan++)
555     {
556       if (quoted)
557         {
558           if (*scan == quoted)
559             quoted = 0;
560           else if (*scan == '\\' && *(scan + 1))
561             scan++;
562         }
563       else if (*scan == c && ! quoted && depth == 0)
564         return scan;
565       else if (*scan == '"' || *scan == '\'')
566         quoted = *scan;
567       else if (*scan == '(' || *scan == '<')
568         depth++;
569       else if ((*scan == ')' || *scan == '>') && depth > 0)
570         depth--;
571     }
572
573   return 0;
574 }
575
576 /* Determines if the gives string corresponds to an Objective-C method
577    representation, such as -[Foo bar:] or +[Foo bar].  Objective-C symbols
578    are allowed to have spaces and parentheses in them.  */
579
580 static int 
581 is_objc_method_format (const char *s)
582 {
583   if (s == NULL || *s == '\0')
584     return 0;
585   /* Handle arguments with the format FILENAME:SYMBOL.  */
586   if ((s[0] == ':') && (strchr ("+-", s[1]) != NULL) 
587       && (s[2] == '[') && strchr(s, ']'))
588     return 1;
589   /* Handle arguments that are just SYMBOL.  */
590   else if ((strchr ("+-", s[0]) != NULL) && (s[1] == '[') && strchr(s, ']'))
591     return 1;
592   return 0;
593 }
594
595 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
596    and store the result in SELF->CANONICAL.  */
597
598 static void
599 filter_results (struct linespec_state *self,
600                 struct symtabs_and_lines *result,
601                 VEC (const_char_ptr) *filters)
602 {
603   int i;
604   const char *name;
605
606   for (i = 0; VEC_iterate (const_char_ptr, filters, i, name); ++i)
607     {
608       struct linespec_sals lsal;
609       int j;
610
611       memset (&lsal, 0, sizeof (lsal));
612
613       for (j = 0; j < result->nelts; ++j)
614         {
615           if (strcmp (name, self->canonical_names[j]) == 0)
616             add_sal_to_sals_basic (&lsal.sals, &result->sals[j]);
617         }
618
619       if (lsal.sals.nelts > 0)
620         {
621           lsal.canonical = xstrdup (name);
622           VEC_safe_push (linespec_sals, self->canonical->sals, &lsal);
623         }
624     }
625
626   self->canonical->pre_expanded = 0;
627 }
628
629 /* Store RESULT into SELF->CANONICAL.  */
630
631 static void
632 convert_results_to_lsals (struct linespec_state *self,
633                           struct symtabs_and_lines *result)
634 {
635   struct linespec_sals lsal;
636
637   lsal.canonical = NULL;
638   lsal.sals = *result;
639   VEC_safe_push (linespec_sals, self->canonical->sals, &lsal);
640 }
641
642 /* Handle multiple results in RESULT depending on SELECT_MODE.  This
643    will either return normally, throw an exception on multiple
644    results, or present a menu to the user.  On return, the SALS vector
645    in SELF->CANONICAL is set up properly.  */
646
647 static void
648 decode_line_2 (struct linespec_state *self,
649                struct symtabs_and_lines *result,
650                const char *select_mode)
651 {
652   const char *iter;
653   char *args, *prompt;
654   int i;
655   struct cleanup *old_chain;
656   VEC (const_char_ptr) *item_names = NULL, *filters = NULL;
657   struct get_number_or_range_state state;
658
659   gdb_assert (select_mode != multiple_symbols_all);
660   gdb_assert (self->canonical != NULL);
661
662   old_chain = make_cleanup (VEC_cleanup (const_char_ptr), &item_names);
663   make_cleanup (VEC_cleanup (const_char_ptr), &filters);
664   for (i = 0; i < result->nelts; ++i)
665     {
666       int j, found = 0;
667       const char *iter;
668
669       gdb_assert (self->canonical_names[i] != NULL);
670       for (j = 0; VEC_iterate (const_char_ptr, item_names, j, iter); ++j)
671         {
672           if (strcmp (iter, self->canonical_names[i]) == 0)
673             {
674               found = 1;
675               break;
676             }
677         }
678
679       if (!found)
680         VEC_safe_push (const_char_ptr, item_names, self->canonical_names[i]);
681     }
682
683   if (select_mode == multiple_symbols_cancel
684       && VEC_length (const_char_ptr, item_names) > 1)
685     error (_("canceled because the command is ambiguous\n"
686              "See set/show multiple-symbol."));
687   
688   if (select_mode == multiple_symbols_all
689       || VEC_length (const_char_ptr, item_names) == 1)
690     {
691       do_cleanups (old_chain);
692       convert_results_to_lsals (self, result);
693       return;
694     }
695
696   /* Sort the list of method names alphabetically.  */
697   qsort (VEC_address (const_char_ptr, item_names),
698          VEC_length (const_char_ptr, item_names),
699          sizeof (const_char_ptr), compare_strings);
700
701   printf_unfiltered (_("[0] cancel\n[1] all\n"));
702   for (i = 0; VEC_iterate (const_char_ptr, item_names, i, iter); ++i)
703     printf_unfiltered ("[%d] %s\n", i + 2, iter);
704
705   prompt = getenv ("PS2");
706   if (prompt == NULL)
707     {
708       prompt = "> ";
709     }
710   args = command_line_input (prompt, 0, "overload-choice");
711
712   if (args == 0 || *args == 0)
713     error_no_arg (_("one or more choice numbers"));
714
715   init_number_or_range (&state, args);
716   while (!state.finished)
717     {
718       int num;
719
720       num = get_number_or_range (&state);
721
722       if (num == 0)
723         error (_("canceled"));
724       else if (num == 1)
725         {
726           /* We intentionally make this result in a single breakpoint,
727              contrary to what older versions of gdb did.  The
728              rationale is that this lets a user get the
729              multiple_symbols_all behavior even with the 'ask'
730              setting; and he can get separate breakpoints by entering
731              "2-57" at the query.  */
732           do_cleanups (old_chain);
733           convert_results_to_lsals (self, result);
734           return;
735         }
736
737       num -= 2;
738       if (num >= VEC_length (const_char_ptr, item_names))
739         printf_unfiltered (_("No choice number %d.\n"), num);
740       else
741         {
742           const char *elt = VEC_index (const_char_ptr, item_names, num);
743
744           if (elt != NULL)
745             {
746               VEC_safe_push (const_char_ptr, filters, elt);
747               VEC_replace (const_char_ptr, item_names, num, NULL);
748             }
749           else
750             {
751               printf_unfiltered (_("duplicate request for %d ignored.\n"),
752                                  num);
753             }
754         }
755     }
756
757   filter_results (self, result, filters);
758   do_cleanups (old_chain);
759 }
760
761 /* Valid delimiters for linespec keywords "if", "thread" or "task".  */
762
763 static int
764 is_linespec_boundary (char c)
765 {
766   return c == ' ' || c == '\t' || c == '\0' || c == ',';
767 }
768
769 /* A helper function for decode_line_1 and friends which skips P
770    past any method overload information at the beginning of P, e.g.,
771    "(const struct foo *)".
772
773    This function assumes that P has already been validated to contain
774    overload information, and it will assert if *P != '('.  */
775 static char *
776 find_method_overload_end (char *p)
777 {
778   int depth = 0;
779
780   gdb_assert (*p == '(');
781
782   while (*p)
783     {
784       if (*p == '(')
785         ++depth;
786       else if (*p == ')')
787         {
788           if (--depth == 0)
789             {
790               ++p;
791               break;
792             }
793         }
794       ++p;
795     }
796
797   return p;
798 }
799
800 /* Keep important information used when looking up a name.  This includes
801    template parameters, overload information, and important keywords, including
802    the possible Java trailing type.  */
803
804 static char *
805 keep_name_info (char *p, int on_boundary)
806 {
807   const char *quotes = get_gdb_completer_quote_characters ();
808   char *saved_p = p;
809   int nest = 0;
810
811   while (*p)
812     {
813       if (strchr (quotes, *p))
814         break;
815
816       if (*p == ',' && !nest)
817         break;
818
819       if (on_boundary && !nest)
820         {
821           const char *const words[] = { "if", "thread", "task" };
822           int wordi;
823
824           for (wordi = 0; wordi < ARRAY_SIZE (words); wordi++)
825             if (strncmp (p, words[wordi], strlen (words[wordi])) == 0
826                 && is_linespec_boundary (p[strlen (words[wordi])]))
827               break;
828           if (wordi < ARRAY_SIZE (words))
829             break;
830         }
831
832       if (*p == '(' || *p == '<' || *p == '[')
833         nest++;
834       else if ((*p == ')' || *p == '>' || *p == ']') && nest > 0)
835         nest--;
836
837       p++;
838
839       /* The ',' check could fail on "operator ,".  */
840       p += cp_validate_operator (p);
841
842       on_boundary = is_linespec_boundary (p[-1]);
843     }
844
845   while (p > saved_p && is_linespec_boundary (p[-1]))
846     p--;
847
848   return p;
849 }
850
851 \f
852 /* The parser of linespec itself.  */
853
854 /* Parse a string that specifies a line number.
855    Pass the address of a char * variable; that variable will be
856    advanced over the characters actually parsed.
857
858    The string can be:
859
860    LINENUM -- that line number in current file.  PC returned is 0.
861    FILE:LINENUM -- that line in that file.  PC returned is 0.
862    FUNCTION -- line number of openbrace of that function.
863    PC returned is the start of the function.
864    LABEL -- a label in the current scope
865    VARIABLE -- line number of definition of that variable.
866    PC returned is 0.
867    FILE:FUNCTION -- likewise, but prefer functions in that file.
868    *EXPR -- line in which address EXPR appears.
869
870    This may all be followed by an "if EXPR", which we ignore.
871
872    FUNCTION may be an undebuggable function found in minimal symbol table.
873
874    If the argument FUNFIRSTLINE is nonzero, we want the first line
875    of real code inside a function when a function is specified, and it is
876    not OK to specify a variable or type to get its line number.
877
878    DEFAULT_SYMTAB specifies the file to use if none is specified.
879    It defaults to current_source_symtab.
880    DEFAULT_LINE specifies the line number to use for relative
881    line numbers (that start with signs).  Defaults to current_source_line.
882    If CANONICAL is non-NULL, store an array of strings containing the canonical
883    line specs there if necessary.  Currently overloaded member functions and
884    line numbers or static functions without a filename yield a canonical
885    line spec.  The array and the line spec strings are allocated on the heap,
886    it is the callers responsibility to free them.
887
888    Note that it is possible to return zero for the symtab
889    if no file is validly specified.  Callers must check that.
890    Also, the line number returned may be invalid.  */
891
892 /* We allow single quotes in various places.  This is a hideous
893    kludge, which exists because the completer can't yet deal with the
894    lack of single quotes.  FIXME: write a linespec_completer which we
895    can use as appropriate instead of make_symbol_completion_list.  */
896
897 static struct symtabs_and_lines
898 decode_line_internal (struct linespec_state *self, char **argptr)
899 {
900   char *p;
901   char *q;
902
903   char *copy;
904   /* This says whether or not something in *ARGPTR is quoted with
905      completer_quotes (i.e. with single quotes).  */
906   int is_quoted;
907   /* Is *ARGPTR enclosed in double quotes?  */
908   int is_quote_enclosed;
909   int is_objc_method = 0;
910   char *saved_arg = *argptr;
911   /* If IS_QUOTED, the end of the quoted bit.  */
912   char *end_quote = NULL;
913   /* Is *ARGPTR enclosed in single quotes?  */
914   int is_squote_enclosed = 0;
915   /* The "first half" of the linespec.  */
916   char *first_half;
917
918   /* If we are parsing `function:label', this holds the symbols
919      matching the function name.  */
920   VEC (symbolp) *function_symbols = NULL;
921   /* If FUNCTION_SYMBOLS is not NULL, then this is the exception that
922      was thrown when trying to parse a filename.  */
923   volatile struct gdb_exception file_exception;
924
925   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
926
927   /* Defaults have defaults.  */
928
929   initialize_defaults (&self->default_symtab, &self->default_line);
930   
931   /* See if arg is *PC.  */
932
933   if (**argptr == '*')
934     {
935       do_cleanups (cleanup);
936       return decode_indirect (self, argptr);
937     }
938
939   is_quoted = (strchr (get_gdb_completer_quote_characters (),
940                        **argptr) != NULL);
941
942   if (is_quoted)
943     {
944       end_quote = skip_quoted (*argptr);
945       if (*end_quote == '\0')
946         is_squote_enclosed = 1;
947     }
948
949   /* Check to see if it's a multipart linespec (with colons or
950      periods).  */
951
952   /* Locate the end of the first half of the linespec.
953      After the call, for instance, if the argptr string is "foo.c:123"
954      p will point at ":123".  If there is only one part, like "foo", p
955      will point to "".  If this is a C++ name, like "A::B::foo", p will
956      point to "::B::foo".  Argptr is not changed by this call.  */
957
958   first_half = p = locate_first_half (argptr, &is_quote_enclosed);
959
960   /* First things first: if ARGPTR starts with a filename, get its
961      symtab and strip the filename from ARGPTR.
962      Avoid calling symtab_from_filename if we know can,
963      it can be expensive.  We know we can avoid the call if we see a
964      single word (e.g., "break NAME") or if we see a qualified C++
965      name ("break QUAL::NAME").  */
966
967   if (*p != '\0' && !(p[0] == ':' && p[1] == ':'))
968     {
969       TRY_CATCH (file_exception, RETURN_MASK_ERROR)
970         {
971           self->file_symtabs = symtabs_from_filename (argptr, p,
972                                                       is_quote_enclosed,
973                                                       &self->user_filename);
974         }
975
976       if (file_exception.reason >= 0)
977         {
978           /* Check for single quotes on the non-filename part.  */
979           is_quoted = (**argptr
980                        && strchr (get_gdb_completer_quote_characters (),
981                                   **argptr) != NULL);
982           if (is_quoted)
983             end_quote = skip_quoted (*argptr);
984
985           /* Locate the next "half" of the linespec.  */
986           first_half = p = locate_first_half (argptr, &is_quote_enclosed);
987         }
988
989       if (VEC_empty (symtab_p, self->file_symtabs))
990         {
991           /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
992           VEC_safe_push (symtab_p, self->file_symtabs, NULL);
993         }
994     }
995   else
996     {
997       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
998       VEC_safe_push (symtab_p, self->file_symtabs, NULL);
999     }
1000
1001   /* Check if this is an Objective-C method (anything that starts with
1002      a '+' or '-' and a '[').  */
1003   if (is_objc_method_format (p))
1004     is_objc_method = 1;
1005
1006   /* Check if the symbol could be an Objective-C selector.  */
1007
1008   {
1009     struct symtabs_and_lines values;
1010
1011     values = decode_objc (self, argptr);
1012     if (values.sals != NULL)
1013       {
1014         do_cleanups (cleanup);
1015         return values;
1016       }
1017   }
1018
1019   /* Does it look like there actually were two parts?  */
1020
1021   if (p[0] == ':' || p[0] == '.')
1022     {
1023       /* Is it a C++ or Java compound data structure?
1024          The check on p[1] == ':' is capturing the case of "::",
1025          since p[0]==':' was checked above.
1026          Note that the call to decode_compound does everything
1027          for us, including the lookup on the symbol table, so we
1028          can return now.  */
1029         
1030       if (p[0] == '.' || p[1] == ':')
1031         {
1032          /* We only perform this check for the languages where it might
1033             make sense.  For instance, Ada does not use this type of
1034             syntax, and trying to apply this logic on an Ada linespec
1035             may trigger a spurious error (for instance, decode_compound
1036             does not like expressions such as `ops."<"', which is a
1037             valid function name in Ada).  */
1038           if (current_language->la_language == language_c
1039               || current_language->la_language == language_cplus
1040               || current_language->la_language == language_java)
1041             {
1042               struct symtabs_and_lines values;
1043               volatile struct gdb_exception ex;
1044               char *saved_argptr = *argptr;
1045
1046               if (is_quote_enclosed)
1047                 ++saved_arg;
1048
1049               /* Initialize it just to avoid a GCC false warning.  */
1050               memset (&values, 0, sizeof (values));
1051
1052               TRY_CATCH (ex, RETURN_MASK_ERROR)
1053                 {
1054                   values = decode_compound (self, argptr, saved_arg, p);
1055                 }
1056               if ((is_quoted || is_squote_enclosed) && **argptr == '\'')
1057                 *argptr = *argptr + 1;
1058
1059               if (ex.reason >= 0)
1060                 {
1061                   do_cleanups (cleanup);
1062                   return values;
1063                 }
1064
1065               if (ex.error != NOT_FOUND_ERROR)
1066                 throw_exception (ex);
1067
1068               *argptr = saved_argptr;
1069             }
1070         }
1071       else
1072         {
1073           /* If there was an exception looking up a specified filename earlier,
1074              then check whether we were really given `function:label'.   */
1075           if (file_exception.reason < 0)
1076             {
1077               function_symbols = find_function_symbols (argptr, p,
1078                                                         is_quote_enclosed,
1079                                                         &self->user_function);
1080
1081               /* If we did not find a function, re-throw the original
1082                  exception.  */
1083               if (!function_symbols)
1084                 throw_exception (file_exception);
1085
1086               make_cleanup (VEC_cleanup (symbolp), &function_symbols);
1087             }
1088
1089           /* Check for single quotes on the non-filename part.  */
1090           if (!is_quoted)
1091             {
1092               is_quoted = (**argptr
1093                            && strchr (get_gdb_completer_quote_characters (),
1094                                       **argptr) != NULL);
1095               if (is_quoted)
1096                 end_quote = skip_quoted (*argptr);
1097             }
1098         }
1099     }
1100
1101   /* self->file_symtabs holds the  specified file symtabs, or 0 if no file
1102      specified.
1103      If we are parsing `function:symbol', then FUNCTION_SYMBOLS holds the
1104      functions before the `:'.
1105      arg no longer contains the file name.  */
1106
1107   /* If the filename was quoted, we must re-check the quotation.  */
1108
1109   if (end_quote == first_half && *end_quote!= '\0')
1110     {
1111       is_quoted = (**argptr
1112                    && strchr (get_gdb_completer_quote_characters (),
1113                               **argptr) != NULL);
1114       if (is_quoted)
1115         end_quote = skip_quoted (*argptr);
1116     }
1117
1118   /* Check whether arg is all digits (and sign).  */
1119
1120   q = *argptr;
1121   if (*q == '-' || *q == '+')
1122     q++;
1123   while (*q >= '0' && *q <= '9')
1124     q++;
1125
1126   if (q != *argptr && (*q == 0 || *q == ' ' || *q == '\t' || *q == ',')
1127       && function_symbols == NULL)
1128     {
1129       struct symtabs_and_lines values;
1130
1131       /* We found a token consisting of all digits -- at least one digit.  */
1132       values = decode_all_digits (self, argptr, q);
1133       do_cleanups (cleanup);
1134       return values;
1135     }
1136
1137   /* Arg token is not digits => try it as a variable name
1138      Find the next token (everything up to end or next whitespace).  */
1139
1140   if (**argptr == '$')          /* May be a convenience variable.  */
1141     /* One or two $ chars possible.  */
1142     p = skip_quoted (*argptr + (((*argptr)[1] == '$') ? 2 : 1));
1143   else if (is_quoted || is_squote_enclosed)
1144     {
1145       p = end_quote;
1146       if (p[-1] != '\'')
1147         error (_("Unmatched single quote."));
1148     }
1149   else if (is_objc_method)
1150     {
1151       /* allow word separators in method names for Obj-C.  */
1152       p = skip_quoted_chars (*argptr, NULL, "");
1153     }
1154   else
1155     {
1156       p = skip_quoted (*argptr);
1157     }
1158
1159   /* Keep any important naming information.  */
1160   p = keep_name_info (p, p == saved_arg || is_linespec_boundary (p[-1]));
1161
1162   copy = (char *) alloca (p - *argptr + 1);
1163   memcpy (copy, *argptr, p - *argptr);
1164   copy[p - *argptr] = '\0';
1165   if (p != *argptr
1166       && copy[0]
1167       && copy[0] == copy[p - *argptr - 1]
1168       && strchr (get_gdb_completer_quote_characters (), copy[0]) != NULL)
1169     {
1170       copy[p - *argptr - 1] = '\0';
1171       copy++;
1172     }
1173   else if (is_quoted || is_squote_enclosed)
1174     copy[p - *argptr - 1] = '\0';
1175   
1176   *argptr = skip_spaces (p);
1177
1178   /* If it starts with $: may be a legitimate variable or routine name
1179      (e.g. HP-UX millicode routines such as $$dyncall), or it may
1180      be history value, or it may be a convenience variable.  */
1181
1182   if (*copy == '$' && function_symbols == NULL)
1183     {
1184       struct symtabs_and_lines values;
1185
1186       values = decode_dollar (self, copy);
1187       do_cleanups (cleanup);
1188       return values;
1189     }
1190
1191   /* Try the token as a label, but only if no file was specified,
1192      because we can only really find labels in the current scope.  */
1193
1194   if (VEC_length (symtab_p, self->file_symtabs) == 1
1195       && VEC_index (symtab_p, self->file_symtabs, 0) == NULL)
1196     {
1197       struct symtabs_and_lines label_result;
1198       if (decode_label (self, function_symbols, copy, &label_result))
1199         {
1200           do_cleanups (cleanup);
1201           return label_result;
1202         }
1203     }
1204
1205   if (function_symbols)
1206     throw_exception (file_exception);
1207
1208   /* Look up that token as a variable.
1209      If file specified, use that file's per-file block to start with.  */
1210
1211   {
1212     struct symtabs_and_lines values;
1213
1214     values = decode_variable (self, copy);
1215     do_cleanups (cleanup);
1216     return values;
1217   }
1218 }
1219
1220 /* A constructor for linespec_state.  */
1221
1222 static void
1223 linespec_state_constructor (struct linespec_state *self,
1224                             int flags,
1225                             struct symtab *default_symtab,
1226                             int default_line,
1227                             struct linespec_result *canonical)
1228 {
1229   memset (self, 0, sizeof (*self));
1230   self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
1231   self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
1232   self->default_symtab = default_symtab;
1233   self->default_line = default_line;
1234   self->canonical = canonical;
1235   self->program_space = current_program_space;
1236   self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
1237                                       xfree, xcalloc, xfree);
1238 }
1239
1240 /* A destructor for linespec_state.  */
1241
1242 static void
1243 linespec_state_destructor (void *arg)
1244 {
1245   struct linespec_state *self = arg;
1246
1247   xfree (self->user_filename);
1248   xfree (self->user_function);
1249   VEC_free (symtab_p, self->file_symtabs);
1250   htab_delete (self->addr_set);
1251 }
1252
1253 /* See linespec.h.  */
1254
1255 void
1256 decode_line_full (char **argptr, int flags,
1257                   struct symtab *default_symtab,
1258                   int default_line, struct linespec_result *canonical,
1259                   const char *select_mode,
1260                   const char *filter)
1261 {
1262   struct symtabs_and_lines result;
1263   struct linespec_state state;
1264   struct cleanup *cleanups;
1265   char *arg_start = *argptr;
1266   VEC (const_char_ptr) *filters = NULL;
1267
1268   gdb_assert (canonical != NULL);
1269   /* The filter only makes sense for 'all'.  */
1270   gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
1271   gdb_assert (select_mode == NULL
1272               || select_mode == multiple_symbols_all
1273               || select_mode == multiple_symbols_ask
1274               || select_mode == multiple_symbols_cancel);
1275   gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
1276
1277   linespec_state_constructor (&state, flags,
1278                               default_symtab, default_line, canonical);
1279   cleanups = make_cleanup (linespec_state_destructor, &state);
1280   save_current_program_space ();
1281
1282   result = decode_line_internal (&state, argptr);
1283
1284   gdb_assert (result.nelts == 1 || canonical->pre_expanded);
1285   gdb_assert (canonical->addr_string != NULL);
1286   canonical->pre_expanded = 1;
1287
1288   /* Fill in the missing canonical names.  */
1289   if (result.nelts > 0)
1290     {
1291       int i;
1292
1293       if (state.canonical_names == NULL)
1294         state.canonical_names = xcalloc (result.nelts, sizeof (char *));
1295       make_cleanup (xfree, state.canonical_names);
1296       for (i = 0; i < result.nelts; ++i)
1297         {
1298           if (state.canonical_names[i] == NULL)
1299             state.canonical_names[i] = savestring (arg_start,
1300                                                    *argptr - arg_start);
1301           make_cleanup (xfree, state.canonical_names[i]);
1302         }
1303     }
1304
1305   if (select_mode == NULL)
1306     {
1307       if (ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
1308         select_mode = multiple_symbols_all;
1309       else
1310         select_mode = multiple_symbols_select_mode ();
1311     }
1312
1313   if (select_mode == multiple_symbols_all)
1314     {
1315       if (filter != NULL)
1316         {
1317           make_cleanup (VEC_cleanup (const_char_ptr), &filters);
1318           VEC_safe_push (const_char_ptr, filters, filter);
1319           filter_results (&state, &result, filters);
1320         }
1321       else
1322         convert_results_to_lsals (&state, &result);
1323     }
1324   else
1325     decode_line_2 (&state, &result, select_mode);
1326
1327   do_cleanups (cleanups);
1328 }
1329
1330 struct symtabs_and_lines
1331 decode_line_1 (char **argptr, int flags,
1332                struct symtab *default_symtab,
1333                int default_line)
1334 {
1335   struct symtabs_and_lines result;
1336   struct linespec_state state;
1337   struct cleanup *cleanups;
1338
1339   linespec_state_constructor (&state, flags,
1340                               default_symtab, default_line, NULL);
1341   cleanups = make_cleanup (linespec_state_destructor, &state);
1342   save_current_program_space ();
1343
1344   result = decode_line_internal (&state, argptr);
1345   do_cleanups (cleanups);
1346   return result;
1347 }
1348
1349 \f
1350
1351 /* First, some functions to initialize stuff at the beggining of the
1352    function.  */
1353
1354 static void
1355 initialize_defaults (struct symtab **default_symtab, int *default_line)
1356 {
1357   if (*default_symtab == 0)
1358     {
1359       /* Use whatever we have for the default source line.  We don't use
1360          get_current_or_default_symtab_and_line as it can recurse and call
1361          us back!  */
1362       struct symtab_and_line cursal = 
1363         get_current_source_symtab_and_line ();
1364       
1365       *default_symtab = cursal.symtab;
1366       *default_line = cursal.line;
1367     }
1368 }
1369
1370 \f
1371
1372 /* Decode arg of the form *PC.  */
1373
1374 static struct symtabs_and_lines
1375 decode_indirect (struct linespec_state *self, char **argptr)
1376 {
1377   struct symtabs_and_lines values;
1378   CORE_ADDR pc;
1379   char *initial = *argptr;
1380   
1381   if (current_program_space->executing_startup)
1382     /* The error message doesn't really matter, because this case
1383        should only hit during breakpoint reset.  */
1384     throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
1385                                     "program space is in startup"));
1386
1387   (*argptr)++;
1388   pc = value_as_address (parse_to_comma_and_eval (argptr));
1389
1390   values.sals = (struct symtab_and_line *)
1391     xmalloc (sizeof (struct symtab_and_line));
1392
1393   values.nelts = 1;
1394   values.sals[0] = find_pc_line (pc, 0);
1395   values.sals[0].pc = pc;
1396   values.sals[0].section = find_pc_overlay (pc);
1397   values.sals[0].explicit_pc = 1;
1398
1399   if (self->canonical)
1400     self->canonical->addr_string = savestring (initial, *argptr - initial);
1401
1402   return values;
1403 }
1404
1405 \f
1406
1407 /* Locate the first half of the linespec, ending in a colon, period,
1408    or whitespace.  (More or less.)  Also, check to see if *ARGPTR is
1409    enclosed in double quotes; if so, set is_quote_enclosed, advance
1410    ARGPTR past that and zero out the trailing double quote.
1411    If ARGPTR is just a simple name like "main", p will point to ""
1412    at the end.  */
1413
1414 static char *
1415 locate_first_half (char **argptr, int *is_quote_enclosed)
1416 {
1417   char *ii;
1418   char *p, *p1;
1419   int has_comma;
1420
1421   /* Check if the linespec starts with an Ada operator (such as "+",
1422      or ">", for instance).  */
1423   p = *argptr;
1424   if (p[0] == '"'
1425       && current_language->la_language == language_ada)
1426     {
1427       const struct ada_opname_map *op;
1428
1429       for (op = ada_opname_table; op->encoded != NULL; op++)
1430         if (strncmp (op->decoded, p, strlen (op->decoded)) == 0)
1431           break;
1432       if (op->encoded != NULL)
1433         {
1434           *is_quote_enclosed = 0;
1435           return p + strlen (op->decoded);
1436         }
1437     }
1438
1439   /* Maybe we were called with a line range FILENAME:LINENUM,FILENAME:LINENUM
1440      and we must isolate the first half.  Outer layers will call again later
1441      for the second half.
1442
1443      Don't count commas that appear in argument lists of overloaded
1444      functions, or in quoted strings.  It's stupid to go to this much
1445      trouble when the rest of the function is such an obvious roach hotel.  */
1446   ii = find_toplevel_char (*argptr, ',');
1447   has_comma = (ii != 0);
1448
1449   /* Temporarily zap out second half to not confuse the code below.
1450      This is undone below.  Do not change ii!!  */
1451   if (has_comma)
1452     {
1453       *ii = '\0';
1454     }
1455
1456   /* Maybe arg is FILE : LINENUM or FILE : FUNCTION.  May also be
1457      CLASS::MEMBER, or NAMESPACE::NAME.  Look for ':', but ignore
1458      inside of <>.  */
1459
1460   p = *argptr;
1461   if (p[0] == '"')
1462     {
1463       *is_quote_enclosed = 1;
1464       (*argptr)++;
1465       p++;
1466     }
1467   else
1468     {
1469       *is_quote_enclosed = 0;
1470       if (strchr (get_gdb_completer_quote_characters (), *p))
1471         {
1472           ++(*argptr);
1473           ++p;
1474         }
1475     }
1476
1477
1478   /* Check for a drive letter in the filename.  This is done on all hosts
1479      to capture cross-compilation environments.  On Unixen, directory
1480      separators are illegal in filenames, so if the user enters "e:/foo.c",
1481      he is referring to a directory named "e:" and a source file named
1482      "foo.c", and we still want to keep these two pieces together.  */
1483   if (isalpha (p[0]) && p[1] == ':' && IS_DIR_SEPARATOR (p[2]))
1484     p += 3;
1485
1486   for (; *p; p++)
1487     {
1488       if (p[0] == '<')
1489         {
1490           char *temp_end = find_template_name_end (p);
1491
1492           if (!temp_end)
1493             error (_("malformed template specification in command"));
1494           p = temp_end;
1495         }
1496
1497       if (p[0] == '(')
1498         p = find_method_overload_end (p);
1499
1500       /* Check for a colon and a plus or minus and a [ (which
1501          indicates an Objective-C method).  */
1502       if (is_objc_method_format (p))
1503         {
1504           break;
1505         }
1506       /* Check for the end of the first half of the linespec.  End of
1507          line, a tab, a colon or a space.  But if enclosed in double
1508          quotes we do not break on enclosed spaces.  */
1509       if (!*p
1510           || p[0] == '\t'
1511           || (p[0] == ':')
1512           || ((p[0] == ' ') && !*is_quote_enclosed))
1513         break;
1514       if (p[0] == '.' && strchr (p, ':') == NULL)
1515         {
1516           /* Java qualified method.  Find the *last* '.', since the
1517              others are package qualifiers.  Stop at any open parenthesis
1518              which might provide overload information.  */
1519           for (p1 = p; *p1 && *p1 != '('; p1++)
1520             {
1521               if (*p1 == '.')
1522                 p = p1;
1523             }
1524           break;
1525         }
1526     }
1527   p = skip_spaces (p);
1528
1529   /* If the closing double quote was left at the end, remove it.  */
1530   if (*is_quote_enclosed)
1531     {
1532       char *closing_quote = strchr (p - 1, '"');
1533
1534       if (closing_quote && closing_quote[1] == '\0')
1535         *closing_quote = '\0';
1536     }
1537
1538   /* Now that we've safely parsed the first half, put back ',' so
1539      outer layers can see it.  */
1540   if (has_comma)
1541     *ii = ',';
1542
1543   return p;
1544 }
1545
1546 \f
1547
1548 /* Here's where we recognise an Objective-C Selector.  An Objective C
1549    selector may be implemented by more than one class, therefore it
1550    may represent more than one method/function.  This gives us a
1551    situation somewhat analogous to C++ overloading.  If there's more
1552    than one method that could represent the selector, then use some of
1553    the existing C++ code to let the user choose one.  */
1554
1555 static struct symtabs_and_lines
1556 decode_objc (struct linespec_state *self, char **argptr)
1557 {
1558   struct collect_info info;
1559   VEC (const_char_ptr) *symbol_names = NULL;
1560   char *new_argptr;
1561   struct cleanup *cleanup = make_cleanup (VEC_cleanup (const_char_ptr),
1562                                           &symbol_names);
1563
1564   info.state = self;
1565   info.result.sals = NULL;
1566   info.result.nelts = 0;
1567
1568   new_argptr = find_imps (*argptr, &symbol_names); 
1569   if (VEC_empty (const_char_ptr, symbol_names))
1570     {
1571       do_cleanups (cleanup);
1572       return info.result;
1573     }
1574
1575   add_all_symbol_names_from_pspace (&info, NULL, symbol_names);
1576
1577   if (info.result.nelts > 0)
1578     {
1579       char *saved_arg;
1580
1581       saved_arg = alloca (new_argptr - *argptr + 1);
1582       memcpy (saved_arg, *argptr, new_argptr - *argptr);
1583       saved_arg[new_argptr - *argptr] = '\0';
1584
1585       if (self->canonical)
1586         {
1587           self->canonical->pre_expanded = 1;
1588           if (self->user_filename)
1589             self->canonical->addr_string
1590               = xstrprintf ("%s:%s", self->user_filename, saved_arg);
1591           else
1592             self->canonical->addr_string = xstrdup (saved_arg);
1593         }
1594     }
1595
1596   *argptr = new_argptr;
1597
1598   do_cleanups (cleanup);
1599   return info.result;
1600 }
1601
1602 /* This handles C++ and Java compound data structures.  P should point
1603    at the first component separator, i.e. double-colon or period.  As
1604    an example, on entrance to this function we could have ARGPTR
1605    pointing to "AAA::inA::fun" and P pointing to "::inA::fun".  */
1606
1607 static struct symtabs_and_lines
1608 decode_compound (struct linespec_state *self,
1609                  char **argptr, char *the_real_saved_arg, char *p)
1610 {
1611   struct symtabs_and_lines values;
1612   char *p2;
1613   char *saved_arg2 = *argptr;
1614   char *temp_end;
1615   struct symbol *sym;
1616   char *copy;
1617   VEC (symbolp) *sym_classes;
1618   char *saved_arg, *class_name;
1619   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
1620
1621   /* If the user specified any completer quote characters in the input,
1622      strip them.  They are superfluous.  */
1623   saved_arg = alloca (strlen (the_real_saved_arg) + 1);
1624   {
1625     char *dst = saved_arg;
1626     char *src = the_real_saved_arg;
1627     char *quotes = get_gdb_completer_quote_characters ();
1628     while (*src != '\0')
1629       {
1630         if (strchr (quotes, *src) == NULL)
1631           *dst++ = *src;
1632         ++src;
1633       }
1634     *dst = '\0';
1635   }
1636
1637   /* First check for "global" namespace specification, of the form
1638      "::foo".  If found, skip over the colons and jump to normal
1639      symbol processing.  I.e. the whole line specification starts with
1640      "::" (note the condition that *argptr == p).  */
1641   if (p[0] == ':' 
1642       && ((*argptr == p) || (p[-1] == ' ') || (p[-1] == '\t')))
1643     saved_arg2 += 2;
1644
1645   /* Given our example "AAA::inA::fun", we have two cases to consider:
1646
1647      1) AAA::inA is the name of a class.  In that case, presumably it
1648         has a method called "fun"; we then look up that method using
1649         find_method.
1650
1651      2) AAA::inA isn't the name of a class.  In that case, either the
1652         user made a typo, AAA::inA is the name of a namespace, or it is
1653         the name of a minimal symbol.
1654         In this case we just delegate to decode_variable.
1655
1656      Thus, our first task is to find everything before the last set of
1657      double-colons and figure out if it's the name of a class.  So we
1658      first loop through all of the double-colons.  */
1659
1660   p2 = p;               /* Save for restart.  */
1661
1662   /* This is very messy.  Following the example above we have now the
1663      following pointers:
1664      p -> "::inA::fun"
1665      argptr -> "AAA::inA::fun
1666      saved_arg -> "AAA::inA::fun
1667      saved_arg2 -> "AAA::inA::fun
1668      p2 -> "::inA::fun".  */
1669
1670   /* In the loop below, with these strings, we'll make 2 passes, each
1671      is marked in comments.  */
1672
1673   while (1)
1674     {
1675       static char *break_characters = " \t(";
1676
1677       /* Move pointer up to next possible class/namespace token.  */
1678
1679       p = p2 + 1;       /* Restart with old value +1.  */
1680
1681       /* PASS1: at this point p2->"::inA::fun", so p->":inA::fun",
1682          i.e. if there is a double-colon, p will now point to the
1683          second colon.  */
1684       /* PASS2: p2->"::fun", p->":fun" */
1685
1686       /* Move pointer ahead to next double-colon.  */
1687       while (*p
1688              && strchr (break_characters, *p) == NULL
1689              && strchr (get_gdb_completer_quote_characters (), *p) == NULL)
1690         {
1691           if (current_language->la_language == language_cplus)
1692             p += cp_validate_operator (p);
1693
1694           if (p[0] == '<')
1695             {
1696               temp_end = find_template_name_end (p);
1697               if (!temp_end)
1698                 error (_("malformed template specification in command"));
1699               p = temp_end;
1700             }
1701           /* Note that, since, at the start of this loop, p would be
1702              pointing to the second colon in a double-colon, we only
1703              satisfy the condition below if there is another
1704              double-colon to the right (after).  I.e. there is another
1705              component that can be a class or a namespace.  I.e, if at
1706              the beginning of this loop (PASS1), we had
1707              p->":inA::fun", we'll trigger this when p has been
1708              advanced to point to "::fun".  */
1709           /* PASS2: we will not trigger this.  */
1710           else if ((p[0] == ':') && (p[1] == ':'))
1711             break;      /* Found double-colon.  */
1712           else
1713             {
1714               /* PASS2: We'll keep getting here, until P points to one of the
1715                  break characters, at which point we exit this loop.  */
1716               if (*p)
1717                 {
1718                   if (p[1] == '('
1719                       && strncmp (&p[1], CP_ANONYMOUS_NAMESPACE_STR,
1720                                   CP_ANONYMOUS_NAMESPACE_LEN) == 0)
1721                     p += CP_ANONYMOUS_NAMESPACE_LEN;
1722                   else if (strchr (break_characters, *p) == NULL)
1723                     ++p;
1724                 }
1725             }
1726         }
1727
1728       if (*p != ':')
1729         break;          /* Out of the while (1).  This would happen
1730                            for instance if we have looked up
1731                            unsuccessfully all the components of the
1732                            string, and p->""(PASS2).  */
1733
1734       /* We get here if p points to one of the break characters or "" (i.e.,
1735          string ended).  */
1736       /* Save restart for next time around.  */
1737       p2 = p;
1738       /* Restore argptr as it was on entry to this function.  */
1739       *argptr = saved_arg2;
1740       /* PASS1: at this point p->"::fun" argptr->"AAA::inA::fun",
1741          p2->"::fun".  */
1742
1743       /* All ready for next pass through the loop.  */
1744     }                   /* while (1) */
1745
1746
1747   /* Start of lookup in the symbol tables.  */
1748
1749   /* Lookup in the symbol table the substring between argptr and
1750      p.  Note, this call changes the value of argptr.  */
1751   /* Before the call, argptr->"AAA::inA::fun",
1752      p->"", p2->"::fun".  After the call: argptr->"fun", p, p2
1753      unchanged.  */
1754   sym_classes = lookup_prefix_sym (argptr, p2, self->file_symtabs,
1755                                    &class_name);
1756   make_cleanup (VEC_cleanup (symbolp), &sym_classes);
1757   make_cleanup (xfree, class_name);
1758
1759   /* If a class has been found, then we're in case 1 above.  So we
1760      look up "fun" as a method of those classes.  */
1761   if (!VEC_empty (symbolp, sym_classes))
1762     {
1763       /* Arg token is not digits => try it as a function name.
1764          Find the next token (everything up to end or next
1765          blank).  */
1766       if (**argptr
1767           && strchr (get_gdb_completer_quote_characters (),
1768                      **argptr) != NULL)
1769         {
1770           p = skip_quoted (*argptr);
1771           *argptr = *argptr + 1;
1772         }
1773       else
1774         {
1775           /* At this point argptr->"fun".  */
1776           char *a;
1777
1778           p = *argptr;
1779           while (*p && *p != ' ' && *p != '\t' && *p != ',' && *p != ':'
1780                  && *p != '(')
1781             p++;
1782           /* At this point p->"".  String ended.  */
1783           /* Nope, C++ operators could have spaces in them
1784              ("foo::operator <" or "foo::operator delete []").
1785              I apologize, this is a bit hacky...  */
1786           if (current_language->la_language == language_cplus
1787               && *p == ' ' && p - 8 - *argptr + 1 > 0)
1788             {
1789               /* The above loop has already swallowed "operator".  */
1790               p += cp_validate_operator (p - 8) - 8;
1791             }
1792
1793           /* Keep any important naming information.  */
1794           p = keep_name_info (p, 1);
1795         }
1796
1797       /* Allocate our own copy of the substring between argptr and
1798          p.  */
1799       copy = (char *) alloca (p - *argptr + 1);
1800       memcpy (copy, *argptr, p - *argptr);
1801       copy[p - *argptr] = '\0';
1802       if (p != *argptr
1803           && copy[p - *argptr - 1]
1804           && strchr (get_gdb_completer_quote_characters (),
1805                      copy[p - *argptr - 1]) != NULL)
1806         copy[p - *argptr - 1] = '\0';
1807
1808       /* At this point copy->"fun", p->"".  */
1809
1810       /* No line number may be specified.  */
1811       *argptr = skip_spaces (p);
1812       /* At this point arptr->"".  */
1813
1814       /* Look for copy as a method of sym_class.  */
1815       /* At this point copy->"fun", sym_class is "AAA:inA",
1816          saved_arg->"AAA::inA::fun".  This concludes the scanning of
1817          the string for possible components matches.  If we find it
1818          here, we return.  If not, and we are at the and of the string,
1819          we'll lookup the whole string in the symbol tables.  */
1820
1821       values = find_method (self, saved_arg, copy, class_name, sym_classes);
1822
1823       do_cleanups (cleanup);
1824       return values;
1825     } /* End if symbol found.  */
1826
1827
1828   /* We couldn't find a class, so we're in case 2 above.  We check the
1829      entire name as a symbol instead.  The simplest way to do this is
1830      to just throw an exception and let our caller fall through to
1831      decode_variable.  */
1832
1833   throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
1834 }
1835
1836 /* An instance of this type is used when collecting prefix symbols for
1837    decode_compound.  */
1838
1839 struct decode_compound_collector
1840 {
1841   /* The result vector.  */
1842   VEC (symbolp) *symbols;
1843
1844   /* A hash table of all symbols we found.  We use this to avoid
1845      adding any symbol more than once.  */
1846   htab_t unique_syms;
1847 };
1848
1849 /* A callback for iterate_over_symbols that is used by
1850    lookup_prefix_sym to collect type symbols.  */
1851
1852 static int
1853 collect_one_symbol (struct symbol *sym, void *d)
1854 {
1855   struct decode_compound_collector *collector = d;
1856   void **slot;
1857   struct type *t;
1858
1859   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
1860     return 1; /* Continue iterating.  */
1861
1862   t = SYMBOL_TYPE (sym);
1863   CHECK_TYPEDEF (t);
1864   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
1865       && TYPE_CODE (t) != TYPE_CODE_UNION
1866       && TYPE_CODE (t) != TYPE_CODE_NAMESPACE)
1867     return 1; /* Continue iterating.  */
1868
1869   slot = htab_find_slot (collector->unique_syms, sym, INSERT);
1870   if (!*slot)
1871     {
1872       *slot = sym;
1873       VEC_safe_push (symbolp, collector->symbols, sym);
1874     }
1875
1876   return 1; /* Continue iterating.  */
1877 }
1878
1879 /* Return the symbol corresponding to the substring of *ARGPTR ending
1880    at P, allowing whitespace.  Also, advance *ARGPTR past the symbol
1881    name in question, the compound object separator ("::" or "."), and
1882    whitespace.  Note that *ARGPTR is changed whether or not the
1883    this call finds anything (i.e we return NULL).  As an
1884    example, say ARGPTR is "AAA::inA::fun" and P is "::inA::fun".  */
1885
1886 static VEC (symbolp) *
1887 lookup_prefix_sym (char **argptr, char *p, VEC (symtab_p) *file_symtabs,
1888                    char **class_name)
1889 {
1890   char *p1;
1891   char *copy;
1892   int ix;
1893   struct symtab *elt;
1894   struct decode_compound_collector collector;
1895   struct cleanup *outer;
1896   struct cleanup *cleanup;
1897   struct block *search_block;
1898
1899   /* Extract the class name.  */
1900   p1 = p;
1901   while (p != *argptr && p[-1] == ' ')
1902     --p;
1903   copy = (char *) xmalloc (p - *argptr + 1);
1904   memcpy (copy, *argptr, p - *argptr);
1905   copy[p - *argptr] = 0;
1906   *class_name = copy;
1907   outer = make_cleanup (xfree, copy);
1908
1909   /* Discard the class name from the argptr.  */
1910   p = p1 + (p1[0] == ':' ? 2 : 1);
1911   p = skip_spaces (p);
1912   *argptr = p;
1913
1914   /* At this point p1->"::inA::fun", p->"inA::fun" copy->"AAA",
1915      argptr->"inA::fun".  */
1916
1917   collector.symbols = NULL;
1918   make_cleanup (VEC_cleanup (symbolp), &collector.symbols);
1919
1920   collector.unique_syms = htab_create_alloc (1, htab_hash_pointer,
1921                                              htab_eq_pointer, NULL,
1922                                              xcalloc, xfree);
1923   cleanup = make_cleanup_htab_delete (collector.unique_syms);
1924
1925   for (ix = 0; VEC_iterate (symtab_p, file_symtabs, ix, elt); ++ix)
1926     {
1927       if (elt == NULL)
1928         {
1929           iterate_over_all_matching_symtabs (copy, STRUCT_DOMAIN,
1930                                              collect_one_symbol, &collector,
1931                                              NULL, 0);
1932           iterate_over_all_matching_symtabs (copy, VAR_DOMAIN,
1933                                              collect_one_symbol, &collector,
1934                                              NULL, 0);
1935         }
1936       else
1937         {
1938           struct block *search_block;
1939
1940           /* Program spaces that are executing startup should have
1941              been filtered out earlier.  */
1942           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
1943           set_current_program_space (SYMTAB_PSPACE (elt));
1944           search_block = get_search_block (elt);
1945           LA_ITERATE_OVER_SYMBOLS (search_block, copy, STRUCT_DOMAIN,
1946                                    collect_one_symbol, &collector);
1947           LA_ITERATE_OVER_SYMBOLS (search_block, copy, VAR_DOMAIN,
1948                                    collect_one_symbol, &collector);
1949         }
1950     }
1951
1952   do_cleanups (cleanup);
1953   discard_cleanups (outer);
1954   return collector.symbols;
1955 }
1956
1957 /* A qsort comparison function for symbols.  The resulting order does
1958    not actually matter; we just need to be able to sort them so that
1959    symbols with the same program space end up next to each other.  */
1960
1961 static int
1962 compare_symbols (const void *a, const void *b)
1963 {
1964   struct symbol * const *sa = a;
1965   struct symbol * const *sb = b;
1966   uintptr_t uia, uib;
1967
1968   uia = (uintptr_t) SYMTAB_PSPACE (SYMBOL_SYMTAB (*sa));
1969   uib = (uintptr_t) SYMTAB_PSPACE (SYMBOL_SYMTAB (*sb));
1970
1971   if (uia < uib)
1972     return -1;
1973   if (uia > uib)
1974     return 1;
1975
1976   uia = (uintptr_t) *sa;
1977   uib = (uintptr_t) *sb;
1978
1979   if (uia < uib)
1980     return -1;
1981   if (uia > uib)
1982     return 1;
1983
1984   return 0;
1985 }
1986
1987 /* Look for all the matching instances of each symbol in NAMES.  Only
1988    instances from PSPACE are considered; other program spaces are
1989    handled by our caller.  If PSPACE is NULL, then all program spaces
1990    are considered.  Results are stored into INFO.  */
1991
1992 static void
1993 add_all_symbol_names_from_pspace (struct collect_info *info,
1994                                   struct program_space *pspace,
1995                                   VEC (const_char_ptr) *names)
1996 {
1997   int ix;
1998   const char *iter;
1999
2000   for (ix = 0; VEC_iterate (const_char_ptr, names, ix, iter); ++ix)
2001     add_matching_symbols_to_info (iter, info, pspace);
2002 }
2003
2004 static void
2005 find_superclass_methods (VEC (typep) *superclasses,
2006                          const char *name,
2007                          VEC (const_char_ptr) **result_names)
2008 {
2009   int old_len = VEC_length (const_char_ptr, *result_names);
2010   VEC (typep) *iter_classes;
2011   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2012
2013   iter_classes = superclasses;
2014   while (1)
2015     {
2016       VEC (typep) *new_supers = NULL;
2017       int ix;
2018       struct type *t;
2019
2020       make_cleanup (VEC_cleanup (typep), &new_supers);
2021       for (ix = 0; VEC_iterate (typep, iter_classes, ix, t); ++ix)
2022         find_methods (t, name, result_names, &new_supers);
2023
2024       if (VEC_length (const_char_ptr, *result_names) != old_len
2025           || VEC_empty (typep, new_supers))
2026         break;
2027
2028       iter_classes = new_supers;
2029     }
2030
2031   do_cleanups (cleanup);
2032 }
2033
2034 /* This finds the method COPY in the class whose type is given by one
2035    of the symbols in SYM_CLASSES.  */
2036
2037 static struct symtabs_and_lines
2038 find_method (struct linespec_state *self, char *saved_arg,
2039              char *copy, const char *class_name, VEC (symbolp) *sym_classes)
2040 {
2041   char *canon;
2042   struct symbol *sym;
2043   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2044   int ix;
2045   int last_result_len;
2046   VEC (typep) *superclass_vec;
2047   VEC (const_char_ptr) *result_names;
2048   struct collect_info info;
2049   char *name_iter;
2050
2051   /* NAME is typed by the user: it needs to be canonicalized before
2052      searching the symbol tables.  */
2053   canon = cp_canonicalize_string_no_typedefs (copy);
2054   if (canon != NULL)
2055     {
2056       copy = canon;
2057       make_cleanup (xfree, copy);
2058     }
2059
2060   /* Sort symbols so that symbols with the same program space are next
2061      to each other.  */
2062   qsort (VEC_address (symbolp, sym_classes),
2063          VEC_length (symbolp, sym_classes),
2064          sizeof (symbolp),
2065          compare_symbols);
2066
2067   info.state = self;
2068   info.result.sals = NULL;
2069   info.result.nelts = 0;
2070
2071   /* Iterate over all the types, looking for the names of existing
2072      methods matching COPY.  If we cannot find a direct method in a
2073      given program space, then we consider inherited methods; this is
2074      not ideal (ideal would be to respect C++ hiding rules), but it
2075      seems good enough and is what GDB has historically done.  We only
2076      need to collect the names because later we find all symbols with
2077      those names.  This loop is written in a somewhat funny way
2078      because we collect data across the program space before deciding
2079      what to do.  */
2080   superclass_vec = NULL;
2081   make_cleanup (VEC_cleanup (typep), &superclass_vec);
2082   result_names = NULL;
2083   make_cleanup (VEC_cleanup (const_char_ptr), &result_names);
2084   last_result_len = 0;
2085   for (ix = 0; VEC_iterate (symbolp, sym_classes, ix, sym); ++ix)
2086     {
2087       struct type *t;
2088       struct program_space *pspace;
2089
2090       /* Program spaces that are executing startup should have
2091          been filtered out earlier.  */
2092       gdb_assert (!SYMTAB_PSPACE (SYMBOL_SYMTAB (sym))->executing_startup);
2093       pspace = SYMTAB_PSPACE (SYMBOL_SYMTAB (sym));
2094       set_current_program_space (pspace);
2095       t = check_typedef (SYMBOL_TYPE (sym));
2096       find_methods (t, copy, &result_names, &superclass_vec);
2097
2098       /* Handle all items from a single program space at once; and be
2099          sure not to miss the last batch.  */
2100       if (ix == VEC_length (symbolp, sym_classes) - 1
2101           || (pspace
2102               != SYMTAB_PSPACE (SYMBOL_SYMTAB (VEC_index (symbolp, sym_classes,
2103                                                           ix + 1)))))
2104         {
2105           /* If we did not find a direct implementation anywhere in
2106              this program space, consider superclasses.  */
2107           if (VEC_length (const_char_ptr, result_names) == last_result_len)
2108             find_superclass_methods (superclass_vec, copy, &result_names);
2109
2110           /* We have a list of candidate symbol names, so now we
2111              iterate over the symbol tables looking for all
2112              matches in this pspace.  */
2113           add_all_symbol_names_from_pspace (&info, pspace, result_names);
2114
2115           VEC_truncate (typep, superclass_vec, 0);
2116           last_result_len = VEC_length (const_char_ptr, result_names);
2117         }
2118     }
2119
2120   if (info.result.nelts > 0)
2121     {
2122       if (self->canonical)
2123         {
2124           self->canonical->pre_expanded = 1;
2125           if (self->user_filename)
2126             self->canonical->addr_string
2127               = xstrprintf ("%s:%s", self->user_filename, saved_arg);
2128           else
2129             self->canonical->addr_string = xstrdup (saved_arg);
2130         }
2131
2132       do_cleanups (cleanup);
2133
2134       return info.result;
2135     }
2136
2137   if (copy[0] == '~')
2138     cplusplus_error (saved_arg,
2139                      "the class `%s' does not have destructor defined\n",
2140                      class_name);
2141   else
2142     cplusplus_error (saved_arg,
2143                      "the class %s does not have any method named %s\n",
2144                      class_name, copy);
2145 }
2146
2147 \f
2148
2149 /* This object is used when collecting all matching symtabs.  */
2150
2151 struct symtab_collector
2152 {
2153   /* The result vector of symtabs.  */
2154   VEC (symtab_p) *symtabs;
2155
2156   /* This is used to ensure the symtabs are unique.  */
2157   htab_t symtab_table;
2158 };
2159
2160 /* Callback for iterate_over_symtabs.  */
2161
2162 static int
2163 add_symtabs_to_list (struct symtab *symtab, void *d)
2164 {
2165   struct symtab_collector *data = d;
2166   void **slot;
2167
2168   slot = htab_find_slot (data->symtab_table, symtab, INSERT);
2169   if (!*slot)
2170     {
2171       *slot = symtab;
2172       VEC_safe_push (symtab_p, data->symtabs, symtab);
2173     }
2174
2175   return 0;
2176 }
2177
2178 /* Given a file name, return a VEC of all matching symtabs.  */
2179
2180 static VEC (symtab_p) *
2181 collect_symtabs_from_filename (const char *file)
2182 {
2183   struct symtab_collector collector;
2184   struct cleanup *cleanups;
2185   struct program_space *pspace;
2186
2187   collector.symtabs = NULL;
2188   collector.symtab_table = htab_create (1, htab_hash_pointer, htab_eq_pointer,
2189                                         NULL);
2190   cleanups = make_cleanup_htab_delete (collector.symtab_table);
2191
2192   /* Find that file's data.  */
2193   ALL_PSPACES (pspace)
2194   {
2195     if (pspace->executing_startup)
2196       continue;
2197
2198     set_current_program_space (pspace);
2199     iterate_over_symtabs (file, add_symtabs_to_list, &collector);
2200   }
2201
2202   do_cleanups (cleanups);
2203   return collector.symtabs;
2204 }
2205
2206 /* Return all the symtabs associated to the filename given by the
2207    substring of *ARGPTR ending at P, and advance ARGPTR past that
2208    filename.  */
2209
2210 static VEC (symtab_p) *
2211 symtabs_from_filename (char **argptr, char *p, int is_quote_enclosed,
2212                        char **user_filename)
2213 {
2214   char *p1;
2215   char *copy;
2216   struct cleanup *outer;
2217   VEC (symtab_p) *result;
2218   
2219   p1 = p;
2220   while (p != *argptr && p[-1] == ' ')
2221     --p;
2222   if ((*p == '"') && is_quote_enclosed)
2223     --p;
2224   copy = xmalloc (p - *argptr + 1);
2225   outer = make_cleanup (xfree, copy);
2226   memcpy (copy, *argptr, p - *argptr);
2227   /* It may have the ending quote right after the file name.  */
2228   if ((is_quote_enclosed && copy[p - *argptr - 1] == '"')
2229       || copy[p - *argptr - 1] == '\'')
2230     copy[p - *argptr - 1] = 0;
2231   else
2232     copy[p - *argptr] = 0;
2233
2234   result = collect_symtabs_from_filename (copy);
2235
2236   if (VEC_empty (symtab_p, result))
2237     {
2238       if (!have_full_symbols () && !have_partial_symbols ())
2239         throw_error (NOT_FOUND_ERROR,
2240                      _("No symbol table is loaded.  "
2241                        "Use the \"file\" command."));
2242       throw_error (NOT_FOUND_ERROR, _("No source file named %s."), copy);
2243     }
2244
2245   /* Discard the file name from the arg.  */
2246   if (*p1 == '\0')
2247     *argptr = p1;
2248   else
2249     *argptr = skip_spaces (p1 + 1);
2250
2251   discard_cleanups (outer);
2252   *user_filename = copy;
2253   return result;
2254 }
2255
2256 /* A callback used by iterate_over_all_matching_symtabs that collects
2257    symbols for find_function_symbols.  */
2258
2259 static int
2260 collect_function_symbols (struct symbol *sym, void *arg)
2261 {
2262   VEC (symbolp) **syms = arg;
2263
2264   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
2265     VEC_safe_push (symbolp, *syms, sym);
2266
2267   return 1; /* Continue iterating.  */
2268 }
2269
2270 /* Look up a function symbol in *ARGPTR.  If found, advance *ARGPTR
2271    and return the symbol.  If not found, return NULL.  */
2272
2273 static VEC (symbolp) *
2274 find_function_symbols (char **argptr, char *p, int is_quote_enclosed,
2275                        char **user_function)
2276 {
2277   char *p1;
2278   char *copy;
2279   VEC (symbolp) *result = NULL;
2280
2281   p1 = p;
2282   while (p != *argptr && p[-1] == ' ')
2283     --p;
2284   if ((*p == '"') && is_quote_enclosed)
2285     --p;
2286   copy = (char *) xmalloc (p - *argptr + 1);
2287   *user_function = copy;
2288   memcpy (copy, *argptr, p - *argptr);
2289   /* It may have the ending quote right after the file name.  */
2290   if ((is_quote_enclosed && copy[p - *argptr - 1] == '"')
2291       || copy[p - *argptr - 1] == '\'')
2292     copy[p - *argptr - 1] = 0;
2293   else
2294     copy[p - *argptr] = 0;
2295
2296   iterate_over_all_matching_symtabs (copy, VAR_DOMAIN,
2297                                      collect_function_symbols, &result, NULL,
2298                                      0);
2299
2300   if (VEC_empty (symbolp, result))
2301     VEC_free (symbolp, result);
2302   else
2303     {
2304       /* Discard the file name from the arg.  */
2305       *argptr = skip_spaces (p1 + 1);
2306     }
2307
2308   return result;
2309 }
2310
2311 \f
2312
2313 /* A helper for decode_all_digits that handles the 'list_mode' case.  */
2314
2315 static void
2316 decode_digits_list_mode (struct linespec_state *self,
2317                          struct symtabs_and_lines *values,
2318                          struct symtab_and_line val)
2319 {
2320   int ix;
2321   struct symtab *elt;
2322
2323   gdb_assert (self->list_mode);
2324
2325   for (ix = 0; VEC_iterate (symtab_p, self->file_symtabs, ix, elt); ++ix)
2326     {
2327       /* The logic above should ensure this.  */
2328       gdb_assert (elt != NULL);
2329
2330       set_current_program_space (SYMTAB_PSPACE (elt));
2331
2332       /* Simplistic search just for the list command.  */
2333       val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
2334       if (val.symtab == NULL)
2335         val.symtab = elt;
2336       val.pspace = SYMTAB_PSPACE (elt);
2337       val.pc = 0;
2338       val.explicit_line = 1;
2339
2340       add_sal_to_sals (self, values, &val, NULL);
2341     }
2342 }
2343
2344 /* A helper for decode_all_digits that iterates over the symtabs,
2345    adding lines to the VEC.  */
2346
2347 static void
2348 decode_digits_ordinary (struct linespec_state *self,
2349                         int line,
2350                         struct symtabs_and_lines *sals,
2351                         struct linetable_entry **best_entry)
2352 {
2353   int ix;
2354   struct symtab *elt;
2355
2356   for (ix = 0; VEC_iterate (symtab_p, self->file_symtabs, ix, elt); ++ix)
2357     {
2358       int i;
2359       VEC (CORE_ADDR) *pcs;
2360       CORE_ADDR pc;
2361
2362       /* The logic above should ensure this.  */
2363       gdb_assert (elt != NULL);
2364
2365       set_current_program_space (SYMTAB_PSPACE (elt));
2366
2367       pcs = find_pcs_for_symtab_line (elt, line, best_entry);
2368       for (i = 0; VEC_iterate (CORE_ADDR, pcs, i, pc); ++i)
2369         {
2370           struct symtab_and_line sal;
2371
2372           init_sal (&sal);
2373           sal.pspace = SYMTAB_PSPACE (elt);
2374           sal.symtab = elt;
2375           sal.line = line;
2376           sal.pc = pc;
2377           add_sal_to_sals_basic (sals, &sal);
2378         }
2379
2380       VEC_free (CORE_ADDR, pcs);
2381     }
2382 }
2383
2384 /* This decodes a line where the argument is all digits (possibly
2385    preceded by a sign).  Q should point to the end of those digits;
2386    the other arguments are as usual.  */
2387
2388 static struct symtabs_and_lines
2389 decode_all_digits (struct linespec_state *self,
2390                    char **argptr,
2391                    char *q)
2392 {
2393   struct symtabs_and_lines values;
2394   struct symtab_and_line val;
2395   int use_default = 0;
2396   char *saved_arg = *argptr;
2397
2398   enum sign
2399     {
2400       none, plus, minus
2401     }
2402   sign = none;
2403
2404   init_sal (&val);
2405   values.sals = NULL;
2406   values.nelts = 0;
2407
2408   /* This is where we need to make sure that we have good defaults.
2409      We must guarantee that this section of code is never executed
2410      when we are called with just a function name, since
2411      set_default_source_symtab_and_line uses
2412      select_source_symtab that calls us with such an argument.  */
2413
2414   if (VEC_length (symtab_p, self->file_symtabs) == 1
2415       && VEC_index (symtab_p, self->file_symtabs, 0) == NULL)
2416     {
2417       set_current_program_space (self->program_space);
2418
2419       /* Make sure we have at least a default source file.  */
2420       set_default_source_symtab_and_line ();
2421       initialize_defaults (&self->default_symtab, &self->default_line);
2422       VEC_pop (symtab_p, self->file_symtabs);
2423       VEC_free (symtab_p, self->file_symtabs);
2424       self->file_symtabs
2425         = collect_symtabs_from_filename (self->default_symtab->filename);
2426       use_default = 1;
2427     }
2428
2429   if (**argptr == '+')
2430     sign = plus, (*argptr)++;
2431   else if (**argptr == '-')
2432     sign = minus, (*argptr)++;
2433   val.line = atoi (*argptr);
2434   switch (sign)
2435     {
2436     case plus:
2437       if (q == *argptr)
2438         val.line = 5;
2439       if (use_default)
2440         val.line = self->default_line + val.line;
2441       break;
2442     case minus:
2443       if (q == *argptr)
2444         val.line = 15;
2445       if (use_default)
2446         val.line = self->default_line - val.line;
2447       else
2448         val.line = 1;
2449       break;
2450     case none:
2451       break;            /* No need to adjust val.line.  */
2452     }
2453
2454   *argptr = skip_spaces (q);
2455
2456   if (self->list_mode)
2457     decode_digits_list_mode (self, &values, val);
2458   else
2459     {
2460       struct linetable_entry *best_entry = NULL;
2461       int *filter;
2462       struct block **blocks;
2463       struct cleanup *cleanup;
2464       struct symtabs_and_lines intermediate_results;
2465       int i, j;
2466
2467       intermediate_results.sals = NULL;
2468       intermediate_results.nelts = 0;
2469
2470       decode_digits_ordinary (self, val.line, &intermediate_results,
2471                               &best_entry);
2472       if (intermediate_results.nelts == 0 && best_entry != NULL)
2473         decode_digits_ordinary (self, best_entry->line, &intermediate_results,
2474                                 &best_entry);
2475
2476       cleanup = make_cleanup (xfree, intermediate_results.sals);
2477
2478       /* For optimized code, compiler can scatter one source line
2479          accross disjoint ranges of PC values, even when no duplicate
2480          functions or inline functions are involved.  For example,
2481          'for (;;)' inside non-template non-inline non-ctor-or-dtor
2482          function can result in two PC ranges.  In this case, we don't
2483          want to set breakpoint on first PC of each range.  To filter
2484          such cases, we use containing blocks -- for each PC found
2485          above we see if there are other PCs that are in the same
2486          block.  If yes, the other PCs are filtered out.  */
2487
2488       filter = xmalloc (intermediate_results.nelts * sizeof (int));
2489       make_cleanup (xfree, filter);
2490       blocks = xmalloc (intermediate_results.nelts * sizeof (struct block *));
2491       make_cleanup (xfree, blocks);
2492
2493       for (i = 0; i < intermediate_results.nelts; ++i)
2494         {
2495           set_current_program_space (intermediate_results.sals[i].pspace);
2496
2497           filter[i] = 1;
2498           blocks[i] = block_for_pc_sect (intermediate_results.sals[i].pc,
2499                                          intermediate_results.sals[i].section);
2500         }
2501
2502       for (i = 0; i < intermediate_results.nelts; ++i)
2503         {
2504           if (blocks[i] != NULL)
2505             for (j = i + 1; j < intermediate_results.nelts; ++j)
2506               {
2507                 if (blocks[j] == blocks[i])
2508                   {
2509                     filter[j] = 0;
2510                     break;
2511                   }
2512               }
2513         }
2514
2515       for (i = 0; i < intermediate_results.nelts; ++i)
2516         if (filter[i])
2517           {
2518             struct symbol *sym = (blocks[i]
2519                                   ? block_containing_function (blocks[i])
2520                                   : NULL);
2521
2522             if (self->funfirstline)
2523               skip_prologue_sal (&intermediate_results.sals[i]);
2524             /* Make sure the line matches the request, not what was
2525                found.  */
2526             intermediate_results.sals[i].line = val.line;
2527             add_sal_to_sals (self, &values, &intermediate_results.sals[i],
2528                              sym ? SYMBOL_NATURAL_NAME (sym) : NULL);
2529           }
2530
2531       do_cleanups (cleanup);
2532     }
2533
2534   if (values.nelts == 0)
2535     {
2536       if (self->user_filename)
2537         throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
2538                      val.line, self->user_filename);
2539       else
2540         throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
2541                      val.line);
2542     }
2543
2544   if (self->canonical)
2545     {
2546       char *copy = savestring (saved_arg, q - saved_arg);
2547
2548       self->canonical->pre_expanded = 1;
2549       gdb_assert (self->user_filename || use_default);
2550       self->canonical->addr_string
2551         = xstrprintf ("%s:%s", (self->user_filename
2552                                 ? self->user_filename
2553                                 : self->default_symtab->filename),
2554                       copy);
2555       xfree (copy);
2556     }
2557
2558   return values;
2559 }
2560
2561 \f
2562
2563 /* Decode a linespec starting with a dollar sign.  */
2564
2565 static struct symtabs_and_lines
2566 decode_dollar (struct linespec_state *self, char *copy)
2567 {
2568   LONGEST valx;
2569   int index = 0;
2570   struct symtabs_and_lines values;
2571   struct symtab_and_line val;
2572   char *p;
2573   struct symbol *sym;
2574   struct minimal_symbol *msymbol;
2575   int ix;
2576   struct symtab *elt;
2577
2578   p = (copy[1] == '$') ? copy + 2 : copy + 1;
2579   while (*p >= '0' && *p <= '9')
2580     p++;
2581   if (!*p)              /* Reached end of token without hitting non-digit.  */
2582     {
2583       /* We have a value history reference.  */
2584       struct value *val_history;
2585
2586       sscanf ((copy[1] == '$') ? copy + 2 : copy + 1, "%d", &index);
2587       val_history = access_value_history ((copy[1] == '$') ? -index : index);
2588       if (TYPE_CODE (value_type (val_history)) != TYPE_CODE_INT)
2589         error (_("History values used in line "
2590                  "specs must have integer values."));
2591       valx = value_as_long (val_history);
2592     }
2593   else
2594     {
2595       /* Not all digits -- may be user variable/function or a
2596          convenience variable.  */
2597
2598       volatile struct gdb_exception exc;
2599
2600       /* Avoid "may be used uninitialized" warning.  */
2601       values.sals = NULL;
2602       values.nelts = 0;
2603
2604       TRY_CATCH (exc, RETURN_MASK_ERROR)
2605         {
2606           values = decode_variable (self, copy);
2607         }
2608
2609       if (exc.reason == 0)
2610         return values;
2611
2612       if (exc.error != NOT_FOUND_ERROR)
2613         throw_exception (exc);
2614
2615       /* Not a user variable or function -- must be convenience variable.  */
2616       if (!get_internalvar_integer (lookup_internalvar (copy + 1), &valx))
2617         error (_("Convenience variables used in line "
2618                  "specs must have integer values."));
2619     }
2620
2621   init_sal (&val);
2622
2623   values.sals = NULL;
2624   values.nelts = 0;
2625
2626   for (ix = 0; VEC_iterate (symtab_p, self->file_symtabs, ix, elt); ++ix)
2627     {
2628       if (elt == NULL)
2629         {
2630           elt = self->default_symtab;
2631           set_current_program_space (self->program_space);
2632         }
2633       else
2634         set_current_program_space (SYMTAB_PSPACE (elt));
2635
2636       /* Either history value or convenience value from above, in valx.  */
2637       val.symtab = elt;
2638       val.line = valx;
2639       val.pc = 0;
2640       val.pspace = elt ? SYMTAB_PSPACE (elt) : current_program_space;
2641
2642       add_sal_to_sals (self, &values, &val, NULL);
2643     }
2644
2645   if (self->canonical)
2646     {
2647       self->canonical->pre_expanded = 1;
2648       if (self->user_filename)
2649         self->canonical->addr_string = xstrprintf ("%s:%s",
2650                                                    self->user_filename, copy);
2651       else
2652         self->canonical->addr_string = xstrdup (copy);
2653     }
2654
2655   return values;
2656 }
2657
2658 \f
2659
2660 /* A helper for decode_line_1 that tries to find a label.  The label
2661    is searched for in the current block.
2662    FUNCTION_SYMBOLS is a list of the enclosing functions; or NULL if none
2663    specified.
2664    COPY is the name of the label to find.
2665    CANONICAL is the same as the "canonical" argument to decode_line_1.
2666    RESULT is a pointer to a symtabs_and_lines structure which will be
2667    filled in on success.
2668    This function returns 1 if a label was found, 0 otherwise.  */
2669
2670 static int
2671 decode_label (struct linespec_state *self,
2672               VEC (symbolp) *function_symbols, char *copy,
2673               struct symtabs_and_lines *result)
2674 {
2675   struct symbol *fn_sym;
2676   int ix;
2677
2678   if (function_symbols == NULL)
2679     {
2680       struct block *block;
2681       struct symbol *sym;
2682       struct symtab_and_line sal;
2683       struct symtabs_and_lines values;
2684
2685       values.nelts = 0;
2686       values.sals = NULL;
2687
2688       set_current_program_space (self->program_space);
2689       block = get_search_block (NULL);
2690
2691       for (;
2692            block && !BLOCK_FUNCTION (block);
2693            block = BLOCK_SUPERBLOCK (block))
2694         ;
2695       if (!block)
2696         return 0;
2697       fn_sym = BLOCK_FUNCTION (block);
2698
2699       sym = lookup_symbol (copy, block, LABEL_DOMAIN, 0);
2700
2701       if (sym == NULL)
2702         return 0;
2703
2704       symbol_to_sal (&sal, self->funfirstline, sym);
2705       add_sal_to_sals (self, &values, &sal,
2706                        SYMBOL_NATURAL_NAME (fn_sym));
2707
2708       if (self->canonical)
2709         {
2710           self->canonical->special_display = 1;
2711           self->canonical->addr_string
2712             = xstrprintf ("%s:%s", SYMBOL_NATURAL_NAME (fn_sym),
2713                           copy);
2714         }
2715
2716       *result = values;
2717
2718       return 1;
2719     }
2720
2721   result->sals = NULL;
2722   result->nelts = 0;
2723
2724   for (ix = 0; VEC_iterate (symbolp, function_symbols, ix, fn_sym); ++ix)
2725     {
2726       struct block *block;
2727       struct symbol *sym;
2728
2729       set_current_program_space (SYMTAB_PSPACE (SYMBOL_SYMTAB (fn_sym)));
2730       block = SYMBOL_BLOCK_VALUE (fn_sym);
2731       sym = lookup_symbol (copy, block, LABEL_DOMAIN, 0);
2732
2733       if (sym != NULL)
2734         {
2735           struct symtab_and_line sal;
2736           char *symname;
2737
2738           symbol_to_sal (&sal, self->funfirstline, sym);
2739           symname = xstrprintf ("%s:%s",
2740                                 SYMBOL_NATURAL_NAME (fn_sym),
2741                                 SYMBOL_NATURAL_NAME (sym));
2742           add_sal_to_sals (self, result, &sal, symname);
2743           xfree (symname);
2744         }
2745     }
2746
2747   if (self->canonical && result->nelts > 0)
2748     {
2749       self->canonical->pre_expanded = 1;
2750       self->canonical->special_display = 1;
2751
2752       gdb_assert (self->user_function);
2753       self->canonical->addr_string
2754         = xstrprintf ("%s:%s", self->user_function, copy);
2755     }
2756
2757   return result->nelts > 0;
2758 }
2759
2760 /* A callback used to possibly add a symbol to the results.  */
2761
2762 static int
2763 collect_symbols (struct symbol *sym, void *data)
2764 {
2765   struct collect_info *info = data;
2766   struct symtab_and_line sal;
2767
2768   if (symbol_to_sal (&sal, info->state->funfirstline, sym)
2769       && maybe_add_address (info->state->addr_set,
2770                             SYMTAB_PSPACE (SYMBOL_SYMTAB (sym)),
2771                             sal.pc))
2772     add_sal_to_sals (info->state, &info->result, &sal,
2773                      SYMBOL_NATURAL_NAME (sym));
2774
2775   return 1; /* Continue iterating.  */
2776 }
2777
2778 /* We've found a minimal symbol MSYMBOL to associate with our
2779    linespec; add it to the result symtabs_and_lines.  */
2780
2781 static void
2782 minsym_found (struct linespec_state *self, struct objfile *objfile,
2783               struct minimal_symbol *msymbol,
2784               struct symtabs_and_lines *result)
2785 {
2786   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2787   CORE_ADDR pc;
2788   struct symtab_and_line sal;
2789
2790   sal = find_pc_sect_line (SYMBOL_VALUE_ADDRESS (msymbol),
2791                            (struct obj_section *) 0, 0);
2792   sal.section = SYMBOL_OBJ_SECTION (msymbol);
2793
2794   /* The minimal symbol might point to a function descriptor;
2795      resolve it to the actual code address instead.  */
2796   pc = gdbarch_convert_from_func_ptr_addr (gdbarch, sal.pc, &current_target);
2797   if (pc != sal.pc)
2798     sal = find_pc_sect_line (pc, NULL, 0);
2799
2800   if (self->funfirstline)
2801     skip_prologue_sal (&sal);
2802
2803   if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
2804     add_sal_to_sals (self, result, &sal, SYMBOL_NATURAL_NAME (msymbol));
2805 }
2806
2807 /* A helper struct which just holds a minimal symbol and the object
2808    file from which it came.  */
2809
2810 typedef struct minsym_and_objfile
2811 {
2812   struct minimal_symbol *minsym;
2813   struct objfile *objfile;
2814 } minsym_and_objfile_d;
2815
2816 DEF_VEC_O (minsym_and_objfile_d);
2817
2818 /* A helper struct to pass some data through
2819    iterate_over_minimal_symbols.  */
2820
2821 struct collect_minsyms
2822 {
2823   /* The objfile we're examining.  */
2824   struct objfile *objfile;
2825
2826   /* The funfirstline setting from the initial call.  */
2827   int funfirstline;
2828
2829   /* The list_mode setting from the initial call.  */
2830   int list_mode;
2831
2832   /* The resulting symbols.  */
2833   VEC (minsym_and_objfile_d) *msyms;
2834 };
2835
2836 /* A helper function to classify a minimal_symbol_type according to
2837    priority.  */
2838
2839 static int
2840 classify_mtype (enum minimal_symbol_type t)
2841 {
2842   switch (t)
2843     {
2844     case mst_file_text:
2845     case mst_file_data:
2846     case mst_file_bss:
2847       /* Intermediate priority.  */
2848       return 1;
2849
2850     case mst_solib_trampoline:
2851       /* Lowest priority.  */
2852       return 2;
2853
2854     default:
2855       /* Highest priority.  */
2856       return 0;
2857     }
2858 }
2859
2860 /* Callback for qsort that sorts symbols by priority.  */
2861
2862 static int
2863 compare_msyms (const void *a, const void *b)
2864 {
2865   const minsym_and_objfile_d *moa = a;
2866   const minsym_and_objfile_d *mob = b;
2867   enum minimal_symbol_type ta = MSYMBOL_TYPE (moa->minsym);
2868   enum minimal_symbol_type tb = MSYMBOL_TYPE (mob->minsym);
2869
2870   return classify_mtype (ta) - classify_mtype (tb);
2871 }
2872
2873 /* Callback for iterate_over_minimal_symbols that adds the symbol to
2874    the result.  */
2875
2876 static void
2877 add_minsym (struct minimal_symbol *minsym, void *d)
2878 {
2879   struct collect_minsyms *info = d;
2880   minsym_and_objfile_d mo;
2881
2882   /* Exclude data symbols when looking for breakpoint locations.   */
2883   if (!info->list_mode)
2884     switch (minsym->type)
2885       {
2886         case mst_slot_got_plt:
2887         case mst_data:
2888         case mst_bss:
2889         case mst_abs:
2890         case mst_file_data:
2891         case mst_file_bss:
2892           {
2893             /* Make sure this minsym is not a function descriptor
2894                before we decide to discard it.  */
2895             struct gdbarch *gdbarch = info->objfile->gdbarch;
2896             CORE_ADDR addr = gdbarch_convert_from_func_ptr_addr
2897                                (gdbarch, SYMBOL_VALUE_ADDRESS (minsym),
2898                                 &current_target);
2899
2900             if (addr == SYMBOL_VALUE_ADDRESS (minsym))
2901               return;
2902           }
2903       }
2904
2905   mo.minsym = minsym;
2906   mo.objfile = info->objfile;
2907   VEC_safe_push (minsym_and_objfile_d, info->msyms, &mo);
2908 }
2909
2910 /* Search minimal symbols in all objfiles for NAME.  If SEARCH_PSPACE
2911    is not NULL, the search is restricted to just that program
2912    space.  */
2913
2914 static void
2915 search_minsyms_for_name (struct collect_info *info, const char *name,
2916                          struct program_space *search_pspace)
2917 {
2918   struct objfile *objfile;
2919   struct program_space *pspace;
2920
2921   ALL_PSPACES (pspace)
2922   {
2923     struct collect_minsyms local;
2924     struct cleanup *cleanup;
2925
2926     if (search_pspace != NULL && search_pspace != pspace)
2927       continue;
2928     if (pspace->executing_startup)
2929       continue;
2930
2931     set_current_program_space (pspace);
2932
2933     memset (&local, 0, sizeof (local));
2934     local.funfirstline = info->state->funfirstline;
2935     local.list_mode = info->state->list_mode;
2936
2937     cleanup = make_cleanup (VEC_cleanup (minsym_and_objfile_d),
2938                             &local.msyms);
2939
2940     ALL_OBJFILES (objfile)
2941     {
2942       local.objfile = objfile;
2943       iterate_over_minimal_symbols (objfile, name, add_minsym, &local);
2944     }
2945
2946     if (!VEC_empty (minsym_and_objfile_d, local.msyms))
2947       {
2948         int classification;
2949         int ix;
2950         minsym_and_objfile_d *item;
2951
2952         qsort (VEC_address (minsym_and_objfile_d, local.msyms),
2953                VEC_length (minsym_and_objfile_d, local.msyms),
2954                sizeof (minsym_and_objfile_d),
2955                compare_msyms);
2956
2957         /* Now the minsyms are in classification order.  So, we walk
2958            over them and process just the minsyms with the same
2959            classification as the very first minsym in the list.  */
2960         item = VEC_index (minsym_and_objfile_d, local.msyms, 0);
2961         classification = classify_mtype (MSYMBOL_TYPE (item->minsym));
2962
2963         for (ix = 0;
2964              VEC_iterate (minsym_and_objfile_d, local.msyms, ix, item);
2965              ++ix)
2966           {
2967             if (classify_mtype (MSYMBOL_TYPE (item->minsym)) != classification)
2968               break;
2969
2970             minsym_found (info->state, item->objfile, item->minsym,
2971                           &info->result);
2972           }
2973       }
2974
2975     do_cleanups (cleanup);
2976   }
2977 }
2978
2979 /* A helper function to add all symbols matching NAME to INFO.  If
2980    PSPACE is not NULL, the search is restricted to just that program
2981    space.  */
2982
2983 static void
2984 add_matching_symbols_to_info (const char *name,
2985                               struct collect_info *info,
2986                               struct program_space *pspace)
2987 {
2988   int ix;
2989   struct symtab *elt;
2990
2991   for (ix = 0; VEC_iterate (symtab_p, info->state->file_symtabs, ix, elt); ++ix)
2992     {
2993       struct symbol *sym;
2994
2995       if (elt == NULL)
2996         {
2997           iterate_over_all_matching_symtabs (name, VAR_DOMAIN,
2998                                              collect_symbols, info,
2999                                              pspace, 1);
3000           search_minsyms_for_name (info, name, pspace);
3001         }
3002       else if (pspace == NULL || pspace == SYMTAB_PSPACE (elt))
3003         {
3004           /* Program spaces that are executing startup should have
3005              been filtered out earlier.  */
3006           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
3007           set_current_program_space (SYMTAB_PSPACE (elt));
3008           LA_ITERATE_OVER_SYMBOLS (get_search_block (elt), name,
3009                                    VAR_DOMAIN, collect_symbols,
3010                                    info);
3011         }
3012     }
3013 }
3014
3015 /* Decode a linespec that's a variable.  If FILE_SYMTAB is non-NULL,
3016    look in that symtab's static variables first.  */ 
3017
3018 static struct symtabs_and_lines
3019 decode_variable (struct linespec_state *self, char *copy)
3020 {
3021   struct collect_info info;
3022   const char *lookup_name;
3023   char *canon;
3024   struct cleanup *cleanup;
3025
3026   info.state = self;
3027   info.result.sals = NULL;
3028   info.result.nelts = 0;
3029
3030   cleanup = demangle_for_lookup (copy, current_language->la_language,
3031                                  &lookup_name);
3032   if (current_language->la_language == language_ada)
3033     {
3034       /* In Ada, the symbol lookups are performed using the encoded
3035          name rather than the demangled name.  */
3036       lookup_name = ada_name_for_lookup (copy);
3037       make_cleanup (xfree, (void *) lookup_name);
3038     }
3039
3040   canon = cp_canonicalize_string_no_typedefs (lookup_name);
3041   if (canon != NULL)
3042     {
3043       make_cleanup (xfree, canon);
3044       lookup_name = canon;
3045     }
3046
3047   add_matching_symbols_to_info (lookup_name, &info, NULL);
3048
3049   if (info.result.nelts > 0)
3050     {
3051       if (self->canonical)
3052         {
3053           self->canonical->pre_expanded = 1;
3054           if (self->user_filename)
3055             self->canonical->addr_string
3056               = xstrprintf ("%s:%s", self->user_filename, copy);
3057           else
3058             self->canonical->addr_string = xstrdup (copy);
3059         }
3060       return info.result;
3061     }
3062
3063   if (!have_full_symbols ()
3064       && !have_partial_symbols ()
3065       && !have_minimal_symbols ())
3066     throw_error (NOT_FOUND_ERROR,
3067                  _("No symbol table is loaded.  Use the \"file\" command."));
3068   if (self->user_filename)
3069     throw_error (NOT_FOUND_ERROR, _("Function \"%s\" not defined in \"%s\"."),
3070                  copy, self->user_filename);
3071   else
3072     throw_error (NOT_FOUND_ERROR, _("Function \"%s\" not defined."), copy);
3073 }
3074
3075
3076 \f
3077
3078 /* Now come some functions that are called from multiple places within
3079    decode_line_1.  */
3080
3081 static int
3082 symbol_to_sal (struct symtab_and_line *result,
3083                int funfirstline, struct symbol *sym)
3084 {
3085   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
3086     {
3087       *result = find_function_start_sal (sym, funfirstline);
3088       return 1;
3089     }
3090   else
3091     {
3092       if (SYMBOL_CLASS (sym) == LOC_LABEL && SYMBOL_VALUE_ADDRESS (sym) != 0)
3093         {
3094           init_sal (result);
3095           result->symtab = SYMBOL_SYMTAB (sym);
3096           result->line = SYMBOL_LINE (sym);
3097           result->pc = SYMBOL_VALUE_ADDRESS (sym);
3098           result->pspace = SYMTAB_PSPACE (SYMBOL_SYMTAB (sym));
3099           result->explicit_pc = 1;
3100           return 1;
3101         }
3102       else if (funfirstline)
3103         {
3104           /* Nothing.  */
3105         }
3106       else if (SYMBOL_LINE (sym) != 0)
3107         {
3108           /* We know its line number.  */
3109           init_sal (result);
3110           result->symtab = SYMBOL_SYMTAB (sym);
3111           result->line = SYMBOL_LINE (sym);
3112           result->pspace = SYMTAB_PSPACE (SYMBOL_SYMTAB (sym));
3113           return 1;
3114         }
3115     }
3116
3117   return 0;
3118 }
3119
3120 /* See the comment in linespec.h.  */
3121
3122 void
3123 init_linespec_result (struct linespec_result *lr)
3124 {
3125   memset (lr, 0, sizeof (*lr));
3126 }
3127
3128 /* See the comment in linespec.h.  */
3129
3130 void
3131 destroy_linespec_result (struct linespec_result *ls)
3132 {
3133   int i;
3134   struct linespec_sals *lsal;
3135
3136   xfree (ls->addr_string);
3137   for (i = 0; VEC_iterate (linespec_sals, ls->sals, i, lsal); ++i)
3138     {
3139       xfree (lsal->canonical);
3140       xfree (lsal->sals.sals);
3141     }
3142   VEC_free (linespec_sals, ls->sals);
3143 }
3144
3145 /* Cleanup function for a linespec_result.  */
3146
3147 static void
3148 cleanup_linespec_result (void *a)
3149 {
3150   destroy_linespec_result (a);
3151 }
3152
3153 /* See the comment in linespec.h.  */
3154
3155 struct cleanup *
3156 make_cleanup_destroy_linespec_result (struct linespec_result *ls)
3157 {
3158   return make_cleanup (cleanup_linespec_result, ls);
3159 }