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