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