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