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