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