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