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