]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/parse.c
Unify gdb printf functions
[thirdparty/binutils-gdb.git] / gdb / parse.c
1 /* Parse expressions for GDB.
2
3 Copyright (C) 1986-2022 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" /* for overlay functions */
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
55 static unsigned int expressiondebug = 0;
56 static void
57 show_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. */
65 bool parser_debug;
66
67 static void
68 show_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 static expression_up parse_exp_in_context (const char **, CORE_ADDR,
76 const struct block *, int,
77 bool, innermost_block_tracker *,
78 expr_completion_state *);
79
80 /* Documented at it's declaration. */
81
82 void
83 innermost_block_tracker::update (const struct block *b,
84 innermost_block_tracker_types t)
85 {
86 if ((m_types & t) != 0
87 && (m_innermost_block == NULL
88 || contained_in (b, m_innermost_block)))
89 m_innermost_block = b;
90 }
91
92 \f
93
94 /* Return the type of MSYMBOL, a minimal symbol of OBJFILE. If
95 ADDRESS_P is not NULL, set it to the MSYMBOL's resolved
96 address. */
97
98 type *
99 find_minsym_type_and_address (minimal_symbol *msymbol,
100 struct objfile *objfile,
101 CORE_ADDR *address_p)
102 {
103 bound_minimal_symbol bound_msym = {msymbol, objfile};
104 struct obj_section *section = msymbol->obj_section (objfile);
105 enum minimal_symbol_type type = MSYMBOL_TYPE (msymbol);
106
107 bool is_tls = (section != NULL
108 && section->the_bfd_section->flags & SEC_THREAD_LOCAL);
109
110 /* The minimal symbol might point to a function descriptor;
111 resolve it to the actual code address instead. */
112 CORE_ADDR addr;
113 if (is_tls)
114 {
115 /* Addresses of TLS symbols are really offsets into a
116 per-objfile/per-thread storage block. */
117 addr = MSYMBOL_VALUE_RAW_ADDRESS (bound_msym.minsym);
118 }
119 else if (msymbol_is_function (objfile, msymbol, &addr))
120 {
121 if (addr != BMSYMBOL_VALUE_ADDRESS (bound_msym))
122 {
123 /* This means we resolved a function descriptor, and we now
124 have an address for a code/text symbol instead of a data
125 symbol. */
126 if (MSYMBOL_TYPE (msymbol) == mst_data_gnu_ifunc)
127 type = mst_text_gnu_ifunc;
128 else
129 type = mst_text;
130 section = NULL;
131 }
132 }
133 else
134 addr = BMSYMBOL_VALUE_ADDRESS (bound_msym);
135
136 if (overlay_debugging)
137 addr = symbol_overlayed_address (addr, section);
138
139 if (is_tls)
140 {
141 /* Skip translation if caller does not need the address. */
142 if (address_p != NULL)
143 *address_p = target_translate_tls_address (objfile, addr);
144 return objfile_type (objfile)->nodebug_tls_symbol;
145 }
146
147 if (address_p != NULL)
148 *address_p = addr;
149
150 switch (type)
151 {
152 case mst_text:
153 case mst_file_text:
154 case mst_solib_trampoline:
155 return objfile_type (objfile)->nodebug_text_symbol;
156
157 case mst_text_gnu_ifunc:
158 return objfile_type (objfile)->nodebug_text_gnu_ifunc_symbol;
159
160 case mst_data:
161 case mst_file_data:
162 case mst_bss:
163 case mst_file_bss:
164 return objfile_type (objfile)->nodebug_data_symbol;
165
166 case mst_slot_got_plt:
167 return objfile_type (objfile)->nodebug_got_plt_symbol;
168
169 default:
170 return objfile_type (objfile)->nodebug_unknown_symbol;
171 }
172 }
173
174 /* See parser-defs.h. */
175
176 void
177 parser_state::mark_struct_expression (expr::structop_base_operation *op)
178 {
179 gdb_assert (parse_completion
180 && (m_completion_state.expout_tag_completion_type
181 == TYPE_CODE_UNDEF));
182 m_completion_state.expout_last_op = op;
183 }
184
185 /* Indicate that the current parser invocation is completing a tag.
186 TAG is the type code of the tag, and PTR and LENGTH represent the
187 start of the tag name. */
188
189 void
190 parser_state::mark_completion_tag (enum type_code tag, const char *ptr,
191 int length)
192 {
193 gdb_assert (parse_completion
194 && (m_completion_state.expout_tag_completion_type
195 == TYPE_CODE_UNDEF)
196 && m_completion_state.expout_completion_name == NULL
197 && m_completion_state.expout_last_op == nullptr);
198 gdb_assert (tag == TYPE_CODE_UNION
199 || tag == TYPE_CODE_STRUCT
200 || tag == TYPE_CODE_ENUM);
201 m_completion_state.expout_tag_completion_type = tag;
202 m_completion_state.expout_completion_name
203 = make_unique_xstrndup (ptr, length);
204 }
205
206 /* See parser-defs.h. */
207
208 void
209 parser_state::push_c_string (int kind, struct stoken_vector *vec)
210 {
211 std::vector<std::string> data (vec->len);
212 for (int i = 0; i < vec->len; ++i)
213 data[i] = std::string (vec->tokens[i].ptr, vec->tokens[i].length);
214
215 push_new<expr::c_string_operation> ((enum c_string_type_values) kind,
216 std::move (data));
217 }
218
219 /* See parser-defs.h. */
220
221 void
222 parser_state::push_symbol (const char *name, block_symbol sym)
223 {
224 if (sym.symbol != nullptr)
225 {
226 if (symbol_read_needs_frame (sym.symbol))
227 block_tracker->update (sym);
228 push_new<expr::var_value_operation> (sym);
229 }
230 else
231 {
232 struct bound_minimal_symbol msymbol = lookup_bound_minimal_symbol (name);
233 if (msymbol.minsym != NULL)
234 push_new<expr::var_msym_value_operation> (msymbol);
235 else if (!have_full_symbols () && !have_partial_symbols ())
236 error (_("No symbol table is loaded. Use the \"file\" command."));
237 else
238 error (_("No symbol \"%s\" in current context."), name);
239 }
240 }
241
242 /* See parser-defs.h. */
243
244 void
245 parser_state::push_dollar (struct stoken str)
246 {
247 struct block_symbol sym;
248 struct bound_minimal_symbol msym;
249 struct internalvar *isym = NULL;
250 std::string copy;
251
252 /* Handle the tokens $digits; also $ (short for $0) and $$ (short for $$1)
253 and $$digits (equivalent to $<-digits> if you could type that). */
254
255 int negate = 0;
256 int i = 1;
257 /* Double dollar means negate the number and add -1 as well.
258 Thus $$ alone means -1. */
259 if (str.length >= 2 && str.ptr[1] == '$')
260 {
261 negate = 1;
262 i = 2;
263 }
264 if (i == str.length)
265 {
266 /* Just dollars (one or two). */
267 i = -negate;
268 goto handle_last;
269 }
270 /* Is the rest of the token digits? */
271 for (; i < str.length; i++)
272 if (!(str.ptr[i] >= '0' && str.ptr[i] <= '9'))
273 break;
274 if (i == str.length)
275 {
276 i = atoi (str.ptr + 1 + negate);
277 if (negate)
278 i = -i;
279 goto handle_last;
280 }
281
282 /* Handle tokens that refer to machine registers:
283 $ followed by a register name. */
284 i = user_reg_map_name_to_regnum (gdbarch (),
285 str.ptr + 1, str.length - 1);
286 if (i >= 0)
287 goto handle_register;
288
289 /* Any names starting with $ are probably debugger internal variables. */
290
291 copy = copy_name (str);
292 isym = lookup_only_internalvar (copy.c_str () + 1);
293 if (isym)
294 {
295 push_new<expr::internalvar_operation> (isym);
296 return;
297 }
298
299 /* On some systems, such as HP-UX and hppa-linux, certain system routines
300 have names beginning with $ or $$. Check for those, first. */
301
302 sym = lookup_symbol (copy.c_str (), NULL, VAR_DOMAIN, NULL);
303 if (sym.symbol)
304 {
305 push_new<expr::var_value_operation> (sym);
306 return;
307 }
308 msym = lookup_bound_minimal_symbol (copy.c_str ());
309 if (msym.minsym)
310 {
311 push_new<expr::var_msym_value_operation> (msym);
312 return;
313 }
314
315 /* Any other names are assumed to be debugger internal variables. */
316
317 push_new<expr::internalvar_operation>
318 (create_internalvar (copy.c_str () + 1));
319 return;
320 handle_last:
321 push_new<expr::last_operation> (i);
322 return;
323 handle_register:
324 str.length--;
325 str.ptr++;
326 push_new<expr::register_operation> (copy_name (str));
327 block_tracker->update (expression_context_block,
328 INNERMOST_BLOCK_FOR_REGISTERS);
329 return;
330 }
331
332 \f
333
334 const char *
335 find_template_name_end (const char *p)
336 {
337 int depth = 1;
338 int just_seen_right = 0;
339 int just_seen_colon = 0;
340 int just_seen_space = 0;
341
342 if (!p || (*p != '<'))
343 return 0;
344
345 while (*++p)
346 {
347 switch (*p)
348 {
349 case '\'':
350 case '\"':
351 case '{':
352 case '}':
353 /* In future, may want to allow these?? */
354 return 0;
355 case '<':
356 depth++; /* start nested template */
357 if (just_seen_colon || just_seen_right || just_seen_space)
358 return 0; /* but not after : or :: or > or space */
359 break;
360 case '>':
361 if (just_seen_colon || just_seen_right)
362 return 0; /* end a (nested?) template */
363 just_seen_right = 1; /* but not after : or :: */
364 if (--depth == 0) /* also disallow >>, insist on > > */
365 return ++p; /* if outermost ended, return */
366 break;
367 case ':':
368 if (just_seen_space || (just_seen_colon > 1))
369 return 0; /* nested class spec coming up */
370 just_seen_colon++; /* we allow :: but not :::: */
371 break;
372 case ' ':
373 break;
374 default:
375 if (!((*p >= 'a' && *p <= 'z') || /* allow token chars */
376 (*p >= 'A' && *p <= 'Z') ||
377 (*p >= '0' && *p <= '9') ||
378 (*p == '_') || (*p == ',') || /* commas for template args */
379 (*p == '&') || (*p == '*') || /* pointer and ref types */
380 (*p == '(') || (*p == ')') || /* function types */
381 (*p == '[') || (*p == ']'))) /* array types */
382 return 0;
383 }
384 if (*p != ' ')
385 just_seen_space = 0;
386 if (*p != ':')
387 just_seen_colon = 0;
388 if (*p != '>')
389 just_seen_right = 0;
390 }
391 return 0;
392 }
393 \f
394
395 /* Return a null-terminated temporary copy of the name of a string token.
396
397 Tokens that refer to names do so with explicit pointer and length,
398 so they can share the storage that lexptr is parsing.
399 When it is necessary to pass a name to a function that expects
400 a null-terminated string, the substring is copied out
401 into a separate block of storage. */
402
403 std::string
404 copy_name (struct stoken token)
405 {
406 return std::string (token.ptr, token.length);
407 }
408 \f
409
410 /* Read an expression from the string *STRINGPTR points to,
411 parse it, and return a pointer to a struct expression that we malloc.
412 Use block BLOCK as the lexical context for variable names;
413 if BLOCK is zero, use the block of the selected stack frame.
414 Meanwhile, advance *STRINGPTR to point after the expression,
415 at the first nonwhite character that is not part of the expression
416 (possibly a null character).
417
418 If COMMA is nonzero, stop if a comma is reached. */
419
420 expression_up
421 parse_exp_1 (const char **stringptr, CORE_ADDR pc, const struct block *block,
422 int comma, innermost_block_tracker *tracker)
423 {
424 return parse_exp_in_context (stringptr, pc, block, comma, false,
425 tracker, nullptr);
426 }
427
428 /* As for parse_exp_1, except that if VOID_CONTEXT_P, then
429 no value is expected from the expression. */
430
431 static expression_up
432 parse_exp_in_context (const char **stringptr, CORE_ADDR pc,
433 const struct block *block,
434 int comma, bool void_context_p,
435 innermost_block_tracker *tracker,
436 expr_completion_state *cstate)
437 {
438 const struct language_defn *lang = NULL;
439
440 if (*stringptr == 0 || **stringptr == 0)
441 error_no_arg (_("expression to compute"));
442
443 const struct block *expression_context_block = block;
444 CORE_ADDR expression_context_pc = 0;
445
446 innermost_block_tracker local_tracker;
447 if (tracker == nullptr)
448 tracker = &local_tracker;
449
450 /* If no context specified, try using the current frame, if any. */
451 if (!expression_context_block)
452 expression_context_block = get_selected_block (&expression_context_pc);
453 else if (pc == 0)
454 expression_context_pc = BLOCK_ENTRY_PC (expression_context_block);
455 else
456 expression_context_pc = pc;
457
458 /* Fall back to using the current source static context, if any. */
459
460 if (!expression_context_block)
461 {
462 struct symtab_and_line cursal = get_current_source_symtab_and_line ();
463 if (cursal.symtab)
464 expression_context_block
465 = BLOCKVECTOR_BLOCK (cursal.symtab->blockvector (),
466 STATIC_BLOCK);
467 if (expression_context_block)
468 expression_context_pc = BLOCK_ENTRY_PC (expression_context_block);
469 }
470
471 if (language_mode == language_mode_auto && block != NULL)
472 {
473 /* Find the language associated to the given context block.
474 Default to the current language if it can not be determined.
475
476 Note that using the language corresponding to the current frame
477 can sometimes give unexpected results. For instance, this
478 routine is often called several times during the inferior
479 startup phase to re-parse breakpoint expressions after
480 a new shared library has been loaded. The language associated
481 to the current frame at this moment is not relevant for
482 the breakpoint. Using it would therefore be silly, so it seems
483 better to rely on the current language rather than relying on
484 the current frame language to parse the expression. That's why
485 we do the following language detection only if the context block
486 has been specifically provided. */
487 struct symbol *func = block_linkage_function (block);
488
489 if (func != NULL)
490 lang = language_def (func->language ());
491 if (lang == NULL || lang->la_language == language_unknown)
492 lang = current_language;
493 }
494 else
495 lang = current_language;
496
497 /* get_current_arch may reset CURRENT_LANGUAGE via select_frame.
498 While we need CURRENT_LANGUAGE to be set to LANG (for lookup_symbol
499 and others called from *.y) ensure CURRENT_LANGUAGE gets restored
500 to the value matching SELECTED_FRAME as set by get_current_arch. */
501
502 parser_state ps (lang, get_current_arch (), expression_context_block,
503 expression_context_pc, comma, *stringptr,
504 cstate != nullptr, tracker, void_context_p);
505
506 scoped_restore_current_language lang_saver;
507 set_language (lang->la_language);
508
509 try
510 {
511 lang->parser (&ps);
512 }
513 catch (const gdb_exception &except)
514 {
515 /* If parsing for completion, allow this to succeed; but if no
516 expression elements have been written, then there's nothing
517 to do, so fail. */
518 if (! ps.parse_completion || ps.expout->op == nullptr)
519 throw;
520 }
521
522 expression_up result = ps.release ();
523 result->op->set_outermost ();
524
525 if (expressiondebug)
526 dump_prefix_expression (result.get (), gdb_stdlog);
527
528 if (cstate != nullptr)
529 *cstate = std::move (ps.m_completion_state);
530 *stringptr = ps.lexptr;
531 return result;
532 }
533
534 /* Parse STRING as an expression, and complain if this fails to use up
535 all of the contents of STRING. TRACKER, if non-null, will be
536 updated by the parser. VOID_CONTEXT_P should be true to indicate
537 that the expression may be expected to return a value with void
538 type. Parsers are free to ignore this, or to use it to help with
539 overload resolution decisions. */
540
541 expression_up
542 parse_expression (const char *string, innermost_block_tracker *tracker,
543 bool void_context_p)
544 {
545 expression_up exp = parse_exp_in_context (&string, 0, nullptr, 0,
546 void_context_p,
547 tracker, nullptr);
548 if (*string)
549 error (_("Junk after end of expression."));
550 return exp;
551 }
552
553 /* Same as parse_expression, but using the given language (LANG)
554 to parse the expression. */
555
556 expression_up
557 parse_expression_with_language (const char *string, enum language lang)
558 {
559 gdb::optional<scoped_restore_current_language> lang_saver;
560 if (current_language->la_language != lang)
561 {
562 lang_saver.emplace ();
563 set_language (lang);
564 }
565
566 return parse_expression (string);
567 }
568
569 /* Parse STRING as an expression. If parsing ends in the middle of a
570 field reference, return the type of the left-hand-side of the
571 reference; furthermore, if the parsing ends in the field name,
572 return the field name in *NAME. If the parsing ends in the middle
573 of a field reference, but the reference is somehow invalid, throw
574 an exception. In all other cases, return NULL. */
575
576 struct type *
577 parse_expression_for_completion (const char *string,
578 gdb::unique_xmalloc_ptr<char> *name,
579 enum type_code *code)
580 {
581 expression_up exp;
582 expr_completion_state cstate;
583
584 try
585 {
586 exp = parse_exp_in_context (&string, 0, 0, 0, false, nullptr, &cstate);
587 }
588 catch (const gdb_exception_error &except)
589 {
590 /* Nothing, EXP remains NULL. */
591 }
592
593 if (exp == NULL)
594 return NULL;
595
596 if (cstate.expout_tag_completion_type != TYPE_CODE_UNDEF)
597 {
598 *code = cstate.expout_tag_completion_type;
599 *name = std::move (cstate.expout_completion_name);
600 return NULL;
601 }
602
603 if (cstate.expout_last_op == nullptr)
604 return nullptr;
605
606 expr::structop_base_operation *op = cstate.expout_last_op;
607 const std::string &fld = op->get_string ();
608 *name = make_unique_xstrdup (fld.c_str ());
609 return value_type (op->evaluate_lhs (exp.get ()));
610 }
611
612 /* Parse floating point value P of length LEN.
613 Return false if invalid, true if valid.
614 The successfully parsed number is stored in DATA in
615 target format for floating-point type TYPE.
616
617 NOTE: This accepts the floating point syntax that sscanf accepts. */
618
619 bool
620 parse_float (const char *p, int len,
621 const struct type *type, gdb_byte *data)
622 {
623 return target_float_from_string (data, type, std::string (p, len));
624 }
625 \f
626 /* This function avoids direct calls to fprintf
627 in the parser generated debug code. */
628 void
629 parser_fprintf (FILE *x, const char *y, ...)
630 {
631 va_list args;
632
633 va_start (args, y);
634 if (x == stderr)
635 gdb_vprintf (gdb_stderr, y, args);
636 else
637 {
638 gdb_printf (gdb_stderr, " Unknown FILE used.\n");
639 gdb_vprintf (gdb_stderr, y, args);
640 }
641 va_end (args);
642 }
643
644 /* Return rue if EXP uses OBJFILE (and will become dangling when
645 OBJFILE is unloaded), otherwise return false. OBJFILE must not be
646 a separate debug info file. */
647
648 bool
649 exp_uses_objfile (struct expression *exp, struct objfile *objfile)
650 {
651 gdb_assert (objfile->separate_debug_objfile_backlink == NULL);
652
653 return exp->op->uses_objfile (objfile);
654 }
655
656 void _initialize_parse ();
657 void
658 _initialize_parse ()
659 {
660 add_setshow_zuinteger_cmd ("expression", class_maintenance,
661 &expressiondebug,
662 _("Set expression debugging."),
663 _("Show expression debugging."),
664 _("When non-zero, the internal representation "
665 "of expressions will be printed."),
666 NULL,
667 show_expressiondebug,
668 &setdebuglist, &showdebuglist);
669 add_setshow_boolean_cmd ("parser", class_maintenance,
670 &parser_debug,
671 _("Set parser debugging."),
672 _("Show parser debugging."),
673 _("When non-zero, expression parser "
674 "tracing will be enabled."),
675 NULL,
676 show_parserdebug,
677 &setdebuglist, &showdebuglist);
678 }