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