Split TRY_CATCH into TRY + CATCH
[external/binutils.git] / gdb / linespec.c
1 /* Parser for linespec for the GNU debugger, GDB.
2
3    Copyright (C) 1986-2015 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 "language.h"
37 #include "interps.h"
38 #include "mi/mi-cmds.h"
39 #include "target.h"
40 #include "arch-utils.h"
41 #include <ctype.h>
42 #include "cli/cli-utils.h"
43 #include "filenames.h"
44 #include "ada-lang.h"
45 #include "stack.h"
46
47 typedef struct symbol *symbolp;
48 DEF_VEC_P (symbolp);
49
50 typedef struct type *typep;
51 DEF_VEC_P (typep);
52
53 /* An address entry is used to ensure that any given location is only
54    added to the result a single time.  It holds an address and the
55    program space from which the address came.  */
56
57 struct address_entry
58 {
59   struct program_space *pspace;
60   CORE_ADDR addr;
61 };
62
63 typedef struct bound_minimal_symbol bound_minimal_symbol_d;
64
65 DEF_VEC_O (bound_minimal_symbol_d);
66
67 /* An enumeration of possible signs for a line offset.  */
68 enum offset_relative_sign
69 {
70   /* No sign  */
71   LINE_OFFSET_NONE,
72
73   /* A plus sign ("+")  */
74   LINE_OFFSET_PLUS,
75
76   /* A minus sign ("-")  */
77   LINE_OFFSET_MINUS,
78
79   /* A special "sign" for unspecified offset.  */
80   LINE_OFFSET_UNKNOWN
81 };
82
83 /* A line offset in a linespec.  */
84
85 struct line_offset
86 {
87   /* Line offset and any specified sign.  */
88   int offset;
89   enum offset_relative_sign sign;
90 };
91
92 /* A linespec.  Elements of this structure are filled in by a parser
93    (either parse_linespec or some other function).  The structure is
94    then converted into SALs by convert_linespec_to_sals.  */
95
96 struct linespec
97 {
98   /* An expression and the resulting PC.  Specifying an expression
99      currently precludes the use of other members.  */
100
101   /* The expression entered by the user.  */
102   const char *expression;
103
104   /* The resulting PC expression derived from evaluating EXPRESSION.  */
105   CORE_ADDR expr_pc;
106
107   /* Any specified file symtabs.  */
108
109   /* The user-supplied source filename or NULL if none was specified.  */
110   const char *source_filename;
111
112   /* The list of symtabs to search to which to limit the search.  May not
113      be NULL.  If SOURCE_FILENAME is NULL (no user-specified filename),
114      FILE_SYMTABS should contain one single NULL member.  This will
115      cause the code to use the default symtab.  */
116   VEC (symtab_ptr) *file_symtabs;
117
118   /* The name of a function or method and any matching symbols.  */
119
120   /* The user-specified function name.  If no function name was
121      supplied, this may be NULL.  */
122   const char *function_name;
123
124   /* A list of matching function symbols and minimal symbols.  Both lists
125      may be NULL if no matching symbols were found.  */
126   VEC (symbolp) *function_symbols;
127   VEC (bound_minimal_symbol_d) *minimal_symbols;
128
129   /* The name of a label and matching symbols.  */
130
131   /* The user-specified label name.  */
132   const char *label_name;
133
134   /* A structure of matching label symbols and the corresponding
135      function symbol in which the label was found.  Both may be NULL
136      or both must be non-NULL.  */
137   struct
138   {
139     VEC (symbolp) *label_symbols;
140     VEC (symbolp) *function_symbols;
141   } labels;
142
143   /* Line offset.  It may be LINE_OFFSET_UNKNOWN, meaning that no
144    offset was specified.  */
145   struct line_offset line_offset;
146 };
147 typedef struct linespec *linespec_p;
148
149 /* A canonical linespec represented as a symtab-related string.
150
151    Each entry represents the "SYMTAB:SUFFIX" linespec string.
152    SYMTAB can be converted for example by symtab_to_fullname or
153    symtab_to_filename_for_display as needed.  */
154
155 struct linespec_canonical_name
156 {
157   /* Remaining text part of the linespec string.  */
158   char *suffix;
159
160   /* If NULL then SUFFIX is the whole linespec string.  */
161   struct symtab *symtab;
162 };
163
164 /* An instance of this is used to keep all state while linespec
165    operates.  This instance is passed around as a 'this' pointer to
166    the various implementation methods.  */
167
168 struct linespec_state
169 {
170   /* The language in use during linespec processing.  */
171   const struct language_defn *language;
172
173   /* The program space as seen when the module was entered.  */
174   struct program_space *program_space;
175
176   /* The default symtab to use, if no other symtab is specified.  */
177   struct symtab *default_symtab;
178
179   /* The default line to use.  */
180   int default_line;
181
182   /* The 'funfirstline' value that was passed in to decode_line_1 or
183      decode_line_full.  */
184   int funfirstline;
185
186   /* Nonzero if we are running in 'list' mode; see decode_line_list.  */
187   int list_mode;
188
189   /* The 'canonical' value passed to decode_line_full, or NULL.  */
190   struct linespec_result *canonical;
191
192   /* Canonical strings that mirror the symtabs_and_lines result.  */
193   struct linespec_canonical_name *canonical_names;
194
195   /* This is a set of address_entry objects which is used to prevent
196      duplicate symbols from being entered into the result.  */
197   htab_t addr_set;
198 };
199
200 /* This is a helper object that is used when collecting symbols into a
201    result.  */
202
203 struct collect_info
204 {
205   /* The linespec object in use.  */
206   struct linespec_state *state;
207
208   /* A list of symtabs to which to restrict matches.  */
209   VEC (symtab_ptr) *file_symtabs;
210
211   /* The result being accumulated.  */
212   struct
213   {
214     VEC (symbolp) *symbols;
215     VEC (bound_minimal_symbol_d) *minimal_symbols;
216   } result;
217 };
218
219 /* Token types  */
220
221 enum ls_token_type
222 {
223   /* A keyword  */
224   LSTOKEN_KEYWORD = 0,
225
226   /* A colon "separator"  */
227   LSTOKEN_COLON,
228
229   /* A string  */
230   LSTOKEN_STRING,
231
232   /* A number  */
233   LSTOKEN_NUMBER,
234
235   /* A comma  */
236   LSTOKEN_COMMA,
237
238   /* EOI (end of input)  */
239   LSTOKEN_EOI,
240
241   /* Consumed token  */
242   LSTOKEN_CONSUMED
243 };
244 typedef enum ls_token_type linespec_token_type;
245
246 /* List of keywords  */
247
248 static const char * const linespec_keywords[] = { "if", "thread", "task" };
249
250 /* A token of the linespec lexer  */
251
252 struct ls_token
253 {
254   /* The type of the token  */
255   linespec_token_type type;
256
257   /* Data for the token  */
258   union
259   {
260     /* A string, given as a stoken  */
261     struct stoken string;
262
263     /* A keyword  */
264     const char *keyword;
265   } data;
266 };
267 typedef struct ls_token linespec_token;
268
269 #define LS_TOKEN_STOKEN(TOK) (TOK).data.string
270 #define LS_TOKEN_KEYWORD(TOK) (TOK).data.keyword
271
272 /* An instance of the linespec parser.  */
273
274 struct ls_parser
275 {
276   /* Lexer internal data  */
277   struct
278   {
279     /* Save head of input stream.  */
280     const char *saved_arg;
281
282     /* Head of the input stream.  */
283     const char **stream;
284 #define PARSER_STREAM(P) (*(P)->lexer.stream)
285
286     /* The current token.  */
287     linespec_token current;
288   } lexer;
289
290   /* Is the entire linespec quote-enclosed?  */
291   int is_quote_enclosed;
292
293   /* Is a keyword syntactically valid at this point?
294      In, e.g., "break thread thread 1", the leading "keyword" must not
295      be interpreted as such.  */
296   int keyword_ok;
297
298   /* The state of the parse.  */
299   struct linespec_state state;
300 #define PARSER_STATE(PPTR) (&(PPTR)->state)
301
302   /* The result of the parse.  */
303   struct linespec result;
304 #define PARSER_RESULT(PPTR) (&(PPTR)->result)
305 };
306 typedef struct ls_parser linespec_parser;
307
308 /* Prototypes for local functions.  */
309
310 static void iterate_over_file_blocks (struct symtab *symtab,
311                                       const char *name, domain_enum domain,
312                                       symbol_found_callback_ftype *callback,
313                                       void *data);
314
315 static void initialize_defaults (struct symtab **default_symtab,
316                                  int *default_line);
317
318 static CORE_ADDR linespec_expression_to_pc (const char **exp_ptr);
319
320 static struct symtabs_and_lines decode_objc (struct linespec_state *self,
321                                              linespec_p ls,
322                                              const char **argptr);
323
324 static VEC (symtab_ptr) *symtabs_from_filename (const char *);
325
326 static VEC (symbolp) *find_label_symbols (struct linespec_state *self,
327                                           VEC (symbolp) *function_symbols,
328                                           VEC (symbolp) **label_funcs_ret,
329                                           const char *name);
330
331 static void find_linespec_symbols (struct linespec_state *self,
332                                    VEC (symtab_ptr) *file_symtabs,
333                                    const char *name,
334                                    VEC (symbolp) **symbols,
335                                    VEC (bound_minimal_symbol_d) **minsyms);
336
337 static struct line_offset
338      linespec_parse_variable (struct linespec_state *self,
339                               const char *variable);
340
341 static int symbol_to_sal (struct symtab_and_line *result,
342                           int funfirstline, struct symbol *sym);
343
344 static void add_matching_symbols_to_info (const char *name,
345                                           struct collect_info *info,
346                                           struct program_space *pspace);
347
348 static void add_all_symbol_names_from_pspace (struct collect_info *info,
349                                               struct program_space *pspace,
350                                               VEC (const_char_ptr) *names);
351
352 static VEC (symtab_ptr) *collect_symtabs_from_filename (const char *file);
353
354 static void decode_digits_ordinary (struct linespec_state *self,
355                                     linespec_p ls,
356                                     int line,
357                                     struct symtabs_and_lines *sals,
358                                     struct linetable_entry **best_entry);
359
360 static void decode_digits_list_mode (struct linespec_state *self,
361                                      linespec_p ls,
362                                      struct symtabs_and_lines *values,
363                                      struct symtab_and_line val);
364
365 static void minsym_found (struct linespec_state *self, struct objfile *objfile,
366                           struct minimal_symbol *msymbol,
367                           struct symtabs_and_lines *result);
368
369 static int compare_symbols (const void *a, const void *b);
370
371 static int compare_msymbols (const void *a, const void *b);
372
373 static const char *find_toplevel_char (const char *s, char c);
374
375 /* Permitted quote characters for the parser.  This is different from the
376    completer's quote characters to allow backward compatibility with the
377    previous parser.  */
378 static const char *const linespec_quote_characters = "\"\'";
379
380 /* Lexer functions.  */
381
382 /* Lex a number from the input in PARSER.  This only supports
383    decimal numbers.
384
385    Return true if input is decimal numbers.  Return false if not.  */
386
387 static int
388 linespec_lexer_lex_number (linespec_parser *parser, linespec_token *tokenp)
389 {
390   tokenp->type = LSTOKEN_NUMBER;
391   LS_TOKEN_STOKEN (*tokenp).length = 0;
392   LS_TOKEN_STOKEN (*tokenp).ptr = PARSER_STREAM (parser);
393
394   /* Keep any sign at the start of the stream.  */
395   if (*PARSER_STREAM (parser) == '+' || *PARSER_STREAM (parser) == '-')
396     {
397       ++LS_TOKEN_STOKEN (*tokenp).length;
398       ++(PARSER_STREAM (parser));
399     }
400
401   while (isdigit (*PARSER_STREAM (parser)))
402     {
403       ++LS_TOKEN_STOKEN (*tokenp).length;
404       ++(PARSER_STREAM (parser));
405     }
406
407   /* If the next character in the input buffer is not a space, comma,
408      quote, or colon, this input does not represent a number.  */
409   if (*PARSER_STREAM (parser) != '\0'
410       && !isspace (*PARSER_STREAM (parser)) && *PARSER_STREAM (parser) != ','
411       && *PARSER_STREAM (parser) != ':'
412       && !strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
413     {
414       PARSER_STREAM (parser) = LS_TOKEN_STOKEN (*tokenp).ptr;
415       return 0;
416     }
417
418   return 1;
419 }
420
421 /* Does P represent one of the keywords?  If so, return
422    the keyword.  If not, return NULL.  */
423
424 static const char *
425 linespec_lexer_lex_keyword (const char *p)
426 {
427   int i;
428
429   if (p != NULL)
430     {
431       for (i = 0; i < ARRAY_SIZE (linespec_keywords); ++i)
432         {
433           int len = strlen (linespec_keywords[i]);
434
435           /* If P begins with one of the keywords and the next
436              character is not a valid identifier character,
437              we have found a keyword.  */
438           if (strncmp (p, linespec_keywords[i], len) == 0
439               && !(isalnum (p[len]) || p[len] == '_'))
440             return linespec_keywords[i];
441         }
442     }
443
444   return NULL;
445 }
446
447 /* Does STRING represent an Ada operator?  If so, return the length
448    of the decoded operator name.  If not, return 0.  */
449
450 static int
451 is_ada_operator (const char *string)
452 {
453   const struct ada_opname_map *mapping;
454
455   for (mapping = ada_opname_table;
456        mapping->encoded != NULL
457          && !startswith (string, mapping->decoded); ++mapping)
458     ;
459
460   return mapping->decoded == NULL ? 0 : strlen (mapping->decoded);
461 }
462
463 /* Find QUOTE_CHAR in STRING, accounting for the ':' terminal.  Return
464    the location of QUOTE_CHAR, or NULL if not found.  */
465
466 static const char *
467 skip_quote_char (const char *string, char quote_char)
468 {
469   const char *p, *last;
470
471   p = last = find_toplevel_char (string, quote_char);
472   while (p && *p != '\0' && *p != ':')
473     {
474       p = find_toplevel_char (p, quote_char);
475       if (p != NULL)
476         last = p++;
477     }
478
479   return last;
480 }
481
482 /* Make a writable copy of the string given in TOKEN, trimming
483    any trailing whitespace.  */
484
485 static char *
486 copy_token_string (linespec_token token)
487 {
488   char *str, *s;
489
490   if (token.type == LSTOKEN_KEYWORD)
491     return xstrdup (LS_TOKEN_KEYWORD (token));
492
493   str = savestring (LS_TOKEN_STOKEN (token).ptr,
494                     LS_TOKEN_STOKEN (token).length);
495   s = remove_trailing_whitespace (str, str + LS_TOKEN_STOKEN (token).length);
496   *s = '\0';
497
498   return str;
499 }
500
501 /* Does P represent the end of a quote-enclosed linespec?  */
502
503 static int
504 is_closing_quote_enclosed (const char *p)
505 {
506   if (strchr (linespec_quote_characters, *p))
507     ++p;
508   p = skip_spaces ((char *) p);
509   return (*p == '\0' || linespec_lexer_lex_keyword (p));
510 }
511
512 /* Find the end of the parameter list that starts with *INPUT.
513    This helper function assists with lexing string segments
514    which might contain valid (non-terminating) commas.  */
515
516 static const char *
517 find_parameter_list_end (const char *input)
518 {
519   char end_char, start_char;
520   int depth;
521   const char *p;
522
523   start_char = *input;
524   if (start_char == '(')
525     end_char = ')';
526   else if (start_char == '<')
527     end_char = '>';
528   else
529     return NULL;
530
531   p = input;
532   depth = 0;
533   while (*p)
534     {
535       if (*p == start_char)
536         ++depth;
537       else if (*p == end_char)
538         {
539           if (--depth == 0)
540             {
541               ++p;
542               break;
543             }
544         }
545       ++p;
546     }
547
548   return p;
549 }
550
551
552 /* Lex a string from the input in PARSER.  */
553
554 static linespec_token
555 linespec_lexer_lex_string (linespec_parser *parser)
556 {
557   linespec_token token;
558   const char *start = PARSER_STREAM (parser);
559
560   token.type = LSTOKEN_STRING;
561
562   /* If the input stream starts with a quote character, skip to the next
563      quote character, regardless of the content.  */
564   if (strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
565     {
566       const char *end;
567       char quote_char = *PARSER_STREAM (parser);
568
569       /* Special case: Ada operators.  */
570       if (PARSER_STATE (parser)->language->la_language == language_ada
571           && quote_char == '\"')
572         {
573           int len = is_ada_operator (PARSER_STREAM (parser));
574
575           if (len != 0)
576             {
577               /* The input is an Ada operator.  Return the quoted string
578                  as-is.  */
579               LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
580               LS_TOKEN_STOKEN (token).length = len;
581               PARSER_STREAM (parser) += len;
582               return token;
583             }
584
585           /* The input does not represent an Ada operator -- fall through
586              to normal quoted string handling.  */
587         }
588
589       /* Skip past the beginning quote.  */
590       ++(PARSER_STREAM (parser));
591
592       /* Mark the start of the string.  */
593       LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
594
595       /* Skip to the ending quote.  */
596       end = skip_quote_char (PARSER_STREAM (parser), quote_char);
597
598       /* Error if the input did not terminate properly.  */
599       if (end == NULL)
600         error (_("unmatched quote"));
601
602       /* Skip over the ending quote and mark the length of the string.  */
603       PARSER_STREAM (parser) = (char *) ++end;
604       LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 2 - start;
605     }
606   else
607     {
608       const char *p;
609
610       /* Otherwise, only identifier characters are permitted.
611          Spaces are the exception.  In general, we keep spaces,
612          but only if the next characters in the input do not resolve
613          to one of the keywords.
614
615          This allows users to forgo quoting CV-qualifiers, template arguments,
616          and similar common language constructs.  */
617
618       while (1)
619         {
620           if (isspace (*PARSER_STREAM (parser)))
621             {
622               p = skip_spaces_const (PARSER_STREAM (parser));
623               /* When we get here we know we've found something followed by
624                  a space (we skip over parens and templates below).
625                  So if we find a keyword now, we know it is a keyword and not,
626                  say, a function name.  */
627               if (linespec_lexer_lex_keyword (p) != NULL)
628                 {
629                   LS_TOKEN_STOKEN (token).ptr = start;
630                   LS_TOKEN_STOKEN (token).length
631                     = PARSER_STREAM (parser) - start;
632                   return token;
633                 }
634
635               /* Advance past the whitespace.  */
636               PARSER_STREAM (parser) = p;
637             }
638
639           /* If the next character is EOI or (single) ':', the
640              string is complete;  return the token.  */
641           if (*PARSER_STREAM (parser) == 0)
642             {
643               LS_TOKEN_STOKEN (token).ptr = start;
644               LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
645               return token;
646             }
647           else if (PARSER_STREAM (parser)[0] == ':')
648             {
649               /* Do not tokenize the C++ scope operator. */
650               if (PARSER_STREAM (parser)[1] == ':')
651                 ++(PARSER_STREAM (parser));
652
653               /* Do not tokenify if the input length so far is one
654                  (i.e, a single-letter drive name) and the next character
655                  is a directory separator.  This allows Windows-style
656                  paths to be recognized as filenames without quoting it.  */
657               else if ((PARSER_STREAM (parser) - start) != 1
658                        || !IS_DIR_SEPARATOR (PARSER_STREAM (parser)[1]))
659                 {
660                   LS_TOKEN_STOKEN (token).ptr = start;
661                   LS_TOKEN_STOKEN (token).length
662                     = PARSER_STREAM (parser) - start;
663                   return token;
664                 }
665             }
666           /* Special case: permit quote-enclosed linespecs.  */
667           else if (parser->is_quote_enclosed
668                    && strchr (linespec_quote_characters,
669                               *PARSER_STREAM (parser))
670                    && is_closing_quote_enclosed (PARSER_STREAM (parser)))
671             {
672               LS_TOKEN_STOKEN (token).ptr = start;
673               LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
674               return token;
675             }
676           /* Because commas may terminate a linespec and appear in
677              the middle of valid string input, special cases for
678              '<' and '(' are necessary.  */
679           else if (*PARSER_STREAM (parser) == '<'
680                    || *PARSER_STREAM (parser) == '(')
681             {
682               const char *p;
683
684               p = find_parameter_list_end (PARSER_STREAM (parser));
685               if (p != NULL)
686                 {
687                   PARSER_STREAM (parser) = p;
688                   continue;
689                 }
690             }
691           /* Commas are terminators, but not if they are part of an
692              operator name.  */
693           else if (*PARSER_STREAM (parser) == ',')
694             {
695               if ((PARSER_STATE (parser)->language->la_language
696                    == language_cplus)
697                   && (PARSER_STREAM (parser) - start) > 8
698                   /* strlen ("operator") */)
699                 {
700                   char *p = strstr (start, "operator");
701
702                   if (p != NULL && is_operator_name (p))
703                     {
704                       /* This is an operator name.  Keep going.  */
705                       ++(PARSER_STREAM (parser));
706                       continue;
707                     }
708                 }
709
710               /* Comma terminates the string.  */
711               LS_TOKEN_STOKEN (token).ptr = start;
712               LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
713               return token;
714             }
715
716           /* Advance the stream.  */
717           ++(PARSER_STREAM (parser));
718         }
719     }
720
721   return token;
722 }
723
724 /* Lex a single linespec token from PARSER.  */
725
726 static linespec_token
727 linespec_lexer_lex_one (linespec_parser *parser)
728 {
729   const char *keyword;
730
731   if (parser->lexer.current.type == LSTOKEN_CONSUMED)
732     {
733       /* Skip any whitespace.  */
734       PARSER_STREAM (parser) = skip_spaces_const (PARSER_STREAM (parser));
735
736       /* Check for a keyword, they end the linespec.  */
737       keyword = NULL;
738       if (parser->keyword_ok)
739         keyword = linespec_lexer_lex_keyword (PARSER_STREAM (parser));
740       if (keyword != NULL)
741         {
742           parser->lexer.current.type = LSTOKEN_KEYWORD;
743           LS_TOKEN_KEYWORD (parser->lexer.current) = keyword;
744           return parser->lexer.current;
745         }
746
747       /* Handle other tokens.  */
748       switch (*PARSER_STREAM (parser))
749         {
750         case 0:
751           parser->lexer.current.type = LSTOKEN_EOI;
752           break;
753
754         case '+': case '-':
755         case '0': case '1': case '2': case '3': case '4':
756         case '5': case '6': case '7': case '8': case '9':
757            if (!linespec_lexer_lex_number (parser, &(parser->lexer.current)))
758              parser->lexer.current = linespec_lexer_lex_string (parser);
759           break;
760
761         case ':':
762           /* If we have a scope operator, lex the input as a string.
763              Otherwise, return LSTOKEN_COLON.  */
764           if (PARSER_STREAM (parser)[1] == ':')
765             parser->lexer.current = linespec_lexer_lex_string (parser);
766           else
767             {
768               parser->lexer.current.type = LSTOKEN_COLON;
769               ++(PARSER_STREAM (parser));
770             }
771           break;
772
773         case '\'': case '\"':
774           /* Special case: permit quote-enclosed linespecs.  */
775           if (parser->is_quote_enclosed
776               && is_closing_quote_enclosed (PARSER_STREAM (parser)))
777             {
778               ++(PARSER_STREAM (parser));
779               parser->lexer.current.type = LSTOKEN_EOI;
780             }
781           else
782             parser->lexer.current = linespec_lexer_lex_string (parser);
783           break;
784
785         case ',':
786           parser->lexer.current.type = LSTOKEN_COMMA;
787           LS_TOKEN_STOKEN (parser->lexer.current).ptr
788             = PARSER_STREAM (parser);
789           LS_TOKEN_STOKEN (parser->lexer.current).length = 1;
790           ++(PARSER_STREAM (parser));
791           break;
792
793         default:
794           /* If the input is not a number, it must be a string.
795              [Keywords were already considered above.]  */
796           parser->lexer.current = linespec_lexer_lex_string (parser);
797           break;
798         }
799     }
800
801   return parser->lexer.current;
802 }
803
804 /* Consume the current token and return the next token in PARSER's
805    input stream.  */
806
807 static linespec_token
808 linespec_lexer_consume_token (linespec_parser *parser)
809 {
810   parser->lexer.current.type = LSTOKEN_CONSUMED;
811   return linespec_lexer_lex_one (parser);
812 }
813
814 /* Return the next token without consuming the current token.  */
815
816 static linespec_token
817 linespec_lexer_peek_token (linespec_parser *parser)
818 {
819   linespec_token next;
820   const char *saved_stream = PARSER_STREAM (parser);
821   linespec_token saved_token = parser->lexer.current;
822
823   next = linespec_lexer_consume_token (parser);
824   PARSER_STREAM (parser) = saved_stream;
825   parser->lexer.current = saved_token;
826   return next;
827 }
828
829 /* Helper functions.  */
830
831 /* Add SAL to SALS.  */
832
833 static void
834 add_sal_to_sals_basic (struct symtabs_and_lines *sals,
835                        struct symtab_and_line *sal)
836 {
837   ++sals->nelts;
838   sals->sals = xrealloc (sals->sals, sals->nelts * sizeof (sals->sals[0]));
839   sals->sals[sals->nelts - 1] = *sal;
840 }
841
842 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
843    the new sal, if needed.  If not NULL, SYMNAME is the name of the
844    symbol to use when constructing the new canonical name.
845
846    If LITERAL_CANONICAL is non-zero, SYMNAME will be used as the
847    canonical name for the SAL.  */
848
849 static void
850 add_sal_to_sals (struct linespec_state *self,
851                  struct symtabs_and_lines *sals,
852                  struct symtab_and_line *sal,
853                  const char *symname, int literal_canonical)
854 {
855   add_sal_to_sals_basic (sals, sal);
856
857   if (self->canonical)
858     {
859       struct linespec_canonical_name *canonical;
860
861       self->canonical_names = xrealloc (self->canonical_names,
862                                         (sals->nelts
863                                          * sizeof (*self->canonical_names)));
864       canonical = &self->canonical_names[sals->nelts - 1];
865       if (!literal_canonical && sal->symtab)
866         {
867           const char *fullname = symtab_to_fullname (sal->symtab);
868
869           /* Note that the filter doesn't have to be a valid linespec
870              input.  We only apply the ":LINE" treatment to Ada for
871              the time being.  */
872           if (symname != NULL && sal->line != 0
873               && self->language->la_language == language_ada)
874             canonical->suffix = xstrprintf ("%s:%d", symname, sal->line);
875           else if (symname != NULL)
876             canonical->suffix = xstrdup (symname);
877           else
878             canonical->suffix = xstrprintf ("%d", sal->line);
879           canonical->symtab = sal->symtab;
880         }
881       else
882         {
883           if (symname != NULL)
884             canonical->suffix = xstrdup (symname);
885           else
886             canonical->suffix = xstrdup ("<unknown>");
887           canonical->symtab = NULL;
888         }
889     }
890 }
891
892 /* A hash function for address_entry.  */
893
894 static hashval_t
895 hash_address_entry (const void *p)
896 {
897   const struct address_entry *aep = p;
898   hashval_t hash;
899
900   hash = iterative_hash_object (aep->pspace, 0);
901   return iterative_hash_object (aep->addr, hash);
902 }
903
904 /* An equality function for address_entry.  */
905
906 static int
907 eq_address_entry (const void *a, const void *b)
908 {
909   const struct address_entry *aea = a;
910   const struct address_entry *aeb = b;
911
912   return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
913 }
914
915 /* Check whether the address, represented by PSPACE and ADDR, is
916    already in the set.  If so, return 0.  Otherwise, add it and return
917    1.  */
918
919 static int
920 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
921 {
922   struct address_entry e, *p;
923   void **slot;
924
925   e.pspace = pspace;
926   e.addr = addr;
927   slot = htab_find_slot (set, &e, INSERT);
928   if (*slot)
929     return 0;
930
931   p = XNEW (struct address_entry);
932   memcpy (p, &e, sizeof (struct address_entry));
933   *slot = p;
934
935   return 1;
936 }
937
938 /* A callback function and the additional data to call it with.  */
939
940 struct symbol_and_data_callback
941 {
942   /* The callback to use.  */
943   symbol_found_callback_ftype *callback;
944
945   /* Data to be passed to the callback.  */
946   void *data;
947 };
948
949 /* A helper for iterate_over_all_matching_symtabs that is used to
950    restrict calls to another callback to symbols representing inline
951    symbols only.  */
952
953 static int
954 iterate_inline_only (struct symbol *sym, void *d)
955 {
956   if (SYMBOL_INLINED (sym))
957     {
958       struct symbol_and_data_callback *cad = d;
959
960       return cad->callback (sym, cad->data);
961     }
962   return 1; /* Continue iterating.  */
963 }
964
965 /* Some data for the expand_symtabs_matching callback.  */
966
967 struct symbol_matcher_data
968 {
969   /* The lookup name against which symbol name should be compared.  */
970   const char *lookup_name;
971
972   /* The routine to be used for comparison.  */
973   symbol_name_cmp_ftype symbol_name_cmp;
974 };
975
976 /* A helper for iterate_over_all_matching_symtabs that is passed as a
977    callback to the expand_symtabs_matching method.  */
978
979 static int
980 iterate_name_matcher (const char *name, void *d)
981 {
982   const struct symbol_matcher_data *data = d;
983
984   if (data->symbol_name_cmp (name, data->lookup_name) == 0)
985     return 1; /* Expand this symbol's symbol table.  */
986   return 0; /* Skip this symbol.  */
987 }
988
989 /* A helper that walks over all matching symtabs in all objfiles and
990    calls CALLBACK for each symbol matching NAME.  If SEARCH_PSPACE is
991    not NULL, then the search is restricted to just that program
992    space.  If INCLUDE_INLINE is nonzero then symbols representing
993    inlined instances of functions will be included in the result.  */
994
995 static void
996 iterate_over_all_matching_symtabs (struct linespec_state *state,
997                                    const char *name,
998                                    const domain_enum domain,
999                                    symbol_found_callback_ftype *callback,
1000                                    void *data,
1001                                    struct program_space *search_pspace,
1002                                    int include_inline)
1003 {
1004   struct objfile *objfile;
1005   struct program_space *pspace;
1006   struct symbol_matcher_data matcher_data;
1007
1008   matcher_data.lookup_name = name;
1009   matcher_data.symbol_name_cmp =
1010     state->language->la_get_symbol_name_cmp != NULL
1011     ? state->language->la_get_symbol_name_cmp (name)
1012     : strcmp_iw;
1013
1014   ALL_PSPACES (pspace)
1015   {
1016     if (search_pspace != NULL && search_pspace != pspace)
1017       continue;
1018     if (pspace->executing_startup)
1019       continue;
1020
1021     set_current_program_space (pspace);
1022
1023     ALL_OBJFILES (objfile)
1024     {
1025       struct compunit_symtab *cu;
1026
1027       if (objfile->sf)
1028         objfile->sf->qf->expand_symtabs_matching (objfile, NULL,
1029                                                   iterate_name_matcher,
1030                                                   NULL, ALL_DOMAIN,
1031                                                   &matcher_data);
1032
1033       ALL_OBJFILE_COMPUNITS (objfile, cu)
1034         {
1035           struct symtab *symtab = COMPUNIT_FILETABS (cu);
1036
1037           iterate_over_file_blocks (symtab, name, domain, callback, data);
1038
1039           if (include_inline)
1040             {
1041               struct symbol_and_data_callback cad = { callback, data };
1042               struct block *block;
1043               int i;
1044
1045               for (i = FIRST_LOCAL_BLOCK;
1046                    i < BLOCKVECTOR_NBLOCKS (SYMTAB_BLOCKVECTOR (symtab));
1047                    i++)
1048                 {
1049                   block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symtab), i);
1050                   state->language->la_iterate_over_symbols
1051                     (block, name, domain, iterate_inline_only, &cad);
1052                 }
1053             }
1054         }
1055     }
1056   }
1057 }
1058
1059 /* Returns the block to be used for symbol searches from
1060    the current location.  */
1061
1062 static const struct block *
1063 get_current_search_block (void)
1064 {
1065   const struct block *block;
1066   enum language save_language;
1067
1068   /* get_selected_block can change the current language when there is
1069      no selected frame yet.  */
1070   save_language = current_language->la_language;
1071   block = get_selected_block (0);
1072   set_language (save_language);
1073
1074   return block;
1075 }
1076
1077 /* Iterate over static and global blocks.  */
1078
1079 static void
1080 iterate_over_file_blocks (struct symtab *symtab,
1081                           const char *name, domain_enum domain,
1082                           symbol_found_callback_ftype *callback, void *data)
1083 {
1084   struct block *block;
1085
1086   for (block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symtab), STATIC_BLOCK);
1087        block != NULL;
1088        block = BLOCK_SUPERBLOCK (block))
1089     LA_ITERATE_OVER_SYMBOLS (block, name, domain, callback, data);
1090 }
1091
1092 /* A helper for find_method.  This finds all methods in type T which
1093    match NAME.  It adds matching symbol names to RESULT_NAMES, and
1094    adds T's direct superclasses to SUPERCLASSES.  */
1095
1096 static void
1097 find_methods (struct type *t, const char *name,
1098               VEC (const_char_ptr) **result_names,
1099               VEC (typep) **superclasses)
1100 {
1101   int ibase;
1102   const char *class_name = type_name_no_tag (t);
1103
1104   /* Ignore this class if it doesn't have a name.  This is ugly, but
1105      unless we figure out how to get the physname without the name of
1106      the class, then the loop can't do any good.  */
1107   if (class_name)
1108     {
1109       int method_counter;
1110
1111       CHECK_TYPEDEF (t);
1112
1113       /* Loop over each method name.  At this level, all overloads of a name
1114          are counted as a single name.  There is an inner loop which loops over
1115          each overload.  */
1116
1117       for (method_counter = TYPE_NFN_FIELDS (t) - 1;
1118            method_counter >= 0;
1119            --method_counter)
1120         {
1121           const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
1122           char dem_opname[64];
1123
1124           if (startswith (method_name, "__") ||
1125               startswith (method_name, "op") ||
1126               startswith (method_name, "type"))
1127             {
1128               if (cplus_demangle_opname (method_name, dem_opname, DMGL_ANSI))
1129                 method_name = dem_opname;
1130               else if (cplus_demangle_opname (method_name, dem_opname, 0))
1131                 method_name = dem_opname;
1132             }
1133
1134           if (strcmp_iw (method_name, name) == 0)
1135             {
1136               int field_counter;
1137
1138               for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
1139                                     - 1);
1140                    field_counter >= 0;
1141                    --field_counter)
1142                 {
1143                   struct fn_field *f;
1144                   const char *phys_name;
1145
1146                   f = TYPE_FN_FIELDLIST1 (t, method_counter);
1147                   if (TYPE_FN_FIELD_STUB (f, field_counter))
1148                     continue;
1149                   phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
1150                   VEC_safe_push (const_char_ptr, *result_names, phys_name);
1151                 }
1152             }
1153         }
1154     }
1155
1156   for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
1157     VEC_safe_push (typep, *superclasses, TYPE_BASECLASS (t, ibase));
1158 }
1159
1160 /* Find an instance of the character C in the string S that is outside
1161    of all parenthesis pairs, single-quoted strings, and double-quoted
1162    strings.  Also, ignore the char within a template name, like a ','
1163    within foo<int, int>.  */
1164
1165 static const char *
1166 find_toplevel_char (const char *s, char c)
1167 {
1168   int quoted = 0;               /* zero if we're not in quotes;
1169                                    '"' if we're in a double-quoted string;
1170                                    '\'' if we're in a single-quoted string.  */
1171   int depth = 0;                /* Number of unclosed parens we've seen.  */
1172   const char *scan;
1173
1174   for (scan = s; *scan; scan++)
1175     {
1176       if (quoted)
1177         {
1178           if (*scan == quoted)
1179             quoted = 0;
1180           else if (*scan == '\\' && *(scan + 1))
1181             scan++;
1182         }
1183       else if (*scan == c && ! quoted && depth == 0)
1184         return scan;
1185       else if (*scan == '"' || *scan == '\'')
1186         quoted = *scan;
1187       else if (*scan == '(' || *scan == '<')
1188         depth++;
1189       else if ((*scan == ')' || *scan == '>') && depth > 0)
1190         depth--;
1191     }
1192
1193   return 0;
1194 }
1195
1196 /* The string equivalent of find_toplevel_char.  Returns a pointer
1197    to the location of NEEDLE in HAYSTACK, ignoring any occurrences
1198    inside "()" and "<>".  Returns NULL if NEEDLE was not found.  */
1199
1200 static const char *
1201 find_toplevel_string (const char *haystack, const char *needle)
1202 {
1203   const char *s = haystack;
1204
1205   do
1206     {
1207       s = find_toplevel_char (s, *needle);
1208
1209       if (s != NULL)
1210         {
1211           /* Found first char in HAYSTACK;  check rest of string.  */
1212           if (startswith (s, needle))
1213             return s;
1214
1215           /* Didn't find it; loop over HAYSTACK, looking for the next
1216              instance of the first character of NEEDLE.  */
1217           ++s;
1218         }
1219     }
1220   while (s != NULL && *s != '\0');
1221
1222   /* NEEDLE was not found in HAYSTACK.  */
1223   return NULL;
1224 }
1225
1226 /* Convert CANONICAL to its string representation using
1227    symtab_to_fullname for SYMTAB.  The caller must xfree the result.  */
1228
1229 static char *
1230 canonical_to_fullform (const struct linespec_canonical_name *canonical)
1231 {
1232   if (canonical->symtab == NULL)
1233     return xstrdup (canonical->suffix);
1234   else
1235     return xstrprintf ("%s:%s", symtab_to_fullname (canonical->symtab),
1236                        canonical->suffix);
1237 }
1238
1239 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
1240    and store the result in SELF->CANONICAL.  */
1241
1242 static void
1243 filter_results (struct linespec_state *self,
1244                 struct symtabs_and_lines *result,
1245                 VEC (const_char_ptr) *filters)
1246 {
1247   int i;
1248   const char *name;
1249
1250   for (i = 0; VEC_iterate (const_char_ptr, filters, i, name); ++i)
1251     {
1252       struct linespec_sals lsal;
1253       int j;
1254
1255       memset (&lsal, 0, sizeof (lsal));
1256
1257       for (j = 0; j < result->nelts; ++j)
1258         {
1259           const struct linespec_canonical_name *canonical;
1260           char *fullform;
1261           struct cleanup *cleanup;
1262
1263           canonical = &self->canonical_names[j];
1264           fullform = canonical_to_fullform (canonical);
1265           cleanup = make_cleanup (xfree, fullform);
1266
1267           if (strcmp (name, fullform) == 0)
1268             add_sal_to_sals_basic (&lsal.sals, &result->sals[j]);
1269
1270           do_cleanups (cleanup);
1271         }
1272
1273       if (lsal.sals.nelts > 0)
1274         {
1275           lsal.canonical = xstrdup (name);
1276           VEC_safe_push (linespec_sals, self->canonical->sals, &lsal);
1277         }
1278     }
1279
1280   self->canonical->pre_expanded = 0;
1281 }
1282
1283 /* Store RESULT into SELF->CANONICAL.  */
1284
1285 static void
1286 convert_results_to_lsals (struct linespec_state *self,
1287                           struct symtabs_and_lines *result)
1288 {
1289   struct linespec_sals lsal;
1290
1291   lsal.canonical = NULL;
1292   lsal.sals = *result;
1293   VEC_safe_push (linespec_sals, self->canonical->sals, &lsal);
1294 }
1295
1296 /* A structure that contains two string representations of a struct
1297    linespec_canonical_name:
1298      - one where the the symtab's fullname is used;
1299      - one where the filename followed the "set filename-display"
1300        setting.  */
1301
1302 struct decode_line_2_item
1303 {
1304   /* The form using symtab_to_fullname.
1305      It must be xfree'ed after use.  */
1306   char *fullform;
1307
1308   /* The form using symtab_to_filename_for_display.
1309      It must be xfree'ed after use.  */
1310   char *displayform;
1311
1312   /* Field is initialized to zero and it is set to one if the user
1313      requested breakpoint for this entry.  */
1314   unsigned int selected : 1;
1315 };
1316
1317 /* Helper for qsort to sort decode_line_2_item entries by DISPLAYFORM and
1318    secondarily by FULLFORM.  */
1319
1320 static int
1321 decode_line_2_compare_items (const void *ap, const void *bp)
1322 {
1323   const struct decode_line_2_item *a = ap;
1324   const struct decode_line_2_item *b = bp;
1325   int retval;
1326
1327   retval = strcmp (a->displayform, b->displayform);
1328   if (retval != 0)
1329     return retval;
1330
1331   return strcmp (a->fullform, b->fullform);
1332 }
1333
1334 /* Handle multiple results in RESULT depending on SELECT_MODE.  This
1335    will either return normally, throw an exception on multiple
1336    results, or present a menu to the user.  On return, the SALS vector
1337    in SELF->CANONICAL is set up properly.  */
1338
1339 static void
1340 decode_line_2 (struct linespec_state *self,
1341                struct symtabs_and_lines *result,
1342                const char *select_mode)
1343 {
1344   char *args, *prompt;
1345   int i;
1346   struct cleanup *old_chain;
1347   VEC (const_char_ptr) *filters = NULL;
1348   struct get_number_or_range_state state;
1349   struct decode_line_2_item *items;
1350   int items_count;
1351
1352   gdb_assert (select_mode != multiple_symbols_all);
1353   gdb_assert (self->canonical != NULL);
1354   gdb_assert (result->nelts >= 1);
1355
1356   old_chain = make_cleanup (VEC_cleanup (const_char_ptr), &filters);
1357
1358   /* Prepare ITEMS array.  */
1359   items_count = result->nelts;
1360   items = xmalloc (sizeof (*items) * items_count);
1361   make_cleanup (xfree, items);
1362   for (i = 0; i < items_count; ++i)
1363     {
1364       const struct linespec_canonical_name *canonical;
1365       struct decode_line_2_item *item;
1366
1367       canonical = &self->canonical_names[i];
1368       gdb_assert (canonical->suffix != NULL);
1369       item = &items[i];
1370
1371       item->fullform = canonical_to_fullform (canonical);
1372       make_cleanup (xfree, item->fullform);
1373
1374       if (canonical->symtab == NULL)
1375         item->displayform = canonical->suffix;
1376       else
1377         {
1378           const char *fn_for_display;
1379
1380           fn_for_display = symtab_to_filename_for_display (canonical->symtab);
1381           item->displayform = xstrprintf ("%s:%s", fn_for_display,
1382                                           canonical->suffix);
1383           make_cleanup (xfree, item->displayform);
1384         }
1385
1386       item->selected = 0;
1387     }
1388
1389   /* Sort the list of method names.  */
1390   qsort (items, items_count, sizeof (*items), decode_line_2_compare_items);
1391
1392   /* Remove entries with the same FULLFORM.  */
1393   if (items_count >= 2)
1394     {
1395       struct decode_line_2_item *dst, *src;
1396
1397       dst = items;
1398       for (src = &items[1]; src < &items[items_count]; src++)
1399         if (strcmp (src->fullform, dst->fullform) != 0)
1400           *++dst = *src;
1401       items_count = dst + 1 - items;
1402     }
1403
1404   if (select_mode == multiple_symbols_cancel && items_count > 1)
1405     error (_("canceled because the command is ambiguous\n"
1406              "See set/show multiple-symbol."));
1407   
1408   if (select_mode == multiple_symbols_all || items_count == 1)
1409     {
1410       do_cleanups (old_chain);
1411       convert_results_to_lsals (self, result);
1412       return;
1413     }
1414
1415   printf_unfiltered (_("[0] cancel\n[1] all\n"));
1416   for (i = 0; i < items_count; i++)
1417     printf_unfiltered ("[%d] %s\n", i + 2, items[i].displayform);
1418
1419   prompt = getenv ("PS2");
1420   if (prompt == NULL)
1421     {
1422       prompt = "> ";
1423     }
1424   args = command_line_input (prompt, 0, "overload-choice");
1425
1426   if (args == 0 || *args == 0)
1427     error_no_arg (_("one or more choice numbers"));
1428
1429   init_number_or_range (&state, args);
1430   while (!state.finished)
1431     {
1432       int num;
1433
1434       num = get_number_or_range (&state);
1435
1436       if (num == 0)
1437         error (_("canceled"));
1438       else if (num == 1)
1439         {
1440           /* We intentionally make this result in a single breakpoint,
1441              contrary to what older versions of gdb did.  The
1442              rationale is that this lets a user get the
1443              multiple_symbols_all behavior even with the 'ask'
1444              setting; and he can get separate breakpoints by entering
1445              "2-57" at the query.  */
1446           do_cleanups (old_chain);
1447           convert_results_to_lsals (self, result);
1448           return;
1449         }
1450
1451       num -= 2;
1452       if (num >= items_count)
1453         printf_unfiltered (_("No choice number %d.\n"), num);
1454       else
1455         {
1456           struct decode_line_2_item *item = &items[num];
1457
1458           if (!item->selected)
1459             {
1460               VEC_safe_push (const_char_ptr, filters, item->fullform);
1461               item->selected = 1;
1462             }
1463           else
1464             {
1465               printf_unfiltered (_("duplicate request for %d ignored.\n"),
1466                                  num + 2);
1467             }
1468         }
1469     }
1470
1471   filter_results (self, result, filters);
1472   do_cleanups (old_chain);
1473 }
1474
1475 \f
1476
1477 /* The parser of linespec itself.  */
1478
1479 /* Throw an appropriate error when SYMBOL is not found (optionally in
1480    FILENAME).  */
1481
1482 static void ATTRIBUTE_NORETURN
1483 symbol_not_found_error (const char *symbol, const char *filename)
1484 {
1485   if (symbol == NULL)
1486     symbol = "";
1487
1488   if (!have_full_symbols ()
1489       && !have_partial_symbols ()
1490       && !have_minimal_symbols ())
1491     throw_error (NOT_FOUND_ERROR,
1492                  _("No symbol table is loaded.  Use the \"file\" command."));
1493
1494   /* If SYMBOL starts with '$', the user attempted to either lookup
1495      a function/variable in his code starting with '$' or an internal
1496      variable of that name.  Since we do not know which, be concise and
1497      explain both possibilities.  */
1498   if (*symbol == '$')
1499     {
1500       if (filename)
1501         throw_error (NOT_FOUND_ERROR,
1502                      _("Undefined convenience variable or function \"%s\" "
1503                        "not defined in \"%s\"."), symbol, filename);
1504       else
1505         throw_error (NOT_FOUND_ERROR,
1506                      _("Undefined convenience variable or function \"%s\" "
1507                        "not defined."), symbol);
1508     }
1509   else
1510     {
1511       if (filename)
1512         throw_error (NOT_FOUND_ERROR,
1513                      _("Function \"%s\" not defined in \"%s\"."),
1514                      symbol, filename);
1515       else
1516         throw_error (NOT_FOUND_ERROR,
1517                      _("Function \"%s\" not defined."), symbol);
1518     }
1519 }
1520
1521 /* Throw an appropriate error when an unexpected token is encountered 
1522    in the input.  */
1523
1524 static void ATTRIBUTE_NORETURN
1525 unexpected_linespec_error (linespec_parser *parser)
1526 {
1527   linespec_token token;
1528   static const char * token_type_strings[]
1529     = {"keyword", "colon", "string", "number", "comma", "end of input"};
1530
1531   /* Get the token that generated the error.  */
1532   token = linespec_lexer_lex_one (parser);
1533
1534   /* Finally, throw the error.  */
1535   if (token.type == LSTOKEN_STRING || token.type == LSTOKEN_NUMBER
1536       || token.type == LSTOKEN_KEYWORD)
1537     {
1538       char *string;
1539       struct cleanup *cleanup;
1540
1541       string = copy_token_string (token);
1542       cleanup = make_cleanup (xfree, string);
1543       throw_error (GENERIC_ERROR,
1544                    _("malformed linespec error: unexpected %s, \"%s\""),
1545                    token_type_strings[token.type], string);
1546     }
1547   else
1548     throw_error (GENERIC_ERROR,
1549                  _("malformed linespec error: unexpected %s"),
1550                  token_type_strings[token.type]);
1551 }
1552
1553 /* Parse and return a line offset in STRING.  */
1554
1555 static struct line_offset
1556 linespec_parse_line_offset (const char *string)
1557 {
1558   struct line_offset line_offset = {0, LINE_OFFSET_NONE};
1559
1560   if (*string == '+')
1561     {
1562       line_offset.sign = LINE_OFFSET_PLUS;
1563       ++string;
1564     }
1565   else if (*string == '-')
1566     {
1567       line_offset.sign = LINE_OFFSET_MINUS;
1568       ++string;
1569     }
1570
1571   /* Right now, we only allow base 10 for offsets.  */
1572   line_offset.offset = atoi (string);
1573   return line_offset;
1574 }
1575
1576 /* Parse the basic_spec in PARSER's input.  */
1577
1578 static void
1579 linespec_parse_basic (linespec_parser *parser)
1580 {
1581   char *name;
1582   linespec_token token;
1583   VEC (symbolp) *symbols, *labels;
1584   VEC (bound_minimal_symbol_d) *minimal_symbols;
1585   struct cleanup *cleanup;
1586
1587   /* Get the next token.  */
1588   token = linespec_lexer_lex_one (parser);
1589
1590   /* If it is EOI or KEYWORD, issue an error.  */
1591   if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1592     unexpected_linespec_error (parser);
1593   /* If it is a LSTOKEN_NUMBER, we have an offset.  */
1594   else if (token.type == LSTOKEN_NUMBER)
1595     {
1596       /* Record the line offset and get the next token.  */
1597       name = copy_token_string (token);
1598       cleanup = make_cleanup (xfree, name);
1599       PARSER_RESULT (parser)->line_offset = linespec_parse_line_offset (name);
1600       do_cleanups (cleanup);
1601
1602       /* Get the next token.  */
1603       token = linespec_lexer_consume_token (parser);
1604
1605       /* If the next token is a comma, stop parsing and return.  */
1606       if (token.type == LSTOKEN_COMMA)
1607         return;
1608
1609       /* If the next token is anything but EOI or KEYWORD, issue
1610          an error.  */
1611       if (token.type != LSTOKEN_KEYWORD && token.type != LSTOKEN_EOI)
1612         unexpected_linespec_error (parser);
1613     }
1614
1615   if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1616     return;
1617
1618   /* Next token must be LSTOKEN_STRING.  */
1619   if (token.type != LSTOKEN_STRING)
1620     unexpected_linespec_error (parser);
1621
1622   /* The current token will contain the name of a function, method,
1623      or label.  */
1624   name  = copy_token_string (token);
1625   cleanup = make_cleanup (xfree, name);
1626
1627   /* Try looking it up as a function/method.  */
1628   find_linespec_symbols (PARSER_STATE (parser),
1629                          PARSER_RESULT (parser)->file_symtabs, name,
1630                          &symbols, &minimal_symbols);
1631
1632   if (symbols != NULL || minimal_symbols != NULL)
1633     {
1634       PARSER_RESULT (parser)->function_symbols = symbols;
1635       PARSER_RESULT (parser)->minimal_symbols = minimal_symbols;
1636       PARSER_RESULT (parser)->function_name = name;
1637       symbols = NULL;
1638       discard_cleanups (cleanup);
1639     }
1640   else
1641     {
1642       /* NAME was not a function or a method.  So it must be a label
1643          name or user specified variable like "break foo.c:$zippo".  */
1644       labels = find_label_symbols (PARSER_STATE (parser), NULL,
1645                                    &symbols, name);
1646       if (labels != NULL)
1647         {
1648           PARSER_RESULT (parser)->labels.label_symbols = labels;
1649           PARSER_RESULT (parser)->labels.function_symbols = symbols;
1650           PARSER_RESULT (parser)->label_name = name;
1651           symbols = NULL;
1652           discard_cleanups (cleanup);
1653         }
1654       else if (token.type == LSTOKEN_STRING
1655                && *LS_TOKEN_STOKEN (token).ptr == '$')
1656         {
1657           /* User specified a convenience variable or history value.  */
1658           PARSER_RESULT (parser)->line_offset
1659             = linespec_parse_variable (PARSER_STATE (parser), name);
1660
1661           if (PARSER_RESULT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN)
1662             {
1663               /* The user-specified variable was not valid.  Do not
1664                  throw an error here.  parse_linespec will do it for us.  */
1665               PARSER_RESULT (parser)->function_name = name;
1666               discard_cleanups (cleanup);
1667               return;
1668             }
1669
1670           /* The convenience variable/history value parsed correctly.
1671              NAME is no longer needed.  */
1672           do_cleanups (cleanup);
1673         }
1674       else
1675         {
1676           /* The name is also not a label.  Abort parsing.  Do not throw
1677              an error here.  parse_linespec will do it for us.  */
1678
1679           /* Save a copy of the name we were trying to lookup.  */
1680           PARSER_RESULT (parser)->function_name = name;
1681           discard_cleanups (cleanup);
1682           return;
1683         }
1684     }
1685
1686   /* Get the next token.  */
1687   token = linespec_lexer_consume_token (parser);
1688
1689   if (token.type == LSTOKEN_COLON)
1690     {
1691       /* User specified a label or a lineno.  */
1692       token = linespec_lexer_consume_token (parser);
1693
1694       if (token.type == LSTOKEN_NUMBER)
1695         {
1696           /* User specified an offset.  Record the line offset and
1697              get the next token.  */
1698           name = copy_token_string (token);
1699           cleanup = make_cleanup (xfree, name);
1700           PARSER_RESULT (parser)->line_offset
1701             = linespec_parse_line_offset (name);
1702           do_cleanups (cleanup);
1703
1704           /* Ge the next token.  */
1705           token = linespec_lexer_consume_token (parser);
1706         }
1707       else if (token.type == LSTOKEN_STRING)
1708         {
1709           /* Grab a copy of the label's name and look it up.  */
1710           name = copy_token_string (token);
1711           cleanup = make_cleanup (xfree, name);
1712           labels = find_label_symbols (PARSER_STATE (parser),
1713                                        PARSER_RESULT (parser)->function_symbols,
1714                                        &symbols, name);
1715
1716           if (labels != NULL)
1717             {
1718               PARSER_RESULT (parser)->labels.label_symbols = labels;
1719               PARSER_RESULT (parser)->labels.function_symbols = symbols;
1720               PARSER_RESULT (parser)->label_name = name;
1721               symbols = NULL;
1722               discard_cleanups (cleanup);
1723             }
1724           else
1725             {
1726               /* We don't know what it was, but it isn't a label.  */
1727               throw_error (NOT_FOUND_ERROR,
1728                            _("No label \"%s\" defined in function \"%s\"."),
1729                            name, PARSER_RESULT (parser)->function_name);
1730             }
1731
1732           /* Check for a line offset.  */
1733           token = linespec_lexer_consume_token (parser);
1734           if (token.type == LSTOKEN_COLON)
1735             {
1736               /* Get the next token.  */
1737               token = linespec_lexer_consume_token (parser);
1738
1739               /* It must be a line offset.  */
1740               if (token.type != LSTOKEN_NUMBER)
1741                 unexpected_linespec_error (parser);
1742
1743               /* Record the lione offset and get the next token.  */
1744               name = copy_token_string (token);
1745               cleanup = make_cleanup (xfree, name);
1746
1747               PARSER_RESULT (parser)->line_offset
1748                 = linespec_parse_line_offset (name);
1749               do_cleanups (cleanup);
1750
1751               /* Get the next token.  */
1752               token = linespec_lexer_consume_token (parser);
1753             }
1754         }
1755       else
1756         {
1757           /* Trailing ':' in the input. Issue an error.  */
1758           unexpected_linespec_error (parser);
1759         }
1760     }
1761 }
1762
1763 /* Canonicalize the linespec contained in LS.  The result is saved into
1764    STATE->canonical.  */
1765
1766 static void
1767 canonicalize_linespec (struct linespec_state *state, linespec_p ls)
1768 {
1769   /* If canonicalization was not requested, no need to do anything.  */
1770   if (!state->canonical)
1771     return;
1772
1773   /* Shortcut expressions, which can only appear by themselves.  */
1774   if (ls->expression != NULL)
1775     state->canonical->addr_string = xstrdup (ls->expression);
1776   else
1777     {
1778       struct ui_file *buf;
1779       int need_colon = 0;
1780
1781       buf = mem_fileopen ();
1782       if (ls->source_filename)
1783         {
1784           fputs_unfiltered (ls->source_filename, buf);
1785           need_colon = 1;
1786         }
1787
1788       if (ls->function_name)
1789         {
1790           if (need_colon)
1791             fputc_unfiltered (':', buf);
1792           fputs_unfiltered (ls->function_name, buf);
1793           need_colon = 1;
1794         }
1795
1796       if (ls->label_name)
1797         {
1798           if (need_colon)
1799             fputc_unfiltered (':', buf);
1800
1801           if (ls->function_name == NULL)
1802             {
1803               struct symbol *s;
1804
1805               /* No function was specified, so add the symbol name.  */
1806               gdb_assert (ls->labels.function_symbols != NULL
1807                           && (VEC_length (symbolp, ls->labels.function_symbols)
1808                               == 1));
1809               s = VEC_index (symbolp, ls->labels.function_symbols, 0);
1810               fputs_unfiltered (SYMBOL_NATURAL_NAME (s), buf);
1811               fputc_unfiltered (':', buf);
1812             }
1813
1814           fputs_unfiltered (ls->label_name, buf);
1815           need_colon = 1;
1816           state->canonical->special_display = 1;
1817         }
1818
1819       if (ls->line_offset.sign != LINE_OFFSET_UNKNOWN)
1820         {
1821           if (need_colon)
1822             fputc_unfiltered (':', buf);
1823           fprintf_filtered (buf, "%s%d",
1824                             (ls->line_offset.sign == LINE_OFFSET_NONE ? ""
1825                              : (ls->line_offset.sign
1826                                 == LINE_OFFSET_PLUS ? "+" : "-")),
1827                             ls->line_offset.offset);
1828         }
1829
1830       state->canonical->addr_string = ui_file_xstrdup (buf, NULL);
1831       ui_file_delete (buf);
1832     }
1833 }
1834
1835 /* Given a line offset in LS, construct the relevant SALs.  */
1836
1837 static struct symtabs_and_lines
1838 create_sals_line_offset (struct linespec_state *self,
1839                          linespec_p ls)
1840 {
1841   struct symtabs_and_lines values;
1842   struct symtab_and_line val;
1843   int use_default = 0;
1844
1845   init_sal (&val);
1846   values.sals = NULL;
1847   values.nelts = 0;
1848
1849   /* This is where we need to make sure we have good defaults.
1850      We must guarantee that this section of code is never executed
1851      when we are called with just a function name, since
1852      set_default_source_symtab_and_line uses
1853      select_source_symtab that calls us with such an argument.  */
1854
1855   if (VEC_length (symtab_ptr, ls->file_symtabs) == 1
1856       && VEC_index (symtab_ptr, ls->file_symtabs, 0) == NULL)
1857     {
1858       const char *fullname;
1859
1860       set_current_program_space (self->program_space);
1861
1862       /* Make sure we have at least a default source line.  */
1863       set_default_source_symtab_and_line ();
1864       initialize_defaults (&self->default_symtab, &self->default_line);
1865       fullname = symtab_to_fullname (self->default_symtab);
1866       VEC_pop (symtab_ptr, ls->file_symtabs);
1867       VEC_free (symtab_ptr, ls->file_symtabs);
1868       ls->file_symtabs = collect_symtabs_from_filename (fullname);
1869       use_default = 1;
1870     }
1871
1872   val.line = ls->line_offset.offset;
1873   switch (ls->line_offset.sign)
1874     {
1875     case LINE_OFFSET_PLUS:
1876       if (ls->line_offset.offset == 0)
1877         val.line = 5;
1878       if (use_default)
1879         val.line = self->default_line + val.line;
1880       break;
1881
1882     case LINE_OFFSET_MINUS:
1883       if (ls->line_offset.offset == 0)
1884         val.line = 15;
1885       if (use_default)
1886         val.line = self->default_line - val.line;
1887       else
1888         val.line = -val.line;
1889       break;
1890
1891     case LINE_OFFSET_NONE:
1892       break;                    /* No need to adjust val.line.  */
1893     }
1894
1895   if (self->list_mode)
1896     decode_digits_list_mode (self, ls, &values, val);
1897   else
1898     {
1899       struct linetable_entry *best_entry = NULL;
1900       int *filter;
1901       const struct block **blocks;
1902       struct cleanup *cleanup;
1903       struct symtabs_and_lines intermediate_results;
1904       int i, j;
1905
1906       intermediate_results.sals = NULL;
1907       intermediate_results.nelts = 0;
1908
1909       decode_digits_ordinary (self, ls, val.line, &intermediate_results,
1910                               &best_entry);
1911       if (intermediate_results.nelts == 0 && best_entry != NULL)
1912         decode_digits_ordinary (self, ls, best_entry->line,
1913                                 &intermediate_results, &best_entry);
1914
1915       cleanup = make_cleanup (xfree, intermediate_results.sals);
1916
1917       /* For optimized code, the compiler can scatter one source line
1918          across disjoint ranges of PC values, even when no duplicate
1919          functions or inline functions are involved.  For example,
1920          'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
1921          function can result in two PC ranges.  In this case, we don't
1922          want to set a breakpoint on the first PC of each range.  To filter
1923          such cases, we use containing blocks -- for each PC found
1924          above, we see if there are other PCs that are in the same
1925          block.  If yes, the other PCs are filtered out.  */
1926
1927       filter = XNEWVEC (int, intermediate_results.nelts);
1928       make_cleanup (xfree, filter);
1929       blocks = XNEWVEC (const struct block *, intermediate_results.nelts);
1930       make_cleanup (xfree, blocks);
1931
1932       for (i = 0; i < intermediate_results.nelts; ++i)
1933         {
1934           set_current_program_space (intermediate_results.sals[i].pspace);
1935
1936           filter[i] = 1;
1937           blocks[i] = block_for_pc_sect (intermediate_results.sals[i].pc,
1938                                          intermediate_results.sals[i].section);
1939         }
1940
1941       for (i = 0; i < intermediate_results.nelts; ++i)
1942         {
1943           if (blocks[i] != NULL)
1944             for (j = i + 1; j < intermediate_results.nelts; ++j)
1945               {
1946                 if (blocks[j] == blocks[i])
1947                   {
1948                     filter[j] = 0;
1949                     break;
1950                   }
1951               }
1952         }
1953
1954       for (i = 0; i < intermediate_results.nelts; ++i)
1955         if (filter[i])
1956           {
1957             struct symbol *sym = (blocks[i]
1958                                   ? block_containing_function (blocks[i])
1959                                   : NULL);
1960
1961             if (self->funfirstline)
1962               skip_prologue_sal (&intermediate_results.sals[i]);
1963             /* Make sure the line matches the request, not what was
1964                found.  */
1965             intermediate_results.sals[i].line = val.line;
1966             add_sal_to_sals (self, &values, &intermediate_results.sals[i],
1967                              sym ? SYMBOL_NATURAL_NAME (sym) : NULL, 0);
1968           }
1969
1970       do_cleanups (cleanup);
1971     }
1972
1973   if (values.nelts == 0)
1974     {
1975       if (ls->source_filename)
1976         throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
1977                      val.line, ls->source_filename);
1978       else
1979         throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
1980                      val.line);
1981     }
1982
1983   return values;
1984 }
1985
1986 /* Create and return SALs from the linespec LS.  */
1987
1988 static struct symtabs_and_lines
1989 convert_linespec_to_sals (struct linespec_state *state, linespec_p ls)
1990 {
1991   struct symtabs_and_lines sals = {NULL, 0};
1992
1993   if (ls->expression != NULL)
1994     {
1995       struct symtab_and_line sal;
1996
1997       /* We have an expression.  No other attribute is allowed.  */
1998       sal = find_pc_line (ls->expr_pc, 0);
1999       sal.pc = ls->expr_pc;
2000       sal.section = find_pc_overlay (ls->expr_pc);
2001       sal.explicit_pc = 1;
2002       add_sal_to_sals (state, &sals, &sal, ls->expression, 1);
2003     }
2004   else if (ls->labels.label_symbols != NULL)
2005     {
2006       /* We have just a bunch of functions/methods or labels.  */
2007       int i;
2008       struct symtab_and_line sal;
2009       struct symbol *sym;
2010
2011       for (i = 0; VEC_iterate (symbolp, ls->labels.label_symbols, i, sym); ++i)
2012         {
2013           struct program_space *pspace = SYMTAB_PSPACE (symbol_symtab (sym));
2014
2015           if (symbol_to_sal (&sal, state->funfirstline, sym)
2016               && maybe_add_address (state->addr_set, pspace, sal.pc))
2017             add_sal_to_sals (state, &sals, &sal,
2018                              SYMBOL_NATURAL_NAME (sym), 0);
2019         }
2020     }
2021   else if (ls->function_symbols != NULL || ls->minimal_symbols != NULL)
2022     {
2023       /* We have just a bunch of functions and/or methods.  */
2024       int i;
2025       struct symtab_and_line sal;
2026       struct symbol *sym;
2027       bound_minimal_symbol_d *elem;
2028       struct program_space *pspace;
2029
2030       if (ls->function_symbols != NULL)
2031         {
2032           /* Sort symbols so that symbols with the same program space are next
2033              to each other.  */
2034           qsort (VEC_address (symbolp, ls->function_symbols),
2035                  VEC_length (symbolp, ls->function_symbols),
2036                  sizeof (symbolp), compare_symbols);
2037
2038           for (i = 0; VEC_iterate (symbolp, ls->function_symbols, i, sym); ++i)
2039             {
2040               pspace = SYMTAB_PSPACE (symbol_symtab (sym));
2041               set_current_program_space (pspace);
2042               if (symbol_to_sal (&sal, state->funfirstline, sym)
2043                   && maybe_add_address (state->addr_set, pspace, sal.pc))
2044                 add_sal_to_sals (state, &sals, &sal,
2045                                  SYMBOL_NATURAL_NAME (sym), 0);
2046             }
2047         }
2048
2049       if (ls->minimal_symbols != NULL)
2050         {
2051           /* Sort minimal symbols by program space, too.  */
2052           qsort (VEC_address (bound_minimal_symbol_d, ls->minimal_symbols),
2053                  VEC_length (bound_minimal_symbol_d, ls->minimal_symbols),
2054                  sizeof (bound_minimal_symbol_d), compare_msymbols);
2055
2056           for (i = 0;
2057                VEC_iterate (bound_minimal_symbol_d, ls->minimal_symbols,
2058                             i, elem);
2059                ++i)
2060             {
2061               pspace = elem->objfile->pspace;
2062               set_current_program_space (pspace);
2063               minsym_found (state, elem->objfile, elem->minsym, &sals);
2064             }
2065         }
2066     }
2067   else if (ls->line_offset.sign != LINE_OFFSET_UNKNOWN)
2068     {
2069       /* Only an offset was specified.  */
2070         sals = create_sals_line_offset (state, ls);
2071
2072         /* Make sure we have a filename for canonicalization.  */
2073         if (ls->source_filename == NULL)
2074           {
2075             const char *fullname = symtab_to_fullname (state->default_symtab);
2076
2077             /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2078                form so that displaying SOURCE_FILENAME can follow the current
2079                FILENAME_DISPLAY_STRING setting.  But as it is used only rarely
2080                it has been kept for code simplicity only in absolute form.  */
2081             ls->source_filename = xstrdup (fullname);
2082           }
2083     }
2084   else
2085     {
2086       /* We haven't found any results...  */
2087       return sals;
2088     }
2089
2090   canonicalize_linespec (state, ls);
2091
2092   if (sals.nelts > 0 && state->canonical != NULL)
2093     state->canonical->pre_expanded = 1;
2094
2095   return sals;
2096 }
2097
2098 /* Parse a string that specifies a linespec.
2099    Pass the address of a char * variable; that variable will be
2100    advanced over the characters actually parsed.
2101
2102    The basic grammar of linespecs:
2103
2104    linespec -> expr_spec | var_spec | basic_spec
2105    expr_spec -> '*' STRING
2106    var_spec -> '$' (STRING | NUMBER)
2107
2108    basic_spec -> file_offset_spec | function_spec | label_spec
2109    file_offset_spec -> opt_file_spec offset_spec
2110    function_spec -> opt_file_spec function_name_spec opt_label_spec
2111    label_spec -> label_name_spec
2112
2113    opt_file_spec -> "" | file_name_spec ':'
2114    opt_label_spec -> "" | ':' label_name_spec
2115
2116    file_name_spec -> STRING
2117    function_name_spec -> STRING
2118    label_name_spec -> STRING
2119    function_name_spec -> STRING
2120    offset_spec -> NUMBER
2121                -> '+' NUMBER
2122                -> '-' NUMBER
2123
2124    This may all be followed by several keywords such as "if EXPR",
2125    which we ignore.
2126
2127    A comma will terminate parsing.
2128
2129    The function may be an undebuggable function found in minimal symbol table.
2130
2131    If the argument FUNFIRSTLINE is nonzero, we want the first line
2132    of real code inside a function when a function is specified, and it is
2133    not OK to specify a variable or type to get its line number.
2134
2135    DEFAULT_SYMTAB specifies the file to use if none is specified.
2136    It defaults to current_source_symtab.
2137    DEFAULT_LINE specifies the line number to use for relative
2138    line numbers (that start with signs).  Defaults to current_source_line.
2139    If CANONICAL is non-NULL, store an array of strings containing the canonical
2140    line specs there if necessary.  Currently overloaded member functions and
2141    line numbers or static functions without a filename yield a canonical
2142    line spec.  The array and the line spec strings are allocated on the heap,
2143    it is the callers responsibility to free them.
2144
2145    Note that it is possible to return zero for the symtab
2146    if no file is validly specified.  Callers must check that.
2147    Also, the line number returned may be invalid.  */
2148
2149 /* Parse the linespec in ARGPTR.  */
2150
2151 static struct symtabs_and_lines
2152 parse_linespec (linespec_parser *parser, const char **argptr)
2153 {
2154   linespec_token token;
2155   struct symtabs_and_lines values;
2156   struct gdb_exception file_exception = exception_none;
2157   struct cleanup *cleanup;
2158
2159   /* A special case to start.  It has become quite popular for
2160      IDEs to work around bugs in the previous parser by quoting
2161      the entire linespec, so we attempt to deal with this nicely.  */
2162   parser->is_quote_enclosed = 0;
2163   if (!is_ada_operator (*argptr)
2164       && strchr (linespec_quote_characters, **argptr) != NULL)
2165     {
2166       const char *end;
2167
2168       end = skip_quote_char (*argptr + 1, **argptr);
2169       if (end != NULL && is_closing_quote_enclosed (end))
2170         {
2171           /* Here's the special case.  Skip ARGPTR past the initial
2172              quote.  */
2173           ++(*argptr);
2174           parser->is_quote_enclosed = 1;
2175         }
2176     }
2177
2178   /* A keyword at the start cannot be interpreted as such.
2179      Consider "b thread thread 42".  */
2180   parser->keyword_ok = 0;
2181
2182   parser->lexer.saved_arg = *argptr;
2183   parser->lexer.stream = argptr;
2184
2185   /* Initialize the default symtab and line offset.  */
2186   initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2187                        &PARSER_STATE (parser)->default_line);
2188
2189   /* Objective-C shortcut.  */
2190   values = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), argptr);
2191   if (values.sals != NULL)
2192     return values;
2193
2194   /* Start parsing.  */
2195
2196   /* Get the first token.  */
2197   token = linespec_lexer_lex_one (parser);
2198
2199   /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER.  */
2200   if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '*')
2201     {
2202       char *expr;
2203       const char *copy;
2204
2205       /* User specified an expression, *EXPR.  */
2206       copy = expr = copy_token_string (token);
2207       cleanup = make_cleanup (xfree, expr);
2208       PARSER_RESULT (parser)->expr_pc = linespec_expression_to_pc (&copy);
2209       discard_cleanups (cleanup);
2210       PARSER_RESULT (parser)->expression = expr;
2211
2212       /* This is a little hacky/tricky.  If linespec_expression_to_pc
2213          did not evaluate the entire token, then we must find the
2214          string COPY inside the original token buffer.  */
2215       if (*copy != '\0')
2216         {
2217           PARSER_STREAM (parser) = strstr (parser->lexer.saved_arg, copy);
2218           gdb_assert (PARSER_STREAM (parser) != NULL);
2219         }
2220
2221       /* Consume the token.  */
2222       linespec_lexer_consume_token (parser);
2223
2224       goto convert_to_sals;
2225     }
2226   else if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2227     {
2228       char *var;
2229
2230       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2231       VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2232
2233       /* User specified a convenience variable or history value.  */
2234       var = copy_token_string (token);
2235       cleanup = make_cleanup (xfree, var);
2236       PARSER_RESULT (parser)->line_offset
2237         = linespec_parse_variable (PARSER_STATE (parser), var);
2238       do_cleanups (cleanup);
2239
2240       /* If a line_offset wasn't found (VAR is the name of a user
2241          variable/function), then skip to normal symbol processing.  */
2242       if (PARSER_RESULT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2243         {
2244           /* Consume this token.  */
2245           linespec_lexer_consume_token (parser);
2246
2247           goto convert_to_sals;
2248         }
2249     }
2250   else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2251     unexpected_linespec_error (parser);
2252
2253   /* Now we can recognize keywords.  */
2254   parser->keyword_ok = 1;
2255
2256   /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2257      this token cannot represent a filename.  */
2258   token = linespec_lexer_peek_token (parser);
2259
2260   if (token.type == LSTOKEN_COLON)
2261     {
2262       char *user_filename;
2263
2264       /* Get the current token again and extract the filename.  */
2265       token = linespec_lexer_lex_one (parser);
2266       user_filename = copy_token_string (token);
2267
2268       /* Check if the input is a filename.  */
2269       TRY
2270         {
2271           PARSER_RESULT (parser)->file_symtabs
2272             = symtabs_from_filename (user_filename);
2273         }
2274       CATCH (ex, RETURN_MASK_ERROR)
2275         {
2276           file_exception = ex;
2277         }
2278       END_CATCH
2279
2280       if (file_exception.reason >= 0)
2281         {
2282           /* Symtabs were found for the file.  Record the filename.  */
2283           PARSER_RESULT (parser)->source_filename = user_filename;
2284
2285           /* Get the next token.  */
2286           token = linespec_lexer_consume_token (parser);
2287
2288           /* This is LSTOKEN_COLON; consume it.  */
2289           linespec_lexer_consume_token (parser);
2290         }
2291       else
2292         {
2293           /* No symtabs found -- discard user_filename.  */
2294           xfree (user_filename);
2295
2296           /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2297           VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2298         }
2299     }
2300   /* If the next token is not EOI, KEYWORD, or COMMA, issue an error.  */
2301   else if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2302            && token.type != LSTOKEN_COMMA)
2303     {
2304       /* TOKEN is the _next_ token, not the one currently in the parser.
2305          Consuming the token will give the correct error message.  */
2306       linespec_lexer_consume_token (parser);
2307       unexpected_linespec_error (parser);
2308     }
2309   else
2310     {
2311       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2312       VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2313     }
2314
2315   /* Parse the rest of the linespec.  */
2316   linespec_parse_basic (parser);
2317
2318   if (PARSER_RESULT (parser)->function_symbols == NULL
2319       && PARSER_RESULT (parser)->labels.label_symbols == NULL
2320       && PARSER_RESULT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2321       && PARSER_RESULT (parser)->minimal_symbols == NULL)
2322     {
2323       /* The linespec didn't parse.  Re-throw the file exception if
2324          there was one.  */
2325       if (file_exception.reason < 0)
2326         throw_exception (file_exception);
2327
2328       /* Otherwise, the symbol is not found.  */
2329       symbol_not_found_error (PARSER_RESULT (parser)->function_name,
2330                               PARSER_RESULT (parser)->source_filename);
2331     }
2332
2333  convert_to_sals:
2334
2335   /* Get the last token and record how much of the input was parsed,
2336      if necessary.  */
2337   token = linespec_lexer_lex_one (parser);
2338   if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2339     PARSER_STREAM (parser) = LS_TOKEN_STOKEN (token).ptr;
2340
2341   /* Convert the data in PARSER_RESULT to SALs.  */
2342   values = convert_linespec_to_sals (PARSER_STATE (parser),
2343                                      PARSER_RESULT (parser));
2344
2345   return values;
2346 }
2347
2348
2349 /* A constructor for linespec_state.  */
2350
2351 static void
2352 linespec_state_constructor (struct linespec_state *self,
2353                             int flags, const struct language_defn *language,
2354                             struct symtab *default_symtab,
2355                             int default_line,
2356                             struct linespec_result *canonical)
2357 {
2358   memset (self, 0, sizeof (*self));
2359   self->language = language;
2360   self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2361   self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2362   self->default_symtab = default_symtab;
2363   self->default_line = default_line;
2364   self->canonical = canonical;
2365   self->program_space = current_program_space;
2366   self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2367                                       xfree, xcalloc, xfree);
2368 }
2369
2370 /* Initialize a new linespec parser.  */
2371
2372 static void
2373 linespec_parser_new (linespec_parser *parser,
2374                      int flags, const struct language_defn *language,
2375                      struct symtab *default_symtab,
2376                      int default_line,
2377                      struct linespec_result *canonical)
2378 {
2379   parser->lexer.current.type = LSTOKEN_CONSUMED;
2380   memset (PARSER_RESULT (parser), 0, sizeof (struct linespec));
2381   PARSER_RESULT (parser)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2382   linespec_state_constructor (PARSER_STATE (parser), flags, language,
2383                               default_symtab, default_line, canonical);
2384 }
2385
2386 /* A destructor for linespec_state.  */
2387
2388 static void
2389 linespec_state_destructor (struct linespec_state *self)
2390 {
2391   htab_delete (self->addr_set);
2392 }
2393
2394 /* Delete a linespec parser.  */
2395
2396 static void
2397 linespec_parser_delete (void *arg)
2398 {
2399   linespec_parser *parser = (linespec_parser *) arg;
2400
2401   xfree ((char *) PARSER_RESULT (parser)->expression);
2402   xfree ((char *) PARSER_RESULT (parser)->source_filename);
2403   xfree ((char *) PARSER_RESULT (parser)->label_name);
2404   xfree ((char *) PARSER_RESULT (parser)->function_name);
2405
2406   if (PARSER_RESULT (parser)->file_symtabs != NULL)
2407     VEC_free (symtab_ptr, PARSER_RESULT (parser)->file_symtabs);
2408
2409   if (PARSER_RESULT (parser)->function_symbols != NULL)
2410     VEC_free (symbolp, PARSER_RESULT (parser)->function_symbols);
2411
2412   if (PARSER_RESULT (parser)->minimal_symbols != NULL)
2413     VEC_free (bound_minimal_symbol_d, PARSER_RESULT (parser)->minimal_symbols);
2414
2415   if (PARSER_RESULT (parser)->labels.label_symbols != NULL)
2416     VEC_free (symbolp, PARSER_RESULT (parser)->labels.label_symbols);
2417
2418   if (PARSER_RESULT (parser)->labels.function_symbols != NULL)
2419     VEC_free (symbolp, PARSER_RESULT (parser)->labels.function_symbols);
2420
2421   linespec_state_destructor (PARSER_STATE (parser));
2422 }
2423
2424 /* See linespec.h.  */
2425
2426 void
2427 decode_line_full (char **argptr, int flags,
2428                   struct symtab *default_symtab,
2429                   int default_line, struct linespec_result *canonical,
2430                   const char *select_mode,
2431                   const char *filter)
2432 {
2433   struct symtabs_and_lines result;
2434   struct cleanup *cleanups;
2435   VEC (const_char_ptr) *filters = NULL;
2436   linespec_parser parser;
2437   struct linespec_state *state;
2438   const char *copy, *orig;
2439
2440   gdb_assert (canonical != NULL);
2441   /* The filter only makes sense for 'all'.  */
2442   gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
2443   gdb_assert (select_mode == NULL
2444               || select_mode == multiple_symbols_all
2445               || select_mode == multiple_symbols_ask
2446               || select_mode == multiple_symbols_cancel);
2447   gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
2448
2449   linespec_parser_new (&parser, flags, current_language, default_symtab,
2450                        default_line, canonical);
2451   cleanups = make_cleanup (linespec_parser_delete, &parser);
2452   save_current_program_space ();
2453
2454   orig = copy = *argptr;
2455   result = parse_linespec (&parser, &copy);
2456   *argptr += copy - orig;
2457   state = PARSER_STATE (&parser);
2458
2459   gdb_assert (result.nelts == 1 || canonical->pre_expanded);
2460   gdb_assert (canonical->addr_string != NULL);
2461   canonical->pre_expanded = 1;
2462
2463   /* Arrange for allocated canonical names to be freed.  */
2464   if (result.nelts > 0)
2465     {
2466       int i;
2467
2468       make_cleanup (xfree, state->canonical_names);
2469       for (i = 0; i < result.nelts; ++i)
2470         {
2471           gdb_assert (state->canonical_names[i].suffix != NULL);
2472           make_cleanup (xfree, state->canonical_names[i].suffix);
2473         }
2474     }
2475
2476   if (select_mode == NULL)
2477     {
2478       if (ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
2479         select_mode = multiple_symbols_all;
2480       else
2481         select_mode = multiple_symbols_select_mode ();
2482     }
2483
2484   if (select_mode == multiple_symbols_all)
2485     {
2486       if (filter != NULL)
2487         {
2488           make_cleanup (VEC_cleanup (const_char_ptr), &filters);
2489           VEC_safe_push (const_char_ptr, filters, filter);
2490           filter_results (state, &result, filters);
2491         }
2492       else
2493         convert_results_to_lsals (state, &result);
2494     }
2495   else
2496     decode_line_2 (state, &result, select_mode);
2497
2498   do_cleanups (cleanups);
2499 }
2500
2501 /* See linespec.h.  */
2502
2503 struct symtabs_and_lines
2504 decode_line_1 (char **argptr, int flags,
2505                struct symtab *default_symtab,
2506                int default_line)
2507 {
2508   struct symtabs_and_lines result;
2509   linespec_parser parser;
2510   struct cleanup *cleanups;
2511   const char *copy, *orig;
2512
2513   linespec_parser_new (&parser, flags, current_language, default_symtab,
2514                        default_line, NULL);
2515   cleanups = make_cleanup (linespec_parser_delete, &parser);
2516   save_current_program_space ();
2517
2518   orig = copy = *argptr;
2519   result = parse_linespec (&parser, &copy);
2520   *argptr += copy - orig;
2521
2522   do_cleanups (cleanups);
2523   return result;
2524 }
2525
2526 /* See linespec.h.  */
2527
2528 struct symtabs_and_lines
2529 decode_line_with_current_source (char *string, int flags)
2530 {
2531   struct symtabs_and_lines sals;
2532   struct symtab_and_line cursal;
2533
2534   if (string == 0)
2535     error (_("Empty line specification."));
2536
2537   /* We use whatever is set as the current source line.  We do not try
2538      and get a default source symtab+line or it will recursively call us!  */
2539   cursal = get_current_source_symtab_and_line ();
2540
2541   sals = decode_line_1 (&string, flags,
2542                         cursal.symtab, cursal.line);
2543
2544   if (*string)
2545     error (_("Junk at end of line specification: %s"), string);
2546   return sals;
2547 }
2548
2549 /* See linespec.h.  */
2550
2551 struct symtabs_and_lines
2552 decode_line_with_last_displayed (char *string, int flags)
2553 {
2554   struct symtabs_and_lines sals;
2555
2556   if (string == 0)
2557     error (_("Empty line specification."));
2558
2559   if (last_displayed_sal_is_valid ())
2560     sals = decode_line_1 (&string, flags,
2561                           get_last_displayed_symtab (),
2562                           get_last_displayed_line ());
2563   else
2564     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
2565
2566   if (*string)
2567     error (_("Junk at end of line specification: %s"), string);
2568   return sals;
2569 }
2570
2571 \f
2572
2573 /* First, some functions to initialize stuff at the beggining of the
2574    function.  */
2575
2576 static void
2577 initialize_defaults (struct symtab **default_symtab, int *default_line)
2578 {
2579   if (*default_symtab == 0)
2580     {
2581       /* Use whatever we have for the default source line.  We don't use
2582          get_current_or_default_symtab_and_line as it can recurse and call
2583          us back!  */
2584       struct symtab_and_line cursal = 
2585         get_current_source_symtab_and_line ();
2586       
2587       *default_symtab = cursal.symtab;
2588       *default_line = cursal.line;
2589     }
2590 }
2591
2592 \f
2593
2594 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
2595    advancing EXP_PTR past any parsed text.  */
2596
2597 static CORE_ADDR
2598 linespec_expression_to_pc (const char **exp_ptr)
2599 {
2600   if (current_program_space->executing_startup)
2601     /* The error message doesn't really matter, because this case
2602        should only hit during breakpoint reset.  */
2603     throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
2604                                     "program space is in startup"));
2605
2606   (*exp_ptr)++;
2607   return value_as_address (parse_to_comma_and_eval (exp_ptr));
2608 }
2609
2610 \f
2611
2612 /* Here's where we recognise an Objective-C Selector.  An Objective C
2613    selector may be implemented by more than one class, therefore it
2614    may represent more than one method/function.  This gives us a
2615    situation somewhat analogous to C++ overloading.  If there's more
2616    than one method that could represent the selector, then use some of
2617    the existing C++ code to let the user choose one.  */
2618
2619 static struct symtabs_and_lines
2620 decode_objc (struct linespec_state *self, linespec_p ls, const char **argptr)
2621 {
2622   struct collect_info info;
2623   VEC (const_char_ptr) *symbol_names = NULL;
2624   struct symtabs_and_lines values;
2625   const char *new_argptr;
2626   struct cleanup *cleanup = make_cleanup (VEC_cleanup (const_char_ptr),
2627                                           &symbol_names);
2628
2629   info.state = self;
2630   info.file_symtabs = NULL;
2631   VEC_safe_push (symtab_ptr, info.file_symtabs, NULL);
2632   make_cleanup (VEC_cleanup (symtab_ptr), &info.file_symtabs);
2633   info.result.symbols = NULL;
2634   info.result.minimal_symbols = NULL;
2635   values.nelts = 0;
2636   values.sals = NULL;
2637
2638   new_argptr = find_imps (*argptr, &symbol_names); 
2639   if (VEC_empty (const_char_ptr, symbol_names))
2640     {
2641       do_cleanups (cleanup);
2642       return values;
2643     }
2644
2645   add_all_symbol_names_from_pspace (&info, NULL, symbol_names);
2646
2647   if (!VEC_empty (symbolp, info.result.symbols)
2648       || !VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
2649     {
2650       char *saved_arg;
2651
2652       saved_arg = alloca (new_argptr - *argptr + 1);
2653       memcpy (saved_arg, *argptr, new_argptr - *argptr);
2654       saved_arg[new_argptr - *argptr] = '\0';
2655
2656       ls->function_name = xstrdup (saved_arg);
2657       ls->function_symbols = info.result.symbols;
2658       ls->minimal_symbols = info.result.minimal_symbols;
2659       values = convert_linespec_to_sals (self, ls);
2660
2661       if (self->canonical)
2662         {
2663           self->canonical->pre_expanded = 1;
2664           if (ls->source_filename)
2665             self->canonical->addr_string
2666               = xstrprintf ("%s:%s", ls->source_filename, saved_arg);
2667           else
2668             self->canonical->addr_string = xstrdup (saved_arg);
2669         }
2670     }
2671
2672   *argptr = new_argptr;
2673
2674   do_cleanups (cleanup);
2675
2676   return values;
2677 }
2678
2679 /* An instance of this type is used when collecting prefix symbols for
2680    decode_compound.  */
2681
2682 struct decode_compound_collector
2683 {
2684   /* The result vector.  */
2685   VEC (symbolp) *symbols;
2686
2687   /* A hash table of all symbols we found.  We use this to avoid
2688      adding any symbol more than once.  */
2689   htab_t unique_syms;
2690 };
2691
2692 /* A callback for iterate_over_symbols that is used by
2693    lookup_prefix_sym to collect type symbols.  */
2694
2695 static int
2696 collect_one_symbol (struct symbol *sym, void *d)
2697 {
2698   struct decode_compound_collector *collector = d;
2699   void **slot;
2700   struct type *t;
2701
2702   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
2703     return 1; /* Continue iterating.  */
2704
2705   t = SYMBOL_TYPE (sym);
2706   CHECK_TYPEDEF (t);
2707   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2708       && TYPE_CODE (t) != TYPE_CODE_UNION
2709       && TYPE_CODE (t) != TYPE_CODE_NAMESPACE)
2710     return 1; /* Continue iterating.  */
2711
2712   slot = htab_find_slot (collector->unique_syms, sym, INSERT);
2713   if (!*slot)
2714     {
2715       *slot = sym;
2716       VEC_safe_push (symbolp, collector->symbols, sym);
2717     }
2718
2719   return 1; /* Continue iterating.  */
2720 }
2721
2722 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS.  */
2723
2724 static VEC (symbolp) *
2725 lookup_prefix_sym (struct linespec_state *state, VEC (symtab_ptr) *file_symtabs,
2726                    const char *class_name)
2727 {
2728   int ix;
2729   struct symtab *elt;
2730   struct decode_compound_collector collector;
2731   struct cleanup *outer;
2732   struct cleanup *cleanup;
2733
2734   collector.symbols = NULL;
2735   outer = make_cleanup (VEC_cleanup (symbolp), &collector.symbols);
2736
2737   collector.unique_syms = htab_create_alloc (1, htab_hash_pointer,
2738                                              htab_eq_pointer, NULL,
2739                                              xcalloc, xfree);
2740   cleanup = make_cleanup_htab_delete (collector.unique_syms);
2741
2742   for (ix = 0; VEC_iterate (symtab_ptr, file_symtabs, ix, elt); ++ix)
2743     {
2744       if (elt == NULL)
2745         {
2746           iterate_over_all_matching_symtabs (state, class_name, STRUCT_DOMAIN,
2747                                              collect_one_symbol, &collector,
2748                                              NULL, 0);
2749           iterate_over_all_matching_symtabs (state, class_name, VAR_DOMAIN,
2750                                              collect_one_symbol, &collector,
2751                                              NULL, 0);
2752         }
2753       else
2754         {
2755           /* Program spaces that are executing startup should have
2756              been filtered out earlier.  */
2757           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
2758           set_current_program_space (SYMTAB_PSPACE (elt));
2759           iterate_over_file_blocks (elt, class_name, STRUCT_DOMAIN,
2760                                     collect_one_symbol, &collector);
2761           iterate_over_file_blocks (elt, class_name, VAR_DOMAIN,
2762                                     collect_one_symbol, &collector);
2763         }
2764     }
2765
2766   do_cleanups (cleanup);
2767   discard_cleanups (outer);
2768   return collector.symbols;
2769 }
2770
2771 /* A qsort comparison function for symbols.  The resulting order does
2772    not actually matter; we just need to be able to sort them so that
2773    symbols with the same program space end up next to each other.  */
2774
2775 static int
2776 compare_symbols (const void *a, const void *b)
2777 {
2778   struct symbol * const *sa = a;
2779   struct symbol * const *sb = b;
2780   uintptr_t uia, uib;
2781
2782   uia = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (*sa));
2783   uib = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (*sb));
2784
2785   if (uia < uib)
2786     return -1;
2787   if (uia > uib)
2788     return 1;
2789
2790   uia = (uintptr_t) *sa;
2791   uib = (uintptr_t) *sb;
2792
2793   if (uia < uib)
2794     return -1;
2795   if (uia > uib)
2796     return 1;
2797
2798   return 0;
2799 }
2800
2801 /* Like compare_symbols but for minimal symbols.  */
2802
2803 static int
2804 compare_msymbols (const void *a, const void *b)
2805 {
2806   const struct bound_minimal_symbol *sa = a;
2807   const struct bound_minimal_symbol *sb = b;
2808   uintptr_t uia, uib;
2809
2810   uia = (uintptr_t) sa->objfile->pspace;
2811   uib = (uintptr_t) sa->objfile->pspace;
2812
2813   if (uia < uib)
2814     return -1;
2815   if (uia > uib)
2816     return 1;
2817
2818   uia = (uintptr_t) sa->minsym;
2819   uib = (uintptr_t) sb->minsym;
2820
2821   if (uia < uib)
2822     return -1;
2823   if (uia > uib)
2824     return 1;
2825
2826   return 0;
2827 }
2828
2829 /* Look for all the matching instances of each symbol in NAMES.  Only
2830    instances from PSPACE are considered; other program spaces are
2831    handled by our caller.  If PSPACE is NULL, then all program spaces
2832    are considered.  Results are stored into INFO.  */
2833
2834 static void
2835 add_all_symbol_names_from_pspace (struct collect_info *info,
2836                                   struct program_space *pspace,
2837                                   VEC (const_char_ptr) *names)
2838 {
2839   int ix;
2840   const char *iter;
2841
2842   for (ix = 0; VEC_iterate (const_char_ptr, names, ix, iter); ++ix)
2843     add_matching_symbols_to_info (iter, info, pspace);
2844 }
2845
2846 static void
2847 find_superclass_methods (VEC (typep) *superclasses,
2848                          const char *name,
2849                          VEC (const_char_ptr) **result_names)
2850 {
2851   int old_len = VEC_length (const_char_ptr, *result_names);
2852   VEC (typep) *iter_classes;
2853   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2854
2855   iter_classes = superclasses;
2856   while (1)
2857     {
2858       VEC (typep) *new_supers = NULL;
2859       int ix;
2860       struct type *t;
2861
2862       make_cleanup (VEC_cleanup (typep), &new_supers);
2863       for (ix = 0; VEC_iterate (typep, iter_classes, ix, t); ++ix)
2864         find_methods (t, name, result_names, &new_supers);
2865
2866       if (VEC_length (const_char_ptr, *result_names) != old_len
2867           || VEC_empty (typep, new_supers))
2868         break;
2869
2870       iter_classes = new_supers;
2871     }
2872
2873   do_cleanups (cleanup);
2874 }
2875
2876 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
2877    given by one of the symbols in SYM_CLASSES.  Matches are returned
2878    in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols).  */
2879
2880 static void
2881 find_method (struct linespec_state *self, VEC (symtab_ptr) *file_symtabs,
2882              const char *class_name, const char *method_name,
2883              VEC (symbolp) *sym_classes, VEC (symbolp) **symbols,
2884              VEC (bound_minimal_symbol_d) **minsyms)
2885 {
2886   struct symbol *sym;
2887   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2888   int ix;
2889   int last_result_len;
2890   VEC (typep) *superclass_vec;
2891   VEC (const_char_ptr) *result_names;
2892   struct collect_info info;
2893
2894   /* Sort symbols so that symbols with the same program space are next
2895      to each other.  */
2896   qsort (VEC_address (symbolp, sym_classes),
2897          VEC_length (symbolp, sym_classes),
2898          sizeof (symbolp),
2899          compare_symbols);
2900
2901   info.state = self;
2902   info.file_symtabs = file_symtabs;
2903   info.result.symbols = NULL;
2904   info.result.minimal_symbols = NULL;
2905
2906   /* Iterate over all the types, looking for the names of existing
2907      methods matching METHOD_NAME.  If we cannot find a direct method in a
2908      given program space, then we consider inherited methods; this is
2909      not ideal (ideal would be to respect C++ hiding rules), but it
2910      seems good enough and is what GDB has historically done.  We only
2911      need to collect the names because later we find all symbols with
2912      those names.  This loop is written in a somewhat funny way
2913      because we collect data across the program space before deciding
2914      what to do.  */
2915   superclass_vec = NULL;
2916   make_cleanup (VEC_cleanup (typep), &superclass_vec);
2917   result_names = NULL;
2918   make_cleanup (VEC_cleanup (const_char_ptr), &result_names);
2919   last_result_len = 0;
2920   for (ix = 0; VEC_iterate (symbolp, sym_classes, ix, sym); ++ix)
2921     {
2922       struct type *t;
2923       struct program_space *pspace;
2924
2925       /* Program spaces that are executing startup should have
2926          been filtered out earlier.  */
2927       pspace = SYMTAB_PSPACE (symbol_symtab (sym));
2928       gdb_assert (!pspace->executing_startup);
2929       set_current_program_space (pspace);
2930       t = check_typedef (SYMBOL_TYPE (sym));
2931       find_methods (t, method_name, &result_names, &superclass_vec);
2932
2933       /* Handle all items from a single program space at once; and be
2934          sure not to miss the last batch.  */
2935       if (ix == VEC_length (symbolp, sym_classes) - 1
2936           || (pspace
2937               != SYMTAB_PSPACE (symbol_symtab (VEC_index (symbolp, sym_classes,
2938                                                           ix + 1)))))
2939         {
2940           /* If we did not find a direct implementation anywhere in
2941              this program space, consider superclasses.  */
2942           if (VEC_length (const_char_ptr, result_names) == last_result_len)
2943             find_superclass_methods (superclass_vec, method_name,
2944                                      &result_names);
2945
2946           /* We have a list of candidate symbol names, so now we
2947              iterate over the symbol tables looking for all
2948              matches in this pspace.  */
2949           add_all_symbol_names_from_pspace (&info, pspace, result_names);
2950
2951           VEC_truncate (typep, superclass_vec, 0);
2952           last_result_len = VEC_length (const_char_ptr, result_names);
2953         }
2954     }
2955
2956   if (!VEC_empty (symbolp, info.result.symbols)
2957       || !VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
2958     {
2959       *symbols = info.result.symbols;
2960       *minsyms = info.result.minimal_symbols;
2961       do_cleanups (cleanup);
2962       return;
2963     }
2964
2965   /* Throw an NOT_FOUND_ERROR.  This will be caught by the caller
2966      and other attempts to locate the symbol will be made.  */
2967   throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
2968 }
2969
2970 \f
2971
2972 /* This object is used when collecting all matching symtabs.  */
2973
2974 struct symtab_collector
2975 {
2976   /* The result vector of symtabs.  */
2977   VEC (symtab_ptr) *symtabs;
2978
2979   /* This is used to ensure the symtabs are unique.  */
2980   htab_t symtab_table;
2981 };
2982
2983 /* Callback for iterate_over_symtabs.  */
2984
2985 static int
2986 add_symtabs_to_list (struct symtab *symtab, void *d)
2987 {
2988   struct symtab_collector *data = d;
2989   void **slot;
2990
2991   slot = htab_find_slot (data->symtab_table, symtab, INSERT);
2992   if (!*slot)
2993     {
2994       *slot = symtab;
2995       VEC_safe_push (symtab_ptr, data->symtabs, symtab);
2996     }
2997
2998   return 0;
2999 }
3000
3001 /* Given a file name, return a VEC of all matching symtabs.  */
3002
3003 static VEC (symtab_ptr) *
3004 collect_symtabs_from_filename (const char *file)
3005 {
3006   struct symtab_collector collector;
3007   struct cleanup *cleanups;
3008   struct program_space *pspace;
3009
3010   collector.symtabs = NULL;
3011   collector.symtab_table = htab_create (1, htab_hash_pointer, htab_eq_pointer,
3012                                         NULL);
3013   cleanups = make_cleanup_htab_delete (collector.symtab_table);
3014
3015   /* Find that file's data.  */
3016   ALL_PSPACES (pspace)
3017   {
3018     if (pspace->executing_startup)
3019       continue;
3020
3021     set_current_program_space (pspace);
3022     iterate_over_symtabs (file, add_symtabs_to_list, &collector);
3023   }
3024
3025   do_cleanups (cleanups);
3026   return collector.symtabs;
3027 }
3028
3029 /* Return all the symtabs associated to the FILENAME.  */
3030
3031 static VEC (symtab_ptr) *
3032 symtabs_from_filename (const char *filename)
3033 {
3034   VEC (symtab_ptr) *result;
3035   
3036   result = collect_symtabs_from_filename (filename);
3037
3038   if (VEC_empty (symtab_ptr, result))
3039     {
3040       if (!have_full_symbols () && !have_partial_symbols ())
3041         throw_error (NOT_FOUND_ERROR,
3042                      _("No symbol table is loaded.  "
3043                        "Use the \"file\" command."));
3044       throw_error (NOT_FOUND_ERROR, _("No source file named %s."), filename);
3045     }
3046
3047   return result;
3048 }
3049
3050 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS.  Matching
3051    debug symbols are returned in SYMBOLS.  Matching minimal symbols are
3052    returned in MINSYMS.  */
3053
3054 static void
3055 find_function_symbols (struct linespec_state *state,
3056                        VEC (symtab_ptr) *file_symtabs, const char *name,
3057                        VEC (symbolp) **symbols,
3058                        VEC (bound_minimal_symbol_d) **minsyms)
3059 {
3060   struct collect_info info;
3061   VEC (const_char_ptr) *symbol_names = NULL;
3062   struct cleanup *cleanup = make_cleanup (VEC_cleanup (const_char_ptr),
3063                                           &symbol_names);
3064
3065   info.state = state;
3066   info.result.symbols = NULL;
3067   info.result.minimal_symbols = NULL;
3068   info.file_symtabs = file_symtabs;
3069
3070   /* Try NAME as an Objective-C selector.  */
3071   find_imps (name, &symbol_names);
3072   if (!VEC_empty (const_char_ptr, symbol_names))
3073     add_all_symbol_names_from_pspace (&info, NULL, symbol_names);
3074   else
3075     add_matching_symbols_to_info (name, &info, NULL);
3076
3077   do_cleanups (cleanup);
3078
3079   if (VEC_empty (symbolp, info.result.symbols))
3080     {
3081       VEC_free (symbolp, info.result.symbols);
3082       *symbols = NULL;
3083     }
3084   else
3085     *symbols = info.result.symbols;
3086
3087   if (VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
3088     {
3089       VEC_free (bound_minimal_symbol_d, info.result.minimal_symbols);
3090       *minsyms = NULL;
3091     }
3092   else
3093     *minsyms = info.result.minimal_symbols;
3094 }
3095
3096 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3097    in SYMBOLS and minimal symbols in MINSYMS.  */
3098
3099 static void
3100 find_linespec_symbols (struct linespec_state *state,
3101                        VEC (symtab_ptr) *file_symtabs,
3102                        const char *name,
3103                        VEC (symbolp) **symbols,
3104                        VEC (bound_minimal_symbol_d) **minsyms)
3105 {
3106   struct cleanup *cleanup;
3107   char *canon;
3108   const char *lookup_name;
3109
3110   cleanup = demangle_for_lookup (name, state->language->la_language,
3111                                  &lookup_name);
3112   if (state->language->la_language == language_ada)
3113     {
3114       /* In Ada, the symbol lookups are performed using the encoded
3115          name rather than the demangled name.  */
3116       lookup_name = ada_name_for_lookup (name);
3117       make_cleanup (xfree, (void *) lookup_name);
3118     }
3119
3120   canon = cp_canonicalize_string_no_typedefs (lookup_name);
3121   if (canon != NULL)
3122     {
3123       lookup_name = canon;
3124       make_cleanup (xfree, canon);
3125     }
3126
3127   /* It's important to not call expand_symtabs_matching unnecessarily
3128      as it can really slow things down (by unnecessarily expanding
3129      potentially 1000s of symtabs, which when debugging some apps can
3130      cost 100s of seconds).  Avoid this to some extent by *first* calling
3131      find_function_symbols, and only if that doesn't find anything
3132      *then* call find_method.  This handles two important cases:
3133      1) break (anonymous namespace)::foo
3134      2) break class::method where method is in class (and not a baseclass)  */
3135
3136   find_function_symbols (state, file_symtabs, lookup_name,
3137                          symbols, minsyms);
3138
3139   /* If we were unable to locate a symbol of the same name, try dividing
3140      the name into class and method names and searching the class and its
3141      baseclasses.  */
3142   if (VEC_empty (symbolp, *symbols)
3143       && VEC_empty (bound_minimal_symbol_d, *minsyms))
3144     {
3145       char *klass, *method;
3146       const char *last, *p, *scope_op;
3147       VEC (symbolp) *classes;
3148
3149       /* See if we can find a scope operator and break this symbol
3150          name into namespaces${SCOPE_OPERATOR}class_name and method_name.  */
3151       scope_op = "::";
3152       p = find_toplevel_string (lookup_name, scope_op);
3153       if (p == NULL)
3154         {
3155           /* No C++ scope operator.  Try Java.  */
3156           scope_op = ".";
3157           p = find_toplevel_string (lookup_name, scope_op);
3158         }
3159
3160       last = NULL;
3161       while (p != NULL)
3162         {
3163           last = p;
3164           p = find_toplevel_string (p + strlen (scope_op), scope_op);
3165         }
3166
3167       /* If no scope operator was found, there is nothing more we can do;
3168          we already attempted to lookup the entire name as a symbol
3169          and failed.  */
3170       if (last == NULL)
3171         {
3172           do_cleanups (cleanup);
3173           return;
3174         }
3175
3176       /* LOOKUP_NAME points to the class name.
3177          LAST points to the method name.  */
3178       klass = xmalloc ((last - lookup_name + 1) * sizeof (char));
3179       make_cleanup (xfree, klass);
3180       strncpy (klass, lookup_name, last - lookup_name);
3181       klass[last - lookup_name] = '\0';
3182
3183       /* Skip past the scope operator.  */
3184       last += strlen (scope_op);
3185       method = xmalloc ((strlen (last) + 1) * sizeof (char));
3186       make_cleanup (xfree, method);
3187       strcpy (method, last);
3188
3189       /* Find a list of classes named KLASS.  */
3190       classes = lookup_prefix_sym (state, file_symtabs, klass);
3191       make_cleanup (VEC_cleanup (symbolp), &classes);
3192
3193       if (!VEC_empty (symbolp, classes))
3194         {
3195           /* Now locate a list of suitable methods named METHOD.  */
3196           TRY
3197             {
3198               find_method (state, file_symtabs, klass, method, classes,
3199                            symbols, minsyms);
3200             }
3201
3202           /* If successful, we're done.  If NOT_FOUND_ERROR
3203              was not thrown, rethrow the exception that we did get.  */
3204           CATCH (except, RETURN_MASK_ERROR)
3205             {
3206               if (except.error != NOT_FOUND_ERROR)
3207                 throw_exception (except);
3208             }
3209           END_CATCH
3210         }
3211     }
3212
3213   do_cleanups (cleanup);
3214 }
3215
3216 /* Return all labels named NAME in FUNCTION_SYMBOLS.  Return the
3217    actual function symbol in which the label was found in LABEL_FUNC_RET.  */
3218
3219 static VEC (symbolp) *
3220 find_label_symbols (struct linespec_state *self,
3221                     VEC (symbolp) *function_symbols,
3222                     VEC (symbolp) **label_funcs_ret, const char *name)
3223 {
3224   int ix;
3225   const struct block *block;
3226   struct symbol *sym;
3227   struct symbol *fn_sym;
3228   VEC (symbolp) *result = NULL;
3229
3230   if (function_symbols == NULL)
3231     {
3232       set_current_program_space (self->program_space);
3233       block = get_current_search_block ();
3234
3235       for (;
3236            block && !BLOCK_FUNCTION (block);
3237            block = BLOCK_SUPERBLOCK (block))
3238         ;
3239       if (!block)
3240         return NULL;
3241       fn_sym = BLOCK_FUNCTION (block);
3242
3243       sym = lookup_symbol (name, block, LABEL_DOMAIN, 0);
3244
3245       if (sym != NULL)
3246         {
3247           VEC_safe_push (symbolp, result, sym);
3248           VEC_safe_push (symbolp, *label_funcs_ret, fn_sym);
3249         }
3250     }
3251   else
3252     {
3253       for (ix = 0;
3254            VEC_iterate (symbolp, function_symbols, ix, fn_sym); ++ix)
3255         {
3256           set_current_program_space (SYMTAB_PSPACE (symbol_symtab (fn_sym)));
3257           block = SYMBOL_BLOCK_VALUE (fn_sym);
3258           sym = lookup_symbol (name, block, LABEL_DOMAIN, 0);
3259
3260           if (sym != NULL)
3261             {
3262               VEC_safe_push (symbolp, result, sym);
3263               VEC_safe_push (symbolp, *label_funcs_ret, fn_sym);
3264             }
3265         }
3266     }
3267
3268   return result;
3269 }
3270
3271 \f
3272
3273 /* A helper for create_sals_line_offset that handles the 'list_mode' case.  */
3274
3275 static void
3276 decode_digits_list_mode (struct linespec_state *self,
3277                          linespec_p ls,
3278                          struct symtabs_and_lines *values,
3279                          struct symtab_and_line val)
3280 {
3281   int ix;
3282   struct symtab *elt;
3283
3284   gdb_assert (self->list_mode);
3285
3286   for (ix = 0; VEC_iterate (symtab_ptr, ls->file_symtabs, ix, elt);
3287        ++ix)
3288     {
3289       /* The logic above should ensure this.  */
3290       gdb_assert (elt != NULL);
3291
3292       set_current_program_space (SYMTAB_PSPACE (elt));
3293
3294       /* Simplistic search just for the list command.  */
3295       val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
3296       if (val.symtab == NULL)
3297         val.symtab = elt;
3298       val.pspace = SYMTAB_PSPACE (elt);
3299       val.pc = 0;
3300       val.explicit_line = 1;
3301
3302       add_sal_to_sals (self, values, &val, NULL, 0);
3303     }
3304 }
3305
3306 /* A helper for create_sals_line_offset that iterates over the symtabs,
3307    adding lines to the VEC.  */
3308
3309 static void
3310 decode_digits_ordinary (struct linespec_state *self,
3311                         linespec_p ls,
3312                         int line,
3313                         struct symtabs_and_lines *sals,
3314                         struct linetable_entry **best_entry)
3315 {
3316   int ix;
3317   struct symtab *elt;
3318
3319   for (ix = 0; VEC_iterate (symtab_ptr, ls->file_symtabs, ix, elt); ++ix)
3320     {
3321       int i;
3322       VEC (CORE_ADDR) *pcs;
3323       CORE_ADDR pc;
3324
3325       /* The logic above should ensure this.  */
3326       gdb_assert (elt != NULL);
3327
3328       set_current_program_space (SYMTAB_PSPACE (elt));
3329
3330       pcs = find_pcs_for_symtab_line (elt, line, best_entry);
3331       for (i = 0; VEC_iterate (CORE_ADDR, pcs, i, pc); ++i)
3332         {
3333           struct symtab_and_line sal;
3334
3335           init_sal (&sal);
3336           sal.pspace = SYMTAB_PSPACE (elt);
3337           sal.symtab = elt;
3338           sal.line = line;
3339           sal.pc = pc;
3340           add_sal_to_sals_basic (sals, &sal);
3341         }
3342
3343       VEC_free (CORE_ADDR, pcs);
3344     }
3345 }
3346
3347 \f
3348
3349 /* Return the line offset represented by VARIABLE.  */
3350
3351 static struct line_offset
3352 linespec_parse_variable (struct linespec_state *self, const char *variable)
3353 {
3354   int index = 0;
3355   const char *p;
3356   struct line_offset offset = {0, LINE_OFFSET_NONE};
3357
3358   p = (variable[1] == '$') ? variable + 2 : variable + 1;
3359   if (*p == '$')
3360     ++p;
3361   while (*p >= '0' && *p <= '9')
3362     ++p;
3363   if (!*p)              /* Reached end of token without hitting non-digit.  */
3364     {
3365       /* We have a value history reference.  */
3366       struct value *val_history;
3367
3368       sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
3369       val_history
3370         = access_value_history ((variable[1] == '$') ? -index : index);
3371       if (TYPE_CODE (value_type (val_history)) != TYPE_CODE_INT)
3372         error (_("History values used in line "
3373                  "specs must have integer values."));
3374       offset.offset = value_as_long (val_history);
3375     }
3376   else
3377     {
3378       /* Not all digits -- may be user variable/function or a
3379          convenience variable.  */
3380       LONGEST valx;
3381       struct internalvar *ivar;
3382
3383       /* Try it as a convenience variable.  If it is not a convenience
3384          variable, return and allow normal symbol lookup to occur.  */
3385       ivar = lookup_only_internalvar (variable + 1);
3386       if (ivar == NULL)
3387         /* No internal variable with that name.  Mark the offset
3388            as unknown to allow the name to be looked up as a symbol.  */
3389         offset.sign = LINE_OFFSET_UNKNOWN;
3390       else
3391         {
3392           /* We found a valid variable name.  If it is not an integer,
3393              throw an error.  */
3394           if (!get_internalvar_integer (ivar, &valx))
3395             error (_("Convenience variables used in line "
3396                      "specs must have integer values."));
3397           else
3398             offset.offset = valx;
3399         }
3400     }
3401
3402   return offset;
3403 }
3404 \f
3405
3406 /* A callback used to possibly add a symbol to the results.  */
3407
3408 static int
3409 collect_symbols (struct symbol *sym, void *data)
3410 {
3411   struct collect_info *info = data;
3412
3413   /* In list mode, add all matching symbols, regardless of class.
3414      This allows the user to type "list a_global_variable".  */
3415   if (SYMBOL_CLASS (sym) == LOC_BLOCK || info->state->list_mode)
3416     VEC_safe_push (symbolp, info->result.symbols, sym);
3417   return 1; /* Continue iterating.  */
3418 }
3419
3420 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
3421    linespec; return the SAL in RESULT.  */
3422
3423 static void
3424 minsym_found (struct linespec_state *self, struct objfile *objfile,
3425               struct minimal_symbol *msymbol,
3426               struct symtabs_and_lines *result)
3427 {
3428   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3429   CORE_ADDR pc;
3430   struct symtab_and_line sal;
3431
3432   sal = find_pc_sect_line (MSYMBOL_VALUE_ADDRESS (objfile, msymbol),
3433                            (struct obj_section *) 0, 0);
3434   sal.section = MSYMBOL_OBJ_SECTION (objfile, msymbol);
3435
3436   /* The minimal symbol might point to a function descriptor;
3437      resolve it to the actual code address instead.  */
3438   pc = gdbarch_convert_from_func_ptr_addr (gdbarch, sal.pc, &current_target);
3439   if (pc != sal.pc)
3440     sal = find_pc_sect_line (pc, NULL, 0);
3441
3442   if (self->funfirstline)
3443     skip_prologue_sal (&sal);
3444
3445   if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
3446     add_sal_to_sals (self, result, &sal, MSYMBOL_NATURAL_NAME (msymbol), 0);
3447 }
3448
3449 /* A helper struct to pass some data through
3450    iterate_over_minimal_symbols.  */
3451
3452 struct collect_minsyms
3453 {
3454   /* The objfile we're examining.  */
3455   struct objfile *objfile;
3456
3457   /* Only search the given symtab, or NULL to search for all symbols.  */
3458   struct symtab *symtab;
3459
3460   /* The funfirstline setting from the initial call.  */
3461   int funfirstline;
3462
3463   /* The list_mode setting from the initial call.  */
3464   int list_mode;
3465
3466   /* The resulting symbols.  */
3467   VEC (bound_minimal_symbol_d) *msyms;
3468 };
3469
3470 /* A helper function to classify a minimal_symbol_type according to
3471    priority.  */
3472
3473 static int
3474 classify_mtype (enum minimal_symbol_type t)
3475 {
3476   switch (t)
3477     {
3478     case mst_file_text:
3479     case mst_file_data:
3480     case mst_file_bss:
3481       /* Intermediate priority.  */
3482       return 1;
3483
3484     case mst_solib_trampoline:
3485       /* Lowest priority.  */
3486       return 2;
3487
3488     default:
3489       /* Highest priority.  */
3490       return 0;
3491     }
3492 }
3493
3494 /* Callback for qsort that sorts symbols by priority.  */
3495
3496 static int
3497 compare_msyms (const void *a, const void *b)
3498 {
3499   const bound_minimal_symbol_d *moa = a;
3500   const bound_minimal_symbol_d *mob = b;
3501   enum minimal_symbol_type ta = MSYMBOL_TYPE (moa->minsym);
3502   enum minimal_symbol_type tb = MSYMBOL_TYPE (mob->minsym);
3503
3504   return classify_mtype (ta) - classify_mtype (tb);
3505 }
3506
3507 /* Callback for iterate_over_minimal_symbols that adds the symbol to
3508    the result.  */
3509
3510 static void
3511 add_minsym (struct minimal_symbol *minsym, void *d)
3512 {
3513   struct collect_minsyms *info = d;
3514   bound_minimal_symbol_d mo;
3515
3516   mo.minsym = minsym;
3517   mo.objfile = info->objfile;
3518
3519   if (info->symtab != NULL)
3520     {
3521       CORE_ADDR pc;
3522       struct symtab_and_line sal;
3523       struct gdbarch *gdbarch = get_objfile_arch (info->objfile);
3524
3525       sal = find_pc_sect_line (MSYMBOL_VALUE_ADDRESS (info->objfile, minsym),
3526                                NULL, 0);
3527       sal.section = MSYMBOL_OBJ_SECTION (info->objfile, minsym);
3528       pc
3529         = gdbarch_convert_from_func_ptr_addr (gdbarch, sal.pc, &current_target);
3530       if (pc != sal.pc)
3531         sal = find_pc_sect_line (pc, NULL, 0);
3532
3533       if (info->symtab != sal.symtab)
3534         return;
3535     }
3536
3537   /* Exclude data symbols when looking for breakpoint locations.   */
3538   if (!info->list_mode)
3539     switch (minsym->type)
3540       {
3541         case mst_slot_got_plt:
3542         case mst_data:
3543         case mst_bss:
3544         case mst_abs:
3545         case mst_file_data:
3546         case mst_file_bss:
3547           {
3548             /* Make sure this minsym is not a function descriptor
3549                before we decide to discard it.  */
3550             struct gdbarch *gdbarch = get_objfile_arch (info->objfile);
3551             CORE_ADDR addr = gdbarch_convert_from_func_ptr_addr
3552                                (gdbarch, BMSYMBOL_VALUE_ADDRESS (mo),
3553                                 &current_target);
3554
3555             if (addr == BMSYMBOL_VALUE_ADDRESS (mo))
3556               return;
3557           }
3558       }
3559
3560   VEC_safe_push (bound_minimal_symbol_d, info->msyms, &mo);
3561 }
3562
3563 /* Search for minimal symbols called NAME.  If SEARCH_PSPACE
3564    is not NULL, the search is restricted to just that program
3565    space.
3566
3567    If SYMTAB is NULL, search all objfiles, otherwise
3568    restrict results to the given SYMTAB.  */
3569
3570 static void
3571 search_minsyms_for_name (struct collect_info *info, const char *name,
3572                          struct program_space *search_pspace,
3573                          struct symtab *symtab)
3574 {
3575   struct collect_minsyms local;
3576   struct cleanup *cleanup;
3577
3578   memset (&local, 0, sizeof (local));
3579   local.funfirstline = info->state->funfirstline;
3580   local.list_mode = info->state->list_mode;
3581   local.symtab = symtab;
3582
3583   cleanup = make_cleanup (VEC_cleanup (bound_minimal_symbol_d), &local.msyms);
3584
3585   if (symtab == NULL)
3586     {
3587       struct program_space *pspace;
3588
3589       ALL_PSPACES (pspace)
3590       {
3591         struct objfile *objfile;
3592
3593         if (search_pspace != NULL && search_pspace != pspace)
3594           continue;
3595         if (pspace->executing_startup)
3596           continue;
3597
3598         set_current_program_space (pspace);
3599
3600         ALL_OBJFILES (objfile)
3601         {
3602           local.objfile = objfile;
3603           iterate_over_minimal_symbols (objfile, name, add_minsym, &local);
3604         }
3605       }
3606     }
3607   else
3608     {
3609       if (search_pspace == NULL || SYMTAB_PSPACE (symtab) == search_pspace)
3610         {
3611           set_current_program_space (SYMTAB_PSPACE (symtab));
3612           local.objfile = SYMTAB_OBJFILE(symtab);
3613           iterate_over_minimal_symbols (local.objfile, name, add_minsym,
3614                                         &local);
3615         }
3616     }
3617
3618     if (!VEC_empty (bound_minimal_symbol_d, local.msyms))
3619       {
3620         int classification;
3621         int ix;
3622         bound_minimal_symbol_d *item;
3623
3624         qsort (VEC_address (bound_minimal_symbol_d, local.msyms),
3625                VEC_length (bound_minimal_symbol_d, local.msyms),
3626                sizeof (bound_minimal_symbol_d),
3627                compare_msyms);
3628
3629         /* Now the minsyms are in classification order.  So, we walk
3630            over them and process just the minsyms with the same
3631            classification as the very first minsym in the list.  */
3632         item = VEC_index (bound_minimal_symbol_d, local.msyms, 0);
3633         classification = classify_mtype (MSYMBOL_TYPE (item->minsym));
3634
3635         for (ix = 0;
3636              VEC_iterate (bound_minimal_symbol_d, local.msyms, ix, item);
3637              ++ix)
3638           {
3639             if (classify_mtype (MSYMBOL_TYPE (item->minsym)) != classification)
3640               break;
3641
3642             VEC_safe_push (bound_minimal_symbol_d,
3643                            info->result.minimal_symbols, item);
3644           }
3645       }
3646
3647     do_cleanups (cleanup);
3648 }
3649
3650 /* A helper function to add all symbols matching NAME to INFO.  If
3651    PSPACE is not NULL, the search is restricted to just that program
3652    space.  */
3653
3654 static void
3655 add_matching_symbols_to_info (const char *name,
3656                               struct collect_info *info,
3657                               struct program_space *pspace)
3658 {
3659   int ix;
3660   struct symtab *elt;
3661
3662   for (ix = 0; VEC_iterate (symtab_ptr, info->file_symtabs, ix, elt); ++ix)
3663     {
3664       if (elt == NULL)
3665         {
3666           iterate_over_all_matching_symtabs (info->state, name, VAR_DOMAIN,
3667                                              collect_symbols, info,
3668                                              pspace, 1);
3669           search_minsyms_for_name (info, name, pspace, NULL);
3670         }
3671       else if (pspace == NULL || pspace == SYMTAB_PSPACE (elt))
3672         {
3673           int prev_len = VEC_length (symbolp, info->result.symbols);
3674
3675           /* Program spaces that are executing startup should have
3676              been filtered out earlier.  */
3677           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
3678           set_current_program_space (SYMTAB_PSPACE (elt));
3679           iterate_over_file_blocks (elt, name, VAR_DOMAIN,
3680                                     collect_symbols, info);
3681
3682           /* If no new symbols were found in this iteration and this symtab
3683              is in assembler, we might actually be looking for a label for
3684              which we don't have debug info.  Check for a minimal symbol in
3685              this case.  */
3686           if (prev_len == VEC_length (symbolp, info->result.symbols)
3687               && elt->language == language_asm)
3688             search_minsyms_for_name (info, name, pspace, elt);
3689         }
3690     }
3691 }
3692
3693 \f
3694
3695 /* Now come some functions that are called from multiple places within
3696    decode_line_1.  */
3697
3698 static int
3699 symbol_to_sal (struct symtab_and_line *result,
3700                int funfirstline, struct symbol *sym)
3701 {
3702   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
3703     {
3704       *result = find_function_start_sal (sym, funfirstline);
3705       return 1;
3706     }
3707   else
3708     {
3709       if (SYMBOL_CLASS (sym) == LOC_LABEL && SYMBOL_VALUE_ADDRESS (sym) != 0)
3710         {
3711           init_sal (result);
3712           result->symtab = symbol_symtab (sym);
3713           result->line = SYMBOL_LINE (sym);
3714           result->pc = SYMBOL_VALUE_ADDRESS (sym);
3715           result->pspace = SYMTAB_PSPACE (result->symtab);
3716           result->explicit_pc = 1;
3717           return 1;
3718         }
3719       else if (funfirstline)
3720         {
3721           /* Nothing.  */
3722         }
3723       else if (SYMBOL_LINE (sym) != 0)
3724         {
3725           /* We know its line number.  */
3726           init_sal (result);
3727           result->symtab = symbol_symtab (sym);
3728           result->line = SYMBOL_LINE (sym);
3729           result->pspace = SYMTAB_PSPACE (result->symtab);
3730           return 1;
3731         }
3732     }
3733
3734   return 0;
3735 }
3736
3737 /* See the comment in linespec.h.  */
3738
3739 void
3740 init_linespec_result (struct linespec_result *lr)
3741 {
3742   memset (lr, 0, sizeof (*lr));
3743 }
3744
3745 /* See the comment in linespec.h.  */
3746
3747 void
3748 destroy_linespec_result (struct linespec_result *ls)
3749 {
3750   int i;
3751   struct linespec_sals *lsal;
3752
3753   xfree (ls->addr_string);
3754   for (i = 0; VEC_iterate (linespec_sals, ls->sals, i, lsal); ++i)
3755     {
3756       xfree (lsal->canonical);
3757       xfree (lsal->sals.sals);
3758     }
3759   VEC_free (linespec_sals, ls->sals);
3760 }
3761
3762 /* Cleanup function for a linespec_result.  */
3763
3764 static void
3765 cleanup_linespec_result (void *a)
3766 {
3767   destroy_linespec_result (a);
3768 }
3769
3770 /* See the comment in linespec.h.  */
3771
3772 struct cleanup *
3773 make_cleanup_destroy_linespec_result (struct linespec_result *ls)
3774 {
3775   return make_cleanup (cleanup_linespec_result, ls);
3776 }