arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / linespec.c
blob528abc46b892e25cfb8067f71601aaad0b6beb1f
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 "symtab.h"
21 #include "frame.h"
22 #include "command.h"
23 #include "symfile.h"
24 #include "objfiles.h"
25 #include "source.h"
26 #include "value.h"
27 #include "completer.h"
28 #include "cp-abi.h"
29 #include "cp-support.h"
30 #include "parser-defs.h"
31 #include "block.h"
32 #include "objc-lang.h"
33 #include "linespec.h"
34 #include "language.h"
35 #include "interps.h"
36 #include "target.h"
37 #include "arch-utils.h"
38 #include <ctype.h>
39 #include "cli/cli-utils.h"
40 #include "filenames.h"
41 #include "ada-lang.h"
42 #include "stack.h"
43 #include "location.h"
44 #include "gdbsupport/function-view.h"
45 #include "gdbsupport/def-vector.h"
46 #include <algorithm>
47 #include "inferior.h"
49 /* An enumeration of the various things a user might attempt to
50 complete for a linespec location. */
52 enum class linespec_complete_what
54 /* Nothing, no possible completion. */
55 NOTHING,
57 /* A function/method name. Due to ambiguity between
59 (gdb) b source[TAB]
60 source_file.c
61 source_function
63 this can also indicate a source filename, iff we haven't seen a
64 separate source filename component, as in "b source.c:function". */
65 FUNCTION,
67 /* A label symbol. E.g., break file.c:function:LABEL. */
68 LABEL,
70 /* An expression. E.g., "break foo if EXPR", or "break *EXPR". */
71 EXPRESSION,
73 /* A linespec keyword ("if"/"thread"/"task"/"-force-condition").
74 E.g., "break func threa<tab>". */
75 KEYWORD,
78 /* An address entry is used to ensure that any given location is only
79 added to the result a single time. It holds an address and the
80 program space from which the address came. */
82 struct address_entry
84 struct program_space *pspace;
85 CORE_ADDR addr;
88 /* A linespec. Elements of this structure are filled in by a parser
89 (either parse_linespec or some other function). The structure is
90 then converted into SALs by convert_linespec_to_sals. */
92 struct linespec
94 /* An explicit location spec describing the SaLs. */
95 explicit_location_spec explicit_loc;
97 /* The list of symtabs to search to which to limit the search.
99 If explicit.SOURCE_FILENAME is NULL (no user-specified filename),
100 FILE_SYMTABS should contain one single NULL member. This will cause the
101 code to use the default symtab. */
102 std::vector<symtab *> file_symtabs;
104 /* A list of matching function symbols and minimal symbols. Both lists
105 may be empty if no matching symbols were found. */
106 std::vector<block_symbol> function_symbols;
107 std::vector<bound_minimal_symbol> minimal_symbols;
109 /* A structure of matching label symbols and the corresponding
110 function symbol in which the label was found. Both may be empty
111 or both must be non-empty. */
112 struct
114 std::vector<block_symbol> label_symbols;
115 std::vector<block_symbol> function_symbols;
116 } labels;
119 /* A canonical linespec represented as a symtab-related string.
121 Each entry represents the "SYMTAB:SUFFIX" linespec string.
122 SYMTAB can be converted for example by symtab_to_fullname or
123 symtab_to_filename_for_display as needed. */
125 struct linespec_canonical_name
127 /* Remaining text part of the linespec string. */
128 char *suffix;
130 /* If NULL then SUFFIX is the whole linespec string. */
131 struct symtab *symtab;
134 /* An instance of this is used to keep all state while linespec
135 operates. This instance is passed around as a 'this' pointer to
136 the various implementation methods. */
138 struct linespec_state
140 /* The language in use during linespec processing. */
141 const struct language_defn *language;
143 /* The program space as seen when the module was entered. */
144 struct program_space *program_space;
146 /* If not NULL, the search is restricted to just this program
147 space. */
148 struct program_space *search_pspace;
150 /* The default symtab to use, if no other symtab is specified. */
151 struct symtab *default_symtab;
153 /* The default line to use. */
154 int default_line;
156 /* The 'funfirstline' value that was passed in to decode_line_1 or
157 decode_line_full. */
158 int funfirstline;
160 /* Nonzero if we are running in 'list' mode; see decode_line_list. */
161 int list_mode;
163 /* The 'canonical' value passed to decode_line_full, or NULL. */
164 struct linespec_result *canonical;
166 /* Canonical strings that mirror the std::vector<symtab_and_line> result. */
167 struct linespec_canonical_name *canonical_names;
169 /* This is a set of address_entry objects which is used to prevent
170 duplicate symbols from being entered into the result. */
171 htab_t addr_set;
173 /* Are we building a linespec? */
174 int is_linespec;
177 /* This is a helper object that is used when collecting symbols into a
178 result. */
180 struct collect_info
182 /* The linespec object in use. */
183 struct linespec_state *state;
185 /* A list of symtabs to which to restrict matches. */
186 const std::vector<symtab *> *file_symtabs;
188 /* The result being accumulated. */
189 struct
191 std::vector<block_symbol> *symbols;
192 std::vector<bound_minimal_symbol> *minimal_symbols;
193 } result;
195 /* Possibly add a symbol to the results. */
196 virtual bool add_symbol (block_symbol *bsym);
199 bool
200 collect_info::add_symbol (block_symbol *bsym)
202 /* In list mode, add all matching symbols, regardless of class.
203 This allows the user to type "list a_global_variable". */
204 if (bsym->symbol->aclass () == LOC_BLOCK || this->state->list_mode)
205 this->result.symbols->push_back (*bsym);
207 /* Continue iterating. */
208 return true;
211 /* Custom collect_info for symbol_searcher. */
213 struct symbol_searcher_collect_info
214 : collect_info
216 bool add_symbol (block_symbol *bsym) override
218 /* Add everything. */
219 this->result.symbols->push_back (*bsym);
221 /* Continue iterating. */
222 return true;
226 /* Token types */
228 enum linespec_token_type
230 /* A keyword */
231 LSTOKEN_KEYWORD = 0,
233 /* A colon "separator" */
234 LSTOKEN_COLON,
236 /* A string */
237 LSTOKEN_STRING,
239 /* A number */
240 LSTOKEN_NUMBER,
242 /* A comma */
243 LSTOKEN_COMMA,
245 /* EOI (end of input) */
246 LSTOKEN_EOI,
248 /* Consumed token */
249 LSTOKEN_CONSUMED
252 /* List of keywords. This is NULL-terminated so that it can be used
253 as enum completer. */
254 const char * const linespec_keywords[] = { "if", "thread", "task", "inferior", "-force-condition", NULL };
255 #define IF_KEYWORD_INDEX 0
256 #define FORCE_KEYWORD_INDEX 4
258 /* A token of the linespec lexer */
260 struct linespec_token
262 /* The type of the token */
263 linespec_token_type type;
265 /* Data for the token */
266 union
268 /* A string, given as a stoken */
269 struct stoken string;
271 /* A keyword */
272 const char *keyword;
273 } data;
276 /* An instance of the linespec parser. */
278 struct linespec_parser
280 linespec_parser (int flags, const struct language_defn *language,
281 struct program_space *search_pspace,
282 struct symtab *default_symtab,
283 int default_line,
284 struct linespec_result *canonical);
286 ~linespec_parser ();
288 DISABLE_COPY_AND_ASSIGN (linespec_parser);
290 /* Lexer internal data */
291 struct
293 /* Save head of input stream. */
294 const char *saved_arg;
296 /* Head of the input stream. */
297 const char *stream;
299 /* The current token. */
300 linespec_token current;
301 } lexer {};
303 /* Is the entire linespec quote-enclosed? */
304 int is_quote_enclosed = 0;
306 /* The state of the parse. */
307 struct linespec_state state {};
309 /* The result of the parse. */
310 linespec result;
312 /* What the parser believes the current word point should complete
313 to. */
314 linespec_complete_what complete_what = linespec_complete_what::NOTHING;
316 /* The completion word point. The parser advances this as it skips
317 tokens. At some point the input string will end or parsing will
318 fail, and then we attempt completion at the captured completion
319 word point, interpreting the string at completion_word as
320 COMPLETE_WHAT. */
321 const char *completion_word = nullptr;
323 /* If the current token was a quoted string, then this is the
324 quoting character (either " or '). */
325 int completion_quote_char = 0;
327 /* If the current token was a quoted string, then this points at the
328 end of the quoted string. */
329 const char *completion_quote_end = nullptr;
331 /* If parsing for completion, then this points at the completion
332 tracker. Otherwise, this is NULL. */
333 struct completion_tracker *completion_tracker = nullptr;
336 /* Prototypes for local functions. */
338 static void iterate_over_file_blocks
339 (struct symtab *symtab, const lookup_name_info &name,
340 domain_search_flags domain,
341 gdb::function_view<symbol_found_callback_ftype> callback);
343 static void initialize_defaults (struct symtab **default_symtab,
344 int *default_line);
346 CORE_ADDR linespec_expression_to_pc (const char **exp_ptr);
348 static std::vector<symtab_and_line> decode_objc (struct linespec_state *self,
349 linespec *ls,
350 const char *arg);
352 static std::vector<symtab *> symtabs_from_filename
353 (const char *, struct program_space *pspace);
355 static std::vector<block_symbol> find_label_symbols
356 (struct linespec_state *self,
357 const std::vector<block_symbol> &function_symbols,
358 std::vector<block_symbol> *label_funcs_ret,
359 const char *name, bool completion_mode = false);
361 static void find_linespec_symbols (struct linespec_state *self,
362 const std::vector<symtab *> &file_symtabs,
363 const char *name,
364 symbol_name_match_type name_match_type,
365 std::vector<block_symbol> *symbols,
366 std::vector<bound_minimal_symbol> *minsyms);
368 static struct line_offset
369 linespec_parse_variable (struct linespec_state *self,
370 const char *variable);
372 static int symbol_to_sal (struct symtab_and_line *result,
373 int funfirstline, struct symbol *sym);
375 static void add_matching_symbols_to_info (const char *name,
376 symbol_name_match_type name_match_type,
377 domain_search_flags domain_search_flags,
378 struct collect_info *info,
379 struct program_space *pspace);
381 static void add_all_symbol_names_from_pspace
382 (struct collect_info *info, struct program_space *pspace,
383 const std::vector<const char *> &names, domain_search_flags domain_search_flags);
385 static std::vector<symtab *>
386 collect_symtabs_from_filename (const char *file,
387 struct program_space *pspace);
389 static std::vector<symtab_and_line> decode_digits_ordinary
390 (struct linespec_state *self,
391 linespec *ls,
392 int line,
393 const linetable_entry **best_entry);
395 static std::vector<symtab_and_line> decode_digits_list_mode
396 (struct linespec_state *self,
397 linespec *ls,
398 struct symtab_and_line val);
400 static void minsym_found (struct linespec_state *self, struct objfile *objfile,
401 struct minimal_symbol *msymbol,
402 std::vector<symtab_and_line> *result);
404 static bool compare_symbols (const block_symbol &a, const block_symbol &b);
406 static bool compare_msymbols (const bound_minimal_symbol &a,
407 const bound_minimal_symbol &b);
409 /* Permitted quote characters for the parser. This is different from the
410 completer's quote characters to allow backward compatibility with the
411 previous parser. */
412 static const char linespec_quote_characters[] = "\"\'";
414 /* Lexer functions. */
416 /* Lex a number from the input in PARSER. This only supports
417 decimal numbers.
419 Return true if input is decimal numbers. Return false if not. */
421 static int
422 linespec_lexer_lex_number (linespec_parser *parser, linespec_token *tokenp)
424 tokenp->type = LSTOKEN_NUMBER;
425 tokenp->data.string.length = 0;
426 tokenp->data.string.ptr = parser->lexer.stream;
428 /* Keep any sign at the start of the stream. */
429 if (*parser->lexer.stream == '+' || *parser->lexer.stream == '-')
431 ++tokenp->data.string.length;
432 ++(parser->lexer.stream);
435 while (isdigit (*parser->lexer.stream))
437 ++tokenp->data.string.length;
438 ++(parser->lexer.stream);
441 /* If the next character in the input buffer is not a space, comma,
442 quote, or colon, this input does not represent a number. */
443 if (*parser->lexer.stream != '\0'
444 && !isspace (*parser->lexer.stream) && *parser->lexer.stream != ','
445 && *parser->lexer.stream != ':'
446 && !strchr (linespec_quote_characters, *parser->lexer.stream))
448 parser->lexer.stream = tokenp->data.string.ptr;
449 return 0;
452 return 1;
455 /* See linespec.h. */
457 const char *
458 linespec_lexer_lex_keyword (const char *p)
460 int i;
462 if (p != NULL)
464 for (i = 0; linespec_keywords[i] != NULL; ++i)
466 int len = strlen (linespec_keywords[i]);
468 /* If P begins with
470 - "thread" or "task" and the next character is
471 whitespace, we may have found a keyword. It is only a
472 keyword if it is not followed by another keyword.
474 - "-force-condition", the next character may be EOF
475 since this keyword does not take any arguments. Otherwise,
476 it should be followed by a keyword.
478 - "if", ALWAYS stop the lexer, since it is not possible to
479 predict what is going to appear in the condition, which can
480 only be parsed after SaLs have been found. */
481 if (strncmp (p, linespec_keywords[i], len) == 0)
483 int j;
485 if (i == FORCE_KEYWORD_INDEX && p[len] == '\0')
486 return linespec_keywords[i];
488 if (!isspace (p[len]))
489 continue;
491 if (i == FORCE_KEYWORD_INDEX)
493 p += len;
494 p = skip_spaces (p);
495 for (j = 0; linespec_keywords[j] != NULL; ++j)
497 int nextlen = strlen (linespec_keywords[j]);
499 if (strncmp (p, linespec_keywords[j], nextlen) == 0
500 && isspace (p[nextlen]))
501 return linespec_keywords[i];
504 else if (i != IF_KEYWORD_INDEX)
506 /* We matched a "thread" or "task". */
507 p += len;
508 p = skip_spaces (p);
509 for (j = 0; linespec_keywords[j] != NULL; ++j)
511 int nextlen = strlen (linespec_keywords[j]);
513 if (strncmp (p, linespec_keywords[j], nextlen) == 0
514 && isspace (p[nextlen]))
515 return NULL;
519 return linespec_keywords[i];
524 return NULL;
527 /* See description in linespec.h. */
530 is_ada_operator (const char *string)
532 const struct ada_opname_map *mapping;
534 for (mapping = ada_opname_table;
535 mapping->encoded != NULL
536 && !startswith (string, mapping->decoded); ++mapping)
539 return mapping->decoded == NULL ? 0 : strlen (mapping->decoded);
542 /* Find QUOTE_CHAR in STRING, accounting for the ':' terminal. Return
543 the location of QUOTE_CHAR, or NULL if not found. */
545 static const char *
546 skip_quote_char (const char *string, char quote_char)
548 const char *p, *last;
550 p = last = find_toplevel_char (string, quote_char);
551 while (p && *p != '\0' && *p != ':')
553 p = find_toplevel_char (p, quote_char);
554 if (p != NULL)
555 last = p++;
558 return last;
561 /* Make a writable copy of the string given in TOKEN, trimming
562 any trailing whitespace. */
564 static gdb::unique_xmalloc_ptr<char>
565 copy_token_string (linespec_token token)
567 const char *str, *s;
569 if (token.type == LSTOKEN_KEYWORD)
570 return make_unique_xstrdup (token.data.keyword);
572 str = token.data.string.ptr;
573 s = remove_trailing_whitespace (str, str + token.data.string.length);
575 return gdb::unique_xmalloc_ptr<char> (savestring (str, s - str));
578 /* Does P represent the end of a quote-enclosed linespec? */
580 static int
581 is_closing_quote_enclosed (const char *p)
583 if (strchr (linespec_quote_characters, *p))
584 ++p;
585 p = skip_spaces ((char *) p);
586 return (*p == '\0' || linespec_lexer_lex_keyword (p));
589 /* Find the end of the parameter list that starts with *INPUT.
590 This helper function assists with lexing string segments
591 which might contain valid (non-terminating) commas. */
593 static const char *
594 find_parameter_list_end (const char *input)
596 char end_char, start_char;
597 int depth;
598 const char *p;
600 start_char = *input;
601 if (start_char == '(')
602 end_char = ')';
603 else if (start_char == '<')
604 end_char = '>';
605 else
606 return NULL;
608 p = input;
609 depth = 0;
610 while (*p)
612 if (*p == start_char)
613 ++depth;
614 else if (*p == end_char)
616 if (--depth == 0)
618 ++p;
619 break;
622 ++p;
625 return p;
628 /* If the [STRING, STRING_LEN) string ends with what looks like a
629 keyword, return the keyword start offset in STRING. Return -1
630 otherwise. */
632 static size_t
633 string_find_incomplete_keyword_at_end (const char * const *keywords,
634 const char *string, size_t string_len)
636 const char *end = string + string_len;
637 const char *p = end;
639 while (p > string && *p != ' ')
640 --p;
641 if (p > string)
643 p++;
644 size_t len = end - p;
645 for (size_t i = 0; keywords[i] != NULL; ++i)
646 if (strncmp (keywords[i], p, len) == 0)
647 return p - string;
650 return -1;
653 /* Lex a string from the input in PARSER. */
655 static linespec_token
656 linespec_lexer_lex_string (linespec_parser *parser)
658 linespec_token token;
659 const char *start = parser->lexer.stream;
661 token.type = LSTOKEN_STRING;
663 /* If the input stream starts with a quote character, skip to the next
664 quote character, regardless of the content. */
665 if (strchr (linespec_quote_characters, *parser->lexer.stream))
667 const char *end;
668 char quote_char = *parser->lexer.stream;
670 /* Special case: Ada operators. */
671 if (parser->state.language->la_language == language_ada
672 && quote_char == '\"')
674 int len = is_ada_operator (parser->lexer.stream);
676 if (len != 0)
678 /* The input is an Ada operator. Return the quoted string
679 as-is. */
680 token.data.string.ptr = parser->lexer.stream;
681 token.data.string.length = len;
682 parser->lexer.stream += len;
683 return token;
686 /* The input does not represent an Ada operator -- fall through
687 to normal quoted string handling. */
690 /* Skip past the beginning quote. */
691 ++(parser->lexer.stream);
693 /* Mark the start of the string. */
694 token.data.string.ptr = parser->lexer.stream;
696 /* Skip to the ending quote. */
697 end = skip_quote_char (parser->lexer.stream, quote_char);
699 /* This helps the completer mode decide whether we have a
700 complete string. */
701 parser->completion_quote_char = quote_char;
702 parser->completion_quote_end = end;
704 /* Error if the input did not terminate properly, unless in
705 completion mode. */
706 if (end == NULL)
708 if (parser->completion_tracker == NULL)
709 error (_("unmatched quote"));
711 /* In completion mode, we'll try to complete the incomplete
712 token. */
713 token.type = LSTOKEN_STRING;
714 while (*parser->lexer.stream != '\0')
715 parser->lexer.stream++;
716 token.data.string.length = parser->lexer.stream - 1 - start;
718 else
720 /* Skip over the ending quote and mark the length of the string. */
721 parser->lexer.stream = (char *) ++end;
722 token.data.string.length = parser->lexer.stream - 2 - start;
725 else
727 const char *p;
729 /* Otherwise, only identifier characters are permitted.
730 Spaces are the exception. In general, we keep spaces,
731 but only if the next characters in the input do not resolve
732 to one of the keywords.
734 This allows users to forgo quoting CV-qualifiers, template arguments,
735 and similar common language constructs. */
737 while (1)
739 if (isspace (*parser->lexer.stream))
741 p = skip_spaces (parser->lexer.stream);
742 /* When we get here we know we've found something followed by
743 a space (we skip over parens and templates below).
744 So if we find a keyword now, we know it is a keyword and not,
745 say, a function name. */
746 if (linespec_lexer_lex_keyword (p) != NULL)
748 token.data.string.ptr = start;
749 token.data.string.length
750 = parser->lexer.stream - start;
751 return token;
754 /* Advance past the whitespace. */
755 parser->lexer.stream = p;
758 /* If the next character is EOI or (single) ':', the
759 string is complete; return the token. */
760 if (*parser->lexer.stream == 0)
762 token.data.string.ptr = start;
763 token.data.string.length = parser->lexer.stream - start;
764 return token;
766 else if (parser->lexer.stream[0] == ':')
768 /* Do not tokenize the C++ scope operator. */
769 if (parser->lexer.stream[1] == ':')
770 ++(parser->lexer.stream);
772 /* Do not tokenize ABI tags such as "[abi:cxx11]". */
773 else if (parser->lexer.stream - start > 4
774 && startswith (parser->lexer.stream - 4, "[abi"))
776 /* Nothing. */
779 /* Do not tokenify if the input length so far is one
780 (i.e, a single-letter drive name) and the next character
781 is a directory separator. This allows Windows-style
782 paths to be recognized as filenames without quoting it. */
783 else if ((parser->lexer.stream - start) != 1
784 || !IS_DIR_SEPARATOR (parser->lexer.stream[1]))
786 token.data.string.ptr = start;
787 token.data.string.length
788 = parser->lexer.stream - start;
789 return token;
792 /* Special case: permit quote-enclosed linespecs. */
793 else if (parser->is_quote_enclosed
794 && strchr (linespec_quote_characters,
795 *parser->lexer.stream)
796 && is_closing_quote_enclosed (parser->lexer.stream))
798 token.data.string.ptr = start;
799 token.data.string.length = parser->lexer.stream - start;
800 return token;
802 /* Because commas may terminate a linespec and appear in
803 the middle of valid string input, special cases for
804 '<' and '(' are necessary. */
805 else if (*parser->lexer.stream == '<'
806 || *parser->lexer.stream == '(')
808 /* Don't interpret 'operator<' / 'operator<<' as a
809 template parameter list though. */
810 if (*parser->lexer.stream == '<'
811 && (parser->state.language->la_language
812 == language_cplus)
813 && (parser->lexer.stream - start) >= CP_OPERATOR_LEN)
815 const char *op = parser->lexer.stream;
817 while (op > start && isspace (op[-1]))
818 op--;
819 if (op - start >= CP_OPERATOR_LEN)
821 op -= CP_OPERATOR_LEN;
822 if (strncmp (op, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
823 && (op == start
824 || !(isalnum (op[-1]) || op[-1] == '_')))
826 /* This is an operator name. Keep going. */
827 ++(parser->lexer.stream);
828 if (*parser->lexer.stream == '<')
829 ++(parser->lexer.stream);
830 continue;
835 const char *end = find_parameter_list_end (parser->lexer.stream);
836 parser->lexer.stream = end;
838 /* Don't loop around to the normal \0 case above because
839 we don't want to misinterpret a potential keyword at
840 the end of the token when the string isn't
841 "()<>"-balanced. This handles "b
842 function(thread<tab>" in completion mode. */
843 if (*end == '\0')
845 token.data.string.ptr = start;
846 token.data.string.length
847 = parser->lexer.stream - start;
848 return token;
850 else
851 continue;
853 /* Commas are terminators, but not if they are part of an
854 operator name. */
855 else if (*parser->lexer.stream == ',')
857 if ((parser->state.language->la_language
858 == language_cplus)
859 && (parser->lexer.stream - start) > CP_OPERATOR_LEN)
861 const char *op = strstr (start, CP_OPERATOR_STR);
863 if (op != NULL && is_operator_name (op))
865 /* This is an operator name. Keep going. */
866 ++(parser->lexer.stream);
867 continue;
871 /* Comma terminates the string. */
872 token.data.string.ptr = start;
873 token.data.string.length = parser->lexer.stream - start;
874 return token;
877 /* Advance the stream. */
878 gdb_assert (*(parser->lexer.stream) != '\0');
879 ++(parser->lexer.stream);
883 return token;
886 /* Lex a single linespec token from PARSER. */
888 static linespec_token
889 linespec_lexer_lex_one (linespec_parser *parser)
891 const char *keyword;
893 if (parser->lexer.current.type == LSTOKEN_CONSUMED)
895 /* Skip any whitespace. */
896 parser->lexer.stream = skip_spaces (parser->lexer.stream);
898 /* Check for a keyword, they end the linespec. */
899 keyword = linespec_lexer_lex_keyword (parser->lexer.stream);
900 if (keyword != NULL)
902 parser->lexer.current.type = LSTOKEN_KEYWORD;
903 parser->lexer.current.data.keyword = keyword;
904 /* We do not advance the stream here intentionally:
905 we would like lexing to stop when a keyword is seen.
907 parser->lexer.stream += strlen (keyword); */
909 return parser->lexer.current;
912 /* Handle other tokens. */
913 switch (*parser->lexer.stream)
915 case 0:
916 parser->lexer.current.type = LSTOKEN_EOI;
917 break;
919 case '+': case '-':
920 case '0': case '1': case '2': case '3': case '4':
921 case '5': case '6': case '7': case '8': case '9':
922 if (!linespec_lexer_lex_number (parser, &(parser->lexer.current)))
923 parser->lexer.current = linespec_lexer_lex_string (parser);
924 break;
926 case ':':
927 /* If we have a scope operator, lex the input as a string.
928 Otherwise, return LSTOKEN_COLON. */
929 if (parser->lexer.stream[1] == ':')
930 parser->lexer.current = linespec_lexer_lex_string (parser);
931 else
933 parser->lexer.current.type = LSTOKEN_COLON;
934 ++(parser->lexer.stream);
936 break;
938 case '\'': case '\"':
939 /* Special case: permit quote-enclosed linespecs. */
940 if (parser->is_quote_enclosed
941 && is_closing_quote_enclosed (parser->lexer.stream))
943 ++(parser->lexer.stream);
944 parser->lexer.current.type = LSTOKEN_EOI;
946 else
947 parser->lexer.current = linespec_lexer_lex_string (parser);
948 break;
950 case ',':
951 parser->lexer.current.type = LSTOKEN_COMMA;
952 parser->lexer.current.data.string.ptr
953 = parser->lexer.stream;
954 parser->lexer.current.data.string.length = 1;
955 ++(parser->lexer.stream);
956 break;
958 default:
959 /* If the input is not a number, it must be a string.
960 [Keywords were already considered above.] */
961 parser->lexer.current = linespec_lexer_lex_string (parser);
962 break;
966 return parser->lexer.current;
969 /* Consume the current token and return the next token in PARSER's
970 input stream. Also advance the completion word for completion
971 mode. */
973 static linespec_token
974 linespec_lexer_consume_token (linespec_parser *parser)
976 gdb_assert (parser->lexer.current.type != LSTOKEN_EOI);
978 bool advance_word = (parser->lexer.current.type != LSTOKEN_STRING
979 || *parser->lexer.stream != '\0');
981 /* If we're moving past a string to some other token, it must be the
982 quote was terminated. */
983 if (parser->completion_quote_char)
985 gdb_assert (parser->lexer.current.type == LSTOKEN_STRING);
987 /* If the string was the last (non-EOI) token, we're past the
988 quote, but remember that for later. */
989 if (*parser->lexer.stream != '\0')
991 parser->completion_quote_char = '\0';
992 parser->completion_quote_end = NULL;;
996 parser->lexer.current.type = LSTOKEN_CONSUMED;
997 linespec_lexer_lex_one (parser);
999 if (parser->lexer.current.type == LSTOKEN_STRING)
1001 /* Advance the completion word past a potential initial
1002 quote-char. */
1003 parser->completion_word = parser->lexer.current.data.string.ptr;
1005 else if (advance_word)
1007 /* Advance the completion word past any whitespace. */
1008 parser->completion_word = parser->lexer.stream;
1011 return parser->lexer.current;
1014 /* Return the next token without consuming the current token. */
1016 static linespec_token
1017 linespec_lexer_peek_token (linespec_parser *parser)
1019 linespec_token next;
1020 const char *saved_stream = parser->lexer.stream;
1021 linespec_token saved_token = parser->lexer.current;
1022 int saved_completion_quote_char = parser->completion_quote_char;
1023 const char *saved_completion_quote_end = parser->completion_quote_end;
1024 const char *saved_completion_word = parser->completion_word;
1026 next = linespec_lexer_consume_token (parser);
1027 parser->lexer.stream = saved_stream;
1028 parser->lexer.current = saved_token;
1029 parser->completion_quote_char = saved_completion_quote_char;
1030 parser->completion_quote_end = saved_completion_quote_end;
1031 parser->completion_word = saved_completion_word;
1032 return next;
1035 /* Helper functions. */
1037 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
1038 the new sal, if needed. If not NULL, SYMNAME is the name of the
1039 symbol to use when constructing the new canonical name.
1041 If LITERAL_CANONICAL is non-zero, SYMNAME will be used as the
1042 canonical name for the SAL. */
1044 static void
1045 add_sal_to_sals (struct linespec_state *self,
1046 std::vector<symtab_and_line> *sals,
1047 struct symtab_and_line *sal,
1048 const char *symname, int literal_canonical)
1050 sals->push_back (*sal);
1052 if (self->canonical)
1054 struct linespec_canonical_name *canonical;
1056 self->canonical_names = XRESIZEVEC (struct linespec_canonical_name,
1057 self->canonical_names,
1058 sals->size ());
1059 canonical = &self->canonical_names[sals->size () - 1];
1060 if (!literal_canonical && sal->symtab)
1062 symtab_to_fullname (sal->symtab);
1064 /* Note that the filter doesn't have to be a valid linespec
1065 input. We only apply the ":LINE" treatment to Ada for
1066 the time being. */
1067 if (symname != NULL && sal->line != 0
1068 && self->language->la_language == language_ada)
1069 canonical->suffix = xstrprintf ("%s:%d", symname,
1070 sal->line).release ();
1071 else if (symname != NULL)
1072 canonical->suffix = xstrdup (symname);
1073 else
1074 canonical->suffix = xstrprintf ("%d", sal->line).release ();
1075 canonical->symtab = sal->symtab;
1077 else
1079 if (symname != NULL)
1080 canonical->suffix = xstrdup (symname);
1081 else
1082 canonical->suffix = xstrdup ("<unknown>");
1083 canonical->symtab = NULL;
1088 /* A hash function for address_entry. */
1090 static hashval_t
1091 hash_address_entry (const void *p)
1093 const struct address_entry *aep = (const struct address_entry *) p;
1094 hashval_t hash;
1096 hash = iterative_hash_object (aep->pspace, 0);
1097 return iterative_hash_object (aep->addr, hash);
1100 /* An equality function for address_entry. */
1102 static int
1103 eq_address_entry (const void *a, const void *b)
1105 const struct address_entry *aea = (const struct address_entry *) a;
1106 const struct address_entry *aeb = (const struct address_entry *) b;
1108 return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
1111 /* Check whether the address, represented by PSPACE and ADDR, is
1112 already in the set. If so, return 0. Otherwise, add it and return
1113 1. */
1115 static int
1116 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
1118 struct address_entry e, *p;
1119 void **slot;
1121 e.pspace = pspace;
1122 e.addr = addr;
1123 slot = htab_find_slot (set, &e, INSERT);
1124 if (*slot)
1125 return 0;
1127 p = XNEW (struct address_entry);
1128 memcpy (p, &e, sizeof (struct address_entry));
1129 *slot = p;
1131 return 1;
1134 /* A helper that walks over all matching symtabs in all objfiles and
1135 calls CALLBACK for each symbol matching NAME. If SEARCH_PSPACE is
1136 not NULL, then the search is restricted to just that program
1137 space. If INCLUDE_INLINE is true then symbols representing
1138 inlined instances of functions will be included in the result. */
1140 static void
1141 iterate_over_all_matching_symtabs
1142 (struct linespec_state *state,
1143 const lookup_name_info &lookup_name,
1144 const domain_search_flags domain,
1145 struct program_space *search_pspace, bool include_inline,
1146 gdb::function_view<symbol_found_callback_ftype> callback)
1148 for (struct program_space *pspace : program_spaces)
1150 if (search_pspace != NULL && search_pspace != pspace)
1151 continue;
1152 if (pspace->executing_startup)
1153 continue;
1155 set_current_program_space (pspace);
1157 for (objfile *objfile : pspace->objfiles ())
1159 objfile->expand_symtabs_matching (NULL, &lookup_name, NULL, NULL,
1160 (SEARCH_GLOBAL_BLOCK
1161 | SEARCH_STATIC_BLOCK),
1162 domain);
1164 for (compunit_symtab *cu : objfile->compunits ())
1166 struct symtab *symtab = cu->primary_filetab ();
1168 iterate_over_file_blocks (symtab, lookup_name, domain, callback);
1170 if (include_inline)
1172 const struct block *block;
1173 int i;
1174 const blockvector *bv = symtab->compunit ()->blockvector ();
1176 for (i = FIRST_LOCAL_BLOCK; i < bv->num_blocks (); i++)
1178 block = bv->block (i);
1179 state->language->iterate_over_symbols
1180 (block, lookup_name, domain,
1181 [&] (block_symbol *bsym)
1183 /* Restrict calls to CALLBACK to symbols
1184 representing inline symbols only. */
1185 if (bsym->symbol->is_inlined ())
1186 return callback (bsym);
1187 return true;
1196 /* Returns the block to be used for symbol searches from
1197 the current location. */
1199 static const struct block *
1200 get_current_search_block (void)
1202 /* get_selected_block can change the current language when there is
1203 no selected frame yet. */
1204 scoped_restore_current_language save_language;
1205 return get_selected_block (0);
1208 /* Iterate over static and global blocks. */
1210 static void
1211 iterate_over_file_blocks
1212 (struct symtab *symtab, const lookup_name_info &name,
1213 domain_search_flags domain,
1214 gdb::function_view<symbol_found_callback_ftype> callback)
1216 const struct block *block;
1218 for (block = symtab->compunit ()->blockvector ()->static_block ();
1219 block != NULL;
1220 block = block->superblock ())
1221 current_language->iterate_over_symbols (block, name, domain, callback);
1224 /* A helper for find_method. This finds all methods in type T of
1225 language T_LANG which match NAME. It adds matching symbol names to
1226 RESULT_NAMES, and adds T's direct superclasses to SUPERCLASSES. */
1228 static void
1229 find_methods (struct type *t, enum language t_lang, const char *name,
1230 std::vector<const char *> *result_names,
1231 std::vector<struct type *> *superclasses)
1233 int ibase;
1234 const char *class_name = t->name ();
1236 /* Ignore this class if it doesn't have a name. This is ugly, but
1237 unless we figure out how to get the physname without the name of
1238 the class, then the loop can't do any good. */
1239 if (class_name)
1241 int method_counter;
1242 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1243 symbol_name_matcher_ftype *symbol_name_compare
1244 = language_def (t_lang)->get_symbol_name_matcher (lookup_name);
1246 t = check_typedef (t);
1248 /* Loop over each method name. At this level, all overloads of a name
1249 are counted as a single name. There is an inner loop which loops over
1250 each overload. */
1252 for (method_counter = TYPE_NFN_FIELDS (t) - 1;
1253 method_counter >= 0;
1254 --method_counter)
1256 const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
1258 if (symbol_name_compare (method_name, lookup_name, NULL))
1260 int field_counter;
1262 for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
1263 - 1);
1264 field_counter >= 0;
1265 --field_counter)
1267 struct fn_field *f;
1268 const char *phys_name;
1270 f = TYPE_FN_FIELDLIST1 (t, method_counter);
1271 if (TYPE_FN_FIELD_STUB (f, field_counter))
1272 continue;
1273 phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
1274 result_names->push_back (phys_name);
1280 for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
1281 superclasses->push_back (TYPE_BASECLASS (t, ibase));
1284 /* The string equivalent of find_toplevel_char. Returns a pointer
1285 to the location of NEEDLE in HAYSTACK, ignoring any occurrences
1286 inside "()" and "<>". Returns NULL if NEEDLE was not found. */
1288 static const char *
1289 find_toplevel_string (const char *haystack, const char *needle)
1291 const char *s = haystack;
1295 s = find_toplevel_char (s, *needle);
1297 if (s != NULL)
1299 /* Found first char in HAYSTACK; check rest of string. */
1300 if (startswith (s, needle))
1301 return s;
1303 /* Didn't find it; loop over HAYSTACK, looking for the next
1304 instance of the first character of NEEDLE. */
1305 ++s;
1308 while (s != NULL && *s != '\0');
1310 /* NEEDLE was not found in HAYSTACK. */
1311 return NULL;
1314 /* Convert CANONICAL to its string representation using
1315 symtab_to_fullname for SYMTAB. */
1317 static std::string
1318 canonical_to_fullform (const struct linespec_canonical_name *canonical)
1320 if (canonical->symtab == NULL)
1321 return canonical->suffix;
1322 else
1323 return string_printf ("%s:%s", symtab_to_fullname (canonical->symtab),
1324 canonical->suffix);
1327 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
1328 and store the result in SELF->CANONICAL. */
1330 static void
1331 filter_results (struct linespec_state *self,
1332 std::vector<symtab_and_line> *result,
1333 const std::vector<const char *> &filters)
1335 for (const char *name : filters)
1337 linespec_sals lsal;
1339 for (size_t j = 0; j < result->size (); ++j)
1341 const struct linespec_canonical_name *canonical;
1343 canonical = &self->canonical_names[j];
1344 std::string fullform = canonical_to_fullform (canonical);
1346 if (name == fullform)
1347 lsal.sals.push_back ((*result)[j]);
1350 if (!lsal.sals.empty ())
1352 lsal.canonical = xstrdup (name);
1353 self->canonical->lsals.push_back (std::move (lsal));
1357 self->canonical->pre_expanded = 0;
1360 /* Store RESULT into SELF->CANONICAL. */
1362 static void
1363 convert_results_to_lsals (struct linespec_state *self,
1364 std::vector<symtab_and_line> *result)
1366 struct linespec_sals lsal;
1368 lsal.canonical = NULL;
1369 lsal.sals = std::move (*result);
1370 self->canonical->lsals.push_back (std::move (lsal));
1373 /* A structure that contains two string representations of a struct
1374 linespec_canonical_name:
1375 - one where the symtab's fullname is used;
1376 - one where the filename followed the "set filename-display"
1377 setting. */
1379 struct decode_line_2_item
1381 decode_line_2_item (std::string &&fullform_, std::string &&displayform_,
1382 bool selected_)
1383 : fullform (std::move (fullform_)),
1384 displayform (std::move (displayform_)),
1385 selected (selected_)
1389 /* Used for sorting. */
1390 bool operator< (const decode_line_2_item &other) const
1392 if (displayform != other.displayform)
1393 return displayform < other.displayform;
1394 return fullform < other.fullform;
1397 /* The form using symtab_to_fullname. */
1398 std::string fullform;
1400 /* The form using symtab_to_filename_for_display. */
1401 std::string displayform;
1403 /* Field is initialized to zero and it is set to one if the user
1404 requested breakpoint for this entry. */
1405 unsigned int selected : 1;
1408 /* Handle multiple results in RESULT depending on SELECT_MODE. This
1409 will either return normally, throw an exception on multiple
1410 results, or present a menu to the user. On return, the SALS vector
1411 in SELF->CANONICAL is set up properly. */
1413 static void
1414 decode_line_2 (struct linespec_state *self,
1415 std::vector<symtab_and_line> *result,
1416 const char *select_mode)
1418 const char *args;
1419 const char *prompt;
1420 int i;
1421 std::vector<const char *> filters;
1422 std::vector<struct decode_line_2_item> items;
1424 gdb_assert (select_mode != multiple_symbols_all);
1425 gdb_assert (self->canonical != NULL);
1426 gdb_assert (!result->empty ());
1428 /* Prepare ITEMS array. */
1429 for (i = 0; i < result->size (); ++i)
1431 const struct linespec_canonical_name *canonical;
1432 std::string displayform;
1434 canonical = &self->canonical_names[i];
1435 gdb_assert (canonical->suffix != NULL);
1437 std::string fullform = canonical_to_fullform (canonical);
1439 if (canonical->symtab == NULL)
1440 displayform = canonical->suffix;
1441 else
1443 const char *fn_for_display;
1445 fn_for_display = symtab_to_filename_for_display (canonical->symtab);
1446 displayform = string_printf ("%s:%s", fn_for_display,
1447 canonical->suffix);
1450 items.emplace_back (std::move (fullform), std::move (displayform),
1451 false);
1454 /* Sort the list of method names. */
1455 std::sort (items.begin (), items.end ());
1457 /* Remove entries with the same FULLFORM. */
1458 items.erase (std::unique (items.begin (), items.end (),
1459 [] (const struct decode_line_2_item &a,
1460 const struct decode_line_2_item &b)
1462 return a.fullform == b.fullform;
1464 items.end ());
1466 if (select_mode == multiple_symbols_cancel && items.size () > 1)
1467 error (_("canceled because the command is ambiguous\n"
1468 "See set/show multiple-symbol."));
1470 if (select_mode == multiple_symbols_all || items.size () == 1)
1472 convert_results_to_lsals (self, result);
1473 return;
1476 printf_unfiltered (_("[0] cancel\n[1] all\n"));
1477 for (i = 0; i < items.size (); i++)
1478 printf_unfiltered ("[%d] %s\n", i + 2, items[i].displayform.c_str ());
1480 prompt = getenv ("PS2");
1481 if (prompt == NULL)
1483 prompt = "> ";
1486 std::string buffer;
1487 args = command_line_input (buffer, prompt, "overload-choice");
1489 if (args == 0 || *args == 0)
1490 error_no_arg (_("one or more choice numbers"));
1492 number_or_range_parser parser (args);
1493 while (!parser.finished ())
1495 int num = parser.get_number ();
1497 if (num == 0)
1498 error (_("canceled"));
1499 else if (num == 1)
1501 /* We intentionally make this result in a single breakpoint,
1502 contrary to what older versions of gdb did. The
1503 rationale is that this lets a user get the
1504 multiple_symbols_all behavior even with the 'ask'
1505 setting; and he can get separate breakpoints by entering
1506 "2-57" at the query. */
1507 convert_results_to_lsals (self, result);
1508 return;
1511 num -= 2;
1512 if (num >= items.size ())
1513 printf_unfiltered (_("No choice number %d.\n"), num);
1514 else
1516 struct decode_line_2_item *item = &items[num];
1518 if (!item->selected)
1520 filters.push_back (item->fullform.c_str ());
1521 item->selected = 1;
1523 else
1525 printf_unfiltered (_("duplicate request for %d ignored.\n"),
1526 num + 2);
1531 filter_results (self, result, filters);
1536 /* The parser of linespec itself. */
1538 /* Throw an appropriate error when SYMBOL is not found (optionally in
1539 FILENAME). */
1541 [[noreturn]] static void
1542 symbol_not_found_error (const char *symbol, const char *filename)
1544 if (symbol == NULL)
1545 symbol = "";
1547 if (!have_full_symbols (current_program_space)
1548 && !have_partial_symbols (current_program_space)
1549 && !have_minimal_symbols (current_program_space))
1550 throw_error (NOT_FOUND_ERROR,
1551 _("No symbol table is loaded. Use the \"file\" command."));
1553 /* If SYMBOL starts with '$', the user attempted to either lookup
1554 a function/variable in his code starting with '$' or an internal
1555 variable of that name. Since we do not know which, be concise and
1556 explain both possibilities. */
1557 if (*symbol == '$')
1559 if (filename)
1560 throw_error (NOT_FOUND_ERROR,
1561 _("Undefined convenience variable or function \"%s\" "
1562 "not defined in \"%s\"."), symbol, filename);
1563 else
1564 throw_error (NOT_FOUND_ERROR,
1565 _("Undefined convenience variable or function \"%s\" "
1566 "not defined."), symbol);
1568 else
1570 if (filename)
1571 throw_error (NOT_FOUND_ERROR,
1572 _("Function \"%s\" not defined in \"%s\"."),
1573 symbol, filename);
1574 else
1575 throw_error (NOT_FOUND_ERROR,
1576 _("Function \"%s\" not defined."), symbol);
1580 /* Throw an appropriate error when an unexpected token is encountered
1581 in the input. */
1583 [[noreturn]] static void
1584 unexpected_linespec_error (linespec_parser *parser)
1586 linespec_token token;
1587 static const char * token_type_strings[]
1588 = {"keyword", "colon", "string", "number", "comma", "end of input"};
1590 /* Get the token that generated the error. */
1591 token = linespec_lexer_lex_one (parser);
1593 /* Finally, throw the error. */
1594 if (token.type == LSTOKEN_STRING || token.type == LSTOKEN_NUMBER
1595 || token.type == LSTOKEN_KEYWORD)
1597 gdb::unique_xmalloc_ptr<char> string = copy_token_string (token);
1598 throw_error (GENERIC_ERROR,
1599 _("malformed linespec error: unexpected %s, \"%s\""),
1600 token_type_strings[token.type], string.get ());
1602 else
1603 throw_error (GENERIC_ERROR,
1604 _("malformed linespec error: unexpected %s"),
1605 token_type_strings[token.type]);
1608 /* Throw an undefined label error. */
1610 [[noreturn]] static void
1611 undefined_label_error (const char *function, const char *label)
1613 if (function != NULL)
1614 throw_error (NOT_FOUND_ERROR,
1615 _("No label \"%s\" defined in function \"%s\"."),
1616 label, function);
1617 else
1618 throw_error (NOT_FOUND_ERROR,
1619 _("No label \"%s\" defined in current function."),
1620 label);
1623 /* Throw a source file not found error. */
1625 [[noreturn]] static void
1626 source_file_not_found_error (const char *name)
1628 throw_error (NOT_FOUND_ERROR, _("No source file named %s."), name);
1631 /* Unless at EIO, save the current stream position as completion word
1632 point, and consume the next token. */
1634 static linespec_token
1635 save_stream_and_consume_token (linespec_parser *parser)
1637 if (linespec_lexer_peek_token (parser).type != LSTOKEN_EOI)
1638 parser->completion_word = parser->lexer.stream;
1639 return linespec_lexer_consume_token (parser);
1642 /* See description in linespec.h. */
1644 struct line_offset
1645 linespec_parse_line_offset (const char *string)
1647 const char *start = string;
1648 struct line_offset line_offset;
1650 if (*string == '+')
1652 line_offset.sign = LINE_OFFSET_PLUS;
1653 ++string;
1655 else if (*string == '-')
1657 line_offset.sign = LINE_OFFSET_MINUS;
1658 ++string;
1660 else
1661 line_offset.sign = LINE_OFFSET_NONE;
1663 if (*string != '\0' && !isdigit (*string))
1664 error (_("malformed line offset: \"%s\""), start);
1666 /* Right now, we only allow base 10 for offsets. */
1667 line_offset.offset = atoi (string);
1668 return line_offset;
1671 /* In completion mode, if the user is still typing the number, there's
1672 no possible completion to offer. But if there's already input past
1673 the number, setup to expect NEXT. */
1675 static void
1676 set_completion_after_number (linespec_parser *parser,
1677 linespec_complete_what next)
1679 if (*parser->lexer.stream == ' ')
1681 parser->completion_word = skip_spaces (parser->lexer.stream + 1);
1682 parser->complete_what = next;
1684 else
1686 parser->completion_word = parser->lexer.stream;
1687 parser->complete_what = linespec_complete_what::NOTHING;
1691 /* Parse the basic_spec in PARSER's input. */
1693 static void
1694 linespec_parse_basic (linespec_parser *parser)
1696 gdb::unique_xmalloc_ptr<char> name;
1697 linespec_token token;
1699 /* Get the next token. */
1700 token = linespec_lexer_lex_one (parser);
1702 /* If it is EOI or KEYWORD, issue an error. */
1703 if (token.type == LSTOKEN_KEYWORD)
1705 parser->complete_what = linespec_complete_what::NOTHING;
1706 unexpected_linespec_error (parser);
1708 else if (token.type == LSTOKEN_EOI)
1710 unexpected_linespec_error (parser);
1712 /* If it is a LSTOKEN_NUMBER, we have an offset. */
1713 else if (token.type == LSTOKEN_NUMBER)
1715 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1717 /* Record the line offset and get the next token. */
1718 name = copy_token_string (token);
1719 parser->result.explicit_loc.line_offset
1720 = linespec_parse_line_offset (name.get ());
1722 /* Get the next token. */
1723 token = linespec_lexer_consume_token (parser);
1725 /* If the next token is a comma, stop parsing and return. */
1726 if (token.type == LSTOKEN_COMMA)
1728 parser->complete_what = linespec_complete_what::NOTHING;
1729 return;
1732 /* If the next token is anything but EOI or KEYWORD, issue
1733 an error. */
1734 if (token.type != LSTOKEN_KEYWORD && token.type != LSTOKEN_EOI)
1735 unexpected_linespec_error (parser);
1738 if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1739 return;
1741 /* Next token must be LSTOKEN_STRING. */
1742 if (token.type != LSTOKEN_STRING)
1744 parser->complete_what = linespec_complete_what::NOTHING;
1745 unexpected_linespec_error (parser);
1748 /* The current token will contain the name of a function, method,
1749 or label. */
1750 name = copy_token_string (token);
1752 if (parser->completion_tracker != NULL)
1754 /* If the function name ends with a ":", then this may be an
1755 incomplete "::" scope operator instead of a label separator.
1756 E.g.,
1757 "b klass:<tab>"
1758 which should expand to:
1759 "b klass::method()"
1761 Do a tentative completion assuming the later. If we find
1762 completions, advance the stream past the colon token and make
1763 it part of the function name/token. */
1765 if (!parser->completion_quote_char
1766 && strcmp (parser->lexer.stream, ":") == 0)
1768 completion_tracker tmp_tracker (false);
1769 const char *source_filename
1770 = parser->result.explicit_loc.source_filename.get ();
1771 symbol_name_match_type match_type
1772 = parser->result.explicit_loc.func_name_match_type;
1774 linespec_complete_function (tmp_tracker,
1775 parser->completion_word,
1776 match_type,
1777 source_filename);
1779 if (tmp_tracker.have_completions ())
1781 parser->lexer.stream++;
1782 token.data.string.length++;
1784 name.reset (savestring (parser->completion_word,
1785 (parser->lexer.stream
1786 - parser->completion_word)));
1790 parser->result.explicit_loc.function_name = std::move (name);
1792 else
1794 std::vector<block_symbol> symbols;
1795 std::vector<bound_minimal_symbol> minimal_symbols;
1797 /* Try looking it up as a function/method. */
1798 find_linespec_symbols (&parser->state,
1799 parser->result.file_symtabs, name.get (),
1800 parser->result.explicit_loc.func_name_match_type,
1801 &symbols, &minimal_symbols);
1803 if (!symbols.empty () || !minimal_symbols.empty ())
1805 parser->result.function_symbols = std::move (symbols);
1806 parser->result.minimal_symbols = std::move (minimal_symbols);
1807 parser->result.explicit_loc.function_name = std::move (name);
1809 else
1811 /* NAME was not a function or a method. So it must be a label
1812 name or user specified variable like "break foo.c:$zippo". */
1813 std::vector<block_symbol> labels
1814 = find_label_symbols (&parser->state, {}, &symbols,
1815 name.get ());
1817 if (!labels.empty ())
1819 parser->result.labels.label_symbols = std::move (labels);
1820 parser->result.labels.function_symbols = std::move (symbols);
1821 parser->result.explicit_loc.label_name = std::move (name);
1823 else if (token.type == LSTOKEN_STRING
1824 && *token.data.string.ptr == '$')
1826 /* User specified a convenience variable or history value. */
1827 parser->result.explicit_loc.line_offset
1828 = linespec_parse_variable (&parser->state, name.get ());
1830 if (parser->result.explicit_loc.line_offset.sign
1831 == LINE_OFFSET_UNKNOWN)
1833 /* The user-specified variable was not valid. Do not
1834 throw an error here. parse_linespec will do it for us. */
1835 parser->result.explicit_loc.function_name = std::move (name);
1836 return;
1839 else
1841 /* The name is also not a label. Abort parsing. Do not throw
1842 an error here. parse_linespec will do it for us. */
1844 /* Save a copy of the name we were trying to lookup. */
1845 parser->result.explicit_loc.function_name = std::move (name);
1846 return;
1851 int previous_qc = parser->completion_quote_char;
1853 /* Get the next token. */
1854 token = linespec_lexer_consume_token (parser);
1856 if (token.type == LSTOKEN_EOI)
1858 if (previous_qc && !parser->completion_quote_char)
1859 parser->complete_what = linespec_complete_what::KEYWORD;
1861 else if (token.type == LSTOKEN_COLON)
1863 /* User specified a label or a lineno. */
1864 token = linespec_lexer_consume_token (parser);
1866 if (token.type == LSTOKEN_NUMBER)
1868 /* User specified an offset. Record the line offset and
1869 get the next token. */
1870 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1872 name = copy_token_string (token);
1873 parser->result.explicit_loc.line_offset
1874 = linespec_parse_line_offset (name.get ());
1876 /* Get the next token. */
1877 token = linespec_lexer_consume_token (parser);
1879 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
1881 parser->complete_what = linespec_complete_what::LABEL;
1883 else if (token.type == LSTOKEN_STRING)
1885 parser->complete_what = linespec_complete_what::LABEL;
1887 /* If we have text after the label separated by whitespace
1888 (e.g., "b func():lab i<tab>"), don't consider it part of
1889 the label. In completion mode that should complete to
1890 "if", in normal mode, the 'i' should be treated as
1891 garbage. */
1892 if (parser->completion_quote_char == '\0')
1894 const char *ptr = token.data.string.ptr;
1895 for (size_t i = 0; i < token.data.string.length; i++)
1897 if (ptr[i] == ' ')
1899 token.data.string.length = i;
1900 parser->lexer.stream = skip_spaces (ptr + i + 1);
1901 break;
1906 if (parser->completion_tracker != NULL)
1908 if (parser->lexer.stream[-1] == ' ')
1910 parser->completion_word = parser->lexer.stream;
1911 parser->complete_what = linespec_complete_what::KEYWORD;
1914 else
1916 std::vector<block_symbol> symbols;
1918 /* Grab a copy of the label's name and look it up. */
1919 name = copy_token_string (token);
1920 std::vector<block_symbol> labels
1921 = find_label_symbols (&parser->state,
1922 parser->result.function_symbols,
1923 &symbols, name.get ());
1925 if (!labels.empty ())
1927 parser->result.labels.label_symbols = std::move (labels);
1928 parser->result.labels.function_symbols = std::move (symbols);
1929 parser->result.explicit_loc.label_name = std::move (name);
1931 else
1933 /* We don't know what it was, but it isn't a label. */
1934 undefined_label_error
1935 (parser->result.explicit_loc.function_name.get (),
1936 name.get ());
1941 /* Check for a line offset. */
1942 token = save_stream_and_consume_token (parser);
1943 if (token.type == LSTOKEN_COLON)
1945 /* Get the next token. */
1946 token = linespec_lexer_consume_token (parser);
1948 /* It must be a line offset. */
1949 if (token.type != LSTOKEN_NUMBER)
1950 unexpected_linespec_error (parser);
1952 /* Record the line offset and get the next token. */
1953 name = copy_token_string (token);
1955 parser->result.explicit_loc.line_offset
1956 = linespec_parse_line_offset (name.get ());
1958 /* Get the next token. */
1959 token = linespec_lexer_consume_token (parser);
1962 else
1964 /* Trailing ':' in the input. Issue an error. */
1965 unexpected_linespec_error (parser);
1970 /* Canonicalize the linespec contained in LS. The result is saved into
1971 STATE->canonical. This function handles both linespec and explicit
1972 locations. */
1974 static void
1975 canonicalize_linespec (struct linespec_state *state, const linespec *ls)
1977 /* If canonicalization was not requested, no need to do anything. */
1978 if (!state->canonical)
1979 return;
1981 /* Save everything as an explicit location. */
1982 state->canonical->locspec = ls->explicit_loc.clone ();
1983 explicit_location_spec *explicit_loc
1984 = as_explicit_location_spec (state->canonical->locspec.get ());
1986 if (explicit_loc->label_name != NULL)
1988 state->canonical->special_display = 1;
1990 if (explicit_loc->function_name == NULL)
1992 /* No function was specified, so add the symbol name. */
1993 gdb_assert (ls->labels.function_symbols.size () == 1);
1994 block_symbol s = ls->labels.function_symbols.front ();
1995 explicit_loc->function_name
1996 = make_unique_xstrdup (s.symbol->natural_name ());
2000 /* If this location originally came from a linespec, save a string
2001 representation of it for display and saving to file. */
2002 if (state->is_linespec)
2003 explicit_loc->set_string (explicit_loc->to_linespec ());
2006 /* Given a line offset in LS, construct the relevant SALs. */
2008 static std::vector<symtab_and_line>
2009 create_sals_line_offset (struct linespec_state *self,
2010 linespec *ls)
2012 int use_default = 0;
2014 /* This is where we need to make sure we have good defaults.
2015 We must guarantee that this section of code is never executed
2016 when we are called with just a function name, since
2017 set_default_source_symtab_and_line uses
2018 select_source_symtab that calls us with such an argument. */
2020 if (ls->file_symtabs.size () == 1
2021 && ls->file_symtabs.front () == nullptr)
2023 set_current_program_space (self->program_space);
2025 /* Make sure we have at least a default source line. */
2026 set_default_source_symtab_and_line ();
2027 initialize_defaults (&self->default_symtab, &self->default_line);
2028 ls->file_symtabs
2029 = collect_symtabs_from_filename (self->default_symtab->filename,
2030 self->search_pspace);
2031 use_default = 1;
2034 symtab_and_line val;
2035 val.line = ls->explicit_loc.line_offset.offset;
2036 switch (ls->explicit_loc.line_offset.sign)
2038 case LINE_OFFSET_PLUS:
2039 if (ls->explicit_loc.line_offset.offset == 0)
2040 val.line = 5;
2041 if (use_default)
2042 val.line = self->default_line + val.line;
2043 break;
2045 case LINE_OFFSET_MINUS:
2046 if (ls->explicit_loc.line_offset.offset == 0)
2047 val.line = 15;
2048 if (use_default)
2049 val.line = self->default_line - val.line;
2050 else
2051 val.line = -val.line;
2052 break;
2054 case LINE_OFFSET_NONE:
2055 break; /* No need to adjust val.line. */
2058 std::vector<symtab_and_line> values;
2059 if (self->list_mode)
2060 values = decode_digits_list_mode (self, ls, val);
2061 else
2063 const linetable_entry *best_entry = NULL;
2064 int i, j;
2066 /* True if the provided line gave an exact match. False if we had to
2067 search for the next following line with code. */
2068 bool was_exact = true;
2070 std::vector<symtab_and_line> intermediate_results
2071 = decode_digits_ordinary (self, ls, val.line, &best_entry);
2072 if (intermediate_results.empty () && best_entry != NULL)
2074 was_exact = false;
2075 intermediate_results = decode_digits_ordinary (self, ls,
2076 best_entry->line,
2077 &best_entry);
2080 /* For optimized code, the compiler can scatter one source line
2081 across disjoint ranges of PC values, even when no duplicate
2082 functions or inline functions are involved. For example,
2083 'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
2084 function can result in two PC ranges. In this case, we don't
2085 want to set a breakpoint on the first PC of each range. To filter
2086 such cases, we use containing blocks -- for each PC found
2087 above, we see if there are other PCs that are in the same
2088 block. If yes, the other PCs are filtered out. */
2090 gdb::def_vector<int> filter (intermediate_results.size ());
2091 gdb::def_vector<const block *> blocks (intermediate_results.size ());
2093 for (i = 0; i < intermediate_results.size (); ++i)
2095 set_current_program_space (intermediate_results[i].pspace);
2097 filter[i] = 1;
2098 blocks[i] = block_for_pc_sect (intermediate_results[i].pc,
2099 intermediate_results[i].section);
2102 for (i = 0; i < intermediate_results.size (); ++i)
2104 if (blocks[i] != NULL)
2105 for (j = i + 1; j < intermediate_results.size (); ++j)
2107 if (blocks[j] == blocks[i])
2109 filter[j] = 0;
2110 break;
2115 for (i = 0; i < intermediate_results.size (); ++i)
2116 if (filter[i])
2118 struct symbol *sym = (blocks[i]
2119 ? blocks[i]->containing_function ()
2120 : NULL);
2121 symtab_and_line &sal = intermediate_results[i];
2123 /* Don't consider a match if:
2125 - the provided line did not give an exact match (so we
2126 started looking for lines below until we found one with
2127 code associated to it)
2128 - the found location is exactly the start of a function
2129 - the provided line is above the declaration line of the
2130 function
2132 Consider the following source:
2134 10 } // end of a previous function
2136 12 int
2137 13 main (void)
2138 14 {
2139 15 int i = 1;
2141 17 return 0;
2142 18 }
2144 The intent of this heuristic is that a breakpoint requested on
2145 line 11 and 12 will not result in a breakpoint on main, but a
2146 breakpoint on line 13 will. A breakpoint requested on the empty
2147 line 16 will also result in a breakpoint in main, at line 17. */
2148 if (!was_exact
2149 && sym != nullptr
2150 && sym->aclass () == LOC_BLOCK
2151 && sal.pc == sym->value_block ()->entry_pc ()
2152 && val.line < sym->line ())
2153 continue;
2155 if (self->funfirstline)
2156 skip_prologue_sal (&sal);
2158 sal.symbol = sym;
2159 add_sal_to_sals (self, &values, &sal,
2160 sym ? sym->natural_name () : NULL, 0);
2164 if (values.empty ())
2166 if (ls->explicit_loc.source_filename)
2167 throw_error (NOT_FOUND_ERROR,
2168 _("No compiled code for line %d in file \"%s\"."),
2169 val.line, ls->explicit_loc.source_filename.get ());
2170 else
2171 throw_error (NOT_FOUND_ERROR,
2172 _("No compiled code for line %d in the current file."),
2173 val.line);
2176 return values;
2179 /* Convert the given ADDRESS into SaLs. */
2181 static std::vector<symtab_and_line>
2182 convert_address_location_to_sals (struct linespec_state *self,
2183 CORE_ADDR address)
2185 symtab_and_line sal = find_pc_line (address, 0);
2186 sal.pc = address;
2187 sal.section = find_pc_overlay (address);
2188 sal.explicit_pc = 1;
2189 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
2191 std::vector<symtab_and_line> sals;
2192 add_sal_to_sals (self, &sals, &sal, core_addr_to_string (address), 1);
2194 return sals;
2197 /* Create and return SALs from the linespec LS. */
2199 static std::vector<symtab_and_line>
2200 convert_linespec_to_sals (struct linespec_state *state, linespec *ls)
2202 std::vector<symtab_and_line> sals;
2204 if (!ls->labels.label_symbols.empty ())
2206 /* We have just a bunch of functions/methods or labels. */
2207 struct symtab_and_line sal;
2209 for (const auto &sym : ls->labels.label_symbols)
2211 struct program_space *pspace
2212 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace ();
2214 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2215 && maybe_add_address (state->addr_set, pspace, sal.pc))
2216 add_sal_to_sals (state, &sals, &sal,
2217 sym.symbol->natural_name (), 0);
2220 else if (!ls->function_symbols.empty () || !ls->minimal_symbols.empty ())
2222 /* We have just a bunch of functions and/or methods. */
2223 if (!ls->function_symbols.empty ())
2225 /* Sort symbols so that symbols with the same program space are next
2226 to each other. */
2227 std::sort (ls->function_symbols.begin (),
2228 ls->function_symbols.end (),
2229 compare_symbols);
2231 for (const auto &sym : ls->function_symbols)
2233 program_space *pspace
2234 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace ();
2235 set_current_program_space (pspace);
2237 /* Don't skip to the first line of the function if we
2238 had found an ifunc minimal symbol for this function,
2239 because that means that this function is an ifunc
2240 resolver with the same name as the ifunc itself. */
2241 bool found_ifunc = false;
2243 if (state->funfirstline
2244 && !ls->minimal_symbols.empty ()
2245 && sym.symbol->aclass () == LOC_BLOCK)
2247 const CORE_ADDR addr
2248 = sym.symbol->value_block ()->entry_pc ();
2250 for (const auto &elem : ls->minimal_symbols)
2252 if (elem.minsym->type () == mst_text_gnu_ifunc
2253 || elem.minsym->type () == mst_data_gnu_ifunc)
2255 CORE_ADDR msym_addr = elem.value_address ();
2256 if (elem.minsym->type () == mst_data_gnu_ifunc)
2258 struct gdbarch *gdbarch
2259 = elem.objfile->arch ();
2260 msym_addr
2261 = (gdbarch_convert_from_func_ptr_addr
2262 (gdbarch,
2263 msym_addr,
2264 current_inferior ()->top_target ()));
2267 if (msym_addr == addr)
2269 found_ifunc = true;
2270 break;
2276 if (!found_ifunc)
2278 symtab_and_line sal;
2279 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2280 && maybe_add_address (state->addr_set, pspace, sal.pc))
2281 add_sal_to_sals (state, &sals, &sal,
2282 sym.symbol->natural_name (), 0);
2287 if (!ls->minimal_symbols.empty ())
2289 /* Sort minimal symbols by program space, too */
2290 std::sort (ls->minimal_symbols.begin (),
2291 ls->minimal_symbols.end (),
2292 compare_msymbols);
2294 for (const auto &elem : ls->minimal_symbols)
2296 program_space *pspace = elem.objfile->pspace ();
2297 set_current_program_space (pspace);
2298 minsym_found (state, elem.objfile, elem.minsym, &sals);
2302 else if (ls->explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2304 /* Only an offset was specified. */
2305 sals = create_sals_line_offset (state, ls);
2307 /* Make sure we have a filename for canonicalization. */
2308 if (ls->explicit_loc.source_filename == NULL)
2310 const char *filename = state->default_symtab->filename;
2312 /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2313 form so that displaying SOURCE_FILENAME can follow the current
2314 FILENAME_DISPLAY_STRING setting. But as it is used only rarely
2315 it has been kept for code simplicity only in absolute form. */
2316 ls->explicit_loc.source_filename = make_unique_xstrdup (filename);
2319 else
2321 /* We haven't found any results... */
2322 return sals;
2325 canonicalize_linespec (state, ls);
2327 if (!sals.empty () && state->canonical != NULL)
2328 state->canonical->pre_expanded = 1;
2330 return sals;
2333 /* Build RESULT from the explicit location spec components
2334 SOURCE_FILENAME, FUNCTION_NAME, LABEL_NAME and LINE_OFFSET. */
2336 static void
2337 convert_explicit_location_spec_to_linespec
2338 (struct linespec_state *self,
2339 linespec *result,
2340 const char *source_filename,
2341 const char *function_name,
2342 symbol_name_match_type fname_match_type,
2343 const char *label_name,
2344 struct line_offset line_offset)
2346 std::vector<bound_minimal_symbol> minimal_symbols;
2348 result->explicit_loc.func_name_match_type = fname_match_type;
2350 if (source_filename != NULL)
2354 result->file_symtabs
2355 = symtabs_from_filename (source_filename, self->search_pspace);
2357 catch (const gdb_exception_error &except)
2359 source_file_not_found_error (source_filename);
2361 result->explicit_loc.source_filename
2362 = make_unique_xstrdup (source_filename);
2364 else
2366 /* A NULL entry means to use the default symtab. */
2367 result->file_symtabs.push_back (nullptr);
2370 if (function_name != NULL)
2372 std::vector<block_symbol> symbols;
2374 find_linespec_symbols (self, result->file_symtabs,
2375 function_name, fname_match_type,
2376 &symbols, &minimal_symbols);
2378 if (symbols.empty () && minimal_symbols.empty ())
2379 symbol_not_found_error (function_name,
2380 result->explicit_loc.source_filename.get ());
2382 result->explicit_loc.function_name
2383 = make_unique_xstrdup (function_name);
2384 result->function_symbols = std::move (symbols);
2385 result->minimal_symbols = std::move (minimal_symbols);
2388 if (label_name != NULL)
2390 std::vector<block_symbol> symbols;
2391 std::vector<block_symbol> labels
2392 = find_label_symbols (self, result->function_symbols,
2393 &symbols, label_name);
2395 if (labels.empty ())
2396 undefined_label_error (result->explicit_loc.function_name.get (),
2397 label_name);
2399 result->explicit_loc.label_name = make_unique_xstrdup (label_name);
2400 result->labels.label_symbols = labels;
2401 result->labels.function_symbols = std::move (symbols);
2404 if (line_offset.sign != LINE_OFFSET_UNKNOWN)
2405 result->explicit_loc.line_offset = line_offset;
2408 /* Convert the explicit location EXPLICIT_LOC into SaLs. */
2410 static std::vector<symtab_and_line>
2411 convert_explicit_location_spec_to_sals
2412 (struct linespec_state *self,
2413 linespec *result,
2414 const explicit_location_spec *explicit_spec)
2416 convert_explicit_location_spec_to_linespec (self, result,
2417 explicit_spec->source_filename.get (),
2418 explicit_spec->function_name.get (),
2419 explicit_spec->func_name_match_type,
2420 explicit_spec->label_name.get (),
2421 explicit_spec->line_offset);
2422 return convert_linespec_to_sals (self, result);
2425 /* Parse a string that specifies a linespec.
2427 The basic grammar of linespecs:
2429 linespec -> var_spec | basic_spec
2430 var_spec -> '$' (STRING | NUMBER)
2432 basic_spec -> file_offset_spec | function_spec | label_spec
2433 file_offset_spec -> opt_file_spec offset_spec
2434 function_spec -> opt_file_spec function_name_spec opt_label_spec
2435 label_spec -> label_name_spec
2437 opt_file_spec -> "" | file_name_spec ':'
2438 opt_label_spec -> "" | ':' label_name_spec
2440 file_name_spec -> STRING
2441 function_name_spec -> STRING
2442 label_name_spec -> STRING
2443 function_name_spec -> STRING
2444 offset_spec -> NUMBER
2445 -> '+' NUMBER
2446 -> '-' NUMBER
2448 This may all be followed by several keywords such as "if EXPR",
2449 which we ignore.
2451 A comma will terminate parsing.
2453 The function may be an undebuggable function found in minimal symbol table.
2455 If the argument FUNFIRSTLINE is nonzero, we want the first line
2456 of real code inside a function when a function is specified, and it is
2457 not OK to specify a variable or type to get its line number.
2459 DEFAULT_SYMTAB specifies the file to use if none is specified.
2460 It defaults to current_source_symtab.
2461 DEFAULT_LINE specifies the line number to use for relative
2462 line numbers (that start with signs). Defaults to current_source_line.
2463 If CANONICAL is non-NULL, store an array of strings containing the canonical
2464 line specs there if necessary. Currently overloaded member functions and
2465 line numbers or static functions without a filename yield a canonical
2466 line spec. The array and the line spec strings are allocated on the heap,
2467 it is the callers responsibility to free them.
2469 Note that it is possible to return zero for the symtab
2470 if no file is validly specified. Callers must check that.
2471 Also, the line number returned may be invalid. */
2473 /* Parse the linespec in ARG, which must not be nullptr. MATCH_TYPE
2474 indicates how function names should be matched. */
2476 static std::vector<symtab_and_line>
2477 parse_linespec (linespec_parser *parser, const char *arg,
2478 symbol_name_match_type match_type)
2480 gdb_assert (arg != nullptr);
2482 struct gdb_exception file_exception;
2484 /* A special case to start. It has become quite popular for
2485 IDEs to work around bugs in the previous parser by quoting
2486 the entire linespec, so we attempt to deal with this nicely. */
2487 parser->is_quote_enclosed = 0;
2488 if (parser->completion_tracker == NULL
2489 && !is_ada_operator (arg)
2490 && *arg != '\0'
2491 && strchr (linespec_quote_characters, *arg) != NULL)
2493 const char *end = skip_quote_char (arg + 1, *arg);
2494 if (end != NULL && is_closing_quote_enclosed (end))
2496 /* Here's the special case. Skip ARG past the initial
2497 quote. */
2498 ++arg;
2499 parser->is_quote_enclosed = 1;
2503 parser->lexer.saved_arg = arg;
2504 parser->lexer.stream = arg;
2505 parser->completion_word = arg;
2506 parser->complete_what = linespec_complete_what::FUNCTION;
2507 parser->result.explicit_loc.func_name_match_type = match_type;
2509 /* Initialize the default symtab and line offset. */
2510 initialize_defaults (&parser->state.default_symtab,
2511 &parser->state.default_line);
2513 /* Objective-C shortcut. */
2514 if (parser->completion_tracker == NULL)
2516 std::vector<symtab_and_line> values
2517 = decode_objc (&parser->state, &parser->result, arg);
2518 if (!values.empty ())
2519 return values;
2521 else
2523 /* "-"/"+" is either an objc selector, or a number. There's
2524 nothing to complete the latter to, so just let the caller
2525 complete on functions, which finds objc selectors, if there's
2526 any. */
2527 if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '\0')
2528 return {};
2531 /* Start parsing. */
2533 /* Get the first token. */
2534 linespec_token token = linespec_lexer_consume_token (parser);
2536 /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER. */
2537 if (token.type == LSTOKEN_STRING && *token.data.string.ptr == '$')
2539 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2540 if (parser->completion_tracker == NULL)
2541 parser->result.file_symtabs.push_back (nullptr);
2543 /* User specified a convenience variable or history value. */
2544 gdb::unique_xmalloc_ptr<char> var = copy_token_string (token);
2545 parser->result.explicit_loc.line_offset
2546 = linespec_parse_variable (&parser->state, var.get ());
2548 /* If a line_offset wasn't found (VAR is the name of a user
2549 variable/function), then skip to normal symbol processing. */
2550 if (parser->result.explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2552 /* Consume this token. */
2553 linespec_lexer_consume_token (parser);
2555 goto convert_to_sals;
2558 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
2560 /* Let the default linespec_complete_what::FUNCTION kick in. */
2561 unexpected_linespec_error (parser);
2563 else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2565 parser->complete_what = linespec_complete_what::NOTHING;
2566 unexpected_linespec_error (parser);
2569 /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2570 this token cannot represent a filename. */
2571 token = linespec_lexer_peek_token (parser);
2573 if (token.type == LSTOKEN_COLON)
2575 /* Get the current token again and extract the filename. */
2576 token = linespec_lexer_lex_one (parser);
2577 gdb::unique_xmalloc_ptr<char> user_filename = copy_token_string (token);
2579 /* Check if the input is a filename. */
2582 parser->result.file_symtabs
2583 = symtabs_from_filename (user_filename.get (),
2584 parser->state.search_pspace);
2586 catch (gdb_exception_error &ex)
2588 file_exception = std::move (ex);
2591 if (file_exception.reason >= 0)
2593 /* Symtabs were found for the file. Record the filename. */
2594 parser->result.explicit_loc.source_filename = std::move (user_filename);
2596 /* Get the next token. */
2597 token = linespec_lexer_consume_token (parser);
2599 /* This is LSTOKEN_COLON; consume it. */
2600 linespec_lexer_consume_token (parser);
2602 else
2604 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2605 parser->result.file_symtabs.push_back (nullptr);
2608 /* If the next token is not EOI, KEYWORD, or COMMA, issue an error. */
2609 else if (parser->completion_tracker == NULL
2610 && (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2611 && token.type != LSTOKEN_COMMA))
2613 /* TOKEN is the _next_ token, not the one currently in the parser.
2614 Consuming the token will give the correct error message. */
2615 linespec_lexer_consume_token (parser);
2616 unexpected_linespec_error (parser);
2618 else
2620 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2621 parser->result.file_symtabs.push_back (nullptr);
2624 /* Parse the rest of the linespec. */
2625 linespec_parse_basic (parser);
2627 if (parser->completion_tracker == NULL
2628 && parser->result.function_symbols.empty ()
2629 && parser->result.labels.label_symbols.empty ()
2630 && parser->result.explicit_loc.line_offset.sign == LINE_OFFSET_UNKNOWN
2631 && parser->result.minimal_symbols.empty ())
2633 /* The linespec didn't parse. Re-throw the file exception if
2634 there was one. */
2635 if (file_exception.reason < 0)
2636 throw_exception (std::move (file_exception));
2638 /* Otherwise, the symbol is not found. */
2639 symbol_not_found_error
2640 (parser->result.explicit_loc.function_name.get (),
2641 parser->result.explicit_loc.source_filename.get ());
2644 convert_to_sals:
2646 /* Get the last token and record how much of the input was parsed,
2647 if necessary. */
2648 token = linespec_lexer_lex_one (parser);
2649 if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2650 unexpected_linespec_error (parser);
2651 else if (token.type == LSTOKEN_KEYWORD)
2653 /* Setup the completion word past the keyword. Lexing never
2654 advances past a keyword automatically, so skip it
2655 manually. */
2656 parser->completion_word
2657 = skip_spaces (skip_to_space (parser->lexer.stream));
2658 parser->complete_what = linespec_complete_what::EXPRESSION;
2661 /* Convert the data in the parser's result to SALs. */
2662 if (parser->completion_tracker == NULL)
2663 return convert_linespec_to_sals (&parser->state, &parser->result);
2665 return {};
2669 /* A constructor for linespec_state. */
2671 static void
2672 linespec_state_constructor (struct linespec_state *self,
2673 int flags, 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 memset (self, 0, sizeof (*self));
2680 self->language = language;
2681 self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2682 self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2683 self->search_pspace = search_pspace;
2684 self->default_symtab = default_symtab;
2685 self->default_line = default_line;
2686 self->canonical = canonical;
2687 self->program_space = current_program_space;
2688 self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2689 xfree, xcalloc, xfree);
2690 self->is_linespec = 0;
2693 /* Initialize a new linespec parser. */
2695 linespec_parser::linespec_parser (int flags,
2696 const struct language_defn *language,
2697 struct program_space *search_pspace,
2698 struct symtab *default_symtab,
2699 int default_line,
2700 struct linespec_result *canonical)
2702 lexer.current.type = LSTOKEN_CONSUMED;
2703 result.explicit_loc.func_name_match_type
2704 = symbol_name_match_type::WILD;
2705 result.explicit_loc.line_offset.sign = LINE_OFFSET_UNKNOWN;
2706 linespec_state_constructor (&state, flags, language,
2707 search_pspace,
2708 default_symtab, default_line, canonical);
2711 /* A destructor for linespec_state. */
2713 static void
2714 linespec_state_destructor (struct linespec_state *self)
2716 htab_delete (self->addr_set);
2717 xfree (self->canonical_names);
2720 /* Delete a linespec parser. */
2722 linespec_parser::~linespec_parser ()
2724 linespec_state_destructor (&state);
2727 /* See description in linespec.h. */
2729 void
2730 linespec_lex_to_end (const char **stringp)
2732 linespec_token token;
2733 const char *orig;
2735 if (stringp == NULL || *stringp == NULL)
2736 return;
2738 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2739 parser.lexer.saved_arg = *stringp;
2740 parser.lexer.stream = orig = *stringp;
2744 /* Stop before any comma tokens; we need it to keep it
2745 as the next token in the string. */
2746 token = linespec_lexer_peek_token (&parser);
2747 if (token.type == LSTOKEN_COMMA)
2748 break;
2749 token = linespec_lexer_consume_token (&parser);
2751 while (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD);
2753 *stringp += parser.lexer.stream - orig;
2756 /* See linespec.h. */
2758 void
2759 linespec_complete_function (completion_tracker &tracker,
2760 const char *function,
2761 symbol_name_match_type func_match_type,
2762 const char *source_filename)
2764 complete_symbol_mode mode = complete_symbol_mode::LINESPEC;
2766 if (source_filename != NULL)
2768 collect_file_symbol_completion_matches (tracker, mode, func_match_type,
2769 function, function, source_filename);
2771 else
2773 collect_symbol_completion_matches (tracker, mode, func_match_type,
2774 function, function);
2779 /* Helper for complete_linespec to simplify it. SOURCE_FILENAME is
2780 only meaningful if COMPONENT is FUNCTION. */
2782 static void
2783 complete_linespec_component (linespec_parser *parser,
2784 completion_tracker &tracker,
2785 const char *text,
2786 linespec_complete_what component,
2787 const char *source_filename)
2789 if (component == linespec_complete_what::KEYWORD)
2791 complete_on_enum (tracker, linespec_keywords, text, text);
2793 else if (component == linespec_complete_what::EXPRESSION)
2795 const char *word
2796 = advance_to_expression_complete_word_point (tracker, text);
2797 complete_expression (tracker, text, word);
2799 else if (component == linespec_complete_what::FUNCTION)
2801 completion_list fn_list;
2803 symbol_name_match_type match_type
2804 = parser->result.explicit_loc.func_name_match_type;
2805 linespec_complete_function (tracker, text, match_type, source_filename);
2806 if (source_filename == NULL)
2808 /* Haven't seen a source component, like in "b
2809 file.c:function[TAB]". Maybe this wasn't a function, but
2810 a filename instead, like "b file.[TAB]". */
2811 fn_list = complete_source_filenames (text);
2814 /* If we only have a single filename completion, append a ':' for
2815 the user, since that's the only thing that can usefully follow
2816 the filename. */
2817 if (fn_list.size () == 1 && !tracker.have_completions ())
2819 char *fn = fn_list[0].release ();
2821 /* If we also need to append a quote char, it needs to be
2822 appended before the ':'. Append it now, and make ':' the
2823 new "quote" char. */
2824 if (tracker.quote_char ())
2826 char quote_char_str[2] = { (char) tracker.quote_char () };
2828 fn = reconcat (fn, fn, quote_char_str, (char *) NULL);
2829 tracker.set_quote_char (':');
2831 else
2832 fn = reconcat (fn, fn, ":", (char *) NULL);
2833 fn_list[0].reset (fn);
2835 /* Tell readline to skip appending a space. */
2836 tracker.set_suppress_append_ws (true);
2838 tracker.add_completions (std::move (fn_list));
2842 /* Helper for linespec_complete_label. Find labels that match
2843 LABEL_NAME in the function symbols listed in the PARSER, and add
2844 them to the tracker. */
2846 static void
2847 complete_label (completion_tracker &tracker,
2848 linespec_parser *parser,
2849 const char *label_name)
2851 std::vector<block_symbol> label_function_symbols;
2852 std::vector<block_symbol> labels
2853 = find_label_symbols (&parser->state,
2854 parser->result.function_symbols,
2855 &label_function_symbols,
2856 label_name, true);
2858 for (const auto &label : labels)
2860 char *match = xstrdup (label.symbol->search_name ());
2861 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (match));
2865 /* See linespec.h. */
2867 void
2868 linespec_complete_label (completion_tracker &tracker,
2869 const struct language_defn *language,
2870 const char *source_filename,
2871 const char *function_name,
2872 symbol_name_match_type func_name_match_type,
2873 const char *label_name)
2875 linespec_parser parser (0, language, NULL, NULL, 0, NULL);
2877 line_offset unknown_offset;
2881 convert_explicit_location_spec_to_linespec (&parser.state,
2882 &parser.result,
2883 source_filename,
2884 function_name,
2885 func_name_match_type,
2886 NULL, unknown_offset);
2888 catch (const gdb_exception_error &ex)
2890 return;
2893 complete_label (tracker, &parser, label_name);
2896 /* See description in linespec.h. */
2898 void
2899 linespec_complete (completion_tracker &tracker, const char *text,
2900 symbol_name_match_type match_type)
2902 const char *orig = text;
2904 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2905 parser.lexer.saved_arg = text;
2906 parser.result.explicit_loc.func_name_match_type = match_type;
2907 parser.lexer.stream = text;
2909 parser.completion_tracker = &tracker;
2910 parser.state.is_linespec = 1;
2912 /* Parse as much as possible. parser.completion_word will hold
2913 furthest completion point we managed to parse to. */
2916 parse_linespec (&parser, text, match_type);
2918 catch (const gdb_exception_error &except)
2922 if (parser.completion_quote_char != '\0'
2923 && parser.completion_quote_end != NULL
2924 && parser.completion_quote_end[1] == '\0')
2926 /* If completing a quoted string with the cursor right at
2927 terminating quote char, complete the completion word without
2928 interpretation, so that readline advances the cursor one
2929 whitespace past the quote, even if there's no match. This
2930 makes these cases behave the same:
2932 before: "b function()"
2933 after: "b function() "
2935 before: "b 'function()'"
2936 after: "b 'function()' "
2938 and trusts the user in this case:
2940 before: "b 'not_loaded_function_yet()'"
2941 after: "b 'not_loaded_function_yet()' "
2943 parser.complete_what = linespec_complete_what::NOTHING;
2944 parser.completion_quote_char = '\0';
2946 gdb::unique_xmalloc_ptr<char> text_copy
2947 (xstrdup (parser.completion_word));
2948 tracker.add_completion (std::move (text_copy));
2951 tracker.set_quote_char (parser.completion_quote_char);
2953 if (parser.complete_what == linespec_complete_what::LABEL)
2955 parser.complete_what = linespec_complete_what::NOTHING;
2957 const char *func_name = parser.result.explicit_loc.function_name.get ();
2959 std::vector<block_symbol> function_symbols;
2960 std::vector<bound_minimal_symbol> minimal_symbols;
2961 find_linespec_symbols (&parser.state,
2962 parser.result.file_symtabs,
2963 func_name, match_type,
2964 &function_symbols, &minimal_symbols);
2966 parser.result.function_symbols = std::move (function_symbols);
2967 parser.result.minimal_symbols = std::move (minimal_symbols);
2968 complete_label (tracker, &parser, parser.completion_word);
2970 else if (parser.complete_what == linespec_complete_what::FUNCTION)
2972 /* While parsing/lexing, we didn't know whether the completion
2973 word completes to a unique function/source name already or
2974 not.
2976 E.g.:
2977 "b function() <tab>"
2978 may need to complete either to:
2979 "b function() const"
2980 or to:
2981 "b function() if/thread/task"
2983 Or, this:
2984 "b foo t"
2985 may need to complete either to:
2986 "b foo template_fun<T>()"
2987 with "foo" being the template function's return type, or to:
2988 "b foo thread/task"
2990 Or, this:
2991 "b file<TAB>"
2992 may need to complete either to a source file name:
2993 "b file.c"
2994 or this, also a filename, but a unique completion:
2995 "b file.c:"
2996 or to a function name:
2997 "b file_function"
2999 Address that by completing assuming source or function, and
3000 seeing if we find a completion that matches exactly the
3001 completion word. If so, then it must be a function (see note
3002 below) and we advance the completion word to the end of input
3003 and switch to KEYWORD completion mode.
3005 Note: if we find a unique completion for a source filename,
3006 then it won't match the completion word, because the LCD will
3007 contain a trailing ':'. And if we're completing at or after
3008 the ':', then complete_linespec_component won't try to
3009 complete on source filenames. */
3011 const char *word = parser.completion_word;
3013 complete_linespec_component
3014 (&parser, tracker,
3015 parser.completion_word,
3016 linespec_complete_what::FUNCTION,
3017 parser.result.explicit_loc.source_filename.get ());
3019 parser.complete_what = linespec_complete_what::NOTHING;
3021 if (tracker.quote_char ())
3023 /* The function/file name was not close-quoted, so this
3024 can't be a keyword. Note: complete_linespec_component
3025 may have swapped the original quote char for ':' when we
3026 get here, but that still indicates the same. */
3028 else if (!tracker.have_completions ())
3030 size_t key_start;
3031 size_t wordlen = strlen (parser.completion_word);
3033 key_start
3034 = string_find_incomplete_keyword_at_end (linespec_keywords,
3035 parser.completion_word,
3036 wordlen);
3038 if (key_start != -1
3039 || (wordlen > 0
3040 && parser.completion_word[wordlen - 1] == ' '))
3042 parser.completion_word += key_start;
3043 parser.complete_what = linespec_complete_what::KEYWORD;
3046 else if (tracker.completes_to_completion_word (word))
3048 /* Skip the function and complete on keywords. */
3049 parser.completion_word += strlen (word);
3050 parser.complete_what = linespec_complete_what::KEYWORD;
3051 tracker.discard_completions ();
3055 tracker.advance_custom_word_point_by (parser.completion_word - orig);
3057 complete_linespec_component
3058 (&parser, tracker,
3059 parser.completion_word,
3060 parser.complete_what,
3061 parser.result.explicit_loc.source_filename.get ());
3063 /* If we're past the "filename:function:label:offset" linespec, and
3064 didn't find any match, then assume the user might want to create
3065 a pending breakpoint anyway and offer the keyword
3066 completions. */
3067 if (!parser.completion_quote_char
3068 && (parser.complete_what == linespec_complete_what::FUNCTION
3069 || parser.complete_what == linespec_complete_what::LABEL
3070 || parser.complete_what == linespec_complete_what::NOTHING)
3071 && !tracker.have_completions ())
3073 const char *end
3074 = parser.completion_word + strlen (parser.completion_word);
3076 if (end > orig && end[-1] == ' ')
3078 tracker.advance_custom_word_point_by (end - parser.completion_word);
3080 complete_linespec_component (&parser, tracker, end,
3081 linespec_complete_what::KEYWORD,
3082 NULL);
3087 /* A helper function for decode_line_full and decode_line_1 to
3088 turn LOCSPEC into std::vector<symtab_and_line>. */
3090 static std::vector<symtab_and_line>
3091 location_spec_to_sals (linespec_parser *parser,
3092 const location_spec *locspec)
3094 std::vector<symtab_and_line> result;
3096 switch (locspec->type ())
3098 case LINESPEC_LOCATION_SPEC:
3100 const linespec_location_spec *ls = as_linespec_location_spec (locspec);
3101 parser->state.is_linespec = 1;
3102 result = parse_linespec (parser, ls->spec_string.get (),
3103 ls->match_type);
3105 break;
3107 case ADDRESS_LOCATION_SPEC:
3109 const address_location_spec *addr_spec
3110 = as_address_location_spec (locspec);
3111 const char *addr_string = addr_spec->to_string ();
3112 CORE_ADDR addr;
3114 if (addr_string != NULL)
3116 addr = linespec_expression_to_pc (&addr_string);
3117 if (parser->state.canonical != NULL)
3118 parser->state.canonical->locspec = locspec->clone ();
3120 else
3121 addr = addr_spec->address;
3123 result = convert_address_location_to_sals (&parser->state,
3124 addr);
3126 break;
3128 case EXPLICIT_LOCATION_SPEC:
3130 const explicit_location_spec *explicit_locspec
3131 = as_explicit_location_spec (locspec);
3132 result = convert_explicit_location_spec_to_sals (&parser->state,
3133 &parser->result,
3134 explicit_locspec);
3136 break;
3138 case PROBE_LOCATION_SPEC:
3139 /* Probes are handled by their own decoders. */
3140 gdb_assert_not_reached ("attempt to decode probe location");
3141 break;
3143 default:
3144 gdb_assert_not_reached ("unhandled location spec type");
3147 return result;
3150 /* See linespec.h. */
3152 void
3153 decode_line_full (struct location_spec *locspec, int flags,
3154 struct program_space *search_pspace,
3155 struct symtab *default_symtab,
3156 int default_line, struct linespec_result *canonical,
3157 const char *select_mode,
3158 const char *filter)
3160 std::vector<const char *> filters;
3162 gdb_assert (canonical != NULL);
3163 /* The filter only makes sense for 'all'. */
3164 gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
3165 gdb_assert (select_mode == NULL
3166 || select_mode == multiple_symbols_all
3167 || select_mode == multiple_symbols_ask
3168 || select_mode == multiple_symbols_cancel);
3169 gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
3171 linespec_parser parser (flags, current_language,
3172 search_pspace, default_symtab,
3173 default_line, canonical);
3175 scoped_restore_current_program_space restore_pspace;
3177 std::vector<symtab_and_line> result = location_spec_to_sals (&parser,
3178 locspec);
3179 linespec_state *state = &parser.state;
3181 if (result.size () == 0)
3182 throw_error (NOT_SUPPORTED_ERROR, _("Location %s not available"),
3183 locspec->to_string ());
3185 gdb_assert (result.size () == 1 || canonical->pre_expanded);
3186 canonical->pre_expanded = 1;
3188 /* Arrange for allocated canonical names to be freed. */
3189 std::vector<gdb::unique_xmalloc_ptr<char>> hold_names;
3190 for (int i = 0; i < result.size (); ++i)
3192 gdb_assert (state->canonical_names[i].suffix != NULL);
3193 hold_names.emplace_back (state->canonical_names[i].suffix);
3196 if (select_mode == NULL)
3198 if (top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
3199 select_mode = multiple_symbols_all;
3200 else
3201 select_mode = multiple_symbols_select_mode ();
3204 if (select_mode == multiple_symbols_all)
3206 if (filter != NULL)
3208 filters.push_back (filter);
3209 filter_results (state, &result, filters);
3211 else
3212 convert_results_to_lsals (state, &result);
3214 else
3215 decode_line_2 (state, &result, select_mode);
3218 /* See linespec.h. */
3220 std::vector<symtab_and_line>
3221 decode_line_1 (const location_spec *locspec, int flags,
3222 struct program_space *search_pspace,
3223 struct symtab *default_symtab,
3224 int default_line)
3226 linespec_parser parser (flags, current_language,
3227 search_pspace, default_symtab,
3228 default_line, NULL);
3230 scoped_restore_current_program_space restore_pspace;
3232 return location_spec_to_sals (&parser, locspec);
3235 /* See linespec.h. */
3237 std::vector<symtab_and_line>
3238 decode_line_with_current_source (const char *string, int flags)
3240 if (string == 0)
3241 error (_("Empty line specification."));
3243 /* We use whatever is set as the current source line. We do not try
3244 and get a default source symtab+line or it will recursively call us! */
3245 symtab_and_line cursal
3246 = get_current_source_symtab_and_line (current_program_space);
3248 location_spec_up locspec = string_to_location_spec (&string,
3249 current_language);
3250 std::vector<symtab_and_line> sals
3251 = decode_line_1 (locspec.get (), flags, cursal.pspace, cursal.symtab,
3252 cursal.line);
3254 if (*string)
3255 error (_("Junk at end of line specification: %s"), string);
3257 return sals;
3260 /* See linespec.h. */
3262 std::vector<symtab_and_line>
3263 decode_line_with_last_displayed (const char *string, int flags)
3265 if (string == 0)
3266 error (_("Empty line specification."));
3268 location_spec_up locspec = string_to_location_spec (&string,
3269 current_language);
3270 std::vector<symtab_and_line> sals
3271 = (last_displayed_sal_is_valid ()
3272 ? decode_line_1 (locspec.get (), flags, NULL,
3273 get_last_displayed_symtab (),
3274 get_last_displayed_line ())
3275 : decode_line_1 (locspec.get (), flags, NULL, NULL, 0));
3277 if (*string)
3278 error (_("Junk at end of line specification: %s"), string);
3280 return sals;
3285 /* First, some functions to initialize stuff at the beginning of the
3286 function. */
3288 static void
3289 initialize_defaults (struct symtab **default_symtab, int *default_line)
3291 if (*default_symtab == 0)
3293 /* Use whatever we have for the default source line. We don't use
3294 get_current_or_default_symtab_and_line as it can recurse and call
3295 us back! */
3296 symtab_and_line cursal
3297 = get_current_source_symtab_and_line (current_program_space);
3299 *default_symtab = cursal.symtab;
3300 *default_line = cursal.line;
3306 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
3307 advancing EXP_PTR past any parsed text. */
3309 CORE_ADDR
3310 linespec_expression_to_pc (const char **exp_ptr)
3312 if (current_program_space->executing_startup)
3313 /* The error message doesn't really matter, because this case
3314 should only hit during breakpoint reset. */
3315 throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
3316 "program space is in startup"));
3318 (*exp_ptr)++;
3319 return value_as_address (parse_to_comma_and_eval (exp_ptr));
3324 /* Here's where we recognise an Objective-C Selector. An Objective C
3325 selector may be implemented by more than one class, therefore it
3326 may represent more than one method/function. This gives us a
3327 situation somewhat analogous to C++ overloading. If there's more
3328 than one method that could represent the selector, then use some of
3329 the existing C++ code to let the user choose one. */
3331 static std::vector<symtab_and_line>
3332 decode_objc (struct linespec_state *self, linespec *ls, const char *arg)
3334 struct collect_info info;
3335 std::vector<const char *> symbol_names;
3336 const char *new_argptr;
3338 info.state = self;
3339 std::vector<symtab *> symtabs;
3340 symtabs.push_back (nullptr);
3342 info.file_symtabs = &symtabs;
3344 std::vector<block_symbol> symbols;
3345 info.result.symbols = &symbols;
3346 std::vector<bound_minimal_symbol> minimal_symbols;
3347 info.result.minimal_symbols = &minimal_symbols;
3349 new_argptr = find_imps (arg, &symbol_names);
3350 if (symbol_names.empty ())
3351 return {};
3353 add_all_symbol_names_from_pspace (&info, NULL, symbol_names,
3354 SEARCH_FUNCTION_DOMAIN);
3356 std::vector<symtab_and_line> values;
3357 if (!symbols.empty () || !minimal_symbols.empty ())
3359 char *saved_arg;
3361 saved_arg = (char *) alloca (new_argptr - arg + 1);
3362 memcpy (saved_arg, arg, new_argptr - arg);
3363 saved_arg[new_argptr - arg] = '\0';
3365 ls->explicit_loc.function_name = make_unique_xstrdup (saved_arg);
3366 ls->function_symbols = std::move (symbols);
3367 ls->minimal_symbols = std::move (minimal_symbols);
3368 values = convert_linespec_to_sals (self, ls);
3370 if (self->canonical)
3372 std::string holder;
3373 const char *str;
3375 self->canonical->pre_expanded = 1;
3377 if (ls->explicit_loc.source_filename)
3379 holder = string_printf ("%s:%s",
3380 ls->explicit_loc.source_filename.get (),
3381 saved_arg);
3382 str = holder.c_str ();
3384 else
3385 str = saved_arg;
3387 self->canonical->locspec
3388 = new_linespec_location_spec (&str, symbol_name_match_type::FULL);
3392 return values;
3395 namespace {
3397 /* A function object that serves as symbol_found_callback_ftype
3398 callback for iterate_over_symbols. This is used by
3399 lookup_prefix_sym to collect type symbols. */
3400 class decode_compound_collector
3402 public:
3403 decode_compound_collector ()
3404 : m_unique_syms (htab_create_alloc (1, htab_hash_pointer,
3405 htab_eq_pointer, NULL,
3406 xcalloc, xfree))
3410 /* Return all symbols collected. */
3411 std::vector<block_symbol> release_symbols ()
3413 return std::move (m_symbols);
3416 /* Callable as a symbol_found_callback_ftype callback. */
3417 bool operator () (block_symbol *bsym);
3419 private:
3420 /* A hash table of all symbols we found. We use this to avoid
3421 adding any symbol more than once. */
3422 htab_up m_unique_syms;
3424 /* The result vector. */
3425 std::vector<block_symbol> m_symbols;
3428 bool
3429 decode_compound_collector::operator () (block_symbol *bsym)
3431 void **slot;
3432 struct type *t;
3433 struct symbol *sym = bsym->symbol;
3435 if (sym->aclass () != LOC_TYPEDEF)
3436 return true; /* Continue iterating. */
3438 t = sym->type ();
3439 t = check_typedef (t);
3440 if (t->code () != TYPE_CODE_STRUCT
3441 && t->code () != TYPE_CODE_UNION
3442 && t->code () != TYPE_CODE_NAMESPACE)
3443 return true; /* Continue iterating. */
3445 slot = htab_find_slot (m_unique_syms.get (), sym, INSERT);
3446 if (!*slot)
3448 *slot = sym;
3449 m_symbols.push_back (*bsym);
3452 return true; /* Continue iterating. */
3455 } // namespace
3457 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS. */
3459 static std::vector<block_symbol>
3460 lookup_prefix_sym (struct linespec_state *state,
3461 const std::vector<symtab *> &file_symtabs,
3462 const char *class_name)
3464 decode_compound_collector collector;
3466 lookup_name_info lookup_name (class_name, symbol_name_match_type::FULL);
3468 for (const auto &elt : file_symtabs)
3470 if (elt == nullptr)
3471 iterate_over_all_matching_symtabs (state, lookup_name,
3472 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3473 NULL, false, collector);
3474 else
3476 /* Program spaces that are executing startup should have
3477 been filtered out earlier. */
3478 program_space *pspace = elt->compunit ()->objfile ()->pspace ();
3480 gdb_assert (!pspace->executing_startup);
3481 set_current_program_space (pspace);
3482 iterate_over_file_blocks (elt, lookup_name,
3483 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3484 collector);
3488 return collector.release_symbols ();
3491 /* A std::sort comparison function for symbols. The resulting order does
3492 not actually matter; we just need to be able to sort them so that
3493 symbols with the same program space end up next to each other. */
3495 static bool
3496 compare_symbols (const block_symbol &a, const block_symbol &b)
3498 uintptr_t uia, uib;
3500 uia = (uintptr_t) a.symbol->symtab ()->compunit ()->objfile ()->pspace ();
3501 uib = (uintptr_t) b.symbol->symtab ()->compunit ()->objfile ()->pspace ();
3503 if (uia < uib)
3504 return true;
3505 if (uia > uib)
3506 return false;
3508 uia = (uintptr_t) a.symbol;
3509 uib = (uintptr_t) b.symbol;
3511 if (uia < uib)
3512 return true;
3514 return false;
3517 /* Like compare_symbols but for minimal symbols. */
3519 static bool
3520 compare_msymbols (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
3522 uintptr_t uia, uib;
3524 uia = (uintptr_t) a.objfile->pspace ();
3525 uib = (uintptr_t) a.objfile->pspace ();
3527 if (uia < uib)
3528 return true;
3529 if (uia > uib)
3530 return false;
3532 uia = (uintptr_t) a.minsym;
3533 uib = (uintptr_t) b.minsym;
3535 if (uia < uib)
3536 return true;
3538 return false;
3541 /* Look for all the matching instances of each symbol in NAMES. Only
3542 instances from PSPACE are considered; other program spaces are
3543 handled by our caller. If PSPACE is NULL, then all program spaces
3544 are considered. Results are stored into INFO. */
3546 static void
3547 add_all_symbol_names_from_pspace (struct collect_info *info,
3548 struct program_space *pspace,
3549 const std::vector<const char *> &names,
3550 domain_search_flags domain_search_flags)
3552 for (const char *iter : names)
3553 add_matching_symbols_to_info (iter,
3554 symbol_name_match_type::FULL,
3555 domain_search_flags, info, pspace);
3558 static void
3559 find_superclass_methods (std::vector<struct type *> &&superclasses,
3560 const char *name, enum language name_lang,
3561 std::vector<const char *> *result_names)
3563 size_t old_len = result_names->size ();
3565 while (1)
3567 std::vector<struct type *> new_supers;
3569 for (type *t : superclasses)
3570 find_methods (t, name_lang, name, result_names, &new_supers);
3572 if (result_names->size () != old_len || new_supers.empty ())
3573 break;
3575 superclasses = std::move (new_supers);
3579 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
3580 given by one of the symbols in SYM_CLASSES. Matches are returned
3581 in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols). */
3583 static void
3584 find_method (struct linespec_state *self,
3585 const std::vector<symtab *> &file_symtabs,
3586 const char *class_name, const char *method_name,
3587 std::vector<block_symbol> *sym_classes,
3588 std::vector<block_symbol> *symbols,
3589 std::vector<bound_minimal_symbol> *minsyms)
3591 size_t last_result_len;
3592 std::vector<struct type *> superclass_vec;
3593 std::vector<const char *> result_names;
3594 struct collect_info info;
3596 /* Sort symbols so that symbols with the same program space are next
3597 to each other. */
3598 std::sort (sym_classes->begin (), sym_classes->end (),
3599 compare_symbols);
3601 info.state = self;
3602 info.file_symtabs = &file_symtabs;
3603 info.result.symbols = symbols;
3604 info.result.minimal_symbols = minsyms;
3606 /* Iterate over all the types, looking for the names of existing
3607 methods matching METHOD_NAME. If we cannot find a direct method in a
3608 given program space, then we consider inherited methods; this is
3609 not ideal (ideal would be to respect C++ hiding rules), but it
3610 seems good enough and is what GDB has historically done. We only
3611 need to collect the names because later we find all symbols with
3612 those names. This loop is written in a somewhat funny way
3613 because we collect data across the program space before deciding
3614 what to do. */
3615 last_result_len = 0;
3616 for (const auto &elt : *sym_classes)
3618 struct type *t;
3619 struct program_space *pspace;
3620 struct symbol *sym = elt.symbol;
3621 unsigned int ix = &elt - &*sym_classes->begin ();
3623 /* Program spaces that are executing startup should have
3624 been filtered out earlier. */
3625 pspace = sym->symtab ()->compunit ()->objfile ()->pspace ();
3626 gdb_assert (!pspace->executing_startup);
3627 set_current_program_space (pspace);
3628 t = check_typedef (sym->type ());
3629 find_methods (t, sym->language (),
3630 method_name, &result_names, &superclass_vec);
3632 /* Handle all items from a single program space at once; and be
3633 sure not to miss the last batch. */
3634 if (ix == sym_classes->size () - 1
3635 || (pspace
3636 != (sym_classes->at (ix + 1).symbol->symtab ()
3637 ->compunit ()->objfile ()->pspace ())))
3639 /* If we did not find a direct implementation anywhere in
3640 this program space, consider superclasses. */
3641 if (result_names.size () == last_result_len)
3642 find_superclass_methods (std::move (superclass_vec), method_name,
3643 sym->language (), &result_names);
3645 /* We have a list of candidate symbol names, so now we
3646 iterate over the symbol tables looking for all
3647 matches in this pspace. */
3648 add_all_symbol_names_from_pspace (&info, pspace, result_names,
3649 SEARCH_FUNCTION_DOMAIN);
3651 superclass_vec.clear ();
3652 last_result_len = result_names.size ();
3656 if (!symbols->empty () || !minsyms->empty ())
3657 return;
3659 /* Throw an NOT_FOUND_ERROR. This will be caught by the caller
3660 and other attempts to locate the symbol will be made. */
3661 throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
3666 namespace {
3668 /* This function object is a callback for iterate_over_symtabs, used
3669 when collecting all matching symtabs. */
3671 class symtab_collector
3673 public:
3674 symtab_collector ()
3675 : m_symtab_table (htab_create (1, htab_hash_pointer, htab_eq_pointer,
3676 NULL))
3680 /* Callable as a symbol_found_callback_ftype callback. */
3681 bool operator () (symtab *sym);
3683 /* Return an rvalue reference to the collected symtabs. */
3684 std::vector<symtab *> &&release_symtabs ()
3686 return std::move (m_symtabs);
3689 private:
3690 /* The result vector of symtabs. */
3691 std::vector<symtab *> m_symtabs;
3693 /* This is used to ensure the symtabs are unique. */
3694 htab_up m_symtab_table;
3697 bool
3698 symtab_collector::operator () (struct symtab *symtab)
3700 void **slot;
3702 slot = htab_find_slot (m_symtab_table.get (), symtab, INSERT);
3703 if (!*slot)
3705 *slot = symtab;
3706 m_symtabs.push_back (symtab);
3709 return false;
3712 } // namespace
3714 /* Given a file name, return a list of all matching symtabs. If
3715 SEARCH_PSPACE is not NULL, the search is restricted to just that
3716 program space. */
3718 static std::vector<symtab *>
3719 collect_symtabs_from_filename (const char *file,
3720 struct program_space *search_pspace)
3722 symtab_collector collector;
3724 /* Find that file's data. */
3725 if (search_pspace == NULL)
3727 for (struct program_space *pspace : program_spaces)
3729 if (pspace->executing_startup)
3730 continue;
3732 iterate_over_symtabs (pspace, file, collector);
3735 else
3736 iterate_over_symtabs (search_pspace, file, collector);
3738 return collector.release_symtabs ();
3741 /* Return all the symtabs associated to the FILENAME. If SEARCH_PSPACE is
3742 not NULL, the search is restricted to just that program space. */
3744 static std::vector<symtab *>
3745 symtabs_from_filename (const char *filename,
3746 struct program_space *search_pspace)
3748 std::vector<symtab *> result
3749 = collect_symtabs_from_filename (filename, search_pspace);
3751 if (result.empty ())
3753 if (!have_full_symbols (current_program_space)
3754 && !have_partial_symbols (current_program_space))
3755 throw_error (NOT_FOUND_ERROR,
3756 _("No symbol table is loaded. "
3757 "Use the \"file\" command."));
3758 source_file_not_found_error (filename);
3761 return result;
3764 /* See symtab.h. */
3766 void
3767 symbol_searcher::find_all_symbols (const std::string &name,
3768 const struct language_defn *language,
3769 domain_search_flags domain_search_flags,
3770 std::vector<symtab *> *search_symtabs,
3771 struct program_space *search_pspace)
3773 symbol_searcher_collect_info info;
3774 struct linespec_state state;
3776 memset (&state, 0, sizeof (state));
3777 state.language = language;
3778 info.state = &state;
3780 info.result.symbols = &m_symbols;
3781 info.result.minimal_symbols = &m_minimal_symbols;
3782 std::vector<symtab *> all_symtabs;
3783 if (search_symtabs == nullptr)
3785 all_symtabs.push_back (nullptr);
3786 search_symtabs = &all_symtabs;
3788 info.file_symtabs = search_symtabs;
3790 add_matching_symbols_to_info (name.c_str (), symbol_name_match_type::WILD,
3791 domain_search_flags, &info, search_pspace);
3794 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS. Matching
3795 debug symbols are returned in SYMBOLS. Matching minimal symbols are
3796 returned in MINSYMS. */
3798 static void
3799 find_function_symbols (struct linespec_state *state,
3800 const std::vector<symtab *> &file_symtabs, const char *name,
3801 symbol_name_match_type name_match_type,
3802 std::vector<block_symbol> *symbols,
3803 std::vector<bound_minimal_symbol> *minsyms)
3805 struct collect_info info;
3806 std::vector<const char *> symbol_names;
3808 info.state = state;
3809 info.result.symbols = symbols;
3810 info.result.minimal_symbols = minsyms;
3811 info.file_symtabs = &file_symtabs;
3813 /* Try NAME as an Objective-C selector. */
3814 find_imps (name, &symbol_names);
3816 domain_search_flags flags = SEARCH_FUNCTION_DOMAIN;
3817 if (state->list_mode)
3818 flags = SEARCH_VFT;
3820 if (!symbol_names.empty ())
3821 add_all_symbol_names_from_pspace (&info, state->search_pspace,
3822 symbol_names, flags);
3823 else
3824 add_matching_symbols_to_info (name, name_match_type, flags,
3825 &info, state->search_pspace);
3828 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3829 in SYMBOLS and minimal symbols in MINSYMS. */
3831 static void
3832 find_linespec_symbols (struct linespec_state *state,
3833 const std::vector<symtab *> &file_symtabs,
3834 const char *lookup_name,
3835 symbol_name_match_type name_match_type,
3836 std::vector <block_symbol> *symbols,
3837 std::vector<bound_minimal_symbol> *minsyms)
3839 gdb::unique_xmalloc_ptr<char> canon
3840 = cp_canonicalize_string_no_typedefs (lookup_name);
3841 if (canon != nullptr)
3842 lookup_name = canon.get ();
3844 /* It's important to not call expand_symtabs_matching unnecessarily
3845 as it can really slow things down (by unnecessarily expanding
3846 potentially 1000s of symtabs, which when debugging some apps can
3847 cost 100s of seconds). Avoid this to some extent by *first* calling
3848 find_function_symbols, and only if that doesn't find anything
3849 *then* call find_method. This handles two important cases:
3850 1) break (anonymous namespace)::foo
3851 2) break class::method where method is in class (and not a baseclass) */
3853 find_function_symbols (state, file_symtabs, lookup_name,
3854 name_match_type, symbols, minsyms);
3856 /* If we were unable to locate a symbol of the same name, try dividing
3857 the name into class and method names and searching the class and its
3858 baseclasses. */
3859 if (symbols->empty () && minsyms->empty ())
3861 std::string klass, method;
3862 const char *last, *p, *scope_op;
3864 /* See if we can find a scope operator and break this symbol
3865 name into namespaces${SCOPE_OPERATOR}class_name and method_name. */
3866 scope_op = "::";
3867 p = find_toplevel_string (lookup_name, scope_op);
3869 last = NULL;
3870 while (p != NULL)
3872 last = p;
3873 p = find_toplevel_string (p + strlen (scope_op), scope_op);
3876 /* If no scope operator was found, there is nothing more we can do;
3877 we already attempted to lookup the entire name as a symbol
3878 and failed. */
3879 if (last == NULL)
3880 return;
3882 /* LOOKUP_NAME points to the class name.
3883 LAST points to the method name. */
3884 klass = std::string (lookup_name, last - lookup_name);
3886 /* Skip past the scope operator. */
3887 last += strlen (scope_op);
3888 method = last;
3890 /* Find a list of classes named KLASS. */
3891 std::vector<block_symbol> classes
3892 = lookup_prefix_sym (state, file_symtabs, klass.c_str ());
3893 if (!classes.empty ())
3895 /* Now locate a list of suitable methods named METHOD. */
3898 find_method (state, file_symtabs,
3899 klass.c_str (), method.c_str (),
3900 &classes, symbols, minsyms);
3903 /* If successful, we're done. If NOT_FOUND_ERROR
3904 was not thrown, rethrow the exception that we did get. */
3905 catch (const gdb_exception_error &except)
3907 if (except.error != NOT_FOUND_ERROR)
3908 throw;
3914 /* Helper for find_label_symbols. Find all labels that match name
3915 NAME in BLOCK. Return all labels that match in FUNCTION_SYMBOLS.
3916 Return the actual function symbol in which the label was found in
3917 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3918 interpreted as a label name prefix. Otherwise, only a label named
3919 exactly NAME match. */
3921 static void
3922 find_label_symbols_in_block (const struct block *block,
3923 const char *name, struct symbol *fn_sym,
3924 bool completion_mode,
3925 std::vector<block_symbol> *result,
3926 std::vector<block_symbol> *label_funcs_ret)
3928 if (completion_mode)
3930 size_t name_len = strlen (name);
3932 int (*cmp) (const char *, const char *, size_t);
3933 cmp = case_sensitivity == case_sensitive_on ? strncmp : strncasecmp;
3935 for (struct symbol *sym : block_iterator_range (block))
3937 if (sym->domain () == LABEL_DOMAIN
3938 && cmp (sym->search_name (), name, name_len) == 0)
3940 result->push_back ({sym, block});
3941 label_funcs_ret->push_back ({fn_sym, block});
3945 else
3947 struct block_symbol label_sym
3948 = lookup_symbol (name, block, SEARCH_LABEL_DOMAIN, 0);
3950 if (label_sym.symbol != NULL)
3952 result->push_back (label_sym);
3953 label_funcs_ret->push_back ({fn_sym, block});
3958 /* Return all labels that match name NAME in FUNCTION_SYMBOLS.
3960 Return the actual function symbol in which the label was found in
3961 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3962 interpreted as a label name prefix. Otherwise, only labels named
3963 exactly NAME match. */
3966 static std::vector<block_symbol>
3967 find_label_symbols (struct linespec_state *self,
3968 const std::vector<block_symbol> &function_symbols,
3969 std::vector<block_symbol> *label_funcs_ret,
3970 const char *name,
3971 bool completion_mode)
3973 const struct block *block;
3974 struct symbol *fn_sym;
3975 std::vector<block_symbol> result;
3977 if (function_symbols.empty ())
3979 set_current_program_space (self->program_space);
3980 block = get_current_search_block ();
3982 for (;
3983 block && !block->function ();
3984 block = block->superblock ())
3987 if (!block)
3988 return {};
3990 fn_sym = block->function ();
3992 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
3993 &result, label_funcs_ret);
3995 else
3997 for (const auto &elt : function_symbols)
3999 fn_sym = elt.symbol;
4000 set_current_program_space
4001 (fn_sym->symtab ()->compunit ()->objfile ()->pspace ());
4002 block = fn_sym->value_block ();
4004 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
4005 &result, label_funcs_ret);
4009 return result;
4014 /* A helper for create_sals_line_offset that handles the 'list_mode' case. */
4016 static std::vector<symtab_and_line>
4017 decode_digits_list_mode (struct linespec_state *self,
4018 linespec *ls,
4019 struct symtab_and_line val)
4021 gdb_assert (self->list_mode);
4023 std::vector<symtab_and_line> values;
4025 for (const auto &elt : ls->file_symtabs)
4027 /* The logic above should ensure this. */
4028 gdb_assert (elt != NULL);
4030 program_space *pspace = elt->compunit ()->objfile ()->pspace ();
4031 set_current_program_space (pspace);
4033 /* Simplistic search just for the list command. */
4034 val.symtab = find_line_symtab (elt, val.line, nullptr);
4035 if (val.symtab == NULL)
4036 val.symtab = elt;
4037 val.pspace = pspace;
4038 val.pc = 0;
4039 val.explicit_line = true;
4041 add_sal_to_sals (self, &values, &val, NULL, 0);
4044 return values;
4047 /* A helper for create_sals_line_offset that iterates over the symtabs
4048 associated with LS and returns a vector of corresponding symtab_and_line
4049 structures. */
4051 static std::vector<symtab_and_line>
4052 decode_digits_ordinary (struct linespec_state *self,
4053 linespec *ls,
4054 int line,
4055 const linetable_entry **best_entry)
4057 std::vector<symtab_and_line> sals;
4058 for (const auto &elt : ls->file_symtabs)
4060 std::vector<CORE_ADDR> pcs;
4062 /* The logic above should ensure this. */
4063 gdb_assert (elt != NULL);
4065 program_space *pspace = elt->compunit ()->objfile ()->pspace ();
4066 set_current_program_space (pspace);
4068 pcs = find_pcs_for_symtab_line (elt, line, best_entry);
4069 for (CORE_ADDR pc : pcs)
4071 symtab_and_line sal;
4072 sal.pspace = pspace;
4073 sal.symtab = elt;
4074 sal.line = line;
4075 sal.explicit_line = true;
4076 sal.pc = pc;
4077 sals.push_back (std::move (sal));
4081 return sals;
4086 /* Return the line offset represented by VARIABLE. */
4088 static struct line_offset
4089 linespec_parse_variable (struct linespec_state *self, const char *variable)
4091 int index = 0;
4092 const char *p;
4093 line_offset offset;
4095 p = (variable[1] == '$') ? variable + 2 : variable + 1;
4096 if (*p == '$')
4097 ++p;
4098 while (*p >= '0' && *p <= '9')
4099 ++p;
4100 if (!*p) /* Reached end of token without hitting non-digit. */
4102 /* We have a value history reference. */
4103 struct value *val_history;
4105 sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
4106 val_history
4107 = access_value_history ((variable[1] == '$') ? -index : index);
4108 if (val_history->type ()->code () != TYPE_CODE_INT)
4109 error (_("History values used in line "
4110 "specs must have integer values."));
4111 offset.offset = value_as_long (val_history);
4112 offset.sign = LINE_OFFSET_NONE;
4114 else
4116 /* Not all digits -- may be user variable/function or a
4117 convenience variable. */
4118 LONGEST valx;
4119 struct internalvar *ivar;
4121 /* Try it as a convenience variable. If it is not a convenience
4122 variable, return and allow normal symbol lookup to occur. */
4123 ivar = lookup_only_internalvar (variable + 1);
4124 /* If there's no internal variable with that name, let the
4125 offset remain as unknown to allow the name to be looked up
4126 as a symbol. */
4127 if (ivar != nullptr)
4129 /* We found a valid variable name. If it is not an integer,
4130 throw an error. */
4131 if (!get_internalvar_integer (ivar, &valx))
4132 error (_("Convenience variables used in line "
4133 "specs must have integer values."));
4134 else
4136 offset.offset = valx;
4137 offset.sign = LINE_OFFSET_NONE;
4142 return offset;
4146 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
4147 linespec; return the SAL in RESULT. This function should return SALs
4148 matching those from find_function_start_sal, otherwise false
4149 multiple-locations breakpoints could be placed. */
4151 static void
4152 minsym_found (struct linespec_state *self, struct objfile *objfile,
4153 struct minimal_symbol *msymbol,
4154 std::vector<symtab_and_line> *result)
4156 bool want_start_sal = false;
4158 CORE_ADDR func_addr;
4159 bool is_function = msymbol_is_function (objfile, msymbol, &func_addr);
4161 if (is_function)
4163 const char *msym_name = msymbol->linkage_name ();
4165 if (msymbol->type () == mst_text_gnu_ifunc
4166 || msymbol->type () == mst_data_gnu_ifunc)
4167 want_start_sal = gnu_ifunc_resolve_name (msym_name, &func_addr);
4168 else
4169 want_start_sal = true;
4172 symtab_and_line sal;
4174 if (is_function && want_start_sal)
4175 sal = find_function_start_sal (func_addr, NULL, self->funfirstline);
4176 else
4178 sal.objfile = objfile;
4179 sal.msymbol = msymbol;
4180 /* Store func_addr, not the minsym's address in case this was an
4181 ifunc that hasn't been resolved yet. */
4182 if (is_function)
4183 sal.pc = func_addr;
4184 else
4185 sal.pc = msymbol->value_address (objfile);
4186 sal.pspace = current_program_space;
4189 sal.section = msymbol->obj_section (objfile);
4191 if (maybe_add_address (self->addr_set, objfile->pspace (), sal.pc))
4192 add_sal_to_sals (self, result, &sal, msymbol->natural_name (), 0);
4195 /* Helper for search_minsyms_for_name that adds the symbol to the
4196 result. */
4198 static void
4199 add_minsym (struct minimal_symbol *minsym, struct objfile *objfile,
4200 struct symtab *symtab, int list_mode,
4201 std::vector<bound_minimal_symbol> *msyms)
4203 if (symtab != NULL)
4205 /* We're looking for a label for which we don't have debug
4206 info. */
4207 CORE_ADDR func_addr;
4208 if (msymbol_is_function (objfile, minsym, &func_addr))
4210 symtab_and_line sal = find_pc_sect_line (func_addr, NULL, 0);
4212 if (symtab != sal.symtab)
4213 return;
4217 /* Exclude data symbols when looking for breakpoint locations. */
4218 if (!list_mode && !msymbol_is_function (objfile, minsym))
4219 return;
4221 msyms->emplace_back (minsym, objfile);
4222 return;
4225 /* Search for minimal symbols called NAME. If SEARCH_PSPACE
4226 is not NULL, the search is restricted to just that program
4227 space.
4229 If SYMTAB is NULL, search all objfiles, otherwise
4230 restrict results to the given SYMTAB. */
4232 static void
4233 search_minsyms_for_name (struct collect_info *info,
4234 const lookup_name_info &name,
4235 struct program_space *search_pspace,
4236 struct symtab *symtab)
4238 std::vector<bound_minimal_symbol> minsyms;
4240 if (symtab == NULL)
4242 for (struct program_space *pspace : program_spaces)
4244 if (search_pspace != NULL && search_pspace != pspace)
4245 continue;
4246 if (pspace->executing_startup)
4247 continue;
4249 set_current_program_space (pspace);
4251 for (objfile *objfile : pspace->objfiles ())
4253 iterate_over_minimal_symbols (objfile, name,
4254 [&] (struct minimal_symbol *msym)
4256 add_minsym (msym, objfile, nullptr,
4257 info->state->list_mode,
4258 &minsyms);
4259 return false;
4264 else
4266 program_space *pspace = symtab->compunit ()->objfile ()->pspace ();
4268 if (search_pspace == NULL || pspace == search_pspace)
4270 set_current_program_space (pspace);
4271 iterate_over_minimal_symbols
4272 (symtab->compunit ()->objfile (), name,
4273 [&] (struct minimal_symbol *msym)
4275 add_minsym (msym, symtab->compunit ()->objfile (), symtab,
4276 info->state->list_mode, &minsyms);
4277 return false;
4282 /* Return true if TYPE is a static symbol. */
4283 auto msymbol_type_is_static = [] (enum minimal_symbol_type type)
4285 switch (type)
4287 case mst_file_text:
4288 case mst_file_data:
4289 case mst_file_bss:
4290 return true;
4291 default:
4292 return false;
4296 /* Add minsyms to the result set, but filter out trampoline symbols
4297 if we also found extern symbols with the same name. I.e., don't
4298 set a breakpoint on both '<foo@plt>' and 'foo', assuming that
4299 'foo' is the symbol that the plt resolves to. */
4300 for (const bound_minimal_symbol &item : minsyms)
4302 bool skip = false;
4303 if (item.minsym->type () == mst_solib_trampoline)
4305 for (const bound_minimal_symbol &item2 : minsyms)
4307 if (&item2 == &item)
4308 continue;
4310 /* Ignore other trampoline symbols. */
4311 if (item2.minsym->type () == mst_solib_trampoline)
4312 continue;
4314 /* Trampoline symbols can only jump to exported
4315 symbols. */
4316 if (msymbol_type_is_static (item2.minsym->type ()))
4317 continue;
4319 if (strcmp (item.minsym->linkage_name (),
4320 item2.minsym->linkage_name ()) != 0)
4321 continue;
4323 /* Found a global minsym with the same name as the
4324 trampoline. Don't create a location for this
4325 trampoline. */
4326 skip = true;
4327 break;
4331 if (!skip)
4332 info->result.minimal_symbols->push_back (item);
4336 /* A helper function to add all symbols matching NAME to INFO. If
4337 PSPACE is not NULL, the search is restricted to just that program
4338 space. */
4340 static void
4341 add_matching_symbols_to_info (const char *name,
4342 symbol_name_match_type name_match_type,
4343 domain_search_flags domain_search_flags,
4344 struct collect_info *info,
4345 struct program_space *pspace)
4347 lookup_name_info lookup_name (name, name_match_type);
4349 for (const auto &elt : *info->file_symtabs)
4351 if (elt == nullptr)
4353 iterate_over_all_matching_symtabs (info->state, lookup_name,
4354 domain_search_flags,
4355 pspace, true,
4356 [&] (block_symbol *bsym)
4357 { return info->add_symbol (bsym); });
4358 search_minsyms_for_name (info, lookup_name, pspace, NULL);
4360 else if (pspace == NULL || pspace == elt->compunit ()->objfile ()->pspace ())
4362 int prev_len = info->result.symbols->size ();
4364 /* Program spaces that are executing startup should have
4365 been filtered out earlier. */
4366 program_space *elt_pspace = elt->compunit ()->objfile ()->pspace ();
4367 gdb_assert (!elt_pspace->executing_startup);
4368 set_current_program_space (elt_pspace);
4369 iterate_over_file_blocks (elt, lookup_name, SEARCH_VFT,
4370 [&] (block_symbol *bsym)
4371 { return info->add_symbol (bsym); });
4373 /* If no new symbols were found in this iteration and this symtab
4374 is in assembler, we might actually be looking for a label for
4375 which we don't have debug info. Check for a minimal symbol in
4376 this case. */
4377 if (prev_len == info->result.symbols->size ()
4378 && elt->language () == language_asm)
4379 search_minsyms_for_name (info, lookup_name, pspace, elt);
4386 /* Now come some functions that are called from multiple places within
4387 decode_line_1. */
4389 static int
4390 symbol_to_sal (struct symtab_and_line *result,
4391 int funfirstline, struct symbol *sym)
4393 if (sym->aclass () == LOC_BLOCK)
4395 *result = find_function_start_sal (sym, funfirstline);
4396 return 1;
4398 else
4400 if (sym->aclass () == LOC_LABEL && sym->value_address () != 0)
4402 *result = {};
4403 result->symtab = sym->symtab ();
4404 result->symbol = sym;
4405 result->line = sym->line ();
4406 result->pc = sym->value_address ();
4407 result->pspace = result->symtab->compunit ()->objfile ()->pspace ();
4408 result->explicit_pc = 1;
4409 return 1;
4411 else if (funfirstline)
4413 /* Nothing. */
4415 else if (sym->line () != 0)
4417 /* We know its line number. */
4418 *result = {};
4419 result->symtab = sym->symtab ();
4420 result->symbol = sym;
4421 result->line = sym->line ();
4422 result->pc = sym->value_address ();
4423 result->pspace = result->symtab->compunit ()->objfile ()->pspace ();
4424 return 1;
4428 return 0;
4431 linespec_result::~linespec_result ()
4433 for (linespec_sals &lsal : lsals)
4434 xfree (lsal.canonical);
4437 /* Return the quote characters permitted by the linespec parser. */
4439 const char *
4440 get_gdb_linespec_parser_quote_characters (void)
4442 return linespec_quote_characters;