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