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