[gdb/testsuite] Fix gdb.threads/threadcrash.exp with glibc debuginfo
[binutils-gdb.git] / gdb / linespec.c
blobca154d2dcba1cb8688eef0c31432dae6c62ef73d
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 "demangle.h"
27 #include "value.h"
28 #include "completer.h"
29 #include "cp-abi.h"
30 #include "cp-support.h"
31 #include "parser-defs.h"
32 #include "block.h"
33 #include "objc-lang.h"
34 #include "linespec.h"
35 #include "language.h"
36 #include "interps.h"
37 #include "mi/mi-cmds.h"
38 #include "target.h"
39 #include "arch-utils.h"
40 #include <ctype.h>
41 #include "cli/cli-utils.h"
42 #include "filenames.h"
43 #include "ada-lang.h"
44 #include "stack.h"
45 #include "location.h"
46 #include "gdbsupport/function-view.h"
47 #include "gdbsupport/def-vector.h"
48 #include <algorithm>
49 #include "inferior.h"
51 /* An enumeration of the various things a user might attempt to
52 complete for a linespec location. */
54 enum class linespec_complete_what
56 /* Nothing, no possible completion. */
57 NOTHING,
59 /* A function/method name. Due to ambiguity between
61 (gdb) b source[TAB]
62 source_file.c
63 source_function
65 this can also indicate a source filename, iff we haven't seen a
66 separate source filename component, as in "b source.c:function". */
67 FUNCTION,
69 /* A label symbol. E.g., break file.c:function:LABEL. */
70 LABEL,
72 /* An expression. E.g., "break foo if EXPR", or "break *EXPR". */
73 EXPRESSION,
75 /* A linespec keyword ("if"/"thread"/"task"/"-force-condition").
76 E.g., "break func threa<tab>". */
77 KEYWORD,
80 /* An address entry is used to ensure that any given location is only
81 added to the result a single time. It holds an address and the
82 program space from which the address came. */
84 struct address_entry
86 struct program_space *pspace;
87 CORE_ADDR addr;
90 /* A linespec. Elements of this structure are filled in by a parser
91 (either parse_linespec or some other function). The structure is
92 then converted into SALs by convert_linespec_to_sals. */
94 struct linespec
96 /* An explicit location spec describing the SaLs. */
97 explicit_location_spec explicit_loc;
99 /* The list of symtabs to search to which to limit the search.
101 If explicit.SOURCE_FILENAME is NULL (no user-specified filename),
102 FILE_SYMTABS should contain one single NULL member. This will cause the
103 code to use the default symtab. */
104 std::vector<symtab *> file_symtabs;
106 /* A list of matching function symbols and minimal symbols. Both lists
107 may be empty if no matching symbols were found. */
108 std::vector<block_symbol> function_symbols;
109 std::vector<bound_minimal_symbol> minimal_symbols;
111 /* A structure of matching label symbols and the corresponding
112 function symbol in which the label was found. Both may be empty
113 or both must be non-empty. */
114 struct
116 std::vector<block_symbol> label_symbols;
117 std::vector<block_symbol> function_symbols;
118 } labels;
121 /* A canonical linespec represented as a symtab-related string.
123 Each entry represents the "SYMTAB:SUFFIX" linespec string.
124 SYMTAB can be converted for example by symtab_to_fullname or
125 symtab_to_filename_for_display as needed. */
127 struct linespec_canonical_name
129 /* Remaining text part of the linespec string. */
130 char *suffix;
132 /* If NULL then SUFFIX is the whole linespec string. */
133 struct symtab *symtab;
136 /* An instance of this is used to keep all state while linespec
137 operates. This instance is passed around as a 'this' pointer to
138 the various implementation methods. */
140 struct linespec_state
142 /* The language in use during linespec processing. */
143 const struct language_defn *language;
145 /* The program space as seen when the module was entered. */
146 struct program_space *program_space;
148 /* If not NULL, the search is restricted to just this program
149 space. */
150 struct program_space *search_pspace;
152 /* The default symtab to use, if no other symtab is specified. */
153 struct symtab *default_symtab;
155 /* The default line to use. */
156 int default_line;
158 /* The 'funfirstline' value that was passed in to decode_line_1 or
159 decode_line_full. */
160 int funfirstline;
162 /* Nonzero if we are running in 'list' mode; see decode_line_list. */
163 int list_mode;
165 /* The 'canonical' value passed to decode_line_full, or NULL. */
166 struct linespec_result *canonical;
168 /* Canonical strings that mirror the std::vector<symtab_and_line> result. */
169 struct linespec_canonical_name *canonical_names;
171 /* This is a set of address_entry objects which is used to prevent
172 duplicate symbols from being entered into the result. */
173 htab_t addr_set;
175 /* Are we building a linespec? */
176 int is_linespec;
179 /* This is a helper object that is used when collecting symbols into a
180 result. */
182 struct collect_info
184 /* The linespec object in use. */
185 struct linespec_state *state;
187 /* A list of symtabs to which to restrict matches. */
188 const std::vector<symtab *> *file_symtabs;
190 /* The result being accumulated. */
191 struct
193 std::vector<block_symbol> *symbols;
194 std::vector<bound_minimal_symbol> *minimal_symbols;
195 } result;
197 /* Possibly add a symbol to the results. */
198 virtual bool add_symbol (block_symbol *bsym);
201 bool
202 collect_info::add_symbol (block_symbol *bsym)
204 /* In list mode, add all matching symbols, regardless of class.
205 This allows the user to type "list a_global_variable". */
206 if (bsym->symbol->aclass () == LOC_BLOCK || this->state->list_mode)
207 this->result.symbols->push_back (*bsym);
209 /* Continue iterating. */
210 return true;
213 /* Custom collect_info for symbol_searcher. */
215 struct symbol_searcher_collect_info
216 : collect_info
218 bool add_symbol (block_symbol *bsym) override
220 /* Add everything. */
221 this->result.symbols->push_back (*bsym);
223 /* Continue iterating. */
224 return true;
228 /* Token types */
230 enum linespec_token_type
232 /* A keyword */
233 LSTOKEN_KEYWORD = 0,
235 /* A colon "separator" */
236 LSTOKEN_COLON,
238 /* A string */
239 LSTOKEN_STRING,
241 /* A number */
242 LSTOKEN_NUMBER,
244 /* A comma */
245 LSTOKEN_COMMA,
247 /* EOI (end of input) */
248 LSTOKEN_EOI,
250 /* Consumed token */
251 LSTOKEN_CONSUMED
254 /* List of keywords. This is NULL-terminated so that it can be used
255 as enum completer. */
256 const char * const linespec_keywords[] = { "if", "thread", "task", "inferior", "-force-condition", NULL };
257 #define IF_KEYWORD_INDEX 0
258 #define FORCE_KEYWORD_INDEX 4
260 /* A token of the linespec lexer */
262 struct linespec_token
264 /* The type of the token */
265 linespec_token_type type;
267 /* Data for the token */
268 union
270 /* A string, given as a stoken */
271 struct stoken string;
273 /* A keyword */
274 const char *keyword;
275 } data;
278 #define LS_TOKEN_STOKEN(TOK) (TOK).data.string
279 #define LS_TOKEN_KEYWORD(TOK) (TOK).data.keyword
281 /* An instance of the linespec parser. */
283 struct linespec_parser
285 linespec_parser (int flags, const struct language_defn *language,
286 struct program_space *search_pspace,
287 struct symtab *default_symtab,
288 int default_line,
289 struct linespec_result *canonical);
291 ~linespec_parser ();
293 DISABLE_COPY_AND_ASSIGN (linespec_parser);
295 /* Lexer internal data */
296 struct
298 /* Save head of input stream. */
299 const char *saved_arg;
301 /* Head of the input stream. */
302 const char *stream;
303 #define PARSER_STREAM(P) ((P)->lexer.stream)
305 /* The current token. */
306 linespec_token current;
307 } lexer {};
309 /* Is the entire linespec quote-enclosed? */
310 int is_quote_enclosed = 0;
312 /* The state of the parse. */
313 struct linespec_state state {};
314 #define PARSER_STATE(PPTR) (&(PPTR)->state)
316 /* The result of the parse. */
317 linespec result;
318 #define PARSER_RESULT(PPTR) (&(PPTR)->result)
320 /* What the parser believes the current word point should complete
321 to. */
322 linespec_complete_what complete_what = linespec_complete_what::NOTHING;
324 /* The completion word point. The parser advances this as it skips
325 tokens. At some point the input string will end or parsing will
326 fail, and then we attempt completion at the captured completion
327 word point, interpreting the string at completion_word as
328 COMPLETE_WHAT. */
329 const char *completion_word = nullptr;
331 /* If the current token was a quoted string, then this is the
332 quoting character (either " or '). */
333 int completion_quote_char = 0;
335 /* If the current token was a quoted string, then this points at the
336 end of the quoted string. */
337 const char *completion_quote_end = nullptr;
339 /* If parsing for completion, then this points at the completion
340 tracker. Otherwise, this is NULL. */
341 struct completion_tracker *completion_tracker = nullptr;
344 /* A convenience macro for accessing the explicit location spec result
345 of the parser. */
346 #define PARSER_EXPLICIT(PPTR) (&PARSER_RESULT ((PPTR))->explicit_loc)
348 /* Prototypes for local functions. */
350 static void iterate_over_file_blocks
351 (struct symtab *symtab, const lookup_name_info &name,
352 domain_search_flags domain,
353 gdb::function_view<symbol_found_callback_ftype> callback);
355 static void initialize_defaults (struct symtab **default_symtab,
356 int *default_line);
358 CORE_ADDR linespec_expression_to_pc (const char **exp_ptr);
360 static std::vector<symtab_and_line> decode_objc (struct linespec_state *self,
361 linespec *ls,
362 const char *arg);
364 static std::vector<symtab *> symtabs_from_filename
365 (const char *, struct program_space *pspace);
367 static std::vector<block_symbol> find_label_symbols
368 (struct linespec_state *self,
369 const std::vector<block_symbol> &function_symbols,
370 std::vector<block_symbol> *label_funcs_ret,
371 const char *name, bool completion_mode = false);
373 static void find_linespec_symbols (struct linespec_state *self,
374 const std::vector<symtab *> &file_symtabs,
375 const char *name,
376 symbol_name_match_type name_match_type,
377 std::vector<block_symbol> *symbols,
378 std::vector<bound_minimal_symbol> *minsyms);
380 static struct line_offset
381 linespec_parse_variable (struct linespec_state *self,
382 const char *variable);
384 static int symbol_to_sal (struct symtab_and_line *result,
385 int funfirstline, struct symbol *sym);
387 static void add_matching_symbols_to_info (const char *name,
388 symbol_name_match_type name_match_type,
389 domain_search_flags domain_search_flags,
390 struct collect_info *info,
391 struct program_space *pspace);
393 static void add_all_symbol_names_from_pspace
394 (struct collect_info *info, struct program_space *pspace,
395 const std::vector<const char *> &names, domain_search_flags domain_search_flags);
397 static std::vector<symtab *>
398 collect_symtabs_from_filename (const char *file,
399 struct program_space *pspace);
401 static std::vector<symtab_and_line> decode_digits_ordinary
402 (struct linespec_state *self,
403 linespec *ls,
404 int line,
405 const linetable_entry **best_entry);
407 static std::vector<symtab_and_line> decode_digits_list_mode
408 (struct linespec_state *self,
409 linespec *ls,
410 struct symtab_and_line val);
412 static void minsym_found (struct linespec_state *self, struct objfile *objfile,
413 struct minimal_symbol *msymbol,
414 std::vector<symtab_and_line> *result);
416 static bool compare_symbols (const block_symbol &a, const block_symbol &b);
418 static bool compare_msymbols (const bound_minimal_symbol &a,
419 const bound_minimal_symbol &b);
421 /* Permitted quote characters for the parser. This is different from the
422 completer's quote characters to allow backward compatibility with the
423 previous parser. */
424 static const char linespec_quote_characters[] = "\"\'";
426 /* Lexer functions. */
428 /* Lex a number from the input in PARSER. This only supports
429 decimal numbers.
431 Return true if input is decimal numbers. Return false if not. */
433 static int
434 linespec_lexer_lex_number (linespec_parser *parser, linespec_token *tokenp)
436 tokenp->type = LSTOKEN_NUMBER;
437 LS_TOKEN_STOKEN (*tokenp).length = 0;
438 LS_TOKEN_STOKEN (*tokenp).ptr = PARSER_STREAM (parser);
440 /* Keep any sign at the start of the stream. */
441 if (*PARSER_STREAM (parser) == '+' || *PARSER_STREAM (parser) == '-')
443 ++LS_TOKEN_STOKEN (*tokenp).length;
444 ++(PARSER_STREAM (parser));
447 while (isdigit (*PARSER_STREAM (parser)))
449 ++LS_TOKEN_STOKEN (*tokenp).length;
450 ++(PARSER_STREAM (parser));
453 /* If the next character in the input buffer is not a space, comma,
454 quote, or colon, this input does not represent a number. */
455 if (*PARSER_STREAM (parser) != '\0'
456 && !isspace (*PARSER_STREAM (parser)) && *PARSER_STREAM (parser) != ','
457 && *PARSER_STREAM (parser) != ':'
458 && !strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
460 PARSER_STREAM (parser) = LS_TOKEN_STOKEN (*tokenp).ptr;
461 return 0;
464 return 1;
467 /* See linespec.h. */
469 const char *
470 linespec_lexer_lex_keyword (const char *p)
472 int i;
474 if (p != NULL)
476 for (i = 0; linespec_keywords[i] != NULL; ++i)
478 int len = strlen (linespec_keywords[i]);
480 /* If P begins with
482 - "thread" or "task" and the next character is
483 whitespace, we may have found a keyword. It is only a
484 keyword if it is not followed by another keyword.
486 - "-force-condition", the next character may be EOF
487 since this keyword does not take any arguments. Otherwise,
488 it should be followed by a keyword.
490 - "if", ALWAYS stop the lexer, since it is not possible to
491 predict what is going to appear in the condition, which can
492 only be parsed after SaLs have been found. */
493 if (strncmp (p, linespec_keywords[i], len) == 0)
495 int j;
497 if (i == FORCE_KEYWORD_INDEX && p[len] == '\0')
498 return linespec_keywords[i];
500 if (!isspace (p[len]))
501 continue;
503 if (i == FORCE_KEYWORD_INDEX)
505 p += len;
506 p = skip_spaces (p);
507 for (j = 0; linespec_keywords[j] != NULL; ++j)
509 int nextlen = strlen (linespec_keywords[j]);
511 if (strncmp (p, linespec_keywords[j], nextlen) == 0
512 && isspace (p[nextlen]))
513 return linespec_keywords[i];
516 else if (i != IF_KEYWORD_INDEX)
518 /* We matched a "thread" or "task". */
519 p += len;
520 p = skip_spaces (p);
521 for (j = 0; linespec_keywords[j] != NULL; ++j)
523 int nextlen = strlen (linespec_keywords[j]);
525 if (strncmp (p, linespec_keywords[j], nextlen) == 0
526 && isspace (p[nextlen]))
527 return NULL;
531 return linespec_keywords[i];
536 return NULL;
539 /* See description in linespec.h. */
542 is_ada_operator (const char *string)
544 const struct ada_opname_map *mapping;
546 for (mapping = ada_opname_table;
547 mapping->encoded != NULL
548 && !startswith (string, mapping->decoded); ++mapping)
551 return mapping->decoded == NULL ? 0 : strlen (mapping->decoded);
554 /* Find QUOTE_CHAR in STRING, accounting for the ':' terminal. Return
555 the location of QUOTE_CHAR, or NULL if not found. */
557 static const char *
558 skip_quote_char (const char *string, char quote_char)
560 const char *p, *last;
562 p = last = find_toplevel_char (string, quote_char);
563 while (p && *p != '\0' && *p != ':')
565 p = find_toplevel_char (p, quote_char);
566 if (p != NULL)
567 last = p++;
570 return last;
573 /* Make a writable copy of the string given in TOKEN, trimming
574 any trailing whitespace. */
576 static gdb::unique_xmalloc_ptr<char>
577 copy_token_string (linespec_token token)
579 const char *str, *s;
581 if (token.type == LSTOKEN_KEYWORD)
582 return make_unique_xstrdup (LS_TOKEN_KEYWORD (token));
584 str = LS_TOKEN_STOKEN (token).ptr;
585 s = remove_trailing_whitespace (str, str + LS_TOKEN_STOKEN (token).length);
587 return gdb::unique_xmalloc_ptr<char> (savestring (str, s - str));
590 /* Does P represent the end of a quote-enclosed linespec? */
592 static int
593 is_closing_quote_enclosed (const char *p)
595 if (strchr (linespec_quote_characters, *p))
596 ++p;
597 p = skip_spaces ((char *) p);
598 return (*p == '\0' || linespec_lexer_lex_keyword (p));
601 /* Find the end of the parameter list that starts with *INPUT.
602 This helper function assists with lexing string segments
603 which might contain valid (non-terminating) commas. */
605 static const char *
606 find_parameter_list_end (const char *input)
608 char end_char, start_char;
609 int depth;
610 const char *p;
612 start_char = *input;
613 if (start_char == '(')
614 end_char = ')';
615 else if (start_char == '<')
616 end_char = '>';
617 else
618 return NULL;
620 p = input;
621 depth = 0;
622 while (*p)
624 if (*p == start_char)
625 ++depth;
626 else if (*p == end_char)
628 if (--depth == 0)
630 ++p;
631 break;
634 ++p;
637 return p;
640 /* If the [STRING, STRING_LEN) string ends with what looks like a
641 keyword, return the keyword start offset in STRING. Return -1
642 otherwise. */
644 static size_t
645 string_find_incomplete_keyword_at_end (const char * const *keywords,
646 const char *string, size_t string_len)
648 const char *end = string + string_len;
649 const char *p = end;
651 while (p > string && *p != ' ')
652 --p;
653 if (p > string)
655 p++;
656 size_t len = end - p;
657 for (size_t i = 0; keywords[i] != NULL; ++i)
658 if (strncmp (keywords[i], p, len) == 0)
659 return p - string;
662 return -1;
665 /* Lex a string from the input in PARSER. */
667 static linespec_token
668 linespec_lexer_lex_string (linespec_parser *parser)
670 linespec_token token;
671 const char *start = PARSER_STREAM (parser);
673 token.type = LSTOKEN_STRING;
675 /* If the input stream starts with a quote character, skip to the next
676 quote character, regardless of the content. */
677 if (strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
679 const char *end;
680 char quote_char = *PARSER_STREAM (parser);
682 /* Special case: Ada operators. */
683 if (PARSER_STATE (parser)->language->la_language == language_ada
684 && quote_char == '\"')
686 int len = is_ada_operator (PARSER_STREAM (parser));
688 if (len != 0)
690 /* The input is an Ada operator. Return the quoted string
691 as-is. */
692 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
693 LS_TOKEN_STOKEN (token).length = len;
694 PARSER_STREAM (parser) += len;
695 return token;
698 /* The input does not represent an Ada operator -- fall through
699 to normal quoted string handling. */
702 /* Skip past the beginning quote. */
703 ++(PARSER_STREAM (parser));
705 /* Mark the start of the string. */
706 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
708 /* Skip to the ending quote. */
709 end = skip_quote_char (PARSER_STREAM (parser), quote_char);
711 /* This helps the completer mode decide whether we have a
712 complete string. */
713 parser->completion_quote_char = quote_char;
714 parser->completion_quote_end = end;
716 /* Error if the input did not terminate properly, unless in
717 completion mode. */
718 if (end == NULL)
720 if (parser->completion_tracker == NULL)
721 error (_("unmatched quote"));
723 /* In completion mode, we'll try to complete the incomplete
724 token. */
725 token.type = LSTOKEN_STRING;
726 while (*PARSER_STREAM (parser) != '\0')
727 PARSER_STREAM (parser)++;
728 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 1 - start;
730 else
732 /* Skip over the ending quote and mark the length of the string. */
733 PARSER_STREAM (parser) = (char *) ++end;
734 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 2 - start;
737 else
739 const char *p;
741 /* Otherwise, only identifier characters are permitted.
742 Spaces are the exception. In general, we keep spaces,
743 but only if the next characters in the input do not resolve
744 to one of the keywords.
746 This allows users to forgo quoting CV-qualifiers, template arguments,
747 and similar common language constructs. */
749 while (1)
751 if (isspace (*PARSER_STREAM (parser)))
753 p = skip_spaces (PARSER_STREAM (parser));
754 /* When we get here we know we've found something followed by
755 a space (we skip over parens and templates below).
756 So if we find a keyword now, we know it is a keyword and not,
757 say, a function name. */
758 if (linespec_lexer_lex_keyword (p) != NULL)
760 LS_TOKEN_STOKEN (token).ptr = start;
761 LS_TOKEN_STOKEN (token).length
762 = PARSER_STREAM (parser) - start;
763 return token;
766 /* Advance past the whitespace. */
767 PARSER_STREAM (parser) = p;
770 /* If the next character is EOI or (single) ':', the
771 string is complete; return the token. */
772 if (*PARSER_STREAM (parser) == 0)
774 LS_TOKEN_STOKEN (token).ptr = start;
775 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
776 return token;
778 else if (PARSER_STREAM (parser)[0] == ':')
780 /* Do not tokenize the C++ scope operator. */
781 if (PARSER_STREAM (parser)[1] == ':')
782 ++(PARSER_STREAM (parser));
784 /* Do not tokenize ABI tags such as "[abi:cxx11]". */
785 else if (PARSER_STREAM (parser) - start > 4
786 && startswith (PARSER_STREAM (parser) - 4, "[abi"))
788 /* Nothing. */
791 /* Do not tokenify if the input length so far is one
792 (i.e, a single-letter drive name) and the next character
793 is a directory separator. This allows Windows-style
794 paths to be recognized as filenames without quoting it. */
795 else if ((PARSER_STREAM (parser) - start) != 1
796 || !IS_DIR_SEPARATOR (PARSER_STREAM (parser)[1]))
798 LS_TOKEN_STOKEN (token).ptr = start;
799 LS_TOKEN_STOKEN (token).length
800 = PARSER_STREAM (parser) - start;
801 return token;
804 /* Special case: permit quote-enclosed linespecs. */
805 else if (parser->is_quote_enclosed
806 && strchr (linespec_quote_characters,
807 *PARSER_STREAM (parser))
808 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
810 LS_TOKEN_STOKEN (token).ptr = start;
811 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
812 return token;
814 /* Because commas may terminate a linespec and appear in
815 the middle of valid string input, special cases for
816 '<' and '(' are necessary. */
817 else if (*PARSER_STREAM (parser) == '<'
818 || *PARSER_STREAM (parser) == '(')
820 /* Don't interpret 'operator<' / 'operator<<' as a
821 template parameter list though. */
822 if (*PARSER_STREAM (parser) == '<'
823 && (PARSER_STATE (parser)->language->la_language
824 == language_cplus)
825 && (PARSER_STREAM (parser) - start) >= CP_OPERATOR_LEN)
827 const char *op = PARSER_STREAM (parser);
829 while (op > start && isspace (op[-1]))
830 op--;
831 if (op - start >= CP_OPERATOR_LEN)
833 op -= CP_OPERATOR_LEN;
834 if (strncmp (op, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
835 && (op == start
836 || !(isalnum (op[-1]) || op[-1] == '_')))
838 /* This is an operator name. Keep going. */
839 ++(PARSER_STREAM (parser));
840 if (*PARSER_STREAM (parser) == '<')
841 ++(PARSER_STREAM (parser));
842 continue;
847 const char *end = find_parameter_list_end (PARSER_STREAM (parser));
848 PARSER_STREAM (parser) = end;
850 /* Don't loop around to the normal \0 case above because
851 we don't want to misinterpret a potential keyword at
852 the end of the token when the string isn't
853 "()<>"-balanced. This handles "b
854 function(thread<tab>" in completion mode. */
855 if (*end == '\0')
857 LS_TOKEN_STOKEN (token).ptr = start;
858 LS_TOKEN_STOKEN (token).length
859 = PARSER_STREAM (parser) - start;
860 return token;
862 else
863 continue;
865 /* Commas are terminators, but not if they are part of an
866 operator name. */
867 else if (*PARSER_STREAM (parser) == ',')
869 if ((PARSER_STATE (parser)->language->la_language
870 == language_cplus)
871 && (PARSER_STREAM (parser) - start) > CP_OPERATOR_LEN)
873 const char *op = strstr (start, CP_OPERATOR_STR);
875 if (op != NULL && is_operator_name (op))
877 /* This is an operator name. Keep going. */
878 ++(PARSER_STREAM (parser));
879 continue;
883 /* Comma terminates the string. */
884 LS_TOKEN_STOKEN (token).ptr = start;
885 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
886 return token;
889 /* Advance the stream. */
890 gdb_assert (*(PARSER_STREAM (parser)) != '\0');
891 ++(PARSER_STREAM (parser));
895 return token;
898 /* Lex a single linespec token from PARSER. */
900 static linespec_token
901 linespec_lexer_lex_one (linespec_parser *parser)
903 const char *keyword;
905 if (parser->lexer.current.type == LSTOKEN_CONSUMED)
907 /* Skip any whitespace. */
908 PARSER_STREAM (parser) = skip_spaces (PARSER_STREAM (parser));
910 /* Check for a keyword, they end the linespec. */
911 keyword = linespec_lexer_lex_keyword (PARSER_STREAM (parser));
912 if (keyword != NULL)
914 parser->lexer.current.type = LSTOKEN_KEYWORD;
915 LS_TOKEN_KEYWORD (parser->lexer.current) = keyword;
916 /* We do not advance the stream here intentionally:
917 we would like lexing to stop when a keyword is seen.
919 PARSER_STREAM (parser) += strlen (keyword); */
921 return parser->lexer.current;
924 /* Handle other tokens. */
925 switch (*PARSER_STREAM (parser))
927 case 0:
928 parser->lexer.current.type = LSTOKEN_EOI;
929 break;
931 case '+': case '-':
932 case '0': case '1': case '2': case '3': case '4':
933 case '5': case '6': case '7': case '8': case '9':
934 if (!linespec_lexer_lex_number (parser, &(parser->lexer.current)))
935 parser->lexer.current = linespec_lexer_lex_string (parser);
936 break;
938 case ':':
939 /* If we have a scope operator, lex the input as a string.
940 Otherwise, return LSTOKEN_COLON. */
941 if (PARSER_STREAM (parser)[1] == ':')
942 parser->lexer.current = linespec_lexer_lex_string (parser);
943 else
945 parser->lexer.current.type = LSTOKEN_COLON;
946 ++(PARSER_STREAM (parser));
948 break;
950 case '\'': case '\"':
951 /* Special case: permit quote-enclosed linespecs. */
952 if (parser->is_quote_enclosed
953 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
955 ++(PARSER_STREAM (parser));
956 parser->lexer.current.type = LSTOKEN_EOI;
958 else
959 parser->lexer.current = linespec_lexer_lex_string (parser);
960 break;
962 case ',':
963 parser->lexer.current.type = LSTOKEN_COMMA;
964 LS_TOKEN_STOKEN (parser->lexer.current).ptr
965 = PARSER_STREAM (parser);
966 LS_TOKEN_STOKEN (parser->lexer.current).length = 1;
967 ++(PARSER_STREAM (parser));
968 break;
970 default:
971 /* If the input is not a number, it must be a string.
972 [Keywords were already considered above.] */
973 parser->lexer.current = linespec_lexer_lex_string (parser);
974 break;
978 return parser->lexer.current;
981 /* Consume the current token and return the next token in PARSER's
982 input stream. Also advance the completion word for completion
983 mode. */
985 static linespec_token
986 linespec_lexer_consume_token (linespec_parser *parser)
988 gdb_assert (parser->lexer.current.type != LSTOKEN_EOI);
990 bool advance_word = (parser->lexer.current.type != LSTOKEN_STRING
991 || *PARSER_STREAM (parser) != '\0');
993 /* If we're moving past a string to some other token, it must be the
994 quote was terminated. */
995 if (parser->completion_quote_char)
997 gdb_assert (parser->lexer.current.type == LSTOKEN_STRING);
999 /* If the string was the last (non-EOI) token, we're past the
1000 quote, but remember that for later. */
1001 if (*PARSER_STREAM (parser) != '\0')
1003 parser->completion_quote_char = '\0';
1004 parser->completion_quote_end = NULL;;
1008 parser->lexer.current.type = LSTOKEN_CONSUMED;
1009 linespec_lexer_lex_one (parser);
1011 if (parser->lexer.current.type == LSTOKEN_STRING)
1013 /* Advance the completion word past a potential initial
1014 quote-char. */
1015 parser->completion_word = LS_TOKEN_STOKEN (parser->lexer.current).ptr;
1017 else if (advance_word)
1019 /* Advance the completion word past any whitespace. */
1020 parser->completion_word = PARSER_STREAM (parser);
1023 return parser->lexer.current;
1026 /* Return the next token without consuming the current token. */
1028 static linespec_token
1029 linespec_lexer_peek_token (linespec_parser *parser)
1031 linespec_token next;
1032 const char *saved_stream = PARSER_STREAM (parser);
1033 linespec_token saved_token = parser->lexer.current;
1034 int saved_completion_quote_char = parser->completion_quote_char;
1035 const char *saved_completion_quote_end = parser->completion_quote_end;
1036 const char *saved_completion_word = parser->completion_word;
1038 next = linespec_lexer_consume_token (parser);
1039 PARSER_STREAM (parser) = saved_stream;
1040 parser->lexer.current = saved_token;
1041 parser->completion_quote_char = saved_completion_quote_char;
1042 parser->completion_quote_end = saved_completion_quote_end;
1043 parser->completion_word = saved_completion_word;
1044 return next;
1047 /* Helper functions. */
1049 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
1050 the new sal, if needed. If not NULL, SYMNAME is the name of the
1051 symbol to use when constructing the new canonical name.
1053 If LITERAL_CANONICAL is non-zero, SYMNAME will be used as the
1054 canonical name for the SAL. */
1056 static void
1057 add_sal_to_sals (struct linespec_state *self,
1058 std::vector<symtab_and_line> *sals,
1059 struct symtab_and_line *sal,
1060 const char *symname, int literal_canonical)
1062 sals->push_back (*sal);
1064 if (self->canonical)
1066 struct linespec_canonical_name *canonical;
1068 self->canonical_names = XRESIZEVEC (struct linespec_canonical_name,
1069 self->canonical_names,
1070 sals->size ());
1071 canonical = &self->canonical_names[sals->size () - 1];
1072 if (!literal_canonical && sal->symtab)
1074 symtab_to_fullname (sal->symtab);
1076 /* Note that the filter doesn't have to be a valid linespec
1077 input. We only apply the ":LINE" treatment to Ada for
1078 the time being. */
1079 if (symname != NULL && sal->line != 0
1080 && self->language->la_language == language_ada)
1081 canonical->suffix = xstrprintf ("%s:%d", symname,
1082 sal->line).release ();
1083 else if (symname != NULL)
1084 canonical->suffix = xstrdup (symname);
1085 else
1086 canonical->suffix = xstrprintf ("%d", sal->line).release ();
1087 canonical->symtab = sal->symtab;
1089 else
1091 if (symname != NULL)
1092 canonical->suffix = xstrdup (symname);
1093 else
1094 canonical->suffix = xstrdup ("<unknown>");
1095 canonical->symtab = NULL;
1100 /* A hash function for address_entry. */
1102 static hashval_t
1103 hash_address_entry (const void *p)
1105 const struct address_entry *aep = (const struct address_entry *) p;
1106 hashval_t hash;
1108 hash = iterative_hash_object (aep->pspace, 0);
1109 return iterative_hash_object (aep->addr, hash);
1112 /* An equality function for address_entry. */
1114 static int
1115 eq_address_entry (const void *a, const void *b)
1117 const struct address_entry *aea = (const struct address_entry *) a;
1118 const struct address_entry *aeb = (const struct address_entry *) b;
1120 return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
1123 /* Check whether the address, represented by PSPACE and ADDR, is
1124 already in the set. If so, return 0. Otherwise, add it and return
1125 1. */
1127 static int
1128 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
1130 struct address_entry e, *p;
1131 void **slot;
1133 e.pspace = pspace;
1134 e.addr = addr;
1135 slot = htab_find_slot (set, &e, INSERT);
1136 if (*slot)
1137 return 0;
1139 p = XNEW (struct address_entry);
1140 memcpy (p, &e, sizeof (struct address_entry));
1141 *slot = p;
1143 return 1;
1146 /* A helper that walks over all matching symtabs in all objfiles and
1147 calls CALLBACK for each symbol matching NAME. If SEARCH_PSPACE is
1148 not NULL, then the search is restricted to just that program
1149 space. If INCLUDE_INLINE is true then symbols representing
1150 inlined instances of functions will be included in the result. */
1152 static void
1153 iterate_over_all_matching_symtabs
1154 (struct linespec_state *state,
1155 const lookup_name_info &lookup_name,
1156 const domain_search_flags domain,
1157 struct program_space *search_pspace, bool include_inline,
1158 gdb::function_view<symbol_found_callback_ftype> callback)
1160 for (struct program_space *pspace : program_spaces)
1162 if (search_pspace != NULL && search_pspace != pspace)
1163 continue;
1164 if (pspace->executing_startup)
1165 continue;
1167 set_current_program_space (pspace);
1169 for (objfile *objfile : current_program_space->objfiles ())
1171 objfile->expand_symtabs_matching (NULL, &lookup_name, NULL, NULL,
1172 (SEARCH_GLOBAL_BLOCK
1173 | SEARCH_STATIC_BLOCK),
1174 domain);
1176 for (compunit_symtab *cu : objfile->compunits ())
1178 struct symtab *symtab = cu->primary_filetab ();
1180 iterate_over_file_blocks (symtab, lookup_name, domain, callback);
1182 if (include_inline)
1184 const struct block *block;
1185 int i;
1186 const blockvector *bv = symtab->compunit ()->blockvector ();
1188 for (i = FIRST_LOCAL_BLOCK; i < bv->num_blocks (); i++)
1190 block = bv->block (i);
1191 state->language->iterate_over_symbols
1192 (block, lookup_name, domain,
1193 [&] (block_symbol *bsym)
1195 /* Restrict calls to CALLBACK to symbols
1196 representing inline symbols only. */
1197 if (bsym->symbol->is_inlined ())
1198 return callback (bsym);
1199 return true;
1208 /* Returns the block to be used for symbol searches from
1209 the current location. */
1211 static const struct block *
1212 get_current_search_block (void)
1214 /* get_selected_block can change the current language when there is
1215 no selected frame yet. */
1216 scoped_restore_current_language save_language;
1217 return get_selected_block (0);
1220 /* Iterate over static and global blocks. */
1222 static void
1223 iterate_over_file_blocks
1224 (struct symtab *symtab, const lookup_name_info &name,
1225 domain_search_flags domain,
1226 gdb::function_view<symbol_found_callback_ftype> callback)
1228 const struct block *block;
1230 for (block = symtab->compunit ()->blockvector ()->static_block ();
1231 block != NULL;
1232 block = block->superblock ())
1233 current_language->iterate_over_symbols (block, name, domain, callback);
1236 /* A helper for find_method. This finds all methods in type T of
1237 language T_LANG which match NAME. It adds matching symbol names to
1238 RESULT_NAMES, and adds T's direct superclasses to SUPERCLASSES. */
1240 static void
1241 find_methods (struct type *t, enum language t_lang, const char *name,
1242 std::vector<const char *> *result_names,
1243 std::vector<struct type *> *superclasses)
1245 int ibase;
1246 const char *class_name = t->name ();
1248 /* Ignore this class if it doesn't have a name. This is ugly, but
1249 unless we figure out how to get the physname without the name of
1250 the class, then the loop can't do any good. */
1251 if (class_name)
1253 int method_counter;
1254 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1255 symbol_name_matcher_ftype *symbol_name_compare
1256 = language_def (t_lang)->get_symbol_name_matcher (lookup_name);
1258 t = check_typedef (t);
1260 /* Loop over each method name. At this level, all overloads of a name
1261 are counted as a single name. There is an inner loop which loops over
1262 each overload. */
1264 for (method_counter = TYPE_NFN_FIELDS (t) - 1;
1265 method_counter >= 0;
1266 --method_counter)
1268 const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
1270 if (symbol_name_compare (method_name, lookup_name, NULL))
1272 int field_counter;
1274 for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
1275 - 1);
1276 field_counter >= 0;
1277 --field_counter)
1279 struct fn_field *f;
1280 const char *phys_name;
1282 f = TYPE_FN_FIELDLIST1 (t, method_counter);
1283 if (TYPE_FN_FIELD_STUB (f, field_counter))
1284 continue;
1285 phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
1286 result_names->push_back (phys_name);
1292 for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
1293 superclasses->push_back (TYPE_BASECLASS (t, ibase));
1296 /* The string equivalent of find_toplevel_char. Returns a pointer
1297 to the location of NEEDLE in HAYSTACK, ignoring any occurrences
1298 inside "()" and "<>". Returns NULL if NEEDLE was not found. */
1300 static const char *
1301 find_toplevel_string (const char *haystack, const char *needle)
1303 const char *s = haystack;
1307 s = find_toplevel_char (s, *needle);
1309 if (s != NULL)
1311 /* Found first char in HAYSTACK; check rest of string. */
1312 if (startswith (s, needle))
1313 return s;
1315 /* Didn't find it; loop over HAYSTACK, looking for the next
1316 instance of the first character of NEEDLE. */
1317 ++s;
1320 while (s != NULL && *s != '\0');
1322 /* NEEDLE was not found in HAYSTACK. */
1323 return NULL;
1326 /* Convert CANONICAL to its string representation using
1327 symtab_to_fullname for SYMTAB. */
1329 static std::string
1330 canonical_to_fullform (const struct linespec_canonical_name *canonical)
1332 if (canonical->symtab == NULL)
1333 return canonical->suffix;
1334 else
1335 return string_printf ("%s:%s", symtab_to_fullname (canonical->symtab),
1336 canonical->suffix);
1339 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
1340 and store the result in SELF->CANONICAL. */
1342 static void
1343 filter_results (struct linespec_state *self,
1344 std::vector<symtab_and_line> *result,
1345 const std::vector<const char *> &filters)
1347 for (const char *name : filters)
1349 linespec_sals lsal;
1351 for (size_t j = 0; j < result->size (); ++j)
1353 const struct linespec_canonical_name *canonical;
1355 canonical = &self->canonical_names[j];
1356 std::string fullform = canonical_to_fullform (canonical);
1358 if (name == fullform)
1359 lsal.sals.push_back ((*result)[j]);
1362 if (!lsal.sals.empty ())
1364 lsal.canonical = xstrdup (name);
1365 self->canonical->lsals.push_back (std::move (lsal));
1369 self->canonical->pre_expanded = 0;
1372 /* Store RESULT into SELF->CANONICAL. */
1374 static void
1375 convert_results_to_lsals (struct linespec_state *self,
1376 std::vector<symtab_and_line> *result)
1378 struct linespec_sals lsal;
1380 lsal.canonical = NULL;
1381 lsal.sals = std::move (*result);
1382 self->canonical->lsals.push_back (std::move (lsal));
1385 /* A structure that contains two string representations of a struct
1386 linespec_canonical_name:
1387 - one where the symtab's fullname is used;
1388 - one where the filename followed the "set filename-display"
1389 setting. */
1391 struct decode_line_2_item
1393 decode_line_2_item (std::string &&fullform_, std::string &&displayform_,
1394 bool selected_)
1395 : fullform (std::move (fullform_)),
1396 displayform (std::move (displayform_)),
1397 selected (selected_)
1401 /* The form using symtab_to_fullname. */
1402 std::string fullform;
1404 /* The form using symtab_to_filename_for_display. */
1405 std::string displayform;
1407 /* Field is initialized to zero and it is set to one if the user
1408 requested breakpoint for this entry. */
1409 unsigned int selected : 1;
1412 /* Helper for std::sort to sort decode_line_2_item entries by
1413 DISPLAYFORM and secondarily by FULLFORM. */
1415 static bool
1416 decode_line_2_compare_items (const decode_line_2_item &a,
1417 const decode_line_2_item &b)
1419 if (a.displayform != b.displayform)
1420 return a.displayform < b.displayform;
1421 return a.fullform < b.fullform;
1424 /* Handle multiple results in RESULT depending on SELECT_MODE. This
1425 will either return normally, throw an exception on multiple
1426 results, or present a menu to the user. On return, the SALS vector
1427 in SELF->CANONICAL is set up properly. */
1429 static void
1430 decode_line_2 (struct linespec_state *self,
1431 std::vector<symtab_and_line> *result,
1432 const char *select_mode)
1434 const char *args;
1435 const char *prompt;
1436 int i;
1437 std::vector<const char *> filters;
1438 std::vector<struct decode_line_2_item> items;
1440 gdb_assert (select_mode != multiple_symbols_all);
1441 gdb_assert (self->canonical != NULL);
1442 gdb_assert (!result->empty ());
1444 /* Prepare ITEMS array. */
1445 for (i = 0; i < result->size (); ++i)
1447 const struct linespec_canonical_name *canonical;
1448 std::string displayform;
1450 canonical = &self->canonical_names[i];
1451 gdb_assert (canonical->suffix != NULL);
1453 std::string fullform = canonical_to_fullform (canonical);
1455 if (canonical->symtab == NULL)
1456 displayform = canonical->suffix;
1457 else
1459 const char *fn_for_display;
1461 fn_for_display = symtab_to_filename_for_display (canonical->symtab);
1462 displayform = string_printf ("%s:%s", fn_for_display,
1463 canonical->suffix);
1466 items.emplace_back (std::move (fullform), std::move (displayform),
1467 false);
1470 /* Sort the list of method names. */
1471 std::sort (items.begin (), items.end (), decode_line_2_compare_items);
1473 /* Remove entries with the same FULLFORM. */
1474 items.erase (std::unique (items.begin (), items.end (),
1475 [] (const struct decode_line_2_item &a,
1476 const struct decode_line_2_item &b)
1478 return a.fullform == b.fullform;
1480 items.end ());
1482 if (select_mode == multiple_symbols_cancel && items.size () > 1)
1483 error (_("canceled because the command is ambiguous\n"
1484 "See set/show multiple-symbol."));
1486 if (select_mode == multiple_symbols_all || items.size () == 1)
1488 convert_results_to_lsals (self, result);
1489 return;
1492 printf_unfiltered (_("[0] cancel\n[1] all\n"));
1493 for (i = 0; i < items.size (); i++)
1494 printf_unfiltered ("[%d] %s\n", i + 2, items[i].displayform.c_str ());
1496 prompt = getenv ("PS2");
1497 if (prompt == NULL)
1499 prompt = "> ";
1502 std::string buffer;
1503 args = command_line_input (buffer, prompt, "overload-choice");
1505 if (args == 0 || *args == 0)
1506 error_no_arg (_("one or more choice numbers"));
1508 number_or_range_parser parser (args);
1509 while (!parser.finished ())
1511 int num = parser.get_number ();
1513 if (num == 0)
1514 error (_("canceled"));
1515 else if (num == 1)
1517 /* We intentionally make this result in a single breakpoint,
1518 contrary to what older versions of gdb did. The
1519 rationale is that this lets a user get the
1520 multiple_symbols_all behavior even with the 'ask'
1521 setting; and he can get separate breakpoints by entering
1522 "2-57" at the query. */
1523 convert_results_to_lsals (self, result);
1524 return;
1527 num -= 2;
1528 if (num >= items.size ())
1529 printf_unfiltered (_("No choice number %d.\n"), num);
1530 else
1532 struct decode_line_2_item *item = &items[num];
1534 if (!item->selected)
1536 filters.push_back (item->fullform.c_str ());
1537 item->selected = 1;
1539 else
1541 printf_unfiltered (_("duplicate request for %d ignored.\n"),
1542 num + 2);
1547 filter_results (self, result, filters);
1552 /* The parser of linespec itself. */
1554 /* Throw an appropriate error when SYMBOL is not found (optionally in
1555 FILENAME). */
1557 static void ATTRIBUTE_NORETURN
1558 symbol_not_found_error (const char *symbol, const char *filename)
1560 if (symbol == NULL)
1561 symbol = "";
1563 if (!have_full_symbols ()
1564 && !have_partial_symbols ()
1565 && !have_minimal_symbols ())
1566 throw_error (NOT_FOUND_ERROR,
1567 _("No symbol table is loaded. Use the \"file\" command."));
1569 /* If SYMBOL starts with '$', the user attempted to either lookup
1570 a function/variable in his code starting with '$' or an internal
1571 variable of that name. Since we do not know which, be concise and
1572 explain both possibilities. */
1573 if (*symbol == '$')
1575 if (filename)
1576 throw_error (NOT_FOUND_ERROR,
1577 _("Undefined convenience variable or function \"%s\" "
1578 "not defined in \"%s\"."), symbol, filename);
1579 else
1580 throw_error (NOT_FOUND_ERROR,
1581 _("Undefined convenience variable or function \"%s\" "
1582 "not defined."), symbol);
1584 else
1586 if (filename)
1587 throw_error (NOT_FOUND_ERROR,
1588 _("Function \"%s\" not defined in \"%s\"."),
1589 symbol, filename);
1590 else
1591 throw_error (NOT_FOUND_ERROR,
1592 _("Function \"%s\" not defined."), symbol);
1596 /* Throw an appropriate error when an unexpected token is encountered
1597 in the input. */
1599 static void ATTRIBUTE_NORETURN
1600 unexpected_linespec_error (linespec_parser *parser)
1602 linespec_token token;
1603 static const char * token_type_strings[]
1604 = {"keyword", "colon", "string", "number", "comma", "end of input"};
1606 /* Get the token that generated the error. */
1607 token = linespec_lexer_lex_one (parser);
1609 /* Finally, throw the error. */
1610 if (token.type == LSTOKEN_STRING || token.type == LSTOKEN_NUMBER
1611 || token.type == LSTOKEN_KEYWORD)
1613 gdb::unique_xmalloc_ptr<char> string = copy_token_string (token);
1614 throw_error (GENERIC_ERROR,
1615 _("malformed linespec error: unexpected %s, \"%s\""),
1616 token_type_strings[token.type], string.get ());
1618 else
1619 throw_error (GENERIC_ERROR,
1620 _("malformed linespec error: unexpected %s"),
1621 token_type_strings[token.type]);
1624 /* Throw an undefined label error. */
1626 static void ATTRIBUTE_NORETURN
1627 undefined_label_error (const char *function, const char *label)
1629 if (function != NULL)
1630 throw_error (NOT_FOUND_ERROR,
1631 _("No label \"%s\" defined in function \"%s\"."),
1632 label, function);
1633 else
1634 throw_error (NOT_FOUND_ERROR,
1635 _("No label \"%s\" defined in current function."),
1636 label);
1639 /* Throw a source file not found error. */
1641 static void ATTRIBUTE_NORETURN
1642 source_file_not_found_error (const char *name)
1644 throw_error (NOT_FOUND_ERROR, _("No source file named %s."), name);
1647 /* Unless at EIO, save the current stream position as completion word
1648 point, and consume the next token. */
1650 static linespec_token
1651 save_stream_and_consume_token (linespec_parser *parser)
1653 if (linespec_lexer_peek_token (parser).type != LSTOKEN_EOI)
1654 parser->completion_word = PARSER_STREAM (parser);
1655 return linespec_lexer_consume_token (parser);
1658 /* See description in linespec.h. */
1660 struct line_offset
1661 linespec_parse_line_offset (const char *string)
1663 const char *start = string;
1664 struct line_offset line_offset;
1666 if (*string == '+')
1668 line_offset.sign = LINE_OFFSET_PLUS;
1669 ++string;
1671 else if (*string == '-')
1673 line_offset.sign = LINE_OFFSET_MINUS;
1674 ++string;
1676 else
1677 line_offset.sign = LINE_OFFSET_NONE;
1679 if (*string != '\0' && !isdigit (*string))
1680 error (_("malformed line offset: \"%s\""), start);
1682 /* Right now, we only allow base 10 for offsets. */
1683 line_offset.offset = atoi (string);
1684 return line_offset;
1687 /* In completion mode, if the user is still typing the number, there's
1688 no possible completion to offer. But if there's already input past
1689 the number, setup to expect NEXT. */
1691 static void
1692 set_completion_after_number (linespec_parser *parser,
1693 linespec_complete_what next)
1695 if (*PARSER_STREAM (parser) == ' ')
1697 parser->completion_word = skip_spaces (PARSER_STREAM (parser) + 1);
1698 parser->complete_what = next;
1700 else
1702 parser->completion_word = PARSER_STREAM (parser);
1703 parser->complete_what = linespec_complete_what::NOTHING;
1707 /* Parse the basic_spec in PARSER's input. */
1709 static void
1710 linespec_parse_basic (linespec_parser *parser)
1712 gdb::unique_xmalloc_ptr<char> name;
1713 linespec_token token;
1715 /* Get the next token. */
1716 token = linespec_lexer_lex_one (parser);
1718 /* If it is EOI or KEYWORD, issue an error. */
1719 if (token.type == LSTOKEN_KEYWORD)
1721 parser->complete_what = linespec_complete_what::NOTHING;
1722 unexpected_linespec_error (parser);
1724 else if (token.type == LSTOKEN_EOI)
1726 unexpected_linespec_error (parser);
1728 /* If it is a LSTOKEN_NUMBER, we have an offset. */
1729 else if (token.type == LSTOKEN_NUMBER)
1731 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1733 /* Record the line offset and get the next token. */
1734 name = copy_token_string (token);
1735 PARSER_EXPLICIT (parser)->line_offset
1736 = linespec_parse_line_offset (name.get ());
1738 /* Get the next token. */
1739 token = linespec_lexer_consume_token (parser);
1741 /* If the next token is a comma, stop parsing and return. */
1742 if (token.type == LSTOKEN_COMMA)
1744 parser->complete_what = linespec_complete_what::NOTHING;
1745 return;
1748 /* If the next token is anything but EOI or KEYWORD, issue
1749 an error. */
1750 if (token.type != LSTOKEN_KEYWORD && token.type != LSTOKEN_EOI)
1751 unexpected_linespec_error (parser);
1754 if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1755 return;
1757 /* Next token must be LSTOKEN_STRING. */
1758 if (token.type != LSTOKEN_STRING)
1760 parser->complete_what = linespec_complete_what::NOTHING;
1761 unexpected_linespec_error (parser);
1764 /* The current token will contain the name of a function, method,
1765 or label. */
1766 name = copy_token_string (token);
1768 if (parser->completion_tracker != NULL)
1770 /* If the function name ends with a ":", then this may be an
1771 incomplete "::" scope operator instead of a label separator.
1772 E.g.,
1773 "b klass:<tab>"
1774 which should expand to:
1775 "b klass::method()"
1777 Do a tentative completion assuming the later. If we find
1778 completions, advance the stream past the colon token and make
1779 it part of the function name/token. */
1781 if (!parser->completion_quote_char
1782 && strcmp (PARSER_STREAM (parser), ":") == 0)
1784 completion_tracker tmp_tracker (false);
1785 const char *source_filename
1786 = PARSER_EXPLICIT (parser)->source_filename.get ();
1787 symbol_name_match_type match_type
1788 = PARSER_EXPLICIT (parser)->func_name_match_type;
1790 linespec_complete_function (tmp_tracker,
1791 parser->completion_word,
1792 match_type,
1793 source_filename);
1795 if (tmp_tracker.have_completions ())
1797 PARSER_STREAM (parser)++;
1798 LS_TOKEN_STOKEN (token).length++;
1800 name.reset (savestring (parser->completion_word,
1801 (PARSER_STREAM (parser)
1802 - parser->completion_word)));
1806 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1808 else
1810 std::vector<block_symbol> symbols;
1811 std::vector<bound_minimal_symbol> minimal_symbols;
1813 /* Try looking it up as a function/method. */
1814 find_linespec_symbols (PARSER_STATE (parser),
1815 PARSER_RESULT (parser)->file_symtabs, name.get (),
1816 PARSER_EXPLICIT (parser)->func_name_match_type,
1817 &symbols, &minimal_symbols);
1819 if (!symbols.empty () || !minimal_symbols.empty ())
1821 PARSER_RESULT (parser)->function_symbols = std::move (symbols);
1822 PARSER_RESULT (parser)->minimal_symbols = std::move (minimal_symbols);
1823 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1825 else
1827 /* NAME was not a function or a method. So it must be a label
1828 name or user specified variable like "break foo.c:$zippo". */
1829 std::vector<block_symbol> labels
1830 = find_label_symbols (PARSER_STATE (parser), {}, &symbols,
1831 name.get ());
1833 if (!labels.empty ())
1835 PARSER_RESULT (parser)->labels.label_symbols = std::move (labels);
1836 PARSER_RESULT (parser)->labels.function_symbols
1837 = std::move (symbols);
1838 PARSER_EXPLICIT (parser)->label_name = std::move (name);
1840 else if (token.type == LSTOKEN_STRING
1841 && *LS_TOKEN_STOKEN (token).ptr == '$')
1843 /* User specified a convenience variable or history value. */
1844 PARSER_EXPLICIT (parser)->line_offset
1845 = linespec_parse_variable (PARSER_STATE (parser), name.get ());
1847 if (PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN)
1849 /* The user-specified variable was not valid. Do not
1850 throw an error here. parse_linespec will do it for us. */
1851 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1852 return;
1855 else
1857 /* The name is also not a label. Abort parsing. Do not throw
1858 an error here. parse_linespec will do it for us. */
1860 /* Save a copy of the name we were trying to lookup. */
1861 PARSER_EXPLICIT (parser)->function_name = std::move (name);
1862 return;
1867 int previous_qc = parser->completion_quote_char;
1869 /* Get the next token. */
1870 token = linespec_lexer_consume_token (parser);
1872 if (token.type == LSTOKEN_EOI)
1874 if (previous_qc && !parser->completion_quote_char)
1875 parser->complete_what = linespec_complete_what::KEYWORD;
1877 else if (token.type == LSTOKEN_COLON)
1879 /* User specified a label or a lineno. */
1880 token = linespec_lexer_consume_token (parser);
1882 if (token.type == LSTOKEN_NUMBER)
1884 /* User specified an offset. Record the line offset and
1885 get the next token. */
1886 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1888 name = copy_token_string (token);
1889 PARSER_EXPLICIT (parser)->line_offset
1890 = linespec_parse_line_offset (name.get ());
1892 /* Get the next token. */
1893 token = linespec_lexer_consume_token (parser);
1895 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
1897 parser->complete_what = linespec_complete_what::LABEL;
1899 else if (token.type == LSTOKEN_STRING)
1901 parser->complete_what = linespec_complete_what::LABEL;
1903 /* If we have text after the label separated by whitespace
1904 (e.g., "b func():lab i<tab>"), don't consider it part of
1905 the label. In completion mode that should complete to
1906 "if", in normal mode, the 'i' should be treated as
1907 garbage. */
1908 if (parser->completion_quote_char == '\0')
1910 const char *ptr = LS_TOKEN_STOKEN (token).ptr;
1911 for (size_t i = 0; i < LS_TOKEN_STOKEN (token).length; i++)
1913 if (ptr[i] == ' ')
1915 LS_TOKEN_STOKEN (token).length = i;
1916 PARSER_STREAM (parser) = skip_spaces (ptr + i + 1);
1917 break;
1922 if (parser->completion_tracker != NULL)
1924 if (PARSER_STREAM (parser)[-1] == ' ')
1926 parser->completion_word = PARSER_STREAM (parser);
1927 parser->complete_what = linespec_complete_what::KEYWORD;
1930 else
1932 std::vector<block_symbol> symbols;
1934 /* Grab a copy of the label's name and look it up. */
1935 name = copy_token_string (token);
1936 std::vector<block_symbol> labels
1937 = find_label_symbols (PARSER_STATE (parser),
1938 PARSER_RESULT (parser)->function_symbols,
1939 &symbols, name.get ());
1941 if (!labels.empty ())
1943 PARSER_RESULT (parser)->labels.label_symbols
1944 = std::move (labels);
1945 PARSER_RESULT (parser)->labels.function_symbols
1946 = std::move (symbols);
1947 PARSER_EXPLICIT (parser)->label_name = std::move (name);
1949 else
1951 /* We don't know what it was, but it isn't a label. */
1952 undefined_label_error
1953 (PARSER_EXPLICIT (parser)->function_name.get (),
1954 name.get ());
1959 /* Check for a line offset. */
1960 token = save_stream_and_consume_token (parser);
1961 if (token.type == LSTOKEN_COLON)
1963 /* Get the next token. */
1964 token = linespec_lexer_consume_token (parser);
1966 /* It must be a line offset. */
1967 if (token.type != LSTOKEN_NUMBER)
1968 unexpected_linespec_error (parser);
1970 /* Record the line offset and get the next token. */
1971 name = copy_token_string (token);
1973 PARSER_EXPLICIT (parser)->line_offset
1974 = linespec_parse_line_offset (name.get ());
1976 /* Get the next token. */
1977 token = linespec_lexer_consume_token (parser);
1980 else
1982 /* Trailing ':' in the input. Issue an error. */
1983 unexpected_linespec_error (parser);
1988 /* Canonicalize the linespec contained in LS. The result is saved into
1989 STATE->canonical. This function handles both linespec and explicit
1990 locations. */
1992 static void
1993 canonicalize_linespec (struct linespec_state *state, const linespec *ls)
1995 /* If canonicalization was not requested, no need to do anything. */
1996 if (!state->canonical)
1997 return;
1999 /* Save everything as an explicit location. */
2000 state->canonical->locspec = ls->explicit_loc.clone ();
2001 explicit_location_spec *explicit_loc
2002 = as_explicit_location_spec (state->canonical->locspec.get ());
2004 if (explicit_loc->label_name != NULL)
2006 state->canonical->special_display = 1;
2008 if (explicit_loc->function_name == NULL)
2010 /* No function was specified, so add the symbol name. */
2011 gdb_assert (ls->labels.function_symbols.size () == 1);
2012 block_symbol s = ls->labels.function_symbols.front ();
2013 explicit_loc->function_name
2014 = make_unique_xstrdup (s.symbol->natural_name ());
2018 /* If this location originally came from a linespec, save a string
2019 representation of it for display and saving to file. */
2020 if (state->is_linespec)
2021 explicit_loc->set_string (explicit_loc->to_linespec ());
2024 /* Given a line offset in LS, construct the relevant SALs. */
2026 static std::vector<symtab_and_line>
2027 create_sals_line_offset (struct linespec_state *self,
2028 linespec *ls)
2030 int use_default = 0;
2032 /* This is where we need to make sure we have good defaults.
2033 We must guarantee that this section of code is never executed
2034 when we are called with just a function name, since
2035 set_default_source_symtab_and_line uses
2036 select_source_symtab that calls us with such an argument. */
2038 if (ls->file_symtabs.size () == 1
2039 && ls->file_symtabs.front () == nullptr)
2041 set_current_program_space (self->program_space);
2043 /* Make sure we have at least a default source line. */
2044 set_default_source_symtab_and_line ();
2045 initialize_defaults (&self->default_symtab, &self->default_line);
2046 ls->file_symtabs
2047 = collect_symtabs_from_filename (self->default_symtab->filename,
2048 self->search_pspace);
2049 use_default = 1;
2052 symtab_and_line val;
2053 val.line = ls->explicit_loc.line_offset.offset;
2054 switch (ls->explicit_loc.line_offset.sign)
2056 case LINE_OFFSET_PLUS:
2057 if (ls->explicit_loc.line_offset.offset == 0)
2058 val.line = 5;
2059 if (use_default)
2060 val.line = self->default_line + val.line;
2061 break;
2063 case LINE_OFFSET_MINUS:
2064 if (ls->explicit_loc.line_offset.offset == 0)
2065 val.line = 15;
2066 if (use_default)
2067 val.line = self->default_line - val.line;
2068 else
2069 val.line = -val.line;
2070 break;
2072 case LINE_OFFSET_NONE:
2073 break; /* No need to adjust val.line. */
2076 std::vector<symtab_and_line> values;
2077 if (self->list_mode)
2078 values = decode_digits_list_mode (self, ls, val);
2079 else
2081 const linetable_entry *best_entry = NULL;
2082 int i, j;
2084 std::vector<symtab_and_line> intermediate_results
2085 = decode_digits_ordinary (self, ls, val.line, &best_entry);
2086 if (intermediate_results.empty () && best_entry != NULL)
2087 intermediate_results = decode_digits_ordinary (self, ls,
2088 best_entry->line,
2089 &best_entry);
2091 /* For optimized code, the compiler can scatter one source line
2092 across disjoint ranges of PC values, even when no duplicate
2093 functions or inline functions are involved. For example,
2094 'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
2095 function can result in two PC ranges. In this case, we don't
2096 want to set a breakpoint on the first PC of each range. To filter
2097 such cases, we use containing blocks -- for each PC found
2098 above, we see if there are other PCs that are in the same
2099 block. If yes, the other PCs are filtered out. */
2101 gdb::def_vector<int> filter (intermediate_results.size ());
2102 gdb::def_vector<const block *> blocks (intermediate_results.size ());
2104 for (i = 0; i < intermediate_results.size (); ++i)
2106 set_current_program_space (intermediate_results[i].pspace);
2108 filter[i] = 1;
2109 blocks[i] = block_for_pc_sect (intermediate_results[i].pc,
2110 intermediate_results[i].section);
2113 for (i = 0; i < intermediate_results.size (); ++i)
2115 if (blocks[i] != NULL)
2116 for (j = i + 1; j < intermediate_results.size (); ++j)
2118 if (blocks[j] == blocks[i])
2120 filter[j] = 0;
2121 break;
2126 for (i = 0; i < intermediate_results.size (); ++i)
2127 if (filter[i])
2129 struct symbol *sym = (blocks[i]
2130 ? blocks[i]->containing_function ()
2131 : NULL);
2133 if (self->funfirstline)
2134 skip_prologue_sal (&intermediate_results[i]);
2135 intermediate_results[i].symbol = sym;
2136 add_sal_to_sals (self, &values, &intermediate_results[i],
2137 sym ? sym->natural_name () : NULL, 0);
2141 if (values.empty ())
2143 if (ls->explicit_loc.source_filename)
2144 throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
2145 val.line, ls->explicit_loc.source_filename.get ());
2146 else
2147 throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
2148 val.line);
2151 return values;
2154 /* Convert the given ADDRESS into SaLs. */
2156 static std::vector<symtab_and_line>
2157 convert_address_location_to_sals (struct linespec_state *self,
2158 CORE_ADDR address)
2160 symtab_and_line sal = find_pc_line (address, 0);
2161 sal.pc = address;
2162 sal.section = find_pc_overlay (address);
2163 sal.explicit_pc = 1;
2164 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
2166 std::vector<symtab_and_line> sals;
2167 add_sal_to_sals (self, &sals, &sal, core_addr_to_string (address), 1);
2169 return sals;
2172 /* Create and return SALs from the linespec LS. */
2174 static std::vector<symtab_and_line>
2175 convert_linespec_to_sals (struct linespec_state *state, linespec *ls)
2177 std::vector<symtab_and_line> sals;
2179 if (!ls->labels.label_symbols.empty ())
2181 /* We have just a bunch of functions/methods or labels. */
2182 struct symtab_and_line sal;
2184 for (const auto &sym : ls->labels.label_symbols)
2186 struct program_space *pspace
2187 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace;
2189 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2190 && maybe_add_address (state->addr_set, pspace, sal.pc))
2191 add_sal_to_sals (state, &sals, &sal,
2192 sym.symbol->natural_name (), 0);
2195 else if (!ls->function_symbols.empty () || !ls->minimal_symbols.empty ())
2197 /* We have just a bunch of functions and/or methods. */
2198 if (!ls->function_symbols.empty ())
2200 /* Sort symbols so that symbols with the same program space are next
2201 to each other. */
2202 std::sort (ls->function_symbols.begin (),
2203 ls->function_symbols.end (),
2204 compare_symbols);
2206 for (const auto &sym : ls->function_symbols)
2208 program_space *pspace
2209 = sym.symbol->symtab ()->compunit ()->objfile ()->pspace;
2210 set_current_program_space (pspace);
2212 /* Don't skip to the first line of the function if we
2213 had found an ifunc minimal symbol for this function,
2214 because that means that this function is an ifunc
2215 resolver with the same name as the ifunc itself. */
2216 bool found_ifunc = false;
2218 if (state->funfirstline
2219 && !ls->minimal_symbols.empty ()
2220 && sym.symbol->aclass () == LOC_BLOCK)
2222 const CORE_ADDR addr
2223 = sym.symbol->value_block ()->entry_pc ();
2225 for (const auto &elem : ls->minimal_symbols)
2227 if (elem.minsym->type () == mst_text_gnu_ifunc
2228 || elem.minsym->type () == mst_data_gnu_ifunc)
2230 CORE_ADDR msym_addr = elem.value_address ();
2231 if (elem.minsym->type () == mst_data_gnu_ifunc)
2233 struct gdbarch *gdbarch
2234 = elem.objfile->arch ();
2235 msym_addr
2236 = (gdbarch_convert_from_func_ptr_addr
2237 (gdbarch,
2238 msym_addr,
2239 current_inferior ()->top_target ()));
2242 if (msym_addr == addr)
2244 found_ifunc = true;
2245 break;
2251 if (!found_ifunc)
2253 symtab_and_line sal;
2254 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2255 && maybe_add_address (state->addr_set, pspace, sal.pc))
2256 add_sal_to_sals (state, &sals, &sal,
2257 sym.symbol->natural_name (), 0);
2262 if (!ls->minimal_symbols.empty ())
2264 /* Sort minimal symbols by program space, too */
2265 std::sort (ls->minimal_symbols.begin (),
2266 ls->minimal_symbols.end (),
2267 compare_msymbols);
2269 for (const auto &elem : ls->minimal_symbols)
2271 program_space *pspace = elem.objfile->pspace;
2272 set_current_program_space (pspace);
2273 minsym_found (state, elem.objfile, elem.minsym, &sals);
2277 else if (ls->explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2279 /* Only an offset was specified. */
2280 sals = create_sals_line_offset (state, ls);
2282 /* Make sure we have a filename for canonicalization. */
2283 if (ls->explicit_loc.source_filename == NULL)
2285 const char *filename = state->default_symtab->filename;
2287 /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2288 form so that displaying SOURCE_FILENAME can follow the current
2289 FILENAME_DISPLAY_STRING setting. But as it is used only rarely
2290 it has been kept for code simplicity only in absolute form. */
2291 ls->explicit_loc.source_filename = make_unique_xstrdup (filename);
2294 else
2296 /* We haven't found any results... */
2297 return sals;
2300 canonicalize_linespec (state, ls);
2302 if (!sals.empty () && state->canonical != NULL)
2303 state->canonical->pre_expanded = 1;
2305 return sals;
2308 /* Build RESULT from the explicit location spec components
2309 SOURCE_FILENAME, FUNCTION_NAME, LABEL_NAME and LINE_OFFSET. */
2311 static void
2312 convert_explicit_location_spec_to_linespec
2313 (struct linespec_state *self,
2314 linespec *result,
2315 const char *source_filename,
2316 const char *function_name,
2317 symbol_name_match_type fname_match_type,
2318 const char *label_name,
2319 struct line_offset line_offset)
2321 std::vector<bound_minimal_symbol> minimal_symbols;
2323 result->explicit_loc.func_name_match_type = fname_match_type;
2325 if (source_filename != NULL)
2329 result->file_symtabs
2330 = symtabs_from_filename (source_filename, self->search_pspace);
2332 catch (const gdb_exception_error &except)
2334 source_file_not_found_error (source_filename);
2336 result->explicit_loc.source_filename
2337 = make_unique_xstrdup (source_filename);
2339 else
2341 /* A NULL entry means to use the default symtab. */
2342 result->file_symtabs.push_back (nullptr);
2345 if (function_name != NULL)
2347 std::vector<block_symbol> symbols;
2349 find_linespec_symbols (self, result->file_symtabs,
2350 function_name, fname_match_type,
2351 &symbols, &minimal_symbols);
2353 if (symbols.empty () && minimal_symbols.empty ())
2354 symbol_not_found_error (function_name,
2355 result->explicit_loc.source_filename.get ());
2357 result->explicit_loc.function_name
2358 = make_unique_xstrdup (function_name);
2359 result->function_symbols = std::move (symbols);
2360 result->minimal_symbols = std::move (minimal_symbols);
2363 if (label_name != NULL)
2365 std::vector<block_symbol> symbols;
2366 std::vector<block_symbol> labels
2367 = find_label_symbols (self, result->function_symbols,
2368 &symbols, label_name);
2370 if (labels.empty ())
2371 undefined_label_error (result->explicit_loc.function_name.get (),
2372 label_name);
2374 result->explicit_loc.label_name = make_unique_xstrdup (label_name);
2375 result->labels.label_symbols = labels;
2376 result->labels.function_symbols = std::move (symbols);
2379 if (line_offset.sign != LINE_OFFSET_UNKNOWN)
2380 result->explicit_loc.line_offset = line_offset;
2383 /* Convert the explicit location EXPLICIT_LOC into SaLs. */
2385 static std::vector<symtab_and_line>
2386 convert_explicit_location_spec_to_sals
2387 (struct linespec_state *self,
2388 linespec *result,
2389 const explicit_location_spec *explicit_spec)
2391 convert_explicit_location_spec_to_linespec (self, result,
2392 explicit_spec->source_filename.get (),
2393 explicit_spec->function_name.get (),
2394 explicit_spec->func_name_match_type,
2395 explicit_spec->label_name.get (),
2396 explicit_spec->line_offset);
2397 return convert_linespec_to_sals (self, result);
2400 /* Parse a string that specifies a linespec.
2402 The basic grammar of linespecs:
2404 linespec -> var_spec | basic_spec
2405 var_spec -> '$' (STRING | NUMBER)
2407 basic_spec -> file_offset_spec | function_spec | label_spec
2408 file_offset_spec -> opt_file_spec offset_spec
2409 function_spec -> opt_file_spec function_name_spec opt_label_spec
2410 label_spec -> label_name_spec
2412 opt_file_spec -> "" | file_name_spec ':'
2413 opt_label_spec -> "" | ':' label_name_spec
2415 file_name_spec -> STRING
2416 function_name_spec -> STRING
2417 label_name_spec -> STRING
2418 function_name_spec -> STRING
2419 offset_spec -> NUMBER
2420 -> '+' NUMBER
2421 -> '-' NUMBER
2423 This may all be followed by several keywords such as "if EXPR",
2424 which we ignore.
2426 A comma will terminate parsing.
2428 The function may be an undebuggable function found in minimal symbol table.
2430 If the argument FUNFIRSTLINE is nonzero, we want the first line
2431 of real code inside a function when a function is specified, and it is
2432 not OK to specify a variable or type to get its line number.
2434 DEFAULT_SYMTAB specifies the file to use if none is specified.
2435 It defaults to current_source_symtab.
2436 DEFAULT_LINE specifies the line number to use for relative
2437 line numbers (that start with signs). Defaults to current_source_line.
2438 If CANONICAL is non-NULL, store an array of strings containing the canonical
2439 line specs there if necessary. Currently overloaded member functions and
2440 line numbers or static functions without a filename yield a canonical
2441 line spec. The array and the line spec strings are allocated on the heap,
2442 it is the callers responsibility to free them.
2444 Note that it is possible to return zero for the symtab
2445 if no file is validly specified. Callers must check that.
2446 Also, the line number returned may be invalid. */
2448 /* Parse the linespec in ARG, which must not be nullptr. MATCH_TYPE
2449 indicates how function names should be matched. */
2451 static std::vector<symtab_and_line>
2452 parse_linespec (linespec_parser *parser, const char *arg,
2453 symbol_name_match_type match_type)
2455 gdb_assert (arg != nullptr);
2457 struct gdb_exception file_exception;
2459 /* A special case to start. It has become quite popular for
2460 IDEs to work around bugs in the previous parser by quoting
2461 the entire linespec, so we attempt to deal with this nicely. */
2462 parser->is_quote_enclosed = 0;
2463 if (parser->completion_tracker == NULL
2464 && !is_ada_operator (arg)
2465 && *arg != '\0'
2466 && strchr (linespec_quote_characters, *arg) != NULL)
2468 const char *end = skip_quote_char (arg + 1, *arg);
2469 if (end != NULL && is_closing_quote_enclosed (end))
2471 /* Here's the special case. Skip ARG past the initial
2472 quote. */
2473 ++arg;
2474 parser->is_quote_enclosed = 1;
2478 parser->lexer.saved_arg = arg;
2479 parser->lexer.stream = arg;
2480 parser->completion_word = arg;
2481 parser->complete_what = linespec_complete_what::FUNCTION;
2482 PARSER_EXPLICIT (parser)->func_name_match_type = match_type;
2484 /* Initialize the default symtab and line offset. */
2485 initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2486 &PARSER_STATE (parser)->default_line);
2488 /* Objective-C shortcut. */
2489 if (parser->completion_tracker == NULL)
2491 std::vector<symtab_and_line> values
2492 = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), arg);
2493 if (!values.empty ())
2494 return values;
2496 else
2498 /* "-"/"+" is either an objc selector, or a number. There's
2499 nothing to complete the latter to, so just let the caller
2500 complete on functions, which finds objc selectors, if there's
2501 any. */
2502 if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '\0')
2503 return {};
2506 /* Start parsing. */
2508 /* Get the first token. */
2509 linespec_token token = linespec_lexer_consume_token (parser);
2511 /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER. */
2512 if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2514 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2515 if (parser->completion_tracker == NULL)
2516 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2518 /* User specified a convenience variable or history value. */
2519 gdb::unique_xmalloc_ptr<char> var = copy_token_string (token);
2520 PARSER_EXPLICIT (parser)->line_offset
2521 = linespec_parse_variable (PARSER_STATE (parser), var.get ());
2523 /* If a line_offset wasn't found (VAR is the name of a user
2524 variable/function), then skip to normal symbol processing. */
2525 if (PARSER_EXPLICIT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2527 /* Consume this token. */
2528 linespec_lexer_consume_token (parser);
2530 goto convert_to_sals;
2533 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
2535 /* Let the default linespec_complete_what::FUNCTION kick in. */
2536 unexpected_linespec_error (parser);
2538 else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2540 parser->complete_what = linespec_complete_what::NOTHING;
2541 unexpected_linespec_error (parser);
2544 /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2545 this token cannot represent a filename. */
2546 token = linespec_lexer_peek_token (parser);
2548 if (token.type == LSTOKEN_COLON)
2550 /* Get the current token again and extract the filename. */
2551 token = linespec_lexer_lex_one (parser);
2552 gdb::unique_xmalloc_ptr<char> user_filename = copy_token_string (token);
2554 /* Check if the input is a filename. */
2557 PARSER_RESULT (parser)->file_symtabs
2558 = symtabs_from_filename (user_filename.get (),
2559 PARSER_STATE (parser)->search_pspace);
2561 catch (gdb_exception_error &ex)
2563 file_exception = std::move (ex);
2566 if (file_exception.reason >= 0)
2568 /* Symtabs were found for the file. Record the filename. */
2569 PARSER_EXPLICIT (parser)->source_filename = std::move (user_filename);
2571 /* Get the next token. */
2572 token = linespec_lexer_consume_token (parser);
2574 /* This is LSTOKEN_COLON; consume it. */
2575 linespec_lexer_consume_token (parser);
2577 else
2579 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2580 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2583 /* If the next token is not EOI, KEYWORD, or COMMA, issue an error. */
2584 else if (parser->completion_tracker == NULL
2585 && (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2586 && token.type != LSTOKEN_COMMA))
2588 /* TOKEN is the _next_ token, not the one currently in the parser.
2589 Consuming the token will give the correct error message. */
2590 linespec_lexer_consume_token (parser);
2591 unexpected_linespec_error (parser);
2593 else
2595 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2596 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2599 /* Parse the rest of the linespec. */
2600 linespec_parse_basic (parser);
2602 if (parser->completion_tracker == NULL
2603 && PARSER_RESULT (parser)->function_symbols.empty ()
2604 && PARSER_RESULT (parser)->labels.label_symbols.empty ()
2605 && PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2606 && PARSER_RESULT (parser)->minimal_symbols.empty ())
2608 /* The linespec didn't parse. Re-throw the file exception if
2609 there was one. */
2610 if (file_exception.reason < 0)
2611 throw_exception (std::move (file_exception));
2613 /* Otherwise, the symbol is not found. */
2614 symbol_not_found_error
2615 (PARSER_EXPLICIT (parser)->function_name.get (),
2616 PARSER_EXPLICIT (parser)->source_filename.get ());
2619 convert_to_sals:
2621 /* Get the last token and record how much of the input was parsed,
2622 if necessary. */
2623 token = linespec_lexer_lex_one (parser);
2624 if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2625 unexpected_linespec_error (parser);
2626 else if (token.type == LSTOKEN_KEYWORD)
2628 /* Setup the completion word past the keyword. Lexing never
2629 advances past a keyword automatically, so skip it
2630 manually. */
2631 parser->completion_word
2632 = skip_spaces (skip_to_space (PARSER_STREAM (parser)));
2633 parser->complete_what = linespec_complete_what::EXPRESSION;
2636 /* Convert the data in PARSER_RESULT to SALs. */
2637 if (parser->completion_tracker == NULL)
2638 return convert_linespec_to_sals (PARSER_STATE (parser),
2639 PARSER_RESULT (parser));
2641 return {};
2645 /* A constructor for linespec_state. */
2647 static void
2648 linespec_state_constructor (struct linespec_state *self,
2649 int flags, const struct language_defn *language,
2650 struct program_space *search_pspace,
2651 struct symtab *default_symtab,
2652 int default_line,
2653 struct linespec_result *canonical)
2655 memset (self, 0, sizeof (*self));
2656 self->language = language;
2657 self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2658 self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2659 self->search_pspace = search_pspace;
2660 self->default_symtab = default_symtab;
2661 self->default_line = default_line;
2662 self->canonical = canonical;
2663 self->program_space = current_program_space;
2664 self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2665 xfree, xcalloc, xfree);
2666 self->is_linespec = 0;
2669 /* Initialize a new linespec parser. */
2671 linespec_parser::linespec_parser (int flags,
2672 const struct language_defn *language,
2673 struct program_space *search_pspace,
2674 struct symtab *default_symtab,
2675 int default_line,
2676 struct linespec_result *canonical)
2678 lexer.current.type = LSTOKEN_CONSUMED;
2679 PARSER_EXPLICIT (this)->func_name_match_type
2680 = symbol_name_match_type::WILD;
2681 PARSER_EXPLICIT (this)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2682 linespec_state_constructor (PARSER_STATE (this), flags, language,
2683 search_pspace,
2684 default_symtab, default_line, canonical);
2687 /* A destructor for linespec_state. */
2689 static void
2690 linespec_state_destructor (struct linespec_state *self)
2692 htab_delete (self->addr_set);
2693 xfree (self->canonical_names);
2696 /* Delete a linespec parser. */
2698 linespec_parser::~linespec_parser ()
2700 linespec_state_destructor (PARSER_STATE (this));
2703 /* See description in linespec.h. */
2705 void
2706 linespec_lex_to_end (const char **stringp)
2708 linespec_token token;
2709 const char *orig;
2711 if (stringp == NULL || *stringp == NULL)
2712 return;
2714 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2715 parser.lexer.saved_arg = *stringp;
2716 PARSER_STREAM (&parser) = orig = *stringp;
2720 /* Stop before any comma tokens; we need it to keep it
2721 as the next token in the string. */
2722 token = linespec_lexer_peek_token (&parser);
2723 if (token.type == LSTOKEN_COMMA)
2724 break;
2725 token = linespec_lexer_consume_token (&parser);
2727 while (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD);
2729 *stringp += PARSER_STREAM (&parser) - orig;
2732 /* See linespec.h. */
2734 void
2735 linespec_complete_function (completion_tracker &tracker,
2736 const char *function,
2737 symbol_name_match_type func_match_type,
2738 const char *source_filename)
2740 complete_symbol_mode mode = complete_symbol_mode::LINESPEC;
2742 if (source_filename != NULL)
2744 collect_file_symbol_completion_matches (tracker, mode, func_match_type,
2745 function, function, source_filename);
2747 else
2749 collect_symbol_completion_matches (tracker, mode, func_match_type,
2750 function, function);
2755 /* Helper for complete_linespec to simplify it. SOURCE_FILENAME is
2756 only meaningful if COMPONENT is FUNCTION. */
2758 static void
2759 complete_linespec_component (linespec_parser *parser,
2760 completion_tracker &tracker,
2761 const char *text,
2762 linespec_complete_what component,
2763 const char *source_filename)
2765 if (component == linespec_complete_what::KEYWORD)
2767 complete_on_enum (tracker, linespec_keywords, text, text);
2769 else if (component == linespec_complete_what::EXPRESSION)
2771 const char *word
2772 = advance_to_expression_complete_word_point (tracker, text);
2773 complete_expression (tracker, text, word);
2775 else if (component == linespec_complete_what::FUNCTION)
2777 completion_list fn_list;
2779 symbol_name_match_type match_type
2780 = PARSER_EXPLICIT (parser)->func_name_match_type;
2781 linespec_complete_function (tracker, text, match_type, source_filename);
2782 if (source_filename == NULL)
2784 /* Haven't seen a source component, like in "b
2785 file.c:function[TAB]". Maybe this wasn't a function, but
2786 a filename instead, like "b file.[TAB]". */
2787 fn_list = complete_source_filenames (text);
2790 /* If we only have a single filename completion, append a ':' for
2791 the user, since that's the only thing that can usefully follow
2792 the filename. */
2793 if (fn_list.size () == 1 && !tracker.have_completions ())
2795 char *fn = fn_list[0].release ();
2797 /* If we also need to append a quote char, it needs to be
2798 appended before the ':'. Append it now, and make ':' the
2799 new "quote" char. */
2800 if (tracker.quote_char ())
2802 char quote_char_str[2] = { (char) tracker.quote_char () };
2804 fn = reconcat (fn, fn, quote_char_str, (char *) NULL);
2805 tracker.set_quote_char (':');
2807 else
2808 fn = reconcat (fn, fn, ":", (char *) NULL);
2809 fn_list[0].reset (fn);
2811 /* Tell readline to skip appending a space. */
2812 tracker.set_suppress_append_ws (true);
2814 tracker.add_completions (std::move (fn_list));
2818 /* Helper for linespec_complete_label. Find labels that match
2819 LABEL_NAME in the function symbols listed in the PARSER, and add
2820 them to the tracker. */
2822 static void
2823 complete_label (completion_tracker &tracker,
2824 linespec_parser *parser,
2825 const char *label_name)
2827 std::vector<block_symbol> label_function_symbols;
2828 std::vector<block_symbol> labels
2829 = find_label_symbols (PARSER_STATE (parser),
2830 PARSER_RESULT (parser)->function_symbols,
2831 &label_function_symbols,
2832 label_name, true);
2834 for (const auto &label : labels)
2836 char *match = xstrdup (label.symbol->search_name ());
2837 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (match));
2841 /* See linespec.h. */
2843 void
2844 linespec_complete_label (completion_tracker &tracker,
2845 const struct language_defn *language,
2846 const char *source_filename,
2847 const char *function_name,
2848 symbol_name_match_type func_name_match_type,
2849 const char *label_name)
2851 linespec_parser parser (0, language, NULL, NULL, 0, NULL);
2853 line_offset unknown_offset;
2857 convert_explicit_location_spec_to_linespec (PARSER_STATE (&parser),
2858 PARSER_RESULT (&parser),
2859 source_filename,
2860 function_name,
2861 func_name_match_type,
2862 NULL, unknown_offset);
2864 catch (const gdb_exception_error &ex)
2866 return;
2869 complete_label (tracker, &parser, label_name);
2872 /* See description in linespec.h. */
2874 void
2875 linespec_complete (completion_tracker &tracker, const char *text,
2876 symbol_name_match_type match_type)
2878 const char *orig = text;
2880 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2881 parser.lexer.saved_arg = text;
2882 PARSER_EXPLICIT (&parser)->func_name_match_type = match_type;
2883 PARSER_STREAM (&parser) = text;
2885 parser.completion_tracker = &tracker;
2886 PARSER_STATE (&parser)->is_linespec = 1;
2888 /* Parse as much as possible. parser.completion_word will hold
2889 furthest completion point we managed to parse to. */
2892 parse_linespec (&parser, text, match_type);
2894 catch (const gdb_exception_error &except)
2898 if (parser.completion_quote_char != '\0'
2899 && parser.completion_quote_end != NULL
2900 && parser.completion_quote_end[1] == '\0')
2902 /* If completing a quoted string with the cursor right at
2903 terminating quote char, complete the completion word without
2904 interpretation, so that readline advances the cursor one
2905 whitespace past the quote, even if there's no match. This
2906 makes these cases behave the same:
2908 before: "b function()"
2909 after: "b function() "
2911 before: "b 'function()'"
2912 after: "b 'function()' "
2914 and trusts the user in this case:
2916 before: "b 'not_loaded_function_yet()'"
2917 after: "b 'not_loaded_function_yet()' "
2919 parser.complete_what = linespec_complete_what::NOTHING;
2920 parser.completion_quote_char = '\0';
2922 gdb::unique_xmalloc_ptr<char> text_copy
2923 (xstrdup (parser.completion_word));
2924 tracker.add_completion (std::move (text_copy));
2927 tracker.set_quote_char (parser.completion_quote_char);
2929 if (parser.complete_what == linespec_complete_what::LABEL)
2931 parser.complete_what = linespec_complete_what::NOTHING;
2933 const char *func_name = PARSER_EXPLICIT (&parser)->function_name.get ();
2935 std::vector<block_symbol> function_symbols;
2936 std::vector<bound_minimal_symbol> minimal_symbols;
2937 find_linespec_symbols (PARSER_STATE (&parser),
2938 PARSER_RESULT (&parser)->file_symtabs,
2939 func_name, match_type,
2940 &function_symbols, &minimal_symbols);
2942 PARSER_RESULT (&parser)->function_symbols = std::move (function_symbols);
2943 PARSER_RESULT (&parser)->minimal_symbols = std::move (minimal_symbols);
2945 complete_label (tracker, &parser, parser.completion_word);
2947 else if (parser.complete_what == linespec_complete_what::FUNCTION)
2949 /* While parsing/lexing, we didn't know whether the completion
2950 word completes to a unique function/source name already or
2951 not.
2953 E.g.:
2954 "b function() <tab>"
2955 may need to complete either to:
2956 "b function() const"
2957 or to:
2958 "b function() if/thread/task"
2960 Or, this:
2961 "b foo t"
2962 may need to complete either to:
2963 "b foo template_fun<T>()"
2964 with "foo" being the template function's return type, or to:
2965 "b foo thread/task"
2967 Or, this:
2968 "b file<TAB>"
2969 may need to complete either to a source file name:
2970 "b file.c"
2971 or this, also a filename, but a unique completion:
2972 "b file.c:"
2973 or to a function name:
2974 "b file_function"
2976 Address that by completing assuming source or function, and
2977 seeing if we find a completion that matches exactly the
2978 completion word. If so, then it must be a function (see note
2979 below) and we advance the completion word to the end of input
2980 and switch to KEYWORD completion mode.
2982 Note: if we find a unique completion for a source filename,
2983 then it won't match the completion word, because the LCD will
2984 contain a trailing ':'. And if we're completing at or after
2985 the ':', then complete_linespec_component won't try to
2986 complete on source filenames. */
2988 const char *word = parser.completion_word;
2990 complete_linespec_component
2991 (&parser, tracker,
2992 parser.completion_word,
2993 linespec_complete_what::FUNCTION,
2994 PARSER_EXPLICIT (&parser)->source_filename.get ());
2996 parser.complete_what = linespec_complete_what::NOTHING;
2998 if (tracker.quote_char ())
3000 /* The function/file name was not close-quoted, so this
3001 can't be a keyword. Note: complete_linespec_component
3002 may have swapped the original quote char for ':' when we
3003 get here, but that still indicates the same. */
3005 else if (!tracker.have_completions ())
3007 size_t key_start;
3008 size_t wordlen = strlen (parser.completion_word);
3010 key_start
3011 = string_find_incomplete_keyword_at_end (linespec_keywords,
3012 parser.completion_word,
3013 wordlen);
3015 if (key_start != -1
3016 || (wordlen > 0
3017 && parser.completion_word[wordlen - 1] == ' '))
3019 parser.completion_word += key_start;
3020 parser.complete_what = linespec_complete_what::KEYWORD;
3023 else if (tracker.completes_to_completion_word (word))
3025 /* Skip the function and complete on keywords. */
3026 parser.completion_word += strlen (word);
3027 parser.complete_what = linespec_complete_what::KEYWORD;
3028 tracker.discard_completions ();
3032 tracker.advance_custom_word_point_by (parser.completion_word - orig);
3034 complete_linespec_component
3035 (&parser, tracker,
3036 parser.completion_word,
3037 parser.complete_what,
3038 PARSER_EXPLICIT (&parser)->source_filename.get ());
3040 /* If we're past the "filename:function:label:offset" linespec, and
3041 didn't find any match, then assume the user might want to create
3042 a pending breakpoint anyway and offer the keyword
3043 completions. */
3044 if (!parser.completion_quote_char
3045 && (parser.complete_what == linespec_complete_what::FUNCTION
3046 || parser.complete_what == linespec_complete_what::LABEL
3047 || parser.complete_what == linespec_complete_what::NOTHING)
3048 && !tracker.have_completions ())
3050 const char *end
3051 = parser.completion_word + strlen (parser.completion_word);
3053 if (end > orig && end[-1] == ' ')
3055 tracker.advance_custom_word_point_by (end - parser.completion_word);
3057 complete_linespec_component (&parser, tracker, end,
3058 linespec_complete_what::KEYWORD,
3059 NULL);
3064 /* A helper function for decode_line_full and decode_line_1 to
3065 turn LOCSPEC into std::vector<symtab_and_line>. */
3067 static std::vector<symtab_and_line>
3068 location_spec_to_sals (linespec_parser *parser,
3069 const location_spec *locspec)
3071 std::vector<symtab_and_line> result;
3073 switch (locspec->type ())
3075 case LINESPEC_LOCATION_SPEC:
3077 const linespec_location_spec *ls = as_linespec_location_spec (locspec);
3078 PARSER_STATE (parser)->is_linespec = 1;
3079 result = parse_linespec (parser, ls->spec_string.get (),
3080 ls->match_type);
3082 break;
3084 case ADDRESS_LOCATION_SPEC:
3086 const address_location_spec *addr_spec
3087 = as_address_location_spec (locspec);
3088 const char *addr_string = addr_spec->to_string ();
3089 CORE_ADDR addr;
3091 if (addr_string != NULL)
3093 addr = linespec_expression_to_pc (&addr_string);
3094 if (PARSER_STATE (parser)->canonical != NULL)
3095 PARSER_STATE (parser)->canonical->locspec = locspec->clone ();
3097 else
3098 addr = addr_spec->address;
3100 result = convert_address_location_to_sals (PARSER_STATE (parser),
3101 addr);
3103 break;
3105 case EXPLICIT_LOCATION_SPEC:
3107 const explicit_location_spec *explicit_locspec
3108 = as_explicit_location_spec (locspec);
3109 result = convert_explicit_location_spec_to_sals (PARSER_STATE (parser),
3110 PARSER_RESULT (parser),
3111 explicit_locspec);
3113 break;
3115 case PROBE_LOCATION_SPEC:
3116 /* Probes are handled by their own decoders. */
3117 gdb_assert_not_reached ("attempt to decode probe location");
3118 break;
3120 default:
3121 gdb_assert_not_reached ("unhandled location spec type");
3124 return result;
3127 /* See linespec.h. */
3129 void
3130 decode_line_full (struct location_spec *locspec, int flags,
3131 struct program_space *search_pspace,
3132 struct symtab *default_symtab,
3133 int default_line, struct linespec_result *canonical,
3134 const char *select_mode,
3135 const char *filter)
3137 std::vector<const char *> filters;
3138 struct linespec_state *state;
3140 gdb_assert (canonical != NULL);
3141 /* The filter only makes sense for 'all'. */
3142 gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
3143 gdb_assert (select_mode == NULL
3144 || select_mode == multiple_symbols_all
3145 || select_mode == multiple_symbols_ask
3146 || select_mode == multiple_symbols_cancel);
3147 gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
3149 linespec_parser parser (flags, current_language,
3150 search_pspace, default_symtab,
3151 default_line, canonical);
3153 scoped_restore_current_program_space restore_pspace;
3155 std::vector<symtab_and_line> result = location_spec_to_sals (&parser,
3156 locspec);
3157 state = PARSER_STATE (&parser);
3159 if (result.size () == 0)
3160 throw_error (NOT_SUPPORTED_ERROR, _("Location %s not available"),
3161 locspec->to_string ());
3163 gdb_assert (result.size () == 1 || canonical->pre_expanded);
3164 canonical->pre_expanded = 1;
3166 /* Arrange for allocated canonical names to be freed. */
3167 std::vector<gdb::unique_xmalloc_ptr<char>> hold_names;
3168 for (int i = 0; i < result.size (); ++i)
3170 gdb_assert (state->canonical_names[i].suffix != NULL);
3171 hold_names.emplace_back (state->canonical_names[i].suffix);
3174 if (select_mode == NULL)
3176 if (top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
3177 select_mode = multiple_symbols_all;
3178 else
3179 select_mode = multiple_symbols_select_mode ();
3182 if (select_mode == multiple_symbols_all)
3184 if (filter != NULL)
3186 filters.push_back (filter);
3187 filter_results (state, &result, filters);
3189 else
3190 convert_results_to_lsals (state, &result);
3192 else
3193 decode_line_2 (state, &result, select_mode);
3196 /* See linespec.h. */
3198 std::vector<symtab_and_line>
3199 decode_line_1 (const location_spec *locspec, int flags,
3200 struct program_space *search_pspace,
3201 struct symtab *default_symtab,
3202 int default_line)
3204 linespec_parser parser (flags, current_language,
3205 search_pspace, default_symtab,
3206 default_line, NULL);
3208 scoped_restore_current_program_space restore_pspace;
3210 return location_spec_to_sals (&parser, locspec);
3213 /* See linespec.h. */
3215 std::vector<symtab_and_line>
3216 decode_line_with_current_source (const char *string, int flags)
3218 if (string == 0)
3219 error (_("Empty line specification."));
3221 /* We use whatever is set as the current source line. We do not try
3222 and get a default source symtab+line or it will recursively call us! */
3223 symtab_and_line cursal = get_current_source_symtab_and_line ();
3225 location_spec_up locspec = string_to_location_spec (&string,
3226 current_language);
3227 std::vector<symtab_and_line> sals
3228 = decode_line_1 (locspec.get (), flags, cursal.pspace, cursal.symtab,
3229 cursal.line);
3231 if (*string)
3232 error (_("Junk at end of line specification: %s"), string);
3234 return sals;
3237 /* See linespec.h. */
3239 std::vector<symtab_and_line>
3240 decode_line_with_last_displayed (const char *string, int flags)
3242 if (string == 0)
3243 error (_("Empty line specification."));
3245 location_spec_up locspec = string_to_location_spec (&string,
3246 current_language);
3247 std::vector<symtab_and_line> sals
3248 = (last_displayed_sal_is_valid ()
3249 ? decode_line_1 (locspec.get (), flags, NULL,
3250 get_last_displayed_symtab (),
3251 get_last_displayed_line ())
3252 : decode_line_1 (locspec.get (), flags, NULL, NULL, 0));
3254 if (*string)
3255 error (_("Junk at end of line specification: %s"), string);
3257 return sals;
3262 /* First, some functions to initialize stuff at the beginning of the
3263 function. */
3265 static void
3266 initialize_defaults (struct symtab **default_symtab, int *default_line)
3268 if (*default_symtab == 0)
3270 /* Use whatever we have for the default source line. We don't use
3271 get_current_or_default_symtab_and_line as it can recurse and call
3272 us back! */
3273 struct symtab_and_line cursal =
3274 get_current_source_symtab_and_line ();
3276 *default_symtab = cursal.symtab;
3277 *default_line = cursal.line;
3283 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
3284 advancing EXP_PTR past any parsed text. */
3286 CORE_ADDR
3287 linespec_expression_to_pc (const char **exp_ptr)
3289 if (current_program_space->executing_startup)
3290 /* The error message doesn't really matter, because this case
3291 should only hit during breakpoint reset. */
3292 throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
3293 "program space is in startup"));
3295 (*exp_ptr)++;
3296 return value_as_address (parse_to_comma_and_eval (exp_ptr));
3301 /* Here's where we recognise an Objective-C Selector. An Objective C
3302 selector may be implemented by more than one class, therefore it
3303 may represent more than one method/function. This gives us a
3304 situation somewhat analogous to C++ overloading. If there's more
3305 than one method that could represent the selector, then use some of
3306 the existing C++ code to let the user choose one. */
3308 static std::vector<symtab_and_line>
3309 decode_objc (struct linespec_state *self, linespec *ls, const char *arg)
3311 struct collect_info info;
3312 std::vector<const char *> symbol_names;
3313 const char *new_argptr;
3315 info.state = self;
3316 std::vector<symtab *> symtabs;
3317 symtabs.push_back (nullptr);
3319 info.file_symtabs = &symtabs;
3321 std::vector<block_symbol> symbols;
3322 info.result.symbols = &symbols;
3323 std::vector<bound_minimal_symbol> minimal_symbols;
3324 info.result.minimal_symbols = &minimal_symbols;
3326 new_argptr = find_imps (arg, &symbol_names);
3327 if (symbol_names.empty ())
3328 return {};
3330 add_all_symbol_names_from_pspace (&info, NULL, symbol_names,
3331 SEARCH_FUNCTION_DOMAIN);
3333 std::vector<symtab_and_line> values;
3334 if (!symbols.empty () || !minimal_symbols.empty ())
3336 char *saved_arg;
3338 saved_arg = (char *) alloca (new_argptr - arg + 1);
3339 memcpy (saved_arg, arg, new_argptr - arg);
3340 saved_arg[new_argptr - arg] = '\0';
3342 ls->explicit_loc.function_name = make_unique_xstrdup (saved_arg);
3343 ls->function_symbols = std::move (symbols);
3344 ls->minimal_symbols = std::move (minimal_symbols);
3345 values = convert_linespec_to_sals (self, ls);
3347 if (self->canonical)
3349 std::string holder;
3350 const char *str;
3352 self->canonical->pre_expanded = 1;
3354 if (ls->explicit_loc.source_filename)
3356 holder = string_printf ("%s:%s",
3357 ls->explicit_loc.source_filename.get (),
3358 saved_arg);
3359 str = holder.c_str ();
3361 else
3362 str = saved_arg;
3364 self->canonical->locspec
3365 = new_linespec_location_spec (&str, symbol_name_match_type::FULL);
3369 return values;
3372 namespace {
3374 /* A function object that serves as symbol_found_callback_ftype
3375 callback for iterate_over_symbols. This is used by
3376 lookup_prefix_sym to collect type symbols. */
3377 class decode_compound_collector
3379 public:
3380 decode_compound_collector ()
3381 : m_unique_syms (htab_create_alloc (1, htab_hash_pointer,
3382 htab_eq_pointer, NULL,
3383 xcalloc, xfree))
3387 /* Return all symbols collected. */
3388 std::vector<block_symbol> release_symbols ()
3390 return std::move (m_symbols);
3393 /* Callable as a symbol_found_callback_ftype callback. */
3394 bool operator () (block_symbol *bsym);
3396 private:
3397 /* A hash table of all symbols we found. We use this to avoid
3398 adding any symbol more than once. */
3399 htab_up m_unique_syms;
3401 /* The result vector. */
3402 std::vector<block_symbol> m_symbols;
3405 bool
3406 decode_compound_collector::operator () (block_symbol *bsym)
3408 void **slot;
3409 struct type *t;
3410 struct symbol *sym = bsym->symbol;
3412 if (sym->aclass () != LOC_TYPEDEF)
3413 return true; /* Continue iterating. */
3415 t = sym->type ();
3416 t = check_typedef (t);
3417 if (t->code () != TYPE_CODE_STRUCT
3418 && t->code () != TYPE_CODE_UNION
3419 && t->code () != TYPE_CODE_NAMESPACE)
3420 return true; /* Continue iterating. */
3422 slot = htab_find_slot (m_unique_syms.get (), sym, INSERT);
3423 if (!*slot)
3425 *slot = sym;
3426 m_symbols.push_back (*bsym);
3429 return true; /* Continue iterating. */
3432 } // namespace
3434 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS. */
3436 static std::vector<block_symbol>
3437 lookup_prefix_sym (struct linespec_state *state,
3438 const std::vector<symtab *> &file_symtabs,
3439 const char *class_name)
3441 decode_compound_collector collector;
3443 lookup_name_info lookup_name (class_name, symbol_name_match_type::FULL);
3445 for (const auto &elt : file_symtabs)
3447 if (elt == nullptr)
3448 iterate_over_all_matching_symtabs (state, lookup_name,
3449 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3450 NULL, false, collector);
3451 else
3453 /* Program spaces that are executing startup should have
3454 been filtered out earlier. */
3455 program_space *pspace = elt->compunit ()->objfile ()->pspace;
3457 gdb_assert (!pspace->executing_startup);
3458 set_current_program_space (pspace);
3459 iterate_over_file_blocks (elt, lookup_name,
3460 SEARCH_STRUCT_DOMAIN | SEARCH_VFT,
3461 collector);
3465 return collector.release_symbols ();
3468 /* A std::sort comparison function for symbols. The resulting order does
3469 not actually matter; we just need to be able to sort them so that
3470 symbols with the same program space end up next to each other. */
3472 static bool
3473 compare_symbols (const block_symbol &a, const block_symbol &b)
3475 uintptr_t uia, uib;
3477 uia = (uintptr_t) a.symbol->symtab ()->compunit ()->objfile ()->pspace;
3478 uib = (uintptr_t) b.symbol->symtab ()->compunit ()->objfile ()->pspace;
3480 if (uia < uib)
3481 return true;
3482 if (uia > uib)
3483 return false;
3485 uia = (uintptr_t) a.symbol;
3486 uib = (uintptr_t) b.symbol;
3488 if (uia < uib)
3489 return true;
3491 return false;
3494 /* Like compare_symbols but for minimal symbols. */
3496 static bool
3497 compare_msymbols (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
3499 uintptr_t uia, uib;
3501 uia = (uintptr_t) a.objfile->pspace;
3502 uib = (uintptr_t) a.objfile->pspace;
3504 if (uia < uib)
3505 return true;
3506 if (uia > uib)
3507 return false;
3509 uia = (uintptr_t) a.minsym;
3510 uib = (uintptr_t) b.minsym;
3512 if (uia < uib)
3513 return true;
3515 return false;
3518 /* Look for all the matching instances of each symbol in NAMES. Only
3519 instances from PSPACE are considered; other program spaces are
3520 handled by our caller. If PSPACE is NULL, then all program spaces
3521 are considered. Results are stored into INFO. */
3523 static void
3524 add_all_symbol_names_from_pspace (struct collect_info *info,
3525 struct program_space *pspace,
3526 const std::vector<const char *> &names,
3527 domain_search_flags domain_search_flags)
3529 for (const char *iter : names)
3530 add_matching_symbols_to_info (iter,
3531 symbol_name_match_type::FULL,
3532 domain_search_flags, info, pspace);
3535 static void
3536 find_superclass_methods (std::vector<struct type *> &&superclasses,
3537 const char *name, enum language name_lang,
3538 std::vector<const char *> *result_names)
3540 size_t old_len = result_names->size ();
3542 while (1)
3544 std::vector<struct type *> new_supers;
3546 for (type *t : superclasses)
3547 find_methods (t, name_lang, name, result_names, &new_supers);
3549 if (result_names->size () != old_len || new_supers.empty ())
3550 break;
3552 superclasses = std::move (new_supers);
3556 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
3557 given by one of the symbols in SYM_CLASSES. Matches are returned
3558 in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols). */
3560 static void
3561 find_method (struct linespec_state *self,
3562 const std::vector<symtab *> &file_symtabs,
3563 const char *class_name, const char *method_name,
3564 std::vector<block_symbol> *sym_classes,
3565 std::vector<block_symbol> *symbols,
3566 std::vector<bound_minimal_symbol> *minsyms)
3568 size_t last_result_len;
3569 std::vector<struct type *> superclass_vec;
3570 std::vector<const char *> result_names;
3571 struct collect_info info;
3573 /* Sort symbols so that symbols with the same program space are next
3574 to each other. */
3575 std::sort (sym_classes->begin (), sym_classes->end (),
3576 compare_symbols);
3578 info.state = self;
3579 info.file_symtabs = &file_symtabs;
3580 info.result.symbols = symbols;
3581 info.result.minimal_symbols = minsyms;
3583 /* Iterate over all the types, looking for the names of existing
3584 methods matching METHOD_NAME. If we cannot find a direct method in a
3585 given program space, then we consider inherited methods; this is
3586 not ideal (ideal would be to respect C++ hiding rules), but it
3587 seems good enough and is what GDB has historically done. We only
3588 need to collect the names because later we find all symbols with
3589 those names. This loop is written in a somewhat funny way
3590 because we collect data across the program space before deciding
3591 what to do. */
3592 last_result_len = 0;
3593 for (const auto &elt : *sym_classes)
3595 struct type *t;
3596 struct program_space *pspace;
3597 struct symbol *sym = elt.symbol;
3598 unsigned int ix = &elt - &*sym_classes->begin ();
3600 /* Program spaces that are executing startup should have
3601 been filtered out earlier. */
3602 pspace = sym->symtab ()->compunit ()->objfile ()->pspace;
3603 gdb_assert (!pspace->executing_startup);
3604 set_current_program_space (pspace);
3605 t = check_typedef (sym->type ());
3606 find_methods (t, sym->language (),
3607 method_name, &result_names, &superclass_vec);
3609 /* Handle all items from a single program space at once; and be
3610 sure not to miss the last batch. */
3611 if (ix == sym_classes->size () - 1
3612 || (pspace
3613 != (sym_classes->at (ix + 1).symbol->symtab ()
3614 ->compunit ()->objfile ()->pspace)))
3616 /* If we did not find a direct implementation anywhere in
3617 this program space, consider superclasses. */
3618 if (result_names.size () == last_result_len)
3619 find_superclass_methods (std::move (superclass_vec), method_name,
3620 sym->language (), &result_names);
3622 /* We have a list of candidate symbol names, so now we
3623 iterate over the symbol tables looking for all
3624 matches in this pspace. */
3625 add_all_symbol_names_from_pspace (&info, pspace, result_names,
3626 SEARCH_FUNCTION_DOMAIN);
3628 superclass_vec.clear ();
3629 last_result_len = result_names.size ();
3633 if (!symbols->empty () || !minsyms->empty ())
3634 return;
3636 /* Throw an NOT_FOUND_ERROR. This will be caught by the caller
3637 and other attempts to locate the symbol will be made. */
3638 throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
3643 namespace {
3645 /* This function object is a callback for iterate_over_symtabs, used
3646 when collecting all matching symtabs. */
3648 class symtab_collector
3650 public:
3651 symtab_collector ()
3652 : m_symtab_table (htab_create (1, htab_hash_pointer, htab_eq_pointer,
3653 NULL))
3657 /* Callable as a symbol_found_callback_ftype callback. */
3658 bool operator () (symtab *sym);
3660 /* Return an rvalue reference to the collected symtabs. */
3661 std::vector<symtab *> &&release_symtabs ()
3663 return std::move (m_symtabs);
3666 private:
3667 /* The result vector of symtabs. */
3668 std::vector<symtab *> m_symtabs;
3670 /* This is used to ensure the symtabs are unique. */
3671 htab_up m_symtab_table;
3674 bool
3675 symtab_collector::operator () (struct symtab *symtab)
3677 void **slot;
3679 slot = htab_find_slot (m_symtab_table.get (), symtab, INSERT);
3680 if (!*slot)
3682 *slot = symtab;
3683 m_symtabs.push_back (symtab);
3686 return false;
3689 } // namespace
3691 /* Given a file name, return a list of all matching symtabs. If
3692 SEARCH_PSPACE is not NULL, the search is restricted to just that
3693 program space. */
3695 static std::vector<symtab *>
3696 collect_symtabs_from_filename (const char *file,
3697 struct program_space *search_pspace)
3699 symtab_collector collector;
3701 /* Find that file's data. */
3702 if (search_pspace == NULL)
3704 for (struct program_space *pspace : program_spaces)
3706 if (pspace->executing_startup)
3707 continue;
3709 set_current_program_space (pspace);
3710 iterate_over_symtabs (file, collector);
3713 else
3715 set_current_program_space (search_pspace);
3716 iterate_over_symtabs (file, collector);
3719 return collector.release_symtabs ();
3722 /* Return all the symtabs associated to the FILENAME. If SEARCH_PSPACE is
3723 not NULL, the search is restricted to just that program space. */
3725 static std::vector<symtab *>
3726 symtabs_from_filename (const char *filename,
3727 struct program_space *search_pspace)
3729 std::vector<symtab *> result
3730 = collect_symtabs_from_filename (filename, search_pspace);
3732 if (result.empty ())
3734 if (!have_full_symbols () && !have_partial_symbols ())
3735 throw_error (NOT_FOUND_ERROR,
3736 _("No symbol table is loaded. "
3737 "Use the \"file\" command."));
3738 source_file_not_found_error (filename);
3741 return result;
3744 /* See symtab.h. */
3746 void
3747 symbol_searcher::find_all_symbols (const std::string &name,
3748 const struct language_defn *language,
3749 domain_search_flags domain_search_flags,
3750 std::vector<symtab *> *search_symtabs,
3751 struct program_space *search_pspace)
3753 symbol_searcher_collect_info info;
3754 struct linespec_state state;
3756 memset (&state, 0, sizeof (state));
3757 state.language = language;
3758 info.state = &state;
3760 info.result.symbols = &m_symbols;
3761 info.result.minimal_symbols = &m_minimal_symbols;
3762 std::vector<symtab *> all_symtabs;
3763 if (search_symtabs == nullptr)
3765 all_symtabs.push_back (nullptr);
3766 search_symtabs = &all_symtabs;
3768 info.file_symtabs = search_symtabs;
3770 add_matching_symbols_to_info (name.c_str (), symbol_name_match_type::WILD,
3771 domain_search_flags, &info, search_pspace);
3774 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS. Matching
3775 debug symbols are returned in SYMBOLS. Matching minimal symbols are
3776 returned in MINSYMS. */
3778 static void
3779 find_function_symbols (struct linespec_state *state,
3780 const std::vector<symtab *> &file_symtabs, const char *name,
3781 symbol_name_match_type name_match_type,
3782 std::vector<block_symbol> *symbols,
3783 std::vector<bound_minimal_symbol> *minsyms)
3785 struct collect_info info;
3786 std::vector<const char *> symbol_names;
3788 info.state = state;
3789 info.result.symbols = symbols;
3790 info.result.minimal_symbols = minsyms;
3791 info.file_symtabs = &file_symtabs;
3793 /* Try NAME as an Objective-C selector. */
3794 find_imps (name, &symbol_names);
3796 domain_search_flags flags = SEARCH_FUNCTION_DOMAIN;
3797 if (state->list_mode)
3798 flags = SEARCH_VFT;
3800 if (!symbol_names.empty ())
3801 add_all_symbol_names_from_pspace (&info, state->search_pspace,
3802 symbol_names, flags);
3803 else
3804 add_matching_symbols_to_info (name, name_match_type, flags,
3805 &info, state->search_pspace);
3808 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3809 in SYMBOLS and minimal symbols in MINSYMS. */
3811 static void
3812 find_linespec_symbols (struct linespec_state *state,
3813 const std::vector<symtab *> &file_symtabs,
3814 const char *lookup_name,
3815 symbol_name_match_type name_match_type,
3816 std::vector <block_symbol> *symbols,
3817 std::vector<bound_minimal_symbol> *minsyms)
3819 gdb::unique_xmalloc_ptr<char> canon
3820 = cp_canonicalize_string_no_typedefs (lookup_name);
3821 if (canon != nullptr)
3822 lookup_name = canon.get ();
3824 /* It's important to not call expand_symtabs_matching unnecessarily
3825 as it can really slow things down (by unnecessarily expanding
3826 potentially 1000s of symtabs, which when debugging some apps can
3827 cost 100s of seconds). Avoid this to some extent by *first* calling
3828 find_function_symbols, and only if that doesn't find anything
3829 *then* call find_method. This handles two important cases:
3830 1) break (anonymous namespace)::foo
3831 2) break class::method where method is in class (and not a baseclass) */
3833 find_function_symbols (state, file_symtabs, lookup_name,
3834 name_match_type, symbols, minsyms);
3836 /* If we were unable to locate a symbol of the same name, try dividing
3837 the name into class and method names and searching the class and its
3838 baseclasses. */
3839 if (symbols->empty () && minsyms->empty ())
3841 std::string klass, method;
3842 const char *last, *p, *scope_op;
3844 /* See if we can find a scope operator and break this symbol
3845 name into namespaces${SCOPE_OPERATOR}class_name and method_name. */
3846 scope_op = "::";
3847 p = find_toplevel_string (lookup_name, scope_op);
3849 last = NULL;
3850 while (p != NULL)
3852 last = p;
3853 p = find_toplevel_string (p + strlen (scope_op), scope_op);
3856 /* If no scope operator was found, there is nothing more we can do;
3857 we already attempted to lookup the entire name as a symbol
3858 and failed. */
3859 if (last == NULL)
3860 return;
3862 /* LOOKUP_NAME points to the class name.
3863 LAST points to the method name. */
3864 klass = std::string (lookup_name, last - lookup_name);
3866 /* Skip past the scope operator. */
3867 last += strlen (scope_op);
3868 method = last;
3870 /* Find a list of classes named KLASS. */
3871 std::vector<block_symbol> classes
3872 = lookup_prefix_sym (state, file_symtabs, klass.c_str ());
3873 if (!classes.empty ())
3875 /* Now locate a list of suitable methods named METHOD. */
3878 find_method (state, file_symtabs,
3879 klass.c_str (), method.c_str (),
3880 &classes, symbols, minsyms);
3883 /* If successful, we're done. If NOT_FOUND_ERROR
3884 was not thrown, rethrow the exception that we did get. */
3885 catch (const gdb_exception_error &except)
3887 if (except.error != NOT_FOUND_ERROR)
3888 throw;
3894 /* Helper for find_label_symbols. Find all labels that match name
3895 NAME in BLOCK. Return all labels that match in FUNCTION_SYMBOLS.
3896 Return the actual function symbol in which the label was found in
3897 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3898 interpreted as a label name prefix. Otherwise, only a label named
3899 exactly NAME match. */
3901 static void
3902 find_label_symbols_in_block (const struct block *block,
3903 const char *name, struct symbol *fn_sym,
3904 bool completion_mode,
3905 std::vector<block_symbol> *result,
3906 std::vector<block_symbol> *label_funcs_ret)
3908 if (completion_mode)
3910 size_t name_len = strlen (name);
3912 int (*cmp) (const char *, const char *, size_t);
3913 cmp = case_sensitivity == case_sensitive_on ? strncmp : strncasecmp;
3915 for (struct symbol *sym : block_iterator_range (block))
3917 if (sym->domain () == LABEL_DOMAIN
3918 && cmp (sym->search_name (), name, name_len) == 0)
3920 result->push_back ({sym, block});
3921 label_funcs_ret->push_back ({fn_sym, block});
3925 else
3927 struct block_symbol label_sym
3928 = lookup_symbol (name, block, SEARCH_LABEL_DOMAIN, 0);
3930 if (label_sym.symbol != NULL)
3932 result->push_back (label_sym);
3933 label_funcs_ret->push_back ({fn_sym, block});
3938 /* Return all labels that match name NAME in FUNCTION_SYMBOLS.
3940 Return the actual function symbol in which the label was found in
3941 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3942 interpreted as a label name prefix. Otherwise, only labels named
3943 exactly NAME match. */
3946 static std::vector<block_symbol>
3947 find_label_symbols (struct linespec_state *self,
3948 const std::vector<block_symbol> &function_symbols,
3949 std::vector<block_symbol> *label_funcs_ret,
3950 const char *name,
3951 bool completion_mode)
3953 const struct block *block;
3954 struct symbol *fn_sym;
3955 std::vector<block_symbol> result;
3957 if (function_symbols.empty ())
3959 set_current_program_space (self->program_space);
3960 block = get_current_search_block ();
3962 for (;
3963 block && !block->function ();
3964 block = block->superblock ())
3967 if (!block)
3968 return {};
3970 fn_sym = block->function ();
3972 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
3973 &result, label_funcs_ret);
3975 else
3977 for (const auto &elt : function_symbols)
3979 fn_sym = elt.symbol;
3980 set_current_program_space
3981 (fn_sym->symtab ()->compunit ()->objfile ()->pspace);
3982 block = fn_sym->value_block ();
3984 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
3985 &result, label_funcs_ret);
3989 return result;
3994 /* A helper for create_sals_line_offset that handles the 'list_mode' case. */
3996 static std::vector<symtab_and_line>
3997 decode_digits_list_mode (struct linespec_state *self,
3998 linespec *ls,
3999 struct symtab_and_line val)
4001 gdb_assert (self->list_mode);
4003 std::vector<symtab_and_line> values;
4005 for (const auto &elt : ls->file_symtabs)
4007 /* The logic above should ensure this. */
4008 gdb_assert (elt != NULL);
4010 program_space *pspace = elt->compunit ()->objfile ()->pspace;
4011 set_current_program_space (pspace);
4013 /* Simplistic search just for the list command. */
4014 val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
4015 if (val.symtab == NULL)
4016 val.symtab = elt;
4017 val.pspace = pspace;
4018 val.pc = 0;
4019 val.explicit_line = true;
4021 add_sal_to_sals (self, &values, &val, NULL, 0);
4024 return values;
4027 /* A helper for create_sals_line_offset that iterates over the symtabs
4028 associated with LS and returns a vector of corresponding symtab_and_line
4029 structures. */
4031 static std::vector<symtab_and_line>
4032 decode_digits_ordinary (struct linespec_state *self,
4033 linespec *ls,
4034 int line,
4035 const linetable_entry **best_entry)
4037 std::vector<symtab_and_line> sals;
4038 for (const auto &elt : ls->file_symtabs)
4040 std::vector<CORE_ADDR> pcs;
4042 /* The logic above should ensure this. */
4043 gdb_assert (elt != NULL);
4045 program_space *pspace = elt->compunit ()->objfile ()->pspace;
4046 set_current_program_space (pspace);
4048 pcs = find_pcs_for_symtab_line (elt, line, best_entry);
4049 for (CORE_ADDR pc : pcs)
4051 symtab_and_line sal;
4052 sal.pspace = pspace;
4053 sal.symtab = elt;
4054 sal.line = line;
4055 sal.explicit_line = true;
4056 sal.pc = pc;
4057 sals.push_back (std::move (sal));
4061 return sals;
4066 /* Return the line offset represented by VARIABLE. */
4068 static struct line_offset
4069 linespec_parse_variable (struct linespec_state *self, const char *variable)
4071 int index = 0;
4072 const char *p;
4073 line_offset offset;
4075 p = (variable[1] == '$') ? variable + 2 : variable + 1;
4076 if (*p == '$')
4077 ++p;
4078 while (*p >= '0' && *p <= '9')
4079 ++p;
4080 if (!*p) /* Reached end of token without hitting non-digit. */
4082 /* We have a value history reference. */
4083 struct value *val_history;
4085 sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
4086 val_history
4087 = access_value_history ((variable[1] == '$') ? -index : index);
4088 if (val_history->type ()->code () != TYPE_CODE_INT)
4089 error (_("History values used in line "
4090 "specs must have integer values."));
4091 offset.offset = value_as_long (val_history);
4092 offset.sign = LINE_OFFSET_NONE;
4094 else
4096 /* Not all digits -- may be user variable/function or a
4097 convenience variable. */
4098 LONGEST valx;
4099 struct internalvar *ivar;
4101 /* Try it as a convenience variable. If it is not a convenience
4102 variable, return and allow normal symbol lookup to occur. */
4103 ivar = lookup_only_internalvar (variable + 1);
4104 /* If there's no internal variable with that name, let the
4105 offset remain as unknown to allow the name to be looked up
4106 as a symbol. */
4107 if (ivar != nullptr)
4109 /* We found a valid variable name. If it is not an integer,
4110 throw an error. */
4111 if (!get_internalvar_integer (ivar, &valx))
4112 error (_("Convenience variables used in line "
4113 "specs must have integer values."));
4114 else
4116 offset.offset = valx;
4117 offset.sign = LINE_OFFSET_NONE;
4122 return offset;
4126 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
4127 linespec; return the SAL in RESULT. This function should return SALs
4128 matching those from find_function_start_sal, otherwise false
4129 multiple-locations breakpoints could be placed. */
4131 static void
4132 minsym_found (struct linespec_state *self, struct objfile *objfile,
4133 struct minimal_symbol *msymbol,
4134 std::vector<symtab_and_line> *result)
4136 bool want_start_sal = false;
4138 CORE_ADDR func_addr;
4139 bool is_function = msymbol_is_function (objfile, msymbol, &func_addr);
4141 if (is_function)
4143 const char *msym_name = msymbol->linkage_name ();
4145 if (msymbol->type () == mst_text_gnu_ifunc
4146 || msymbol->type () == mst_data_gnu_ifunc)
4147 want_start_sal = gnu_ifunc_resolve_name (msym_name, &func_addr);
4148 else
4149 want_start_sal = true;
4152 symtab_and_line sal;
4154 if (is_function && want_start_sal)
4155 sal = find_function_start_sal (func_addr, NULL, self->funfirstline);
4156 else
4158 sal.objfile = objfile;
4159 sal.msymbol = msymbol;
4160 /* Store func_addr, not the minsym's address in case this was an
4161 ifunc that hasn't been resolved yet. */
4162 if (is_function)
4163 sal.pc = func_addr;
4164 else
4165 sal.pc = msymbol->value_address (objfile);
4166 sal.pspace = current_program_space;
4169 sal.section = msymbol->obj_section (objfile);
4171 if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
4172 add_sal_to_sals (self, result, &sal, msymbol->natural_name (), 0);
4175 /* Helper for search_minsyms_for_name that adds the symbol to the
4176 result. */
4178 static void
4179 add_minsym (struct minimal_symbol *minsym, struct objfile *objfile,
4180 struct symtab *symtab, int list_mode,
4181 std::vector<struct bound_minimal_symbol> *msyms)
4183 if (symtab != NULL)
4185 /* We're looking for a label for which we don't have debug
4186 info. */
4187 CORE_ADDR func_addr;
4188 if (msymbol_is_function (objfile, minsym, &func_addr))
4190 symtab_and_line sal = find_pc_sect_line (func_addr, NULL, 0);
4192 if (symtab != sal.symtab)
4193 return;
4197 /* Exclude data symbols when looking for breakpoint locations. */
4198 if (!list_mode && !msymbol_is_function (objfile, minsym))
4199 return;
4201 msyms->emplace_back (minsym, objfile);
4202 return;
4205 /* Search for minimal symbols called NAME. If SEARCH_PSPACE
4206 is not NULL, the search is restricted to just that program
4207 space.
4209 If SYMTAB is NULL, search all objfiles, otherwise
4210 restrict results to the given SYMTAB. */
4212 static void
4213 search_minsyms_for_name (struct collect_info *info,
4214 const lookup_name_info &name,
4215 struct program_space *search_pspace,
4216 struct symtab *symtab)
4218 std::vector<struct bound_minimal_symbol> minsyms;
4220 if (symtab == NULL)
4222 for (struct program_space *pspace : program_spaces)
4224 if (search_pspace != NULL && search_pspace != pspace)
4225 continue;
4226 if (pspace->executing_startup)
4227 continue;
4229 set_current_program_space (pspace);
4231 for (objfile *objfile : current_program_space->objfiles ())
4233 iterate_over_minimal_symbols (objfile, name,
4234 [&] (struct minimal_symbol *msym)
4236 add_minsym (msym, objfile, nullptr,
4237 info->state->list_mode,
4238 &minsyms);
4239 return false;
4244 else
4246 program_space *pspace = symtab->compunit ()->objfile ()->pspace;
4248 if (search_pspace == NULL || pspace == search_pspace)
4250 set_current_program_space (pspace);
4251 iterate_over_minimal_symbols
4252 (symtab->compunit ()->objfile (), name,
4253 [&] (struct minimal_symbol *msym)
4255 add_minsym (msym, symtab->compunit ()->objfile (), symtab,
4256 info->state->list_mode, &minsyms);
4257 return false;
4262 /* Return true if TYPE is a static symbol. */
4263 auto msymbol_type_is_static = [] (enum minimal_symbol_type type)
4265 switch (type)
4267 case mst_file_text:
4268 case mst_file_data:
4269 case mst_file_bss:
4270 return true;
4271 default:
4272 return false;
4276 /* Add minsyms to the result set, but filter out trampoline symbols
4277 if we also found extern symbols with the same name. I.e., don't
4278 set a breakpoint on both '<foo@plt>' and 'foo', assuming that
4279 'foo' is the symbol that the plt resolves to. */
4280 for (const bound_minimal_symbol &item : minsyms)
4282 bool skip = false;
4283 if (item.minsym->type () == mst_solib_trampoline)
4285 for (const bound_minimal_symbol &item2 : minsyms)
4287 if (&item2 == &item)
4288 continue;
4290 /* Ignore other trampoline symbols. */
4291 if (item2.minsym->type () == mst_solib_trampoline)
4292 continue;
4294 /* Trampoline symbols can only jump to exported
4295 symbols. */
4296 if (msymbol_type_is_static (item2.minsym->type ()))
4297 continue;
4299 if (strcmp (item.minsym->linkage_name (),
4300 item2.minsym->linkage_name ()) != 0)
4301 continue;
4303 /* Found a global minsym with the same name as the
4304 trampoline. Don't create a location for this
4305 trampoline. */
4306 skip = true;
4307 break;
4311 if (!skip)
4312 info->result.minimal_symbols->push_back (item);
4316 /* A helper function to add all symbols matching NAME to INFO. If
4317 PSPACE is not NULL, the search is restricted to just that program
4318 space. */
4320 static void
4321 add_matching_symbols_to_info (const char *name,
4322 symbol_name_match_type name_match_type,
4323 domain_search_flags domain_search_flags,
4324 struct collect_info *info,
4325 struct program_space *pspace)
4327 lookup_name_info lookup_name (name, name_match_type);
4329 for (const auto &elt : *info->file_symtabs)
4331 if (elt == nullptr)
4333 iterate_over_all_matching_symtabs (info->state, lookup_name,
4334 domain_search_flags,
4335 pspace, true,
4336 [&] (block_symbol *bsym)
4337 { return info->add_symbol (bsym); });
4338 search_minsyms_for_name (info, lookup_name, pspace, NULL);
4340 else if (pspace == NULL || pspace == elt->compunit ()->objfile ()->pspace)
4342 int prev_len = info->result.symbols->size ();
4344 /* Program spaces that are executing startup should have
4345 been filtered out earlier. */
4346 program_space *elt_pspace = elt->compunit ()->objfile ()->pspace;
4347 gdb_assert (!elt_pspace->executing_startup);
4348 set_current_program_space (elt_pspace);
4349 iterate_over_file_blocks (elt, lookup_name, SEARCH_VFT,
4350 [&] (block_symbol *bsym)
4351 { return info->add_symbol (bsym); });
4353 /* If no new symbols were found in this iteration and this symtab
4354 is in assembler, we might actually be looking for a label for
4355 which we don't have debug info. Check for a minimal symbol in
4356 this case. */
4357 if (prev_len == info->result.symbols->size ()
4358 && elt->language () == language_asm)
4359 search_minsyms_for_name (info, lookup_name, pspace, elt);
4366 /* Now come some functions that are called from multiple places within
4367 decode_line_1. */
4369 static int
4370 symbol_to_sal (struct symtab_and_line *result,
4371 int funfirstline, struct symbol *sym)
4373 if (sym->aclass () == LOC_BLOCK)
4375 *result = find_function_start_sal (sym, funfirstline);
4376 return 1;
4378 else
4380 if (sym->aclass () == LOC_LABEL && sym->value_address () != 0)
4382 *result = {};
4383 result->symtab = sym->symtab ();
4384 result->symbol = sym;
4385 result->line = sym->line ();
4386 result->pc = sym->value_address ();
4387 result->pspace = result->symtab->compunit ()->objfile ()->pspace;
4388 result->explicit_pc = 1;
4389 return 1;
4391 else if (funfirstline)
4393 /* Nothing. */
4395 else if (sym->line () != 0)
4397 /* We know its line number. */
4398 *result = {};
4399 result->symtab = sym->symtab ();
4400 result->symbol = sym;
4401 result->line = sym->line ();
4402 result->pc = sym->value_address ();
4403 result->pspace = result->symtab->compunit ()->objfile ()->pspace;
4404 return 1;
4408 return 0;
4411 linespec_result::~linespec_result ()
4413 for (linespec_sals &lsal : lsals)
4414 xfree (lsal.canonical);
4417 /* Return the quote characters permitted by the linespec parser. */
4419 const char *
4420 get_gdb_linespec_parser_quote_characters (void)
4422 return linespec_quote_characters;