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