Use block_symbol in linespec APIs
[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<block_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<block_symbol> *label_symbols;
120     std::vector<block_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<block_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 (block_symbol *bsym);
203 };
204
205 bool
206 collect_info::add_symbol (block_symbol *bsym)
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 (bsym->symbol) == LOC_BLOCK || this->state->list_mode)
211     this->result.symbols->push_back (*bsym);
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<block_symbol> *find_label_symbols
349   (struct linespec_state *self, std::vector<block_symbol> *function_symbols,
350    std::vector<block_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<block_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 block_symbol &a, const block_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, [&] (block_symbol *bsym)
1154                      {
1155                        /* Restrict calls to CALLBACK to symbols
1156                           representing inline symbols only.  */
1157                        if (SYMBOL_INLINED (bsym->symbol))
1158                          return callback (bsym);
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<block_symbol> symbols;
1764   std::vector<block_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<block_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<block_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<block_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           block_symbol s = ls->labels.function_symbols->front ();
2064           explicit_loc->function_name
2065             = xstrdup (SYMBOL_NATURAL_NAME (s.symbol));
2066         }
2067     }
2068
2069   /* If this location originally came from a linespec, save a string
2070      representation of it for display and saving to file.  */
2071   if (state->is_linespec)
2072     {
2073       char *linespec = explicit_location_to_linespec (explicit_loc);
2074
2075       set_event_location_string (canon, linespec);
2076       xfree (linespec);
2077     }
2078 }
2079
2080 /* Given a line offset in LS, construct the relevant SALs.  */
2081
2082 static std::vector<symtab_and_line>
2083 create_sals_line_offset (struct linespec_state *self,
2084                          linespec_p ls)
2085 {
2086   int use_default = 0;
2087
2088   /* This is where we need to make sure we have good defaults.
2089      We must guarantee that this section of code is never executed
2090      when we are called with just a function name, since
2091      set_default_source_symtab_and_line uses
2092      select_source_symtab that calls us with such an argument.  */
2093
2094   if (ls->file_symtabs->size () == 1
2095       && ls->file_symtabs->front () == nullptr)
2096     {
2097       const char *fullname;
2098
2099       set_current_program_space (self->program_space);
2100
2101       /* Make sure we have at least a default source line.  */
2102       set_default_source_symtab_and_line ();
2103       initialize_defaults (&self->default_symtab, &self->default_line);
2104       fullname = symtab_to_fullname (self->default_symtab);
2105       symtab_vector_up r =
2106         collect_symtabs_from_filename (fullname, self->search_pspace);
2107       ls->file_symtabs = r.release ();
2108       use_default = 1;
2109     }
2110
2111   symtab_and_line val;
2112   val.line = ls->explicit_loc.line_offset.offset;
2113   switch (ls->explicit_loc.line_offset.sign)
2114     {
2115     case LINE_OFFSET_PLUS:
2116       if (ls->explicit_loc.line_offset.offset == 0)
2117         val.line = 5;
2118       if (use_default)
2119         val.line = self->default_line + val.line;
2120       break;
2121
2122     case LINE_OFFSET_MINUS:
2123       if (ls->explicit_loc.line_offset.offset == 0)
2124         val.line = 15;
2125       if (use_default)
2126         val.line = self->default_line - val.line;
2127       else
2128         val.line = -val.line;
2129       break;
2130
2131     case LINE_OFFSET_NONE:
2132       break;                    /* No need to adjust val.line.  */
2133     }
2134
2135   std::vector<symtab_and_line> values;
2136   if (self->list_mode)
2137     values = decode_digits_list_mode (self, ls, val);
2138   else
2139     {
2140       struct linetable_entry *best_entry = NULL;
2141       int i, j;
2142
2143       std::vector<symtab_and_line> intermediate_results
2144         = decode_digits_ordinary (self, ls, val.line, &best_entry);
2145       if (intermediate_results.empty () && best_entry != NULL)
2146         intermediate_results = decode_digits_ordinary (self, ls,
2147                                                        best_entry->line,
2148                                                        &best_entry);
2149
2150       /* For optimized code, the compiler can scatter one source line
2151          across disjoint ranges of PC values, even when no duplicate
2152          functions or inline functions are involved.  For example,
2153          'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
2154          function can result in two PC ranges.  In this case, we don't
2155          want to set a breakpoint on the first PC of each range.  To filter
2156          such cases, we use containing blocks -- for each PC found
2157          above, we see if there are other PCs that are in the same
2158          block.  If yes, the other PCs are filtered out.  */
2159
2160       gdb::def_vector<int> filter (intermediate_results.size ());
2161       gdb::def_vector<const block *> blocks (intermediate_results.size ());
2162
2163       for (i = 0; i < intermediate_results.size (); ++i)
2164         {
2165           set_current_program_space (intermediate_results[i].pspace);
2166
2167           filter[i] = 1;
2168           blocks[i] = block_for_pc_sect (intermediate_results[i].pc,
2169                                          intermediate_results[i].section);
2170         }
2171
2172       for (i = 0; i < intermediate_results.size (); ++i)
2173         {
2174           if (blocks[i] != NULL)
2175             for (j = i + 1; j < intermediate_results.size (); ++j)
2176               {
2177                 if (blocks[j] == blocks[i])
2178                   {
2179                     filter[j] = 0;
2180                     break;
2181                   }
2182               }
2183         }
2184
2185       for (i = 0; i < intermediate_results.size (); ++i)
2186         if (filter[i])
2187           {
2188             struct symbol *sym = (blocks[i]
2189                                   ? block_containing_function (blocks[i])
2190                                   : NULL);
2191
2192             if (self->funfirstline)
2193               skip_prologue_sal (&intermediate_results[i]);
2194             intermediate_results[i].symbol = sym;
2195             add_sal_to_sals (self, &values, &intermediate_results[i],
2196                              sym ? SYMBOL_NATURAL_NAME (sym) : NULL, 0);
2197           }
2198     }
2199
2200   if (values.empty ())
2201     {
2202       if (ls->explicit_loc.source_filename)
2203         throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
2204                      val.line, ls->explicit_loc.source_filename);
2205       else
2206         throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
2207                      val.line);
2208     }
2209
2210   return values;
2211 }
2212
2213 /* Convert the given ADDRESS into SaLs.  */
2214
2215 static std::vector<symtab_and_line>
2216 convert_address_location_to_sals (struct linespec_state *self,
2217                                   CORE_ADDR address)
2218 {
2219   symtab_and_line sal = find_pc_line (address, 0);
2220   sal.pc = address;
2221   sal.section = find_pc_overlay (address);
2222   sal.explicit_pc = 1;
2223   sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
2224
2225   std::vector<symtab_and_line> sals;
2226   add_sal_to_sals (self, &sals, &sal, core_addr_to_string (address), 1);
2227
2228   return sals;
2229 }
2230
2231 /* Create and return SALs from the linespec LS.  */
2232
2233 static std::vector<symtab_and_line>
2234 convert_linespec_to_sals (struct linespec_state *state, linespec_p ls)
2235 {
2236   std::vector<symtab_and_line> sals;
2237
2238   if (ls->labels.label_symbols != NULL)
2239     {
2240       /* We have just a bunch of functions/methods or labels.  */
2241       struct symtab_and_line sal;
2242
2243       for (const auto &sym : *ls->labels.label_symbols)
2244         {
2245           struct program_space *pspace
2246             = SYMTAB_PSPACE (symbol_symtab (sym.symbol));
2247
2248           if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2249               && maybe_add_address (state->addr_set, pspace, sal.pc))
2250             add_sal_to_sals (state, &sals, &sal,
2251                              SYMBOL_NATURAL_NAME (sym.symbol), 0);
2252         }
2253     }
2254   else if (ls->function_symbols != NULL || ls->minimal_symbols != NULL)
2255     {
2256       /* We have just a bunch of functions and/or methods.  */
2257       if (ls->function_symbols != NULL)
2258         {
2259           /* Sort symbols so that symbols with the same program space are next
2260              to each other.  */
2261           std::sort (ls->function_symbols->begin (),
2262                      ls->function_symbols->end (),
2263                      compare_symbols);
2264
2265           for (const auto &sym : *ls->function_symbols)
2266             {
2267               program_space *pspace
2268                 = SYMTAB_PSPACE (symbol_symtab (sym.symbol));
2269               set_current_program_space (pspace);
2270
2271               /* Don't skip to the first line of the function if we
2272                  had found an ifunc minimal symbol for this function,
2273                  because that means that this function is an ifunc
2274                  resolver with the same name as the ifunc itself.  */
2275               bool found_ifunc = false;
2276
2277               if (state->funfirstline
2278                    && ls->minimal_symbols != NULL
2279                    && SYMBOL_CLASS (sym.symbol) == LOC_BLOCK)
2280                 {
2281                   const CORE_ADDR addr
2282                     = BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (sym.symbol));
2283
2284                   for (const auto &elem : *ls->minimal_symbols)
2285                     {
2286                       if (MSYMBOL_TYPE (elem.minsym) == mst_text_gnu_ifunc
2287                           || MSYMBOL_TYPE (elem.minsym) == mst_data_gnu_ifunc)
2288                         {
2289                           CORE_ADDR msym_addr = BMSYMBOL_VALUE_ADDRESS (elem);
2290                           if (MSYMBOL_TYPE (elem.minsym) == mst_data_gnu_ifunc)
2291                             {
2292                               struct gdbarch *gdbarch
2293                                 = get_objfile_arch (elem.objfile);
2294                               msym_addr
2295                                 = (gdbarch_convert_from_func_ptr_addr
2296                                    (gdbarch,
2297                                     msym_addr,
2298                                     current_top_target ()));
2299                             }
2300
2301                           if (msym_addr == addr)
2302                             {
2303                               found_ifunc = true;
2304                               break;
2305                             }
2306                         }
2307                     }
2308                 }
2309
2310               if (!found_ifunc)
2311                 {
2312                   symtab_and_line sal;
2313                   if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2314                       && maybe_add_address (state->addr_set, pspace, sal.pc))
2315                     add_sal_to_sals (state, &sals, &sal,
2316                                      SYMBOL_NATURAL_NAME (sym.symbol), 0);
2317                 }
2318             }
2319         }
2320
2321       if (ls->minimal_symbols != NULL)
2322         {
2323           /* Sort minimal symbols by program space, too  */
2324           std::sort (ls->minimal_symbols->begin (),
2325                      ls->minimal_symbols->end (),
2326                      compare_msymbols);
2327
2328           for (const auto &elem : *ls->minimal_symbols)
2329             {
2330               program_space *pspace = elem.objfile->pspace;
2331               set_current_program_space (pspace);
2332               minsym_found (state, elem.objfile, elem.minsym, &sals);
2333             }
2334         }
2335     }
2336   else if (ls->explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2337     {
2338       /* Only an offset was specified.  */
2339         sals = create_sals_line_offset (state, ls);
2340
2341         /* Make sure we have a filename for canonicalization.  */
2342         if (ls->explicit_loc.source_filename == NULL)
2343           {
2344             const char *fullname = symtab_to_fullname (state->default_symtab);
2345
2346             /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2347                form so that displaying SOURCE_FILENAME can follow the current
2348                FILENAME_DISPLAY_STRING setting.  But as it is used only rarely
2349                it has been kept for code simplicity only in absolute form.  */
2350             ls->explicit_loc.source_filename = xstrdup (fullname);
2351           }
2352     }
2353   else
2354     {
2355       /* We haven't found any results...  */
2356       return sals;
2357     }
2358
2359   canonicalize_linespec (state, ls);
2360
2361   if (!sals.empty () && state->canonical != NULL)
2362     state->canonical->pre_expanded = 1;
2363
2364   return sals;
2365 }
2366
2367 /* Build RESULT from the explicit location components SOURCE_FILENAME,
2368    FUNCTION_NAME, LABEL_NAME and LINE_OFFSET.  */
2369
2370 static void
2371 convert_explicit_location_to_linespec (struct linespec_state *self,
2372                                        linespec_p result,
2373                                        const char *source_filename,
2374                                        const char *function_name,
2375                                        symbol_name_match_type fname_match_type,
2376                                        const char *label_name,
2377                                        struct line_offset line_offset)
2378 {
2379   std::vector<block_symbol> symbols;
2380   std::vector<block_symbol> *labels;
2381   std::vector<bound_minimal_symbol> minimal_symbols;
2382
2383   result->explicit_loc.func_name_match_type = fname_match_type;
2384
2385   if (source_filename != NULL)
2386     {
2387       TRY
2388         {
2389           result->file_symtabs
2390             = symtabs_from_filename (source_filename,
2391                                      self->search_pspace).release ();
2392         }
2393       CATCH (except, RETURN_MASK_ERROR)
2394         {
2395           source_file_not_found_error (source_filename);
2396         }
2397       END_CATCH
2398       result->explicit_loc.source_filename = xstrdup (source_filename);
2399     }
2400   else
2401     {
2402       /* A NULL entry means to use the default symtab.  */
2403       result->file_symtabs->push_back (nullptr);
2404     }
2405
2406   if (function_name != NULL)
2407     {
2408       find_linespec_symbols (self, result->file_symtabs,
2409                              function_name, fname_match_type,
2410                              &symbols, &minimal_symbols);
2411
2412       if (symbols.empty () && minimal_symbols.empty ())
2413         symbol_not_found_error (function_name,
2414                                 result->explicit_loc.source_filename);
2415
2416       result->explicit_loc.function_name = xstrdup (function_name);
2417       result->function_symbols
2418         = new std::vector<block_symbol> (std::move (symbols));
2419       result->minimal_symbols
2420         = new std::vector<bound_minimal_symbol> (std::move (minimal_symbols));
2421     }
2422
2423   if (label_name != NULL)
2424     {
2425       labels = find_label_symbols (self, result->function_symbols,
2426                                    &symbols, label_name);
2427
2428       if (labels == NULL)
2429         undefined_label_error (result->explicit_loc.function_name,
2430                                label_name);
2431
2432       result->explicit_loc.label_name = xstrdup (label_name);
2433       result->labels.label_symbols = labels;
2434       result->labels.function_symbols
2435         = new std::vector<block_symbol> (std::move (symbols));
2436     }
2437
2438   if (line_offset.sign != LINE_OFFSET_UNKNOWN)
2439     result->explicit_loc.line_offset = line_offset;
2440 }
2441
2442 /* Convert the explicit location EXPLICIT_LOC into SaLs.  */
2443
2444 static std::vector<symtab_and_line>
2445 convert_explicit_location_to_sals (struct linespec_state *self,
2446                                    linespec_p result,
2447                                    const struct explicit_location *explicit_loc)
2448 {
2449   convert_explicit_location_to_linespec (self, result,
2450                                          explicit_loc->source_filename,
2451                                          explicit_loc->function_name,
2452                                          explicit_loc->func_name_match_type,
2453                                          explicit_loc->label_name,
2454                                          explicit_loc->line_offset);
2455   return convert_linespec_to_sals (self, result);
2456 }
2457
2458 /* Parse a string that specifies a linespec.
2459
2460    The basic grammar of linespecs:
2461
2462    linespec -> var_spec | basic_spec
2463    var_spec -> '$' (STRING | NUMBER)
2464
2465    basic_spec -> file_offset_spec | function_spec | label_spec
2466    file_offset_spec -> opt_file_spec offset_spec
2467    function_spec -> opt_file_spec function_name_spec opt_label_spec
2468    label_spec -> label_name_spec
2469
2470    opt_file_spec -> "" | file_name_spec ':'
2471    opt_label_spec -> "" | ':' label_name_spec
2472
2473    file_name_spec -> STRING
2474    function_name_spec -> STRING
2475    label_name_spec -> STRING
2476    function_name_spec -> STRING
2477    offset_spec -> NUMBER
2478                -> '+' NUMBER
2479                -> '-' NUMBER
2480
2481    This may all be followed by several keywords such as "if EXPR",
2482    which we ignore.
2483
2484    A comma will terminate parsing.
2485
2486    The function may be an undebuggable function found in minimal symbol table.
2487
2488    If the argument FUNFIRSTLINE is nonzero, we want the first line
2489    of real code inside a function when a function is specified, and it is
2490    not OK to specify a variable or type to get its line number.
2491
2492    DEFAULT_SYMTAB specifies the file to use if none is specified.
2493    It defaults to current_source_symtab.
2494    DEFAULT_LINE specifies the line number to use for relative
2495    line numbers (that start with signs).  Defaults to current_source_line.
2496    If CANONICAL is non-NULL, store an array of strings containing the canonical
2497    line specs there if necessary.  Currently overloaded member functions and
2498    line numbers or static functions without a filename yield a canonical
2499    line spec.  The array and the line spec strings are allocated on the heap,
2500    it is the callers responsibility to free them.
2501
2502    Note that it is possible to return zero for the symtab
2503    if no file is validly specified.  Callers must check that.
2504    Also, the line number returned may be invalid.  */
2505
2506 /* Parse the linespec in ARG.  MATCH_TYPE indicates how function names
2507    should be matched.  */
2508
2509 static std::vector<symtab_and_line>
2510 parse_linespec (linespec_parser *parser, const char *arg,
2511                 symbol_name_match_type match_type)
2512 {
2513   linespec_token token;
2514   struct gdb_exception file_exception = exception_none;
2515
2516   /* A special case to start.  It has become quite popular for
2517      IDEs to work around bugs in the previous parser by quoting
2518      the entire linespec, so we attempt to deal with this nicely.  */
2519   parser->is_quote_enclosed = 0;
2520   if (parser->completion_tracker == NULL
2521       && !is_ada_operator (arg)
2522       && strchr (linespec_quote_characters, *arg) != NULL)
2523     {
2524       const char *end;
2525
2526       end = skip_quote_char (arg + 1, *arg);
2527       if (end != NULL && is_closing_quote_enclosed (end))
2528         {
2529           /* Here's the special case.  Skip ARG past the initial
2530              quote.  */
2531           ++arg;
2532           parser->is_quote_enclosed = 1;
2533         }
2534     }
2535
2536   parser->lexer.saved_arg = arg;
2537   parser->lexer.stream = arg;
2538   parser->completion_word = arg;
2539   parser->complete_what = linespec_complete_what::FUNCTION;
2540   PARSER_EXPLICIT (parser)->func_name_match_type = match_type;
2541
2542   /* Initialize the default symtab and line offset.  */
2543   initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2544                        &PARSER_STATE (parser)->default_line);
2545
2546   /* Objective-C shortcut.  */
2547   if (parser->completion_tracker == NULL)
2548     {
2549       std::vector<symtab_and_line> values
2550         = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), arg);
2551       if (!values.empty ())
2552         return values;
2553     }
2554   else
2555     {
2556       /* "-"/"+" is either an objc selector, or a number.  There's
2557          nothing to complete the latter to, so just let the caller
2558          complete on functions, which finds objc selectors, if there's
2559          any.  */
2560       if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '\0')
2561         return {};
2562     }
2563
2564   /* Start parsing.  */
2565
2566   /* Get the first token.  */
2567   token = linespec_lexer_consume_token (parser);
2568
2569   /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER.  */
2570   if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2571     {
2572       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2573       if (parser->completion_tracker == NULL)
2574         PARSER_RESULT (parser)->file_symtabs->push_back (nullptr);
2575
2576       /* User specified a convenience variable or history value.  */
2577       gdb::unique_xmalloc_ptr<char> var = copy_token_string (token);
2578       PARSER_EXPLICIT (parser)->line_offset
2579         = linespec_parse_variable (PARSER_STATE (parser), var.get ());
2580
2581       /* If a line_offset wasn't found (VAR is the name of a user
2582          variable/function), then skip to normal symbol processing.  */
2583       if (PARSER_EXPLICIT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2584         {
2585           /* Consume this token.  */
2586           linespec_lexer_consume_token (parser);
2587
2588           goto convert_to_sals;
2589         }
2590     }
2591   else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
2592     {
2593       /* Let the default linespec_complete_what::FUNCTION kick in.  */
2594       unexpected_linespec_error (parser);
2595     }
2596   else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2597     {
2598       parser->complete_what = linespec_complete_what::NOTHING;
2599       unexpected_linespec_error (parser);
2600     }
2601
2602   /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2603      this token cannot represent a filename.  */
2604   token = linespec_lexer_peek_token (parser);
2605
2606   if (token.type == LSTOKEN_COLON)
2607     {
2608       /* Get the current token again and extract the filename.  */
2609       token = linespec_lexer_lex_one (parser);
2610       gdb::unique_xmalloc_ptr<char> user_filename = copy_token_string (token);
2611
2612       /* Check if the input is a filename.  */
2613       TRY
2614         {
2615           symtab_vector_up r
2616             = symtabs_from_filename (user_filename.get (),
2617                                      PARSER_STATE (parser)->search_pspace);
2618           PARSER_RESULT (parser)->file_symtabs = r.release ();
2619         }
2620       CATCH (ex, RETURN_MASK_ERROR)
2621         {
2622           file_exception = ex;
2623         }
2624       END_CATCH
2625
2626       if (file_exception.reason >= 0)
2627         {
2628           /* Symtabs were found for the file.  Record the filename.  */
2629           PARSER_EXPLICIT (parser)->source_filename = user_filename.release ();
2630
2631           /* Get the next token.  */
2632           token = linespec_lexer_consume_token (parser);
2633
2634           /* This is LSTOKEN_COLON; consume it.  */
2635           linespec_lexer_consume_token (parser);
2636         }
2637       else
2638         {
2639           /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2640           PARSER_RESULT (parser)->file_symtabs->push_back (nullptr);
2641         }
2642     }
2643   /* If the next token is not EOI, KEYWORD, or COMMA, issue an error.  */
2644   else if (parser->completion_tracker == NULL
2645            && (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2646                && token.type != LSTOKEN_COMMA))
2647     {
2648       /* TOKEN is the _next_ token, not the one currently in the parser.
2649          Consuming the token will give the correct error message.  */
2650       linespec_lexer_consume_token (parser);
2651       unexpected_linespec_error (parser);
2652     }
2653   else
2654     {
2655       /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB.  */
2656       PARSER_RESULT (parser)->file_symtabs->push_back (nullptr);
2657     }
2658
2659   /* Parse the rest of the linespec.  */
2660   linespec_parse_basic (parser);
2661
2662   if (parser->completion_tracker == NULL
2663       && PARSER_RESULT (parser)->function_symbols == NULL
2664       && PARSER_RESULT (parser)->labels.label_symbols == NULL
2665       && PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2666       && PARSER_RESULT (parser)->minimal_symbols == NULL)
2667     {
2668       /* The linespec didn't parse.  Re-throw the file exception if
2669          there was one.  */
2670       if (file_exception.reason < 0)
2671         throw_exception (file_exception);
2672
2673       /* Otherwise, the symbol is not found.  */
2674       symbol_not_found_error (PARSER_EXPLICIT (parser)->function_name,
2675                               PARSER_EXPLICIT (parser)->source_filename);
2676     }
2677
2678  convert_to_sals:
2679
2680   /* Get the last token and record how much of the input was parsed,
2681      if necessary.  */
2682   token = linespec_lexer_lex_one (parser);
2683   if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2684     unexpected_linespec_error (parser);
2685   else if (token.type == LSTOKEN_KEYWORD)
2686     {
2687       /* Setup the completion word past the keyword.  Lexing never
2688          advances past a keyword automatically, so skip it
2689          manually.  */
2690       parser->completion_word
2691         = skip_spaces (skip_to_space (PARSER_STREAM (parser)));
2692       parser->complete_what = linespec_complete_what::EXPRESSION;
2693     }
2694
2695   /* Convert the data in PARSER_RESULT to SALs.  */
2696   if (parser->completion_tracker == NULL)
2697     return convert_linespec_to_sals (PARSER_STATE (parser),
2698                                      PARSER_RESULT (parser));
2699
2700   return {};
2701 }
2702
2703
2704 /* A constructor for linespec_state.  */
2705
2706 static void
2707 linespec_state_constructor (struct linespec_state *self,
2708                             int flags, const struct language_defn *language,
2709                             struct program_space *search_pspace,
2710                             struct symtab *default_symtab,
2711                             int default_line,
2712                             struct linespec_result *canonical)
2713 {
2714   memset (self, 0, sizeof (*self));
2715   self->language = language;
2716   self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2717   self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2718   self->search_pspace = search_pspace;
2719   self->default_symtab = default_symtab;
2720   self->default_line = default_line;
2721   self->canonical = canonical;
2722   self->program_space = current_program_space;
2723   self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2724                                       xfree, xcalloc, xfree);
2725   self->is_linespec = 0;
2726 }
2727
2728 /* Initialize a new linespec parser.  */
2729
2730 static void
2731 linespec_parser_new (linespec_parser *parser,
2732                      int flags, const struct language_defn *language,
2733                      struct program_space *search_pspace,
2734                      struct symtab *default_symtab,
2735                      int default_line,
2736                      struct linespec_result *canonical)
2737 {
2738   memset (parser, 0, sizeof (linespec_parser));
2739   parser->lexer.current.type = LSTOKEN_CONSUMED;
2740   memset (PARSER_RESULT (parser), 0, sizeof (struct linespec));
2741   PARSER_RESULT (parser)->file_symtabs = new std::vector<symtab *> ();
2742   PARSER_EXPLICIT (parser)->func_name_match_type
2743     = symbol_name_match_type::WILD;
2744   PARSER_EXPLICIT (parser)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2745   linespec_state_constructor (PARSER_STATE (parser), flags, language,
2746                               search_pspace,
2747                               default_symtab, default_line, canonical);
2748 }
2749
2750 /* A destructor for linespec_state.  */
2751
2752 static void
2753 linespec_state_destructor (struct linespec_state *self)
2754 {
2755   htab_delete (self->addr_set);
2756 }
2757
2758 /* Delete a linespec parser.  */
2759
2760 static void
2761 linespec_parser_delete (void *arg)
2762 {
2763   linespec_parser *parser = (linespec_parser *) arg;
2764
2765   xfree (PARSER_EXPLICIT (parser)->source_filename);
2766   xfree (PARSER_EXPLICIT (parser)->label_name);
2767   xfree (PARSER_EXPLICIT (parser)->function_name);
2768
2769   delete PARSER_RESULT (parser)->file_symtabs;
2770   delete PARSER_RESULT (parser)->function_symbols;
2771   delete PARSER_RESULT (parser)->minimal_symbols;
2772   delete PARSER_RESULT (parser)->labels.label_symbols;
2773   delete PARSER_RESULT (parser)->labels.function_symbols;
2774
2775   linespec_state_destructor (PARSER_STATE (parser));
2776 }
2777
2778 /* See description in linespec.h.  */
2779
2780 void
2781 linespec_lex_to_end (const char **stringp)
2782 {
2783   linespec_parser parser;
2784   struct cleanup *cleanup;
2785   linespec_token token;
2786   const char *orig;
2787
2788   if (stringp == NULL || *stringp == NULL)
2789     return;
2790
2791   linespec_parser_new (&parser, 0, current_language, NULL, NULL, 0, NULL);
2792   cleanup = make_cleanup (linespec_parser_delete, &parser);
2793   parser.lexer.saved_arg = *stringp;
2794   PARSER_STREAM (&parser) = orig = *stringp;
2795
2796   do
2797     {
2798       /* Stop before any comma tokens;  we need it to keep it
2799          as the next token in the string.  */
2800       token = linespec_lexer_peek_token (&parser);
2801       if (token.type == LSTOKEN_COMMA)
2802         break;
2803       token = linespec_lexer_consume_token (&parser);
2804     }
2805   while (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD);
2806
2807   *stringp += PARSER_STREAM (&parser) - orig;
2808   do_cleanups (cleanup);
2809 }
2810
2811 /* See linespec.h.  */
2812
2813 void
2814 linespec_complete_function (completion_tracker &tracker,
2815                             const char *function,
2816                             symbol_name_match_type func_match_type,
2817                             const char *source_filename)
2818 {
2819   complete_symbol_mode mode = complete_symbol_mode::LINESPEC;
2820
2821   if (source_filename != NULL)
2822     {
2823       collect_file_symbol_completion_matches (tracker, mode, func_match_type,
2824                                               function, function, source_filename);
2825     }
2826   else
2827     {
2828       collect_symbol_completion_matches (tracker, mode, func_match_type,
2829                                          function, function);
2830
2831     }
2832 }
2833
2834 /* Helper for complete_linespec to simplify it.  SOURCE_FILENAME is
2835    only meaningful if COMPONENT is FUNCTION.  */
2836
2837 static void
2838 complete_linespec_component (linespec_parser *parser,
2839                              completion_tracker &tracker,
2840                              const char *text,
2841                              linespec_complete_what component,
2842                              const char *source_filename)
2843 {
2844   if (component == linespec_complete_what::KEYWORD)
2845     {
2846       complete_on_enum (tracker, linespec_keywords, text, text);
2847     }
2848   else if (component == linespec_complete_what::EXPRESSION)
2849     {
2850       const char *word
2851         = advance_to_expression_complete_word_point (tracker, text);
2852       complete_expression (tracker, text, word);
2853     }
2854   else if (component == linespec_complete_what::FUNCTION)
2855     {
2856       completion_list fn_list;
2857
2858       symbol_name_match_type match_type
2859         = PARSER_EXPLICIT (parser)->func_name_match_type;
2860       linespec_complete_function (tracker, text, match_type, source_filename);
2861       if (source_filename == NULL)
2862         {
2863           /* Haven't seen a source component, like in "b
2864              file.c:function[TAB]".  Maybe this wasn't a function, but
2865              a filename instead, like "b file.[TAB]".  */
2866           fn_list = complete_source_filenames (text);
2867         }
2868
2869       /* If we only have a single filename completion, append a ':' for
2870          the user, since that's the only thing that can usefully follow
2871          the filename.  */
2872       if (fn_list.size () == 1 && !tracker.have_completions ())
2873         {
2874           char *fn = fn_list[0].release ();
2875
2876           /* If we also need to append a quote char, it needs to be
2877              appended before the ':'.  Append it now, and make ':' the
2878              new "quote" char.  */
2879           if (tracker.quote_char ())
2880             {
2881               char quote_char_str[2] = { (char) tracker.quote_char () };
2882
2883               fn = reconcat (fn, fn, quote_char_str, (char *) NULL);
2884               tracker.set_quote_char (':');
2885             }
2886           else
2887             fn = reconcat (fn, fn, ":", (char *) NULL);
2888           fn_list[0].reset (fn);
2889
2890           /* Tell readline to skip appending a space.  */
2891           tracker.set_suppress_append_ws (true);
2892         }
2893       tracker.add_completions (std::move (fn_list));
2894     }
2895 }
2896
2897 /* Helper for linespec_complete_label.  Find labels that match
2898    LABEL_NAME in the function symbols listed in the PARSER, and add
2899    them to the tracker.  */
2900
2901 static void
2902 complete_label (completion_tracker &tracker,
2903                 linespec_parser *parser,
2904                 const char *label_name)
2905 {
2906   std::vector<block_symbol> label_function_symbols;
2907   std::vector<block_symbol> *labels
2908     = find_label_symbols (PARSER_STATE (parser),
2909                           PARSER_RESULT (parser)->function_symbols,
2910                           &label_function_symbols,
2911                           label_name, true);
2912
2913   if (labels != nullptr)
2914     {
2915       for (const auto &label : *labels)
2916         {
2917           char *match = xstrdup (SYMBOL_SEARCH_NAME (label.symbol));
2918           tracker.add_completion (gdb::unique_xmalloc_ptr<char> (match));
2919         }
2920       delete labels;
2921     }
2922 }
2923
2924 /* See linespec.h.  */
2925
2926 void
2927 linespec_complete_label (completion_tracker &tracker,
2928                          const struct language_defn *language,
2929                          const char *source_filename,
2930                          const char *function_name,
2931                          symbol_name_match_type func_name_match_type,
2932                          const char *label_name)
2933 {
2934   linespec_parser parser;
2935   struct cleanup *cleanup;
2936
2937   linespec_parser_new (&parser, 0, language, NULL, NULL, 0, NULL);
2938   cleanup = make_cleanup (linespec_parser_delete, &parser);
2939
2940   line_offset unknown_offset = { 0, LINE_OFFSET_UNKNOWN };
2941
2942   TRY
2943     {
2944       convert_explicit_location_to_linespec (PARSER_STATE (&parser),
2945                                              PARSER_RESULT (&parser),
2946                                              source_filename,
2947                                              function_name,
2948                                              func_name_match_type,
2949                                              NULL, unknown_offset);
2950     }
2951   CATCH (ex, RETURN_MASK_ERROR)
2952     {
2953       do_cleanups (cleanup);
2954       return;
2955     }
2956   END_CATCH
2957
2958   complete_label (tracker, &parser, label_name);
2959
2960   do_cleanups (cleanup);
2961 }
2962
2963 /* See description in linespec.h.  */
2964
2965 void
2966 linespec_complete (completion_tracker &tracker, const char *text,
2967                    symbol_name_match_type match_type)
2968 {
2969   linespec_parser parser;
2970   struct cleanup *cleanup;
2971   const char *orig = text;
2972
2973   linespec_parser_new (&parser, 0, current_language, NULL, NULL, 0, NULL);
2974   cleanup = make_cleanup (linespec_parser_delete, &parser);
2975   parser.lexer.saved_arg = text;
2976   PARSER_EXPLICIT (&parser)->func_name_match_type = match_type;
2977   PARSER_STREAM (&parser) = text;
2978
2979   parser.completion_tracker = &tracker;
2980   PARSER_STATE (&parser)->is_linespec = 1;
2981
2982   /* Parse as much as possible.  parser.completion_word will hold
2983      furthest completion point we managed to parse to.  */
2984   TRY
2985     {
2986       parse_linespec (&parser, text, match_type);
2987     }
2988   CATCH (except, RETURN_MASK_ERROR)
2989     {
2990     }
2991   END_CATCH
2992
2993   if (parser.completion_quote_char != '\0'
2994       && parser.completion_quote_end != NULL
2995       && parser.completion_quote_end[1] == '\0')
2996     {
2997       /* If completing a quoted string with the cursor right at
2998          terminating quote char, complete the completion word without
2999          interpretation, so that readline advances the cursor one
3000          whitespace past the quote, even if there's no match.  This
3001          makes these cases behave the same:
3002
3003            before: "b function()"
3004            after:  "b function() "
3005
3006            before: "b 'function()'"
3007            after:  "b 'function()' "
3008
3009          and trusts the user in this case:
3010
3011            before: "b 'not_loaded_function_yet()'"
3012            after:  "b 'not_loaded_function_yet()' "
3013       */
3014       parser.complete_what = linespec_complete_what::NOTHING;
3015       parser.completion_quote_char = '\0';
3016
3017       gdb::unique_xmalloc_ptr<char> text_copy
3018         (xstrdup (parser.completion_word));
3019       tracker.add_completion (std::move (text_copy));
3020     }
3021
3022   tracker.set_quote_char (parser.completion_quote_char);
3023
3024   if (parser.complete_what == linespec_complete_what::LABEL)
3025     {
3026       parser.complete_what = linespec_complete_what::NOTHING;
3027
3028       const char *func_name = PARSER_EXPLICIT (&parser)->function_name;
3029
3030       std::vector<block_symbol> function_symbols;
3031       std::vector<bound_minimal_symbol> minimal_symbols;
3032       find_linespec_symbols (PARSER_STATE (&parser),
3033                              PARSER_RESULT (&parser)->file_symtabs,
3034                              func_name, match_type,
3035                              &function_symbols, &minimal_symbols);
3036
3037       PARSER_RESULT (&parser)->function_symbols
3038         = new std::vector<block_symbol> (std::move (function_symbols));
3039       PARSER_RESULT (&parser)->minimal_symbols
3040         = new std::vector<bound_minimal_symbol> (std::move (minimal_symbols));
3041
3042       complete_label (tracker, &parser, parser.completion_word);
3043     }
3044   else if (parser.complete_what == linespec_complete_what::FUNCTION)
3045     {
3046       /* While parsing/lexing, we didn't know whether the completion
3047          word completes to a unique function/source name already or
3048          not.
3049
3050          E.g.:
3051            "b function() <tab>"
3052          may need to complete either to:
3053            "b function() const"
3054          or to:
3055            "b function() if/thread/task"
3056
3057          Or, this:
3058            "b foo t"
3059          may need to complete either to:
3060            "b foo template_fun<T>()"
3061          with "foo" being the template function's return type, or to:
3062            "b foo thread/task"
3063
3064          Or, this:
3065            "b file<TAB>"
3066          may need to complete either to a source file name:
3067            "b file.c"
3068          or this, also a filename, but a unique completion:
3069            "b file.c:"
3070          or to a function name:
3071            "b file_function"
3072
3073          Address that by completing assuming source or function, and
3074          seeing if we find a completion that matches exactly the
3075          completion word.  If so, then it must be a function (see note
3076          below) and we advance the completion word to the end of input
3077          and switch to KEYWORD completion mode.
3078
3079          Note: if we find a unique completion for a source filename,
3080          then it won't match the completion word, because the LCD will
3081          contain a trailing ':'.  And if we're completing at or after
3082          the ':', then complete_linespec_component won't try to
3083          complete on source filenames.  */
3084
3085       const char *word = parser.completion_word;
3086
3087       complete_linespec_component (&parser, tracker,
3088                                    parser.completion_word,
3089                                    linespec_complete_what::FUNCTION,
3090                                    PARSER_EXPLICIT (&parser)->source_filename);
3091
3092       parser.complete_what = linespec_complete_what::NOTHING;
3093
3094       if (tracker.quote_char ())
3095         {
3096           /* The function/file name was not close-quoted, so this
3097              can't be a keyword.  Note: complete_linespec_component
3098              may have swapped the original quote char for ':' when we
3099              get here, but that still indicates the same.  */
3100         }
3101       else if (!tracker.have_completions ())
3102         {
3103           size_t key_start;
3104           size_t wordlen = strlen (parser.completion_word);
3105
3106           key_start
3107             = string_find_incomplete_keyword_at_end (linespec_keywords,
3108                                                      parser.completion_word,
3109                                                      wordlen);
3110
3111           if (key_start != -1
3112               || (wordlen > 0
3113                   && parser.completion_word[wordlen - 1] == ' '))
3114             {
3115               parser.completion_word += key_start;
3116               parser.complete_what = linespec_complete_what::KEYWORD;
3117             }
3118         }
3119       else if (tracker.completes_to_completion_word (word))
3120         {
3121           /* Skip the function and complete on keywords.  */
3122           parser.completion_word += strlen (word);
3123           parser.complete_what = linespec_complete_what::KEYWORD;
3124           tracker.discard_completions ();
3125         }
3126     }
3127
3128   tracker.advance_custom_word_point_by (parser.completion_word - orig);
3129
3130   complete_linespec_component (&parser, tracker,
3131                                parser.completion_word,
3132                                parser.complete_what,
3133                                PARSER_EXPLICIT (&parser)->source_filename);
3134
3135   /* If we're past the "filename:function:label:offset" linespec, and
3136      didn't find any match, then assume the user might want to create
3137      a pending breakpoint anyway and offer the keyword
3138      completions.  */
3139   if (!parser.completion_quote_char
3140       && (parser.complete_what == linespec_complete_what::FUNCTION
3141           || parser.complete_what == linespec_complete_what::LABEL
3142           || parser.complete_what == linespec_complete_what::NOTHING)
3143       && !tracker.have_completions ())
3144     {
3145       const char *end
3146         = parser.completion_word + strlen (parser.completion_word);
3147
3148       if (end > orig && end[-1] == ' ')
3149         {
3150           tracker.advance_custom_word_point_by (end - parser.completion_word);
3151
3152           complete_linespec_component (&parser, tracker, end,
3153                                        linespec_complete_what::KEYWORD,
3154                                        NULL);
3155         }
3156     }
3157
3158   do_cleanups (cleanup);
3159 }
3160
3161 /* A helper function for decode_line_full and decode_line_1 to
3162    turn LOCATION into std::vector<symtab_and_line>.  */
3163
3164 static std::vector<symtab_and_line>
3165 event_location_to_sals (linespec_parser *parser,
3166                         const struct event_location *location)
3167 {
3168   std::vector<symtab_and_line> result;
3169
3170   switch (event_location_type (location))
3171     {
3172     case LINESPEC_LOCATION:
3173       {
3174         PARSER_STATE (parser)->is_linespec = 1;
3175         TRY
3176           {
3177             const linespec_location *ls = get_linespec_location (location);
3178             result = parse_linespec (parser,
3179                                      ls->spec_string, ls->match_type);
3180           }
3181         CATCH (except, RETURN_MASK_ERROR)
3182           {
3183             throw_exception (except);
3184           }
3185         END_CATCH
3186       }
3187       break;
3188
3189     case ADDRESS_LOCATION:
3190       {
3191         const char *addr_string = get_address_string_location (location);
3192         CORE_ADDR addr = get_address_location (location);
3193
3194         if (addr_string != NULL)
3195           {
3196             addr = linespec_expression_to_pc (&addr_string);
3197             if (PARSER_STATE (parser)->canonical != NULL)
3198               PARSER_STATE (parser)->canonical->location
3199                 = copy_event_location (location);
3200           }
3201
3202         result = convert_address_location_to_sals (PARSER_STATE (parser),
3203                                                    addr);
3204       }
3205       break;
3206
3207     case EXPLICIT_LOCATION:
3208       {
3209         const struct explicit_location *explicit_loc;
3210
3211         explicit_loc = get_explicit_location_const (location);
3212         result = convert_explicit_location_to_sals (PARSER_STATE (parser),
3213                                                     PARSER_RESULT (parser),
3214                                                     explicit_loc);
3215       }
3216       break;
3217
3218     case PROBE_LOCATION:
3219       /* Probes are handled by their own decoders.  */
3220       gdb_assert_not_reached ("attempt to decode probe location");
3221       break;
3222
3223     default:
3224       gdb_assert_not_reached ("unhandled event location type");
3225     }
3226
3227   return result;
3228 }
3229
3230 /* See linespec.h.  */
3231
3232 void
3233 decode_line_full (const struct event_location *location, int flags,
3234                   struct program_space *search_pspace,
3235                   struct symtab *default_symtab,
3236                   int default_line, struct linespec_result *canonical,
3237                   const char *select_mode,
3238                   const char *filter)
3239 {
3240   struct cleanup *cleanups;
3241   std::vector<const char *> filters;
3242   linespec_parser parser;
3243   struct linespec_state *state;
3244
3245   gdb_assert (canonical != NULL);
3246   /* The filter only makes sense for 'all'.  */
3247   gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
3248   gdb_assert (select_mode == NULL
3249               || select_mode == multiple_symbols_all
3250               || select_mode == multiple_symbols_ask
3251               || select_mode == multiple_symbols_cancel);
3252   gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
3253
3254   linespec_parser_new (&parser, flags, current_language,
3255                        search_pspace, default_symtab,
3256                        default_line, canonical);
3257   cleanups = make_cleanup (linespec_parser_delete, &parser);
3258
3259   scoped_restore_current_program_space restore_pspace;
3260
3261   std::vector<symtab_and_line> result = event_location_to_sals (&parser,
3262                                                                 location);
3263   state = PARSER_STATE (&parser);
3264
3265   gdb_assert (result.size () == 1 || canonical->pre_expanded);
3266   canonical->pre_expanded = 1;
3267
3268   /* Arrange for allocated canonical names to be freed.  */
3269   if (!result.empty ())
3270     {
3271       int i;
3272
3273       make_cleanup (xfree, state->canonical_names);
3274       for (i = 0; i < result.size (); ++i)
3275         {
3276           gdb_assert (state->canonical_names[i].suffix != NULL);
3277           make_cleanup (xfree, state->canonical_names[i].suffix);
3278         }
3279     }
3280
3281   if (select_mode == NULL)
3282     {
3283       if (top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
3284         select_mode = multiple_symbols_all;
3285       else
3286         select_mode = multiple_symbols_select_mode ();
3287     }
3288
3289   if (select_mode == multiple_symbols_all)
3290     {
3291       if (filter != NULL)
3292         {
3293           filters.push_back (filter);
3294           filter_results (state, &result, filters);
3295         }
3296       else
3297         convert_results_to_lsals (state, &result);
3298     }
3299   else
3300     decode_line_2 (state, &result, select_mode);
3301
3302   do_cleanups (cleanups);
3303 }
3304
3305 /* See linespec.h.  */
3306
3307 std::vector<symtab_and_line>
3308 decode_line_1 (const struct event_location *location, int flags,
3309                struct program_space *search_pspace,
3310                struct symtab *default_symtab,
3311                int default_line)
3312 {
3313   linespec_parser parser;
3314   struct cleanup *cleanups;
3315
3316   linespec_parser_new (&parser, flags, current_language,
3317                        search_pspace, default_symtab,
3318                        default_line, NULL);
3319   cleanups = make_cleanup (linespec_parser_delete, &parser);
3320
3321   scoped_restore_current_program_space restore_pspace;
3322
3323   std::vector<symtab_and_line> result = event_location_to_sals (&parser,
3324                                                                 location);
3325
3326   do_cleanups (cleanups);
3327   return result;
3328 }
3329
3330 /* See linespec.h.  */
3331
3332 std::vector<symtab_and_line>
3333 decode_line_with_current_source (const char *string, int flags)
3334 {
3335   if (string == 0)
3336     error (_("Empty line specification."));
3337
3338   /* We use whatever is set as the current source line.  We do not try
3339      and get a default source symtab+line or it will recursively call us!  */
3340   symtab_and_line cursal = get_current_source_symtab_and_line ();
3341
3342   event_location_up location = string_to_event_location (&string,
3343                                                          current_language);
3344   std::vector<symtab_and_line> sals
3345     = decode_line_1 (location.get (), flags, NULL, cursal.symtab, cursal.line);
3346
3347   if (*string)
3348     error (_("Junk at end of line specification: %s"), string);
3349
3350   return sals;
3351 }
3352
3353 /* See linespec.h.  */
3354
3355 std::vector<symtab_and_line>
3356 decode_line_with_last_displayed (const char *string, int flags)
3357 {
3358   if (string == 0)
3359     error (_("Empty line specification."));
3360
3361   event_location_up location = string_to_event_location (&string,
3362                                                          current_language);
3363   std::vector<symtab_and_line> sals
3364     = (last_displayed_sal_is_valid ()
3365        ? decode_line_1 (location.get (), flags, NULL,
3366                         get_last_displayed_symtab (),
3367                         get_last_displayed_line ())
3368        : decode_line_1 (location.get (), flags, NULL,
3369                         (struct symtab *) NULL, 0));
3370
3371   if (*string)
3372     error (_("Junk at end of line specification: %s"), string);
3373
3374   return sals;
3375 }
3376
3377 \f
3378
3379 /* First, some functions to initialize stuff at the beggining of the
3380    function.  */
3381
3382 static void
3383 initialize_defaults (struct symtab **default_symtab, int *default_line)
3384 {
3385   if (*default_symtab == 0)
3386     {
3387       /* Use whatever we have for the default source line.  We don't use
3388          get_current_or_default_symtab_and_line as it can recurse and call
3389          us back!  */
3390       struct symtab_and_line cursal = 
3391         get_current_source_symtab_and_line ();
3392       
3393       *default_symtab = cursal.symtab;
3394       *default_line = cursal.line;
3395     }
3396 }
3397
3398 \f
3399
3400 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
3401    advancing EXP_PTR past any parsed text.  */
3402
3403 CORE_ADDR
3404 linespec_expression_to_pc (const char **exp_ptr)
3405 {
3406   if (current_program_space->executing_startup)
3407     /* The error message doesn't really matter, because this case
3408        should only hit during breakpoint reset.  */
3409     throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
3410                                     "program space is in startup"));
3411
3412   (*exp_ptr)++;
3413   return value_as_address (parse_to_comma_and_eval (exp_ptr));
3414 }
3415
3416 \f
3417
3418 /* Here's where we recognise an Objective-C Selector.  An Objective C
3419    selector may be implemented by more than one class, therefore it
3420    may represent more than one method/function.  This gives us a
3421    situation somewhat analogous to C++ overloading.  If there's more
3422    than one method that could represent the selector, then use some of
3423    the existing C++ code to let the user choose one.  */
3424
3425 static std::vector<symtab_and_line>
3426 decode_objc (struct linespec_state *self, linespec_p ls, const char *arg)
3427 {
3428   struct collect_info info;
3429   std::vector<const char *> symbol_names;
3430   const char *new_argptr;
3431
3432   info.state = self;
3433   std::vector<symtab *> symtabs;
3434   symtabs.push_back (nullptr);
3435
3436   info.file_symtabs = &symtabs;
3437
3438   std::vector<block_symbol> symbols;
3439   info.result.symbols = &symbols;
3440   std::vector<bound_minimal_symbol> minimal_symbols;
3441   info.result.minimal_symbols = &minimal_symbols;
3442
3443   new_argptr = find_imps (arg, &symbol_names);
3444   if (symbol_names.empty ())
3445     return {};
3446
3447   add_all_symbol_names_from_pspace (&info, NULL, symbol_names,
3448                                     FUNCTIONS_DOMAIN);
3449
3450   std::vector<symtab_and_line> values;
3451   if (!symbols.empty () || !minimal_symbols.empty ())
3452     {
3453       char *saved_arg;
3454
3455       saved_arg = (char *) alloca (new_argptr - arg + 1);
3456       memcpy (saved_arg, arg, new_argptr - arg);
3457       saved_arg[new_argptr - arg] = '\0';
3458
3459       ls->explicit_loc.function_name = xstrdup (saved_arg);
3460       ls->function_symbols
3461         = new std::vector<block_symbol> (std::move (symbols));
3462       ls->minimal_symbols
3463         = new std::vector<bound_minimal_symbol> (std::move (minimal_symbols));
3464       values = convert_linespec_to_sals (self, ls);
3465
3466       if (self->canonical)
3467         {
3468           std::string holder;
3469           const char *str;
3470
3471           self->canonical->pre_expanded = 1;
3472
3473           if (ls->explicit_loc.source_filename)
3474             {
3475               holder = string_printf ("%s:%s",
3476                                       ls->explicit_loc.source_filename,
3477                                       saved_arg);
3478               str = holder.c_str ();
3479             }
3480           else
3481             str = saved_arg;
3482
3483           self->canonical->location
3484             = new_linespec_location (&str, symbol_name_match_type::FULL);
3485         }
3486     }
3487
3488   return values;
3489 }
3490
3491 namespace {
3492
3493 /* A function object that serves as symbol_found_callback_ftype
3494    callback for iterate_over_symbols.  This is used by
3495    lookup_prefix_sym to collect type symbols.  */
3496 class decode_compound_collector
3497 {
3498 public:
3499   decode_compound_collector ()
3500   {
3501     m_unique_syms = htab_create_alloc (1, htab_hash_pointer,
3502                                        htab_eq_pointer, NULL,
3503                                        xcalloc, xfree);
3504   }
3505
3506   ~decode_compound_collector ()
3507   {
3508     if (m_unique_syms != NULL)
3509       htab_delete (m_unique_syms);
3510   }
3511
3512   /* Return all symbols collected.  */
3513   std::vector<block_symbol> release_symbols ()
3514   {
3515     return std::move (m_symbols);
3516   }
3517
3518   /* Callable as a symbol_found_callback_ftype callback.  */
3519   bool operator () (block_symbol *bsym);
3520
3521 private:
3522   /* A hash table of all symbols we found.  We use this to avoid
3523      adding any symbol more than once.  */
3524   htab_t m_unique_syms;
3525
3526   /* The result vector.  */
3527   std::vector<block_symbol>  m_symbols;
3528 };
3529
3530 bool
3531 decode_compound_collector::operator () (block_symbol *bsym)
3532 {
3533   void **slot;
3534   struct type *t;
3535   struct symbol *sym = bsym->symbol;
3536
3537   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
3538     return true; /* Continue iterating.  */
3539
3540   t = SYMBOL_TYPE (sym);
3541   t = check_typedef (t);
3542   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
3543       && TYPE_CODE (t) != TYPE_CODE_UNION
3544       && TYPE_CODE (t) != TYPE_CODE_NAMESPACE)
3545     return true; /* Continue iterating.  */
3546
3547   slot = htab_find_slot (m_unique_syms, sym, INSERT);
3548   if (!*slot)
3549     {
3550       *slot = sym;
3551       m_symbols.push_back (*bsym);
3552     }
3553
3554   return true; /* Continue iterating.  */
3555 }
3556
3557 } // namespace
3558
3559 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS.  */
3560
3561 static std::vector<block_symbol>
3562 lookup_prefix_sym (struct linespec_state *state,
3563                    std::vector<symtab *> *file_symtabs,
3564                    const char *class_name)
3565 {
3566   decode_compound_collector collector;
3567
3568   lookup_name_info lookup_name (class_name, symbol_name_match_type::FULL);
3569
3570   for (const auto &elt : *file_symtabs)
3571     {
3572       if (elt == nullptr)
3573         {
3574           iterate_over_all_matching_symtabs (state, lookup_name,
3575                                              STRUCT_DOMAIN, ALL_DOMAIN,
3576                                              NULL, false, collector);
3577           iterate_over_all_matching_symtabs (state, lookup_name,
3578                                              VAR_DOMAIN, ALL_DOMAIN,
3579                                              NULL, false, collector);
3580         }
3581       else
3582         {
3583           /* Program spaces that are executing startup should have
3584              been filtered out earlier.  */
3585           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
3586           set_current_program_space (SYMTAB_PSPACE (elt));
3587           iterate_over_file_blocks (elt, lookup_name, STRUCT_DOMAIN, collector);
3588           iterate_over_file_blocks (elt, lookup_name, VAR_DOMAIN, collector);
3589         }
3590     }
3591
3592   return collector.release_symbols ();
3593 }
3594
3595 /* A std::sort comparison function for symbols.  The resulting order does
3596    not actually matter; we just need to be able to sort them so that
3597    symbols with the same program space end up next to each other.  */
3598
3599 static bool
3600 compare_symbols (const block_symbol &a, const block_symbol &b)
3601 {
3602   uintptr_t uia, uib;
3603
3604   uia = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (a.symbol));
3605   uib = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (b.symbol));
3606
3607   if (uia < uib)
3608     return true;
3609   if (uia > uib)
3610     return false;
3611
3612   uia = (uintptr_t) a.symbol;
3613   uib = (uintptr_t) b.symbol;
3614
3615   if (uia < uib)
3616     return true;
3617
3618   return false;
3619 }
3620
3621 /* Like compare_symbols but for minimal symbols.  */
3622
3623 static bool
3624 compare_msymbols (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
3625 {
3626   uintptr_t uia, uib;
3627
3628   uia = (uintptr_t) a.objfile->pspace;
3629   uib = (uintptr_t) a.objfile->pspace;
3630
3631   if (uia < uib)
3632     return true;
3633   if (uia > uib)
3634     return false;
3635
3636   uia = (uintptr_t) a.minsym;
3637   uib = (uintptr_t) b.minsym;
3638
3639   if (uia < uib)
3640     return true;
3641
3642   return false;
3643 }
3644
3645 /* Look for all the matching instances of each symbol in NAMES.  Only
3646    instances from PSPACE are considered; other program spaces are
3647    handled by our caller.  If PSPACE is NULL, then all program spaces
3648    are considered.  Results are stored into INFO.  */
3649
3650 static void
3651 add_all_symbol_names_from_pspace (struct collect_info *info,
3652                                   struct program_space *pspace,
3653                                   const std::vector<const char *> &names,
3654                                   enum search_domain search_domain)
3655 {
3656   for (const char *iter : names)
3657     add_matching_symbols_to_info (iter,
3658                                   symbol_name_match_type::FULL,
3659                                   search_domain, info, pspace);
3660 }
3661
3662 static void
3663 find_superclass_methods (std::vector<struct type *> &&superclasses,
3664                          const char *name, enum language name_lang,
3665                          std::vector<const char *> *result_names)
3666 {
3667   size_t old_len = result_names->size ();
3668
3669   while (1)
3670     {
3671       std::vector<struct type *> new_supers;
3672
3673       for (type *t : superclasses)
3674         find_methods (t, name_lang, name, result_names, &new_supers);
3675
3676       if (result_names->size () != old_len || new_supers.empty ())
3677         break;
3678
3679       superclasses = std::move (new_supers);
3680     }
3681 }
3682
3683 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
3684    given by one of the symbols in SYM_CLASSES.  Matches are returned
3685    in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols).  */
3686
3687 static void
3688 find_method (struct linespec_state *self, std::vector<symtab *> *file_symtabs,
3689              const char *class_name, const char *method_name,
3690              std::vector<block_symbol> *sym_classes,
3691              std::vector<block_symbol> *symbols,
3692              std::vector<bound_minimal_symbol> *minsyms)
3693 {
3694   size_t last_result_len;
3695   std::vector<struct type *> superclass_vec;
3696   std::vector<const char *> result_names;
3697   struct collect_info info;
3698
3699   /* Sort symbols so that symbols with the same program space are next
3700      to each other.  */
3701   std::sort (sym_classes->begin (), sym_classes->end (),
3702              compare_symbols);
3703
3704   info.state = self;
3705   info.file_symtabs = file_symtabs;
3706   info.result.symbols = symbols;
3707   info.result.minimal_symbols = minsyms;
3708
3709   /* Iterate over all the types, looking for the names of existing
3710      methods matching METHOD_NAME.  If we cannot find a direct method in a
3711      given program space, then we consider inherited methods; this is
3712      not ideal (ideal would be to respect C++ hiding rules), but it
3713      seems good enough and is what GDB has historically done.  We only
3714      need to collect the names because later we find all symbols with
3715      those names.  This loop is written in a somewhat funny way
3716      because we collect data across the program space before deciding
3717      what to do.  */
3718   last_result_len = 0;
3719   unsigned int ix = 0;
3720   for (const auto &elt : *sym_classes)
3721     {
3722       struct type *t;
3723       struct program_space *pspace;
3724       struct symbol *sym = elt.symbol;
3725
3726       /* Program spaces that are executing startup should have
3727          been filtered out earlier.  */
3728       pspace = SYMTAB_PSPACE (symbol_symtab (sym));
3729       gdb_assert (!pspace->executing_startup);
3730       set_current_program_space (pspace);
3731       t = check_typedef (SYMBOL_TYPE (sym));
3732       find_methods (t, SYMBOL_LANGUAGE (sym),
3733                     method_name, &result_names, &superclass_vec);
3734
3735       /* Handle all items from a single program space at once; and be
3736          sure not to miss the last batch.  */
3737       if (ix == sym_classes->size () - 1
3738           || (pspace
3739               != SYMTAB_PSPACE (symbol_symtab (sym_classes->at (ix + 1).symbol))))
3740         {
3741           /* If we did not find a direct implementation anywhere in
3742              this program space, consider superclasses.  */
3743           if (result_names.size () == last_result_len)
3744             find_superclass_methods (std::move (superclass_vec), method_name,
3745                                      SYMBOL_LANGUAGE (sym), &result_names);
3746
3747           /* We have a list of candidate symbol names, so now we
3748              iterate over the symbol tables looking for all
3749              matches in this pspace.  */
3750           add_all_symbol_names_from_pspace (&info, pspace, result_names,
3751                                             FUNCTIONS_DOMAIN);
3752
3753           superclass_vec.clear ();
3754           last_result_len = result_names.size ();
3755           ++ix;
3756         }
3757     }
3758
3759   if (!symbols->empty () || !minsyms->empty ())
3760     return;
3761
3762   /* Throw an NOT_FOUND_ERROR.  This will be caught by the caller
3763      and other attempts to locate the symbol will be made.  */
3764   throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
3765 }
3766
3767 \f
3768
3769 namespace {
3770
3771 /* This function object is a callback for iterate_over_symtabs, used
3772    when collecting all matching symtabs.  */
3773
3774 class symtab_collector
3775 {
3776 public:
3777   symtab_collector ()
3778     : m_symtabs (new std::vector<symtab *> ())
3779   {
3780     m_symtab_table = htab_create (1, htab_hash_pointer, htab_eq_pointer,
3781                                   NULL);
3782   }
3783
3784   ~symtab_collector ()
3785   {
3786     if (m_symtab_table != NULL)
3787       htab_delete (m_symtab_table);
3788   }
3789
3790   /* Callable as a symbol_found_callback_ftype callback.  */
3791   bool operator () (symtab *sym);
3792
3793   /* Releases ownership of the collected symtabs and returns them.  */
3794   symtab_vector_up release_symtabs ()
3795   {
3796     return std::move (m_symtabs);
3797   }
3798
3799 private:
3800   /* The result vector of symtabs.  */
3801   symtab_vector_up m_symtabs;
3802
3803   /* This is used to ensure the symtabs are unique.  */
3804   htab_t m_symtab_table;
3805 };
3806
3807 bool
3808 symtab_collector::operator () (struct symtab *symtab)
3809 {
3810   void **slot;
3811
3812   slot = htab_find_slot (m_symtab_table, symtab, INSERT);
3813   if (!*slot)
3814     {
3815       *slot = symtab;
3816       m_symtabs->push_back (symtab);
3817     }
3818
3819   return false;
3820 }
3821
3822 } // namespace
3823
3824 /* Given a file name, return a list of all matching symtabs.  If
3825    SEARCH_PSPACE is not NULL, the search is restricted to just that
3826    program space.  */
3827
3828 static symtab_vector_up
3829 collect_symtabs_from_filename (const char *file,
3830                                struct program_space *search_pspace)
3831 {
3832   symtab_collector collector;
3833
3834   /* Find that file's data.  */
3835   if (search_pspace == NULL)
3836     {
3837       struct program_space *pspace;
3838
3839       ALL_PSPACES (pspace)
3840         {
3841           if (pspace->executing_startup)
3842             continue;
3843
3844           set_current_program_space (pspace);
3845           iterate_over_symtabs (file, collector);
3846         }
3847     }
3848   else
3849     {
3850       set_current_program_space (search_pspace);
3851       iterate_over_symtabs (file, collector);
3852     }
3853
3854   return collector.release_symtabs ();
3855 }
3856
3857 /* Return all the symtabs associated to the FILENAME.  If SEARCH_PSPACE is
3858    not NULL, the search is restricted to just that program space.  */
3859
3860 static symtab_vector_up
3861 symtabs_from_filename (const char *filename,
3862                        struct program_space *search_pspace)
3863 {
3864   symtab_vector_up result
3865     = collect_symtabs_from_filename (filename, search_pspace);
3866
3867   if (result->empty ())
3868     {
3869       if (!have_full_symbols () && !have_partial_symbols ())
3870         throw_error (NOT_FOUND_ERROR,
3871                      _("No symbol table is loaded.  "
3872                        "Use the \"file\" command."));
3873       source_file_not_found_error (filename);
3874     }
3875
3876   return result;
3877 }
3878
3879 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS.  Matching
3880    debug symbols are returned in SYMBOLS.  Matching minimal symbols are
3881    returned in MINSYMS.  */
3882
3883 static void
3884 find_function_symbols (struct linespec_state *state,
3885                        std::vector<symtab *> *file_symtabs, const char *name,
3886                        symbol_name_match_type name_match_type,
3887                        std::vector<block_symbol> *symbols,
3888                        std::vector<bound_minimal_symbol> *minsyms)
3889 {
3890   struct collect_info info;
3891   std::vector<const char *> symbol_names;
3892
3893   info.state = state;
3894   info.result.symbols = symbols;
3895   info.result.minimal_symbols = minsyms;
3896   info.file_symtabs = file_symtabs;
3897
3898   /* Try NAME as an Objective-C selector.  */
3899   find_imps (name, &symbol_names);
3900   if (!symbol_names.empty ())
3901     add_all_symbol_names_from_pspace (&info, state->search_pspace,
3902                                       symbol_names, FUNCTIONS_DOMAIN);
3903   else
3904     add_matching_symbols_to_info (name, name_match_type, FUNCTIONS_DOMAIN,
3905                                   &info, state->search_pspace);
3906 }
3907
3908 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3909    in SYMBOLS and minimal symbols in MINSYMS.  */
3910
3911 static void
3912 find_linespec_symbols (struct linespec_state *state,
3913                        std::vector<symtab *> *file_symtabs,
3914                        const char *lookup_name,
3915                        symbol_name_match_type name_match_type,
3916                        std::vector <block_symbol> *symbols,
3917                        std::vector<bound_minimal_symbol> *minsyms)
3918 {
3919   std::string canon = cp_canonicalize_string_no_typedefs (lookup_name);
3920   if (!canon.empty ())
3921     lookup_name = canon.c_str ();
3922
3923   /* It's important to not call expand_symtabs_matching unnecessarily
3924      as it can really slow things down (by unnecessarily expanding
3925      potentially 1000s of symtabs, which when debugging some apps can
3926      cost 100s of seconds).  Avoid this to some extent by *first* calling
3927      find_function_symbols, and only if that doesn't find anything
3928      *then* call find_method.  This handles two important cases:
3929      1) break (anonymous namespace)::foo
3930      2) break class::method where method is in class (and not a baseclass)  */
3931
3932   find_function_symbols (state, file_symtabs, lookup_name,
3933                          name_match_type, symbols, minsyms);
3934
3935   /* If we were unable to locate a symbol of the same name, try dividing
3936      the name into class and method names and searching the class and its
3937      baseclasses.  */
3938   if (symbols->empty () && minsyms->empty ())
3939     {
3940       std::string klass, method;
3941       const char *last, *p, *scope_op;
3942
3943       /* See if we can find a scope operator and break this symbol
3944          name into namespaces${SCOPE_OPERATOR}class_name and method_name.  */
3945       scope_op = "::";
3946       p = find_toplevel_string (lookup_name, scope_op);
3947
3948       last = NULL;
3949       while (p != NULL)
3950         {
3951           last = p;
3952           p = find_toplevel_string (p + strlen (scope_op), scope_op);
3953         }
3954
3955       /* If no scope operator was found, there is nothing more we can do;
3956          we already attempted to lookup the entire name as a symbol
3957          and failed.  */
3958       if (last == NULL)
3959         return;
3960
3961       /* LOOKUP_NAME points to the class name.
3962          LAST points to the method name.  */
3963       klass = std::string (lookup_name, last - lookup_name);
3964
3965       /* Skip past the scope operator.  */
3966       last += strlen (scope_op);
3967       method = last;
3968
3969       /* Find a list of classes named KLASS.  */
3970       std::vector<block_symbol> classes
3971         = lookup_prefix_sym (state, file_symtabs, klass.c_str ());
3972       if (!classes.empty ())
3973         {
3974           /* Now locate a list of suitable methods named METHOD.  */
3975           TRY
3976             {
3977               find_method (state, file_symtabs,
3978                            klass.c_str (), method.c_str (),
3979                            &classes, symbols, minsyms);
3980             }
3981
3982           /* If successful, we're done.  If NOT_FOUND_ERROR
3983              was not thrown, rethrow the exception that we did get.  */
3984           CATCH (except, RETURN_MASK_ERROR)
3985             {
3986               if (except.error != NOT_FOUND_ERROR)
3987                 throw_exception (except);
3988             }
3989           END_CATCH
3990         }
3991     }
3992 }
3993
3994 /* Helper for find_label_symbols.  Find all labels that match name
3995    NAME in BLOCK.  Return all labels that match in FUNCTION_SYMBOLS.
3996    Return the actual function symbol in which the label was found in
3997    LABEL_FUNC_RET.  If COMPLETION_MODE is true, then NAME is
3998    interpreted as a label name prefix.  Otherwise, only a label named
3999    exactly NAME match.  */
4000
4001 static void
4002 find_label_symbols_in_block (const struct block *block,
4003                              const char *name, struct symbol *fn_sym,
4004                              bool completion_mode,
4005                              std::vector<block_symbol> *result,
4006                              std::vector<block_symbol> *label_funcs_ret)
4007 {
4008   if (completion_mode)
4009     {
4010       struct block_iterator iter;
4011       struct symbol *sym;
4012       size_t name_len = strlen (name);
4013
4014       int (*cmp) (const char *, const char *, size_t);
4015       cmp = case_sensitivity == case_sensitive_on ? strncmp : strncasecmp;
4016
4017       ALL_BLOCK_SYMBOLS (block, iter, sym)
4018         {
4019           if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
4020                                      SYMBOL_DOMAIN (sym), LABEL_DOMAIN)
4021               && cmp (SYMBOL_SEARCH_NAME (sym), name, name_len) == 0)
4022             {
4023               result->push_back ({sym, block});
4024               label_funcs_ret->push_back ({fn_sym, block});
4025             }
4026         }
4027     }
4028   else
4029     {
4030       struct block_symbol label_sym
4031         = lookup_symbol (name, block, LABEL_DOMAIN, 0);
4032
4033       if (label_sym.symbol != NULL)
4034         {
4035           result->push_back (label_sym);
4036           label_funcs_ret->push_back ({fn_sym, block});
4037         }
4038     }
4039 }
4040
4041 /* Return all labels that match name NAME in FUNCTION_SYMBOLS or NULL
4042    if no matches were found.
4043
4044    Return the actual function symbol in which the label was found in
4045    LABEL_FUNC_RET.  If COMPLETION_MODE is true, then NAME is
4046    interpreted as a label name prefix.  Otherwise, only labels named
4047    exactly NAME match.  */
4048
4049
4050 static std::vector<block_symbol> *
4051 find_label_symbols (struct linespec_state *self,
4052                     std::vector<block_symbol> *function_symbols,
4053                     std::vector<block_symbol> *label_funcs_ret,
4054                     const char *name,
4055                     bool completion_mode)
4056 {
4057   const struct block *block;
4058   struct symbol *fn_sym;
4059   std::vector<block_symbol> result;
4060
4061   if (function_symbols == NULL)
4062     {
4063       set_current_program_space (self->program_space);
4064       block = get_current_search_block ();
4065
4066       for (;
4067            block && !BLOCK_FUNCTION (block);
4068            block = BLOCK_SUPERBLOCK (block))
4069         ;
4070       if (!block)
4071         return NULL;
4072       fn_sym = BLOCK_FUNCTION (block);
4073
4074       find_label_symbols_in_block (block, name, fn_sym, completion_mode,
4075                                    &result, label_funcs_ret);
4076     }
4077   else
4078     {
4079       for (const auto &elt : *function_symbols)
4080         {
4081           fn_sym = elt.symbol;
4082           set_current_program_space (SYMTAB_PSPACE (symbol_symtab (fn_sym)));
4083           block = SYMBOL_BLOCK_VALUE (fn_sym);
4084
4085           find_label_symbols_in_block (block, name, fn_sym, completion_mode,
4086                                        &result, label_funcs_ret);
4087         }
4088     }
4089
4090   if (!result.empty ())
4091     return new std::vector<block_symbol> (std::move (result));
4092   return nullptr;
4093 }
4094
4095 \f
4096
4097 /* A helper for create_sals_line_offset that handles the 'list_mode' case.  */
4098
4099 static std::vector<symtab_and_line>
4100 decode_digits_list_mode (struct linespec_state *self,
4101                          linespec_p ls,
4102                          struct symtab_and_line val)
4103 {
4104   gdb_assert (self->list_mode);
4105
4106   std::vector<symtab_and_line> values;
4107
4108   for (const auto &elt : *ls->file_symtabs)
4109     {
4110       /* The logic above should ensure this.  */
4111       gdb_assert (elt != NULL);
4112
4113       set_current_program_space (SYMTAB_PSPACE (elt));
4114
4115       /* Simplistic search just for the list command.  */
4116       val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
4117       if (val.symtab == NULL)
4118         val.symtab = elt;
4119       val.pspace = SYMTAB_PSPACE (elt);
4120       val.pc = 0;
4121       val.explicit_line = 1;
4122
4123       add_sal_to_sals (self, &values, &val, NULL, 0);
4124     }
4125
4126   return values;
4127 }
4128
4129 /* A helper for create_sals_line_offset that iterates over the symtabs,
4130    adding lines to the VEC.  */
4131
4132 static std::vector<symtab_and_line>
4133 decode_digits_ordinary (struct linespec_state *self,
4134                         linespec_p ls,
4135                         int line,
4136                         struct linetable_entry **best_entry)
4137 {
4138   std::vector<symtab_and_line> sals;
4139   for (const auto &elt : *ls->file_symtabs)
4140     {
4141       std::vector<CORE_ADDR> pcs;
4142
4143       /* The logic above should ensure this.  */
4144       gdb_assert (elt != NULL);
4145
4146       set_current_program_space (SYMTAB_PSPACE (elt));
4147
4148       pcs = find_pcs_for_symtab_line (elt, line, best_entry);
4149       for (CORE_ADDR pc : pcs)
4150         {
4151           symtab_and_line sal;
4152           sal.pspace = SYMTAB_PSPACE (elt);
4153           sal.symtab = elt;
4154           sal.line = line;
4155           sal.pc = pc;
4156           sals.push_back (std::move (sal));
4157         }
4158     }
4159
4160   return sals;
4161 }
4162
4163 \f
4164
4165 /* Return the line offset represented by VARIABLE.  */
4166
4167 static struct line_offset
4168 linespec_parse_variable (struct linespec_state *self, const char *variable)
4169 {
4170   int index = 0;
4171   const char *p;
4172   struct line_offset offset = {0, LINE_OFFSET_NONE};
4173
4174   p = (variable[1] == '$') ? variable + 2 : variable + 1;
4175   if (*p == '$')
4176     ++p;
4177   while (*p >= '0' && *p <= '9')
4178     ++p;
4179   if (!*p)              /* Reached end of token without hitting non-digit.  */
4180     {
4181       /* We have a value history reference.  */
4182       struct value *val_history;
4183
4184       sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
4185       val_history
4186         = access_value_history ((variable[1] == '$') ? -index : index);
4187       if (TYPE_CODE (value_type (val_history)) != TYPE_CODE_INT)
4188         error (_("History values used in line "
4189                  "specs must have integer values."));
4190       offset.offset = value_as_long (val_history);
4191     }
4192   else
4193     {
4194       /* Not all digits -- may be user variable/function or a
4195          convenience variable.  */
4196       LONGEST valx;
4197       struct internalvar *ivar;
4198
4199       /* Try it as a convenience variable.  If it is not a convenience
4200          variable, return and allow normal symbol lookup to occur.  */
4201       ivar = lookup_only_internalvar (variable + 1);
4202       if (ivar == NULL)
4203         /* No internal variable with that name.  Mark the offset
4204            as unknown to allow the name to be looked up as a symbol.  */
4205         offset.sign = LINE_OFFSET_UNKNOWN;
4206       else
4207         {
4208           /* We found a valid variable name.  If it is not an integer,
4209              throw an error.  */
4210           if (!get_internalvar_integer (ivar, &valx))
4211             error (_("Convenience variables used in line "
4212                      "specs must have integer values."));
4213           else
4214             offset.offset = valx;
4215         }
4216     }
4217
4218   return offset;
4219 }
4220 \f
4221
4222 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
4223    linespec; return the SAL in RESULT.  This function should return SALs
4224    matching those from find_function_start_sal, otherwise false
4225    multiple-locations breakpoints could be placed.  */
4226
4227 static void
4228 minsym_found (struct linespec_state *self, struct objfile *objfile,
4229               struct minimal_symbol *msymbol,
4230               std::vector<symtab_and_line> *result)
4231 {
4232   bool want_start_sal;
4233
4234   CORE_ADDR func_addr;
4235   bool is_function = msymbol_is_function (objfile, msymbol, &func_addr);
4236
4237   if (is_function)
4238     {
4239       const char *msym_name = MSYMBOL_LINKAGE_NAME (msymbol);
4240
4241       if (MSYMBOL_TYPE (msymbol) == mst_text_gnu_ifunc
4242           || MSYMBOL_TYPE (msymbol) == mst_data_gnu_ifunc)
4243         want_start_sal = gnu_ifunc_resolve_name (msym_name, &func_addr);
4244       else
4245         want_start_sal = true;
4246     }
4247
4248   symtab_and_line sal;
4249
4250   if (is_function && want_start_sal)
4251     sal = find_function_start_sal (func_addr, NULL, self->funfirstline);
4252   else
4253     {
4254       sal.objfile = objfile;
4255       sal.msymbol = msymbol;
4256       /* Store func_addr, not the minsym's address in case this was an
4257          ifunc that hasn't been resolved yet.  */
4258       if (is_function)
4259         sal.pc = func_addr;
4260       else
4261         sal.pc = MSYMBOL_VALUE_ADDRESS (objfile, msymbol);
4262       sal.pspace = current_program_space;
4263     }
4264
4265   sal.section = MSYMBOL_OBJ_SECTION (objfile, msymbol);
4266
4267   if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
4268     add_sal_to_sals (self, result, &sal, MSYMBOL_NATURAL_NAME (msymbol), 0);
4269 }
4270
4271 /* A helper function to classify a minimal_symbol_type according to
4272    priority.  */
4273
4274 static int
4275 classify_mtype (enum minimal_symbol_type t)
4276 {
4277   switch (t)
4278     {
4279     case mst_file_text:
4280     case mst_file_data:
4281     case mst_file_bss:
4282       /* Intermediate priority.  */
4283       return 1;
4284
4285     case mst_solib_trampoline:
4286       /* Lowest priority.  */
4287       return 2;
4288
4289     default:
4290       /* Highest priority.  */
4291       return 0;
4292     }
4293 }
4294
4295 /* Callback for std::sort that sorts symbols by priority.  */
4296
4297 static bool
4298 compare_msyms (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
4299 {
4300   enum minimal_symbol_type ta = MSYMBOL_TYPE (a.minsym);
4301   enum minimal_symbol_type tb = MSYMBOL_TYPE (b.minsym);
4302
4303   return classify_mtype (ta) < classify_mtype (tb);
4304 }
4305
4306 /* Helper for search_minsyms_for_name that adds the symbol to the
4307    result.  */
4308
4309 static void
4310 add_minsym (struct minimal_symbol *minsym, struct objfile *objfile,
4311             struct symtab *symtab, int list_mode,
4312             std::vector<struct bound_minimal_symbol> *msyms)
4313 {
4314   if (symtab != NULL)
4315     {
4316       /* We're looking for a label for which we don't have debug
4317          info.  */
4318       CORE_ADDR func_addr;
4319       if (msymbol_is_function (objfile, minsym, &func_addr))
4320         {
4321           symtab_and_line sal = find_pc_sect_line (func_addr, NULL, 0);
4322
4323           if (symtab != sal.symtab)
4324             return;
4325         }
4326     }
4327
4328   /* Exclude data symbols when looking for breakpoint locations.  */
4329   if (!list_mode && !msymbol_is_function (objfile, minsym))
4330     return;
4331
4332   struct bound_minimal_symbol mo = {minsym, objfile};
4333   msyms->push_back (mo);
4334   return;
4335 }
4336
4337 /* Search for minimal symbols called NAME.  If SEARCH_PSPACE
4338    is not NULL, the search is restricted to just that program
4339    space.
4340
4341    If SYMTAB is NULL, search all objfiles, otherwise
4342    restrict results to the given SYMTAB.  */
4343
4344 static void
4345 search_minsyms_for_name (struct collect_info *info,
4346                          const lookup_name_info &name,
4347                          struct program_space *search_pspace,
4348                          struct symtab *symtab)
4349 {
4350   std::vector<struct bound_minimal_symbol> minsyms;
4351
4352   if (symtab == NULL)
4353     {
4354       struct program_space *pspace;
4355
4356       ALL_PSPACES (pspace)
4357       {
4358         struct objfile *objfile;
4359
4360         if (search_pspace != NULL && search_pspace != pspace)
4361           continue;
4362         if (pspace->executing_startup)
4363           continue;
4364
4365         set_current_program_space (pspace);
4366
4367         ALL_OBJFILES (objfile)
4368         {
4369           iterate_over_minimal_symbols (objfile, name,
4370                                         [&] (struct minimal_symbol *msym)
4371                                           {
4372                                             add_minsym (msym, objfile, nullptr,
4373                                                         info->state->list_mode,
4374                                                         &minsyms);
4375                                             return false;
4376                                           });
4377         }
4378       }
4379     }
4380   else
4381     {
4382       if (search_pspace == NULL || SYMTAB_PSPACE (symtab) == search_pspace)
4383         {
4384           set_current_program_space (SYMTAB_PSPACE (symtab));
4385           iterate_over_minimal_symbols
4386             (SYMTAB_OBJFILE (symtab), name,
4387              [&] (struct minimal_symbol *msym)
4388                {
4389                  add_minsym (msym, SYMTAB_OBJFILE (symtab), symtab,
4390                              info->state->list_mode, &minsyms);
4391                  return false;
4392                });
4393         }
4394     }
4395
4396   if (!minsyms.empty ())
4397     {
4398       int classification;
4399
4400       std::sort (minsyms.begin (), minsyms.end (), compare_msyms);
4401
4402       /* Now the minsyms are in classification order.  So, we walk
4403          over them and process just the minsyms with the same
4404          classification as the very first minsym in the list.  */
4405       classification = classify_mtype (MSYMBOL_TYPE (minsyms[0].minsym));
4406
4407       for (const bound_minimal_symbol &item : minsyms)
4408         {
4409           if (classify_mtype (MSYMBOL_TYPE (item.minsym)) != classification)
4410             break;
4411
4412           info->result.minimal_symbols->push_back (item);
4413         }
4414     }
4415 }
4416
4417 /* A helper function to add all symbols matching NAME to INFO.  If
4418    PSPACE is not NULL, the search is restricted to just that program
4419    space.  */
4420
4421 static void
4422 add_matching_symbols_to_info (const char *name,
4423                               symbol_name_match_type name_match_type,
4424                               enum search_domain search_domain,
4425                               struct collect_info *info,
4426                               struct program_space *pspace)
4427 {
4428   lookup_name_info lookup_name (name, name_match_type);
4429
4430   for (const auto &elt : *info->file_symtabs)
4431     {
4432       if (elt == nullptr)
4433         {
4434           iterate_over_all_matching_symtabs (info->state, lookup_name,
4435                                              VAR_DOMAIN, search_domain,
4436                                              pspace, true,
4437                                              [&] (block_symbol *bsym)
4438             { return info->add_symbol (bsym); });
4439           search_minsyms_for_name (info, lookup_name, pspace, NULL);
4440         }
4441       else if (pspace == NULL || pspace == SYMTAB_PSPACE (elt))
4442         {
4443           int prev_len = info->result.symbols->size ();
4444
4445           /* Program spaces that are executing startup should have
4446              been filtered out earlier.  */
4447           gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
4448           set_current_program_space (SYMTAB_PSPACE (elt));
4449           iterate_over_file_blocks (elt, lookup_name, VAR_DOMAIN,
4450                                     [&] (block_symbol *bsym)
4451             { return info->add_symbol (bsym); });
4452
4453           /* If no new symbols were found in this iteration and this symtab
4454              is in assembler, we might actually be looking for a label for
4455              which we don't have debug info.  Check for a minimal symbol in
4456              this case.  */
4457           if (prev_len == info->result.symbols->size ()
4458               && elt->language == language_asm)
4459             search_minsyms_for_name (info, lookup_name, pspace, elt);
4460         }
4461     }
4462 }
4463
4464 \f
4465
4466 /* Now come some functions that are called from multiple places within
4467    decode_line_1.  */
4468
4469 static int
4470 symbol_to_sal (struct symtab_and_line *result,
4471                int funfirstline, struct symbol *sym)
4472 {
4473   if (SYMBOL_CLASS (sym) == LOC_BLOCK)
4474     {
4475       *result = find_function_start_sal (sym, funfirstline);
4476       return 1;
4477     }
4478   else
4479     {
4480       if (SYMBOL_CLASS (sym) == LOC_LABEL && SYMBOL_VALUE_ADDRESS (sym) != 0)
4481         {
4482           *result = {};
4483           result->symtab = symbol_symtab (sym);
4484           result->symbol = sym;
4485           result->line = SYMBOL_LINE (sym);
4486           result->pc = SYMBOL_VALUE_ADDRESS (sym);
4487           result->pspace = SYMTAB_PSPACE (result->symtab);
4488           result->explicit_pc = 1;
4489           return 1;
4490         }
4491       else if (funfirstline)
4492         {
4493           /* Nothing.  */
4494         }
4495       else if (SYMBOL_LINE (sym) != 0)
4496         {
4497           /* We know its line number.  */
4498           *result = {};
4499           result->symtab = symbol_symtab (sym);
4500           result->symbol = sym;
4501           result->line = SYMBOL_LINE (sym);
4502           result->pc = SYMBOL_VALUE_ADDRESS (sym);
4503           result->pspace = SYMTAB_PSPACE (result->symtab);
4504           return 1;
4505         }
4506     }
4507
4508   return 0;
4509 }
4510
4511 linespec_result::~linespec_result ()
4512 {
4513   for (linespec_sals &lsal : lsals)
4514     xfree (lsal.canonical);
4515 }
4516
4517 /* Return the quote characters permitted by the linespec parser.  */
4518
4519 const char *
4520 get_gdb_linespec_parser_quote_characters (void)
4521 {
4522   return linespec_quote_characters;
4523 }