Fix copyright header in gdb/testsuite/gdb.arch/powerpc-power10.exp
[binutils-gdb.git] / gdb / linespec.c
blobeb911ccdb3592b924e1fda20a7f4af5c14b88443
1 /* Parser for linespec for the GNU debugger, GDB.
3 Copyright (C) 1986-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "symtab.h"
22 #include "frame.h"
23 #include "command.h"
24 #include "symfile.h"
25 #include "objfiles.h"
26 #include "source.h"
27 #include "demangle.h"
28 #include "value.h"
29 #include "completer.h"
30 #include "cp-abi.h"
31 #include "cp-support.h"
32 #include "parser-defs.h"
33 #include "block.h"
34 #include "objc-lang.h"
35 #include "linespec.h"
36 #include "language.h"
37 #include "interps.h"
38 #include "mi/mi-cmds.h"
39 #include "target.h"
40 #include "arch-utils.h"
41 #include <ctype.h>
42 #include "cli/cli-utils.h"
43 #include "filenames.h"
44 #include "ada-lang.h"
45 #include "stack.h"
46 #include "location.h"
47 #include "gdbsupport/function-view.h"
48 #include "gdbsupport/def-vector.h"
49 #include <algorithm>
50 #include "inferior.h"
52 /* An enumeration of the various things a user might attempt to
53 complete for a linespec location. */
55 enum class linespec_complete_what
57 /* Nothing, no possible completion. */
58 NOTHING,
60 /* A function/method name. Due to ambiguity between
62 (gdb) b source[TAB]
63 source_file.c
64 source_function
66 this can also indicate a source filename, iff we haven't seen a
67 separate source filename component, as in "b source.c:function". */
68 FUNCTION,
70 /* A label symbol. E.g., break file.c:function:LABEL. */
71 LABEL,
73 /* An expression. E.g., "break foo if EXPR", or "break *EXPR". */
74 EXPRESSION,
76 /* A linespec keyword ("if"/"thread"/"task"/"-force-condition").
77 E.g., "break func threa<tab>". */
78 KEYWORD,
81 /* An address entry is used to ensure that any given location is only
82 added to the result a single time. It holds an address and the
83 program space from which the address came. */
85 struct address_entry
87 struct program_space *pspace;
88 CORE_ADDR addr;
91 /* A linespec. Elements of this structure are filled in by a parser
92 (either parse_linespec or some other function). The structure is
93 then converted into SALs by convert_linespec_to_sals. */
95 struct linespec
97 /* An explicit location describing the SaLs. */
98 struct explicit_location explicit_loc {};
100 /* The list of symtabs to search to which to limit the search.
102 If explicit.SOURCE_FILENAME is NULL (no user-specified filename),
103 FILE_SYMTABS should contain one single NULL member. This will cause the
104 code to use the default symtab. */
105 std::vector<symtab *> file_symtabs;
107 /* A list of matching function symbols and minimal symbols. Both lists
108 may be empty if no matching symbols were found. */
109 std::vector<block_symbol> function_symbols;
110 std::vector<bound_minimal_symbol> minimal_symbols;
112 /* A structure of matching label symbols and the corresponding
113 function symbol in which the label was found. Both may be empty
114 or both must be non-empty. */
115 struct
117 std::vector<block_symbol> label_symbols;
118 std::vector<block_symbol> function_symbols;
119 } labels;
122 /* A canonical linespec represented as a symtab-related string.
124 Each entry represents the "SYMTAB:SUFFIX" linespec string.
125 SYMTAB can be converted for example by symtab_to_fullname or
126 symtab_to_filename_for_display as needed. */
128 struct linespec_canonical_name
130 /* Remaining text part of the linespec string. */
131 char *suffix;
133 /* If NULL then SUFFIX is the whole linespec string. */
134 struct symtab *symtab;
137 /* An instance of this is used to keep all state while linespec
138 operates. This instance is passed around as a 'this' pointer to
139 the various implementation methods. */
141 struct linespec_state
143 /* The language in use during linespec processing. */
144 const struct language_defn *language;
146 /* The program space as seen when the module was entered. */
147 struct program_space *program_space;
149 /* If not NULL, the search is restricted to just this program
150 space. */
151 struct program_space *search_pspace;
153 /* The default symtab to use, if no other symtab is specified. */
154 struct symtab *default_symtab;
156 /* The default line to use. */
157 int default_line;
159 /* The 'funfirstline' value that was passed in to decode_line_1 or
160 decode_line_full. */
161 int funfirstline;
163 /* Nonzero if we are running in 'list' mode; see decode_line_list. */
164 int list_mode;
166 /* The 'canonical' value passed to decode_line_full, or NULL. */
167 struct linespec_result *canonical;
169 /* Canonical strings that mirror the std::vector<symtab_and_line> result. */
170 struct linespec_canonical_name *canonical_names;
172 /* This is a set of address_entry objects which is used to prevent
173 duplicate symbols from being entered into the result. */
174 htab_t addr_set;
176 /* Are we building a linespec? */
177 int is_linespec;
180 /* This is a helper object that is used when collecting symbols into a
181 result. */
183 struct collect_info
185 /* The linespec object in use. */
186 struct linespec_state *state;
188 /* A list of symtabs to which to restrict matches. */
189 const std::vector<symtab *> *file_symtabs;
191 /* The result being accumulated. */
192 struct
194 std::vector<block_symbol> *symbols;
195 std::vector<bound_minimal_symbol> *minimal_symbols;
196 } result;
198 /* Possibly add a symbol to the results. */
199 virtual bool add_symbol (block_symbol *bsym);
202 bool
203 collect_info::add_symbol (block_symbol *bsym)
205 /* In list mode, add all matching symbols, regardless of class.
206 This allows the user to type "list a_global_variable". */
207 if (SYMBOL_CLASS (bsym->symbol) == LOC_BLOCK || this->state->list_mode)
208 this->result.symbols->push_back (*bsym);
210 /* Continue iterating. */
211 return true;
214 /* Custom collect_info for symbol_searcher. */
216 struct symbol_searcher_collect_info
217 : collect_info
219 bool add_symbol (block_symbol *bsym) override
221 /* Add everything. */
222 this->result.symbols->push_back (*bsym);
224 /* Continue iterating. */
225 return true;
229 /* Token types */
231 enum ls_token_type
233 /* A keyword */
234 LSTOKEN_KEYWORD = 0,
236 /* A colon "separator" */
237 LSTOKEN_COLON,
239 /* A string */
240 LSTOKEN_STRING,
242 /* A number */
243 LSTOKEN_NUMBER,
245 /* A comma */
246 LSTOKEN_COMMA,
248 /* EOI (end of input) */
249 LSTOKEN_EOI,
251 /* Consumed token */
252 LSTOKEN_CONSUMED
254 typedef enum ls_token_type linespec_token_type;
256 /* List of keywords. This is NULL-terminated so that it can be used
257 as enum completer. */
258 const char * const linespec_keywords[] = { "if", "thread", "task", "-force-condition", NULL };
259 #define IF_KEYWORD_INDEX 0
260 #define FORCE_KEYWORD_INDEX 3
262 /* A token of the linespec lexer */
264 struct linespec_token
266 /* The type of the token */
267 linespec_token_type type;
269 /* Data for the token */
270 union
272 /* A string, given as a stoken */
273 struct stoken string;
275 /* A keyword */
276 const char *keyword;
277 } data;
280 #define LS_TOKEN_STOKEN(TOK) (TOK).data.string
281 #define LS_TOKEN_KEYWORD(TOK) (TOK).data.keyword
283 /* An instance of the linespec parser. */
285 struct linespec_parser
287 linespec_parser (int flags, const struct language_defn *language,
288 struct program_space *search_pspace,
289 struct symtab *default_symtab,
290 int default_line,
291 struct linespec_result *canonical);
293 ~linespec_parser ();
295 DISABLE_COPY_AND_ASSIGN (linespec_parser);
297 /* Lexer internal data */
298 struct
300 /* Save head of input stream. */
301 const char *saved_arg;
303 /* Head of the input stream. */
304 const char *stream;
305 #define PARSER_STREAM(P) ((P)->lexer.stream)
307 /* The current token. */
308 linespec_token current;
309 } lexer {};
311 /* Is the entire linespec quote-enclosed? */
312 int is_quote_enclosed = 0;
314 /* The state of the parse. */
315 struct linespec_state state {};
316 #define PARSER_STATE(PPTR) (&(PPTR)->state)
318 /* The result of the parse. */
319 linespec result;
320 #define PARSER_RESULT(PPTR) (&(PPTR)->result)
322 /* What the parser believes the current word point should complete
323 to. */
324 linespec_complete_what complete_what = linespec_complete_what::NOTHING;
326 /* The completion word point. The parser advances this as it skips
327 tokens. At some point the input string will end or parsing will
328 fail, and then we attempt completion at the captured completion
329 word point, interpreting the string at completion_word as
330 COMPLETE_WHAT. */
331 const char *completion_word = nullptr;
333 /* If the current token was a quoted string, then this is the
334 quoting character (either " or '). */
335 int completion_quote_char = 0;
337 /* If the current token was a quoted string, then this points at the
338 end of the quoted string. */
339 const char *completion_quote_end = nullptr;
341 /* If parsing for completion, then this points at the completion
342 tracker. Otherwise, this is NULL. */
343 struct completion_tracker *completion_tracker = nullptr;
346 /* A convenience macro for accessing the explicit location result of
347 the parser. */
348 #define PARSER_EXPLICIT(PPTR) (&PARSER_RESULT ((PPTR))->explicit_loc)
350 /* Prototypes for local functions. */
352 static void iterate_over_file_blocks
353 (struct symtab *symtab, const lookup_name_info &name,
354 domain_enum domain,
355 gdb::function_view<symbol_found_callback_ftype> callback);
357 static void initialize_defaults (struct symtab **default_symtab,
358 int *default_line);
360 CORE_ADDR linespec_expression_to_pc (const char **exp_ptr);
362 static std::vector<symtab_and_line> decode_objc (struct linespec_state *self,
363 linespec *ls,
364 const char *arg);
366 static std::vector<symtab *> symtabs_from_filename
367 (const char *, struct program_space *pspace);
369 static std::vector<block_symbol> find_label_symbols
370 (struct linespec_state *self,
371 const std::vector<block_symbol> &function_symbols,
372 std::vector<block_symbol> *label_funcs_ret,
373 const char *name, bool completion_mode = false);
375 static void find_linespec_symbols (struct linespec_state *self,
376 const std::vector<symtab *> &file_symtabs,
377 const char *name,
378 symbol_name_match_type name_match_type,
379 std::vector<block_symbol> *symbols,
380 std::vector<bound_minimal_symbol> *minsyms);
382 static struct line_offset
383 linespec_parse_variable (struct linespec_state *self,
384 const char *variable);
386 static int symbol_to_sal (struct symtab_and_line *result,
387 int funfirstline, struct symbol *sym);
389 static void add_matching_symbols_to_info (const char *name,
390 symbol_name_match_type name_match_type,
391 enum search_domain search_domain,
392 struct collect_info *info,
393 struct program_space *pspace);
395 static void add_all_symbol_names_from_pspace
396 (struct collect_info *info, struct program_space *pspace,
397 const std::vector<const char *> &names, enum search_domain search_domain);
399 static std::vector<symtab *>
400 collect_symtabs_from_filename (const char *file,
401 struct program_space *pspace);
403 static std::vector<symtab_and_line> decode_digits_ordinary
404 (struct linespec_state *self,
405 linespec *ls,
406 int line,
407 linetable_entry **best_entry);
409 static std::vector<symtab_and_line> decode_digits_list_mode
410 (struct linespec_state *self,
411 linespec *ls,
412 struct symtab_and_line val);
414 static void minsym_found (struct linespec_state *self, struct objfile *objfile,
415 struct minimal_symbol *msymbol,
416 std::vector<symtab_and_line> *result);
418 static bool compare_symbols (const block_symbol &a, const block_symbol &b);
420 static bool compare_msymbols (const bound_minimal_symbol &a,
421 const bound_minimal_symbol &b);
423 /* Permitted quote characters for the parser. This is different from the
424 completer's quote characters to allow backward compatibility with the
425 previous parser. */
426 static const char linespec_quote_characters[] = "\"\'";
428 /* Lexer functions. */
430 /* Lex a number from the input in PARSER. This only supports
431 decimal numbers.
433 Return true if input is decimal numbers. Return false if not. */
435 static int
436 linespec_lexer_lex_number (linespec_parser *parser, linespec_token *tokenp)
438 tokenp->type = LSTOKEN_NUMBER;
439 LS_TOKEN_STOKEN (*tokenp).length = 0;
440 LS_TOKEN_STOKEN (*tokenp).ptr = PARSER_STREAM (parser);
442 /* Keep any sign at the start of the stream. */
443 if (*PARSER_STREAM (parser) == '+' || *PARSER_STREAM (parser) == '-')
445 ++LS_TOKEN_STOKEN (*tokenp).length;
446 ++(PARSER_STREAM (parser));
449 while (isdigit (*PARSER_STREAM (parser)))
451 ++LS_TOKEN_STOKEN (*tokenp).length;
452 ++(PARSER_STREAM (parser));
455 /* If the next character in the input buffer is not a space, comma,
456 quote, or colon, this input does not represent a number. */
457 if (*PARSER_STREAM (parser) != '\0'
458 && !isspace (*PARSER_STREAM (parser)) && *PARSER_STREAM (parser) != ','
459 && *PARSER_STREAM (parser) != ':'
460 && !strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
462 PARSER_STREAM (parser) = LS_TOKEN_STOKEN (*tokenp).ptr;
463 return 0;
466 return 1;
469 /* See linespec.h. */
471 const char *
472 linespec_lexer_lex_keyword (const char *p)
474 int i;
476 if (p != NULL)
478 for (i = 0; linespec_keywords[i] != NULL; ++i)
480 int len = strlen (linespec_keywords[i]);
482 /* If P begins with
484 - "thread" or "task" and the next character is
485 whitespace, we may have found a keyword. It is only a
486 keyword if it is not followed by another keyword.
488 - "-force-condition", the next character may be EOF
489 since this keyword does not take any arguments. Otherwise,
490 it should be followed by a keyword.
492 - "if", ALWAYS stop the lexer, since it is not possible to
493 predict what is going to appear in the condition, which can
494 only be parsed after SaLs have been found. */
495 if (strncmp (p, linespec_keywords[i], len) == 0)
497 int j;
499 if (i == FORCE_KEYWORD_INDEX && p[len] == '\0')
500 return linespec_keywords[i];
502 if (!isspace (p[len]))
503 continue;
505 if (i == FORCE_KEYWORD_INDEX)
507 p += len;
508 p = skip_spaces (p);
509 for (j = 0; linespec_keywords[j] != NULL; ++j)
511 int nextlen = strlen (linespec_keywords[j]);
513 if (strncmp (p, linespec_keywords[j], nextlen) == 0
514 && isspace (p[nextlen]))
515 return linespec_keywords[i];
518 else if (i != IF_KEYWORD_INDEX)
520 /* We matched a "thread" or "task". */
521 p += len;
522 p = skip_spaces (p);
523 for (j = 0; linespec_keywords[j] != NULL; ++j)
525 int nextlen = strlen (linespec_keywords[j]);
527 if (strncmp (p, linespec_keywords[j], nextlen) == 0
528 && isspace (p[nextlen]))
529 return NULL;
533 return linespec_keywords[i];
538 return NULL;
541 /* See description in linespec.h. */
544 is_ada_operator (const char *string)
546 const struct ada_opname_map *mapping;
548 for (mapping = ada_opname_table;
549 mapping->encoded != NULL
550 && !startswith (string, mapping->decoded); ++mapping)
553 return mapping->decoded == NULL ? 0 : strlen (mapping->decoded);
556 /* Find QUOTE_CHAR in STRING, accounting for the ':' terminal. Return
557 the location of QUOTE_CHAR, or NULL if not found. */
559 static const char *
560 skip_quote_char (const char *string, char quote_char)
562 const char *p, *last;
564 p = last = find_toplevel_char (string, quote_char);
565 while (p && *p != '\0' && *p != ':')
567 p = find_toplevel_char (p, quote_char);
568 if (p != NULL)
569 last = p++;
572 return last;
575 /* Make a writable copy of the string given in TOKEN, trimming
576 any trailing whitespace. */
578 static gdb::unique_xmalloc_ptr<char>
579 copy_token_string (linespec_token token)
581 const char *str, *s;
583 if (token.type == LSTOKEN_KEYWORD)
584 return make_unique_xstrdup (LS_TOKEN_KEYWORD (token));
586 str = LS_TOKEN_STOKEN (token).ptr;
587 s = remove_trailing_whitespace (str, str + LS_TOKEN_STOKEN (token).length);
589 return gdb::unique_xmalloc_ptr<char> (savestring (str, s - str));
592 /* Does P represent the end of a quote-enclosed linespec? */
594 static int
595 is_closing_quote_enclosed (const char *p)
597 if (strchr (linespec_quote_characters, *p))
598 ++p;
599 p = skip_spaces ((char *) p);
600 return (*p == '\0' || linespec_lexer_lex_keyword (p));
603 /* Find the end of the parameter list that starts with *INPUT.
604 This helper function assists with lexing string segments
605 which might contain valid (non-terminating) commas. */
607 static const char *
608 find_parameter_list_end (const char *input)
610 char end_char, start_char;
611 int depth;
612 const char *p;
614 start_char = *input;
615 if (start_char == '(')
616 end_char = ')';
617 else if (start_char == '<')
618 end_char = '>';
619 else
620 return NULL;
622 p = input;
623 depth = 0;
624 while (*p)
626 if (*p == start_char)
627 ++depth;
628 else if (*p == end_char)
630 if (--depth == 0)
632 ++p;
633 break;
636 ++p;
639 return p;
642 /* If the [STRING, STRING_LEN) string ends with what looks like a
643 keyword, return the keyword start offset in STRING. Return -1
644 otherwise. */
646 static size_t
647 string_find_incomplete_keyword_at_end (const char * const *keywords,
648 const char *string, size_t string_len)
650 const char *end = string + string_len;
651 const char *p = end;
653 while (p > string && *p != ' ')
654 --p;
655 if (p > string)
657 p++;
658 size_t len = end - p;
659 for (size_t i = 0; keywords[i] != NULL; ++i)
660 if (strncmp (keywords[i], p, len) == 0)
661 return p - string;
664 return -1;
667 /* Lex a string from the input in PARSER. */
669 static linespec_token
670 linespec_lexer_lex_string (linespec_parser *parser)
672 linespec_token token;
673 const char *start = PARSER_STREAM (parser);
675 token.type = LSTOKEN_STRING;
677 /* If the input stream starts with a quote character, skip to the next
678 quote character, regardless of the content. */
679 if (strchr (linespec_quote_characters, *PARSER_STREAM (parser)))
681 const char *end;
682 char quote_char = *PARSER_STREAM (parser);
684 /* Special case: Ada operators. */
685 if (PARSER_STATE (parser)->language->la_language == language_ada
686 && quote_char == '\"')
688 int len = is_ada_operator (PARSER_STREAM (parser));
690 if (len != 0)
692 /* The input is an Ada operator. Return the quoted string
693 as-is. */
694 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
695 LS_TOKEN_STOKEN (token).length = len;
696 PARSER_STREAM (parser) += len;
697 return token;
700 /* The input does not represent an Ada operator -- fall through
701 to normal quoted string handling. */
704 /* Skip past the beginning quote. */
705 ++(PARSER_STREAM (parser));
707 /* Mark the start of the string. */
708 LS_TOKEN_STOKEN (token).ptr = PARSER_STREAM (parser);
710 /* Skip to the ending quote. */
711 end = skip_quote_char (PARSER_STREAM (parser), quote_char);
713 /* This helps the completer mode decide whether we have a
714 complete string. */
715 parser->completion_quote_char = quote_char;
716 parser->completion_quote_end = end;
718 /* Error if the input did not terminate properly, unless in
719 completion mode. */
720 if (end == NULL)
722 if (parser->completion_tracker == NULL)
723 error (_("unmatched quote"));
725 /* In completion mode, we'll try to complete the incomplete
726 token. */
727 token.type = LSTOKEN_STRING;
728 while (*PARSER_STREAM (parser) != '\0')
729 PARSER_STREAM (parser)++;
730 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 1 - start;
732 else
734 /* Skip over the ending quote and mark the length of the string. */
735 PARSER_STREAM (parser) = (char *) ++end;
736 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - 2 - start;
739 else
741 const char *p;
743 /* Otherwise, only identifier characters are permitted.
744 Spaces are the exception. In general, we keep spaces,
745 but only if the next characters in the input do not resolve
746 to one of the keywords.
748 This allows users to forgo quoting CV-qualifiers, template arguments,
749 and similar common language constructs. */
751 while (1)
753 if (isspace (*PARSER_STREAM (parser)))
755 p = skip_spaces (PARSER_STREAM (parser));
756 /* When we get here we know we've found something followed by
757 a space (we skip over parens and templates below).
758 So if we find a keyword now, we know it is a keyword and not,
759 say, a function name. */
760 if (linespec_lexer_lex_keyword (p) != NULL)
762 LS_TOKEN_STOKEN (token).ptr = start;
763 LS_TOKEN_STOKEN (token).length
764 = PARSER_STREAM (parser) - start;
765 return token;
768 /* Advance past the whitespace. */
769 PARSER_STREAM (parser) = p;
772 /* If the next character is EOI or (single) ':', the
773 string is complete; return the token. */
774 if (*PARSER_STREAM (parser) == 0)
776 LS_TOKEN_STOKEN (token).ptr = start;
777 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
778 return token;
780 else if (PARSER_STREAM (parser)[0] == ':')
782 /* Do not tokenize the C++ scope operator. */
783 if (PARSER_STREAM (parser)[1] == ':')
784 ++(PARSER_STREAM (parser));
786 /* Do not tokenize ABI tags such as "[abi:cxx11]". */
787 else if (PARSER_STREAM (parser) - start > 4
788 && startswith (PARSER_STREAM (parser) - 4, "[abi"))
790 /* Nothing. */
793 /* Do not tokenify if the input length so far is one
794 (i.e, a single-letter drive name) and the next character
795 is a directory separator. This allows Windows-style
796 paths to be recognized as filenames without quoting it. */
797 else if ((PARSER_STREAM (parser) - start) != 1
798 || !IS_DIR_SEPARATOR (PARSER_STREAM (parser)[1]))
800 LS_TOKEN_STOKEN (token).ptr = start;
801 LS_TOKEN_STOKEN (token).length
802 = PARSER_STREAM (parser) - start;
803 return token;
806 /* Special case: permit quote-enclosed linespecs. */
807 else if (parser->is_quote_enclosed
808 && strchr (linespec_quote_characters,
809 *PARSER_STREAM (parser))
810 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
812 LS_TOKEN_STOKEN (token).ptr = start;
813 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
814 return token;
816 /* Because commas may terminate a linespec and appear in
817 the middle of valid string input, special cases for
818 '<' and '(' are necessary. */
819 else if (*PARSER_STREAM (parser) == '<'
820 || *PARSER_STREAM (parser) == '(')
822 /* Don't interpret 'operator<' / 'operator<<' as a
823 template parameter list though. */
824 if (*PARSER_STREAM (parser) == '<'
825 && (PARSER_STATE (parser)->language->la_language
826 == language_cplus)
827 && (PARSER_STREAM (parser) - start) >= CP_OPERATOR_LEN)
829 const char *op = PARSER_STREAM (parser);
831 while (op > start && isspace (op[-1]))
832 op--;
833 if (op - start >= CP_OPERATOR_LEN)
835 op -= CP_OPERATOR_LEN;
836 if (strncmp (op, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0
837 && (op == start
838 || !(isalnum (op[-1]) || op[-1] == '_')))
840 /* This is an operator name. Keep going. */
841 ++(PARSER_STREAM (parser));
842 if (*PARSER_STREAM (parser) == '<')
843 ++(PARSER_STREAM (parser));
844 continue;
849 const char *end = find_parameter_list_end (PARSER_STREAM (parser));
850 PARSER_STREAM (parser) = end;
852 /* Don't loop around to the normal \0 case above because
853 we don't want to misinterpret a potential keyword at
854 the end of the token when the string isn't
855 "()<>"-balanced. This handles "b
856 function(thread<tab>" in completion mode. */
857 if (*end == '\0')
859 LS_TOKEN_STOKEN (token).ptr = start;
860 LS_TOKEN_STOKEN (token).length
861 = PARSER_STREAM (parser) - start;
862 return token;
864 else
865 continue;
867 /* Commas are terminators, but not if they are part of an
868 operator name. */
869 else if (*PARSER_STREAM (parser) == ',')
871 if ((PARSER_STATE (parser)->language->la_language
872 == language_cplus)
873 && (PARSER_STREAM (parser) - start) > CP_OPERATOR_LEN)
875 const char *op = strstr (start, CP_OPERATOR_STR);
877 if (op != NULL && is_operator_name (op))
879 /* This is an operator name. Keep going. */
880 ++(PARSER_STREAM (parser));
881 continue;
885 /* Comma terminates the string. */
886 LS_TOKEN_STOKEN (token).ptr = start;
887 LS_TOKEN_STOKEN (token).length = PARSER_STREAM (parser) - start;
888 return token;
891 /* Advance the stream. */
892 gdb_assert (*(PARSER_STREAM (parser)) != '\0');
893 ++(PARSER_STREAM (parser));
897 return token;
900 /* Lex a single linespec token from PARSER. */
902 static linespec_token
903 linespec_lexer_lex_one (linespec_parser *parser)
905 const char *keyword;
907 if (parser->lexer.current.type == LSTOKEN_CONSUMED)
909 /* Skip any whitespace. */
910 PARSER_STREAM (parser) = skip_spaces (PARSER_STREAM (parser));
912 /* Check for a keyword, they end the linespec. */
913 keyword = linespec_lexer_lex_keyword (PARSER_STREAM (parser));
914 if (keyword != NULL)
916 parser->lexer.current.type = LSTOKEN_KEYWORD;
917 LS_TOKEN_KEYWORD (parser->lexer.current) = keyword;
918 /* We do not advance the stream here intentionally:
919 we would like lexing to stop when a keyword is seen.
921 PARSER_STREAM (parser) += strlen (keyword); */
923 return parser->lexer.current;
926 /* Handle other tokens. */
927 switch (*PARSER_STREAM (parser))
929 case 0:
930 parser->lexer.current.type = LSTOKEN_EOI;
931 break;
933 case '+': case '-':
934 case '0': case '1': case '2': case '3': case '4':
935 case '5': case '6': case '7': case '8': case '9':
936 if (!linespec_lexer_lex_number (parser, &(parser->lexer.current)))
937 parser->lexer.current = linespec_lexer_lex_string (parser);
938 break;
940 case ':':
941 /* If we have a scope operator, lex the input as a string.
942 Otherwise, return LSTOKEN_COLON. */
943 if (PARSER_STREAM (parser)[1] == ':')
944 parser->lexer.current = linespec_lexer_lex_string (parser);
945 else
947 parser->lexer.current.type = LSTOKEN_COLON;
948 ++(PARSER_STREAM (parser));
950 break;
952 case '\'': case '\"':
953 /* Special case: permit quote-enclosed linespecs. */
954 if (parser->is_quote_enclosed
955 && is_closing_quote_enclosed (PARSER_STREAM (parser)))
957 ++(PARSER_STREAM (parser));
958 parser->lexer.current.type = LSTOKEN_EOI;
960 else
961 parser->lexer.current = linespec_lexer_lex_string (parser);
962 break;
964 case ',':
965 parser->lexer.current.type = LSTOKEN_COMMA;
966 LS_TOKEN_STOKEN (parser->lexer.current).ptr
967 = PARSER_STREAM (parser);
968 LS_TOKEN_STOKEN (parser->lexer.current).length = 1;
969 ++(PARSER_STREAM (parser));
970 break;
972 default:
973 /* If the input is not a number, it must be a string.
974 [Keywords were already considered above.] */
975 parser->lexer.current = linespec_lexer_lex_string (parser);
976 break;
980 return parser->lexer.current;
983 /* Consume the current token and return the next token in PARSER's
984 input stream. Also advance the completion word for completion
985 mode. */
987 static linespec_token
988 linespec_lexer_consume_token (linespec_parser *parser)
990 gdb_assert (parser->lexer.current.type != LSTOKEN_EOI);
992 bool advance_word = (parser->lexer.current.type != LSTOKEN_STRING
993 || *PARSER_STREAM (parser) != '\0');
995 /* If we're moving past a string to some other token, it must be the
996 quote was terminated. */
997 if (parser->completion_quote_char)
999 gdb_assert (parser->lexer.current.type == LSTOKEN_STRING);
1001 /* If the string was the last (non-EOI) token, we're past the
1002 quote, but remember that for later. */
1003 if (*PARSER_STREAM (parser) != '\0')
1005 parser->completion_quote_char = '\0';
1006 parser->completion_quote_end = NULL;;
1010 parser->lexer.current.type = LSTOKEN_CONSUMED;
1011 linespec_lexer_lex_one (parser);
1013 if (parser->lexer.current.type == LSTOKEN_STRING)
1015 /* Advance the completion word past a potential initial
1016 quote-char. */
1017 parser->completion_word = LS_TOKEN_STOKEN (parser->lexer.current).ptr;
1019 else if (advance_word)
1021 /* Advance the completion word past any whitespace. */
1022 parser->completion_word = PARSER_STREAM (parser);
1025 return parser->lexer.current;
1028 /* Return the next token without consuming the current token. */
1030 static linespec_token
1031 linespec_lexer_peek_token (linespec_parser *parser)
1033 linespec_token next;
1034 const char *saved_stream = PARSER_STREAM (parser);
1035 linespec_token saved_token = parser->lexer.current;
1036 int saved_completion_quote_char = parser->completion_quote_char;
1037 const char *saved_completion_quote_end = parser->completion_quote_end;
1038 const char *saved_completion_word = parser->completion_word;
1040 next = linespec_lexer_consume_token (parser);
1041 PARSER_STREAM (parser) = saved_stream;
1042 parser->lexer.current = saved_token;
1043 parser->completion_quote_char = saved_completion_quote_char;
1044 parser->completion_quote_end = saved_completion_quote_end;
1045 parser->completion_word = saved_completion_word;
1046 return next;
1049 /* Helper functions. */
1051 /* Add SAL to SALS, and also update SELF->CANONICAL_NAMES to reflect
1052 the new sal, if needed. If not NULL, SYMNAME is the name of the
1053 symbol to use when constructing the new canonical name.
1055 If LITERAL_CANONICAL is non-zero, SYMNAME will be used as the
1056 canonical name for the SAL. */
1058 static void
1059 add_sal_to_sals (struct linespec_state *self,
1060 std::vector<symtab_and_line> *sals,
1061 struct symtab_and_line *sal,
1062 const char *symname, int literal_canonical)
1064 sals->push_back (*sal);
1066 if (self->canonical)
1068 struct linespec_canonical_name *canonical;
1070 self->canonical_names = XRESIZEVEC (struct linespec_canonical_name,
1071 self->canonical_names,
1072 sals->size ());
1073 canonical = &self->canonical_names[sals->size () - 1];
1074 if (!literal_canonical && sal->symtab)
1076 symtab_to_fullname (sal->symtab);
1078 /* Note that the filter doesn't have to be a valid linespec
1079 input. We only apply the ":LINE" treatment to Ada for
1080 the time being. */
1081 if (symname != NULL && sal->line != 0
1082 && self->language->la_language == language_ada)
1083 canonical->suffix = xstrprintf ("%s:%d", symname,
1084 sal->line).release ();
1085 else if (symname != NULL)
1086 canonical->suffix = xstrdup (symname);
1087 else
1088 canonical->suffix = xstrprintf ("%d", sal->line).release ();
1089 canonical->symtab = sal->symtab;
1091 else
1093 if (symname != NULL)
1094 canonical->suffix = xstrdup (symname);
1095 else
1096 canonical->suffix = xstrdup ("<unknown>");
1097 canonical->symtab = NULL;
1102 /* A hash function for address_entry. */
1104 static hashval_t
1105 hash_address_entry (const void *p)
1107 const struct address_entry *aep = (const struct address_entry *) p;
1108 hashval_t hash;
1110 hash = iterative_hash_object (aep->pspace, 0);
1111 return iterative_hash_object (aep->addr, hash);
1114 /* An equality function for address_entry. */
1116 static int
1117 eq_address_entry (const void *a, const void *b)
1119 const struct address_entry *aea = (const struct address_entry *) a;
1120 const struct address_entry *aeb = (const struct address_entry *) b;
1122 return aea->pspace == aeb->pspace && aea->addr == aeb->addr;
1125 /* Check whether the address, represented by PSPACE and ADDR, is
1126 already in the set. If so, return 0. Otherwise, add it and return
1127 1. */
1129 static int
1130 maybe_add_address (htab_t set, struct program_space *pspace, CORE_ADDR addr)
1132 struct address_entry e, *p;
1133 void **slot;
1135 e.pspace = pspace;
1136 e.addr = addr;
1137 slot = htab_find_slot (set, &e, INSERT);
1138 if (*slot)
1139 return 0;
1141 p = XNEW (struct address_entry);
1142 memcpy (p, &e, sizeof (struct address_entry));
1143 *slot = p;
1145 return 1;
1148 /* A helper that walks over all matching symtabs in all objfiles and
1149 calls CALLBACK for each symbol matching NAME. If SEARCH_PSPACE is
1150 not NULL, then the search is restricted to just that program
1151 space. If INCLUDE_INLINE is true then symbols representing
1152 inlined instances of functions will be included in the result. */
1154 static void
1155 iterate_over_all_matching_symtabs
1156 (struct linespec_state *state,
1157 const lookup_name_info &lookup_name,
1158 const domain_enum name_domain,
1159 enum search_domain search_domain,
1160 struct program_space *search_pspace, bool include_inline,
1161 gdb::function_view<symbol_found_callback_ftype> callback)
1163 for (struct program_space *pspace : program_spaces)
1165 if (search_pspace != NULL && search_pspace != pspace)
1166 continue;
1167 if (pspace->executing_startup)
1168 continue;
1170 set_current_program_space (pspace);
1172 for (objfile *objfile : current_program_space->objfiles ())
1174 objfile->expand_symtabs_matching (NULL, &lookup_name, NULL, NULL,
1175 (SEARCH_GLOBAL_BLOCK
1176 | SEARCH_STATIC_BLOCK),
1177 UNDEF_DOMAIN,
1178 search_domain);
1180 for (compunit_symtab *cu : objfile->compunits ())
1182 struct symtab *symtab = COMPUNIT_FILETABS (cu);
1184 iterate_over_file_blocks (symtab, lookup_name, name_domain,
1185 callback);
1187 if (include_inline)
1189 const struct block *block;
1190 int i;
1192 for (i = FIRST_LOCAL_BLOCK;
1193 i < BLOCKVECTOR_NBLOCKS (SYMTAB_BLOCKVECTOR (symtab));
1194 i++)
1196 block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symtab), i);
1197 state->language->iterate_over_symbols
1198 (block, lookup_name, name_domain,
1199 [&] (block_symbol *bsym)
1201 /* Restrict calls to CALLBACK to symbols
1202 representing inline symbols only. */
1203 if (SYMBOL_INLINED (bsym->symbol))
1204 return callback (bsym);
1205 return true;
1214 /* Returns the block to be used for symbol searches from
1215 the current location. */
1217 static const struct block *
1218 get_current_search_block (void)
1220 /* get_selected_block can change the current language when there is
1221 no selected frame yet. */
1222 scoped_restore_current_language save_language;
1223 return get_selected_block (0);
1226 /* Iterate over static and global blocks. */
1228 static void
1229 iterate_over_file_blocks
1230 (struct symtab *symtab, const lookup_name_info &name,
1231 domain_enum domain, gdb::function_view<symbol_found_callback_ftype> callback)
1233 const struct block *block;
1235 for (block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (symtab), STATIC_BLOCK);
1236 block != NULL;
1237 block = BLOCK_SUPERBLOCK (block))
1238 current_language->iterate_over_symbols (block, name, domain, callback);
1241 /* A helper for find_method. This finds all methods in type T of
1242 language T_LANG which match NAME. It adds matching symbol names to
1243 RESULT_NAMES, and adds T's direct superclasses to SUPERCLASSES. */
1245 static void
1246 find_methods (struct type *t, enum language t_lang, const char *name,
1247 std::vector<const char *> *result_names,
1248 std::vector<struct type *> *superclasses)
1250 int ibase;
1251 const char *class_name = t->name ();
1253 /* Ignore this class if it doesn't have a name. This is ugly, but
1254 unless we figure out how to get the physname without the name of
1255 the class, then the loop can't do any good. */
1256 if (class_name)
1258 int method_counter;
1259 lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
1260 symbol_name_matcher_ftype *symbol_name_compare
1261 = language_def (t_lang)->get_symbol_name_matcher (lookup_name);
1263 t = check_typedef (t);
1265 /* Loop over each method name. At this level, all overloads of a name
1266 are counted as a single name. There is an inner loop which loops over
1267 each overload. */
1269 for (method_counter = TYPE_NFN_FIELDS (t) - 1;
1270 method_counter >= 0;
1271 --method_counter)
1273 const char *method_name = TYPE_FN_FIELDLIST_NAME (t, method_counter);
1275 if (symbol_name_compare (method_name, lookup_name, NULL))
1277 int field_counter;
1279 for (field_counter = (TYPE_FN_FIELDLIST_LENGTH (t, method_counter)
1280 - 1);
1281 field_counter >= 0;
1282 --field_counter)
1284 struct fn_field *f;
1285 const char *phys_name;
1287 f = TYPE_FN_FIELDLIST1 (t, method_counter);
1288 if (TYPE_FN_FIELD_STUB (f, field_counter))
1289 continue;
1290 phys_name = TYPE_FN_FIELD_PHYSNAME (f, field_counter);
1291 result_names->push_back (phys_name);
1297 for (ibase = 0; ibase < TYPE_N_BASECLASSES (t); ibase++)
1298 superclasses->push_back (TYPE_BASECLASS (t, ibase));
1301 /* Find an instance of the character C in the string S that is outside
1302 of all parenthesis pairs, single-quoted strings, and double-quoted
1303 strings. Also, ignore the char within a template name, like a ','
1304 within foo<int, int>, while considering C++ operator</operator<<. */
1306 const char *
1307 find_toplevel_char (const char *s, char c)
1309 int quoted = 0; /* zero if we're not in quotes;
1310 '"' if we're in a double-quoted string;
1311 '\'' if we're in a single-quoted string. */
1312 int depth = 0; /* Number of unclosed parens we've seen. */
1313 const char *scan;
1315 for (scan = s; *scan; scan++)
1317 if (quoted)
1319 if (*scan == quoted)
1320 quoted = 0;
1321 else if (*scan == '\\' && *(scan + 1))
1322 scan++;
1324 else if (*scan == c && ! quoted && depth == 0)
1325 return scan;
1326 else if (*scan == '"' || *scan == '\'')
1327 quoted = *scan;
1328 else if (*scan == '(' || *scan == '<')
1329 depth++;
1330 else if ((*scan == ')' || *scan == '>') && depth > 0)
1331 depth--;
1332 else if (*scan == 'o' && !quoted && depth == 0)
1334 /* Handle C++ operator names. */
1335 if (strncmp (scan, CP_OPERATOR_STR, CP_OPERATOR_LEN) == 0)
1337 scan += CP_OPERATOR_LEN;
1338 if (*scan == c)
1339 return scan;
1340 while (isspace (*scan))
1342 ++scan;
1343 if (*scan == c)
1344 return scan;
1346 if (*scan == '\0')
1347 break;
1349 switch (*scan)
1351 /* Skip over one less than the appropriate number of
1352 characters: the for loop will skip over the last
1353 one. */
1354 case '<':
1355 if (scan[1] == '<')
1357 scan++;
1358 if (*scan == c)
1359 return scan;
1361 break;
1362 case '>':
1363 if (scan[1] == '>')
1365 scan++;
1366 if (*scan == c)
1367 return scan;
1369 break;
1375 return 0;
1378 /* The string equivalent of find_toplevel_char. Returns a pointer
1379 to the location of NEEDLE in HAYSTACK, ignoring any occurrences
1380 inside "()" and "<>". Returns NULL if NEEDLE was not found. */
1382 static const char *
1383 find_toplevel_string (const char *haystack, const char *needle)
1385 const char *s = haystack;
1389 s = find_toplevel_char (s, *needle);
1391 if (s != NULL)
1393 /* Found first char in HAYSTACK; check rest of string. */
1394 if (startswith (s, needle))
1395 return s;
1397 /* Didn't find it; loop over HAYSTACK, looking for the next
1398 instance of the first character of NEEDLE. */
1399 ++s;
1402 while (s != NULL && *s != '\0');
1404 /* NEEDLE was not found in HAYSTACK. */
1405 return NULL;
1408 /* Convert CANONICAL to its string representation using
1409 symtab_to_fullname for SYMTAB. */
1411 static std::string
1412 canonical_to_fullform (const struct linespec_canonical_name *canonical)
1414 if (canonical->symtab == NULL)
1415 return canonical->suffix;
1416 else
1417 return string_printf ("%s:%s", symtab_to_fullname (canonical->symtab),
1418 canonical->suffix);
1421 /* Given FILTERS, a list of canonical names, filter the sals in RESULT
1422 and store the result in SELF->CANONICAL. */
1424 static void
1425 filter_results (struct linespec_state *self,
1426 std::vector<symtab_and_line> *result,
1427 const std::vector<const char *> &filters)
1429 for (const char *name : filters)
1431 linespec_sals lsal;
1433 for (size_t j = 0; j < result->size (); ++j)
1435 const struct linespec_canonical_name *canonical;
1437 canonical = &self->canonical_names[j];
1438 std::string fullform = canonical_to_fullform (canonical);
1440 if (name == fullform)
1441 lsal.sals.push_back ((*result)[j]);
1444 if (!lsal.sals.empty ())
1446 lsal.canonical = xstrdup (name);
1447 self->canonical->lsals.push_back (std::move (lsal));
1451 self->canonical->pre_expanded = 0;
1454 /* Store RESULT into SELF->CANONICAL. */
1456 static void
1457 convert_results_to_lsals (struct linespec_state *self,
1458 std::vector<symtab_and_line> *result)
1460 struct linespec_sals lsal;
1462 lsal.canonical = NULL;
1463 lsal.sals = std::move (*result);
1464 self->canonical->lsals.push_back (std::move (lsal));
1467 /* A structure that contains two string representations of a struct
1468 linespec_canonical_name:
1469 - one where the symtab's fullname is used;
1470 - one where the filename followed the "set filename-display"
1471 setting. */
1473 struct decode_line_2_item
1475 decode_line_2_item (std::string &&fullform_, std::string &&displayform_,
1476 bool selected_)
1477 : fullform (std::move (fullform_)),
1478 displayform (std::move (displayform_)),
1479 selected (selected_)
1483 /* The form using symtab_to_fullname. */
1484 std::string fullform;
1486 /* The form using symtab_to_filename_for_display. */
1487 std::string displayform;
1489 /* Field is initialized to zero and it is set to one if the user
1490 requested breakpoint for this entry. */
1491 unsigned int selected : 1;
1494 /* Helper for std::sort to sort decode_line_2_item entries by
1495 DISPLAYFORM and secondarily by FULLFORM. */
1497 static bool
1498 decode_line_2_compare_items (const decode_line_2_item &a,
1499 const decode_line_2_item &b)
1501 if (a.displayform != b.displayform)
1502 return a.displayform < b.displayform;
1503 return a.fullform < b.fullform;
1506 /* Handle multiple results in RESULT depending on SELECT_MODE. This
1507 will either return normally, throw an exception on multiple
1508 results, or present a menu to the user. On return, the SALS vector
1509 in SELF->CANONICAL is set up properly. */
1511 static void
1512 decode_line_2 (struct linespec_state *self,
1513 std::vector<symtab_and_line> *result,
1514 const char *select_mode)
1516 const char *args;
1517 const char *prompt;
1518 int i;
1519 std::vector<const char *> filters;
1520 std::vector<struct decode_line_2_item> items;
1522 gdb_assert (select_mode != multiple_symbols_all);
1523 gdb_assert (self->canonical != NULL);
1524 gdb_assert (!result->empty ());
1526 /* Prepare ITEMS array. */
1527 for (i = 0; i < result->size (); ++i)
1529 const struct linespec_canonical_name *canonical;
1530 std::string displayform;
1532 canonical = &self->canonical_names[i];
1533 gdb_assert (canonical->suffix != NULL);
1535 std::string fullform = canonical_to_fullform (canonical);
1537 if (canonical->symtab == NULL)
1538 displayform = canonical->suffix;
1539 else
1541 const char *fn_for_display;
1543 fn_for_display = symtab_to_filename_for_display (canonical->symtab);
1544 displayform = string_printf ("%s:%s", fn_for_display,
1545 canonical->suffix);
1548 items.emplace_back (std::move (fullform), std::move (displayform),
1549 false);
1552 /* Sort the list of method names. */
1553 std::sort (items.begin (), items.end (), decode_line_2_compare_items);
1555 /* Remove entries with the same FULLFORM. */
1556 items.erase (std::unique (items.begin (), items.end (),
1557 [] (const struct decode_line_2_item &a,
1558 const struct decode_line_2_item &b)
1560 return a.fullform == b.fullform;
1562 items.end ());
1564 if (select_mode == multiple_symbols_cancel && items.size () > 1)
1565 error (_("canceled because the command is ambiguous\n"
1566 "See set/show multiple-symbol."));
1568 if (select_mode == multiple_symbols_all || items.size () == 1)
1570 convert_results_to_lsals (self, result);
1571 return;
1574 printf_unfiltered (_("[0] cancel\n[1] all\n"));
1575 for (i = 0; i < items.size (); i++)
1576 printf_unfiltered ("[%d] %s\n", i + 2, items[i].displayform.c_str ());
1578 prompt = getenv ("PS2");
1579 if (prompt == NULL)
1581 prompt = "> ";
1583 args = command_line_input (prompt, "overload-choice");
1585 if (args == 0 || *args == 0)
1586 error_no_arg (_("one or more choice numbers"));
1588 number_or_range_parser parser (args);
1589 while (!parser.finished ())
1591 int num = parser.get_number ();
1593 if (num == 0)
1594 error (_("canceled"));
1595 else if (num == 1)
1597 /* We intentionally make this result in a single breakpoint,
1598 contrary to what older versions of gdb did. The
1599 rationale is that this lets a user get the
1600 multiple_symbols_all behavior even with the 'ask'
1601 setting; and he can get separate breakpoints by entering
1602 "2-57" at the query. */
1603 convert_results_to_lsals (self, result);
1604 return;
1607 num -= 2;
1608 if (num >= items.size ())
1609 printf_unfiltered (_("No choice number %d.\n"), num);
1610 else
1612 struct decode_line_2_item *item = &items[num];
1614 if (!item->selected)
1616 filters.push_back (item->fullform.c_str ());
1617 item->selected = 1;
1619 else
1621 printf_unfiltered (_("duplicate request for %d ignored.\n"),
1622 num + 2);
1627 filter_results (self, result, filters);
1632 /* The parser of linespec itself. */
1634 /* Throw an appropriate error when SYMBOL is not found (optionally in
1635 FILENAME). */
1637 static void ATTRIBUTE_NORETURN
1638 symbol_not_found_error (const char *symbol, const char *filename)
1640 if (symbol == NULL)
1641 symbol = "";
1643 if (!have_full_symbols ()
1644 && !have_partial_symbols ()
1645 && !have_minimal_symbols ())
1646 throw_error (NOT_FOUND_ERROR,
1647 _("No symbol table is loaded. Use the \"file\" command."));
1649 /* If SYMBOL starts with '$', the user attempted to either lookup
1650 a function/variable in his code starting with '$' or an internal
1651 variable of that name. Since we do not know which, be concise and
1652 explain both possibilities. */
1653 if (*symbol == '$')
1655 if (filename)
1656 throw_error (NOT_FOUND_ERROR,
1657 _("Undefined convenience variable or function \"%s\" "
1658 "not defined in \"%s\"."), symbol, filename);
1659 else
1660 throw_error (NOT_FOUND_ERROR,
1661 _("Undefined convenience variable or function \"%s\" "
1662 "not defined."), symbol);
1664 else
1666 if (filename)
1667 throw_error (NOT_FOUND_ERROR,
1668 _("Function \"%s\" not defined in \"%s\"."),
1669 symbol, filename);
1670 else
1671 throw_error (NOT_FOUND_ERROR,
1672 _("Function \"%s\" not defined."), symbol);
1676 /* Throw an appropriate error when an unexpected token is encountered
1677 in the input. */
1679 static void ATTRIBUTE_NORETURN
1680 unexpected_linespec_error (linespec_parser *parser)
1682 linespec_token token;
1683 static const char * token_type_strings[]
1684 = {"keyword", "colon", "string", "number", "comma", "end of input"};
1686 /* Get the token that generated the error. */
1687 token = linespec_lexer_lex_one (parser);
1689 /* Finally, throw the error. */
1690 if (token.type == LSTOKEN_STRING || token.type == LSTOKEN_NUMBER
1691 || token.type == LSTOKEN_KEYWORD)
1693 gdb::unique_xmalloc_ptr<char> string = copy_token_string (token);
1694 throw_error (GENERIC_ERROR,
1695 _("malformed linespec error: unexpected %s, \"%s\""),
1696 token_type_strings[token.type], string.get ());
1698 else
1699 throw_error (GENERIC_ERROR,
1700 _("malformed linespec error: unexpected %s"),
1701 token_type_strings[token.type]);
1704 /* Throw an undefined label error. */
1706 static void ATTRIBUTE_NORETURN
1707 undefined_label_error (const char *function, const char *label)
1709 if (function != NULL)
1710 throw_error (NOT_FOUND_ERROR,
1711 _("No label \"%s\" defined in function \"%s\"."),
1712 label, function);
1713 else
1714 throw_error (NOT_FOUND_ERROR,
1715 _("No label \"%s\" defined in current function."),
1716 label);
1719 /* Throw a source file not found error. */
1721 static void ATTRIBUTE_NORETURN
1722 source_file_not_found_error (const char *name)
1724 throw_error (NOT_FOUND_ERROR, _("No source file named %s."), name);
1727 /* Unless at EIO, save the current stream position as completion word
1728 point, and consume the next token. */
1730 static linespec_token
1731 save_stream_and_consume_token (linespec_parser *parser)
1733 if (linespec_lexer_peek_token (parser).type != LSTOKEN_EOI)
1734 parser->completion_word = PARSER_STREAM (parser);
1735 return linespec_lexer_consume_token (parser);
1738 /* See description in linespec.h. */
1740 struct line_offset
1741 linespec_parse_line_offset (const char *string)
1743 const char *start = string;
1744 struct line_offset line_offset = {0, LINE_OFFSET_NONE};
1746 if (*string == '+')
1748 line_offset.sign = LINE_OFFSET_PLUS;
1749 ++string;
1751 else if (*string == '-')
1753 line_offset.sign = LINE_OFFSET_MINUS;
1754 ++string;
1757 if (*string != '\0' && !isdigit (*string))
1758 error (_("malformed line offset: \"%s\""), start);
1760 /* Right now, we only allow base 10 for offsets. */
1761 line_offset.offset = atoi (string);
1762 return line_offset;
1765 /* In completion mode, if the user is still typing the number, there's
1766 no possible completion to offer. But if there's already input past
1767 the number, setup to expect NEXT. */
1769 static void
1770 set_completion_after_number (linespec_parser *parser,
1771 linespec_complete_what next)
1773 if (*PARSER_STREAM (parser) == ' ')
1775 parser->completion_word = skip_spaces (PARSER_STREAM (parser) + 1);
1776 parser->complete_what = next;
1778 else
1780 parser->completion_word = PARSER_STREAM (parser);
1781 parser->complete_what = linespec_complete_what::NOTHING;
1785 /* Parse the basic_spec in PARSER's input. */
1787 static void
1788 linespec_parse_basic (linespec_parser *parser)
1790 gdb::unique_xmalloc_ptr<char> name;
1791 linespec_token token;
1793 /* Get the next token. */
1794 token = linespec_lexer_lex_one (parser);
1796 /* If it is EOI or KEYWORD, issue an error. */
1797 if (token.type == LSTOKEN_KEYWORD)
1799 parser->complete_what = linespec_complete_what::NOTHING;
1800 unexpected_linespec_error (parser);
1802 else if (token.type == LSTOKEN_EOI)
1804 unexpected_linespec_error (parser);
1806 /* If it is a LSTOKEN_NUMBER, we have an offset. */
1807 else if (token.type == LSTOKEN_NUMBER)
1809 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1811 /* Record the line offset and get the next token. */
1812 name = copy_token_string (token);
1813 PARSER_EXPLICIT (parser)->line_offset
1814 = linespec_parse_line_offset (name.get ());
1816 /* Get the next token. */
1817 token = linespec_lexer_consume_token (parser);
1819 /* If the next token is a comma, stop parsing and return. */
1820 if (token.type == LSTOKEN_COMMA)
1822 parser->complete_what = linespec_complete_what::NOTHING;
1823 return;
1826 /* If the next token is anything but EOI or KEYWORD, issue
1827 an error. */
1828 if (token.type != LSTOKEN_KEYWORD && token.type != LSTOKEN_EOI)
1829 unexpected_linespec_error (parser);
1832 if (token.type == LSTOKEN_KEYWORD || token.type == LSTOKEN_EOI)
1833 return;
1835 /* Next token must be LSTOKEN_STRING. */
1836 if (token.type != LSTOKEN_STRING)
1838 parser->complete_what = linespec_complete_what::NOTHING;
1839 unexpected_linespec_error (parser);
1842 /* The current token will contain the name of a function, method,
1843 or label. */
1844 name = copy_token_string (token);
1846 if (parser->completion_tracker != NULL)
1848 /* If the function name ends with a ":", then this may be an
1849 incomplete "::" scope operator instead of a label separator.
1850 E.g.,
1851 "b klass:<tab>"
1852 which should expand to:
1853 "b klass::method()"
1855 Do a tentative completion assuming the later. If we find
1856 completions, advance the stream past the colon token and make
1857 it part of the function name/token. */
1859 if (!parser->completion_quote_char
1860 && strcmp (PARSER_STREAM (parser), ":") == 0)
1862 completion_tracker tmp_tracker;
1863 const char *source_filename
1864 = PARSER_EXPLICIT (parser)->source_filename;
1865 symbol_name_match_type match_type
1866 = PARSER_EXPLICIT (parser)->func_name_match_type;
1868 linespec_complete_function (tmp_tracker,
1869 parser->completion_word,
1870 match_type,
1871 source_filename);
1873 if (tmp_tracker.have_completions ())
1875 PARSER_STREAM (parser)++;
1876 LS_TOKEN_STOKEN (token).length++;
1878 name.reset (savestring (parser->completion_word,
1879 (PARSER_STREAM (parser)
1880 - parser->completion_word)));
1884 PARSER_EXPLICIT (parser)->function_name = name.release ();
1886 else
1888 std::vector<block_symbol> symbols;
1889 std::vector<bound_minimal_symbol> minimal_symbols;
1891 /* Try looking it up as a function/method. */
1892 find_linespec_symbols (PARSER_STATE (parser),
1893 PARSER_RESULT (parser)->file_symtabs, name.get (),
1894 PARSER_EXPLICIT (parser)->func_name_match_type,
1895 &symbols, &minimal_symbols);
1897 if (!symbols.empty () || !minimal_symbols.empty ())
1899 PARSER_RESULT (parser)->function_symbols = std::move (symbols);
1900 PARSER_RESULT (parser)->minimal_symbols = std::move (minimal_symbols);
1901 PARSER_EXPLICIT (parser)->function_name = name.release ();
1903 else
1905 /* NAME was not a function or a method. So it must be a label
1906 name or user specified variable like "break foo.c:$zippo". */
1907 std::vector<block_symbol> labels
1908 = find_label_symbols (PARSER_STATE (parser), {}, &symbols,
1909 name.get ());
1911 if (!labels.empty ())
1913 PARSER_RESULT (parser)->labels.label_symbols = std::move (labels);
1914 PARSER_RESULT (parser)->labels.function_symbols
1915 = std::move (symbols);
1916 PARSER_EXPLICIT (parser)->label_name = name.release ();
1918 else if (token.type == LSTOKEN_STRING
1919 && *LS_TOKEN_STOKEN (token).ptr == '$')
1921 /* User specified a convenience variable or history value. */
1922 PARSER_EXPLICIT (parser)->line_offset
1923 = linespec_parse_variable (PARSER_STATE (parser), name.get ());
1925 if (PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN)
1927 /* The user-specified variable was not valid. Do not
1928 throw an error here. parse_linespec will do it for us. */
1929 PARSER_EXPLICIT (parser)->function_name = name.release ();
1930 return;
1933 else
1935 /* The name is also not a label. Abort parsing. Do not throw
1936 an error here. parse_linespec will do it for us. */
1938 /* Save a copy of the name we were trying to lookup. */
1939 PARSER_EXPLICIT (parser)->function_name = name.release ();
1940 return;
1945 int previous_qc = parser->completion_quote_char;
1947 /* Get the next token. */
1948 token = linespec_lexer_consume_token (parser);
1950 if (token.type == LSTOKEN_EOI)
1952 if (previous_qc && !parser->completion_quote_char)
1953 parser->complete_what = linespec_complete_what::KEYWORD;
1955 else if (token.type == LSTOKEN_COLON)
1957 /* User specified a label or a lineno. */
1958 token = linespec_lexer_consume_token (parser);
1960 if (token.type == LSTOKEN_NUMBER)
1962 /* User specified an offset. Record the line offset and
1963 get the next token. */
1964 set_completion_after_number (parser, linespec_complete_what::KEYWORD);
1966 name = copy_token_string (token);
1967 PARSER_EXPLICIT (parser)->line_offset
1968 = linespec_parse_line_offset (name.get ());
1970 /* Get the next token. */
1971 token = linespec_lexer_consume_token (parser);
1973 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
1975 parser->complete_what = linespec_complete_what::LABEL;
1977 else if (token.type == LSTOKEN_STRING)
1979 parser->complete_what = linespec_complete_what::LABEL;
1981 /* If we have text after the label separated by whitespace
1982 (e.g., "b func():lab i<tab>"), don't consider it part of
1983 the label. In completion mode that should complete to
1984 "if", in normal mode, the 'i' should be treated as
1985 garbage. */
1986 if (parser->completion_quote_char == '\0')
1988 const char *ptr = LS_TOKEN_STOKEN (token).ptr;
1989 for (size_t i = 0; i < LS_TOKEN_STOKEN (token).length; i++)
1991 if (ptr[i] == ' ')
1993 LS_TOKEN_STOKEN (token).length = i;
1994 PARSER_STREAM (parser) = skip_spaces (ptr + i + 1);
1995 break;
2000 if (parser->completion_tracker != NULL)
2002 if (PARSER_STREAM (parser)[-1] == ' ')
2004 parser->completion_word = PARSER_STREAM (parser);
2005 parser->complete_what = linespec_complete_what::KEYWORD;
2008 else
2010 std::vector<block_symbol> symbols;
2012 /* Grab a copy of the label's name and look it up. */
2013 name = copy_token_string (token);
2014 std::vector<block_symbol> labels
2015 = find_label_symbols (PARSER_STATE (parser),
2016 PARSER_RESULT (parser)->function_symbols,
2017 &symbols, name.get ());
2019 if (!labels.empty ())
2021 PARSER_RESULT (parser)->labels.label_symbols
2022 = std::move (labels);
2023 PARSER_RESULT (parser)->labels.function_symbols
2024 = std::move (symbols);
2025 PARSER_EXPLICIT (parser)->label_name = name.release ();
2027 else
2029 /* We don't know what it was, but it isn't a label. */
2030 undefined_label_error
2031 (PARSER_EXPLICIT (parser)->function_name, name.get ());
2036 /* Check for a line offset. */
2037 token = save_stream_and_consume_token (parser);
2038 if (token.type == LSTOKEN_COLON)
2040 /* Get the next token. */
2041 token = linespec_lexer_consume_token (parser);
2043 /* It must be a line offset. */
2044 if (token.type != LSTOKEN_NUMBER)
2045 unexpected_linespec_error (parser);
2047 /* Record the line offset and get the next token. */
2048 name = copy_token_string (token);
2050 PARSER_EXPLICIT (parser)->line_offset
2051 = linespec_parse_line_offset (name.get ());
2053 /* Get the next token. */
2054 token = linespec_lexer_consume_token (parser);
2057 else
2059 /* Trailing ':' in the input. Issue an error. */
2060 unexpected_linespec_error (parser);
2065 /* Canonicalize the linespec contained in LS. The result is saved into
2066 STATE->canonical. This function handles both linespec and explicit
2067 locations. */
2069 static void
2070 canonicalize_linespec (struct linespec_state *state, const linespec *ls)
2072 struct event_location *canon;
2073 struct explicit_location *explicit_loc;
2075 /* If canonicalization was not requested, no need to do anything. */
2076 if (!state->canonical)
2077 return;
2079 /* Save everything as an explicit location. */
2080 state->canonical->location
2081 = new_explicit_location (&ls->explicit_loc);
2082 canon = state->canonical->location.get ();
2083 explicit_loc = get_explicit_location (canon);
2085 if (explicit_loc->label_name != NULL)
2087 state->canonical->special_display = 1;
2089 if (explicit_loc->function_name == NULL)
2091 /* No function was specified, so add the symbol name. */
2092 gdb_assert (ls->labels.function_symbols.size () == 1);
2093 block_symbol s = ls->labels.function_symbols.front ();
2094 explicit_loc->function_name = xstrdup (s.symbol->natural_name ());
2098 /* If this location originally came from a linespec, save a string
2099 representation of it for display and saving to file. */
2100 if (state->is_linespec)
2102 char *linespec = explicit_location_to_linespec (explicit_loc);
2104 set_event_location_string (canon, linespec);
2105 xfree (linespec);
2109 /* Given a line offset in LS, construct the relevant SALs. */
2111 static std::vector<symtab_and_line>
2112 create_sals_line_offset (struct linespec_state *self,
2113 linespec *ls)
2115 int use_default = 0;
2117 /* This is where we need to make sure we have good defaults.
2118 We must guarantee that this section of code is never executed
2119 when we are called with just a function name, since
2120 set_default_source_symtab_and_line uses
2121 select_source_symtab that calls us with such an argument. */
2123 if (ls->file_symtabs.size () == 1
2124 && ls->file_symtabs.front () == nullptr)
2126 set_current_program_space (self->program_space);
2128 /* Make sure we have at least a default source line. */
2129 set_default_source_symtab_and_line ();
2130 initialize_defaults (&self->default_symtab, &self->default_line);
2131 ls->file_symtabs
2132 = collect_symtabs_from_filename (self->default_symtab->filename,
2133 self->search_pspace);
2134 use_default = 1;
2137 symtab_and_line val;
2138 val.line = ls->explicit_loc.line_offset.offset;
2139 switch (ls->explicit_loc.line_offset.sign)
2141 case LINE_OFFSET_PLUS:
2142 if (ls->explicit_loc.line_offset.offset == 0)
2143 val.line = 5;
2144 if (use_default)
2145 val.line = self->default_line + val.line;
2146 break;
2148 case LINE_OFFSET_MINUS:
2149 if (ls->explicit_loc.line_offset.offset == 0)
2150 val.line = 15;
2151 if (use_default)
2152 val.line = self->default_line - val.line;
2153 else
2154 val.line = -val.line;
2155 break;
2157 case LINE_OFFSET_NONE:
2158 break; /* No need to adjust val.line. */
2161 std::vector<symtab_and_line> values;
2162 if (self->list_mode)
2163 values = decode_digits_list_mode (self, ls, val);
2164 else
2166 struct linetable_entry *best_entry = NULL;
2167 int i, j;
2169 std::vector<symtab_and_line> intermediate_results
2170 = decode_digits_ordinary (self, ls, val.line, &best_entry);
2171 if (intermediate_results.empty () && best_entry != NULL)
2172 intermediate_results = decode_digits_ordinary (self, ls,
2173 best_entry->line,
2174 &best_entry);
2176 /* For optimized code, the compiler can scatter one source line
2177 across disjoint ranges of PC values, even when no duplicate
2178 functions or inline functions are involved. For example,
2179 'for (;;)' inside a non-template, non-inline, and non-ctor-or-dtor
2180 function can result in two PC ranges. In this case, we don't
2181 want to set a breakpoint on the first PC of each range. To filter
2182 such cases, we use containing blocks -- for each PC found
2183 above, we see if there are other PCs that are in the same
2184 block. If yes, the other PCs are filtered out. */
2186 gdb::def_vector<int> filter (intermediate_results.size ());
2187 gdb::def_vector<const block *> blocks (intermediate_results.size ());
2189 for (i = 0; i < intermediate_results.size (); ++i)
2191 set_current_program_space (intermediate_results[i].pspace);
2193 filter[i] = 1;
2194 blocks[i] = block_for_pc_sect (intermediate_results[i].pc,
2195 intermediate_results[i].section);
2198 for (i = 0; i < intermediate_results.size (); ++i)
2200 if (blocks[i] != NULL)
2201 for (j = i + 1; j < intermediate_results.size (); ++j)
2203 if (blocks[j] == blocks[i])
2205 filter[j] = 0;
2206 break;
2211 for (i = 0; i < intermediate_results.size (); ++i)
2212 if (filter[i])
2214 struct symbol *sym = (blocks[i]
2215 ? block_containing_function (blocks[i])
2216 : NULL);
2218 if (self->funfirstline)
2219 skip_prologue_sal (&intermediate_results[i]);
2220 intermediate_results[i].symbol = sym;
2221 add_sal_to_sals (self, &values, &intermediate_results[i],
2222 sym ? sym->natural_name () : NULL, 0);
2226 if (values.empty ())
2228 if (ls->explicit_loc.source_filename)
2229 throw_error (NOT_FOUND_ERROR, _("No line %d in file \"%s\"."),
2230 val.line, ls->explicit_loc.source_filename);
2231 else
2232 throw_error (NOT_FOUND_ERROR, _("No line %d in the current file."),
2233 val.line);
2236 return values;
2239 /* Convert the given ADDRESS into SaLs. */
2241 static std::vector<symtab_and_line>
2242 convert_address_location_to_sals (struct linespec_state *self,
2243 CORE_ADDR address)
2245 symtab_and_line sal = find_pc_line (address, 0);
2246 sal.pc = address;
2247 sal.section = find_pc_overlay (address);
2248 sal.explicit_pc = 1;
2249 sal.symbol = find_pc_sect_containing_function (sal.pc, sal.section);
2251 std::vector<symtab_and_line> sals;
2252 add_sal_to_sals (self, &sals, &sal, core_addr_to_string (address), 1);
2254 return sals;
2257 /* Create and return SALs from the linespec LS. */
2259 static std::vector<symtab_and_line>
2260 convert_linespec_to_sals (struct linespec_state *state, linespec *ls)
2262 std::vector<symtab_and_line> sals;
2264 if (!ls->labels.label_symbols.empty ())
2266 /* We have just a bunch of functions/methods or labels. */
2267 struct symtab_and_line sal;
2269 for (const auto &sym : ls->labels.label_symbols)
2271 struct program_space *pspace
2272 = SYMTAB_PSPACE (symbol_symtab (sym.symbol));
2274 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2275 && maybe_add_address (state->addr_set, pspace, sal.pc))
2276 add_sal_to_sals (state, &sals, &sal,
2277 sym.symbol->natural_name (), 0);
2280 else if (!ls->function_symbols.empty () || !ls->minimal_symbols.empty ())
2282 /* We have just a bunch of functions and/or methods. */
2283 if (!ls->function_symbols.empty ())
2285 /* Sort symbols so that symbols with the same program space are next
2286 to each other. */
2287 std::sort (ls->function_symbols.begin (),
2288 ls->function_symbols.end (),
2289 compare_symbols);
2291 for (const auto &sym : ls->function_symbols)
2293 program_space *pspace
2294 = SYMTAB_PSPACE (symbol_symtab (sym.symbol));
2295 set_current_program_space (pspace);
2297 /* Don't skip to the first line of the function if we
2298 had found an ifunc minimal symbol for this function,
2299 because that means that this function is an ifunc
2300 resolver with the same name as the ifunc itself. */
2301 bool found_ifunc = false;
2303 if (state->funfirstline
2304 && !ls->minimal_symbols.empty ()
2305 && SYMBOL_CLASS (sym.symbol) == LOC_BLOCK)
2307 const CORE_ADDR addr
2308 = BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (sym.symbol));
2310 for (const auto &elem : ls->minimal_symbols)
2312 if (MSYMBOL_TYPE (elem.minsym) == mst_text_gnu_ifunc
2313 || MSYMBOL_TYPE (elem.minsym) == mst_data_gnu_ifunc)
2315 CORE_ADDR msym_addr = BMSYMBOL_VALUE_ADDRESS (elem);
2316 if (MSYMBOL_TYPE (elem.minsym) == mst_data_gnu_ifunc)
2318 struct gdbarch *gdbarch
2319 = elem.objfile->arch ();
2320 msym_addr
2321 = (gdbarch_convert_from_func_ptr_addr
2322 (gdbarch,
2323 msym_addr,
2324 current_inferior ()->top_target ()));
2327 if (msym_addr == addr)
2329 found_ifunc = true;
2330 break;
2336 if (!found_ifunc)
2338 symtab_and_line sal;
2339 if (symbol_to_sal (&sal, state->funfirstline, sym.symbol)
2340 && maybe_add_address (state->addr_set, pspace, sal.pc))
2341 add_sal_to_sals (state, &sals, &sal,
2342 sym.symbol->natural_name (), 0);
2347 if (!ls->minimal_symbols.empty ())
2349 /* Sort minimal symbols by program space, too */
2350 std::sort (ls->minimal_symbols.begin (),
2351 ls->minimal_symbols.end (),
2352 compare_msymbols);
2354 for (const auto &elem : ls->minimal_symbols)
2356 program_space *pspace = elem.objfile->pspace;
2357 set_current_program_space (pspace);
2358 minsym_found (state, elem.objfile, elem.minsym, &sals);
2362 else if (ls->explicit_loc.line_offset.sign != LINE_OFFSET_UNKNOWN)
2364 /* Only an offset was specified. */
2365 sals = create_sals_line_offset (state, ls);
2367 /* Make sure we have a filename for canonicalization. */
2368 if (ls->explicit_loc.source_filename == NULL)
2370 const char *fullname = symtab_to_fullname (state->default_symtab);
2372 /* It may be more appropriate to keep DEFAULT_SYMTAB in its symtab
2373 form so that displaying SOURCE_FILENAME can follow the current
2374 FILENAME_DISPLAY_STRING setting. But as it is used only rarely
2375 it has been kept for code simplicity only in absolute form. */
2376 ls->explicit_loc.source_filename = xstrdup (fullname);
2379 else
2381 /* We haven't found any results... */
2382 return sals;
2385 canonicalize_linespec (state, ls);
2387 if (!sals.empty () && state->canonical != NULL)
2388 state->canonical->pre_expanded = 1;
2390 return sals;
2393 /* Build RESULT from the explicit location components SOURCE_FILENAME,
2394 FUNCTION_NAME, LABEL_NAME and LINE_OFFSET. */
2396 static void
2397 convert_explicit_location_to_linespec (struct linespec_state *self,
2398 linespec *result,
2399 const char *source_filename,
2400 const char *function_name,
2401 symbol_name_match_type fname_match_type,
2402 const char *label_name,
2403 struct line_offset line_offset)
2405 std::vector<bound_minimal_symbol> minimal_symbols;
2407 result->explicit_loc.func_name_match_type = fname_match_type;
2409 if (source_filename != NULL)
2413 result->file_symtabs
2414 = symtabs_from_filename (source_filename, self->search_pspace);
2416 catch (const gdb_exception_error &except)
2418 source_file_not_found_error (source_filename);
2420 result->explicit_loc.source_filename = xstrdup (source_filename);
2422 else
2424 /* A NULL entry means to use the default symtab. */
2425 result->file_symtabs.push_back (nullptr);
2428 if (function_name != NULL)
2430 std::vector<block_symbol> symbols;
2432 find_linespec_symbols (self, result->file_symtabs,
2433 function_name, fname_match_type,
2434 &symbols, &minimal_symbols);
2436 if (symbols.empty () && minimal_symbols.empty ())
2437 symbol_not_found_error (function_name,
2438 result->explicit_loc.source_filename);
2440 result->explicit_loc.function_name = xstrdup (function_name);
2441 result->function_symbols = std::move (symbols);
2442 result->minimal_symbols = std::move (minimal_symbols);
2445 if (label_name != NULL)
2447 std::vector<block_symbol> symbols;
2448 std::vector<block_symbol> labels
2449 = find_label_symbols (self, result->function_symbols,
2450 &symbols, label_name);
2452 if (labels.empty ())
2453 undefined_label_error (result->explicit_loc.function_name,
2454 label_name);
2456 result->explicit_loc.label_name = xstrdup (label_name);
2457 result->labels.label_symbols = labels;
2458 result->labels.function_symbols = std::move (symbols);
2461 if (line_offset.sign != LINE_OFFSET_UNKNOWN)
2462 result->explicit_loc.line_offset = line_offset;
2465 /* Convert the explicit location EXPLICIT_LOC into SaLs. */
2467 static std::vector<symtab_and_line>
2468 convert_explicit_location_to_sals (struct linespec_state *self,
2469 linespec *result,
2470 const struct explicit_location *explicit_loc)
2472 convert_explicit_location_to_linespec (self, result,
2473 explicit_loc->source_filename,
2474 explicit_loc->function_name,
2475 explicit_loc->func_name_match_type,
2476 explicit_loc->label_name,
2477 explicit_loc->line_offset);
2478 return convert_linespec_to_sals (self, result);
2481 /* Parse a string that specifies a linespec.
2483 The basic grammar of linespecs:
2485 linespec -> var_spec | basic_spec
2486 var_spec -> '$' (STRING | NUMBER)
2488 basic_spec -> file_offset_spec | function_spec | label_spec
2489 file_offset_spec -> opt_file_spec offset_spec
2490 function_spec -> opt_file_spec function_name_spec opt_label_spec
2491 label_spec -> label_name_spec
2493 opt_file_spec -> "" | file_name_spec ':'
2494 opt_label_spec -> "" | ':' label_name_spec
2496 file_name_spec -> STRING
2497 function_name_spec -> STRING
2498 label_name_spec -> STRING
2499 function_name_spec -> STRING
2500 offset_spec -> NUMBER
2501 -> '+' NUMBER
2502 -> '-' NUMBER
2504 This may all be followed by several keywords such as "if EXPR",
2505 which we ignore.
2507 A comma will terminate parsing.
2509 The function may be an undebuggable function found in minimal symbol table.
2511 If the argument FUNFIRSTLINE is nonzero, we want the first line
2512 of real code inside a function when a function is specified, and it is
2513 not OK to specify a variable or type to get its line number.
2515 DEFAULT_SYMTAB specifies the file to use if none is specified.
2516 It defaults to current_source_symtab.
2517 DEFAULT_LINE specifies the line number to use for relative
2518 line numbers (that start with signs). Defaults to current_source_line.
2519 If CANONICAL is non-NULL, store an array of strings containing the canonical
2520 line specs there if necessary. Currently overloaded member functions and
2521 line numbers or static functions without a filename yield a canonical
2522 line spec. The array and the line spec strings are allocated on the heap,
2523 it is the callers responsibility to free them.
2525 Note that it is possible to return zero for the symtab
2526 if no file is validly specified. Callers must check that.
2527 Also, the line number returned may be invalid. */
2529 /* Parse the linespec in ARG. MATCH_TYPE indicates how function names
2530 should be matched. */
2532 static std::vector<symtab_and_line>
2533 parse_linespec (linespec_parser *parser, const char *arg,
2534 symbol_name_match_type match_type)
2536 linespec_token token;
2537 struct gdb_exception file_exception;
2539 /* A special case to start. It has become quite popular for
2540 IDEs to work around bugs in the previous parser by quoting
2541 the entire linespec, so we attempt to deal with this nicely. */
2542 parser->is_quote_enclosed = 0;
2543 if (parser->completion_tracker == NULL
2544 && !is_ada_operator (arg)
2545 && strchr (linespec_quote_characters, *arg) != NULL)
2547 const char *end;
2549 end = skip_quote_char (arg + 1, *arg);
2550 if (end != NULL && is_closing_quote_enclosed (end))
2552 /* Here's the special case. Skip ARG past the initial
2553 quote. */
2554 ++arg;
2555 parser->is_quote_enclosed = 1;
2559 parser->lexer.saved_arg = arg;
2560 parser->lexer.stream = arg;
2561 parser->completion_word = arg;
2562 parser->complete_what = linespec_complete_what::FUNCTION;
2563 PARSER_EXPLICIT (parser)->func_name_match_type = match_type;
2565 /* Initialize the default symtab and line offset. */
2566 initialize_defaults (&PARSER_STATE (parser)->default_symtab,
2567 &PARSER_STATE (parser)->default_line);
2569 /* Objective-C shortcut. */
2570 if (parser->completion_tracker == NULL)
2572 std::vector<symtab_and_line> values
2573 = decode_objc (PARSER_STATE (parser), PARSER_RESULT (parser), arg);
2574 if (!values.empty ())
2575 return values;
2577 else
2579 /* "-"/"+" is either an objc selector, or a number. There's
2580 nothing to complete the latter to, so just let the caller
2581 complete on functions, which finds objc selectors, if there's
2582 any. */
2583 if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '\0')
2584 return {};
2587 /* Start parsing. */
2589 /* Get the first token. */
2590 token = linespec_lexer_consume_token (parser);
2592 /* It must be either LSTOKEN_STRING or LSTOKEN_NUMBER. */
2593 if (token.type == LSTOKEN_STRING && *LS_TOKEN_STOKEN (token).ptr == '$')
2595 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2596 if (parser->completion_tracker == NULL)
2597 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2599 /* User specified a convenience variable or history value. */
2600 gdb::unique_xmalloc_ptr<char> var = copy_token_string (token);
2601 PARSER_EXPLICIT (parser)->line_offset
2602 = linespec_parse_variable (PARSER_STATE (parser), var.get ());
2604 /* If a line_offset wasn't found (VAR is the name of a user
2605 variable/function), then skip to normal symbol processing. */
2606 if (PARSER_EXPLICIT (parser)->line_offset.sign != LINE_OFFSET_UNKNOWN)
2608 /* Consume this token. */
2609 linespec_lexer_consume_token (parser);
2611 goto convert_to_sals;
2614 else if (token.type == LSTOKEN_EOI && parser->completion_tracker != NULL)
2616 /* Let the default linespec_complete_what::FUNCTION kick in. */
2617 unexpected_linespec_error (parser);
2619 else if (token.type != LSTOKEN_STRING && token.type != LSTOKEN_NUMBER)
2621 parser->complete_what = linespec_complete_what::NOTHING;
2622 unexpected_linespec_error (parser);
2625 /* Shortcut: If the next token is not LSTOKEN_COLON, we know that
2626 this token cannot represent a filename. */
2627 token = linespec_lexer_peek_token (parser);
2629 if (token.type == LSTOKEN_COLON)
2631 /* Get the current token again and extract the filename. */
2632 token = linespec_lexer_lex_one (parser);
2633 gdb::unique_xmalloc_ptr<char> user_filename = copy_token_string (token);
2635 /* Check if the input is a filename. */
2638 PARSER_RESULT (parser)->file_symtabs
2639 = symtabs_from_filename (user_filename.get (),
2640 PARSER_STATE (parser)->search_pspace);
2642 catch (gdb_exception_error &ex)
2644 file_exception = std::move (ex);
2647 if (file_exception.reason >= 0)
2649 /* Symtabs were found for the file. Record the filename. */
2650 PARSER_EXPLICIT (parser)->source_filename = user_filename.release ();
2652 /* Get the next token. */
2653 token = linespec_lexer_consume_token (parser);
2655 /* This is LSTOKEN_COLON; consume it. */
2656 linespec_lexer_consume_token (parser);
2658 else
2660 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2661 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2664 /* If the next token is not EOI, KEYWORD, or COMMA, issue an error. */
2665 else if (parser->completion_tracker == NULL
2666 && (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD
2667 && token.type != LSTOKEN_COMMA))
2669 /* TOKEN is the _next_ token, not the one currently in the parser.
2670 Consuming the token will give the correct error message. */
2671 linespec_lexer_consume_token (parser);
2672 unexpected_linespec_error (parser);
2674 else
2676 /* A NULL entry means to use GLOBAL_DEFAULT_SYMTAB. */
2677 PARSER_RESULT (parser)->file_symtabs.push_back (nullptr);
2680 /* Parse the rest of the linespec. */
2681 linespec_parse_basic (parser);
2683 if (parser->completion_tracker == NULL
2684 && PARSER_RESULT (parser)->function_symbols.empty ()
2685 && PARSER_RESULT (parser)->labels.label_symbols.empty ()
2686 && PARSER_EXPLICIT (parser)->line_offset.sign == LINE_OFFSET_UNKNOWN
2687 && PARSER_RESULT (parser)->minimal_symbols.empty ())
2689 /* The linespec didn't parse. Re-throw the file exception if
2690 there was one. */
2691 if (file_exception.reason < 0)
2692 throw_exception (std::move (file_exception));
2694 /* Otherwise, the symbol is not found. */
2695 symbol_not_found_error (PARSER_EXPLICIT (parser)->function_name,
2696 PARSER_EXPLICIT (parser)->source_filename);
2699 convert_to_sals:
2701 /* Get the last token and record how much of the input was parsed,
2702 if necessary. */
2703 token = linespec_lexer_lex_one (parser);
2704 if (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD)
2705 unexpected_linespec_error (parser);
2706 else if (token.type == LSTOKEN_KEYWORD)
2708 /* Setup the completion word past the keyword. Lexing never
2709 advances past a keyword automatically, so skip it
2710 manually. */
2711 parser->completion_word
2712 = skip_spaces (skip_to_space (PARSER_STREAM (parser)));
2713 parser->complete_what = linespec_complete_what::EXPRESSION;
2716 /* Convert the data in PARSER_RESULT to SALs. */
2717 if (parser->completion_tracker == NULL)
2718 return convert_linespec_to_sals (PARSER_STATE (parser),
2719 PARSER_RESULT (parser));
2721 return {};
2725 /* A constructor for linespec_state. */
2727 static void
2728 linespec_state_constructor (struct linespec_state *self,
2729 int flags, const struct language_defn *language,
2730 struct program_space *search_pspace,
2731 struct symtab *default_symtab,
2732 int default_line,
2733 struct linespec_result *canonical)
2735 memset (self, 0, sizeof (*self));
2736 self->language = language;
2737 self->funfirstline = (flags & DECODE_LINE_FUNFIRSTLINE) ? 1 : 0;
2738 self->list_mode = (flags & DECODE_LINE_LIST_MODE) ? 1 : 0;
2739 self->search_pspace = search_pspace;
2740 self->default_symtab = default_symtab;
2741 self->default_line = default_line;
2742 self->canonical = canonical;
2743 self->program_space = current_program_space;
2744 self->addr_set = htab_create_alloc (10, hash_address_entry, eq_address_entry,
2745 xfree, xcalloc, xfree);
2746 self->is_linespec = 0;
2749 /* Initialize a new linespec parser. */
2751 linespec_parser::linespec_parser (int flags,
2752 const struct language_defn *language,
2753 struct program_space *search_pspace,
2754 struct symtab *default_symtab,
2755 int default_line,
2756 struct linespec_result *canonical)
2758 lexer.current.type = LSTOKEN_CONSUMED;
2759 PARSER_EXPLICIT (this)->func_name_match_type
2760 = symbol_name_match_type::WILD;
2761 PARSER_EXPLICIT (this)->line_offset.sign = LINE_OFFSET_UNKNOWN;
2762 linespec_state_constructor (PARSER_STATE (this), flags, language,
2763 search_pspace,
2764 default_symtab, default_line, canonical);
2767 /* A destructor for linespec_state. */
2769 static void
2770 linespec_state_destructor (struct linespec_state *self)
2772 htab_delete (self->addr_set);
2773 xfree (self->canonical_names);
2776 /* Delete a linespec parser. */
2778 linespec_parser::~linespec_parser ()
2780 xfree (PARSER_EXPLICIT (this)->source_filename);
2781 xfree (PARSER_EXPLICIT (this)->label_name);
2782 xfree (PARSER_EXPLICIT (this)->function_name);
2784 linespec_state_destructor (PARSER_STATE (this));
2787 /* See description in linespec.h. */
2789 void
2790 linespec_lex_to_end (const char **stringp)
2792 linespec_token token;
2793 const char *orig;
2795 if (stringp == NULL || *stringp == NULL)
2796 return;
2798 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2799 parser.lexer.saved_arg = *stringp;
2800 PARSER_STREAM (&parser) = orig = *stringp;
2804 /* Stop before any comma tokens; we need it to keep it
2805 as the next token in the string. */
2806 token = linespec_lexer_peek_token (&parser);
2807 if (token.type == LSTOKEN_COMMA)
2808 break;
2809 token = linespec_lexer_consume_token (&parser);
2811 while (token.type != LSTOKEN_EOI && token.type != LSTOKEN_KEYWORD);
2813 *stringp += PARSER_STREAM (&parser) - orig;
2816 /* See linespec.h. */
2818 void
2819 linespec_complete_function (completion_tracker &tracker,
2820 const char *function,
2821 symbol_name_match_type func_match_type,
2822 const char *source_filename)
2824 complete_symbol_mode mode = complete_symbol_mode::LINESPEC;
2826 if (source_filename != NULL)
2828 collect_file_symbol_completion_matches (tracker, mode, func_match_type,
2829 function, function, source_filename);
2831 else
2833 collect_symbol_completion_matches (tracker, mode, func_match_type,
2834 function, function);
2839 /* Helper for complete_linespec to simplify it. SOURCE_FILENAME is
2840 only meaningful if COMPONENT is FUNCTION. */
2842 static void
2843 complete_linespec_component (linespec_parser *parser,
2844 completion_tracker &tracker,
2845 const char *text,
2846 linespec_complete_what component,
2847 const char *source_filename)
2849 if (component == linespec_complete_what::KEYWORD)
2851 complete_on_enum (tracker, linespec_keywords, text, text);
2853 else if (component == linespec_complete_what::EXPRESSION)
2855 const char *word
2856 = advance_to_expression_complete_word_point (tracker, text);
2857 complete_expression (tracker, text, word);
2859 else if (component == linespec_complete_what::FUNCTION)
2861 completion_list fn_list;
2863 symbol_name_match_type match_type
2864 = PARSER_EXPLICIT (parser)->func_name_match_type;
2865 linespec_complete_function (tracker, text, match_type, source_filename);
2866 if (source_filename == NULL)
2868 /* Haven't seen a source component, like in "b
2869 file.c:function[TAB]". Maybe this wasn't a function, but
2870 a filename instead, like "b file.[TAB]". */
2871 fn_list = complete_source_filenames (text);
2874 /* If we only have a single filename completion, append a ':' for
2875 the user, since that's the only thing that can usefully follow
2876 the filename. */
2877 if (fn_list.size () == 1 && !tracker.have_completions ())
2879 char *fn = fn_list[0].release ();
2881 /* If we also need to append a quote char, it needs to be
2882 appended before the ':'. Append it now, and make ':' the
2883 new "quote" char. */
2884 if (tracker.quote_char ())
2886 char quote_char_str[2] = { (char) tracker.quote_char () };
2888 fn = reconcat (fn, fn, quote_char_str, (char *) NULL);
2889 tracker.set_quote_char (':');
2891 else
2892 fn = reconcat (fn, fn, ":", (char *) NULL);
2893 fn_list[0].reset (fn);
2895 /* Tell readline to skip appending a space. */
2896 tracker.set_suppress_append_ws (true);
2898 tracker.add_completions (std::move (fn_list));
2902 /* Helper for linespec_complete_label. Find labels that match
2903 LABEL_NAME in the function symbols listed in the PARSER, and add
2904 them to the tracker. */
2906 static void
2907 complete_label (completion_tracker &tracker,
2908 linespec_parser *parser,
2909 const char *label_name)
2911 std::vector<block_symbol> label_function_symbols;
2912 std::vector<block_symbol> labels
2913 = find_label_symbols (PARSER_STATE (parser),
2914 PARSER_RESULT (parser)->function_symbols,
2915 &label_function_symbols,
2916 label_name, true);
2918 for (const auto &label : labels)
2920 char *match = xstrdup (label.symbol->search_name ());
2921 tracker.add_completion (gdb::unique_xmalloc_ptr<char> (match));
2925 /* See linespec.h. */
2927 void
2928 linespec_complete_label (completion_tracker &tracker,
2929 const struct language_defn *language,
2930 const char *source_filename,
2931 const char *function_name,
2932 symbol_name_match_type func_name_match_type,
2933 const char *label_name)
2935 linespec_parser parser (0, language, NULL, NULL, 0, NULL);
2937 line_offset unknown_offset = { 0, LINE_OFFSET_UNKNOWN };
2941 convert_explicit_location_to_linespec (PARSER_STATE (&parser),
2942 PARSER_RESULT (&parser),
2943 source_filename,
2944 function_name,
2945 func_name_match_type,
2946 NULL, unknown_offset);
2948 catch (const gdb_exception_error &ex)
2950 return;
2953 complete_label (tracker, &parser, label_name);
2956 /* See description in linespec.h. */
2958 void
2959 linespec_complete (completion_tracker &tracker, const char *text,
2960 symbol_name_match_type match_type)
2962 const char *orig = text;
2964 linespec_parser parser (0, current_language, NULL, NULL, 0, NULL);
2965 parser.lexer.saved_arg = text;
2966 PARSER_EXPLICIT (&parser)->func_name_match_type = match_type;
2967 PARSER_STREAM (&parser) = text;
2969 parser.completion_tracker = &tracker;
2970 PARSER_STATE (&parser)->is_linespec = 1;
2972 /* Parse as much as possible. parser.completion_word will hold
2973 furthest completion point we managed to parse to. */
2976 parse_linespec (&parser, text, match_type);
2978 catch (const gdb_exception_error &except)
2982 if (parser.completion_quote_char != '\0'
2983 && parser.completion_quote_end != NULL
2984 && parser.completion_quote_end[1] == '\0')
2986 /* If completing a quoted string with the cursor right at
2987 terminating quote char, complete the completion word without
2988 interpretation, so that readline advances the cursor one
2989 whitespace past the quote, even if there's no match. This
2990 makes these cases behave the same:
2992 before: "b function()"
2993 after: "b function() "
2995 before: "b 'function()'"
2996 after: "b 'function()' "
2998 and trusts the user in this case:
3000 before: "b 'not_loaded_function_yet()'"
3001 after: "b 'not_loaded_function_yet()' "
3003 parser.complete_what = linespec_complete_what::NOTHING;
3004 parser.completion_quote_char = '\0';
3006 gdb::unique_xmalloc_ptr<char> text_copy
3007 (xstrdup (parser.completion_word));
3008 tracker.add_completion (std::move (text_copy));
3011 tracker.set_quote_char (parser.completion_quote_char);
3013 if (parser.complete_what == linespec_complete_what::LABEL)
3015 parser.complete_what = linespec_complete_what::NOTHING;
3017 const char *func_name = PARSER_EXPLICIT (&parser)->function_name;
3019 std::vector<block_symbol> function_symbols;
3020 std::vector<bound_minimal_symbol> minimal_symbols;
3021 find_linespec_symbols (PARSER_STATE (&parser),
3022 PARSER_RESULT (&parser)->file_symtabs,
3023 func_name, match_type,
3024 &function_symbols, &minimal_symbols);
3026 PARSER_RESULT (&parser)->function_symbols = std::move (function_symbols);
3027 PARSER_RESULT (&parser)->minimal_symbols = std::move (minimal_symbols);
3029 complete_label (tracker, &parser, parser.completion_word);
3031 else if (parser.complete_what == linespec_complete_what::FUNCTION)
3033 /* While parsing/lexing, we didn't know whether the completion
3034 word completes to a unique function/source name already or
3035 not.
3037 E.g.:
3038 "b function() <tab>"
3039 may need to complete either to:
3040 "b function() const"
3041 or to:
3042 "b function() if/thread/task"
3044 Or, this:
3045 "b foo t"
3046 may need to complete either to:
3047 "b foo template_fun<T>()"
3048 with "foo" being the template function's return type, or to:
3049 "b foo thread/task"
3051 Or, this:
3052 "b file<TAB>"
3053 may need to complete either to a source file name:
3054 "b file.c"
3055 or this, also a filename, but a unique completion:
3056 "b file.c:"
3057 or to a function name:
3058 "b file_function"
3060 Address that by completing assuming source or function, and
3061 seeing if we find a completion that matches exactly the
3062 completion word. If so, then it must be a function (see note
3063 below) and we advance the completion word to the end of input
3064 and switch to KEYWORD completion mode.
3066 Note: if we find a unique completion for a source filename,
3067 then it won't match the completion word, because the LCD will
3068 contain a trailing ':'. And if we're completing at or after
3069 the ':', then complete_linespec_component won't try to
3070 complete on source filenames. */
3072 const char *word = parser.completion_word;
3074 complete_linespec_component (&parser, tracker,
3075 parser.completion_word,
3076 linespec_complete_what::FUNCTION,
3077 PARSER_EXPLICIT (&parser)->source_filename);
3079 parser.complete_what = linespec_complete_what::NOTHING;
3081 if (tracker.quote_char ())
3083 /* The function/file name was not close-quoted, so this
3084 can't be a keyword. Note: complete_linespec_component
3085 may have swapped the original quote char for ':' when we
3086 get here, but that still indicates the same. */
3088 else if (!tracker.have_completions ())
3090 size_t key_start;
3091 size_t wordlen = strlen (parser.completion_word);
3093 key_start
3094 = string_find_incomplete_keyword_at_end (linespec_keywords,
3095 parser.completion_word,
3096 wordlen);
3098 if (key_start != -1
3099 || (wordlen > 0
3100 && parser.completion_word[wordlen - 1] == ' '))
3102 parser.completion_word += key_start;
3103 parser.complete_what = linespec_complete_what::KEYWORD;
3106 else if (tracker.completes_to_completion_word (word))
3108 /* Skip the function and complete on keywords. */
3109 parser.completion_word += strlen (word);
3110 parser.complete_what = linespec_complete_what::KEYWORD;
3111 tracker.discard_completions ();
3115 tracker.advance_custom_word_point_by (parser.completion_word - orig);
3117 complete_linespec_component (&parser, tracker,
3118 parser.completion_word,
3119 parser.complete_what,
3120 PARSER_EXPLICIT (&parser)->source_filename);
3122 /* If we're past the "filename:function:label:offset" linespec, and
3123 didn't find any match, then assume the user might want to create
3124 a pending breakpoint anyway and offer the keyword
3125 completions. */
3126 if (!parser.completion_quote_char
3127 && (parser.complete_what == linespec_complete_what::FUNCTION
3128 || parser.complete_what == linespec_complete_what::LABEL
3129 || parser.complete_what == linespec_complete_what::NOTHING)
3130 && !tracker.have_completions ())
3132 const char *end
3133 = parser.completion_word + strlen (parser.completion_word);
3135 if (end > orig && end[-1] == ' ')
3137 tracker.advance_custom_word_point_by (end - parser.completion_word);
3139 complete_linespec_component (&parser, tracker, end,
3140 linespec_complete_what::KEYWORD,
3141 NULL);
3146 /* A helper function for decode_line_full and decode_line_1 to
3147 turn LOCATION into std::vector<symtab_and_line>. */
3149 static std::vector<symtab_and_line>
3150 event_location_to_sals (linespec_parser *parser,
3151 const struct event_location *location)
3153 std::vector<symtab_and_line> result;
3155 switch (event_location_type (location))
3157 case LINESPEC_LOCATION:
3159 PARSER_STATE (parser)->is_linespec = 1;
3162 const linespec_location *ls = get_linespec_location (location);
3163 result = parse_linespec (parser,
3164 ls->spec_string, ls->match_type);
3166 catch (const gdb_exception_error &except)
3168 throw;
3171 break;
3173 case ADDRESS_LOCATION:
3175 const char *addr_string = get_address_string_location (location);
3176 CORE_ADDR addr = get_address_location (location);
3178 if (addr_string != NULL)
3180 addr = linespec_expression_to_pc (&addr_string);
3181 if (PARSER_STATE (parser)->canonical != NULL)
3182 PARSER_STATE (parser)->canonical->location
3183 = copy_event_location (location);
3186 result = convert_address_location_to_sals (PARSER_STATE (parser),
3187 addr);
3189 break;
3191 case EXPLICIT_LOCATION:
3193 const struct explicit_location *explicit_loc;
3195 explicit_loc = get_explicit_location_const (location);
3196 result = convert_explicit_location_to_sals (PARSER_STATE (parser),
3197 PARSER_RESULT (parser),
3198 explicit_loc);
3200 break;
3202 case PROBE_LOCATION:
3203 /* Probes are handled by their own decoders. */
3204 gdb_assert_not_reached ("attempt to decode probe location");
3205 break;
3207 default:
3208 gdb_assert_not_reached ("unhandled event location type");
3211 return result;
3214 /* See linespec.h. */
3216 void
3217 decode_line_full (struct event_location *location, int flags,
3218 struct program_space *search_pspace,
3219 struct symtab *default_symtab,
3220 int default_line, struct linespec_result *canonical,
3221 const char *select_mode,
3222 const char *filter)
3224 std::vector<const char *> filters;
3225 struct linespec_state *state;
3227 gdb_assert (canonical != NULL);
3228 /* The filter only makes sense for 'all'. */
3229 gdb_assert (filter == NULL || select_mode == multiple_symbols_all);
3230 gdb_assert (select_mode == NULL
3231 || select_mode == multiple_symbols_all
3232 || select_mode == multiple_symbols_ask
3233 || select_mode == multiple_symbols_cancel);
3234 gdb_assert ((flags & DECODE_LINE_LIST_MODE) == 0);
3236 linespec_parser parser (flags, current_language,
3237 search_pspace, default_symtab,
3238 default_line, canonical);
3240 scoped_restore_current_program_space restore_pspace;
3242 std::vector<symtab_and_line> result = event_location_to_sals (&parser,
3243 location);
3244 state = PARSER_STATE (&parser);
3246 if (result.size () == 0)
3247 throw_error (NOT_SUPPORTED_ERROR, _("Location %s not available"),
3248 event_location_to_string (location));
3250 gdb_assert (result.size () == 1 || canonical->pre_expanded);
3251 canonical->pre_expanded = 1;
3253 /* Arrange for allocated canonical names to be freed. */
3254 std::vector<gdb::unique_xmalloc_ptr<char>> hold_names;
3255 for (int i = 0; i < result.size (); ++i)
3257 gdb_assert (state->canonical_names[i].suffix != NULL);
3258 hold_names.emplace_back (state->canonical_names[i].suffix);
3261 if (select_mode == NULL)
3263 if (top_level_interpreter ()->interp_ui_out ()->is_mi_like_p ())
3264 select_mode = multiple_symbols_all;
3265 else
3266 select_mode = multiple_symbols_select_mode ();
3269 if (select_mode == multiple_symbols_all)
3271 if (filter != NULL)
3273 filters.push_back (filter);
3274 filter_results (state, &result, filters);
3276 else
3277 convert_results_to_lsals (state, &result);
3279 else
3280 decode_line_2 (state, &result, select_mode);
3283 /* See linespec.h. */
3285 std::vector<symtab_and_line>
3286 decode_line_1 (const struct event_location *location, int flags,
3287 struct program_space *search_pspace,
3288 struct symtab *default_symtab,
3289 int default_line)
3291 linespec_parser parser (flags, current_language,
3292 search_pspace, default_symtab,
3293 default_line, NULL);
3295 scoped_restore_current_program_space restore_pspace;
3297 return event_location_to_sals (&parser, location);
3300 /* See linespec.h. */
3302 std::vector<symtab_and_line>
3303 decode_line_with_current_source (const char *string, int flags)
3305 if (string == 0)
3306 error (_("Empty line specification."));
3308 /* We use whatever is set as the current source line. We do not try
3309 and get a default source symtab+line or it will recursively call us! */
3310 symtab_and_line cursal = get_current_source_symtab_and_line ();
3312 event_location_up location = string_to_event_location (&string,
3313 current_language);
3314 std::vector<symtab_and_line> sals
3315 = decode_line_1 (location.get (), flags, NULL, cursal.symtab, cursal.line);
3317 if (*string)
3318 error (_("Junk at end of line specification: %s"), string);
3320 return sals;
3323 /* See linespec.h. */
3325 std::vector<symtab_and_line>
3326 decode_line_with_last_displayed (const char *string, int flags)
3328 if (string == 0)
3329 error (_("Empty line specification."));
3331 event_location_up location = string_to_event_location (&string,
3332 current_language);
3333 std::vector<symtab_and_line> sals
3334 = (last_displayed_sal_is_valid ()
3335 ? decode_line_1 (location.get (), flags, NULL,
3336 get_last_displayed_symtab (),
3337 get_last_displayed_line ())
3338 : decode_line_1 (location.get (), flags, NULL, NULL, 0));
3340 if (*string)
3341 error (_("Junk at end of line specification: %s"), string);
3343 return sals;
3348 /* First, some functions to initialize stuff at the beginning of the
3349 function. */
3351 static void
3352 initialize_defaults (struct symtab **default_symtab, int *default_line)
3354 if (*default_symtab == 0)
3356 /* Use whatever we have for the default source line. We don't use
3357 get_current_or_default_symtab_and_line as it can recurse and call
3358 us back! */
3359 struct symtab_and_line cursal =
3360 get_current_source_symtab_and_line ();
3362 *default_symtab = cursal.symtab;
3363 *default_line = cursal.line;
3369 /* Evaluate the expression pointed to by EXP_PTR into a CORE_ADDR,
3370 advancing EXP_PTR past any parsed text. */
3372 CORE_ADDR
3373 linespec_expression_to_pc (const char **exp_ptr)
3375 if (current_program_space->executing_startup)
3376 /* The error message doesn't really matter, because this case
3377 should only hit during breakpoint reset. */
3378 throw_error (NOT_FOUND_ERROR, _("cannot evaluate expressions while "
3379 "program space is in startup"));
3381 (*exp_ptr)++;
3382 return value_as_address (parse_to_comma_and_eval (exp_ptr));
3387 /* Here's where we recognise an Objective-C Selector. An Objective C
3388 selector may be implemented by more than one class, therefore it
3389 may represent more than one method/function. This gives us a
3390 situation somewhat analogous to C++ overloading. If there's more
3391 than one method that could represent the selector, then use some of
3392 the existing C++ code to let the user choose one. */
3394 static std::vector<symtab_and_line>
3395 decode_objc (struct linespec_state *self, linespec *ls, const char *arg)
3397 struct collect_info info;
3398 std::vector<const char *> symbol_names;
3399 const char *new_argptr;
3401 info.state = self;
3402 std::vector<symtab *> symtabs;
3403 symtabs.push_back (nullptr);
3405 info.file_symtabs = &symtabs;
3407 std::vector<block_symbol> symbols;
3408 info.result.symbols = &symbols;
3409 std::vector<bound_minimal_symbol> minimal_symbols;
3410 info.result.minimal_symbols = &minimal_symbols;
3412 new_argptr = find_imps (arg, &symbol_names);
3413 if (symbol_names.empty ())
3414 return {};
3416 add_all_symbol_names_from_pspace (&info, NULL, symbol_names,
3417 FUNCTIONS_DOMAIN);
3419 std::vector<symtab_and_line> values;
3420 if (!symbols.empty () || !minimal_symbols.empty ())
3422 char *saved_arg;
3424 saved_arg = (char *) alloca (new_argptr - arg + 1);
3425 memcpy (saved_arg, arg, new_argptr - arg);
3426 saved_arg[new_argptr - arg] = '\0';
3428 ls->explicit_loc.function_name = xstrdup (saved_arg);
3429 ls->function_symbols = std::move (symbols);
3430 ls->minimal_symbols = std::move (minimal_symbols);
3431 values = convert_linespec_to_sals (self, ls);
3433 if (self->canonical)
3435 std::string holder;
3436 const char *str;
3438 self->canonical->pre_expanded = 1;
3440 if (ls->explicit_loc.source_filename)
3442 holder = string_printf ("%s:%s",
3443 ls->explicit_loc.source_filename,
3444 saved_arg);
3445 str = holder.c_str ();
3447 else
3448 str = saved_arg;
3450 self->canonical->location
3451 = new_linespec_location (&str, symbol_name_match_type::FULL);
3455 return values;
3458 namespace {
3460 /* A function object that serves as symbol_found_callback_ftype
3461 callback for iterate_over_symbols. This is used by
3462 lookup_prefix_sym to collect type symbols. */
3463 class decode_compound_collector
3465 public:
3466 decode_compound_collector ()
3467 : m_unique_syms (htab_create_alloc (1, htab_hash_pointer,
3468 htab_eq_pointer, NULL,
3469 xcalloc, xfree))
3473 /* Return all symbols collected. */
3474 std::vector<block_symbol> release_symbols ()
3476 return std::move (m_symbols);
3479 /* Callable as a symbol_found_callback_ftype callback. */
3480 bool operator () (block_symbol *bsym);
3482 private:
3483 /* A hash table of all symbols we found. We use this to avoid
3484 adding any symbol more than once. */
3485 htab_up m_unique_syms;
3487 /* The result vector. */
3488 std::vector<block_symbol> m_symbols;
3491 bool
3492 decode_compound_collector::operator () (block_symbol *bsym)
3494 void **slot;
3495 struct type *t;
3496 struct symbol *sym = bsym->symbol;
3498 if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
3499 return true; /* Continue iterating. */
3501 t = SYMBOL_TYPE (sym);
3502 t = check_typedef (t);
3503 if (t->code () != TYPE_CODE_STRUCT
3504 && t->code () != TYPE_CODE_UNION
3505 && t->code () != TYPE_CODE_NAMESPACE)
3506 return true; /* Continue iterating. */
3508 slot = htab_find_slot (m_unique_syms.get (), sym, INSERT);
3509 if (!*slot)
3511 *slot = sym;
3512 m_symbols.push_back (*bsym);
3515 return true; /* Continue iterating. */
3518 } // namespace
3520 /* Return any symbols corresponding to CLASS_NAME in FILE_SYMTABS. */
3522 static std::vector<block_symbol>
3523 lookup_prefix_sym (struct linespec_state *state,
3524 const std::vector<symtab *> &file_symtabs,
3525 const char *class_name)
3527 decode_compound_collector collector;
3529 lookup_name_info lookup_name (class_name, symbol_name_match_type::FULL);
3531 for (const auto &elt : file_symtabs)
3533 if (elt == nullptr)
3535 iterate_over_all_matching_symtabs (state, lookup_name,
3536 STRUCT_DOMAIN, ALL_DOMAIN,
3537 NULL, false, collector);
3538 iterate_over_all_matching_symtabs (state, lookup_name,
3539 VAR_DOMAIN, ALL_DOMAIN,
3540 NULL, false, collector);
3542 else
3544 /* Program spaces that are executing startup should have
3545 been filtered out earlier. */
3546 gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
3547 set_current_program_space (SYMTAB_PSPACE (elt));
3548 iterate_over_file_blocks (elt, lookup_name, STRUCT_DOMAIN, collector);
3549 iterate_over_file_blocks (elt, lookup_name, VAR_DOMAIN, collector);
3553 return collector.release_symbols ();
3556 /* A std::sort comparison function for symbols. The resulting order does
3557 not actually matter; we just need to be able to sort them so that
3558 symbols with the same program space end up next to each other. */
3560 static bool
3561 compare_symbols (const block_symbol &a, const block_symbol &b)
3563 uintptr_t uia, uib;
3565 uia = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (a.symbol));
3566 uib = (uintptr_t) SYMTAB_PSPACE (symbol_symtab (b.symbol));
3568 if (uia < uib)
3569 return true;
3570 if (uia > uib)
3571 return false;
3573 uia = (uintptr_t) a.symbol;
3574 uib = (uintptr_t) b.symbol;
3576 if (uia < uib)
3577 return true;
3579 return false;
3582 /* Like compare_symbols but for minimal symbols. */
3584 static bool
3585 compare_msymbols (const bound_minimal_symbol &a, const bound_minimal_symbol &b)
3587 uintptr_t uia, uib;
3589 uia = (uintptr_t) a.objfile->pspace;
3590 uib = (uintptr_t) a.objfile->pspace;
3592 if (uia < uib)
3593 return true;
3594 if (uia > uib)
3595 return false;
3597 uia = (uintptr_t) a.minsym;
3598 uib = (uintptr_t) b.minsym;
3600 if (uia < uib)
3601 return true;
3603 return false;
3606 /* Look for all the matching instances of each symbol in NAMES. Only
3607 instances from PSPACE are considered; other program spaces are
3608 handled by our caller. If PSPACE is NULL, then all program spaces
3609 are considered. Results are stored into INFO. */
3611 static void
3612 add_all_symbol_names_from_pspace (struct collect_info *info,
3613 struct program_space *pspace,
3614 const std::vector<const char *> &names,
3615 enum search_domain search_domain)
3617 for (const char *iter : names)
3618 add_matching_symbols_to_info (iter,
3619 symbol_name_match_type::FULL,
3620 search_domain, info, pspace);
3623 static void
3624 find_superclass_methods (std::vector<struct type *> &&superclasses,
3625 const char *name, enum language name_lang,
3626 std::vector<const char *> *result_names)
3628 size_t old_len = result_names->size ();
3630 while (1)
3632 std::vector<struct type *> new_supers;
3634 for (type *t : superclasses)
3635 find_methods (t, name_lang, name, result_names, &new_supers);
3637 if (result_names->size () != old_len || new_supers.empty ())
3638 break;
3640 superclasses = std::move (new_supers);
3644 /* This finds the method METHOD_NAME in the class CLASS_NAME whose type is
3645 given by one of the symbols in SYM_CLASSES. Matches are returned
3646 in SYMBOLS (for debug symbols) and MINSYMS (for minimal symbols). */
3648 static void
3649 find_method (struct linespec_state *self,
3650 const std::vector<symtab *> &file_symtabs,
3651 const char *class_name, const char *method_name,
3652 std::vector<block_symbol> *sym_classes,
3653 std::vector<block_symbol> *symbols,
3654 std::vector<bound_minimal_symbol> *minsyms)
3656 size_t last_result_len;
3657 std::vector<struct type *> superclass_vec;
3658 std::vector<const char *> result_names;
3659 struct collect_info info;
3661 /* Sort symbols so that symbols with the same program space are next
3662 to each other. */
3663 std::sort (sym_classes->begin (), sym_classes->end (),
3664 compare_symbols);
3666 info.state = self;
3667 info.file_symtabs = &file_symtabs;
3668 info.result.symbols = symbols;
3669 info.result.minimal_symbols = minsyms;
3671 /* Iterate over all the types, looking for the names of existing
3672 methods matching METHOD_NAME. If we cannot find a direct method in a
3673 given program space, then we consider inherited methods; this is
3674 not ideal (ideal would be to respect C++ hiding rules), but it
3675 seems good enough and is what GDB has historically done. We only
3676 need to collect the names because later we find all symbols with
3677 those names. This loop is written in a somewhat funny way
3678 because we collect data across the program space before deciding
3679 what to do. */
3680 last_result_len = 0;
3681 for (const auto &elt : *sym_classes)
3683 struct type *t;
3684 struct program_space *pspace;
3685 struct symbol *sym = elt.symbol;
3686 unsigned int ix = &elt - &*sym_classes->begin ();
3688 /* Program spaces that are executing startup should have
3689 been filtered out earlier. */
3690 pspace = SYMTAB_PSPACE (symbol_symtab (sym));
3691 gdb_assert (!pspace->executing_startup);
3692 set_current_program_space (pspace);
3693 t = check_typedef (SYMBOL_TYPE (sym));
3694 find_methods (t, sym->language (),
3695 method_name, &result_names, &superclass_vec);
3697 /* Handle all items from a single program space at once; and be
3698 sure not to miss the last batch. */
3699 if (ix == sym_classes->size () - 1
3700 || (pspace
3701 != SYMTAB_PSPACE (symbol_symtab (sym_classes->at (ix + 1).symbol))))
3703 /* If we did not find a direct implementation anywhere in
3704 this program space, consider superclasses. */
3705 if (result_names.size () == last_result_len)
3706 find_superclass_methods (std::move (superclass_vec), method_name,
3707 sym->language (), &result_names);
3709 /* We have a list of candidate symbol names, so now we
3710 iterate over the symbol tables looking for all
3711 matches in this pspace. */
3712 add_all_symbol_names_from_pspace (&info, pspace, result_names,
3713 FUNCTIONS_DOMAIN);
3715 superclass_vec.clear ();
3716 last_result_len = result_names.size ();
3720 if (!symbols->empty () || !minsyms->empty ())
3721 return;
3723 /* Throw an NOT_FOUND_ERROR. This will be caught by the caller
3724 and other attempts to locate the symbol will be made. */
3725 throw_error (NOT_FOUND_ERROR, _("see caller, this text doesn't matter"));
3730 namespace {
3732 /* This function object is a callback for iterate_over_symtabs, used
3733 when collecting all matching symtabs. */
3735 class symtab_collector
3737 public:
3738 symtab_collector ()
3739 : m_symtab_table (htab_create (1, htab_hash_pointer, htab_eq_pointer,
3740 NULL))
3744 /* Callable as a symbol_found_callback_ftype callback. */
3745 bool operator () (symtab *sym);
3747 /* Return an rvalue reference to the collected symtabs. */
3748 std::vector<symtab *> &&release_symtabs ()
3750 return std::move (m_symtabs);
3753 private:
3754 /* The result vector of symtabs. */
3755 std::vector<symtab *> m_symtabs;
3757 /* This is used to ensure the symtabs are unique. */
3758 htab_up m_symtab_table;
3761 bool
3762 symtab_collector::operator () (struct symtab *symtab)
3764 void **slot;
3766 slot = htab_find_slot (m_symtab_table.get (), symtab, INSERT);
3767 if (!*slot)
3769 *slot = symtab;
3770 m_symtabs.push_back (symtab);
3773 return false;
3776 } // namespace
3778 /* Given a file name, return a list of all matching symtabs. If
3779 SEARCH_PSPACE is not NULL, the search is restricted to just that
3780 program space. */
3782 static std::vector<symtab *>
3783 collect_symtabs_from_filename (const char *file,
3784 struct program_space *search_pspace)
3786 symtab_collector collector;
3788 /* Find that file's data. */
3789 if (search_pspace == NULL)
3791 for (struct program_space *pspace : program_spaces)
3793 if (pspace->executing_startup)
3794 continue;
3796 set_current_program_space (pspace);
3797 iterate_over_symtabs (file, collector);
3800 else
3802 set_current_program_space (search_pspace);
3803 iterate_over_symtabs (file, collector);
3806 return collector.release_symtabs ();
3809 /* Return all the symtabs associated to the FILENAME. If SEARCH_PSPACE is
3810 not NULL, the search is restricted to just that program space. */
3812 static std::vector<symtab *>
3813 symtabs_from_filename (const char *filename,
3814 struct program_space *search_pspace)
3816 std::vector<symtab *> result
3817 = collect_symtabs_from_filename (filename, search_pspace);
3819 if (result.empty ())
3821 if (!have_full_symbols () && !have_partial_symbols ())
3822 throw_error (NOT_FOUND_ERROR,
3823 _("No symbol table is loaded. "
3824 "Use the \"file\" command."));
3825 source_file_not_found_error (filename);
3828 return result;
3831 /* See symtab.h. */
3833 void
3834 symbol_searcher::find_all_symbols (const std::string &name,
3835 const struct language_defn *language,
3836 enum search_domain search_domain,
3837 std::vector<symtab *> *search_symtabs,
3838 struct program_space *search_pspace)
3840 symbol_searcher_collect_info info;
3841 struct linespec_state state;
3843 memset (&state, 0, sizeof (state));
3844 state.language = language;
3845 info.state = &state;
3847 info.result.symbols = &m_symbols;
3848 info.result.minimal_symbols = &m_minimal_symbols;
3849 std::vector<symtab *> all_symtabs;
3850 if (search_symtabs == nullptr)
3852 all_symtabs.push_back (nullptr);
3853 search_symtabs = &all_symtabs;
3855 info.file_symtabs = search_symtabs;
3857 add_matching_symbols_to_info (name.c_str (), symbol_name_match_type::WILD,
3858 search_domain, &info, search_pspace);
3861 /* Look up a function symbol named NAME in symtabs FILE_SYMTABS. Matching
3862 debug symbols are returned in SYMBOLS. Matching minimal symbols are
3863 returned in MINSYMS. */
3865 static void
3866 find_function_symbols (struct linespec_state *state,
3867 const std::vector<symtab *> &file_symtabs, const char *name,
3868 symbol_name_match_type name_match_type,
3869 std::vector<block_symbol> *symbols,
3870 std::vector<bound_minimal_symbol> *minsyms)
3872 struct collect_info info;
3873 std::vector<const char *> symbol_names;
3875 info.state = state;
3876 info.result.symbols = symbols;
3877 info.result.minimal_symbols = minsyms;
3878 info.file_symtabs = &file_symtabs;
3880 /* Try NAME as an Objective-C selector. */
3881 find_imps (name, &symbol_names);
3882 if (!symbol_names.empty ())
3883 add_all_symbol_names_from_pspace (&info, state->search_pspace,
3884 symbol_names, FUNCTIONS_DOMAIN);
3885 else
3886 add_matching_symbols_to_info (name, name_match_type, FUNCTIONS_DOMAIN,
3887 &info, state->search_pspace);
3890 /* Find all symbols named NAME in FILE_SYMTABS, returning debug symbols
3891 in SYMBOLS and minimal symbols in MINSYMS. */
3893 static void
3894 find_linespec_symbols (struct linespec_state *state,
3895 const std::vector<symtab *> &file_symtabs,
3896 const char *lookup_name,
3897 symbol_name_match_type name_match_type,
3898 std::vector <block_symbol> *symbols,
3899 std::vector<bound_minimal_symbol> *minsyms)
3901 gdb::unique_xmalloc_ptr<char> canon
3902 = cp_canonicalize_string_no_typedefs (lookup_name);
3903 if (canon != nullptr)
3904 lookup_name = canon.get ();
3906 /* It's important to not call expand_symtabs_matching unnecessarily
3907 as it can really slow things down (by unnecessarily expanding
3908 potentially 1000s of symtabs, which when debugging some apps can
3909 cost 100s of seconds). Avoid this to some extent by *first* calling
3910 find_function_symbols, and only if that doesn't find anything
3911 *then* call find_method. This handles two important cases:
3912 1) break (anonymous namespace)::foo
3913 2) break class::method where method is in class (and not a baseclass) */
3915 find_function_symbols (state, file_symtabs, lookup_name,
3916 name_match_type, symbols, minsyms);
3918 /* If we were unable to locate a symbol of the same name, try dividing
3919 the name into class and method names and searching the class and its
3920 baseclasses. */
3921 if (symbols->empty () && minsyms->empty ())
3923 std::string klass, method;
3924 const char *last, *p, *scope_op;
3926 /* See if we can find a scope operator and break this symbol
3927 name into namespaces${SCOPE_OPERATOR}class_name and method_name. */
3928 scope_op = "::";
3929 p = find_toplevel_string (lookup_name, scope_op);
3931 last = NULL;
3932 while (p != NULL)
3934 last = p;
3935 p = find_toplevel_string (p + strlen (scope_op), scope_op);
3938 /* If no scope operator was found, there is nothing more we can do;
3939 we already attempted to lookup the entire name as a symbol
3940 and failed. */
3941 if (last == NULL)
3942 return;
3944 /* LOOKUP_NAME points to the class name.
3945 LAST points to the method name. */
3946 klass = std::string (lookup_name, last - lookup_name);
3948 /* Skip past the scope operator. */
3949 last += strlen (scope_op);
3950 method = last;
3952 /* Find a list of classes named KLASS. */
3953 std::vector<block_symbol> classes
3954 = lookup_prefix_sym (state, file_symtabs, klass.c_str ());
3955 if (!classes.empty ())
3957 /* Now locate a list of suitable methods named METHOD. */
3960 find_method (state, file_symtabs,
3961 klass.c_str (), method.c_str (),
3962 &classes, symbols, minsyms);
3965 /* If successful, we're done. If NOT_FOUND_ERROR
3966 was not thrown, rethrow the exception that we did get. */
3967 catch (const gdb_exception_error &except)
3969 if (except.error != NOT_FOUND_ERROR)
3970 throw;
3976 /* Helper for find_label_symbols. Find all labels that match name
3977 NAME in BLOCK. Return all labels that match in FUNCTION_SYMBOLS.
3978 Return the actual function symbol in which the label was found in
3979 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
3980 interpreted as a label name prefix. Otherwise, only a label named
3981 exactly NAME match. */
3983 static void
3984 find_label_symbols_in_block (const struct block *block,
3985 const char *name, struct symbol *fn_sym,
3986 bool completion_mode,
3987 std::vector<block_symbol> *result,
3988 std::vector<block_symbol> *label_funcs_ret)
3990 if (completion_mode)
3992 struct block_iterator iter;
3993 struct symbol *sym;
3994 size_t name_len = strlen (name);
3996 int (*cmp) (const char *, const char *, size_t);
3997 cmp = case_sensitivity == case_sensitive_on ? strncmp : strncasecmp;
3999 ALL_BLOCK_SYMBOLS (block, iter, sym)
4001 if (symbol_matches_domain (sym->language (),
4002 SYMBOL_DOMAIN (sym), LABEL_DOMAIN)
4003 && cmp (sym->search_name (), name, name_len) == 0)
4005 result->push_back ({sym, block});
4006 label_funcs_ret->push_back ({fn_sym, block});
4010 else
4012 struct block_symbol label_sym
4013 = lookup_symbol (name, block, LABEL_DOMAIN, 0);
4015 if (label_sym.symbol != NULL)
4017 result->push_back (label_sym);
4018 label_funcs_ret->push_back ({fn_sym, block});
4023 /* Return all labels that match name NAME in FUNCTION_SYMBOLS.
4025 Return the actual function symbol in which the label was found in
4026 LABEL_FUNC_RET. If COMPLETION_MODE is true, then NAME is
4027 interpreted as a label name prefix. Otherwise, only labels named
4028 exactly NAME match. */
4031 static std::vector<block_symbol>
4032 find_label_symbols (struct linespec_state *self,
4033 const std::vector<block_symbol> &function_symbols,
4034 std::vector<block_symbol> *label_funcs_ret,
4035 const char *name,
4036 bool completion_mode)
4038 const struct block *block;
4039 struct symbol *fn_sym;
4040 std::vector<block_symbol> result;
4042 if (function_symbols.empty ())
4044 set_current_program_space (self->program_space);
4045 block = get_current_search_block ();
4047 for (;
4048 block && !BLOCK_FUNCTION (block);
4049 block = BLOCK_SUPERBLOCK (block))
4052 if (!block)
4053 return {};
4055 fn_sym = BLOCK_FUNCTION (block);
4057 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
4058 &result, label_funcs_ret);
4060 else
4062 for (const auto &elt : function_symbols)
4064 fn_sym = elt.symbol;
4065 set_current_program_space (SYMTAB_PSPACE (symbol_symtab (fn_sym)));
4066 block = SYMBOL_BLOCK_VALUE (fn_sym);
4068 find_label_symbols_in_block (block, name, fn_sym, completion_mode,
4069 &result, label_funcs_ret);
4073 return result;
4078 /* A helper for create_sals_line_offset that handles the 'list_mode' case. */
4080 static std::vector<symtab_and_line>
4081 decode_digits_list_mode (struct linespec_state *self,
4082 linespec *ls,
4083 struct symtab_and_line val)
4085 gdb_assert (self->list_mode);
4087 std::vector<symtab_and_line> values;
4089 for (const auto &elt : ls->file_symtabs)
4091 /* The logic above should ensure this. */
4092 gdb_assert (elt != NULL);
4094 set_current_program_space (SYMTAB_PSPACE (elt));
4096 /* Simplistic search just for the list command. */
4097 val.symtab = find_line_symtab (elt, val.line, NULL, NULL);
4098 if (val.symtab == NULL)
4099 val.symtab = elt;
4100 val.pspace = SYMTAB_PSPACE (elt);
4101 val.pc = 0;
4102 val.explicit_line = true;
4104 add_sal_to_sals (self, &values, &val, NULL, 0);
4107 return values;
4110 /* A helper for create_sals_line_offset that iterates over the symtabs
4111 associated with LS and returns a vector of corresponding symtab_and_line
4112 structures. */
4114 static std::vector<symtab_and_line>
4115 decode_digits_ordinary (struct linespec_state *self,
4116 linespec *ls,
4117 int line,
4118 struct linetable_entry **best_entry)
4120 std::vector<symtab_and_line> sals;
4121 for (const auto &elt : ls->file_symtabs)
4123 std::vector<CORE_ADDR> pcs;
4125 /* The logic above should ensure this. */
4126 gdb_assert (elt != NULL);
4128 set_current_program_space (SYMTAB_PSPACE (elt));
4130 pcs = find_pcs_for_symtab_line (elt, line, best_entry);
4131 for (CORE_ADDR pc : pcs)
4133 symtab_and_line sal;
4134 sal.pspace = SYMTAB_PSPACE (elt);
4135 sal.symtab = elt;
4136 sal.line = line;
4137 sal.explicit_line = true;
4138 sal.pc = pc;
4139 sals.push_back (std::move (sal));
4143 return sals;
4148 /* Return the line offset represented by VARIABLE. */
4150 static struct line_offset
4151 linespec_parse_variable (struct linespec_state *self, const char *variable)
4153 int index = 0;
4154 const char *p;
4155 struct line_offset offset = {0, LINE_OFFSET_NONE};
4157 p = (variable[1] == '$') ? variable + 2 : variable + 1;
4158 if (*p == '$')
4159 ++p;
4160 while (*p >= '0' && *p <= '9')
4161 ++p;
4162 if (!*p) /* Reached end of token without hitting non-digit. */
4164 /* We have a value history reference. */
4165 struct value *val_history;
4167 sscanf ((variable[1] == '$') ? variable + 2 : variable + 1, "%d", &index);
4168 val_history
4169 = access_value_history ((variable[1] == '$') ? -index : index);
4170 if (value_type (val_history)->code () != TYPE_CODE_INT)
4171 error (_("History values used in line "
4172 "specs must have integer values."));
4173 offset.offset = value_as_long (val_history);
4175 else
4177 /* Not all digits -- may be user variable/function or a
4178 convenience variable. */
4179 LONGEST valx;
4180 struct internalvar *ivar;
4182 /* Try it as a convenience variable. If it is not a convenience
4183 variable, return and allow normal symbol lookup to occur. */
4184 ivar = lookup_only_internalvar (variable + 1);
4185 if (ivar == NULL)
4186 /* No internal variable with that name. Mark the offset
4187 as unknown to allow the name to be looked up as a symbol. */
4188 offset.sign = LINE_OFFSET_UNKNOWN;
4189 else
4191 /* We found a valid variable name. If it is not an integer,
4192 throw an error. */
4193 if (!get_internalvar_integer (ivar, &valx))
4194 error (_("Convenience variables used in line "
4195 "specs must have integer values."));
4196 else
4197 offset.offset = valx;
4201 return offset;
4205 /* We've found a minimal symbol MSYMBOL in OBJFILE to associate with our
4206 linespec; return the SAL in RESULT. This function should return SALs
4207 matching those from find_function_start_sal, otherwise false
4208 multiple-locations breakpoints could be placed. */
4210 static void
4211 minsym_found (struct linespec_state *self, struct objfile *objfile,
4212 struct minimal_symbol *msymbol,
4213 std::vector<symtab_and_line> *result)
4215 bool want_start_sal;
4217 CORE_ADDR func_addr;
4218 bool is_function = msymbol_is_function (objfile, msymbol, &func_addr);
4220 if (is_function)
4222 const char *msym_name = msymbol->linkage_name ();
4224 if (MSYMBOL_TYPE (msymbol) == mst_text_gnu_ifunc
4225 || MSYMBOL_TYPE (msymbol) == mst_data_gnu_ifunc)
4226 want_start_sal = gnu_ifunc_resolve_name (msym_name, &func_addr);
4227 else
4228 want_start_sal = true;
4231 symtab_and_line sal;
4233 if (is_function && want_start_sal)
4234 sal = find_function_start_sal (func_addr, NULL, self->funfirstline);
4235 else
4237 sal.objfile = objfile;
4238 sal.msymbol = msymbol;
4239 /* Store func_addr, not the minsym's address in case this was an
4240 ifunc that hasn't been resolved yet. */
4241 if (is_function)
4242 sal.pc = func_addr;
4243 else
4244 sal.pc = MSYMBOL_VALUE_ADDRESS (objfile, msymbol);
4245 sal.pspace = current_program_space;
4248 sal.section = msymbol->obj_section (objfile);
4250 if (maybe_add_address (self->addr_set, objfile->pspace, sal.pc))
4251 add_sal_to_sals (self, result, &sal, msymbol->natural_name (), 0);
4254 /* Helper for search_minsyms_for_name that adds the symbol to the
4255 result. */
4257 static void
4258 add_minsym (struct minimal_symbol *minsym, struct objfile *objfile,
4259 struct symtab *symtab, int list_mode,
4260 std::vector<struct bound_minimal_symbol> *msyms)
4262 if (symtab != NULL)
4264 /* We're looking for a label for which we don't have debug
4265 info. */
4266 CORE_ADDR func_addr;
4267 if (msymbol_is_function (objfile, minsym, &func_addr))
4269 symtab_and_line sal = find_pc_sect_line (func_addr, NULL, 0);
4271 if (symtab != sal.symtab)
4272 return;
4276 /* Exclude data symbols when looking for breakpoint locations. */
4277 if (!list_mode && !msymbol_is_function (objfile, minsym))
4278 return;
4280 struct bound_minimal_symbol mo = {minsym, objfile};
4281 msyms->push_back (mo);
4282 return;
4285 /* Search for minimal symbols called NAME. If SEARCH_PSPACE
4286 is not NULL, the search is restricted to just that program
4287 space.
4289 If SYMTAB is NULL, search all objfiles, otherwise
4290 restrict results to the given SYMTAB. */
4292 static void
4293 search_minsyms_for_name (struct collect_info *info,
4294 const lookup_name_info &name,
4295 struct program_space *search_pspace,
4296 struct symtab *symtab)
4298 std::vector<struct bound_minimal_symbol> minsyms;
4300 if (symtab == NULL)
4302 for (struct program_space *pspace : program_spaces)
4304 if (search_pspace != NULL && search_pspace != pspace)
4305 continue;
4306 if (pspace->executing_startup)
4307 continue;
4309 set_current_program_space (pspace);
4311 for (objfile *objfile : current_program_space->objfiles ())
4313 iterate_over_minimal_symbols (objfile, name,
4314 [&] (struct minimal_symbol *msym)
4316 add_minsym (msym, objfile, nullptr,
4317 info->state->list_mode,
4318 &minsyms);
4319 return false;
4324 else
4326 if (search_pspace == NULL || SYMTAB_PSPACE (symtab) == search_pspace)
4328 set_current_program_space (SYMTAB_PSPACE (symtab));
4329 iterate_over_minimal_symbols
4330 (SYMTAB_OBJFILE (symtab), name,
4331 [&] (struct minimal_symbol *msym)
4333 add_minsym (msym, SYMTAB_OBJFILE (symtab), symtab,
4334 info->state->list_mode, &minsyms);
4335 return false;
4340 /* Return true if TYPE is a static symbol. */
4341 auto msymbol_type_is_static = [] (enum minimal_symbol_type type)
4343 switch (type)
4345 case mst_file_text:
4346 case mst_file_data:
4347 case mst_file_bss:
4348 return true;
4349 default:
4350 return false;
4354 /* Add minsyms to the result set, but filter out trampoline symbols
4355 if we also found extern symbols with the same name. I.e., don't
4356 set a breakpoint on both '<foo@plt>' and 'foo', assuming that
4357 'foo' is the symbol that the plt resolves to. */
4358 for (const bound_minimal_symbol &item : minsyms)
4360 bool skip = false;
4361 if (MSYMBOL_TYPE (item.minsym) == mst_solib_trampoline)
4363 for (const bound_minimal_symbol &item2 : minsyms)
4365 if (&item2 == &item)
4366 continue;
4368 /* Trampoline symbols can only jump to exported
4369 symbols. */
4370 if (msymbol_type_is_static (MSYMBOL_TYPE (item2.minsym)))
4371 continue;
4373 if (strcmp (item.minsym->linkage_name (),
4374 item2.minsym->linkage_name ()) != 0)
4375 continue;
4377 /* Found a global minsym with the same name as the
4378 trampoline. Don't create a location for this
4379 trampoline. */
4380 skip = true;
4381 break;
4385 if (!skip)
4386 info->result.minimal_symbols->push_back (item);
4390 /* A helper function to add all symbols matching NAME to INFO. If
4391 PSPACE is not NULL, the search is restricted to just that program
4392 space. */
4394 static void
4395 add_matching_symbols_to_info (const char *name,
4396 symbol_name_match_type name_match_type,
4397 enum search_domain search_domain,
4398 struct collect_info *info,
4399 struct program_space *pspace)
4401 lookup_name_info lookup_name (name, name_match_type);
4403 for (const auto &elt : *info->file_symtabs)
4405 if (elt == nullptr)
4407 iterate_over_all_matching_symtabs (info->state, lookup_name,
4408 VAR_DOMAIN, search_domain,
4409 pspace, true,
4410 [&] (block_symbol *bsym)
4411 { return info->add_symbol (bsym); });
4412 search_minsyms_for_name (info, lookup_name, pspace, NULL);
4414 else if (pspace == NULL || pspace == SYMTAB_PSPACE (elt))
4416 int prev_len = info->result.symbols->size ();
4418 /* Program spaces that are executing startup should have
4419 been filtered out earlier. */
4420 gdb_assert (!SYMTAB_PSPACE (elt)->executing_startup);
4421 set_current_program_space (SYMTAB_PSPACE (elt));
4422 iterate_over_file_blocks (elt, lookup_name, VAR_DOMAIN,
4423 [&] (block_symbol *bsym)
4424 { return info->add_symbol (bsym); });
4426 /* If no new symbols were found in this iteration and this symtab
4427 is in assembler, we might actually be looking for a label for
4428 which we don't have debug info. Check for a minimal symbol in
4429 this case. */
4430 if (prev_len == info->result.symbols->size ()
4431 && elt->language == language_asm)
4432 search_minsyms_for_name (info, lookup_name, pspace, elt);
4439 /* Now come some functions that are called from multiple places within
4440 decode_line_1. */
4442 static int
4443 symbol_to_sal (struct symtab_and_line *result,
4444 int funfirstline, struct symbol *sym)
4446 if (SYMBOL_CLASS (sym) == LOC_BLOCK)
4448 *result = find_function_start_sal (sym, funfirstline);
4449 return 1;
4451 else
4453 if (SYMBOL_CLASS (sym) == LOC_LABEL && SYMBOL_VALUE_ADDRESS (sym) != 0)
4455 *result = {};
4456 result->symtab = symbol_symtab (sym);
4457 result->symbol = sym;
4458 result->line = SYMBOL_LINE (sym);
4459 result->pc = SYMBOL_VALUE_ADDRESS (sym);
4460 result->pspace = SYMTAB_PSPACE (result->symtab);
4461 result->explicit_pc = 1;
4462 return 1;
4464 else if (funfirstline)
4466 /* Nothing. */
4468 else if (SYMBOL_LINE (sym) != 0)
4470 /* We know its line number. */
4471 *result = {};
4472 result->symtab = symbol_symtab (sym);
4473 result->symbol = sym;
4474 result->line = SYMBOL_LINE (sym);
4475 result->pc = SYMBOL_VALUE_ADDRESS (sym);
4476 result->pspace = SYMTAB_PSPACE (result->symtab);
4477 return 1;
4481 return 0;
4484 linespec_result::~linespec_result ()
4486 for (linespec_sals &lsal : lsals)
4487 xfree (lsal.canonical);
4490 /* Return the quote characters permitted by the linespec parser. */
4492 const char *
4493 get_gdb_linespec_parser_quote_characters (void)
4495 return linespec_quote_characters;