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