Regenerate AArch64 opcodes files
[binutils-gdb.git] / gdb / linespec.c
blobb5bbd8c433c91a9c76a98c7ed776e95c52f72fd5
1 /* Parser for linespec for the GNU debugger, GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "defs.h"
21 #include "symtab.h"
22 #include "frame.h"
23 #include "command.h"
24 #include "symfile.h"
25 #include "objfiles.h"
26 #include "source.h"
27 #include "demangle.h"
28 #include "value.h"
29 #include "completer.h"
30 #include "cp-abi.h"
31 #include "cp-support.h"
32 #include "parser-defs.h"
33 #include "block.h"
34 #include "objc-lang.h"
35 #include "linespec.h"
36 #include "language.h"
37 #include "interps.h"
38 #include "mi/mi-cmds.h"
39 #include "target.h"
40 #include "arch-utils.h"
41 #include <ctype.h>
42 #include "cli/cli-utils.h"
43 #include "filenames.h"
44 #include "ada-lang.h"
45 #include "stack.h"
46 #include "location.h"
47 #include "gdbsupport/function-view.h"
48 #include "gdbsupport/def-vector.h"
49 #include <algorithm>
50 #include "inferior.h"
52 /* An enumeration of the various things a user might attempt to
53 complete for a linespec location. */
55 enum class linespec_complete_what
57 /* Nothing, no possible completion. */
58 NOTHING,
60 /* A function/method name. Due to ambiguity between
62 (gdb) b source[TAB]
63 source_file.c
64 source_function
66 this can also indicate a source filename, iff we haven't seen a
67 separate source filename component, as in "b source.c:function". */
68 FUNCTION,
70 /* A label symbol. E.g., break file.c:function:LABEL. */
71 LABEL,
73 /* An expression. E.g., "break foo if EXPR", or "break *EXPR". */
74 EXPRESSION,
76 /* A linespec keyword ("if"/"thread"/"task"/"-force-condition").
77 E.g., "break func threa<tab>". */
78 KEYWORD,
81 /* An address entry is used to ensure that any given location is only
82 added to the result a single time. It holds an address and the
83 program space from which the address came. */
85 struct address_entry
87 struct program_space *pspace;
88 CORE_ADDR addr;
91 /* A linespec. Elements of this structure are filled in by a parser
92 (either parse_linespec or some other function). The structure is
93 then converted into SALs by convert_linespec_to_sals. */
95 struct linespec
97 /* An explicit location spec describing the SaLs. */
98 explicit_location_spec explicit_loc;
100 /* The list of symtabs to search to which to limit the search.
102 If explicit.SOURCE_FILENAME is NULL (no user-specified filename),
103 FILE_SYMTABS should contain one single NULL member. This will cause the
104 code to use the default symtab. */
105 std::vector<symtab *> file_symtabs;
107 /* A list of matching function symbols and minimal symbols. Both lists
108 may be empty if no matching symbols were found. */
109 std::vector<block_symbol> function_symbols;
110 std::vector<bound_minimal_symbol> minimal_symbols;
112 /* A structure of matching label symbols and the corresponding
113 function symbol in which the label was found. Both may be empty
114 or both must be non-empty. */
115 struct
117 std::vector<block_symbol> label_symbols;
118 std::vector<block_symbol> function_symbols;
119 } labels;
122 /* A canonical linespec represented as a symtab-related string.
124 Each entry represents the "SYMTAB:SUFFIX" linespec string.
125 SYMTAB can be converted for example by symtab_to_fullname or
126 symtab_to_filename_for_display as needed. */
128 struct linespec_canonical_name
130 /* Remaining text part of the linespec string. */
131 char *suffix;
133 /* If NULL then SUFFIX is the whole linespec string. */
134 struct symtab *symtab;
137 /* An instance of this is used to keep all state while linespec
138 operates. This instance is passed around as a 'this' pointer to
139 the various implementation methods. */
141 struct linespec_state
143 /* The language in use during linespec processing. */
144 const struct language_defn *language;
146 /* The program space as seen when the module was entered. */
147 struct program_space *program_space;
149 /* If not NULL, the search is restricted to just this program
150 space. */
151 struct program_space *search_pspace;
153 /* The default symtab to use, if no other symtab is specified. */
154 struct symtab *default_symtab;
156 /* The default line to use. */
157 int default_line;
159 /* The 'funfirstline' value that was passed in to decode_line_1 or
160 decode_line_full. */
161 int funfirstline;
163 /* Nonzero if we are running in 'list' mode; see decode_line_list. */
164 int list_mode;
166 /* The 'canonical' value passed to decode_line_full, or NULL. */
167 struct linespec_result *canonical;
169 /* Canonical strings that mirror the std::vector<symtab_and_line> result. */
170 struct linespec_canonical_name *canonical_names;
172 /* This is a set of address_entry objects which is used to prevent
173 duplicate symbols from being entered into the result. */
174 htab_t addr_set;
176 /* Are we building a linespec? */
177 int is_linespec;
180 /* This is a helper object that is used when collecting symbols into a
181 result. */
183 struct collect_info
185 /* The linespec object in use. */
186 struct linespec_state *state;
188 /* A list of symtabs to which to restrict matches. */
189 const std::vector<symtab *> *file_symtabs;
191 /* The result being accumulated. */
192 struct
194 std::vector<block_symbol> *symbols;
195 std::vector<bound_minimal_symbol> *minimal_symbols;
196 } result;
198 /* Possibly add a symbol to the results. */
199 virtual bool add_symbol (block_symbol *bsym);
202 bool
203 collect_info::add_symbol (block_symbol *bsym)
205 /* In list mode, add all matching symbols, regardless of class.
206 This allows the user to type "list a_global_variable". */
207 if (bsym->symbol->aclass () == LOC_BLOCK || this->state->list_mode)
208 this->result.symbols->push_back (*bsym);
210 /* Continue iterating. */
211 return true;
214 /* Custom collect_info for symbol_searcher. */
216 struct symbol_searcher_collect_info
217 : collect_info
219 bool add_symbol (block_symbol *bsym) override
221 /* Add everything. */
222 this->result.symbols->push_back (*bsym);
224 /* Continue iterating. */
225 return true;
229 /* Token types */
231 enum linespec_token_type
233 /* A keyword */
234 LSTOKEN_KEYWORD = 0,
236 /* A colon "separator" */
237 LSTOKEN_COLON,
239 /* A string */
240 LSTOKEN_STRING,
242 /* A number */
243 LSTOKEN_NUMBER,
245 /* A comma */
246 LSTOKEN_COMMA,
248 /* EOI (end of input) */
249 LSTOKEN_EOI,
251 /* Consumed token */
252 LSTOKEN_CONSUMED
255 /* List of keywords. This is NULL-terminated so that it can be used
256 as enum completer. */
257 const char * const linespec_keywords[] = { "if", "thread", "task", "inferior", "-force-condition", NULL };
258 #define IF_KEYWORD_INDEX 0
259 #define FORCE_KEYWORD_INDEX 4
261 /* A token of the linespec lexer */
263 struct linespec_token
265 /* The type of the token */
266 linespec_token_type type;
268 /* Data for the token */
269 union
271 /* A string, given as a stoken */
272 struct stoken string;
274 /* A keyword */
275 const char *keyword;
276 } data;
279 #define LS_TOKEN_STOKEN(TOK) (TOK).data.string
280 #define LS_TOKEN_KEYWORD(TOK) (TOK).data.keyword
282 /* An instance of the linespec parser. */
284 struct linespec_parser
286 linespec_parser (int flags, const struct language_defn *language,
287 struct program_space *search_pspace,
288 struct symtab *default_symtab,
289 int default_line,
290 struct linespec_result *canonical);
292 ~linespec_parser ();
294 DISABLE_COPY_AND_ASSIGN (linespec_parser);
296 /* Lexer internal data */
297 struct
299 /* Save head of input stream. */
300 const char *saved_arg;
302 /* Head of the input stream. */
303 const char *stream;
304 #define PARSER_STREAM(P) ((P)->lexer.stream)
306 /* The current token. */
307 linespec_token current;
308 } lexer {};
310 /* Is the entire linespec quote-enclosed? */
311 int is_quote_enclosed = 0;
313 /* The state of the parse. */
314 struct linespec_state state {};
315 #define PARSER_STATE(PPTR) (&(PPTR)->state)
317 /* The result of the parse. */
318 linespec result;
319 #define PARSER_RESULT(PPTR) (&(PPTR)->result)
321 /* What the parser believes the current word point should complete
322 to. */
323 linespec_complete_what complete_what = linespec_complete_what::NOTHING;
325 /* The completion word point. The parser advances this as it skips
326 tokens. At some point the input string will end or parsing will
327 fail, and then we attempt completion at the captured completion
328 word point, interpreting the string at completion_word as
329 COMPLETE_WHAT. */
330 const char *completion_word = nullptr;
332 /* If the current token was a quoted string, then this is the
333 quoting character (either " or '). */
334 int completion_quote_char = 0;
336 /* If the current token was a quoted string, then this points at the
337 end of the quoted string. */
338 const char *completion_quote_end = nullptr;
340 /* If parsing for completion, then this points at the completion
341 tracker. Otherwise, this is NULL. */
342 struct completion_tracker *completion_tracker = nullptr;
345 /* A convenience macro for accessing the explicit location spec result
346 of the parser. */
347 #define PARSER_EXPLICIT(PPTR) (&PARSER_RESULT ((PPTR))->explicit_loc)
349 /* Prototypes for local functions. */
351 static void iterate_over_file_blocks
352 (struct symtab *symtab, const lookup_name_info &name,
353 domain_search_flags domain,
354 gdb::function_view<symbol_found_callback_ftype> callback);
356 static void initialize_defaults (struct symtab **default_symtab,
357 int *default_line);
359 CORE_ADDR linespec_expression_to_pc (const char **exp_ptr);
361 static std::vector<symtab_and_line> decode_objc (struct linespec_state *self,
362 linespec *ls,
363 const char *arg);
365 static std::vector<symtab *> symtabs_from_filename
366 (const char *, struct program_space *pspace);
368 static std::vector<block_symbol> find_label_symbols
369 (struct linespec_state *self,
370 const std::vector<block_symbol> &function_symbols,
371 std::vector<block_symbol> *label_funcs_ret,
372 const char *name, bool completion_mode = false);
374 static void find_linespec_symbols (struct linespec_state *self,
375 const std::vector<symtab *> &file_symtabs,
376 const char *name,
377 symbol_name_match_type name_match_type,
378 std::vector<block_symbol> *symbols,
379 std::vector<bound_minimal_symbol> *minsyms);
381 static struct line_offset
382 linespec_parse_variable (struct linespec_state *self,
383 const char *variable);
385 static int symbol_to_sal (struct symtab_and_line *result,
386 int funfirstline, struct symbol *sym);
388 static void add_matching_symbols_to_info (const char *name,
389 symbol_name_match_type name_match_type,
390 domain_search_flags domain_search_flags,
391 struct collect_info *info,
392 struct program_space *pspace);
394 static void add_all_symbol_names_from_pspace
395 (struct collect_info *info, struct program_space *pspace,
396 const std::vector<const char *> &names, domain_search_flags domain_search_flags);
398 static std::vector<symtab *>
399 collect_symtabs_from_filename (const char *file,
400 struct program_space *pspace);
402 static std::vector<symtab_and_line> decode_digits_ordinary
403 (struct linespec_state *self,
404 linespec *ls,
405 int line,
406 const linetable_entry **best_entry);
408 static std::vector<symtab_and_line> decode_digits_list_mode
409 (struct linespec_state *self,
410 linespec *ls,
411 struct symtab_and_line val);
413 static void minsym_found (struct linespec_state *self, struct objfile *objfile,
414 struct minimal_symbol *msymbol,
415 std::vector<symtab_and_line> *result);
417 static bool compare_symbols (const block_symbol &a, const block_symbol &b);
419 static bool compare_msymbols (const bound_minimal_symbol &a,
420 const bound_minimal_symbol &b);
422 /* Permitted quote characters for the parser. This is different from the
423 completer's quote characters to allow backward compatibility with the
424 previous parser. */
425 static const char linespec_quote_characters[] = "\"\'";
427 /* Lexer functions. */
429 /* Lex a number from the input in PARSER. This only supports
430 decimal numbers.
432 Return true if input is decimal numbers. Return false if not. */
434 static int
435 linespec_lexer_lex_number (linespec_parser *parser, linespec_token *tokenp)
437 tokenp->type = LSTOKEN_NUMBER;
438 LS_TOKEN_STOKEN (*tokenp).length = 0;
439 LS_TOKEN_STOKEN (*tokenp).ptr = PARSER_STREAM (parser);
441 /* Keep any sign at the start of the stream. */
442 if (*PARSER_STREAM (parser) == '+' || *PARSER_STREAM (parser) == '-')
444 ++LS_TOKEN_STOKEN (*tokenp).length;
445 ++(PARSER_STREAM (parser));
448 while (isdigit (*PARSER_STREAM (parser)))
450 ++LS_TOKEN_STOKEN (*tokenp).length;
451 ++(PARSER_STREAM (parser));
454 /* If the next character in the input buffer is not a space, comma,
455 quote, or colon, this input does not represent a number. */
456 if (*PARSER_STREAM (parser) != '\0'
457 && !isspace (*PARSER_STREAM (parser)) && *PARSER_STREAM (parser) != ','
458 && *PARSER_STREAM (parser) != ':'
459 && !strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
461 PARSER_STREAM (parser) = LS_TOKEN_STOKEN (*tokenp).ptr;
462 return 0;
465 return 1;
468 /* See linespec.h. */
470 const char *
471 linespec_lexer_lex_keyword (const char *p)
473 int i;
475 if (p != NULL)
477 for (i = 0; linespec_keywords[i] != NULL; ++i)
479 int len = strlen (linespec_keywords[i]);
481 /* If P begins with
483 - "thread" or "task" and the next character is
484 whitespace, we may have found a keyword. It is only a
485 keyword if it is not followed by another keyword.
487 - "-force-condition", the next character may be EOF
488 since this keyword does not take any arguments. Otherwise,
489 it should be followed by a keyword.
491 - "if", ALWAYS stop the lexer, since it is not possible to
492 predict what is going to appear in the condition, which can
493 only be parsed after SaLs have been found. */
494 if (strncmp (p, linespec_keywords[i], len) == 0)
496 int j;
498 if (i == FORCE_KEYWORD_INDEX && p[len] == '\0')
499 return linespec_keywords[i];
501 if (!isspace (p[len]))
502 continue;
504 if (i == FORCE_KEYWORD_INDEX)
506 p += len;
507 p = skip_spaces (p);
508 for (j = 0; linespec_keywords[j] != NULL; ++j)
510 int nextlen = strlen (linespec_keywords[j]);
512 if (strncmp (p, linespec_keywords[j], nextlen) == 0
513 && isspace (p[nextlen]))
514 return linespec_keywords[i];
517 else if (i != IF_KEYWORD_INDEX)
519 /* We matched a "thread" or "task". */
520 p += len;
521 p = skip_spaces (p);
522 for (j = 0; linespec_keywords[j] != NULL; ++j)
524 int nextlen = strlen (linespec_keywords[j]);
526 if (strncmp (p, linespec_keywords[j], nextlen) == 0
527 && isspace (p[nextlen]))
528 return NULL;
532 return linespec_keywords[i];
537 return NULL;
540 /* See description in linespec.h. */
543 is_ada_operator (const char *string)
545 const struct ada_opname_map *mapping;
547 for (mapping = ada_opname_table;
548 mapping->encoded != NULL
549 && !startswith (string, mapping->decoded); ++mapping)
552 return mapping->decoded == NULL ? 0 : strlen (mapping->decoded);
555 /* Find QUOTE_CHAR in STRING, accounting for the ':' terminal. Return
556 the location of QUOTE_CHAR, or NULL if not found. */
558 static const char *
559 skip_quote_char (const char *string, char quote_char)
561 const char *p, *last;
563 p = last = find_toplevel_char (string, quote_char);
564 while (p && *p != '\0' && *p != ':')
566 p = find_toplevel_char (p, quote_char);
567 if (p != NULL)
568 last = p++;
571 return last;
574 /* Make a writable copy of the string given in TOKEN, trimming
575 any trailing whitespace. */
577 static gdb::unique_xmalloc_ptr<char>
578 copy_token_string (linespec_token token)
580 const char *str, *s;
582 if (token.type == LSTOKEN_KEYWORD)
583 return make_unique_xstrdup (LS_TOKEN_KEYWORD (token));
585 str = LS_TOKEN_STOKEN (token).ptr;
586 s = remove_trailing_whitespace (str, str + LS_TOKEN_STOKEN (token).length);
588 return gdb::unique_xmalloc_ptr<char> (savestring (str, s - str));
591 /* Does P represent the end of a quote-enclosed linespec? */
593 static int
594 is_closing_quote_enclosed (const char *p)
596 if (strchr (linespec_quote_characters, *p))
597 ++p;
598 p = skip_spaces ((char *) p);
599 return (*p == '\0' || linespec_lexer_lex_keyword (p));
602 /* Find the end of the parameter list that starts with *INPUT.
603 This helper function assists with lexing string segments
604 which might contain valid (non-terminating) commas. */
606 static const char *
607 find_parameter_list_end (const char *input)
609 char end_char, start_char;
610 int depth;
611 const char *p;
613 start_char = *input;
614 if (start_char == '(')
615 end_char = ')';
616 else if (start_char == '<')
617 end_char = '>';
618 else
619 return NULL;
621 p = input;
622 depth = 0;
623 while (*p)
625 if (*p == start_char)
626 ++depth;
627 else if (*p == end_char)
629 if (--depth == 0)
631 ++p;
632 break;
635 ++p;
638 return p;
641 /* If the [STRING, STRING_LEN) string ends with what looks like a
642 keyword, return the keyword start offset in STRING. Return -1
643 otherwise. */
645 static size_t
646 string_find_incomplete_keyword_at_end (const char * const *keywords,
647 const char *string, size_t string_len)
649 const char *end = string + string_len;
650 const char *p = end;
652 while (p > string && *p != ' ')
653 --p;
654 if (p > string)
656 p++;
657 size_t len = end - p;
658 for (size_t i = 0; keywords[i] != NULL; ++i)
659 if (strncmp (keywords[i], p, len) == 0)
660 return p - string;
663 return -1;
666 /* Lex a string from the input in PARSER. */
668 static linespec_token
669 linespec_lexer_lex_string (linespec_parser *parser)
671 linespec_token token;
672 const char *start = PARSER_STREAM (parser);
674 token.type = LSTOKEN_STRING;
676 /* If the input stream starts with a quote character, skip to the next
677 quote character, regardless of the content. */
678 if (strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
680 const char *end;
681 char quote_char = *PARSER_STREAM (parser);
683 /* Special case: Ada operators. */
684 if (PARSER_STATE (parser)->language->la_language == language_ada
685 && quote_char == '\"')
687 int len = is_ada_operator (PARSER_STREAM (parser));
689 if (len != 0)
691 /* The input is an Ada operator. Return the quoted string
692 as-is. */
693 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
694 LS_TOKEN_STOKEN (token).length = len;
695 PARSER_STREAM (parser) += len;
696 return token;
699 /* The input does not represent an Ada operator -- fall through
700 to normal quoted string handling. */
703 /* Skip past the beginning quote. */
704 ++(PARSER_STREAM (parser));
706 /* Mark the start of the string. */
707 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
709 /* Skip to the ending quote. */
710 end = skip_quote_char (PARSER_STREAM (parser), quote_char);
712 /* This helps the completer mode decide whether we have a
713 complete string. */
714 parser->completion_quote_char = quote_char;
715 parser->completion_quote_end = end;
717 /* Error if the input did not terminate properly, unless in
718 completion mode. */
719 if (end == NULL)
721 if (parser->completion_tracker == NULL)
722 error (_("unmatched quote"));
724 /* In completion mode, we'll try to complete the incomplete
725 token. */
726 token.type = LSTOKEN_STRING;
727 while (*PARSER_STREAM (parser) != '\0')
728 PARSER_STREAM (parser)++;
729 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 1 - start;
731 else
733 /* Skip over the ending quote and mark the length of the string. */
734 PARSER_STREAM (parser) = (char *) ++end;
735 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 2 - start;
738 else
740 const char *p;
742 /* Otherwise, only identifier characters are permitted.
743 Spaces are the exception. In general, we keep spaces,
744 but only if the next characters in the input do not resolve
745 to one of the keywords.
747 This allows users to forgo quoting CV-qualifiers, template arguments,
748 and similar common language constructs. */
750 while (1)
752 if (isspace (*PARSER_STREAM (parser)))
754 p = skip_spaces (PARSER_STREAM (parser));
755 /* When we get here we know we've found something followed by
756 a space (we skip over parens and templates below).
757 So if we find a keyword now, we know it is a keyword and not,
758 say, a function name. */
759 if (linespec_lexer_lex_keyword (p) != NULL)
761 LS_TOKEN_STOKEN (token).ptr = start;
762 LS_TOKEN_STOKEN (token).length
763 = PARSER_STREAM (parser) - start;
764 return token;
767 /* Advance past the whitespace. */
768 PARSER_STREAM (parser) = p;
771 /* If the next character is EOI or (single) ':', the
772 string is complete; return the token. */
773 if (*PARSER_STREAM (parser) == 0)
775 LS_TOKEN_STOKEN (token).ptr = start;
776 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
777 return token;
779 else if (PARSER_STREAM (parser)[0] == ':')
781 /* Do not tokenize the C++ scope operator. */
782 if (PARSER_STREAM (parser)[1] == ':')
783 ++(PARSER_STREAM (parser));
785 /* Do not tokenize ABI tags such as "[abi:cxx11]". */
786 else if (PARSER_STREAM (parser) - start > 4
787 && startswith (PARSER_STREAM (parser) - 4, "[abi"))
789 /* Nothing. */
792 /* Do not tokenify if the input length so far is one
793 (i.e, a single-letter drive name) and the next character
794 is a directory separator. This allows Windows-style
795 paths to be recognized as filenames without quoting it. */
796 else if ((PARSER_STREAM (parser) - start) != 1
797 || !IS_DIR_SEPARATOR (PARSER_STREAM (parser)[1]))
799 LS_TOKEN_STOKEN (token).ptr = start;
800 LS_TOKEN_STOKEN (token).length
801 = PARSER_STREAM (parser) - start;
802 return token;
805 /* Special case: permit quote-enclosed linespecs. */
806 else if (parser->is_quote_enclosed
807 && strchr (linespec_quote_characters,
808 *PARSER_STREAM (parser))
809 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
811 LS_TOKEN_STOKEN (token).ptr = start;
812 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
813 return token;
815 /* Because commas may terminate a linespec and appear in
816 the middle of valid string input, special cases for
817 '<' and '(' are necessary. */
818 else if (*PARSER_STREAM (parser) == '<'
819 || *PARSER_STREAM (parser) == '(')
821 /* Don't interpret 'operator<' / 'operator<<' as a
822 template parameter list though. */
823 if (*PARSER_STREAM (parser) == '<'
824 && (PARSER_STATE (parser)->language->la_language
825 == language_cplus)
826 && (PARSER_STREAM (parser) - start) >= CP_OPERATOR_LEN)
828 const char *op = PARSER_STREAM (parser);
830 while (op > start && isspace (op[-1]))
831 op--;
832 if (op - start >= CP_OPERATOR_LEN)
834 op -= CP_OPERATOR_LEN;
835 if (strncmp (op, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
836 && (op == start
837 || !(isalnum (op[-1]) || op[-1] == '_')))
839 /* This is an operator name. Keep going. */
840 ++(PARSER_STREAM (parser));
841 if (*PARSER_STREAM (parser) == '<')
842 ++(PARSER_STREAM (parser));
843 continue;
848 const char *end = find_parameter_list_end (PARSER_STREAM (parser));
849 PARSER_STREAM (parser) = end;
851 /* Don't loop around to the normal \0 case above because
852 we don't want to misinterpret a potential keyword at
853 the end of the token when the string isn't
854 "()<>"-balanced. This handles "b
855 function(thread<tab>" in completion mode. */
856 if (*end == '\0')
858 LS_TOKEN_STOKEN (token).ptr = start;
859 LS_TOKEN_STOKEN (token).length
860 = PARSER_STREAM (parser) - start;
861 return token;
863 else
864 continue;
866 /* Commas are terminators, but not if they are part of an
867 operator name. */
868 else if (*PARSER_STREAM (parser) == ',')
870 if ((PARSER_STATE (parser)->language->la_language
871 == language_cplus)
872 && (PARSER_STREAM (parser) - start) > CP_OPERATOR_LEN)
874 const char *op = strstr (start, CP_OPERATOR_STR);
876 if (op != NULL && is_operator_name (op))
878 /* This is an operator name. Keep going. */
879 ++(PARSER_STREAM (parser));
880 continue;
884 /* Comma terminates the string. */
885 LS_TOKEN_STOKEN (token).ptr = start;
886 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
887 return token;
890 /* Advance the stream. */
891 gdb_assert (*(PARSER_STREAM (parser)) != '\0');
892 ++(PARSER_STREAM (parser));
896 return token;
899 /* Lex a single linespec token from PARSER. */
901 static linespec_token
902 linespec_lexer_lex_one (linespec_parser *parser)
904 const char *keyword;
906 if (parser->lexer.current.type == LSTOKEN_CONSUMED)
908 /* Skip any whitespace. */
909 PARSER_STREAM (parser) = skip_spaces (PARSER_STREAM (parser));
911 /* Check for a keyword, they end the linespec. */
912 keyword = linespec_lexer_lex_keyword (PARSER_STREAM (parser));
913 if (keyword != NULL)
915 parser->lexer.current.type = LSTOKEN_KEYWORD;
916 LS_TOKEN_KEYWORD (parser->lexer.current) = keyword;
917 /* We do not advance the stream here intentionally:
918 we would like lexing to stop when a keyword is seen.
920 PARSER_STREAM (parser) += strlen (keyword); */
922 return parser->lexer.current;
925 /* Handle other tokens. */
926 switch (*PARSER_STREAM (parser))
928 case 0:
929 parser->lexer.current.type = LSTOKEN_EOI;
930 break;
932 case '+': case '-':
933 case '0': case '1': case '2': case '3': case '4':
934 case '5': case '6': case '7': case '8': case '9':
935 if (!linespec_lexer_lex_number (parser, &(parser->lexer.current)))
936 parser->lexer.current = linespec_lexer_lex_string (parser);
937 break;
939 case ':':
940 /* If we have a scope operator, lex the input as a string.
941 Otherwise, return LSTOKEN_COLON. */
942 if (PARSER_STREAM (parser)[1] == ':')
943 parser->lexer.current = linespec_lexer_lex_string (parser);
944 else
946 parser->lexer.current.type = LSTOKEN_COLON;
947 ++(PARSER_STREAM (parser));
949 break;
951 case '\'': case '\"':
952 /* Special case: permit quote-enclosed linespecs. */
953 if (parser->is_quote_enclosed
954 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
956 ++(PARSER_STREAM (parser));
957 parser->lexer.current.type = LSTOKEN_EOI;
959 else
960 parser->lexer.current = linespec_lexer_lex_string (parser);
961 break;
963 case ',':
964 parser->lexer.current.type = LSTOKEN_COMMA;
965 LS_TOKEN_STOKEN (parser->lexer.current).ptr
966 = PARSER_STREAM (parser);
967 LS_TOKEN_STOKEN (parser->lexer.current).length = 1;
968 ++(PARSER_STREAM (parser));
969 break;
971 default:
972 /* If the input is not a number, it must be a string.
973 [Keywords were already considered above.] */
974 parser->lexer.current = linespec_lexer_lex_string (parser);
975 break;
979 return parser->lexer.current;
982 /* Consume the current token and return the next token in PARSER's
983 input stream. Also advance the completion word for completion
984 mode. */
986 static linespec_token
987 linespec_lexer_consume_token (linespec_parser *parser)
989 gdb_assert (parser->lexer.current.type != LSTOKEN_EOI);
991 bool advance_word = (parser->lexer.current.type != LSTOKEN_STRING
992 || *PARSER_STREAM (parser) != '\0');
994 /* If we're moving past a string to some other token, it must be the
995 quote was terminated. */
996 if (parser->completion_quote_char)
998 gdb_assert (parser->lexer.current.type == LSTOKEN_STRING);
1000 /* If the string was the last (non-EOI) token, we're past the
1001 quote, but remember that for later. */
1002 if (*PARSER_STREAM (parser) != '\0')
1004 parser->completion_quote_char = '\0';
1005 parser->completion_quote_end = NULL;;
1009 parser->lexer.current.type = LSTOKEN_CONSUMED;
1010 linespec_lexer_lex_one (parser);
1012 if (parser->lexer.current.type == LSTOKEN_STRING)
1014 /* Advance the completion word past a potential initial
1015 quote-char. */
1016 parser->completion_word = LS_TOKEN_STOKEN (parser->lexer.current).ptr;
1018 else if (advance_word)
1020 /* Advance the completion word past any whitespace. */
1021 parser->completion_word = PARSER_STREAM (parser);
1024 return parser->lexer.current;
1027 /* Return the next token without consuming the current token. */
1029 static linespec_token
1030 linespec_lexer_peek_token (linespec_parser *parser)
1032 linespec_token next;
1033 const char *saved_stream = PARSER_STREAM (parser);
1034 linespec_token saved_token = parser->lexer.current;
1035 int saved_completion_quote_char = parser->completion_quote_char;
1036 const char *saved_completion_quote_end = parser->completion_quote_end;
1037 const char *saved_completion_word = parser->completion_word;
1039 next = linespec_lexer_consume_token (parser);
1040 PARSER_STREAM (parser) = saved_stream;
1041 parser->lexer.current = saved_token;
1042 parser->completion_quote_char = saved_completion_quote_char;
1043 parser->completion_quote_end = saved_completion_quote_end;
1044 parser->completion_word = saved_completion_word;
1045 return next;
1048 /* Helper functions. */
1050 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
1051 the new sal, if needed. If not NULL, SYMNAME is the name of the
1052 symbol to use when constructing the new canonical name.
1054 If LITERAL_CANONICAL is non-zero, SYMNAME will be used as the
1055 canonical name for the SAL. */
1057 static void
1058 add_sal_to_sals (struct linespec_state *self,
1059 std::vector<symtab_and_line> *sals,
1060 struct symtab_and_line *sal,
1061 const char *symname, int literal_canonical)
1063 sals->push_back (*sal);
1065 if (self->canonical)
1067 struct linespec_canonical_name *canonical;
1069 self->canonical_names = XRESIZEVEC (struct linespec_canonical_name,
1070 self->canonical_names,
1071 sals->size ());
1072 canonical = &self->canonical_names[sals->size () - 1];
1073 if (!literal_canonical && sal->symtab)
1075 symtab_to_fullname (sal->symtab);
1077 /* Note that the filter doesn't have to be a valid linespec
1078 input. We only apply the ":LINE" treatment to Ada for
1079 the time being. */
1080 if (symname != NULL && sal->line != 0
1081 && self->language->la_language == language_ada)
1082 canonical->suffix = xstrprintf ("%s:%d", symname,
1083 sal->line).release ();
1084 else if (symname != NULL)
1085 canonical->suffix = xstrdup (symname);
1086 else
1087 canonical->suffix = xstrprintf ("%d", sal->line).release ();
1088 canonical->symtab = sal->symtab;
1090 else
1092 if (symname != NULL)
1093 canonical->suffix = xstrdup (symname);
1094 else
1095 canonical->suffix = xstrdup ("<unknown>");
1096 canonical->symtab = NULL;
1101 /* A hash function for address_entry. */
1103 static hashval_t
1104 hash_address_entry (const void *p)
1106 const struct address_entry *aep = (const struct address_entry *) p;
1107 hashval_t hash;
1109 hash = iterative_hash_object (aep->pspace, 0);
1110 return iterative_hash_object (aep->addr, hash);
1113 /* An equality function for address_entry. */
1115 static int
1116 eq_address_entry (const void *a, const void *b)
1118 const struct address_entry *aea = (const struct address_entry *) a;
1119 const struct address_entry *aeb = (const struct address_entry *) b;
1121 return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
1124 /* Check whether the address, represented by PSPACE and ADDR, is
1125 already in the set. If so, return 0. Otherwise, add it and return
1126 1. */
1128 static int
1129 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
1131 struct address_entry e, *p;
1132 void **slot;
1134 e.pspace = pspace;
1135 e.addr = addr;
1136 slot = htab_find_slot (set, &e, INSERT);
1137 if (*slot)
1138 return 0;
1140 p = XNEW (struct address_entry);
1141 memcpy (p, &e, sizeof (struct address_entry));
1142 *slot = p;
1144 return 1;
1147 /* A helper that walks over all matching symtabs in all objfiles and
1148 calls CALLBACK for each symbol matching NAME. If SEARCH_PSPACE is
1149 not NULL, then the search is restricted to just that program
1150 space. If INCLUDE_INLINE is true then symbols representing
1151 inlined instances of functions will be included in the result. */
1153 static void
1154 iterate_over_all_matching_symtabs
1155 (struct linespec_state *state,
1156 const lookup_name_info &lookup_name,
1157 const domain_search_flags domain,
1158 struct program_space *search_pspace, bool include_inline,
1159 gdb::function_view<symbol_found_callback_ftype> callback)
1161 for (struct program_space *pspace : program_spaces)
1163 if (search_pspace != NULL && search_pspace != pspace)
1164 continue;
1165 if (pspace->executing_startup)
1166 continue;
1168 set_current_program_space (pspace);
1170 for (objfile *objfile : current_program_space->objfiles ())
1172 objfile->expand_symtabs_matching (NULL, &lookup_name, NULL, NULL,
1173 (SEARCH_GLOBAL_BLOCK
1174 | SEARCH_STATIC_BLOCK),
1175 domain);
1177 for (compunit_symtab *cu : objfile->compunits ())
1179 struct symtab *symtab = cu->primary_filetab ();
1181 iterate_over_file_blocks (symtab, lookup_name, domain, callback);
1183 if (include_inline)
1185 const struct block *block;
1186 int i;
1187 const blockvector *bv = symtab->compunit ()->blockvector ();
1189 for (i = FIRST_LOCAL_BLOCK; i < bv->num_blocks (); i++)
1191 block = bv->block (i);
1192 state->language->iterate_over_symbols
1193 (block, lookup_name, domain,
1194 [&] (block_symbol *bsym)
1196 /* Restrict calls to CALLBACK to symbols
1197 representing inline symbols only. */
1198 if (bsym->symbol->is_inlined ())
1199 return callback (bsym);
1200 return true;
1209 /* Returns the block to be used for symbol searches from
1210 the current location. */
1212 static const struct block *
1213 get_current_search_block (void)
1215 /* get_selected_block can change the current language when there is
1216 no selected frame yet. */
1217 scoped_restore_current_language save_language;
1218 return get_selected_block (0);
1221 /* Iterate over static and global blocks. */
1223 static void
1224 iterate_over_file_blocks
1225 (struct symtab *symtab, const lookup_name_info &name,
1226 domain_search_flags domain,
1227 gdb::function_view<symbol_found_callback_ftype> callback)
1229 const struct block *block;
1231 for (block = symtab->compunit ()->blockvector ()->static_block ();
1232 block != NULL;
1233 block = block->superblock ())
1234 current_language->iterate_over_symbols (block, name, domain, callback);
1237 /* A helper for find_method. This finds all methods in type T of
1238 language T_LANG which match NAME. It adds matching symbol names to
1239 RESULT_NAMES, and adds T's direct superclasses to SUPERCLASSES. */
1241 static void
1242 find_methods (struct type *t, enum language t_lang, const char *name,
1243 std::vector<const char *> *result_names,
1244 std::vector<struct type *> *superclasses)
1246 int ibase;
1247 const char *class_name = t->name ();
1249 /* Ignore this class if it doesn't have a name. This is ugly, but
1250 unless we figure out how to get the physname without the name of
1251 the class, then the loop can't do any good. */
1252 if (class_name)
1254 int method_counter;
1255 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1256 symbol_name_matcher_ftype *symbol_name_compare
1257 = language_def (t_lang)->get_symbol_name_matcher (lookup_name);
1259 t = check_typedef (t);
1261 /* Loop over each method name. At this level, all overloads of a name
1262 are counted as a single name. There is an inner loop which loops over
1263 each overload. */
1265 for (method_counter = TYPE_NFN_FIELDS (t) - 1;
1266 method_counter >= 0;
1267 --method_counter)
1269 const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
1271 if (symbol_name_compare (method_name, lookup_name, NULL))
1273 int field_counter;
1275 for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
1276 - 1);
1277 field_counter >= 0;
1278 --field_counter)
1280 struct fn_field *f;
1281 const char *phys_name;
1283 f = TYPE_FN_FIELDLIST1 (t, method_counter);
1284 if (TYPE_FN_FIELD_STUB (f, field_counter))
1285 continue;
1286 phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
1287 result_names->push_back (phys_name);
1293 for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
1294 superclasses->push_back (TYPE_BASECLASS (t, ibase));
1297 /* The string equivalent of find_toplevel_char. Returns a pointer
1298 to the location of NEEDLE in HAYSTACK, ignoring any occurrences
1299 inside "()" and "<>". Returns NULL if NEEDLE was not found. */
1301 static const char *
1302 find_toplevel_string (const char *haystack, const char *needle)
1304 const char *s = haystack;
1308 s = find_toplevel_char (s, *needle);
1310 if (s != NULL)
1312 /* Found first char in HAYSTACK; check rest of string. */
1313 if (startswith (s, needle))
1314 return s;
1316 /* Didn't find it; loop over HAYSTACK, looking for the next
1317 instance of the first character of NEEDLE. */
1318 ++s;
1321 while (s != NULL && *s != '\0');
1323 /* NEEDLE was not found in HAYSTACK. */
1324 return NULL;
1327 /* Convert CANONICAL to its string representation using
1328 symtab_to_fullname for SYMTAB. */
1330 static std::string
1331 canonical_to_fullform (const struct linespec_canonical_name *canonical)
1333 if (canonical->symtab == NULL)
1334 return canonical->suffix;
1335 else
1336 return string_printf ("%s:%s", symtab_to_fullname (canonical->symtab),
1337 canonical->suffix);
1340 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
1341 and store the result in SELF->CANONICAL. */
1343 static void
1344 filter_results (struct linespec_state *self,
1345 std::vector<symtab_and_line> *result,
1346 const std::vector<const char *> &filters)
1348 for (const char *name : filters)
1350 linespec_sals lsal;
1352 for (size_t j = 0; j < result->size (); ++j)
1354 const struct linespec_canonical_name *canonical;
1356 canonical = &self->canonical_names[j];
1357 std::string fullform = canonical_to_fullform (canonical);
1359 if (name == fullform)
1360 lsal.sals.push_back ((*result)[j]);
1363 if (!lsal.sals.empty ())
1365 lsal.canonical = xstrdup (name);
1366 self->canonical->lsals.push_back (std::move (lsal));
1370 self->canonical->pre_expanded = 0;
1373 /* Store RESULT into SELF->CANONICAL. */
1375 static void
1376 convert_results_to_lsals (struct linespec_state *self,
1377 std::vector<symtab_and_line> *result)
1379 struct linespec_sals lsal;
1381 lsal.canonical = NULL;
1382 lsal.sals = std::move (*result);
1383 self->canonical->lsals.push_back (std::move (lsal));
1386 /* A structure that contains two string representations of a struct
1387 linespec_canonical_name:
1388 - one where the symtab's fullname is used;
1389 - one where the filename followed the "set filename-display"
1390 setting. */
1392 struct decode_line_2_item
1394 decode_line_2_item (std::string &&fullform_, std::string &&displayform_,
1395 bool selected_)
1396 : fullform (std::move (fullform_)),
1397 displayform (std::move (displayform_)),
1398 selected (selected_)
1402 /* The form using symtab_to_fullname. */
1403 std::string fullform;
1405 /* The form using symtab_to_filename_for_display. */
1406 std::string displayform;
1408 /* Field is initialized to zero and it is set to one if the user
1409 requested breakpoint for this entry. */
1410 unsigned int selected : 1;
1413 /* Helper for std::sort to sort decode_line_2_item entries by
1414 DISPLAYFORM and secondarily by FULLFORM. */
1416 static bool
1417 decode_line_2_compare_items (const decode_line_2_item &a,
1418 const decode_line_2_item &b)
1420 if (a.displayform != b.displayform)
1421 return a.displayform < b.displayform;
1422 return a.fullform < b.fullform;
1425 /* Handle multiple results in RESULT depending on SELECT_MODE. This
1426 will either return normally, throw an exception on multiple
1427 results, or present a menu to the user. On return, the SALS vector
1428 in SELF->CANONICAL is set up properly. */
1430 static void
1431 decode_line_2 (struct linespec_state *self,
1432 std::vector<symtab_and_line> *result,
1433 const char *select_mode)
1435 const char *args;
1436 const char *prompt;
1437 int i;
1438 std::vector<const char *> filters;
1439 std::vector<struct decode_line_2_item> items;
1441 gdb_assert (select_mode != multiple_symbols_all);
1442 gdb_assert (self->canonical != NULL);
1443 gdb_assert (!result->empty ());
1445 /* Prepare ITEMS array. */
1446 for (i = 0; i < result->size (); ++i)
1448 const struct linespec_canonical_name *canonical;
1449 std::string displayform;
1451 canonical = &self->canonical_names[i];
1452 gdb_assert (canonical->suffix != NULL);
1454 std::string fullform = canonical_to_fullform (canonical);
1456 if (canonical->symtab == NULL)
1457 displayform = canonical->suffix;
1458 else
1460 const char *fn_for_display;
1462 fn_for_display = symtab_to_filename_for_display (canonical->symtab);
1463 displayform = string_printf ("%s:%s", fn_for_display,
1464 canonical->suffix);
1467 items.emplace_back (std::move (fullform), std::move (displayform),
1468 false);
1471 /* Sort the list of method names. */
1472 std::sort (items.begin (), items.end (), decode_line_2_compare_items);
1474 /* Remove entries with the same FULLFORM. */
1475 items.erase (std::unique (items.begin (), items.end (),
1476 [] (const struct decode_line_2_item &a,
1477 const struct decode_line_2_item &b)
1479 return a.fullform == b.fullform;
1481 items.end ());
1483 if (select_mode == multiple_symbols_cancel && items.size () > 1)
1484 error (_("canceled because the command is ambiguous\n"
1485 "See set/show multiple-symbol."));
1487 if (select_mode == multiple_symbols_all || items.size () == 1)
1489 convert_results_to_lsals (self, result);
1490 return;
1493 printf_unfiltered (_("[0] cancel\n[1] all\n"));
1494 for (i = 0; i < items.size (); i++)
1495 printf_unfiltered ("[%d] %s\n", i + 2, items[i].displayform.c_str ());
1497 prompt = getenv ("PS2");
1498 if (prompt == NULL)
1500 prompt = "> ";
1503 std::string buffer;
1504 args = command_line_input (buffer, prompt, "overload-choice");
1506 if (args == 0 || *args == 0)
1507 error_no_arg (_("one or more choice numbers"));
1509 number_or_range_parser parser (args);
1510 while (!parser.finished ())
1512 int num = parser.get_number ();
1514 if (num == 0)
1515 error (_("canceled"));
1516 else if (num == 1)
1518 /* We intentionally make this result in a single breakpoint,
1519 contrary to what older versions of gdb did. The
1520 rationale is that this lets a user get the
1521 multiple_symbols_all behavior even with the 'ask'
1522 setting; and he can get separate breakpoints by entering
1523 "2-57" at the query. */
1524 convert_results_to_lsals (self, result);
1525 return;
1528 num -= 2;
1529 if (num >= items.size ())
1530 printf_unfiltered (_("No choice number %d.\n"), num);
1531 else
1533 struct decode_line_2_item *item = &items[num];
1535 if (!item->selected)
1537 filters.push_back (item->fullform.c_str ());
1538 item->selected = 1;
1540 else
1542 printf_unfiltered (_("duplicate request for %d ignored.\n"),
1543 num + 2);
1548 filter_results (self, result, filters);
1553 /* The parser of linespec itself. */
1555 /* Throw an appropriate error when SYMBOL is not found (optionally in
1556 FILENAME). */
1558 static void ATTRIBUTE_NORETURN
1559 symbol_not_found_error (const char *symbol, const char *filename)
1561 if (symbol == NULL)
1562 symbol = "";
1564 if (!have_full_symbols ()
1565 && !have_partial_symbols ()
1566 && !have_minimal_symbols ())
1567 throw_error (NOT_FOUND_ERROR,
1568 _("No symbol table is loaded. Use the \"file\" command."));
1570 /* If SYMBOL starts with '$', the user attempted to either lookup
1571 a function/variable in his code starting with '$' or an internal
1572 variable of that name. Since we do not know which, be concise and
1573 explain both possibilities. */
1574 if (*symbol == '$')
1576 if (filename)
1577 throw_error (NOT_FOUND_ERROR,
1578 _("Undefined convenience variable or function \"%s\" "
1579 "not defined in \"%s\"."), symbol, filename);
1580 else
1581 throw_error (NOT_FOUND_ERROR,
1582 _("Undefined convenience variable or function \"%s\" "
1583 "not defined."), symbol);
1585 else
1587 if (filename)
1588 throw_error (NOT_FOUND_ERROR,
1589 _("Function \"%s\" not defined in \"%s\"."),
1590 symbol, filename);
1591 else
1592 throw_error (NOT_FOUND_ERROR,
1593 _("Function \"%s\" not defined."), symbol);
1597 /* Throw an appropriate error when an unexpected token is encountered
1598 in the input. */
1600 static void ATTRIBUTE_NORETURN
1601 unexpected_linespec_error (linespec_parser *parser)
1603 linespec_token token;
1604 static const char * token_type_strings[]
1605 = {"keyword", "colon", "string", "number", "comma", "end of input"};
1607 /* Get the token that generated the error. */
1608 token = linespec_lexer_lex_one (parser);
1610 /* Finally, throw the error. */
1611 if (token.type == LSTOKEN_STRING || token.type == LSTOKEN_NUMBER
1612 || token.type == LSTOKEN_KEYWORD)
1614 gdb::unique_xmalloc_ptr<char> string = copy_token_string (token);
1615 throw_error (GENERIC_ERROR,
1616 _("malformed linespec error: unexpected %s, \"%s\""),
1617 token_type_strings[token.type], string.get ());
1619 else
1620 throw_error (GENERIC_ERROR,
1621 _("malformed linespec error: unexpected %s"),
1622 token_type_strings[token.type]);
1625 /* Throw an undefined label error. */
1627 static void ATTRIBUTE_NORETURN
1628 undefined_label_error (const char *function, const char *label)
1630 if (function != NULL)
1631 throw_error (NOT_FOUND_ERROR,
1632 _("No label \"%s\" defined in function \"%s\"."),
1633 label, function);
1634 else
1635 throw_error (NOT_FOUND_ERROR,
1636 _("No label \"%s\" defined in current function."),
1637 label);
1640 /* Throw a source file not found error. */
1642 static void ATTRIBUTE_NORETURN
1643 source_file_not_found_error (const char *name)
1645 throw_error (NOT_FOUND_ERROR, _("No source file named %s."), name);
1648 /* Unless at EIO, save the current stream position as completion word
1649 point, and consume the next token. */
1651 static linespec_token
1652 save_stream_and_consume_token (linespec_parser *parser)
1654 if (linespec_lexer_peek_token (parser).type != LSTOKEN_EOI)
1655 parser->completion_word = PARSER_STREAM (parser);
1656 return linespec_lexer_consume_token (parser);
1659 /* See description in linespec.h. */
1661 struct line_offset
1662 linespec_parse_line_offset (const char *string)
1664 const char *start = string;
1665 struct line_offset line_offset;
1667 if (*string == '+')
1669 line_offset.sign = LINE_OFFSET_PLUS;
1670 ++string;
1672 else if (*string == '-')
1674 line_offset.sign = LINE_OFFSET_MINUS;
1675 ++string;
1677 else
1678 line_offset.sign = LINE_OFFSET_NONE;
1680 if (*string != '\0' && !isdigit (*string))
1681 error (_("malformed line offset: \"%s\""), start);
1683 /* Right now, we only allow base 10 for offsets. */
1684 line_offset.offset = atoi (string);
1685 return line_offset;
1688 /* In completion mode, if the user is still typing the number, there's
1689 no possible completion to offer. But if there's already input past
1690 the number, setup to expect NEXT. */
1692 static void
1693 set_completion_after_number (linespec_parser *parser,
1694 linespec_complete_what next)
1696 if (*PARSER_STREAM (parser) == ' ')
1698 parser->completion_word = skip_spaces (PARSER_STREAM (parser) + 1);
1699 parser->complete_what = next;
1701 else
1703 parser->completion_word = PARSER_STREAM (parser);
1704 parser->complete_what = linespec_complete_what::NOTHING;
1708 /* Parse the basic_spec in PARSER's input. */
1710 static void
1711 linespec_parse_basic (linespec_parser *parser)
1713 gdb::unique_xmalloc_ptr<char> name;
1714 linespec_token token;
1716 /* Get the next token. */
1717 token = linespec_lexer_lex_one (parser);
1719 /* If it is EOI or KEYWORD, issue an error. */
1720 if (token.type == LSTOKEN_KEYWORD)
1722 parser->complete_what = linespec_complete_what::NOTHING;
1723 unexpected_linespec_error (parser);
1725 else if (token.type == LSTOKEN_EOI)
1727 unexpected_linespec_error (parser);
1729 /* If it is a LSTOKEN_NUMBER, we have an offset. */
1730 else if (token.type == LSTOKEN_NUMBER)
1732 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1734 /* Record the line offset and get the next token. */
1735 name = copy_token_string (token);
1736 PARSER_EXPLICIT (parser)->line_offset
1737 = linespec_parse_line_offset (name.get ());
1739 /* Get the next token. */
1740 token = linespec_lexer_consume_token (parser);
1742 /* If the next token is a comma, stop parsing and return. */
1743 if (token.type == LSTOKEN_COMMA)
1745 parser->complete_what = linespec_complete_what::NOTHING;
1746 return;
1749 /* If the next token is anything but EOI or KEYWORD, issue
1750 an error. */
1751 if (token.type != LSTOKEN_KEYWORD && token.type != LSTOKEN_EOI)
1752 unexpected_linespec_error (parser);
1755 if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1756 return;
1758 /* Next token must be LSTOKEN_STRING. */
1759 if (token.type != LSTOKEN_STRING)
1761 parser->complete_what = linespec_complete_what::NOTHING;
1762 unexpected_linespec_error (parser);
1765 /* The current token will contain the name of a function, method,
1766 or label. */
1767 name = copy_token_string (token);
1769 if (parser->completion_tracker != NULL)
1771 /* If the function name ends with a ":", then this may be an
1772 incomplete "::" scope operator instead of a label separator.
1773 E.g.,
1774 "b klass:<tab>"
1775 which should expand to:
1776 "b klass::method()"
1778 Do a tentative completion assuming the later. If we find
1779 completions, advance the stream past the colon token and make
1780 it part of the function name/token. */
1782 if (!parser->completion_quote_char
1783 && strcmp (PARSER_STREAM (parser), ":") == 0)
1785 completion_tracker tmp_tracker (false);
1786 const char *source_filename
1787 = PARSER_EXPLICIT (parser)->source_filename.get ();
1788 symbol_name_match_type match_type
1789 = PARSER_EXPLICIT (parser)->func_name_match_type;
1791 linespec_complete_function (tmp_tracker,
1792 parser->completion_word,
1793 match_type,
1794 source_filename);
1796 if (tmp_tracker.have_completions ())
1798 PARSER_STREAM (parser)++;
1799 LS_TOKEN_STOKEN (token).length++;
1801 name.reset (savestring (parser->completion_word,
1802 (PARSER_STREAM (parser)
1803 - parser->completion_word)));
1807 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1809 else
1811 std::vector<block_symbol> symbols;
1812 std::vector<bound_minimal_symbol> minimal_symbols;
1814 /* Try looking it up as a function/method. */
1815 find_linespec_symbols (PARSER_STATE (parser),
1816 PARSER_RESULT (parser)->file_symtabs, name.get (),
1817 PARSER_EXPLICIT (parser)->func_name_match_type,
1818 &symbols, &minimal_symbols);
1820 if (!symbols.empty () || !minimal_symbols.empty ())
1822 PARSER_RESULT (parser)->function_symbols = std::move (symbols);
1823 PARSER_RESULT (parser)->minimal_symbols = std::move (minimal_symbols);
1824 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1826 else
1828 /* NAME was not a function or a method. So it must be a label
1829 name or user specified variable like "break foo.c:$zippo". */
1830 std::vector<block_symbol> labels
1831 = find_label_symbols (PARSER_STATE (parser), {}, &symbols,
1832 name.get ());
1834 if (!labels.empty ())
1836 PARSER_RESULT (parser)->labels.label_symbols = std::move (labels);
1837 PARSER_RESULT (parser)->labels.function_symbols
1838 = std::move (symbols);
1839 PARSER_EXPLICIT (parser)->label_name = std::move (name);
1841 else if (token.type == LSTOKEN_STRING
1842 && *LS_TOKEN_STOKEN (token).ptr == '$')
1844 /* User specified a convenience variable or history value. */
1845 PARSER_EXPLICIT (parser)->line_offset
1846 = linespec_parse_variable (PARSER_STATE (parser), name.get ());
1848 if (PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN)
1850 /* The user-specified variable was not valid. Do not
1851 throw an error here. parse_linespec will do it for us. */
1852 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1853 return;
1856 else
1858 /* The name is also not a label. Abort parsing. Do not throw
1859 an error here. parse_linespec will do it for us. */
1861 /* Save a copy of the name we were trying to lookup. */
1862 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1863 return;
1868 int previous_qc = parser->completion_quote_char;
1870 /* Get the next token. */
1871 token = linespec_lexer_consume_token (parser);
1873 if (token.type == LSTOKEN_EOI)
1875 if (previous_qc && !parser->completion_quote_char)
1876 parser->complete_what = linespec_complete_what::KEYWORD;
1878 else if (token.type == LSTOKEN_COLON)
1880 /* User specified a label or a lineno. */
1881 token = linespec_lexer_consume_token (parser);
1883 if (token.type == LSTOKEN_NUMBER)
1885 /* User specified an offset. Record the line offset and
1886 get the next token. */
1887 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1889 name = copy_token_string (token);
1890 PARSER_EXPLICIT (parser)->line_offset
1891 = linespec_parse_line_offset (name.get ());
1893 /* Get the next token. */
1894 token = linespec_lexer_consume_token (parser);
1896 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
1898 parser->complete_what = linespec_complete_what::LABEL;
1900 else if (token.type == LSTOKEN_STRING)
1902 parser->complete_what = linespec_complete_what::LABEL;
1904 /* If we have text after the label separated by whitespace
1905 (e.g., "b func():lab i<tab>"), don't consider it part of
1906 the label. In completion mode that should complete to
1907 "if", in normal mode, the 'i' should be treated as
1908 garbage. */
1909 if (parser->completion_quote_char == '\0')
1911 const char *ptr = LS_TOKEN_STOKEN (token).ptr;
1912 for (size_t i = 0; i < LS_TOKEN_STOKEN (token).length; i++)
1914 if (ptr[i] == ' ')
1916 LS_TOKEN_STOKEN (token).length = i;
1917 PARSER_STREAM (parser) = skip_spaces (ptr + i + 1);
1918 break;
1923 if (parser->completion_tracker != NULL)
1925 if (PARSER_STREAM (parser)[-1] == ' ')
1927 parser->completion_word = PARSER_STREAM (parser);
1928 parser->complete_what = linespec_complete_what::KEYWORD;
1931 else
1933 std::vector<block_symbol> symbols;
1935 /* Grab a copy of the label's name and look it up. */
1936 name = copy_token_string (token);
1937 std::vector<block_symbol> labels
1938 = find_label_symbols (PARSER_STATE (parser),
1939 PARSER_RESULT (parser)->function_symbols,
1940 &symbols, name.get ());
1942 if (!labels.empty ())
1944 PARSER_RESULT (parser)->labels.label_symbols
1945 = std::move (labels);
1946 PARSER_RESULT (parser)->labels.function_symbols
1947 = std::move (symbols);
1948 PARSER_EXPLICIT (parser)->label_name = std::move (name);
1950 else
1952 /* We don't know what it was, but it isn't a label. */
1953 undefined_label_error
1954 (PARSER_EXPLICIT (parser)->function_name.get (),
1955 name.get ());
1960 /* Check for a line offset. */
1961 token = save_stream_and_consume_token (parser);
1962 if (token.type == LSTOKEN_COLON)
1964 /* Get the next token. */
1965 token = linespec_lexer_consume_token (parser);
1967 /* It must be a line offset. */
1968 if (token.type != LSTOKEN_NUMBER)
1969 unexpected_linespec_error (parser);
1971 /* Record the line offset and get the next token. */
1972 name = copy_token_string (token);
1974 PARSER_EXPLICIT (parser)->line_offset
1975 = linespec_parse_line_offset (name.get ());
1977 /* Get the next token. */
1978 token = linespec_lexer_consume_token (parser);
1981 else
1983 /* Trailing ':' in the input. Issue an error. */
1984 unexpected_linespec_error (parser);
1989 /* Canonicalize the linespec contained in LS. The result is saved into
1990 STATE->canonical. This function handles both linespec and explicit
1991 locations. */
1993 static void
1994 canonicalize_linespec (struct linespec_state *state, const linespec *ls)
1996 /* If canonicalization was not requested, no need to do anything. */
1997 if (!state->canonical)
1998 return;
2000 /* Save everything as an explicit location. */
2001 state->canonical->locspec = ls->explicit_loc.clone ();
2002 explicit_location_spec *explicit_loc
2003 = as_explicit_location_spec (state->canonical->locspec.get ());
2005 if (explicit_loc->label_name != NULL)
2007 state->canonical->special_display = 1;
2009 if (explicit_loc->function_name == NULL)
2011 /* No function was specified, so add the symbol name. */
2012 gdb_assert (ls->labels.function_symbols.size () == 1);
2013 block_symbol s = ls->labels.function_symbols.front ();
2014 explicit_loc->function_name
2015 = make_unique_xstrdup (s.symbol->natural_name ());
2019 /* If this location originally came from a linespec, save a string
2020 representation of it for display and saving to file. */
2021 if (state->is_linespec)
2022 explicit_loc->set_string (explicit_loc->to_linespec ());
2025 /* Given a line offset in LS, construct the relevant SALs. */
2027 static std::vector<symtab_and_line>
2028 create_sals_line_offset (struct linespec_state *self,
2029 linespec *ls)
2031 int use_default = 0;
2033 /* This is where we need to make sure we have good defaults.
2034 We must guarantee that this section of code is never executed
2035 when we are called with just a function name, since
2036 set_default_source_symtab_and_line uses
2037 select_source_symtab that calls us with such an argument. */
2039 if (ls->file_symtabs.size () == 1
2040 && ls->file_symtabs.front () == nullptr)
2042 set_current_program_space (self->program_space);
2044 /* Make sure we have at least a default source line. */
2045 set_default_source_symtab_and_line ();
2046 initialize_defaults (&self->default_symtab, &self->default_line);
2047 ls->file_symtabs
2048 = collect_symtabs_from_filename (self->default_symtab->filename,
2049 self->search_pspace);
2050 use_default = 1;
2053 symtab_and_line val;
2054 val.line = ls->explicit_loc.line_offset.offset;
2055 switch (ls->explicit_loc.line_offset.sign)
2057 case LINE_OFFSET_PLUS:
2058 if (ls->explicit_loc.line_offset.offset == 0)
2059 val.line = 5;
2060 if (use_default)
2061 val.line = self->default_line + val.line;
2062 break;
2064 case LINE_OFFSET_MINUS:
2065 if (ls->explicit_loc.line_offset.offset == 0)
2066 val.line = 15;
2067 if (use_default)
2068 val.line = self->default_line - val.line;
2069 else
2070 val.line = -val.line;
2071 break;
2073 case LINE_OFFSET_NONE:
2074 break; /* No need to adjust val.line. */
2077 std::vector<symtab_and_line> values;
2078 if (self->list_mode)
2079 values = decode_digits_list_mode (self, ls, val);
2080 else
2082 const linetable_entry *best_entry = NULL;
2083 int i, j;
2085 std::vector<symtab_and_line> intermediate_results
2086 = decode_digits_ordinary (self, ls, val.line, &best_entry);
2087 if (intermediate_results.empty () && best_entry != NULL)
2088 intermediate_results = decode_digits_ordinary (self, ls,
2089 best_entry->line,
2090 &best_entry);
2092 /* For optimized code, the compiler can scatter one source line
2093 across disjoint ranges of PC values, even when no duplicate
2094 functions or inline functions are involved. For example,
2095 'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
2096 function can result in two PC ranges. In this case, we don't
2097 want to set a breakpoint on the first PC of each range. To filter
2098 such cases, we use containing blocks -- for each PC found
2099 above, we see if there are other PCs that are in the same
2100 block. If yes, the other PCs are filtered out. */
2102 gdb::def_vector<int> filter (intermediate_results.size ());
2103 gdb::def_vector<const block *> blocks (intermediate_results.size ());
2105 for (i = 0; i < intermediate_results.size (); ++i)
2107 set_current_program_space (intermediate_results[i].pspace);
2109 filter[i] = 1;
2110 blocks[i] = block_for_pc_sect (intermediate_results[i].pc,
2111 intermediate_results[i].section);
2114 for (i = 0; i < intermediate_results.size (); ++i)
2116 if (blocks[i] != NULL)
2117 for (j = i + 1; j < intermediate_results.size (); ++j)
2119 if (blocks[j] == blocks[i])
2121 filter[j] = 0;
2122 break;
2127 for (i = 0; i < intermediate_results.size (); ++i)
2128 if (filter[i])
2130 struct symbol *sym = (blocks[i]
2131 ? blocks[i]->containing_function ()
2132 : NULL);
2134 if (self->funfirstline)
2135 skip_prologue_sal (&intermediate_results[i]);
2136 intermediate_results[i].symbol = sym;
2137 add_sal_to_sals (self, &values, &intermediate_results[i],
2138 sym ? sym->natural_name () : NULL, 0);
2142 if (values.empty ())
2144 if (ls->explicit_loc.source_filename)
2145 throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
2146 val.line, ls->explicit_loc.source_filename.get ());
2147 else
2148 throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
2149 val.line);
2152 return values;
2155 /* Convert the given ADDRESS into SaLs. */
2157 static std::vector<symtab_and_line>
2158 convert_address_location_to_sals (struct linespec_state *self,
2159 CORE_ADDR address)
2161 symtab_and_line sal = find_pc_line (address, 0);
2162 sal.pc = address;
2163 sal.section = find_pc_overlay (address);
2164 sal.explicit_pc = 1;
2165 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
2167 std::vector<symtab_and_line> sals;
2168 add_sal_to_sals (self, &sals, &sal, core_addr_to_string (address), 1);
2170 return sals;
2173 /* Create and return SALs from the linespec LS. */
2175 static std::vector<symtab_and_line>
2176 convert_linespec_to_sals (struct linespec_state *state, linespec *ls)
2178 std::vector<symtab_and_line> sals;
2180 if (!ls->labels.label_symbols.empty ())
2182 /* We have just a bunch of functions/methods or labels. */
2183 struct symtab_and_line sal;
2185 for (const auto &sym : ls->labels.label_symbols)
2187 struct program_space *pspace
2188 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace;
2190 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2191 && maybe_add_address (state->addr_set, pspace, sal.pc))
2192 add_sal_to_sals (state, &sals, &sal,
2193 sym.symbol->natural_name (), 0);
2196 else if (!ls->function_symbols.empty () || !ls->minimal_symbols.empty ())
2198 /* We have just a bunch of functions and/or methods. */
2199 if (!ls->function_symbols.empty ())
2201 /* Sort symbols so that symbols with the same program space are next
2202 to each other. */
2203 std::sort (ls->function_symbols.begin (),
2204 ls->function_symbols.end (),
2205 compare_symbols);
2207 for (const auto &sym : ls->function_symbols)
2209 program_space *pspace
2210 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace;
2211 set_current_program_space (pspace);
2213 /* Don't skip to the first line of the function if we
2214 had found an ifunc minimal symbol for this function,
2215 because that means that this function is an ifunc
2216 resolver with the same name as the ifunc itself. */
2217 bool found_ifunc = false;
2219 if (state->funfirstline
2220 && !ls->minimal_symbols.empty ()
2221 && sym.symbol->aclass () == LOC_BLOCK)
2223 const CORE_ADDR addr
2224 = sym.symbol->value_block ()->entry_pc ();
2226 for (const auto &elem : ls->minimal_symbols)
2228 if (elem.minsym->type () == mst_text_gnu_ifunc
2229 || elem.minsym->type () == mst_data_gnu_ifunc)
2231 CORE_ADDR msym_addr = elem.value_address ();
2232 if (elem.minsym->type () == mst_data_gnu_ifunc)
2234 struct gdbarch *gdbarch
2235 = elem.objfile->arch ();
2236 msym_addr
2237 = (gdbarch_convert_from_func_ptr_addr
2238 (gdbarch,
2239 msym_addr,
2240 current_inferior ()->top_target ()));
2243 if (msym_addr == addr)
2245 found_ifunc = true;
2246 break;
2252 if (!found_ifunc)
2254 symtab_and_line sal;
2255 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2256 && maybe_add_address (state->addr_set, pspace, sal.pc))
2257 add_sal_to_sals (state, &sals, &sal,
2258 sym.symbol->natural_name (), 0);
2263 if (!ls->minimal_symbols.empty ())
2265 /* Sort minimal symbols by program space, too */
2266 std::sort (ls->minimal_symbols.begin (),
2267 ls->minimal_symbols.end (),
2268 compare_msymbols);
2270 for (const auto &elem : ls->minimal_symbols)
2272 program_space *pspace = elem.objfile->pspace;
2273 set_current_program_space (pspace);
2274 minsym_found (state, elem.objfile, elem.minsym, &sals);
2278 else if (ls->explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2280 /* Only an offset was specified. */
2281 sals = create_sals_line_offset (state, ls);
2283 /* Make sure we have a filename for canonicalization. */
2284 if (ls->explicit_loc.source_filename == NULL)
2286 const char *filename = state->default_symtab->filename;
2288 /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2289 form so that displaying SOURCE_FILENAME can follow the current
2290 FILENAME_DISPLAY_STRING setting. But as it is used only rarely
2291 it has been kept for code simplicity only in absolute form. */
2292 ls->explicit_loc.source_filename = make_unique_xstrdup (filename);
2295 else
2297 /* We haven't found any results... */
2298 return sals;
2301 canonicalize_linespec (state, ls);
2303 if (!sals.empty () && state->canonical != NULL)
2304 state->canonical->pre_expanded = 1;
2306 return sals;
2309 /* Build RESULT from the explicit location spec components
2310 SOURCE_FILENAME, FUNCTION_NAME, LABEL_NAME and LINE_OFFSET. */
2312 static void
2313 convert_explicit_location_spec_to_linespec
2314 (struct linespec_state *self,
2315 linespec *result,
2316 const char *source_filename,
2317 const char *function_name,
2318 symbol_name_match_type fname_match_type,
2319 const char *label_name,
2320 struct line_offset line_offset)
2322 std::vector<bound_minimal_symbol> minimal_symbols;
2324 result->explicit_loc.func_name_match_type = fname_match_type;
2326 if (source_filename != NULL)
2330 result->file_symtabs
2331 = symtabs_from_filename (source_filename, self->search_pspace);
2333 catch (const gdb_exception_error &except)
2335 source_file_not_found_error (source_filename);
2337 result->explicit_loc.source_filename
2338 = make_unique_xstrdup (source_filename);
2340 else
2342 /* A NULL entry means to use the default symtab. */
2343 result->file_symtabs.push_back (nullptr);
2346 if (function_name != NULL)
2348 std::vector<block_symbol> symbols;
2350 find_linespec_symbols (self, result->file_symtabs,
2351 function_name, fname_match_type,
2352 &symbols, &minimal_symbols);
2354 if (symbols.empty () && minimal_symbols.empty ())
2355 symbol_not_found_error (function_name,
2356 result->explicit_loc.source_filename.get ());
2358 result->explicit_loc.function_name
2359 = make_unique_xstrdup (function_name);
2360 result->function_symbols = std::move (symbols);
2361 result->minimal_symbols = std::move (minimal_symbols);
2364 if (label_name != NULL)
2366 std::vector<block_symbol> symbols;
2367 std::vector<block_symbol> labels
2368 = find_label_symbols (self, result->function_symbols,
2369 &symbols, label_name);
2371 if (labels.empty ())
2372 undefined_label_error (result->explicit_loc.function_name.get (),
2373 label_name);
2375 result->explicit_loc.label_name = make_unique_xstrdup (label_name);
2376 result->labels.label_symbols = labels;
2377 result->labels.function_symbols = std::move (symbols);
2380 if (line_offset.sign != LINE_OFFSET_UNKNOWN)
2381 result->explicit_loc.line_offset = line_offset;
2384 /* Convert the explicit location EXPLICIT_LOC into SaLs. */
2386 static std::vector<symtab_and_line>
2387 convert_explicit_location_spec_to_sals
2388 (struct linespec_state *self,
2389 linespec *result,
2390 const explicit_location_spec *explicit_spec)
2392 convert_explicit_location_spec_to_linespec (self, result,
2393 explicit_spec->source_filename.get (),
2394 explicit_spec->function_name.get (),
2395 explicit_spec->func_name_match_type,
2396 explicit_spec->label_name.get (),
2397 explicit_spec->line_offset);
2398 return convert_linespec_to_sals (self, result);
2401 /* Parse a string that specifies a linespec.
2403 The basic grammar of linespecs:
2405 linespec -> var_spec | basic_spec
2406 var_spec -> '$' (STRING | NUMBER)
2408 basic_spec -> file_offset_spec | function_spec | label_spec
2409 file_offset_spec -> opt_file_spec offset_spec
2410 function_spec -> opt_file_spec function_name_spec opt_label_spec
2411 label_spec -> label_name_spec
2413 opt_file_spec -> "" | file_name_spec ':'
2414 opt_label_spec -> "" | ':' label_name_spec
2416 file_name_spec -> STRING
2417 function_name_spec -> STRING
2418 label_name_spec -> STRING
2419 function_name_spec -> STRING
2420 offset_spec -> NUMBER
2421 -> '+' NUMBER
2422 -> '-' NUMBER
2424 This may all be followed by several keywords such as "if EXPR",
2425 which we ignore.
2427 A comma will terminate parsing.
2429 The function may be an undebuggable function found in minimal symbol table.
2431 If the argument FUNFIRSTLINE is nonzero, we want the first line
2432 of real code inside a function when a function is specified, and it is
2433 not OK to specify a variable or type to get its line number.
2435 DEFAULT_SYMTAB specifies the file to use if none is specified.
2436 It defaults to current_source_symtab.
2437 DEFAULT_LINE specifies the line number to use for relative
2438 line numbers (that start with signs). Defaults to current_source_line.
2439 If CANONICAL is non-NULL, store an array of strings containing the canonical
2440 line specs there if necessary. Currently overloaded member functions and
2441 line numbers or static functions without a filename yield a canonical
2442 line spec. The array and the line spec strings are allocated on the heap,
2443 it is the callers responsibility to free them.
2445 Note that it is possible to return zero for the symtab
2446 if no file is validly specified. Callers must check that.
2447 Also, the line number returned may be invalid. */
2449 /* Parse the linespec in ARG, which must not be nullptr. MATCH_TYPE
2450 indicates how function names should be matched. */
2452 static std::vector<symtab_and_line>
2453 parse_linespec (linespec_parser *parser, const char *arg,
2454 symbol_name_match_type match_type)
2456 gdb_assert (arg != nullptr);
2458 struct gdb_exception file_exception;
2460 /* A special case to start. It has become quite popular for
2461 IDEs to work around bugs in the previous parser by quoting
2462 the entire linespec, so we attempt to deal with this nicely. */
2463 parser->is_quote_enclosed = 0;
2464 if (parser->completion_tracker == NULL
2465 && !is_ada_operator (arg)
2466 && *arg != '\0'
2467 && strchr (linespec_quote_characters, *arg) != NULL)
2469 const char *end = skip_quote_char (arg + 1, *arg);
2470 if (end != NULL && is_closing_quote_enclosed (end))
2472 /* Here's the special case. Skip ARG past the initial
2473 quote. */
2474 ++arg;
2475 parser->is_quote_enclosed = 1;
2479 parser->lexer.saved_arg = arg;
2480 parser->lexer.stream = arg;
2481 parser->completion_word = arg;
2482 parser->complete_what = linespec_complete_what::FUNCTION;
2483 PARSER_EXPLICIT (parser)->func_name_match_type = match_type;
2485 /* Initialize the default symtab and line offset. */
2486 initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2487 &PARSER_STATE (parser)->default_line);
2489 /* Objective-C shortcut. */
2490 if (parser->completion_tracker == NULL)
2492 std::vector<symtab_and_line> values
2493 = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), arg);
2494 if (!values.empty ())
2495 return values;
2497 else
2499 /* "-"/"+" is either an objc selector, or a number. There's
2500 nothing to complete the latter to, so just let the caller
2501 complete on functions, which finds objc selectors, if there's
2502 any. */
2503 if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '\0')
2504 return {};
2507 /* Start parsing. */
2509 /* Get the first token. */
2510 linespec_token token = linespec_lexer_consume_token (parser);
2512 /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER. */
2513 if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2515 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2516 if (parser->completion_tracker == NULL)
2517 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2519 /* User specified a convenience variable or history value. */
2520 gdb::unique_xmalloc_ptr<char> var = copy_token_string (token);
2521 PARSER_EXPLICIT (parser)->line_offset
2522 = linespec_parse_variable (PARSER_STATE (parser), var.get ());
2524 /* If a line_offset wasn't found (VAR is the name of a user
2525 variable/function), then skip to normal symbol processing. */
2526 if (PARSER_EXPLICIT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2528 /* Consume this token. */
2529 linespec_lexer_consume_token (parser);
2531 goto convert_to_sals;
2534 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
2536 /* Let the default linespec_complete_what::FUNCTION kick in. */
2537 unexpected_linespec_error (parser);
2539 else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2541 parser->complete_what = linespec_complete_what::NOTHING;
2542 unexpected_linespec_error (parser);
2545 /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2546 this token cannot represent a filename. */
2547 token = linespec_lexer_peek_token (parser);
2549 if (token.type == LSTOKEN_COLON)
2551 /* Get the current token again and extract the filename. */
2552 token = linespec_lexer_lex_one (parser);
2553 gdb::unique_xmalloc_ptr<char> user_filename = copy_token_string (token);
2555 /* Check if the input is a filename. */
2558 PARSER_RESULT (parser)->file_symtabs
2559 = symtabs_from_filename (user_filename.get (),
2560 PARSER_STATE (parser)->search_pspace);
2562 catch (gdb_exception_error &ex)
2564 file_exception = std::move (ex);
2567 if (file_exception.reason >= 0)
2569 /* Symtabs were found for the file. Record the filename. */
2570 PARSER_EXPLICIT (parser)->source_filename = std::move (user_filename);
2572 /* Get the next token. */
2573 token = linespec_lexer_consume_token (parser);
2575 /* This is LSTOKEN_COLON; consume it. */
2576 linespec_lexer_consume_token (parser);
2578 else
2580 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2581 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2584 /* If the next token is not EOI, KEYWORD, or COMMA, issue an error. */
2585 else if (parser->completion_tracker == NULL
2586 && (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2587 && token.type != LSTOKEN_COMMA))
2589 /* TOKEN is the _next_ token, not the one currently in the parser.
2590 Consuming the token will give the correct error message. */
2591 linespec_lexer_consume_token (parser);
2592 unexpected_linespec_error (parser);
2594 else
2596 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2597 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2600 /* Parse the rest of the linespec. */
2601 linespec_parse_basic (parser);
2603 if (parser->completion_tracker == NULL
2604 && PARSER_RESULT (parser)->function_symbols.empty ()
2605 && PARSER_RESULT (parser)->labels.label_symbols.empty ()
2606 && PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2607 && PARSER_RESULT (parser)->minimal_symbols.empty ())
2609 /* The linespec didn't parse. Re-throw the file exception if
2610 there was one. */
2611 if (file_exception.reason < 0)
2612 throw_exception (std::move (file_exception));
2614 /* Otherwise, the symbol is not found. */
2615 symbol_not_found_error
2616 (PARSER_EXPLICIT (parser)->function_name.get (),
2617 PARSER_EXPLICIT (parser)->source_filename.get ());
2620 convert_to_sals:
2622 /* Get the last token and record how much of the input was parsed,
2623 if necessary. */
2624 token = linespec_lexer_lex_one (parser);
2625 if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2626 unexpected_linespec_error (parser);
2627 else if (token.type == LSTOKEN_KEYWORD)
2629 /* Setup the completion word past the keyword. Lexing never
2630 advances past a keyword automatically, so skip it
2631 manually. */
2632 parser->completion_word
2633 = skip_spaces (skip_to_space (PARSER_STREAM (parser)));
2634 parser->complete_what = linespec_complete_what::EXPRESSION;
2637 /* Convert the data in PARSER_RESULT to SALs. */
2638 if (parser->completion_tracker == NULL)
2639 return convert_linespec_to_sals (PARSER_STATE (parser),
2640 PARSER_RESULT (parser));
2642 return {};
2646 /* A constructor for linespec_state. */
2648 static void
2649 linespec_state_constructor (struct linespec_state *self,
2650 int flags, const struct language_defn *language,
2651 struct program_space *search_pspace,
2652 struct symtab *default_symtab,
2653 int default_line,
2654 struct linespec_result *canonical)
2656 memset (self, 0, sizeof (*self));
2657 self->language = language;
2658 self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2659 self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2660 self->search_pspace = search_pspace;
2661 self->default_symtab = default_symtab;
2662 self->default_line = default_line;
2663 self->canonical = canonical;
2664 self->program_space = current_program_space;
2665 self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2666 xfree, xcalloc, xfree);
2667 self->is_linespec = 0;
2670 /* Initialize a new linespec parser. */
2672 linespec_parser::linespec_parser (int flags,
2673 const struct language_defn *language,
2674 struct program_space *search_pspace,
2675 struct symtab *default_symtab,
2676 int default_line,
2677 struct linespec_result *canonical)
2679 lexer.current.type = LSTOKEN_CONSUMED;
2680 PARSER_EXPLICIT (this)->func_name_match_type
2681 = symbol_name_match_type::WILD;
2682 PARSER_EXPLICIT (this)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2683 linespec_state_constructor (PARSER_STATE (this), flags, language,
2684 search_pspace,
2685 default_symtab, default_line, canonical);
2688 /* A destructor for linespec_state. */
2690 static void
2691 linespec_state_destructor (struct linespec_state *self)
2693 htab_delete (self->addr_set);
2694 xfree (self->canonical_names);
2697 /* Delete a linespec parser. */
2699 linespec_parser::~linespec_parser ()
2701 linespec_state_destructor (PARSER_STATE (this));
2704 /* See description in linespec.h. */
2706 void
2707 linespec_lex_to_end (const char **stringp)
2709 linespec_token token;
2710 const char *orig;
2712 if (stringp == NULL || *stringp == NULL)
2713 return;
2715 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2716 parser.lexer.saved_arg = *stringp;
2717 PARSER_STREAM (&parser) = orig = *stringp;
2721 /* Stop before any comma tokens; we need it to keep it
2722 as the next token in the string. */
2723 token = linespec_lexer_peek_token (&parser);
2724 if (token.type == LSTOKEN_COMMA)
2725 break;
2726 token = linespec_lexer_consume_token (&parser);
2728 while (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD);
2730 *stringp += PARSER_STREAM (&parser) - orig;
2733 /* See linespec.h. */
2735 void
2736 linespec_complete_function (completion_tracker &tracker,
2737 const char *function,
2738 symbol_name_match_type func_match_type,
2739 const char *source_filename)
2741 complete_symbol_mode mode = complete_symbol_mode::LINESPEC;
2743 if (source_filename != NULL)
2745 collect_file_symbol_completion_matches (tracker, mode, func_match_type,
2746 function, function, source_filename);
2748 else
2750 collect_symbol_completion_matches (tracker, mode, func_match_type,
2751 function, function);
2756 /* Helper for complete_linespec to simplify it. SOURCE_FILENAME is
2757 only meaningful if COMPONENT is FUNCTION. */
2759 static void
2760 complete_linespec_component (linespec_parser *parser,
2761 completion_tracker &tracker,
2762 const char *text,
2763 linespec_complete_what component,
2764 const char *source_filename)
2766 if (component == linespec_complete_what::KEYWORD)
2768 complete_on_enum (tracker, linespec_keywords, text, text);
2770 else if (component == linespec_complete_what::EXPRESSION)
2772 const char *word
2773 = advance_to_expression_complete_word_point (tracker, text);
2774 complete_expression (tracker, text, word);
2776 else if (component == linespec_complete_what::FUNCTION)
2778 completion_list fn_list;
2780 symbol_name_match_type match_type
2781 = PARSER_EXPLICIT (parser)->func_name_match_type;
2782 linespec_complete_function (tracker, text, match_type, source_filename);
2783 if (source_filename == NULL)
2785 /* Haven't seen a source component, like in "b
2786 file.c:function[TAB]". Maybe this wasn't a function, but
2787 a filename instead, like "b file.[TAB]". */
2788 fn_list = complete_source_filenames (text);
2791 /* If we only have a single filename completion, append a ':' for
2792 the user, since that's the only thing that can usefully follow
2793 the filename. */
2794 if (fn_list.size () == 1 && !tracker.have_completions ())
2796 char *fn = fn_list[0].release ();
2798 /* If we also need to append a quote char, it needs to be
2799 appended before the ':'. Append it now, and make ':' the
2800 new "quote" char. */
2801 if (tracker.quote_char ())
2803 char quote_char_str[2] = { (char) tracker.quote_char () };
2805 fn = reconcat (fn, fn, quote_char_str, (char *) NULL);
2806 tracker.set_quote_char (':');
2808 else
2809 fn = reconcat (fn, fn, ":", (char *) NULL);
2810 fn_list[0].reset (fn);
2812 /* Tell readline to skip appending a space. */
2813 tracker.set_suppress_append_ws (true);
2815 tracker.add_completions (std::move (fn_list));
2819 /* Helper for linespec_complete_label. Find labels that match
2820 LABEL_NAME in the function symbols listed in the PARSER, and add
2821 them to the tracker. */
2823 static void
2824 complete_label (completion_tracker &tracker,
2825 linespec_parser *parser,
2826 const char *label_name)
2828 std::vector<block_symbol> label_function_symbols;
2829 std::vector<block_symbol> labels
2830 = find_label_symbols (PARSER_STATE (parser),
2831 PARSER_RESULT (parser)->function_symbols,
2832 &label_function_symbols,
2833 label_name, true);
2835 for (const auto &label : labels)
2837 char *match = xstrdup (label.symbol->search_name ());
2838 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (match));
2842 /* See linespec.h. */
2844 void
2845 linespec_complete_label (completion_tracker &tracker,
2846 const struct language_defn *language,
2847 const char *source_filename,
2848 const char *function_name,
2849 symbol_name_match_type func_name_match_type,
2850 const char *label_name)
2852 linespec_parser parser (0, language, NULL, NULL, 0, NULL);
2854 line_offset unknown_offset;
2858 convert_explicit_location_spec_to_linespec (PARSER_STATE (&parser),
2859 PARSER_RESULT (&parser),
2860 source_filename,
2861 function_name,
2862 func_name_match_type,
2863 NULL, unknown_offset);
2865 catch (const gdb_exception_error &ex)
2867 return;
2870 complete_label (tracker, &parser, label_name);
2873 /* See description in linespec.h. */
2875 void
2876 linespec_complete (completion_tracker &tracker, const char *text,
2877 symbol_name_match_type match_type)
2879 const char *orig = text;
2881 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2882 parser.lexer.saved_arg = text;
2883 PARSER_EXPLICIT (&parser)->func_name_match_type = match_type;
2884 PARSER_STREAM (&parser) = text;
2886 parser.completion_tracker = &tracker;
2887 PARSER_STATE (&parser)->is_linespec = 1;
2889 /* Parse as much as possible. parser.completion_word will hold
2890 furthest completion point we managed to parse to. */
2893 parse_linespec (&parser, text, match_type);
2895 catch (const gdb_exception_error &except)
2899 if (parser.completion_quote_char != '\0'
2900 && parser.completion_quote_end != NULL
2901 && parser.completion_quote_end[1] == '\0')
2903 /* If completing a quoted string with the cursor right at
2904 terminating quote char, complete the completion word without
2905 interpretation, so that readline advances the cursor one
2906 whitespace past the quote, even if there's no match. This
2907 makes these cases behave the same:
2909 before: "b function()"
2910 after: "b function() "
2912 before: "b 'function()'"
2913 after: "b 'function()' "
2915 and trusts the user in this case:
2917 before: "b 'not_loaded_function_yet()'"
2918 after: "b 'not_loaded_function_yet()' "
2920 parser.complete_what = linespec_complete_what::NOTHING;
2921 parser.completion_quote_char = '\0';
2923 gdb::unique_xmalloc_ptr<char> text_copy
2924 (xstrdup (parser.completion_word));
2925 tracker.add_completion (std::move (text_copy));
2928 tracker.set_quote_char (parser.completion_quote_char);
2930 if (parser.complete_what == linespec_complete_what::LABEL)
2932 parser.complete_what = linespec_complete_what::NOTHING;
2934 const char *func_name = PARSER_EXPLICIT (&parser)->function_name.get ();
2936 std::vector<block_symbol> function_symbols;
2937 std::vector<bound_minimal_symbol> minimal_symbols;
2938 find_linespec_symbols (PARSER_STATE (&parser),
2939 PARSER_RESULT (&parser)->file_symtabs,
2940 func_name, match_type,
2941 &function_symbols, &minimal_symbols);
2943 PARSER_RESULT (&parser)->function_symbols = std::move (function_symbols);
2944 PARSER_RESULT (&parser)->minimal_symbols = std::move (minimal_symbols);
2946 complete_label (tracker, &parser, parser.completion_word);
2948 else if (parser.complete_what == linespec_complete_what::FUNCTION)
2950 /* While parsing/lexing, we didn't know whether the completion
2951 word completes to a unique function/source name already or
2952 not.
2954 E.g.:
2955 "b function() <tab>"
2956 may need to complete either to:
2957 "b function() const"
2958 or to:
2959 "b function() if/thread/task"
2961 Or, this:
2962 "b foo t"
2963 may need to complete either to:
2964 "b foo template_fun<T>()"
2965 with "foo" being the template function's return type, or to:
2966 "b foo thread/task"
2968 Or, this:
2969 "b file<TAB>"
2970 may need to complete either to a source file name:
2971 "b file.c"
2972 or this, also a filename, but a unique completion:
2973 "b file.c:"
2974 or to a function name:
2975 "b file_function"
2977 Address that by completing assuming source or function, and
2978 seeing if we find a completion that matches exactly the
2979 completion word. If so, then it must be a function (see note
2980 below) and we advance the completion word to the end of input
2981 and switch to KEYWORD completion mode.
2983 Note: if we find a unique completion for a source filename,
2984 then it won't match the completion word, because the LCD will
2985 contain a trailing ':'. And if we're completing at or after
2986 the ':', then complete_linespec_component won't try to
2987 complete on source filenames. */
2989 const char *word = parser.completion_word;
2991 complete_linespec_component
2992 (&parser, tracker,
2993 parser.completion_word,
2994 linespec_complete_what::FUNCTION,
2995 PARSER_EXPLICIT (&parser)->source_filename.get ());
2997 parser.complete_what = linespec_complete_what::NOTHING;
2999 if (tracker.quote_char ())
3001 /* The function/file name was not close-quoted, so this
3002 can't be a keyword. Note: complete_linespec_component
3003 may have swapped the original quote char for ':' when we
3004 get here, but that still indicates the same. */
3006 else if (!tracker.have_completions ())
3008 size_t key_start;
3009 size_t wordlen = strlen (parser.completion_word);
3011 key_start
3012 = string_find_incomplete_keyword_at_end (linespec_keywords,
3013 parser.completion_word,
3014 wordlen);
3016 if (key_start != -1
3017 || (wordlen > 0
3018 && parser.completion_word[wordlen - 1] == ' '))
3020 parser.completion_word += key_start;
3021 parser.complete_what = linespec_complete_what::KEYWORD;
3024 else if (tracker.completes_to_completion_word (word))
3026 /* Skip the function and complete on keywords. */
3027 parser.completion_word += strlen (word);
3028 parser.complete_what = linespec_complete_what::KEYWORD;
3029 tracker.discard_completions ();
3033 tracker.advance_custom_word_point_by (parser.completion_word - orig);
3035 complete_linespec_component
3036 (&parser, tracker,
3037 parser.completion_word,
3038 parser.complete_what,
3039 PARSER_EXPLICIT (&parser)->source_filename.get ());
3041 /* If we're past the "filename:function:label:offset" linespec, and
3042 didn't find any match, then assume the user might want to create
3043 a pending breakpoint anyway and offer the keyword
3044 completions. */
3045 if (!parser.completion_quote_char
3046 && (parser.complete_what == linespec_complete_what::FUNCTION
3047 || parser.complete_what == linespec_complete_what::LABEL
3048 || parser.complete_what == linespec_complete_what::NOTHING)
3049 && !tracker.have_completions ())
3051 const char *end
3052 = parser.completion_word + strlen (parser.completion_word);
3054 if (end > orig && end[-1] == ' ')
3056 tracker.advance_custom_word_point_by (end - parser.completion_word);
3058 complete_linespec_component (&parser, tracker, end,
3059 linespec_complete_what::KEYWORD,
3060 NULL);
3065 /* A helper function for decode_line_full and decode_line_1 to
3066 turn LOCSPEC into std::vector<symtab_and_line>. */
3068 static std::vector<symtab_and_line>
3069 location_spec_to_sals (linespec_parser *parser,
3070 const location_spec *locspec)
3072 std::vector<symtab_and_line> result;
3074 switch (locspec->type ())
3076 case LINESPEC_LOCATION_SPEC:
3078 const linespec_location_spec *ls = as_linespec_location_spec (locspec);
3079 PARSER_STATE (parser)->is_linespec = 1;
3080 result = parse_linespec (parser, ls->spec_string.get (),
3081 ls->match_type);
3083 break;
3085 case ADDRESS_LOCATION_SPEC:
3087 const address_location_spec *addr_spec
3088 = as_address_location_spec (locspec);
3089 const char *addr_string = addr_spec->to_string ();
3090 CORE_ADDR addr;
3092 if (addr_string != NULL)
3094 addr = linespec_expression_to_pc (&addr_string);
3095 if (PARSER_STATE (parser)->canonical != NULL)
3096 PARSER_STATE (parser)->canonical->locspec = locspec->clone ();
3098 else
3099 addr = addr_spec->address;
3101 result = convert_address_location_to_sals (PARSER_STATE (parser),
3102 addr);
3104 break;
3106 case EXPLICIT_LOCATION_SPEC:
3108 const explicit_location_spec *explicit_locspec
3109 = as_explicit_location_spec (locspec);
3110 result = convert_explicit_location_spec_to_sals (PARSER_STATE (parser),
3111 PARSER_RESULT (parser),
3112 explicit_locspec);
3114 break;
3116 case PROBE_LOCATION_SPEC:
3117 /* Probes are handled by their own decoders. */
3118 gdb_assert_not_reached ("attempt to decode probe location");
3119 break;
3121 default:
3122 gdb_assert_not_reached ("unhandled location spec type");
3125 return result;
3128 /* See linespec.h. */
3130 void
3131 decode_line_full (struct location_spec *locspec, int flags,
3132 struct program_space *search_pspace,
3133 struct symtab *default_symtab,
3134 int default_line, struct linespec_result *canonical,
3135 const char *select_mode,
3136 const char *filter)
3138 std::vector<const char *> filters;
3139 struct linespec_state *state;
3141 gdb_assert (canonical != NULL);
3142 /* The filter only makes sense for 'all'. */
3143 gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
3144 gdb_assert (select_mode == NULL
3145 || select_mode == multiple_symbols_all
3146 || select_mode == multiple_symbols_ask
3147 || select_mode == multiple_symbols_cancel);
3148 gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
3150 linespec_parser parser (flags, current_language,
3151 search_pspace, default_symtab,
3152 default_line, canonical);
3154 scoped_restore_current_program_space restore_pspace;
3156 std::vector<symtab_and_line> result = location_spec_to_sals (&parser,
3157 locspec);
3158 state = PARSER_STATE (&parser);
3160 if (result.size () == 0)
3161 throw_error (NOT_SUPPORTED_ERROR, _("Location %s not available"),
3162 locspec->to_string ());
3164 gdb_assert (result.size () == 1 || canonical->pre_expanded);
3165 canonical->pre_expanded = 1;
3167 /* Arrange for allocated canonical names to be freed. */
3168 std::vector<gdb::unique_xmalloc_ptr<char>> hold_names;
3169 for (int i = 0; i < result.size (); ++i)
3171 gdb_assert (state->canonical_names[i].suffix != NULL);
3172 hold_names.emplace_back (state->canonical_names[i].suffix);
3175 if (select_mode == NULL)
3177 if (top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
3178 select_mode = multiple_symbols_all;
3179 else
3180 select_mode = multiple_symbols_select_mode ();
3183 if (select_mode == multiple_symbols_all)
3185 if (filter != NULL)
3187 filters.push_back (filter);
3188 filter_results (state, &result, filters);
3190 else
3191 convert_results_to_lsals (state, &result);
3193 else
3194 decode_line_2 (state, &result, select_mode);
3197 /* See linespec.h. */
3199 std::vector<symtab_and_line>
3200 decode_line_1 (const location_spec *locspec, int flags,
3201 struct program_space *search_pspace,
3202 struct symtab *default_symtab,
3203 int default_line)
3205 linespec_parser parser (flags, current_language,
3206 search_pspace, default_symtab,
3207 default_line, NULL);
3209 scoped_restore_current_program_space restore_pspace;
3211 return location_spec_to_sals (&parser, locspec);
3214 /* See linespec.h. */
3216 std::vector<symtab_and_line>
3217 decode_line_with_current_source (const char *string, int flags)
3219 if (string == 0)
3220 error (_("Empty line specification."));
3222 /* We use whatever is set as the current source line. We do not try
3223 and get a default source symtab+line or it will recursively call us! */
3224 symtab_and_line cursal = get_current_source_symtab_and_line ();
3226 location_spec_up locspec = string_to_location_spec (&string,
3227 current_language);
3228 std::vector<symtab_and_line> sals
3229 = decode_line_1 (locspec.get (), flags, cursal.pspace, cursal.symtab,
3230 cursal.line);
3232 if (*string)
3233 error (_("Junk at end of line specification: %s"), string);
3235 return sals;
3238 /* See linespec.h. */
3240 std::vector<symtab_and_line>
3241 decode_line_with_last_displayed (const char *string, int flags)
3243 if (string == 0)
3244 error (_("Empty line specification."));
3246 location_spec_up locspec = string_to_location_spec (&string,
3247 current_language);
3248 std::vector<symtab_and_line> sals
3249 = (last_displayed_sal_is_valid ()
3250 ? decode_line_1 (locspec.get (), flags, NULL,
3251 get_last_displayed_symtab (),
3252 get_last_displayed_line ())
3253 : decode_line_1 (locspec.get (), flags, NULL, NULL, 0));
3255 if (*string)
3256 error (_("Junk at end of line specification: %s"), string);
3258 return sals;
3263 /* First, some functions to initialize stuff at the beginning of the
3264 function. */
3266 static void
3267 initialize_defaults (struct symtab **default_symtab, int *default_line)
3269 if (*default_symtab == 0)
3271 /* Use whatever we have for the default source line. We don't use
3272 get_current_or_default_symtab_and_line as it can recurse and call
3273 us back! */
3274 struct symtab_and_line cursal =
3275 get_current_source_symtab_and_line ();
3277 *default_symtab = cursal.symtab;
3278 *default_line = cursal.line;
3284 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
3285 advancing EXP_PTR past any parsed text. */
3287 CORE_ADDR
3288 linespec_expression_to_pc (const char **exp_ptr)
3290 if (current_program_space->executing_startup)
3291 /* The error message doesn't really matter, because this case
3292 should only hit during breakpoint reset. */
3293 throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
3294 "program space is in startup"));
3296 (*exp_ptr)++;
3297 return value_as_address (parse_to_comma_and_eval (exp_ptr));
3302 /* Here's where we recognise an Objective-C Selector. An Objective C
3303 selector may be implemented by more than one class, therefore it
3304 may represent more than one method/function. This gives us a
3305 situation somewhat analogous to C++ overloading. If there's more
3306 than one method that could represent the selector, then use some of
3307 the existing C++ code to let the user choose one. */
3309 static std::vector<symtab_and_line>
3310 decode_objc (struct linespec_state *self, linespec *ls, const char *arg)
3312 struct collect_info info;
3313 std::vector<const char *> symbol_names;
3314 const char *new_argptr;
3316 info.state = self;
3317 std::vector<symtab *> symtabs;
3318 symtabs.push_back (nullptr);
3320 info.file_symtabs = &symtabs;
3322 std::vector<block_symbol> symbols;
3323 info.result.symbols = &symbols;
3324 std::vector<bound_minimal_symbol> minimal_symbols;
3325 info.result.minimal_symbols = &minimal_symbols;
3327 new_argptr = find_imps (arg, &symbol_names);
3328 if (symbol_names.empty ())
3329 return {};
3331 add_all_symbol_names_from_pspace (&info, NULL, symbol_names,
3332 SEARCH_FUNCTION_DOMAIN);
3334 std::vector<symtab_and_line> values;
3335 if (!symbols.empty () || !minimal_symbols.empty ())
3337 char *saved_arg;
3339 saved_arg = (char *) alloca (new_argptr - arg + 1);
3340 memcpy (saved_arg, arg, new_argptr - arg);
3341 saved_arg[new_argptr - arg] = '\0';
3343 ls->explicit_loc.function_name = make_unique_xstrdup (saved_arg);
3344 ls->function_symbols = std::move (symbols);
3345 ls->minimal_symbols = std::move (minimal_symbols);
3346 values = convert_linespec_to_sals (self, ls);
3348 if (self->canonical)
3350 std::string holder;
3351 const char *str;
3353 self->canonical->pre_expanded = 1;
3355 if (ls->explicit_loc.source_filename)
3357 holder = string_printf ("%s:%s",
3358 ls->explicit_loc.source_filename.get (),
3359 saved_arg);
3360 str = holder.c_str ();
3362 else
3363 str = saved_arg;
3365 self->canonical->locspec
3366 = new_linespec_location_spec (&str, symbol_name_match_type::FULL);
3370 return values;
3373 namespace {
3375 /* A function object that serves as symbol_found_callback_ftype
3376 callback for iterate_over_symbols. This is used by
3377 lookup_prefix_sym to collect type symbols. */
3378 class decode_compound_collector
3380 public:
3381 decode_compound_collector ()
3382 : m_unique_syms (htab_create_alloc (1, htab_hash_pointer,
3383 htab_eq_pointer, NULL,
3384 xcalloc, xfree))
3388 /* Return all symbols collected. */
3389 std::vector<block_symbol> release_symbols ()
3391 return std::move (m_symbols);
3394 /* Callable as a symbol_found_callback_ftype callback. */
3395 bool operator () (block_symbol *bsym);
3397 private:
3398 /* A hash table of all symbols we found. We use this to avoid
3399 adding any symbol more than once. */
3400 htab_up m_unique_syms;
3402 /* The result vector. */
3403 std::vector<block_symbol> m_symbols;
3406 bool
3407 decode_compound_collector::operator () (block_symbol *bsym)
3409 void **slot;
3410 struct type *t;
3411 struct symbol *sym = bsym->symbol;
3413 if (sym->aclass () != LOC_TYPEDEF)
3414 return true; /* Continue iterating. */
3416 t = sym->type ();
3417 t = check_typedef (t);
3418 if (t->code () != TYPE_CODE_STRUCT
3419 && t->code () != TYPE_CODE_UNION
3420 && t->code () != TYPE_CODE_NAMESPACE)
3421 return true; /* Continue iterating. */
3423 slot = htab_find_slot (m_unique_syms.get (), sym, INSERT);
3424 if (!*slot)
3426 *slot = sym;
3427 m_symbols.push_back (*bsym);
3430 return true; /* Continue iterating. */
3433 } // namespace
3435 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS. */
3437 static std::vector<block_symbol>
3438 lookup_prefix_sym (struct linespec_state *state,
3439 const std::vector<symtab *> &file_symtabs,
3440 const char *class_name)
3442 decode_compound_collector collector;
3444 lookup_name_info lookup_name (class_name, symbol_name_match_type::FULL);
3446 for (const auto &elt : file_symtabs)
3448 if (elt == nullptr)
3449 iterate_over_all_matching_symtabs (state, lookup_name,
3450 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3451 NULL, false, collector);
3452 else
3454 /* Program spaces that are executing startup should have
3455 been filtered out earlier. */
3456 program_space *pspace = elt->compunit ()->objfile ()->pspace;
3458 gdb_assert (!pspace->executing_startup);
3459 set_current_program_space (pspace);
3460 iterate_over_file_blocks (elt, lookup_name,
3461 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3462 collector);
3466 return collector.release_symbols ();
3469 /* A std::sort comparison function for symbols. The resulting order does
3470 not actually matter; we just need to be able to sort them so that
3471 symbols with the same program space end up next to each other. */
3473 static bool
3474 compare_symbols (const block_symbol &a, const block_symbol &b)
3476 uintptr_t uia, uib;
3478 uia = (uintptr_t) a.symbol->symtab ()->compunit ()->objfile ()->pspace;
3479 uib = (uintptr_t) b.symbol->symtab ()->compunit ()->objfile ()->pspace;
3481 if (uia < uib)
3482 return true;
3483 if (uia > uib)
3484 return false;
3486 uia = (uintptr_t) a.symbol;
3487 uib = (uintptr_t) b.symbol;
3489 if (uia < uib)
3490 return true;
3492 return false;
3495 /* Like compare_symbols but for minimal symbols. */
3497 static bool
3498 compare_msymbols (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
3500 uintptr_t uia, uib;
3502 uia = (uintptr_t) a.objfile->pspace;
3503 uib = (uintptr_t) a.objfile->pspace;
3505 if (uia < uib)
3506 return true;
3507 if (uia > uib)
3508 return false;
3510 uia = (uintptr_t) a.minsym;
3511 uib = (uintptr_t) b.minsym;
3513 if (uia < uib)
3514 return true;
3516 return false;
3519 /* Look for all the matching instances of each symbol in NAMES. Only
3520 instances from PSPACE are considered; other program spaces are
3521 handled by our caller. If PSPACE is NULL, then all program spaces
3522 are considered. Results are stored into INFO. */
3524 static void
3525 add_all_symbol_names_from_pspace (struct collect_info *info,
3526 struct program_space *pspace,
3527 const std::vector<const char *> &names,
3528 domain_search_flags domain_search_flags)
3530 for (const char *iter : names)
3531 add_matching_symbols_to_info (iter,
3532 symbol_name_match_type::FULL,
3533 domain_search_flags, info, pspace);
3536 static void
3537 find_superclass_methods (std::vector<struct type *> &&superclasses,
3538 const char *name, enum language name_lang,
3539 std::vector<const char *> *result_names)
3541 size_t old_len = result_names->size ();
3543 while (1)
3545 std::vector<struct type *> new_supers;
3547 for (type *t : superclasses)
3548 find_methods (t, name_lang, name, result_names, &new_supers);
3550 if (result_names->size () != old_len || new_supers.empty ())
3551 break;
3553 superclasses = std::move (new_supers);
3557 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
3558 given by one of the symbols in SYM_CLASSES. Matches are returned
3559 in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols). */
3561 static void
3562 find_method (struct linespec_state *self,
3563 const std::vector<symtab *> &file_symtabs,
3564 const char *class_name, const char *method_name,
3565 std::vector<block_symbol> *sym_classes,
3566 std::vector<block_symbol> *symbols,
3567 std::vector<bound_minimal_symbol> *minsyms)
3569 size_t last_result_len;
3570 std::vector<struct type *> superclass_vec;
3571 std::vector<const char *> result_names;
3572 struct collect_info info;
3574 /* Sort symbols so that symbols with the same program space are next
3575 to each other. */
3576 std::sort (sym_classes->begin (), sym_classes->end (),
3577 compare_symbols);
3579 info.state = self;
3580 info.file_symtabs = &file_symtabs;
3581 info.result.symbols = symbols;
3582 info.result.minimal_symbols = minsyms;
3584 /* Iterate over all the types, looking for the names of existing
3585 methods matching METHOD_NAME. If we cannot find a direct method in a
3586 given program space, then we consider inherited methods; this is
3587 not ideal (ideal would be to respect C++ hiding rules), but it
3588 seems good enough and is what GDB has historically done. We only
3589 need to collect the names because later we find all symbols with
3590 those names. This loop is written in a somewhat funny way
3591 because we collect data across the program space before deciding
3592 what to do. */
3593 last_result_len = 0;
3594 for (const auto &elt : *sym_classes)
3596 struct type *t;
3597 struct program_space *pspace;
3598 struct symbol *sym = elt.symbol;
3599 unsigned int ix = &elt - &*sym_classes->begin ();
3601 /* Program spaces that are executing startup should have
3602 been filtered out earlier. */
3603 pspace = sym->symtab ()->compunit ()->objfile ()->pspace;
3604 gdb_assert (!pspace->executing_startup);
3605 set_current_program_space (pspace);
3606 t = check_typedef (sym->type ());
3607 find_methods (t, sym->language (),
3608 method_name, &result_names, &superclass_vec);
3610 /* Handle all items from a single program space at once; and be
3611 sure not to miss the last batch. */
3612 if (ix == sym_classes->size () - 1
3613 || (pspace
3614 != (sym_classes->at (ix + 1).symbol->symtab ()
3615 ->compunit ()->objfile ()->pspace)))
3617 /* If we did not find a direct implementation anywhere in
3618 this program space, consider superclasses. */
3619 if (result_names.size () == last_result_len)
3620 find_superclass_methods (std::move (superclass_vec), method_name,
3621 sym->language (), &result_names);
3623 /* We have a list of candidate symbol names, so now we
3624 iterate over the symbol tables looking for all
3625 matches in this pspace. */
3626 add_all_symbol_names_from_pspace (&info, pspace, result_names,
3627 SEARCH_FUNCTION_DOMAIN);
3629 superclass_vec.clear ();
3630 last_result_len = result_names.size ();
3634 if (!symbols->empty () || !minsyms->empty ())
3635 return;
3637 /* Throw an NOT_FOUND_ERROR. This will be caught by the caller
3638 and other attempts to locate the symbol will be made. */
3639 throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
3644 namespace {
3646 /* This function object is a callback for iterate_over_symtabs, used
3647 when collecting all matching symtabs. */
3649 class symtab_collector
3651 public:
3652 symtab_collector ()
3653 : m_symtab_table (htab_create (1, htab_hash_pointer, htab_eq_pointer,
3654 NULL))
3658 /* Callable as a symbol_found_callback_ftype callback. */
3659 bool operator () (symtab *sym);
3661 /* Return an rvalue reference to the collected symtabs. */
3662 std::vector<symtab *> &&release_symtabs ()
3664 return std::move (m_symtabs);
3667 private:
3668 /* The result vector of symtabs. */
3669 std::vector<symtab *> m_symtabs;
3671 /* This is used to ensure the symtabs are unique. */
3672 htab_up m_symtab_table;
3675 bool
3676 symtab_collector::operator () (struct symtab *symtab)
3678 void **slot;
3680 slot = htab_find_slot (m_symtab_table.get (), symtab, INSERT);
3681 if (!*slot)
3683 *slot = symtab;
3684 m_symtabs.push_back (symtab);
3687 return false;
3690 } // namespace
3692 /* Given a file name, return a list of all matching symtabs. If
3693 SEARCH_PSPACE is not NULL, the search is restricted to just that
3694 program space. */
3696 static std::vector<symtab *>
3697 collect_symtabs_from_filename (const char *file,
3698 struct program_space *search_pspace)
3700 symtab_collector collector;
3702 /* Find that file's data. */
3703 if (search_pspace == NULL)
3705 for (struct program_space *pspace : program_spaces)
3707 if (pspace->executing_startup)
3708 continue;
3710 set_current_program_space (pspace);
3711 iterate_over_symtabs (file, collector);
3714 else
3716 set_current_program_space (search_pspace);
3717 iterate_over_symtabs (file, collector);
3720 return collector.release_symtabs ();
3723 /* Return all the symtabs associated to the FILENAME. If SEARCH_PSPACE is
3724 not NULL, the search is restricted to just that program space. */
3726 static std::vector<symtab *>
3727 symtabs_from_filename (const char *filename,
3728 struct program_space *search_pspace)
3730 std::vector<symtab *> result
3731 = collect_symtabs_from_filename (filename, search_pspace);
3733 if (result.empty ())
3735 if (!have_full_symbols () && !have_partial_symbols ())
3736 throw_error (NOT_FOUND_ERROR,
3737 _("No symbol table is loaded. "
3738 "Use the \"file\" command."));
3739 source_file_not_found_error (filename);
3742 return result;
3745 /* See symtab.h. */
3747 void
3748 symbol_searcher::find_all_symbols (const std::string &name,
3749 const struct language_defn *language,
3750 domain_search_flags domain_search_flags,
3751 std::vector<symtab *> *search_symtabs,
3752 struct program_space *search_pspace)
3754 symbol_searcher_collect_info info;
3755 struct linespec_state state;
3757 memset (&state, 0, sizeof (state));
3758 state.language = language;
3759 info.state = &state;
3761 info.result.symbols = &m_symbols;
3762 info.result.minimal_symbols = &m_minimal_symbols;
3763 std::vector<symtab *> all_symtabs;
3764 if (search_symtabs == nullptr)
3766 all_symtabs.push_back (nullptr);
3767 search_symtabs = &all_symtabs;
3769 info.file_symtabs = search_symtabs;
3771 add_matching_symbols_to_info (name.c_str (), symbol_name_match_type::WILD,
3772 domain_search_flags, &info, search_pspace);
3775 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS. Matching
3776 debug symbols are returned in SYMBOLS. Matching minimal symbols are
3777 returned in MINSYMS. */
3779 static void
3780 find_function_symbols (struct linespec_state *state,
3781 const std::vector<symtab *> &file_symtabs, const char *name,
3782 symbol_name_match_type name_match_type,
3783 std::vector<block_symbol> *symbols,
3784 std::vector<bound_minimal_symbol> *minsyms)
3786 struct collect_info info;
3787 std::vector<const char *> symbol_names;
3789 info.state = state;
3790 info.result.symbols = symbols;
3791 info.result.minimal_symbols = minsyms;
3792 info.file_symtabs = &file_symtabs;
3794 /* Try NAME as an Objective-C selector. */
3795 find_imps (name, &symbol_names);
3797 domain_search_flags flags = SEARCH_FUNCTION_DOMAIN;
3798 if (state->list_mode)
3799 flags = SEARCH_VFT;
3801 if (!symbol_names.empty ())
3802 add_all_symbol_names_from_pspace (&info, state->search_pspace,
3803 symbol_names, flags);
3804 else
3805 add_matching_symbols_to_info (name, name_match_type, flags,
3806 &info, state->search_pspace);
3809 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3810 in SYMBOLS and minimal symbols in MINSYMS. */
3812 static void
3813 find_linespec_symbols (struct linespec_state *state,
3814 const std::vector<symtab *> &file_symtabs,
3815 const char *lookup_name,
3816 symbol_name_match_type name_match_type,
3817 std::vector <block_symbol> *symbols,
3818 std::vector<bound_minimal_symbol> *minsyms)
3820 gdb::unique_xmalloc_ptr<char> canon
3821 = cp_canonicalize_string_no_typedefs (lookup_name);
3822 if (canon != nullptr)
3823 lookup_name = canon.get ();
3825 /* It's important to not call expand_symtabs_matching unnecessarily
3826 as it can really slow things down (by unnecessarily expanding
3827 potentially 1000s of symtabs, which when debugging some apps can
3828 cost 100s of seconds). Avoid this to some extent by *first* calling
3829 find_function_symbols, and only if that doesn't find anything
3830 *then* call find_method. This handles two important cases:
3831 1) break (anonymous namespace)::foo
3832 2) break class::method where method is in class (and not a baseclass) */
3834 find_function_symbols (state, file_symtabs, lookup_name,
3835 name_match_type, symbols, minsyms);
3837 /* If we were unable to locate a symbol of the same name, try dividing
3838 the name into class and method names and searching the class and its
3839 baseclasses. */
3840 if (symbols->empty () && minsyms->empty ())
3842 std::string klass, method;
3843 const char *last, *p, *scope_op;
3845 /* See if we can find a scope operator and break this symbol
3846 name into namespaces${SCOPE_OPERATOR}class_name and method_name. */
3847 scope_op = "::";
3848 p = find_toplevel_string (lookup_name, scope_op);
3850 last = NULL;
3851 while (p != NULL)
3853 last = p;
3854 p = find_toplevel_string (p + strlen (scope_op), scope_op);
3857 /* If no scope operator was found, there is nothing more we can do;
3858 we already attempted to lookup the entire name as a symbol
3859 and failed. */
3860 if (last == NULL)
3861 return;
3863 /* LOOKUP_NAME points to the class name.
3864 LAST points to the method name. */
3865 klass = std::string (lookup_name, last - lookup_name);
3867 /* Skip past the scope operator. */
3868 last += strlen (scope_op);
3869 method = last;
3871 /* Find a list of classes named KLASS. */
3872 std::vector<block_symbol> classes
3873 = lookup_prefix_sym (state, file_symtabs, klass.c_str ());
3874 if (!classes.empty ())
3876 /* Now locate a list of suitable methods named METHOD. */
3879 find_method (state, file_symtabs,
3880 klass.c_str (), method.c_str (),
3881 &classes, symbols, minsyms);
3884 /* If successful, we're done. If NOT_FOUND_ERROR
3885 was not thrown, rethrow the exception that we did get. */
3886 catch (const gdb_exception_error &except)
3888 if (except.error != NOT_FOUND_ERROR)
3889 throw;
3895 /* Helper for find_label_symbols. Find all labels that match name
3896 NAME in BLOCK. Return all labels that match in FUNCTION_SYMBOLS.
3897 Return the actual function symbol in which the label was found in
3898 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3899 interpreted as a label name prefix. Otherwise, only a label named
3900 exactly NAME match. */
3902 static void
3903 find_label_symbols_in_block (const struct block *block,
3904 const char *name, struct symbol *fn_sym,
3905 bool completion_mode,
3906 std::vector<block_symbol> *result,
3907 std::vector<block_symbol> *label_funcs_ret)
3909 if (completion_mode)
3911 size_t name_len = strlen (name);
3913 int (*cmp) (const char *, const char *, size_t);
3914 cmp = case_sensitivity == case_sensitive_on ? strncmp : strncasecmp;
3916 for (struct symbol *sym : block_iterator_range (block))
3918 if (sym->domain () == LABEL_DOMAIN
3919 && cmp (sym->search_name (), name, name_len) == 0)
3921 result->push_back ({sym, block});
3922 label_funcs_ret->push_back ({fn_sym, block});
3926 else
3928 struct block_symbol label_sym
3929 = lookup_symbol (name, block, SEARCH_LABEL_DOMAIN, 0);
3931 if (label_sym.symbol != NULL)
3933 result->push_back (label_sym);
3934 label_funcs_ret->push_back ({fn_sym, block});
3939 /* Return all labels that match name NAME in FUNCTION_SYMBOLS.
3941 Return the actual function symbol in which the label was found in
3942 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3943 interpreted as a label name prefix. Otherwise, only labels named
3944 exactly NAME match. */
3947 static std::vector<block_symbol>
3948 find_label_symbols (struct linespec_state *self,
3949 const std::vector<block_symbol> &function_symbols,
3950 std::vector<block_symbol> *label_funcs_ret,
3951 const char *name,
3952 bool completion_mode)
3954 const struct block *block;
3955 struct symbol *fn_sym;
3956 std::vector<block_symbol> result;
3958 if (function_symbols.empty ())
3960 set_current_program_space (self->program_space);
3961 block = get_current_search_block ();
3963 for (;
3964 block && !block->function ();
3965 block = block->superblock ())
3968 if (!block)
3969 return {};
3971 fn_sym = block->function ();
3973 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
3974 &result, label_funcs_ret);
3976 else
3978 for (const auto &elt : function_symbols)
3980 fn_sym = elt.symbol;
3981 set_current_program_space
3982 (fn_sym->symtab ()->compunit ()->objfile ()->pspace);
3983 block = fn_sym->value_block ();
3985 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
3986 &result, label_funcs_ret);
3990 return result;
3995 /* A helper for create_sals_line_offset that handles the 'list_mode' case. */
3997 static std::vector<symtab_and_line>
3998 decode_digits_list_mode (struct linespec_state *self,
3999 linespec *ls,
4000 struct symtab_and_line val)
4002 gdb_assert (self->list_mode);
4004 std::vector<symtab_and_line> values;
4006 for (const auto &elt : ls->file_symtabs)
4008 /* The logic above should ensure this. */
4009 gdb_assert (elt != NULL);
4011 program_space *pspace = elt->compunit ()->objfile ()->pspace;
4012 set_current_program_space (pspace);
4014 /* Simplistic search just for the list command. */
4015 val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
4016 if (val.symtab == NULL)
4017 val.symtab = elt;
4018 val.pspace = pspace;
4019 val.pc = 0;
4020 val.explicit_line = true;
4022 add_sal_to_sals (self, &values, &val, NULL, 0);
4025 return values;
4028 /* A helper for create_sals_line_offset that iterates over the symtabs
4029 associated with LS and returns a vector of corresponding symtab_and_line
4030 structures. */
4032 static std::vector<symtab_and_line>
4033 decode_digits_ordinary (struct linespec_state *self,
4034 linespec *ls,
4035 int line,
4036 const linetable_entry **best_entry)
4038 std::vector<symtab_and_line> sals;
4039 for (const auto &elt : ls->file_symtabs)
4041 std::vector<CORE_ADDR> pcs;
4043 /* The logic above should ensure this. */
4044 gdb_assert (elt != NULL);
4046 program_space *pspace = elt->compunit ()->objfile ()->pspace;
4047 set_current_program_space (pspace);
4049 pcs = find_pcs_for_symtab_line (elt, line, best_entry);
4050 for (CORE_ADDR pc : pcs)
4052 symtab_and_line sal;
4053 sal.pspace = pspace;
4054 sal.symtab = elt;
4055 sal.line = line;
4056 sal.explicit_line = true;
4057 sal.pc = pc;
4058 sals.push_back (std::move (sal));
4062 return sals;
4067 /* Return the line offset represented by VARIABLE. */
4069 static struct line_offset
4070 linespec_parse_variable (struct linespec_state *self, const char *variable)
4072 int index = 0;
4073 const char *p;
4074 line_offset offset;
4076 p = (variable[1] == '$') ? variable + 2 : variable + 1;
4077 if (*p == '$')
4078 ++p;
4079 while (*p >= '0' && *p <= '9')
4080 ++p;
4081 if (!*p) /* Reached end of token without hitting non-digit. */
4083 /* We have a value history reference. */
4084 struct value *val_history;
4086 sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
4087 val_history
4088 = access_value_history ((variable[1] == '$') ? -index : index);
4089 if (val_history->type ()->code () != TYPE_CODE_INT)
4090 error (_("History values used in line "
4091 "specs must have integer values."));
4092 offset.offset = value_as_long (val_history);
4093 offset.sign = LINE_OFFSET_NONE;
4095 else
4097 /* Not all digits -- may be user variable/function or a
4098 convenience variable. */
4099 LONGEST valx;
4100 struct internalvar *ivar;
4102 /* Try it as a convenience variable. If it is not a convenience
4103 variable, return and allow normal symbol lookup to occur. */
4104 ivar = lookup_only_internalvar (variable + 1);
4105 /* If there's no internal variable with that name, let the
4106 offset remain as unknown to allow the name to be looked up
4107 as a symbol. */
4108 if (ivar != nullptr)
4110 /* We found a valid variable name. If it is not an integer,
4111 throw an error. */
4112 if (!get_internalvar_integer (ivar, &valx))
4113 error (_("Convenience variables used in line "
4114 "specs must have integer values."));
4115 else
4117 offset.offset = valx;
4118 offset.sign = LINE_OFFSET_NONE;
4123 return offset;
4127 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
4128 linespec; return the SAL in RESULT. This function should return SALs
4129 matching those from find_function_start_sal, otherwise false
4130 multiple-locations breakpoints could be placed. */
4132 static void
4133 minsym_found (struct linespec_state *self, struct objfile *objfile,
4134 struct minimal_symbol *msymbol,
4135 std::vector<symtab_and_line> *result)
4137 bool want_start_sal = false;
4139 CORE_ADDR func_addr;
4140 bool is_function = msymbol_is_function (objfile, msymbol, &func_addr);
4142 if (is_function)
4144 const char *msym_name = msymbol->linkage_name ();
4146 if (msymbol->type () == mst_text_gnu_ifunc
4147 || msymbol->type () == mst_data_gnu_ifunc)
4148 want_start_sal = gnu_ifunc_resolve_name (msym_name, &func_addr);
4149 else
4150 want_start_sal = true;
4153 symtab_and_line sal;
4155 if (is_function && want_start_sal)
4156 sal = find_function_start_sal (func_addr, NULL, self->funfirstline);
4157 else
4159 sal.objfile = objfile;
4160 sal.msymbol = msymbol;
4161 /* Store func_addr, not the minsym's address in case this was an
4162 ifunc that hasn't been resolved yet. */
4163 if (is_function)
4164 sal.pc = func_addr;
4165 else
4166 sal.pc = msymbol->value_address (objfile);
4167 sal.pspace = current_program_space;
4170 sal.section = msymbol->obj_section (objfile);
4172 if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
4173 add_sal_to_sals (self, result, &sal, msymbol->natural_name (), 0);
4176 /* Helper for search_minsyms_for_name that adds the symbol to the
4177 result. */
4179 static void
4180 add_minsym (struct minimal_symbol *minsym, struct objfile *objfile,
4181 struct symtab *symtab, int list_mode,
4182 std::vector<struct bound_minimal_symbol> *msyms)
4184 if (symtab != NULL)
4186 /* We're looking for a label for which we don't have debug
4187 info. */
4188 CORE_ADDR func_addr;
4189 if (msymbol_is_function (objfile, minsym, &func_addr))
4191 symtab_and_line sal = find_pc_sect_line (func_addr, NULL, 0);
4193 if (symtab != sal.symtab)
4194 return;
4198 /* Exclude data symbols when looking for breakpoint locations. */
4199 if (!list_mode && !msymbol_is_function (objfile, minsym))
4200 return;
4202 msyms->emplace_back (minsym, objfile);
4203 return;
4206 /* Search for minimal symbols called NAME. If SEARCH_PSPACE
4207 is not NULL, the search is restricted to just that program
4208 space.
4210 If SYMTAB is NULL, search all objfiles, otherwise
4211 restrict results to the given SYMTAB. */
4213 static void
4214 search_minsyms_for_name (struct collect_info *info,
4215 const lookup_name_info &name,
4216 struct program_space *search_pspace,
4217 struct symtab *symtab)
4219 std::vector<struct bound_minimal_symbol> minsyms;
4221 if (symtab == NULL)
4223 for (struct program_space *pspace : program_spaces)
4225 if (search_pspace != NULL && search_pspace != pspace)
4226 continue;
4227 if (pspace->executing_startup)
4228 continue;
4230 set_current_program_space (pspace);
4232 for (objfile *objfile : current_program_space->objfiles ())
4234 iterate_over_minimal_symbols (objfile, name,
4235 [&] (struct minimal_symbol *msym)
4237 add_minsym (msym, objfile, nullptr,
4238 info->state->list_mode,
4239 &minsyms);
4240 return false;
4245 else
4247 program_space *pspace = symtab->compunit ()->objfile ()->pspace;
4249 if (search_pspace == NULL || pspace == search_pspace)
4251 set_current_program_space (pspace);
4252 iterate_over_minimal_symbols
4253 (symtab->compunit ()->objfile (), name,
4254 [&] (struct minimal_symbol *msym)
4256 add_minsym (msym, symtab->compunit ()->objfile (), symtab,
4257 info->state->list_mode, &minsyms);
4258 return false;
4263 /* Return true if TYPE is a static symbol. */
4264 auto msymbol_type_is_static = [] (enum minimal_symbol_type type)
4266 switch (type)
4268 case mst_file_text:
4269 case mst_file_data:
4270 case mst_file_bss:
4271 return true;
4272 default:
4273 return false;
4277 /* Add minsyms to the result set, but filter out trampoline symbols
4278 if we also found extern symbols with the same name. I.e., don't
4279 set a breakpoint on both '<foo@plt>' and 'foo', assuming that
4280 'foo' is the symbol that the plt resolves to. */
4281 for (const bound_minimal_symbol &item : minsyms)
4283 bool skip = false;
4284 if (item.minsym->type () == mst_solib_trampoline)
4286 for (const bound_minimal_symbol &item2 : minsyms)
4288 if (&item2 == &item)
4289 continue;
4291 /* Ignore other trampoline symbols. */
4292 if (item2.minsym->type () == mst_solib_trampoline)
4293 continue;
4295 /* Trampoline symbols can only jump to exported
4296 symbols. */
4297 if (msymbol_type_is_static (item2.minsym->type ()))
4298 continue;
4300 if (strcmp (item.minsym->linkage_name (),
4301 item2.minsym->linkage_name ()) != 0)
4302 continue;
4304 /* Found a global minsym with the same name as the
4305 trampoline. Don't create a location for this
4306 trampoline. */
4307 skip = true;
4308 break;
4312 if (!skip)
4313 info->result.minimal_symbols->push_back (item);
4317 /* A helper function to add all symbols matching NAME to INFO. If
4318 PSPACE is not NULL, the search is restricted to just that program
4319 space. */
4321 static void
4322 add_matching_symbols_to_info (const char *name,
4323 symbol_name_match_type name_match_type,
4324 domain_search_flags domain_search_flags,
4325 struct collect_info *info,
4326 struct program_space *pspace)
4328 lookup_name_info lookup_name (name, name_match_type);
4330 for (const auto &elt : *info->file_symtabs)
4332 if (elt == nullptr)
4334 iterate_over_all_matching_symtabs (info->state, lookup_name,
4335 domain_search_flags,
4336 pspace, true,
4337 [&] (block_symbol *bsym)
4338 { return info->add_symbol (bsym); });
4339 search_minsyms_for_name (info, lookup_name, pspace, NULL);
4341 else if (pspace == NULL || pspace == elt->compunit ()->objfile ()->pspace)
4343 int prev_len = info->result.symbols->size ();
4345 /* Program spaces that are executing startup should have
4346 been filtered out earlier. */
4347 program_space *elt_pspace = elt->compunit ()->objfile ()->pspace;
4348 gdb_assert (!elt_pspace->executing_startup);
4349 set_current_program_space (elt_pspace);
4350 iterate_over_file_blocks (elt, lookup_name, SEARCH_VFT,
4351 [&] (block_symbol *bsym)
4352 { return info->add_symbol (bsym); });
4354 /* If no new symbols were found in this iteration and this symtab
4355 is in assembler, we might actually be looking for a label for
4356 which we don't have debug info. Check for a minimal symbol in
4357 this case. */
4358 if (prev_len == info->result.symbols->size ()
4359 && elt->language () == language_asm)
4360 search_minsyms_for_name (info, lookup_name, pspace, elt);
4367 /* Now come some functions that are called from multiple places within
4368 decode_line_1. */
4370 static int
4371 symbol_to_sal (struct symtab_and_line *result,
4372 int funfirstline, struct symbol *sym)
4374 if (sym->aclass () == LOC_BLOCK)
4376 *result = find_function_start_sal (sym, funfirstline);
4377 return 1;
4379 else
4381 if (sym->aclass () == LOC_LABEL && sym->value_address () != 0)
4383 *result = {};
4384 result->symtab = sym->symtab ();
4385 result->symbol = sym;
4386 result->line = sym->line ();
4387 result->pc = sym->value_address ();
4388 result->pspace = result->symtab->compunit ()->objfile ()->pspace;
4389 result->explicit_pc = 1;
4390 return 1;
4392 else if (funfirstline)
4394 /* Nothing. */
4396 else if (sym->line () != 0)
4398 /* We know its line number. */
4399 *result = {};
4400 result->symtab = sym->symtab ();
4401 result->symbol = sym;
4402 result->line = sym->line ();
4403 result->pc = sym->value_address ();
4404 result->pspace = result->symtab->compunit ()->objfile ()->pspace;
4405 return 1;
4409 return 0;
4412 linespec_result::~linespec_result ()
4414 for (linespec_sals &lsal : lsals)
4415 xfree (lsal.canonical);
4418 /* Return the quote characters permitted by the linespec parser. */
4420 const char *
4421 get_gdb_linespec_parser_quote_characters (void)
4423 return linespec_quote_characters;