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