New common function "startswith"
[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   volatile struct gdb_exception file_exception;
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   file_exception.reason = 0;
2185
2186   /* Initialize the default symtab and line offset.  */
2187   initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2188                        &PARSER_STATE (parser)->default_line);
2189
2190   /* Objective-C shortcut.  */
2191   values = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), argptr);
2192   if (values.sals != NULL)
2193     return values;
2194
2195   /* Start parsing.  */
2196
2197   /* Get the first token.  */
2198   token = linespec_lexer_lex_one (parser);
2199
2200   /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER.  */
2201   if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '*')
2202     {
2203       char *expr;
2204       const char *copy;
2205
2206       /* User specified an expression, *EXPR.  */
2207       copy = expr = copy_token_string (token);
2208       cleanup = make_cleanup (xfree, expr);
2209       PARSER_RESULT (parser)->expr_pc = linespec_expression_to_pc (&copy);
2210       discard_cleanups (cleanup);
2211       PARSER_RESULT (parser)->expression = expr;
2212
2213       /* This is a little hacky/tricky.  If linespec_expression_to_pc
2214          did not evaluate the entire token, then we must find the
2215          string COPY inside the original token buffer.  */
2216       if (*copy != '\0')
2217         {
2218           PARSER_STREAM (parser) = strstr (parser->lexer.saved_arg, copy);
2219           gdb_assert (PARSER_STREAM (parser) != NULL);
2220         }
2221
2222       /* Consume the token.  */
2223       linespec_lexer_consume_token (parser);
2224
2225       goto convert_to_sals;
2226     }
2227   else if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2228     {
2229       char *var;
2230
2231       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2232       VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2233
2234       /* User specified a convenience variable or history value.  */
2235       var = copy_token_string (token);
2236       cleanup = make_cleanup (xfree, var);
2237       PARSER_RESULT (parser)->line_offset
2238         = linespec_parse_variable (PARSER_STATE (parser), var);
2239       do_cleanups (cleanup);
2240
2241       /* If a line_offset wasn't found (VAR is the name of a user
2242          variable/function), then skip to normal symbol processing.  */
2243       if (PARSER_RESULT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2244         {
2245           /* Consume this token.  */
2246           linespec_lexer_consume_token (parser);
2247
2248           goto convert_to_sals;
2249         }
2250     }
2251   else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2252     unexpected_linespec_error (parser);
2253
2254   /* Now we can recognize keywords.  */
2255   parser->keyword_ok = 1;
2256
2257   /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2258      this token cannot represent a filename.  */
2259   token = linespec_lexer_peek_token (parser);
2260
2261   if (token.type == LSTOKEN_COLON)
2262     {
2263       char *user_filename;
2264
2265       /* Get the current token again and extract the filename.  */
2266       token = linespec_lexer_lex_one (parser);
2267       user_filename = copy_token_string (token);
2268
2269       /* Check if the input is a filename.  */
2270       TRY_CATCH (file_exception, RETURN_MASK_ERROR)
2271         {
2272           PARSER_RESULT (parser)->file_symtabs
2273             = symtabs_from_filename (user_filename);
2274         }
2275
2276       if (file_exception.reason >= 0)
2277         {
2278           /* Symtabs were found for the file.  Record the filename.  */
2279           PARSER_RESULT (parser)->source_filename = user_filename;
2280
2281           /* Get the next token.  */
2282           token = linespec_lexer_consume_token (parser);
2283
2284           /* This is LSTOKEN_COLON; consume it.  */
2285           linespec_lexer_consume_token (parser);
2286         }
2287       else
2288         {
2289           /* No symtabs found -- discard user_filename.  */
2290           xfree (user_filename);
2291
2292           /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2293           VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2294         }
2295     }
2296   /* If the next token is not EOI, KEYWORD, or COMMA, issue an error.  */
2297   else if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2298            && token.type != LSTOKEN_COMMA)
2299     {
2300       /* TOKEN is the _next_ token, not the one currently in the parser.
2301          Consuming the token will give the correct error message.  */
2302       linespec_lexer_consume_token (parser);
2303       unexpected_linespec_error (parser);
2304     }
2305   else
2306     {
2307       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2308       VEC_safe_push (symtab_ptr, PARSER_RESULT (parser)->file_symtabs, NULL);
2309     }
2310
2311   /* Parse the rest of the linespec.  */
2312   linespec_parse_basic (parser);
2313
2314   if (PARSER_RESULT (parser)->function_symbols == NULL
2315       && PARSER_RESULT (parser)->labels.label_symbols == NULL
2316       && PARSER_RESULT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2317       && PARSER_RESULT (parser)->minimal_symbols == NULL)
2318     {
2319       /* The linespec didn't parse.  Re-throw the file exception if
2320          there was one.  */
2321       if (file_exception.reason < 0)
2322         throw_exception (file_exception);
2323
2324       /* Otherwise, the symbol is not found.  */
2325       symbol_not_found_error (PARSER_RESULT (parser)->function_name,
2326                               PARSER_RESULT (parser)->source_filename);
2327     }
2328
2329  convert_to_sals:
2330
2331   /* Get the last token and record how much of the input was parsed,
2332      if necessary.  */
2333   token = linespec_lexer_lex_one (parser);
2334   if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2335     PARSER_STREAM (parser) = LS_TOKEN_STOKEN (token).ptr;
2336
2337   /* Convert the data in PARSER_RESULT to SALs.  */
2338   values = convert_linespec_to_sals (PARSER_STATE (parser),
2339                                      PARSER_RESULT (parser));
2340
2341   return values;
2342 }
2343
2344
2345 /* A constructor for linespec_state.  */
2346
2347 static void
2348 linespec_state_constructor (struct linespec_state *self,
2349                             int flags, const struct language_defn *language,
2350                             struct symtab *default_symtab,
2351                             int default_line,
2352                             struct linespec_result *canonical)
2353 {
2354   memset (self, 0, sizeof (*self));
2355   self->language = language;
2356   self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2357   self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2358   self->default_symtab = default_symtab;
2359   self->default_line = default_line;
2360   self->canonical = canonical;
2361   self->program_space = current_program_space;
2362   self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2363                                       xfree, xcalloc, xfree);
2364 }
2365
2366 /* Initialize a new linespec parser.  */
2367
2368 static void
2369 linespec_parser_new (linespec_parser *parser,
2370                      int flags, const struct language_defn *language,
2371                      struct symtab *default_symtab,
2372                      int default_line,
2373                      struct linespec_result *canonical)
2374 {
2375   parser->lexer.current.type = LSTOKEN_CONSUMED;
2376   memset (PARSER_RESULT (parser), 0, sizeof (struct linespec));
2377   PARSER_RESULT (parser)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2378   linespec_state_constructor (PARSER_STATE (parser), flags, language,
2379                               default_symtab, default_line, canonical);
2380 }
2381
2382 /* A destructor for linespec_state.  */
2383
2384 static void
2385 linespec_state_destructor (struct linespec_state *self)
2386 {
2387   htab_delete (self->addr_set);
2388 }
2389
2390 /* Delete a linespec parser.  */
2391
2392 static void
2393 linespec_parser_delete (void *arg)
2394 {
2395   linespec_parser *parser = (linespec_parser *) arg;
2396
2397   xfree ((char *) PARSER_RESULT (parser)->expression);
2398   xfree ((char *) PARSER_RESULT (parser)->source_filename);
2399   xfree ((char *) PARSER_RESULT (parser)->label_name);
2400   xfree ((char *) PARSER_RESULT (parser)->function_name);
2401
2402   if (PARSER_RESULT (parser)->file_symtabs != NULL)
2403     VEC_free (symtab_ptr, PARSER_RESULT (parser)->file_symtabs);
2404
2405   if (PARSER_RESULT (parser)->function_symbols != NULL)
2406     VEC_free (symbolp, PARSER_RESULT (parser)->function_symbols);
2407
2408   if (PARSER_RESULT (parser)->minimal_symbols != NULL)
2409     VEC_free (bound_minimal_symbol_d, PARSER_RESULT (parser)->minimal_symbols);
2410
2411   if (PARSER_RESULT (parser)->labels.label_symbols != NULL)
2412     VEC_free (symbolp, PARSER_RESULT (parser)->labels.label_symbols);
2413
2414   if (PARSER_RESULT (parser)->labels.function_symbols != NULL)
2415     VEC_free (symbolp, PARSER_RESULT (parser)->labels.function_symbols);
2416
2417   linespec_state_destructor (PARSER_STATE (parser));
2418 }
2419
2420 /* See linespec.h.  */
2421
2422 void
2423 decode_line_full (char **argptr, int flags,
2424                   struct symtab *default_symtab,
2425                   int default_line, struct linespec_result *canonical,
2426                   const char *select_mode,
2427                   const char *filter)
2428 {
2429   struct symtabs_and_lines result;
2430   struct cleanup *cleanups;
2431   VEC (const_char_ptr) *filters = NULL;
2432   linespec_parser parser;
2433   struct linespec_state *state;
2434   const char *copy, *orig;
2435
2436   gdb_assert (canonical != NULL);
2437   /* The filter only makes sense for 'all'.  */
2438   gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
2439   gdb_assert (select_mode == NULL
2440               || select_mode == multiple_symbols_all
2441               || select_mode == multiple_symbols_ask
2442               || select_mode == multiple_symbols_cancel);
2443   gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
2444
2445   linespec_parser_new (&parser, flags, current_language, default_symtab,
2446                        default_line, canonical);
2447   cleanups = make_cleanup (linespec_parser_delete, &parser);
2448   save_current_program_space ();
2449
2450   orig = copy = *argptr;
2451   result = parse_linespec (&parser, &copy);
2452   *argptr += copy - orig;
2453   state = PARSER_STATE (&parser);
2454
2455   gdb_assert (result.nelts == 1 || canonical->pre_expanded);
2456   gdb_assert (canonical->addr_string != NULL);
2457   canonical->pre_expanded = 1;
2458
2459   /* Arrange for allocated canonical names to be freed.  */
2460   if (result.nelts > 0)
2461     {
2462       int i;
2463
2464       make_cleanup (xfree, state->canonical_names);
2465       for (i = 0; i < result.nelts; ++i)
2466         {
2467           gdb_assert (state->canonical_names[i].suffix != NULL);
2468           make_cleanup (xfree, state->canonical_names[i].suffix);
2469         }
2470     }
2471
2472   if (select_mode == NULL)
2473     {
2474       if (ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
2475         select_mode = multiple_symbols_all;
2476       else
2477         select_mode = multiple_symbols_select_mode ();
2478     }
2479
2480   if (select_mode == multiple_symbols_all)
2481     {
2482       if (filter != NULL)
2483         {
2484           make_cleanup (VEC_cleanup (const_char_ptr), &filters);
2485           VEC_safe_push (const_char_ptr, filters, filter);
2486           filter_results (state, &result, filters);
2487         }
2488       else
2489         convert_results_to_lsals (state, &result);
2490     }
2491   else
2492     decode_line_2 (state, &result, select_mode);
2493
2494   do_cleanups (cleanups);
2495 }
2496
2497 /* See linespec.h.  */
2498
2499 struct symtabs_and_lines
2500 decode_line_1 (char **argptr, int flags,
2501                struct symtab *default_symtab,
2502                int default_line)
2503 {
2504   struct symtabs_and_lines result;
2505   linespec_parser parser;
2506   struct cleanup *cleanups;
2507   const char *copy, *orig;
2508
2509   linespec_parser_new (&parser, flags, current_language, default_symtab,
2510                        default_line, NULL);
2511   cleanups = make_cleanup (linespec_parser_delete, &parser);
2512   save_current_program_space ();
2513
2514   orig = copy = *argptr;
2515   result = parse_linespec (&parser, &copy);
2516   *argptr += copy - orig;
2517
2518   do_cleanups (cleanups);
2519   return result;
2520 }
2521
2522 /* See linespec.h.  */
2523
2524 struct symtabs_and_lines
2525 decode_line_with_current_source (char *string, int flags)
2526 {
2527   struct symtabs_and_lines sals;
2528   struct symtab_and_line cursal;
2529
2530   if (string == 0)
2531     error (_("Empty line specification."));
2532
2533   /* We use whatever is set as the current source line.  We do not try
2534      and get a default source symtab+line or it will recursively call us!  */
2535   cursal = get_current_source_symtab_and_line ();
2536
2537   sals = decode_line_1 (&string, flags,
2538                         cursal.symtab, cursal.line);
2539
2540   if (*string)
2541     error (_("Junk at end of line specification: %s"), string);
2542   return sals;
2543 }
2544
2545 /* See linespec.h.  */
2546
2547 struct symtabs_and_lines
2548 decode_line_with_last_displayed (char *string, int flags)
2549 {
2550   struct symtabs_and_lines sals;
2551
2552   if (string == 0)
2553     error (_("Empty line specification."));
2554
2555   if (last_displayed_sal_is_valid ())
2556     sals = decode_line_1 (&string, flags,
2557                           get_last_displayed_symtab (),
2558                           get_last_displayed_line ());
2559   else
2560     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
2561
2562   if (*string)
2563     error (_("Junk at end of line specification: %s"), string);
2564   return sals;
2565 }
2566
2567 \f
2568
2569 /* First, some functions to initialize stuff at the beggining of the
2570    function.  */
2571
2572 static void
2573 initialize_defaults (struct symtab **default_symtab, int *default_line)
2574 {
2575   if (*default_symtab == 0)
2576     {
2577       /* Use whatever we have for the default source line.  We don't use
2578          get_current_or_default_symtab_and_line as it can recurse and call
2579          us back!  */
2580       struct symtab_and_line cursal = 
2581         get_current_source_symtab_and_line ();
2582       
2583       *default_symtab = cursal.symtab;
2584       *default_line = cursal.line;
2585     }
2586 }
2587
2588 \f
2589
2590 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
2591    advancing EXP_PTR past any parsed text.  */
2592
2593 static CORE_ADDR
2594 linespec_expression_to_pc (const char **exp_ptr)
2595 {
2596   if (current_program_space->executing_startup)
2597     /* The error message doesn't really matter, because this case
2598        should only hit during breakpoint reset.  */
2599     throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
2600                                     "program space is in startup"));
2601
2602   (*exp_ptr)++;
2603   return value_as_address (parse_to_comma_and_eval (exp_ptr));
2604 }
2605
2606 \f
2607
2608 /* Here's where we recognise an Objective-C Selector.  An Objective C
2609    selector may be implemented by more than one class, therefore it
2610    may represent more than one method/function.  This gives us a
2611    situation somewhat analogous to C++ overloading.  If there's more
2612    than one method that could represent the selector, then use some of
2613    the existing C++ code to let the user choose one.  */
2614
2615 static struct symtabs_and_lines
2616 decode_objc (struct linespec_state *self, linespec_p ls, const char **argptr)
2617 {
2618   struct collect_info info;
2619   VEC (const_char_ptr) *symbol_names = NULL;
2620   struct symtabs_and_lines values;
2621   const char *new_argptr;
2622   struct cleanup *cleanup = make_cleanup (VEC_cleanup (const_char_ptr),
2623                                           &symbol_names);
2624
2625   info.state = self;
2626   info.file_symtabs = NULL;
2627   VEC_safe_push (symtab_ptr, info.file_symtabs, NULL);
2628   make_cleanup (VEC_cleanup (symtab_ptr), &info.file_symtabs);
2629   info.result.symbols = NULL;
2630   info.result.minimal_symbols = NULL;
2631   values.nelts = 0;
2632   values.sals = NULL;
2633
2634   new_argptr = find_imps (*argptr, &symbol_names); 
2635   if (VEC_empty (const_char_ptr, symbol_names))
2636     {
2637       do_cleanups (cleanup);
2638       return values;
2639     }
2640
2641   add_all_symbol_names_from_pspace (&info, NULL, symbol_names);
2642
2643   if (!VEC_empty (symbolp, info.result.symbols)
2644       || !VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
2645     {
2646       char *saved_arg;
2647
2648       saved_arg = alloca (new_argptr - *argptr + 1);
2649       memcpy (saved_arg, *argptr, new_argptr - *argptr);
2650       saved_arg[new_argptr - *argptr] = '\0';
2651
2652       ls->function_name = xstrdup (saved_arg);
2653       ls->function_symbols = info.result.symbols;
2654       ls->minimal_symbols = info.result.minimal_symbols;
2655       values = convert_linespec_to_sals (self, ls);
2656
2657       if (self->canonical)
2658         {
2659           self->canonical->pre_expanded = 1;
2660           if (ls->source_filename)
2661             self->canonical->addr_string
2662               = xstrprintf ("%s:%s", ls->source_filename, saved_arg);
2663           else
2664             self->canonical->addr_string = xstrdup (saved_arg);
2665         }
2666     }
2667
2668   *argptr = new_argptr;
2669
2670   do_cleanups (cleanup);
2671
2672   return values;
2673 }
2674
2675 /* An instance of this type is used when collecting prefix symbols for
2676    decode_compound.  */
2677
2678 struct decode_compound_collector
2679 {
2680   /* The result vector.  */
2681   VEC (symbolp) *symbols;
2682
2683   /* A hash table of all symbols we found.  We use this to avoid
2684      adding any symbol more than once.  */
2685   htab_t unique_syms;
2686 };
2687
2688 /* A callback for iterate_over_symbols that is used by
2689    lookup_prefix_sym to collect type symbols.  */
2690
2691 static int
2692 collect_one_symbol (struct symbol *sym, void *d)
2693 {
2694   struct decode_compound_collector *collector = d;
2695   void **slot;
2696   struct type *t;
2697
2698   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
2699     return 1; /* Continue iterating.  */
2700
2701   t = SYMBOL_TYPE (sym);
2702   CHECK_TYPEDEF (t);
2703   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2704       && TYPE_CODE (t) != TYPE_CODE_UNION
2705       && TYPE_CODE (t) != TYPE_CODE_NAMESPACE)
2706     return 1; /* Continue iterating.  */
2707
2708   slot = htab_find_slot (collector->unique_syms, sym, INSERT);
2709   if (!*slot)
2710     {
2711       *slot = sym;
2712       VEC_safe_push (symbolp, collector->symbols, sym);
2713     }
2714
2715   return 1; /* Continue iterating.  */
2716 }
2717
2718 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS.  */
2719
2720 static VEC (symbolp) *
2721 lookup_prefix_sym (struct linespec_state *state, VEC (symtab_ptr) *file_symtabs,
2722                    const char *class_name)
2723 {
2724   int ix;
2725   struct symtab *elt;
2726   struct decode_compound_collector collector;
2727   struct cleanup *outer;
2728   struct cleanup *cleanup;
2729
2730   collector.symbols = NULL;
2731   outer = make_cleanup (VEC_cleanup (symbolp), &collector.symbols);
2732
2733   collector.unique_syms = htab_create_alloc (1, htab_hash_pointer,
2734                                              htab_eq_pointer, NULL,
2735                                              xcalloc, xfree);
2736   cleanup = make_cleanup_htab_delete (collector.unique_syms);
2737
2738   for (ix = 0; VEC_iterate (symtab_ptr, file_symtabs, ix, elt); ++ix)
2739     {
2740       if (elt == NULL)
2741         {
2742           iterate_over_all_matching_symtabs (state, class_name, STRUCT_DOMAIN,
2743                                              collect_one_symbol, &collector,
2744                                              NULL, 0);
2745           iterate_over_all_matching_symtabs (state, class_name, VAR_DOMAIN,
2746                                              collect_one_symbol, &collector,
2747                                              NULL, 0);
2748         }
2749       else
2750         {
2751           /* Program spaces that are executing startup should have
2752              been filtered out earlier.  */
2753           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
2754           set_current_program_space (SYMTAB_PSPACE (elt));
2755           iterate_over_file_blocks (elt, class_name, STRUCT_DOMAIN,
2756                                     collect_one_symbol, &collector);
2757           iterate_over_file_blocks (elt, class_name, VAR_DOMAIN,
2758                                     collect_one_symbol, &collector);
2759         }
2760     }
2761
2762   do_cleanups (cleanup);
2763   discard_cleanups (outer);
2764   return collector.symbols;
2765 }
2766
2767 /* A qsort comparison function for symbols.  The resulting order does
2768    not actually matter; we just need to be able to sort them so that
2769    symbols with the same program space end up next to each other.  */
2770
2771 static int
2772 compare_symbols (const void *a, const void *b)
2773 {
2774   struct symbol * const *sa = a;
2775   struct symbol * const *sb = b;
2776   uintptr_t uia, uib;
2777
2778   uia = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (*sa));
2779   uib = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (*sb));
2780
2781   if (uia < uib)
2782     return -1;
2783   if (uia > uib)
2784     return 1;
2785
2786   uia = (uintptr_t) *sa;
2787   uib = (uintptr_t) *sb;
2788
2789   if (uia < uib)
2790     return -1;
2791   if (uia > uib)
2792     return 1;
2793
2794   return 0;
2795 }
2796
2797 /* Like compare_symbols but for minimal symbols.  */
2798
2799 static int
2800 compare_msymbols (const void *a, const void *b)
2801 {
2802   const struct bound_minimal_symbol *sa = a;
2803   const struct bound_minimal_symbol *sb = b;
2804   uintptr_t uia, uib;
2805
2806   uia = (uintptr_t) sa->objfile->pspace;
2807   uib = (uintptr_t) sa->objfile->pspace;
2808
2809   if (uia < uib)
2810     return -1;
2811   if (uia > uib)
2812     return 1;
2813
2814   uia = (uintptr_t) sa->minsym;
2815   uib = (uintptr_t) sb->minsym;
2816
2817   if (uia < uib)
2818     return -1;
2819   if (uia > uib)
2820     return 1;
2821
2822   return 0;
2823 }
2824
2825 /* Look for all the matching instances of each symbol in NAMES.  Only
2826    instances from PSPACE are considered; other program spaces are
2827    handled by our caller.  If PSPACE is NULL, then all program spaces
2828    are considered.  Results are stored into INFO.  */
2829
2830 static void
2831 add_all_symbol_names_from_pspace (struct collect_info *info,
2832                                   struct program_space *pspace,
2833                                   VEC (const_char_ptr) *names)
2834 {
2835   int ix;
2836   const char *iter;
2837
2838   for (ix = 0; VEC_iterate (const_char_ptr, names, ix, iter); ++ix)
2839     add_matching_symbols_to_info (iter, info, pspace);
2840 }
2841
2842 static void
2843 find_superclass_methods (VEC (typep) *superclasses,
2844                          const char *name,
2845                          VEC (const_char_ptr) **result_names)
2846 {
2847   int old_len = VEC_length (const_char_ptr, *result_names);
2848   VEC (typep) *iter_classes;
2849   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2850
2851   iter_classes = superclasses;
2852   while (1)
2853     {
2854       VEC (typep) *new_supers = NULL;
2855       int ix;
2856       struct type *t;
2857
2858       make_cleanup (VEC_cleanup (typep), &new_supers);
2859       for (ix = 0; VEC_iterate (typep, iter_classes, ix, t); ++ix)
2860         find_methods (t, name, result_names, &new_supers);
2861
2862       if (VEC_length (const_char_ptr, *result_names) != old_len
2863           || VEC_empty (typep, new_supers))
2864         break;
2865
2866       iter_classes = new_supers;
2867     }
2868
2869   do_cleanups (cleanup);
2870 }
2871
2872 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
2873    given by one of the symbols in SYM_CLASSES.  Matches are returned
2874    in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols).  */
2875
2876 static void
2877 find_method (struct linespec_state *self, VEC (symtab_ptr) *file_symtabs,
2878              const char *class_name, const char *method_name,
2879              VEC (symbolp) *sym_classes, VEC (symbolp) **symbols,
2880              VEC (bound_minimal_symbol_d) **minsyms)
2881 {
2882   struct symbol *sym;
2883   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
2884   int ix;
2885   int last_result_len;
2886   VEC (typep) *superclass_vec;
2887   VEC (const_char_ptr) *result_names;
2888   struct collect_info info;
2889
2890   /* Sort symbols so that symbols with the same program space are next
2891      to each other.  */
2892   qsort (VEC_address (symbolp, sym_classes),
2893          VEC_length (symbolp, sym_classes),
2894          sizeof (symbolp),
2895          compare_symbols);
2896
2897   info.state = self;
2898   info.file_symtabs = file_symtabs;
2899   info.result.symbols = NULL;
2900   info.result.minimal_symbols = NULL;
2901
2902   /* Iterate over all the types, looking for the names of existing
2903      methods matching METHOD_NAME.  If we cannot find a direct method in a
2904      given program space, then we consider inherited methods; this is
2905      not ideal (ideal would be to respect C++ hiding rules), but it
2906      seems good enough and is what GDB has historically done.  We only
2907      need to collect the names because later we find all symbols with
2908      those names.  This loop is written in a somewhat funny way
2909      because we collect data across the program space before deciding
2910      what to do.  */
2911   superclass_vec = NULL;
2912   make_cleanup (VEC_cleanup (typep), &superclass_vec);
2913   result_names = NULL;
2914   make_cleanup (VEC_cleanup (const_char_ptr), &result_names);
2915   last_result_len = 0;
2916   for (ix = 0; VEC_iterate (symbolp, sym_classes, ix, sym); ++ix)
2917     {
2918       struct type *t;
2919       struct program_space *pspace;
2920
2921       /* Program spaces that are executing startup should have
2922          been filtered out earlier.  */
2923       pspace = SYMTAB_PSPACE (symbol_symtab (sym));
2924       gdb_assert (!pspace->executing_startup);
2925       set_current_program_space (pspace);
2926       t = check_typedef (SYMBOL_TYPE (sym));
2927       find_methods (t, method_name, &result_names, &superclass_vec);
2928
2929       /* Handle all items from a single program space at once; and be
2930          sure not to miss the last batch.  */
2931       if (ix == VEC_length (symbolp, sym_classes) - 1
2932           || (pspace
2933               != SYMTAB_PSPACE (symbol_symtab (VEC_index (symbolp, sym_classes,
2934                                                           ix + 1)))))
2935         {
2936           /* If we did not find a direct implementation anywhere in
2937              this program space, consider superclasses.  */
2938           if (VEC_length (const_char_ptr, result_names) == last_result_len)
2939             find_superclass_methods (superclass_vec, method_name,
2940                                      &result_names);
2941
2942           /* We have a list of candidate symbol names, so now we
2943              iterate over the symbol tables looking for all
2944              matches in this pspace.  */
2945           add_all_symbol_names_from_pspace (&info, pspace, result_names);
2946
2947           VEC_truncate (typep, superclass_vec, 0);
2948           last_result_len = VEC_length (const_char_ptr, result_names);
2949         }
2950     }
2951
2952   if (!VEC_empty (symbolp, info.result.symbols)
2953       || !VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
2954     {
2955       *symbols = info.result.symbols;
2956       *minsyms = info.result.minimal_symbols;
2957       do_cleanups (cleanup);
2958       return;
2959     }
2960
2961   /* Throw an NOT_FOUND_ERROR.  This will be caught by the caller
2962      and other attempts to locate the symbol will be made.  */
2963   throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
2964 }
2965
2966 \f
2967
2968 /* This object is used when collecting all matching symtabs.  */
2969
2970 struct symtab_collector
2971 {
2972   /* The result vector of symtabs.  */
2973   VEC (symtab_ptr) *symtabs;
2974
2975   /* This is used to ensure the symtabs are unique.  */
2976   htab_t symtab_table;
2977 };
2978
2979 /* Callback for iterate_over_symtabs.  */
2980
2981 static int
2982 add_symtabs_to_list (struct symtab *symtab, void *d)
2983 {
2984   struct symtab_collector *data = d;
2985   void **slot;
2986
2987   slot = htab_find_slot (data->symtab_table, symtab, INSERT);
2988   if (!*slot)
2989     {
2990       *slot = symtab;
2991       VEC_safe_push (symtab_ptr, data->symtabs, symtab);
2992     }
2993
2994   return 0;
2995 }
2996
2997 /* Given a file name, return a VEC of all matching symtabs.  */
2998
2999 static VEC (symtab_ptr) *
3000 collect_symtabs_from_filename (const char *file)
3001 {
3002   struct symtab_collector collector;
3003   struct cleanup *cleanups;
3004   struct program_space *pspace;
3005
3006   collector.symtabs = NULL;
3007   collector.symtab_table = htab_create (1, htab_hash_pointer, htab_eq_pointer,
3008                                         NULL);
3009   cleanups = make_cleanup_htab_delete (collector.symtab_table);
3010
3011   /* Find that file's data.  */
3012   ALL_PSPACES (pspace)
3013   {
3014     if (pspace->executing_startup)
3015       continue;
3016
3017     set_current_program_space (pspace);
3018     iterate_over_symtabs (file, add_symtabs_to_list, &collector);
3019   }
3020
3021   do_cleanups (cleanups);
3022   return collector.symtabs;
3023 }
3024
3025 /* Return all the symtabs associated to the FILENAME.  */
3026
3027 static VEC (symtab_ptr) *
3028 symtabs_from_filename (const char *filename)
3029 {
3030   VEC (symtab_ptr) *result;
3031   
3032   result = collect_symtabs_from_filename (filename);
3033
3034   if (VEC_empty (symtab_ptr, result))
3035     {
3036       if (!have_full_symbols () && !have_partial_symbols ())
3037         throw_error (NOT_FOUND_ERROR,
3038                      _("No symbol table is loaded.  "
3039                        "Use the \"file\" command."));
3040       throw_error (NOT_FOUND_ERROR, _("No source file named %s."), filename);
3041     }
3042
3043   return result;
3044 }
3045
3046 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS.  Matching
3047    debug symbols are returned in SYMBOLS.  Matching minimal symbols are
3048    returned in MINSYMS.  */
3049
3050 static void
3051 find_function_symbols (struct linespec_state *state,
3052                        VEC (symtab_ptr) *file_symtabs, const char *name,
3053                        VEC (symbolp) **symbols,
3054                        VEC (bound_minimal_symbol_d) **minsyms)
3055 {
3056   struct collect_info info;
3057   VEC (const_char_ptr) *symbol_names = NULL;
3058   struct cleanup *cleanup = make_cleanup (VEC_cleanup (const_char_ptr),
3059                                           &symbol_names);
3060
3061   info.state = state;
3062   info.result.symbols = NULL;
3063   info.result.minimal_symbols = NULL;
3064   info.file_symtabs = file_symtabs;
3065
3066   /* Try NAME as an Objective-C selector.  */
3067   find_imps (name, &symbol_names);
3068   if (!VEC_empty (const_char_ptr, symbol_names))
3069     add_all_symbol_names_from_pspace (&info, NULL, symbol_names);
3070   else
3071     add_matching_symbols_to_info (name, &info, NULL);
3072
3073   do_cleanups (cleanup);
3074
3075   if (VEC_empty (symbolp, info.result.symbols))
3076     {
3077       VEC_free (symbolp, info.result.symbols);
3078       *symbols = NULL;
3079     }
3080   else
3081     *symbols = info.result.symbols;
3082
3083   if (VEC_empty (bound_minimal_symbol_d, info.result.minimal_symbols))
3084     {
3085       VEC_free (bound_minimal_symbol_d, info.result.minimal_symbols);
3086       *minsyms = NULL;
3087     }
3088   else
3089     *minsyms = info.result.minimal_symbols;
3090 }
3091
3092 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3093    in SYMBOLS and minimal symbols in MINSYMS.  */
3094
3095 static void
3096 find_linespec_symbols (struct linespec_state *state,
3097                        VEC (symtab_ptr) *file_symtabs,
3098                        const char *name,
3099                        VEC (symbolp) **symbols,
3100                        VEC (bound_minimal_symbol_d) **minsyms)
3101 {
3102   struct cleanup *cleanup;
3103   char *canon;
3104   const char *lookup_name;
3105   volatile struct gdb_exception except;
3106
3107   cleanup = demangle_for_lookup (name, state->language->la_language,
3108                                  &lookup_name);
3109   if (state->language->la_language == language_ada)
3110     {
3111       /* In Ada, the symbol lookups are performed using the encoded
3112          name rather than the demangled name.  */
3113       lookup_name = ada_name_for_lookup (name);
3114       make_cleanup (xfree, (void *) lookup_name);
3115     }
3116
3117   canon = cp_canonicalize_string_no_typedefs (lookup_name);
3118   if (canon != NULL)
3119     {
3120       lookup_name = canon;
3121       make_cleanup (xfree, canon);
3122     }
3123
3124   /* It's important to not call expand_symtabs_matching unnecessarily
3125      as it can really slow things down (by unnecessarily expanding
3126      potentially 1000s of symtabs, which when debugging some apps can
3127      cost 100s of seconds).  Avoid this to some extent by *first* calling
3128      find_function_symbols, and only if that doesn't find anything
3129      *then* call find_method.  This handles two important cases:
3130      1) break (anonymous namespace)::foo
3131      2) break class::method where method is in class (and not a baseclass)  */
3132
3133   find_function_symbols (state, file_symtabs, lookup_name,
3134                          symbols, minsyms);
3135
3136   /* If we were unable to locate a symbol of the same name, try dividing
3137      the name into class and method names and searching the class and its
3138      baseclasses.  */
3139   if (VEC_empty (symbolp, *symbols)
3140       && VEC_empty (bound_minimal_symbol_d, *minsyms))
3141     {
3142       char *klass, *method;
3143       const char *last, *p, *scope_op;
3144       VEC (symbolp) *classes;
3145
3146       /* See if we can find a scope operator and break this symbol
3147          name into namespaces${SCOPE_OPERATOR}class_name and method_name.  */
3148       scope_op = "::";
3149       p = find_toplevel_string (lookup_name, scope_op);
3150       if (p == NULL)
3151         {
3152           /* No C++ scope operator.  Try Java.  */
3153           scope_op = ".";
3154           p = find_toplevel_string (lookup_name, scope_op);
3155         }
3156
3157       last = NULL;
3158       while (p != NULL)
3159         {
3160           last = p;
3161           p = find_toplevel_string (p + strlen (scope_op), scope_op);
3162         }
3163
3164       /* If no scope operator was found, there is nothing more we can do;
3165          we already attempted to lookup the entire name as a symbol
3166          and failed.  */
3167       if (last == NULL)
3168         {
3169           do_cleanups (cleanup);
3170           return;
3171         }
3172
3173       /* LOOKUP_NAME points to the class name.
3174          LAST points to the method name.  */
3175       klass = xmalloc ((last - lookup_name + 1) * sizeof (char));
3176       make_cleanup (xfree, klass);
3177       strncpy (klass, lookup_name, last - lookup_name);
3178       klass[last - lookup_name] = '\0';
3179
3180       /* Skip past the scope operator.  */
3181       last += strlen (scope_op);
3182       method = xmalloc ((strlen (last) + 1) * sizeof (char));
3183       make_cleanup (xfree, method);
3184       strcpy (method, last);
3185
3186       /* Find a list of classes named KLASS.  */
3187       classes = lookup_prefix_sym (state, file_symtabs, klass);
3188       make_cleanup (VEC_cleanup (symbolp), &classes);
3189
3190       if (!VEC_empty (symbolp, classes))
3191         {
3192           /* Now locate a list of suitable methods named METHOD.  */
3193           TRY_CATCH (except, RETURN_MASK_ERROR)
3194             {
3195               find_method (state, file_symtabs, klass, method, classes,
3196                            symbols, minsyms);
3197             }
3198
3199           /* If successful, we're done.  If NOT_FOUND_ERROR
3200              was not thrown, rethrow the exception that we did get.  */
3201           if (except.reason < 0 && except.error != NOT_FOUND_ERROR)
3202             throw_exception (except);
3203         }
3204     }
3205
3206   do_cleanups (cleanup);
3207 }
3208
3209 /* Return all labels named NAME in FUNCTION_SYMBOLS.  Return the
3210    actual function symbol in which the label was found in LABEL_FUNC_RET.  */
3211
3212 static VEC (symbolp) *
3213 find_label_symbols (struct linespec_state *self,
3214                     VEC (symbolp) *function_symbols,
3215                     VEC (symbolp) **label_funcs_ret, const char *name)
3216 {
3217   int ix;
3218   const struct block *block;
3219   struct symbol *sym;
3220   struct symbol *fn_sym;
3221   VEC (symbolp) *result = NULL;
3222
3223   if (function_symbols == NULL)
3224     {
3225       set_current_program_space (self->program_space);
3226       block = get_current_search_block ();
3227
3228       for (;
3229            block && !BLOCK_FUNCTION (block);
3230            block = BLOCK_SUPERBLOCK (block))
3231         ;
3232       if (!block)
3233         return NULL;
3234       fn_sym = BLOCK_FUNCTION (block);
3235
3236       sym = lookup_symbol (name, block, LABEL_DOMAIN, 0);
3237
3238       if (sym != NULL)
3239         {
3240           VEC_safe_push (symbolp, result, sym);
3241           VEC_safe_push (symbolp, *label_funcs_ret, fn_sym);
3242         }
3243     }
3244   else
3245     {
3246       for (ix = 0;
3247            VEC_iterate (symbolp, function_symbols, ix, fn_sym); ++ix)
3248         {
3249           set_current_program_space (SYMTAB_PSPACE (symbol_symtab (fn_sym)));
3250           block = SYMBOL_BLOCK_VALUE (fn_sym);
3251           sym = lookup_symbol (name, block, LABEL_DOMAIN, 0);
3252
3253           if (sym != NULL)
3254             {
3255               VEC_safe_push (symbolp, result, sym);
3256               VEC_safe_push (symbolp, *label_funcs_ret, fn_sym);
3257             }
3258         }
3259     }
3260
3261   return result;
3262 }
3263
3264 \f
3265
3266 /* A helper for create_sals_line_offset that handles the 'list_mode' case.  */
3267
3268 static void
3269 decode_digits_list_mode (struct linespec_state *self,
3270                          linespec_p ls,
3271                          struct symtabs_and_lines *values,
3272                          struct symtab_and_line val)
3273 {
3274   int ix;
3275   struct symtab *elt;
3276
3277   gdb_assert (self->list_mode);
3278
3279   for (ix = 0; VEC_iterate (symtab_ptr, ls->file_symtabs, ix, elt);
3280        ++ix)
3281     {
3282       /* The logic above should ensure this.  */
3283       gdb_assert (elt != NULL);
3284
3285       set_current_program_space (SYMTAB_PSPACE (elt));
3286
3287       /* Simplistic search just for the list command.  */
3288       val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
3289       if (val.symtab == NULL)
3290         val.symtab = elt;
3291       val.pspace = SYMTAB_PSPACE (elt);
3292       val.pc = 0;
3293       val.explicit_line = 1;
3294
3295       add_sal_to_sals (self, values, &val, NULL, 0);
3296     }
3297 }
3298
3299 /* A helper for create_sals_line_offset that iterates over the symtabs,
3300    adding lines to the VEC.  */
3301
3302 static void
3303 decode_digits_ordinary (struct linespec_state *self,
3304                         linespec_p ls,
3305                         int line,
3306                         struct symtabs_and_lines *sals,
3307                         struct linetable_entry **best_entry)
3308 {
3309   int ix;
3310   struct symtab *elt;
3311
3312   for (ix = 0; VEC_iterate (symtab_ptr, ls->file_symtabs, ix, elt); ++ix)
3313     {
3314       int i;
3315       VEC (CORE_ADDR) *pcs;
3316       CORE_ADDR pc;
3317
3318       /* The logic above should ensure this.  */
3319       gdb_assert (elt != NULL);
3320
3321       set_current_program_space (SYMTAB_PSPACE (elt));
3322
3323       pcs = find_pcs_for_symtab_line (elt, line, best_entry);
3324       for (i = 0; VEC_iterate (CORE_ADDR, pcs, i, pc); ++i)
3325         {
3326           struct symtab_and_line sal;
3327
3328           init_sal (&sal);
3329           sal.pspace = SYMTAB_PSPACE (elt);
3330           sal.symtab = elt;
3331           sal.line = line;
3332           sal.pc = pc;
3333           add_sal_to_sals_basic (sals, &sal);
3334         }
3335
3336       VEC_free (CORE_ADDR, pcs);
3337     }
3338 }
3339
3340 \f
3341
3342 /* Return the line offset represented by VARIABLE.  */
3343
3344 static struct line_offset
3345 linespec_parse_variable (struct linespec_state *self, const char *variable)
3346 {
3347   int index = 0;
3348   const char *p;
3349   struct line_offset offset = {0, LINE_OFFSET_NONE};
3350
3351   p = (variable[1] == '$') ? variable + 2 : variable + 1;
3352   if (*p == '$')
3353     ++p;
3354   while (*p >= '0' && *p <= '9')
3355     ++p;
3356   if (!*p)              /* Reached end of token without hitting non-digit.  */
3357     {
3358       /* We have a value history reference.  */
3359       struct value *val_history;
3360
3361       sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
3362       val_history
3363         = access_value_history ((variable[1] == '$') ? -index : index);
3364       if (TYPE_CODE (value_type (val_history)) != TYPE_CODE_INT)
3365         error (_("History values used in line "
3366                  "specs must have integer values."));
3367       offset.offset = value_as_long (val_history);
3368     }
3369   else
3370     {
3371       /* Not all digits -- may be user variable/function or a
3372          convenience variable.  */
3373       LONGEST valx;
3374       struct internalvar *ivar;
3375
3376       /* Try it as a convenience variable.  If it is not a convenience
3377          variable, return and allow normal symbol lookup to occur.  */
3378       ivar = lookup_only_internalvar (variable + 1);
3379       if (ivar == NULL)
3380         /* No internal variable with that name.  Mark the offset
3381            as unknown to allow the name to be looked up as a symbol.  */
3382         offset.sign = LINE_OFFSET_UNKNOWN;
3383       else
3384         {
3385           /* We found a valid variable name.  If it is not an integer,
3386              throw an error.  */
3387           if (!get_internalvar_integer (ivar, &valx))
3388             error (_("Convenience variables used in line "
3389                      "specs must have integer values."));
3390           else
3391             offset.offset = valx;
3392         }
3393     }
3394
3395   return offset;
3396 }
3397 \f
3398
3399 /* A callback used to possibly add a symbol to the results.  */
3400
3401 static int
3402 collect_symbols (struct symbol *sym, void *data)
3403 {
3404   struct collect_info *info = data;
3405
3406   /* In list mode, add all matching symbols, regardless of class.
3407      This allows the user to type "list a_global_variable".  */
3408   if (SYMBOL_CLASS (sym) == LOC_BLOCK || info->state->list_mode)
3409     VEC_safe_push (symbolp, info->result.symbols, sym);
3410   return 1; /* Continue iterating.  */
3411 }
3412
3413 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
3414    linespec; return the SAL in RESULT.  */
3415
3416 static void
3417 minsym_found (struct linespec_state *self, struct objfile *objfile,
3418               struct minimal_symbol *msymbol,
3419               struct symtabs_and_lines *result)
3420 {
3421   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3422   CORE_ADDR pc;
3423   struct symtab_and_line sal;
3424
3425   sal = find_pc_sect_line (MSYMBOL_VALUE_ADDRESS (objfile, msymbol),
3426                            (struct obj_section *) 0, 0);
3427   sal.section = MSYMBOL_OBJ_SECTION (objfile, msymbol);
3428
3429   /* The minimal symbol might point to a function descriptor;
3430      resolve it to the actual code address instead.  */
3431   pc = gdbarch_convert_from_func_ptr_addr (gdbarch, sal.pc, &current_target);
3432   if (pc != sal.pc)
3433     sal = find_pc_sect_line (pc, NULL, 0);
3434
3435   if (self->funfirstline)
3436     skip_prologue_sal (&sal);
3437
3438   if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
3439     add_sal_to_sals (self, result, &sal, MSYMBOL_NATURAL_NAME (msymbol), 0);
3440 }
3441
3442 /* A helper struct to pass some data through
3443    iterate_over_minimal_symbols.  */
3444
3445 struct collect_minsyms
3446 {
3447   /* The objfile we're examining.  */
3448   struct objfile *objfile;
3449
3450   /* Only search the given symtab, or NULL to search for all symbols.  */
3451   struct symtab *symtab;
3452
3453   /* The funfirstline setting from the initial call.  */
3454   int funfirstline;
3455
3456   /* The list_mode setting from the initial call.  */
3457   int list_mode;
3458
3459   /* The resulting symbols.  */
3460   VEC (bound_minimal_symbol_d) *msyms;
3461 };
3462
3463 /* A helper function to classify a minimal_symbol_type according to
3464    priority.  */
3465
3466 static int
3467 classify_mtype (enum minimal_symbol_type t)
3468 {
3469   switch (t)
3470     {
3471     case mst_file_text:
3472     case mst_file_data:
3473     case mst_file_bss:
3474       /* Intermediate priority.  */
3475       return 1;
3476
3477     case mst_solib_trampoline:
3478       /* Lowest priority.  */
3479       return 2;
3480
3481     default:
3482       /* Highest priority.  */
3483       return 0;
3484     }
3485 }
3486
3487 /* Callback for qsort that sorts symbols by priority.  */
3488
3489 static int
3490 compare_msyms (const void *a, const void *b)
3491 {
3492   const bound_minimal_symbol_d *moa = a;
3493   const bound_minimal_symbol_d *mob = b;
3494   enum minimal_symbol_type ta = MSYMBOL_TYPE (moa->minsym);
3495   enum minimal_symbol_type tb = MSYMBOL_TYPE (mob->minsym);
3496
3497   return classify_mtype (ta) - classify_mtype (tb);
3498 }
3499
3500 /* Callback for iterate_over_minimal_symbols that adds the symbol to
3501    the result.  */
3502
3503 static void
3504 add_minsym (struct minimal_symbol *minsym, void *d)
3505 {
3506   struct collect_minsyms *info = d;
3507   bound_minimal_symbol_d mo;
3508
3509   mo.minsym = minsym;
3510   mo.objfile = info->objfile;
3511
3512   if (info->symtab != NULL)
3513     {
3514       CORE_ADDR pc;
3515       struct symtab_and_line sal;
3516       struct gdbarch *gdbarch = get_objfile_arch (info->objfile);
3517
3518       sal = find_pc_sect_line (MSYMBOL_VALUE_ADDRESS (info->objfile, minsym),
3519                                NULL, 0);
3520       sal.section = MSYMBOL_OBJ_SECTION (info->objfile, minsym);
3521       pc
3522         = gdbarch_convert_from_func_ptr_addr (gdbarch, sal.pc, &current_target);
3523       if (pc != sal.pc)
3524         sal = find_pc_sect_line (pc, NULL, 0);
3525
3526       if (info->symtab != sal.symtab)
3527         return;
3528     }
3529
3530   /* Exclude data symbols when looking for breakpoint locations.   */
3531   if (!info->list_mode)
3532     switch (minsym->type)
3533       {
3534         case mst_slot_got_plt:
3535         case mst_data:
3536         case mst_bss:
3537         case mst_abs:
3538         case mst_file_data:
3539         case mst_file_bss:
3540           {
3541             /* Make sure this minsym is not a function descriptor
3542                before we decide to discard it.  */
3543             struct gdbarch *gdbarch = get_objfile_arch (info->objfile);
3544             CORE_ADDR addr = gdbarch_convert_from_func_ptr_addr
3545                                (gdbarch, BMSYMBOL_VALUE_ADDRESS (mo),
3546                                 &current_target);
3547
3548             if (addr == BMSYMBOL_VALUE_ADDRESS (mo))
3549               return;
3550           }
3551       }
3552
3553   VEC_safe_push (bound_minimal_symbol_d, info->msyms, &mo);
3554 }
3555
3556 /* Search for minimal symbols called NAME.  If SEARCH_PSPACE
3557    is not NULL, the search is restricted to just that program
3558    space.
3559
3560    If SYMTAB is NULL, search all objfiles, otherwise
3561    restrict results to the given SYMTAB.  */
3562
3563 static void
3564 search_minsyms_for_name (struct collect_info *info, const char *name,
3565                          struct program_space *search_pspace,
3566                          struct symtab *symtab)
3567 {
3568   struct collect_minsyms local;
3569   struct cleanup *cleanup;
3570
3571   memset (&local, 0, sizeof (local));
3572   local.funfirstline = info->state->funfirstline;
3573   local.list_mode = info->state->list_mode;
3574   local.symtab = symtab;
3575
3576   cleanup = make_cleanup (VEC_cleanup (bound_minimal_symbol_d), &local.msyms);
3577
3578   if (symtab == NULL)
3579     {
3580       struct program_space *pspace;
3581
3582       ALL_PSPACES (pspace)
3583       {
3584         struct objfile *objfile;
3585
3586         if (search_pspace != NULL && search_pspace != pspace)
3587           continue;
3588         if (pspace->executing_startup)
3589           continue;
3590
3591         set_current_program_space (pspace);
3592
3593         ALL_OBJFILES (objfile)
3594         {
3595           local.objfile = objfile;
3596           iterate_over_minimal_symbols (objfile, name, add_minsym, &local);
3597         }
3598       }
3599     }
3600   else
3601     {
3602       if (search_pspace == NULL || SYMTAB_PSPACE (symtab) == search_pspace)
3603         {
3604           set_current_program_space (SYMTAB_PSPACE (symtab));
3605           local.objfile = SYMTAB_OBJFILE(symtab);
3606           iterate_over_minimal_symbols (local.objfile, name, add_minsym,
3607                                         &local);
3608         }
3609     }
3610
3611     if (!VEC_empty (bound_minimal_symbol_d, local.msyms))
3612       {
3613         int classification;
3614         int ix;
3615         bound_minimal_symbol_d *item;
3616
3617         qsort (VEC_address (bound_minimal_symbol_d, local.msyms),
3618                VEC_length (bound_minimal_symbol_d, local.msyms),
3619                sizeof (bound_minimal_symbol_d),
3620                compare_msyms);
3621
3622         /* Now the minsyms are in classification order.  So, we walk
3623            over them and process just the minsyms with the same
3624            classification as the very first minsym in the list.  */
3625         item = VEC_index (bound_minimal_symbol_d, local.msyms, 0);
3626         classification = classify_mtype (MSYMBOL_TYPE (item->minsym));
3627
3628         for (ix = 0;
3629              VEC_iterate (bound_minimal_symbol_d, local.msyms, ix, item);
3630              ++ix)
3631           {
3632             if (classify_mtype (MSYMBOL_TYPE (item->minsym)) != classification)
3633               break;
3634
3635             VEC_safe_push (bound_minimal_symbol_d,
3636                            info->result.minimal_symbols, item);
3637           }
3638       }
3639
3640     do_cleanups (cleanup);
3641 }
3642
3643 /* A helper function to add all symbols matching NAME to INFO.  If
3644    PSPACE is not NULL, the search is restricted to just that program
3645    space.  */
3646
3647 static void
3648 add_matching_symbols_to_info (const char *name,
3649                               struct collect_info *info,
3650                               struct program_space *pspace)
3651 {
3652   int ix;
3653   struct symtab *elt;
3654
3655   for (ix = 0; VEC_iterate (symtab_ptr, info->file_symtabs, ix, elt); ++ix)
3656     {
3657       if (elt == NULL)
3658         {
3659           iterate_over_all_matching_symtabs (info->state, name, VAR_DOMAIN,
3660                                              collect_symbols, info,
3661                                              pspace, 1);
3662           search_minsyms_for_name (info, name, pspace, NULL);
3663         }
3664       else if (pspace == NULL || pspace == SYMTAB_PSPACE (elt))
3665         {
3666           int prev_len = VEC_length (symbolp, info->result.symbols);
3667
3668           /* Program spaces that are executing startup should have
3669              been filtered out earlier.  */
3670           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
3671           set_current_program_space (SYMTAB_PSPACE (elt));
3672           iterate_over_file_blocks (elt, name, VAR_DOMAIN,
3673                                     collect_symbols, info);
3674
3675           /* If no new symbols were found in this iteration and this symtab
3676              is in assembler, we might actually be looking for a label for
3677              which we don't have debug info.  Check for a minimal symbol in
3678              this case.  */
3679           if (prev_len == VEC_length (symbolp, info->result.symbols)
3680               && elt->language == language_asm)
3681             search_minsyms_for_name (info, name, pspace, elt);
3682         }
3683     }
3684 }
3685
3686 \f
3687
3688 /* Now come some functions that are called from multiple places within
3689    decode_line_1.  */
3690
3691 static int
3692 symbol_to_sal (struct symtab_and_line *result,
3693                int funfirstline, struct symbol *sym)
3694 {
3695   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
3696     {
3697       *result = find_function_start_sal (sym, funfirstline);
3698       return 1;
3699     }
3700   else
3701     {
3702       if (SYMBOL_CLASS (sym) == LOC_LABEL && SYMBOL_VALUE_ADDRESS (sym) != 0)
3703         {
3704           init_sal (result);
3705           result->symtab = symbol_symtab (sym);
3706           result->line = SYMBOL_LINE (sym);
3707           result->pc = SYMBOL_VALUE_ADDRESS (sym);
3708           result->pspace = SYMTAB_PSPACE (result->symtab);
3709           result->explicit_pc = 1;
3710           return 1;
3711         }
3712       else if (funfirstline)
3713         {
3714           /* Nothing.  */
3715         }
3716       else if (SYMBOL_LINE (sym) != 0)
3717         {
3718           /* We know its line number.  */
3719           init_sal (result);
3720           result->symtab = symbol_symtab (sym);
3721           result->line = SYMBOL_LINE (sym);
3722           result->pspace = SYMTAB_PSPACE (result->symtab);
3723           return 1;
3724         }
3725     }
3726
3727   return 0;
3728 }
3729
3730 /* See the comment in linespec.h.  */
3731
3732 void
3733 init_linespec_result (struct linespec_result *lr)
3734 {
3735   memset (lr, 0, sizeof (*lr));
3736 }
3737
3738 /* See the comment in linespec.h.  */
3739
3740 void
3741 destroy_linespec_result (struct linespec_result *ls)
3742 {
3743   int i;
3744   struct linespec_sals *lsal;
3745
3746   xfree (ls->addr_string);
3747   for (i = 0; VEC_iterate (linespec_sals, ls->sals, i, lsal); ++i)
3748     {
3749       xfree (lsal->canonical);
3750       xfree (lsal->sals.sals);
3751     }
3752   VEC_free (linespec_sals, ls->sals);
3753 }
3754
3755 /* Cleanup function for a linespec_result.  */
3756
3757 static void
3758 cleanup_linespec_result (void *a)
3759 {
3760   destroy_linespec_result (a);
3761 }
3762
3763 /* See the comment in linespec.h.  */
3764
3765 struct cleanup *
3766 make_cleanup_destroy_linespec_result (struct linespec_result *ls)
3767 {
3768   return make_cleanup (cleanup_linespec_result, ls);
3769 }