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