GDB (xrefs)
Loading...
Searching...
No Matches
parse.c
Go to the documentation of this file.
1/* Parse expressions for GDB.
2
3 Copyright (C) 1986-2023 Free Software Foundation, Inc.
4
5 Modified from expread.y by the Department of Computer Science at the
6 State University of New York at Buffalo, 1991.
7
8 This file is part of GDB.
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22
23/* Parse an expression from text in a string,
24 and return the result as a struct expression pointer.
25 That structure contains arithmetic operations in reverse polish,
26 with constants represented by operations that are followed by special data.
27 See expression.h for the details of the format.
28 What is important here is that it can be built up sequentially
29 during the process of parsing; the lower levels of the tree always
30 come first in the result. */
31
32#include "defs.h"
33#include <ctype.h>
34#include "arch-utils.h"
35#include "symtab.h"
36#include "gdbtypes.h"
37#include "frame.h"
38#include "expression.h"
39#include "value.h"
40#include "command.h"
41#include "language.h"
42#include "parser-defs.h"
43#include "gdbcmd.h"
44#include "symfile.h"
45#include "inferior.h"
46#include "target-float.h"
47#include "block.h"
48#include "source.h"
49#include "objfiles.h"
50#include "user-regs.h"
51#include <algorithm>
52#include "gdbsupport/gdb_optional.h"
53#include "c-exp.h"
54
55static unsigned int expressiondebug = 0;
56static void
57show_expressiondebug (struct ui_file *file, int from_tty,
58 struct cmd_list_element *c, const char *value)
59{
60 gdb_printf (file, _("Expression debugging is %s.\n"), value);
61}
62
63
64/* True if an expression parser should set yydebug. */
65static bool parser_debug;
66
67static void
68show_parserdebug (struct ui_file *file, int from_tty,
69 struct cmd_list_element *c, const char *value)
70{
71 gdb_printf (file, _("Parser debugging is %s.\n"), value);
72}
73
74
75/* Documented at it's declaration. */
76
77void
79 innermost_block_tracker_types t)
80{
81 if ((m_types & t) != 0
82 && (m_innermost_block == NULL
85}
86
87
88
89bool
91 completion_tracker &tracker)
92{
94 m_name.get (), m_code);
95 return true;
96}
97
98/* See parser-defs.h. */
99
100void
106
107/* Indicate that the current parser invocation is completing a tag.
108 TAG is the type code of the tag, and PTR and LENGTH represent the
109 start of the tag name. */
110
111void
113 int length)
114{
115 gdb_assert (parse_completion && m_completion_state == nullptr);
116 gdb_assert (tag == TYPE_CODE_UNION
117 || tag == TYPE_CODE_STRUCT
118 || tag == TYPE_CODE_ENUM);
120 (new expr_complete_tag (tag, make_unique_xstrndup (ptr, length)));
121}
122
123/* See parser-defs.h. */
124
125void
127{
128 std::vector<std::string> data (vec->len);
129 for (int i = 0; i < vec->len; ++i)
130 data[i] = std::string (vec->tokens[i].ptr, vec->tokens[i].length);
131
132 push_new<expr::c_string_operation> ((enum c_string_type_values) kind,
133 std::move (data));
134}
135
136/* See parser-defs.h. */
137
138void
140{
141 if (sym.symbol != nullptr)
142 {
144 block_tracker->update (sym);
145 push_new<expr::var_value_operation> (sym);
146 }
147 else
148 {
150 if (msymbol.minsym != NULL)
151 push_new<expr::var_msym_value_operation> (msymbol);
152 else if (!have_full_symbols () && !have_partial_symbols ())
153 error (_("No symbol table is loaded. Use the \"file\" command."));
154 else
155 error (_("No symbol \"%s\" in current context."), name);
156 }
157}
158
159/* See parser-defs.h. */
160
161void
163{
164 struct block_symbol sym;
165 struct bound_minimal_symbol msym;
166 struct internalvar *isym = NULL;
167 std::string copy;
168
169 /* Handle the tokens $digits; also $ (short for $0) and $$ (short for $$1)
170 and $$digits (equivalent to $<-digits> if you could type that). */
171
172 int negate = 0;
173 int i = 1;
174 /* Double dollar means negate the number and add -1 as well.
175 Thus $$ alone means -1. */
176 if (str.length >= 2 && str.ptr[1] == '$')
177 {
178 negate = 1;
179 i = 2;
180 }
181 if (i == str.length)
182 {
183 /* Just dollars (one or two). */
184 i = -negate;
185 push_new<expr::last_operation> (i);
186 return;
187 }
188 /* Is the rest of the token digits? */
189 for (; i < str.length; i++)
190 if (!(str.ptr[i] >= '0' && str.ptr[i] <= '9'))
191 break;
192 if (i == str.length)
193 {
194 i = atoi (str.ptr + 1 + negate);
195 if (negate)
196 i = -i;
197 push_new<expr::last_operation> (i);
198 return;
199 }
200
201 /* Handle tokens that refer to machine registers:
202 $ followed by a register name. */
204 str.ptr + 1, str.length - 1);
205 if (i >= 0)
206 {
207 str.length--;
208 str.ptr++;
209 push_new<expr::register_operation> (copy_name (str));
212 return;
213 }
214
215 /* Any names starting with $ are probably debugger internal variables. */
216
217 copy = copy_name (str);
218 isym = lookup_only_internalvar (copy.c_str () + 1);
219 if (isym)
220 {
221 push_new<expr::internalvar_operation> (isym);
222 return;
223 }
224
225 /* On some systems, such as HP-UX and hppa-linux, certain system routines
226 have names beginning with $ or $$. Check for those, first. */
227
228 sym = lookup_symbol (copy.c_str (), NULL, VAR_DOMAIN, NULL);
229 if (sym.symbol)
230 {
231 push_new<expr::var_value_operation> (sym);
232 return;
233 }
234 msym = lookup_bound_minimal_symbol (copy.c_str ());
235 if (msym.minsym)
236 {
237 push_new<expr::var_msym_value_operation> (msym);
238 return;
239 }
240
241 /* Any other names are assumed to be debugger internal variables. */
242
243 push_new<expr::internalvar_operation>
244 (create_internalvar (copy.c_str () + 1));
245}
246
247
248
249const char *
251{
252 int depth = 1;
253 int just_seen_right = 0;
254 int just_seen_colon = 0;
255 int just_seen_space = 0;
256
257 if (!p || (*p != '<'))
258 return 0;
259
260 while (*++p)
261 {
262 switch (*p)
263 {
264 case '\'':
265 case '\"':
266 case '{':
267 case '}':
268 /* In future, may want to allow these?? */
269 return 0;
270 case '<':
271 depth++; /* start nested template */
272 if (just_seen_colon || just_seen_right || just_seen_space)
273 return 0; /* but not after : or :: or > or space */
274 break;
275 case '>':
276 if (just_seen_colon || just_seen_right)
277 return 0; /* end a (nested?) template */
278 just_seen_right = 1; /* but not after : or :: */
279 if (--depth == 0) /* also disallow >>, insist on > > */
280 return ++p; /* if outermost ended, return */
281 break;
282 case ':':
283 if (just_seen_space || (just_seen_colon > 1))
284 return 0; /* nested class spec coming up */
285 just_seen_colon++; /* we allow :: but not :::: */
286 break;
287 case ' ':
288 break;
289 default:
290 if (!((*p >= 'a' && *p <= 'z') || /* allow token chars */
291 (*p >= 'A' && *p <= 'Z') ||
292 (*p >= '0' && *p <= '9') ||
293 (*p == '_') || (*p == ',') || /* commas for template args */
294 (*p == '&') || (*p == '*') || /* pointer and ref types */
295 (*p == '(') || (*p == ')') || /* function types */
296 (*p == '[') || (*p == ']'))) /* array types */
297 return 0;
298 }
299 if (*p != ' ')
300 just_seen_space = 0;
301 if (*p != ':')
302 just_seen_colon = 0;
303 if (*p != '>')
304 just_seen_right = 0;
305 }
306 return 0;
307}
308
309
310/* Return a null-terminated temporary copy of the name of a string token.
311
312 Tokens that refer to names do so with explicit pointer and length,
313 so they can share the storage that lexptr is parsing.
314 When it is necessary to pass a name to a function that expects
315 a null-terminated string, the substring is copied out
316 into a separate block of storage. */
317
318std::string
320{
321 return std::string (token.ptr, token.length);
322}
323
324
325/* As for parse_exp_1, except that if VOID_CONTEXT_P, then
326 no value is expected from the expression. */
327
328static expression_up
329parse_exp_in_context (const char **stringptr, CORE_ADDR pc,
330 const struct block *block,
331 parser_flags flags,
333 std::unique_ptr<expr_completion_base> *completer)
334{
335 const struct language_defn *lang = NULL;
336
337 if (*stringptr == 0 || **stringptr == 0)
338 error_no_arg (_("expression to compute"));
339
340 const struct block *expression_context_block = block;
341 CORE_ADDR expression_context_pc = 0;
342
343 innermost_block_tracker local_tracker;
344 if (tracker == nullptr)
345 tracker = &local_tracker;
346
347 if ((flags & PARSER_LEAVE_BLOCK_ALONE) == 0)
348 {
349 /* If no context specified, try using the current frame, if any. */
350 if (!expression_context_block)
351 expression_context_block
352 = get_selected_block (&expression_context_pc);
353 else if (pc == 0)
354 expression_context_pc = expression_context_block->entry_pc ();
355 else
356 expression_context_pc = pc;
357
358 /* Fall back to using the current source static context, if any. */
359
360 if (!expression_context_block)
361 {
362 struct symtab_and_line cursal
364
365 if (cursal.symtab)
366 expression_context_block
367 = cursal.symtab->compunit ()->blockvector ()->static_block ();
368
369 if (expression_context_block)
370 expression_context_pc = expression_context_block->entry_pc ();
371 }
372 }
373
374 if (language_mode == language_mode_auto && block != NULL)
375 {
376 /* Find the language associated to the given context block.
377 Default to the current language if it can not be determined.
378
379 Note that using the language corresponding to the current frame
380 can sometimes give unexpected results. For instance, this
381 routine is often called several times during the inferior
382 startup phase to re-parse breakpoint expressions after
383 a new shared library has been loaded. The language associated
384 to the current frame at this moment is not relevant for
385 the breakpoint. Using it would therefore be silly, so it seems
386 better to rely on the current language rather than relying on
387 the current frame language to parse the expression. That's why
388 we do the following language detection only if the context block
389 has been specifically provided. */
390 struct symbol *func = block->linkage_function ();
391
392 if (func != NULL)
393 lang = language_def (func->language ());
394 if (lang == NULL || lang->la_language == language_unknown)
395 lang = current_language;
396 }
397 else
398 lang = current_language;
399
400 /* get_current_arch may reset CURRENT_LANGUAGE via select_frame.
401 While we need CURRENT_LANGUAGE to be set to LANG (for lookup_symbol
402 and others called from *.y) ensure CURRENT_LANGUAGE gets restored
403 to the value matching SELECTED_FRAME as set by get_current_arch. */
404
405 parser_state ps (lang, get_current_arch (), expression_context_block,
406 expression_context_pc, flags, *stringptr,
407 completer != nullptr, tracker);
408
411
412 try
413 {
414 lang->parser (&ps);
415 }
416 catch (const gdb_exception_error &except)
417 {
418 /* If parsing for completion, allow this to succeed; but if no
419 expression elements have been written, then there's nothing
420 to do, so fail. */
421 if (! ps.parse_completion || ps.expout->op == nullptr)
422 throw;
423 }
424
425 expression_up result = ps.release ();
426 result->op->set_outermost ();
427
428 if (expressiondebug)
429 result->dump (gdb_stdlog);
430
431 if (completer != nullptr)
432 *completer = std::move (ps.m_completion_state);
433 *stringptr = ps.lexptr;
434 return result;
435}
436
437/* Read an expression from the string *STRINGPTR points to,
438 parse it, and return a pointer to a struct expression that we malloc.
439 Use block BLOCK as the lexical context for variable names;
440 if BLOCK is zero, use the block of the selected stack frame.
441 Meanwhile, advance *STRINGPTR to point after the expression,
442 at the first nonwhite character that is not part of the expression
443 (possibly a null character). FLAGS are passed to the parser. */
444
446parse_exp_1 (const char **stringptr, CORE_ADDR pc, const struct block *block,
447 parser_flags flags, innermost_block_tracker *tracker)
448{
449 return parse_exp_in_context (stringptr, pc, block, flags,
450 tracker, nullptr);
451}
452
453/* Parse STRING as an expression, and complain if this fails to use up
454 all of the contents of STRING. TRACKER, if non-null, will be
455 updated by the parser. FLAGS are passed to the parser. */
456
458parse_expression (const char *string, innermost_block_tracker *tracker,
459 parser_flags flags)
460{
461 expression_up exp = parse_exp_in_context (&string, 0, nullptr, flags,
462 tracker, nullptr);
463 if (*string)
464 error (_("Junk after end of expression."));
465 return exp;
466}
467
468/* Same as parse_expression, but using the given language (LANG)
469 to parse the expression. */
470
472parse_expression_with_language (const char *string, enum language lang)
473{
474 gdb::optional<scoped_restore_current_language> lang_saver;
475 if (current_language->la_language != lang)
476 {
477 lang_saver.emplace ();
478 set_language (lang);
479 }
480
481 return parse_expression (string);
482}
483
484/* Parse STRING as an expression. If the parse is marked for
485 completion, set COMPLETER and return the expression. In all other
486 cases, return NULL. */
487
490 (const char *string,
491 std::unique_ptr<expr_completion_base> *completer)
492{
493 expression_up exp;
494
495 try
496 {
497 exp = parse_exp_in_context (&string, 0, 0, 0, nullptr, completer);
498 }
499 catch (const gdb_exception_error &except)
500 {
501 /* Nothing, EXP remains NULL. */
502 }
503
504 /* If we didn't get a completion result, be sure to also not return
505 an expression to our caller. */
506 if (*completer == nullptr)
507 return nullptr;
508
509 return exp;
510}
511
512/* Parse floating point value P of length LEN.
513 Return false if invalid, true if valid.
514 The successfully parsed number is stored in DATA in
515 target format for floating-point type TYPE.
516
517 NOTE: This accepts the floating point syntax that sscanf accepts. */
518
519bool
520parse_float (const char *p, int len,
521 const struct type *type, gdb_byte *data)
522{
523 return target_float_from_string (data, type, std::string (p, len));
524}
525
526/* Return true if the number N_SIGN * N fits in a type with TYPE_BITS and
527 TYPE_SIGNED_P. N_SIGNED is either 1 or -1. */
528
529bool
530fits_in_type (int n_sign, ULONGEST n, int type_bits, bool type_signed_p)
531{
532 /* Normalize -0. */
533 if (n == 0 && n_sign == -1)
534 n_sign = 1;
535
536 if (n_sign == -1 && !type_signed_p)
537 /* Can't fit a negative number in an unsigned type. */
538 return false;
539
540 if (type_bits > sizeof (ULONGEST) * 8)
541 return true;
542
543 ULONGEST smax = (ULONGEST)1 << (type_bits - 1);
544 if (n_sign == -1)
545 {
546 /* Negative number, signed type. */
547 return (n <= smax);
548 }
549 else if (n_sign == 1 && type_signed_p)
550 {
551 /* Positive number, signed type. */
552 return (n < smax);
553 }
554 else if (n_sign == 1 && !type_signed_p)
555 {
556 /* Positive number, unsigned type. */
557 return ((n >> 1) >> (type_bits - 1)) == 0;
558 }
559 else
560 gdb_assert_not_reached ("");
561}
562
563/* Return true if the number N_SIGN * N fits in a type with TYPE_BITS and
564 TYPE_SIGNED_P. N_SIGNED is either 1 or -1. */
565
566bool
567fits_in_type (int n_sign, const gdb_mpz &n, int type_bits, bool type_signed_p)
568{
569 /* N must be nonnegative. */
570 gdb_assert (n.sgn () >= 0);
571
572 /* Zero always fits. */
573 /* Normalize -0. */
574 if (n.sgn () == 0)
575 return true;
576
577 if (n_sign == -1 && !type_signed_p)
578 /* Can't fit a negative number in an unsigned type. */
579 return false;
580
581 gdb_mpz max = gdb_mpz::pow (2, (type_signed_p
582 ? type_bits - 1
583 : type_bits));
584 if (n_sign == -1)
585 return n <= max;
586 return n < max;
587}
588
589/* This function avoids direct calls to fprintf
590 in the parser generated debug code. */
591void
592parser_fprintf (FILE *x, const char *y, ...)
593{
594 va_list args;
595
596 va_start (args, y);
597 if (x == stderr)
598 gdb_vprintf (gdb_stderr, y, args);
599 else
600 {
601 gdb_printf (gdb_stderr, " Unknown FILE used.\n");
602 gdb_vprintf (gdb_stderr, y, args);
603 }
604 va_end (args);
605}
606
607void _initialize_parse ();
608void
610{
613 _("Set expression debugging."),
614 _("Show expression debugging."),
615 _("When non-zero, the internal representation "
616 "of expressions will be printed."),
617 NULL,
622 _("Set parser debugging."),
623 _("Show parser debugging."),
624 _("When non-zero, expression parser "
625 "tracing will be enabled."),
626 NULL,
629}
const char *const name
struct gdbarch * get_current_arch(void)
Definition arch-utils.c:846
c_string_type_values
Definition c-lang.h:40
innermost_block_tracker_types m_types
Definition expression.h:279
void update(const struct block *b, innermost_block_tracker_types t)
Definition parse.c:78
const struct block * m_innermost_block
Definition expression.h:283
void error_no_arg(const char *why)
Definition cli-cmds.c:206
struct cmd_list_element * showdebuglist
Definition cli-cmds.c:167
struct cmd_list_element * setdebuglist
Definition cli-cmds.c:165
set_show_commands add_setshow_boolean_cmd(const char *name, enum command_class theclass, bool *var, const char *set_doc, const char *show_doc, const char *help_doc, cmd_func_ftype *set_func, show_value_ftype *show_func, struct cmd_list_element **set_list, struct cmd_list_element **show_list)
Definition cli-decode.c:809
set_show_commands add_setshow_zuinteger_cmd(const char *name, enum command_class theclass, unsigned int *var, const char *set_doc, const char *show_doc, const char *help_doc, cmd_func_ftype *set_func, show_value_ftype *show_func, struct cmd_list_element **set_list, struct cmd_list_element **show_list)
@ class_maintenance
Definition command.h:65
language
Definition defs.h:211
@ language_unknown
Definition defs.h:212
std::unique_ptr< expression > expression_up
Definition expression.h:241
@ PARSER_LEAVE_BLOCK_ALONE
Definition expression.h:309
@ INNERMOST_BLOCK_FOR_REGISTERS
Definition expression.h:39
int symbol_read_needs_frame(struct symbol *sym)
Definition findvar.c:388
const struct block * get_selected_block(CORE_ADDR *addr_in_block)
Definition stack.c:2570
type_code
Definition gdbtypes.h:82
mach_port_t kern_return_t mach_port_t mach_msg_type_name_t msgportsPoly mach_port_t kern_return_t pid_t pid mach_port_t kern_return_t mach_port_t task mach_port_t kern_return_t int flags
Definition gnu-nat.c:1861
static void set_language(const char *language)
Definition language.c:140
const struct language_defn * language_def(enum language lang)
Definition language.c:439
const struct language_defn * current_language
Definition language.c:82
language_mode
Definition language.h:717
@ language_mode_auto
Definition language.h:718
int token
Definition m2-exp.c:2422
struct bound_minimal_symbol lookup_bound_minimal_symbol(const char *name)
Definition minsyms.c:481
int have_partial_symbols(void)
Definition objfiles.c:763
int have_full_symbols(void)
Definition objfiles.c:778
bool parse_float(const char *p, int len, const struct type *type, gdb_byte *data)
Definition parse.c:520
expression_up parse_exp_1(const char **stringptr, CORE_ADDR pc, const struct block *block, parser_flags flags, innermost_block_tracker *tracker)
Definition parse.c:446
bool fits_in_type(int n_sign, ULONGEST n, int type_bits, bool type_signed_p)
Definition parse.c:530
expression_up parse_expression_with_language(const char *string, enum language lang)
Definition parse.c:472
std::string copy_name(struct stoken token)
Definition parse.c:319
static unsigned int expressiondebug
Definition parse.c:55
void parser_fprintf(FILE *x, const char *y,...)
Definition parse.c:592
expression_up parse_expression(const char *string, innermost_block_tracker *tracker, parser_flags flags)
Definition parse.c:458
expression_up parse_expression_for_completion(const char *string, std::unique_ptr< expr_completion_base > *completer)
Definition parse.c:490
void _initialize_parse()
Definition parse.c:609
static expression_up parse_exp_in_context(const char **stringptr, CORE_ADDR pc, const struct block *block, parser_flags flags, innermost_block_tracker *tracker, std::unique_ptr< expr_completion_base > *completer)
Definition parse.c:329
static void show_expressiondebug(struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value)
Definition parse.c:57
static bool parser_debug
Definition parse.c:65
static void show_parserdebug(struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value)
Definition parse.c:68
const char * find_template_name_end(const char *p)
Definition parse.c:250
std::string copy_name(struct stoken)
Definition parse.c:319
void(* func)(remote_target *remote, char *)
struct symtab_and_line get_current_source_symtab_and_line(void)
Definition source.c:239
struct symbol * symbol
Definition symtab.h:1533
Definition block.h:109
bool contains(const struct block *a, bool allow_nested=false) const
Definition block.c:68
CORE_ADDR entry_pc() const
Definition block.h:195
struct symbol * linkage_function() const
Definition block.c:91
struct block * static_block()
Definition block.h:405
struct minimal_symbol * minsym
Definition minsyms.h:49
struct blockvector * blockvector()
Definition symtab.h:1847
expression_up expout
Definition parser-defs.h:80
ATTRIBUTE_UNUSED_RESULT expression_up release()
Definition parser-defs.h:52
gdb::unique_xmalloc_ptr< char > m_name
bool complete(struct expression *exp, completion_tracker &tracker) override
Definition parse.c:90
enum type_code m_code
int sgn() const
Definition gmp-utils.h:183
static gdb_mpz pow(unsigned long base, unsigned long exp)
Definition gmp-utils.h:107
enum language la_language
Definition language.h:275
virtual int parser(struct parser_state *ps) const
Definition language.c:596
const struct block *const expression_context_block
bool parse_completion
std::unique_ptr< expr_completion_base > m_completion_state
void push_dollar(struct stoken str)
Definition parse.c:162
void push_symbol(const char *name, block_symbol sym)
Definition parse.c:139
innermost_block_tracker * block_tracker
void mark_completion_tag(enum type_code tag, const char *ptr, int length)
Definition parse.c:112
void push_c_string(int, struct stoken_vector *vec)
Definition parse.c:126
const char * lexptr
void mark_struct_expression(expr::structop_base_operation *op)
Definition parse.c:101
struct typed_stoken * tokens
int length
const char * ptr
struct symtab * symtab
Definition symtab.h:2328
struct compunit_symtab * compunit() const
Definition symtab.h:1677
Definition value.h:130
void collect_symbol_completion_matches_type(completion_tracker &tracker, const char *text, const char *word, enum type_code code)
Definition symtab.c:5968
struct block_symbol lookup_symbol(const char *name, const struct block *block, domain_enum domain, struct field_of_this_result *is_a_field_of_this)
Definition symtab.c:1964
@ VAR_DOMAIN
Definition symtab.h:910
bool target_float_from_string(gdb_byte *addr, const struct type *type, const std::string &string)
int user_reg_map_name_to_regnum(struct gdbarch *gdbarch, const char *name, int len)
Definition user-regs.c:132
void gdb_vprintf(struct ui_file *stream, const char *format, va_list args)
Definition utils.c:1874
void gdb_printf(struct ui_file *stream, const char *format,...)
Definition utils.c:1886
#define gdb_stderr
Definition utils.h:187
#define gdb_stdlog
Definition utils.h:190
struct internalvar * create_internalvar(const char *name)
Definition value.c:1950
struct internalvar * lookup_only_internalvar(const char *name)
Definition value.c:1918