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