Automatic date update in version.in
[binutils-gdb.git] / gdb / varobj.c
blob0683af1991eeb23b669629e07307c2ed62fe6f89
1 /* Implementation of the GDB variable objects API.
3 Copyright (C) 1999-2022 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 #include "defs.h"
19 #include "value.h"
20 #include "expression.h"
21 #include "frame.h"
22 #include "language.h"
23 #include "gdbcmd.h"
24 #include "block.h"
25 #include "valprint.h"
26 #include "gdbsupport/gdb_regex.h"
28 #include "varobj.h"
29 #include "gdbthread.h"
30 #include "inferior.h"
31 #include "varobj-iter.h"
32 #include "parser-defs.h"
33 #include "gdbarch.h"
34 #include <algorithm>
35 #include "observable.h"
37 #if HAVE_PYTHON
38 #include "python/python.h"
39 #include "python/python-internal.h"
40 #else
41 typedef int PyObject;
42 #endif
44 /* See varobj.h. */
46 unsigned int varobjdebug = 0;
47 static void
48 show_varobjdebug (struct ui_file *file, int from_tty,
49 struct cmd_list_element *c, const char *value)
51 gdb_printf (file, _("Varobj debugging is %s.\n"), value);
54 /* String representations of gdb's format codes. */
55 const char *varobj_format_string[] =
56 { "natural", "binary", "decimal", "hexadecimal", "octal", "zero-hexadecimal" };
58 /* True if we want to allow Python-based pretty-printing. */
59 static bool pretty_printing = false;
61 void
62 varobj_enable_pretty_printing (void)
64 pretty_printing = true;
67 /* Data structures */
69 /* Every root variable has one of these structures saved in its
70 varobj. */
71 struct varobj_root
73 /* The expression for this parent. */
74 expression_up exp;
76 /* Cached arch from exp, for use in case exp gets invalidated. */
77 struct gdbarch *gdbarch = nullptr;
79 /* Cached language from exp, for use in case exp gets invalidated. */
80 const struct language_defn *language_defn = nullptr;
82 /* Block for which this expression is valid. */
83 const struct block *valid_block = NULL;
85 /* The frame for this expression. This field is set iff valid_block is
86 not NULL. */
87 struct frame_id frame = null_frame_id;
89 /* The global thread ID that this varobj_root belongs to. This field
90 is only valid if valid_block is not NULL.
91 When not 0, indicates which thread 'frame' belongs to.
92 When 0, indicates that the thread list was empty when the varobj_root
93 was created. */
94 int thread_id = 0;
96 /* If true, the -var-update always recomputes the value in the
97 current thread and frame. Otherwise, variable object is
98 always updated in the specific scope/thread/frame. */
99 bool floating = false;
101 /* Flag that indicates validity: set to false when this varobj_root refers
102 to symbols that do not exist anymore. */
103 bool is_valid = true;
105 /* Set to true if the varobj was created as tracking a global. */
106 bool global = false;
108 /* Language-related operations for this variable and its
109 children. */
110 const struct lang_varobj_ops *lang_ops = NULL;
112 /* The varobj for this root node. */
113 struct varobj *rootvar = NULL;
116 /* Dynamic part of varobj. */
118 struct varobj_dynamic
120 /* Whether the children of this varobj were requested. This field is
121 used to decide if dynamic varobj should recompute their children.
122 In the event that the frontend never asked for the children, we
123 can avoid that. */
124 bool children_requested = false;
126 /* The pretty-printer constructor. If NULL, then the default
127 pretty-printer will be looked up. If None, then no
128 pretty-printer will be installed. */
129 PyObject *constructor = NULL;
131 /* The pretty-printer that has been constructed. If NULL, then a
132 new printer object is needed, and one will be constructed. */
133 PyObject *pretty_printer = NULL;
135 /* The iterator returned by the printer's 'children' method, or NULL
136 if not available. */
137 std::unique_ptr<varobj_iter> child_iter;
139 /* We request one extra item from the iterator, so that we can
140 report to the caller whether there are more items than we have
141 already reported. However, we don't want to install this value
142 when we read it, because that will mess up future updates. So,
143 we stash it here instead. */
144 std::unique_ptr<varobj_item> saved_item;
147 /* Private function prototypes */
149 /* Helper functions for the above subcommands. */
151 static int delete_variable (struct varobj *, bool);
153 static void delete_variable_1 (int *, struct varobj *, bool, bool);
155 static void install_variable (struct varobj *);
157 static void uninstall_variable (struct varobj *);
159 static struct varobj *create_child (struct varobj *, int, std::string &);
161 static struct varobj *
162 create_child_with_value (struct varobj *parent, int index,
163 struct varobj_item *item);
165 /* Utility routines */
167 static enum varobj_display_formats variable_default_display (struct varobj *);
169 static bool update_type_if_necessary (struct varobj *var,
170 struct value *new_value);
172 static bool install_new_value (struct varobj *var, struct value *value,
173 bool initial);
175 /* Language-specific routines. */
177 static int number_of_children (const struct varobj *);
179 static std::string name_of_variable (const struct varobj *);
181 static std::string name_of_child (struct varobj *, int);
183 static struct value *value_of_root (struct varobj **var_handle, bool *);
185 static struct value *value_of_child (const struct varobj *parent, int index);
187 static std::string my_value_of_variable (struct varobj *var,
188 enum varobj_display_formats format);
190 static bool is_root_p (const struct varobj *var);
192 static struct varobj *varobj_add_child (struct varobj *var,
193 struct varobj_item *item);
195 /* Private data */
197 /* Mappings of varobj_display_formats enums to gdb's format codes. */
198 static int format_code[] = { 0, 't', 'd', 'x', 'o', 'z' };
200 /* List of root variable objects. */
201 static std::list<struct varobj_root *> rootlist;
203 /* Pointer to the varobj hash table (built at run time). */
204 static htab_t varobj_table;
208 /* API Implementation */
209 static bool
210 is_root_p (const struct varobj *var)
212 return (var->root->rootvar == var);
215 #ifdef HAVE_PYTHON
217 /* See python-internal.h. */
218 gdbpy_enter_varobj::gdbpy_enter_varobj (const struct varobj *var)
219 : gdbpy_enter (var->root->gdbarch, var->root->language_defn)
223 #endif
225 /* Return the full FRAME which corresponds to the given CORE_ADDR
226 or NULL if no FRAME on the chain corresponds to CORE_ADDR. */
228 static struct frame_info *
229 find_frame_addr_in_frame_chain (CORE_ADDR frame_addr)
231 struct frame_info *frame = NULL;
233 if (frame_addr == (CORE_ADDR) 0)
234 return NULL;
236 for (frame = get_current_frame ();
237 frame != NULL;
238 frame = get_prev_frame (frame))
240 /* The CORE_ADDR we get as argument was parsed from a string GDB
241 output as $fp. This output got truncated to gdbarch_addr_bit.
242 Truncate the frame base address in the same manner before
243 comparing it against our argument. */
244 CORE_ADDR frame_base = get_frame_base_address (frame);
245 int addr_bit = gdbarch_addr_bit (get_frame_arch (frame));
247 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
248 frame_base &= ((CORE_ADDR) 1 << addr_bit) - 1;
250 if (frame_base == frame_addr)
251 return frame;
254 return NULL;
257 /* Creates a varobj (not its children). */
259 struct varobj *
260 varobj_create (const char *objname,
261 const char *expression, CORE_ADDR frame, enum varobj_type type)
263 /* Fill out a varobj structure for the (root) variable being constructed. */
264 std::unique_ptr<varobj> var (new varobj (new varobj_root));
266 if (expression != NULL)
268 struct frame_info *fi;
269 struct frame_id old_id = null_frame_id;
270 const struct block *block;
271 const char *p;
272 struct value *value = NULL;
273 CORE_ADDR pc;
275 /* Parse and evaluate the expression, filling in as much of the
276 variable's data as possible. */
278 if (has_stack_frames ())
280 /* Allow creator to specify context of variable. */
281 if ((type == USE_CURRENT_FRAME) || (type == USE_SELECTED_FRAME))
282 fi = get_selected_frame (NULL);
283 else
284 /* FIXME: cagney/2002-11-23: This code should be doing a
285 lookup using the frame ID and not just the frame's
286 ``address''. This, of course, means an interface
287 change. However, with out that interface change ISAs,
288 such as the ia64 with its two stacks, won't work.
289 Similar goes for the case where there is a frameless
290 function. */
291 fi = find_frame_addr_in_frame_chain (frame);
293 else
294 fi = NULL;
296 if (type == USE_SELECTED_FRAME)
297 var->root->floating = true;
299 pc = 0;
300 block = NULL;
301 if (fi != NULL)
303 block = get_frame_block (fi, 0);
304 pc = get_frame_pc (fi);
307 p = expression;
309 innermost_block_tracker tracker (INNERMOST_BLOCK_FOR_SYMBOLS
310 | INNERMOST_BLOCK_FOR_REGISTERS);
311 /* Wrap the call to parse expression, so we can
312 return a sensible error. */
315 var->root->exp = parse_exp_1 (&p, pc, block, 0, &tracker);
317 /* Cache gdbarch and language_defn as they might be used even
318 after var is invalidated and var->root->exp cleared. */
319 var->root->gdbarch = var->root->exp->gdbarch;
320 var->root->language_defn = var->root->exp->language_defn;
323 catch (const gdb_exception_error &except)
325 return NULL;
328 /* Don't allow variables to be created for types. */
329 enum exp_opcode opcode = var->root->exp->first_opcode ();
330 if (opcode == OP_TYPE
331 || opcode == OP_TYPEOF
332 || opcode == OP_DECLTYPE)
334 gdb_printf (gdb_stderr, "Attempt to use a type name"
335 " as an expression.\n");
336 return NULL;
339 var->format = variable_default_display (var.get ());
340 var->root->valid_block =
341 var->root->floating ? NULL : tracker.block ();
342 var->root->global
343 = var->root->floating ? false : var->root->valid_block == nullptr;
344 var->name = expression;
345 /* For a root var, the name and the expr are the same. */
346 var->path_expr = expression;
348 /* When the frame is different from the current frame,
349 we must select the appropriate frame before parsing
350 the expression, otherwise the value will not be current.
351 Since select_frame is so benign, just call it for all cases. */
352 if (var->root->valid_block)
354 /* User could specify explicit FRAME-ADDR which was not found but
355 EXPRESSION is frame specific and we would not be able to evaluate
356 it correctly next time. With VALID_BLOCK set we must also set
357 FRAME and THREAD_ID. */
358 if (fi == NULL)
359 error (_("Failed to find the specified frame"));
361 var->root->frame = get_frame_id (fi);
362 var->root->thread_id = inferior_thread ()->global_num;
363 old_id = get_frame_id (get_selected_frame (NULL));
364 select_frame (fi);
367 /* We definitely need to catch errors here.
368 If evaluate_expression succeeds we got the value we wanted.
369 But if it fails, we still go on with a call to evaluate_type(). */
372 value = evaluate_expression (var->root->exp.get ());
374 catch (const gdb_exception_error &except)
376 /* Error getting the value. Try to at least get the
377 right type. */
378 struct value *type_only_value = evaluate_type (var->root->exp.get ());
380 var->type = value_type (type_only_value);
383 if (value != NULL)
385 int real_type_found = 0;
387 var->type = value_actual_type (value, 0, &real_type_found);
388 if (real_type_found)
389 value = value_cast (var->type, value);
392 /* Set language info */
393 var->root->lang_ops = var->root->exp->language_defn->varobj_ops ();
395 install_new_value (var.get (), value, 1 /* Initial assignment */);
397 /* Set ourselves as our root. */
398 var->root->rootvar = var.get ();
400 /* Reset the selected frame. */
401 if (frame_id_p (old_id))
402 select_frame (frame_find_by_id (old_id));
405 /* If the variable object name is null, that means this
406 is a temporary variable, so don't install it. */
408 if ((var != NULL) && (objname != NULL))
410 var->obj_name = objname;
411 install_variable (var.get ());
414 return var.release ();
417 /* Generates an unique name that can be used for a varobj. */
419 std::string
420 varobj_gen_name (void)
422 static int id = 0;
424 /* Generate a name for this object. */
425 id++;
426 return string_printf ("var%d", id);
429 /* Given an OBJNAME, returns the pointer to the corresponding varobj. Call
430 error if OBJNAME cannot be found. */
432 struct varobj *
433 varobj_get_handle (const char *objname)
435 varobj *var = (varobj *) htab_find_with_hash (varobj_table, objname,
436 htab_hash_string (objname));
438 if (var == NULL)
439 error (_("Variable object not found"));
441 return var;
444 /* Given the handle, return the name of the object. */
446 const char *
447 varobj_get_objname (const struct varobj *var)
449 return var->obj_name.c_str ();
452 /* Given the handle, return the expression represented by the
453 object. */
455 std::string
456 varobj_get_expression (const struct varobj *var)
458 return name_of_variable (var);
461 /* See varobj.h. */
464 varobj_delete (struct varobj *var, bool only_children)
466 return delete_variable (var, only_children);
469 #if HAVE_PYTHON
471 /* Convenience function for varobj_set_visualizer. Instantiate a
472 pretty-printer for a given value. */
473 static PyObject *
474 instantiate_pretty_printer (PyObject *constructor, struct value *value)
476 gdbpy_ref<> val_obj (value_to_value_object (value));
477 if (val_obj == nullptr)
478 return NULL;
480 return PyObject_CallFunctionObjArgs (constructor, val_obj.get (), NULL);
483 #endif
485 /* Set/Get variable object display format. */
487 enum varobj_display_formats
488 varobj_set_display_format (struct varobj *var,
489 enum varobj_display_formats format)
491 switch (format)
493 case FORMAT_NATURAL:
494 case FORMAT_BINARY:
495 case FORMAT_DECIMAL:
496 case FORMAT_HEXADECIMAL:
497 case FORMAT_OCTAL:
498 case FORMAT_ZHEXADECIMAL:
499 var->format = format;
500 break;
502 default:
503 var->format = variable_default_display (var);
506 if (varobj_value_is_changeable_p (var)
507 && var->value != nullptr && !value_lazy (var->value.get ()))
509 var->print_value = varobj_value_get_print_value (var->value.get (),
510 var->format, var);
513 return var->format;
516 enum varobj_display_formats
517 varobj_get_display_format (const struct varobj *var)
519 return var->format;
522 gdb::unique_xmalloc_ptr<char>
523 varobj_get_display_hint (const struct varobj *var)
525 gdb::unique_xmalloc_ptr<char> result;
527 #if HAVE_PYTHON
528 if (!gdb_python_initialized)
529 return NULL;
531 gdbpy_enter_varobj enter_py (var);
533 if (var->dynamic->pretty_printer != NULL)
534 result = gdbpy_get_display_hint (var->dynamic->pretty_printer);
535 #endif
537 return result;
540 /* Return true if the varobj has items after TO, false otherwise. */
542 bool
543 varobj_has_more (const struct varobj *var, int to)
545 if (var->children.size () > to)
546 return true;
548 return ((to == -1 || var->children.size () == to)
549 && (var->dynamic->saved_item != NULL));
552 /* If the variable object is bound to a specific thread, that
553 is its evaluation can always be done in context of a frame
554 inside that thread, returns GDB id of the thread -- which
555 is always positive. Otherwise, returns -1. */
557 varobj_get_thread_id (const struct varobj *var)
559 if (var->root->valid_block && var->root->thread_id > 0)
560 return var->root->thread_id;
561 else
562 return -1;
565 void
566 varobj_set_frozen (struct varobj *var, bool frozen)
568 /* When a variable is unfrozen, we don't fetch its value.
569 The 'not_fetched' flag remains set, so next -var-update
570 won't complain.
572 We don't fetch the value, because for structures the client
573 should do -var-update anyway. It would be bad to have different
574 client-size logic for structure and other types. */
575 var->frozen = frozen;
578 bool
579 varobj_get_frozen (const struct varobj *var)
581 return var->frozen;
584 /* A helper function that updates the contents of FROM and TO based on the
585 size of the vector CHILDREN. If the contents of either FROM or TO are
586 negative the entire range is used. */
588 void
589 varobj_restrict_range (const std::vector<varobj *> &children,
590 int *from, int *to)
592 int len = children.size ();
594 if (*from < 0 || *to < 0)
596 *from = 0;
597 *to = len;
599 else
601 if (*from > len)
602 *from = len;
603 if (*to > len)
604 *to = len;
605 if (*from > *to)
606 *from = *to;
610 /* A helper for update_dynamic_varobj_children that installs a new
611 child when needed. */
613 static void
614 install_dynamic_child (struct varobj *var,
615 std::vector<varobj *> *changed,
616 std::vector<varobj *> *type_changed,
617 std::vector<varobj *> *newobj,
618 std::vector<varobj *> *unchanged,
619 bool *cchanged,
620 int index,
621 struct varobj_item *item)
623 if (var->children.size () < index + 1)
625 /* There's no child yet. */
626 struct varobj *child = varobj_add_child (var, item);
628 if (newobj != NULL)
630 newobj->push_back (child);
631 *cchanged = true;
634 else
636 varobj *existing = var->children[index];
637 bool type_updated = update_type_if_necessary (existing,
638 item->value.get ());
640 if (type_updated)
642 if (type_changed != NULL)
643 type_changed->push_back (existing);
645 if (install_new_value (existing, item->value.get (), 0))
647 if (!type_updated && changed != NULL)
648 changed->push_back (existing);
650 else if (!type_updated && unchanged != NULL)
651 unchanged->push_back (existing);
655 #if HAVE_PYTHON
657 static bool
658 dynamic_varobj_has_child_method (const struct varobj *var)
660 PyObject *printer = var->dynamic->pretty_printer;
662 if (!gdb_python_initialized)
663 return false;
665 gdbpy_enter_varobj enter_py (var);
666 return PyObject_HasAttr (printer, gdbpy_children_cst);
668 #endif
670 /* A factory for creating dynamic varobj's iterators. Returns an
671 iterator object suitable for iterating over VAR's children. */
673 static std::unique_ptr<varobj_iter>
674 varobj_get_iterator (struct varobj *var)
676 #if HAVE_PYTHON
677 if (var->dynamic->pretty_printer)
679 value_print_options opts;
680 varobj_formatted_print_options (&opts, var->format);
681 return py_varobj_get_iterator (var, var->dynamic->pretty_printer, &opts);
683 #endif
685 gdb_assert_not_reached ("requested an iterator from a non-dynamic varobj");
688 static bool
689 update_dynamic_varobj_children (struct varobj *var,
690 std::vector<varobj *> *changed,
691 std::vector<varobj *> *type_changed,
692 std::vector<varobj *> *newobj,
693 std::vector<varobj *> *unchanged,
694 bool *cchanged,
695 bool update_children,
696 int from,
697 int to)
699 int i;
701 *cchanged = false;
703 if (update_children || var->dynamic->child_iter == NULL)
705 var->dynamic->child_iter = varobj_get_iterator (var);
706 var->dynamic->saved_item.reset (nullptr);
708 i = 0;
710 if (var->dynamic->child_iter == NULL)
711 return false;
713 else
714 i = var->children.size ();
716 /* We ask for one extra child, so that MI can report whether there
717 are more children. */
718 for (; to < 0 || i < to + 1; ++i)
720 std::unique_ptr<varobj_item> item;
722 /* See if there was a leftover from last time. */
723 if (var->dynamic->saved_item != NULL)
724 item = std::move (var->dynamic->saved_item);
725 else
726 item = var->dynamic->child_iter->next ();
728 if (item == NULL)
730 /* Iteration is done. Remove iterator from VAR. */
731 var->dynamic->child_iter.reset (nullptr);
732 break;
734 /* We don't want to push the extra child on any report list. */
735 if (to < 0 || i < to)
737 bool can_mention = from < 0 || i >= from;
739 install_dynamic_child (var, can_mention ? changed : NULL,
740 can_mention ? type_changed : NULL,
741 can_mention ? newobj : NULL,
742 can_mention ? unchanged : NULL,
743 can_mention ? cchanged : NULL, i,
744 item.get ());
746 else
748 var->dynamic->saved_item = std::move (item);
750 /* We want to truncate the child list just before this
751 element. */
752 break;
756 if (i < var->children.size ())
758 *cchanged = true;
759 for (int j = i; j < var->children.size (); ++j)
760 varobj_delete (var->children[j], 0);
762 var->children.resize (i);
765 /* If there are fewer children than requested, note that the list of
766 children changed. */
767 if (to >= 0 && var->children.size () < to)
768 *cchanged = true;
770 var->num_children = var->children.size ();
772 return true;
776 varobj_get_num_children (struct varobj *var)
778 if (var->num_children == -1)
780 if (varobj_is_dynamic_p (var))
782 bool dummy;
784 /* If we have a dynamic varobj, don't report -1 children.
785 So, try to fetch some children first. */
786 update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL, &dummy,
787 false, 0, 0);
789 else
790 var->num_children = number_of_children (var);
793 return var->num_children >= 0 ? var->num_children : 0;
796 /* Creates a list of the immediate children of a variable object;
797 the return code is the number of such children or -1 on error. */
799 const std::vector<varobj *> &
800 varobj_list_children (struct varobj *var, int *from, int *to)
802 var->dynamic->children_requested = true;
804 if (varobj_is_dynamic_p (var))
806 bool children_changed;
808 /* This, in theory, can result in the number of children changing without
809 frontend noticing. But well, calling -var-list-children on the same
810 varobj twice is not something a sane frontend would do. */
811 update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL,
812 &children_changed, false, 0, *to);
813 varobj_restrict_range (var->children, from, to);
814 return var->children;
817 if (var->num_children == -1)
818 var->num_children = number_of_children (var);
820 /* If that failed, give up. */
821 if (var->num_children == -1)
822 return var->children;
824 /* If we're called when the list of children is not yet initialized,
825 allocate enough elements in it. */
826 while (var->children.size () < var->num_children)
827 var->children.push_back (NULL);
829 for (int i = 0; i < var->num_children; i++)
831 if (var->children[i] == NULL)
833 /* Either it's the first call to varobj_list_children for
834 this variable object, and the child was never created,
835 or it was explicitly deleted by the client. */
836 std::string name = name_of_child (var, i);
837 var->children[i] = create_child (var, i, name);
841 varobj_restrict_range (var->children, from, to);
842 return var->children;
845 static struct varobj *
846 varobj_add_child (struct varobj *var, struct varobj_item *item)
848 varobj *v = create_child_with_value (var, var->children.size (), item);
850 var->children.push_back (v);
852 return v;
855 /* Obtain the type of an object Variable as a string similar to the one gdb
856 prints on the console. The caller is responsible for freeing the string.
859 std::string
860 varobj_get_type (struct varobj *var)
862 /* For the "fake" variables, do not return a type. (Its type is
863 NULL, too.)
864 Do not return a type for invalid variables as well. */
865 if (CPLUS_FAKE_CHILD (var) || !var->root->is_valid)
866 return std::string ();
868 return type_to_string (var->type);
871 /* Obtain the type of an object variable. */
873 struct type *
874 varobj_get_gdb_type (const struct varobj *var)
876 return var->type;
879 /* Is VAR a path expression parent, i.e., can it be used to construct
880 a valid path expression? */
882 static bool
883 is_path_expr_parent (const struct varobj *var)
885 gdb_assert (var->root->lang_ops->is_path_expr_parent != NULL);
886 return var->root->lang_ops->is_path_expr_parent (var);
889 /* Is VAR a path expression parent, i.e., can it be used to construct
890 a valid path expression? By default we assume any VAR can be a path
891 parent. */
893 bool
894 varobj_default_is_path_expr_parent (const struct varobj *var)
896 return true;
899 /* Return the path expression parent for VAR. */
901 const struct varobj *
902 varobj_get_path_expr_parent (const struct varobj *var)
904 const struct varobj *parent = var;
906 while (!is_root_p (parent) && !is_path_expr_parent (parent))
907 parent = parent->parent;
909 /* Computation of full rooted expression for children of dynamic
910 varobjs is not supported. */
911 if (varobj_is_dynamic_p (parent))
912 error (_("Invalid variable object (child of a dynamic varobj)"));
914 return parent;
917 /* Return a pointer to the full rooted expression of varobj VAR.
918 If it has not been computed yet, compute it. */
920 const char *
921 varobj_get_path_expr (const struct varobj *var)
923 if (var->path_expr.empty ())
925 /* For root varobjs, we initialize path_expr
926 when creating varobj, so here it should be
927 child varobj. */
928 struct varobj *mutable_var = (struct varobj *) var;
929 gdb_assert (!is_root_p (var));
931 mutable_var->path_expr = (*var->root->lang_ops->path_expr_of_child) (var);
934 return var->path_expr.c_str ();
937 const struct language_defn *
938 varobj_get_language (const struct varobj *var)
940 return var->root->exp->language_defn;
944 varobj_get_attributes (const struct varobj *var)
946 int attributes = 0;
948 if (varobj_editable_p (var))
949 /* FIXME: define masks for attributes. */
950 attributes |= 0x00000001; /* Editable */
952 return attributes;
955 /* Return true if VAR is a dynamic varobj. */
957 bool
958 varobj_is_dynamic_p (const struct varobj *var)
960 return var->dynamic->pretty_printer != NULL;
963 std::string
964 varobj_get_formatted_value (struct varobj *var,
965 enum varobj_display_formats format)
967 return my_value_of_variable (var, format);
970 std::string
971 varobj_get_value (struct varobj *var)
973 return my_value_of_variable (var, var->format);
976 /* Set the value of an object variable (if it is editable) to the
977 value of the given expression. */
978 /* Note: Invokes functions that can call error(). */
980 bool
981 varobj_set_value (struct varobj *var, const char *expression)
983 struct value *val = NULL; /* Initialize to keep gcc happy. */
984 /* The argument "expression" contains the variable's new value.
985 We need to first construct a legal expression for this -- ugh! */
986 /* Does this cover all the bases? */
987 struct value *value = NULL; /* Initialize to keep gcc happy. */
988 int saved_input_radix = input_radix;
989 const char *s = expression;
991 gdb_assert (varobj_editable_p (var));
993 input_radix = 10; /* ALWAYS reset to decimal temporarily. */
994 expression_up exp = parse_exp_1 (&s, 0, 0, 0);
997 value = evaluate_expression (exp.get ());
1000 catch (const gdb_exception_error &except)
1002 /* We cannot proceed without a valid expression. */
1003 return false;
1006 /* All types that are editable must also be changeable. */
1007 gdb_assert (varobj_value_is_changeable_p (var));
1009 /* The value of a changeable variable object must not be lazy. */
1010 gdb_assert (!value_lazy (var->value.get ()));
1012 /* Need to coerce the input. We want to check if the
1013 value of the variable object will be different
1014 after assignment, and the first thing value_assign
1015 does is coerce the input.
1016 For example, if we are assigning an array to a pointer variable we
1017 should compare the pointer with the array's address, not with the
1018 array's content. */
1019 value = coerce_array (value);
1021 /* The new value may be lazy. value_assign, or
1022 rather value_contents, will take care of this. */
1025 val = value_assign (var->value.get (), value);
1028 catch (const gdb_exception_error &except)
1030 return false;
1033 /* If the value has changed, record it, so that next -var-update can
1034 report this change. If a variable had a value of '1', we've set it
1035 to '333' and then set again to '1', when -var-update will report this
1036 variable as changed -- because the first assignment has set the
1037 'updated' flag. There's no need to optimize that, because return value
1038 of -var-update should be considered an approximation. */
1039 var->updated = install_new_value (var, val, false /* Compare values. */);
1040 input_radix = saved_input_radix;
1041 return true;
1044 #if HAVE_PYTHON
1046 /* A helper function to install a constructor function and visualizer
1047 in a varobj_dynamic. */
1049 static void
1050 install_visualizer (struct varobj_dynamic *var, PyObject *constructor,
1051 PyObject *visualizer)
1053 Py_XDECREF (var->constructor);
1054 var->constructor = constructor;
1056 Py_XDECREF (var->pretty_printer);
1057 var->pretty_printer = visualizer;
1059 var->child_iter.reset (nullptr);
1062 /* Install the default visualizer for VAR. */
1064 static void
1065 install_default_visualizer (struct varobj *var)
1067 /* Do not install a visualizer on a CPLUS_FAKE_CHILD. */
1068 if (CPLUS_FAKE_CHILD (var))
1069 return;
1071 if (pretty_printing)
1073 gdbpy_ref<> pretty_printer;
1075 if (var->value != nullptr)
1077 pretty_printer = gdbpy_get_varobj_pretty_printer (var->value.get ());
1078 if (pretty_printer == nullptr)
1080 gdbpy_print_stack ();
1081 error (_("Cannot instantiate printer for default visualizer"));
1085 if (pretty_printer == Py_None)
1086 pretty_printer.reset (nullptr);
1088 install_visualizer (var->dynamic, NULL, pretty_printer.release ());
1092 /* Instantiate and install a visualizer for VAR using CONSTRUCTOR to
1093 make a new object. */
1095 static void
1096 construct_visualizer (struct varobj *var, PyObject *constructor)
1098 PyObject *pretty_printer;
1100 /* Do not install a visualizer on a CPLUS_FAKE_CHILD. */
1101 if (CPLUS_FAKE_CHILD (var))
1102 return;
1104 Py_INCREF (constructor);
1105 if (constructor == Py_None)
1106 pretty_printer = NULL;
1107 else
1109 pretty_printer = instantiate_pretty_printer (constructor,
1110 var->value.get ());
1111 if (! pretty_printer)
1113 gdbpy_print_stack ();
1114 Py_DECREF (constructor);
1115 constructor = Py_None;
1116 Py_INCREF (constructor);
1119 if (pretty_printer == Py_None)
1121 Py_DECREF (pretty_printer);
1122 pretty_printer = NULL;
1126 install_visualizer (var->dynamic, constructor, pretty_printer);
1129 #endif /* HAVE_PYTHON */
1131 /* A helper function for install_new_value. This creates and installs
1132 a visualizer for VAR, if appropriate. */
1134 static void
1135 install_new_value_visualizer (struct varobj *var)
1137 #if HAVE_PYTHON
1138 /* If the constructor is None, then we want the raw value. If VAR
1139 does not have a value, just skip this. */
1140 if (!gdb_python_initialized)
1141 return;
1143 if (var->dynamic->constructor != Py_None && var->value != NULL)
1145 gdbpy_enter_varobj enter_py (var);
1147 if (var->dynamic->constructor == NULL)
1148 install_default_visualizer (var);
1149 else
1150 construct_visualizer (var, var->dynamic->constructor);
1152 #else
1153 /* Do nothing. */
1154 #endif
1157 /* When using RTTI to determine variable type it may be changed in runtime when
1158 the variable value is changed. This function checks whether type of varobj
1159 VAR will change when a new value NEW_VALUE is assigned and if it is so
1160 updates the type of VAR. */
1162 static bool
1163 update_type_if_necessary (struct varobj *var, struct value *new_value)
1165 if (new_value)
1167 struct value_print_options opts;
1169 get_user_print_options (&opts);
1170 if (opts.objectprint)
1172 struct type *new_type = value_actual_type (new_value, 0, 0);
1173 std::string new_type_str = type_to_string (new_type);
1174 std::string curr_type_str = varobj_get_type (var);
1176 /* Did the type name change? */
1177 if (curr_type_str != new_type_str)
1179 var->type = new_type;
1181 /* This information may be not valid for a new type. */
1182 varobj_delete (var, 1);
1183 var->children.clear ();
1184 var->num_children = -1;
1185 return true;
1190 return false;
1193 /* Assign a new value to a variable object. If INITIAL is true,
1194 this is the first assignment after the variable object was just
1195 created, or changed type. In that case, just assign the value
1196 and return false.
1197 Otherwise, assign the new value, and return true if the value is
1198 different from the current one, false otherwise. The comparison is
1199 done on textual representation of value. Therefore, some types
1200 need not be compared. E.g. for structures the reported value is
1201 always "{...}", so no comparison is necessary here. If the old
1202 value was NULL and new one is not, or vice versa, we always return true.
1204 The VALUE parameter should not be released -- the function will
1205 take care of releasing it when needed. */
1206 static bool
1207 install_new_value (struct varobj *var, struct value *value, bool initial)
1209 bool changeable;
1210 bool need_to_fetch;
1211 bool changed = false;
1212 bool intentionally_not_fetched = false;
1214 /* We need to know the varobj's type to decide if the value should
1215 be fetched or not. C++ fake children (public/protected/private)
1216 don't have a type. */
1217 gdb_assert (var->type || CPLUS_FAKE_CHILD (var));
1218 changeable = varobj_value_is_changeable_p (var);
1220 /* If the type has custom visualizer, we consider it to be always
1221 changeable. FIXME: need to make sure this behaviour will not
1222 mess up read-sensitive values. */
1223 if (var->dynamic->pretty_printer != NULL)
1224 changeable = true;
1226 need_to_fetch = changeable;
1228 /* We are not interested in the address of references, and given
1229 that in C++ a reference is not rebindable, it cannot
1230 meaningfully change. So, get hold of the real value. */
1231 if (value)
1232 value = coerce_ref (value);
1234 if (var->type && var->type->code () == TYPE_CODE_UNION)
1235 /* For unions, we need to fetch the value implicitly because
1236 of implementation of union member fetch. When gdb
1237 creates a value for a field and the value of the enclosing
1238 structure is not lazy, it immediately copies the necessary
1239 bytes from the enclosing values. If the enclosing value is
1240 lazy, the call to value_fetch_lazy on the field will read
1241 the data from memory. For unions, that means we'll read the
1242 same memory more than once, which is not desirable. So
1243 fetch now. */
1244 need_to_fetch = true;
1246 /* The new value might be lazy. If the type is changeable,
1247 that is we'll be comparing values of this type, fetch the
1248 value now. Otherwise, on the next update the old value
1249 will be lazy, which means we've lost that old value. */
1250 if (need_to_fetch && value && value_lazy (value))
1252 const struct varobj *parent = var->parent;
1253 bool frozen = var->frozen;
1255 for (; !frozen && parent; parent = parent->parent)
1256 frozen |= parent->frozen;
1258 if (frozen && initial)
1260 /* For variables that are frozen, or are children of frozen
1261 variables, we don't do fetch on initial assignment.
1262 For non-initial assignment we do the fetch, since it means we're
1263 explicitly asked to compare the new value with the old one. */
1264 intentionally_not_fetched = true;
1266 else
1271 value_fetch_lazy (value);
1274 catch (const gdb_exception_error &except)
1276 /* Set the value to NULL, so that for the next -var-update,
1277 we don't try to compare the new value with this value,
1278 that we couldn't even read. */
1279 value = NULL;
1284 /* Get a reference now, before possibly passing it to any Python
1285 code that might release it. */
1286 value_ref_ptr value_holder;
1287 if (value != NULL)
1288 value_holder = value_ref_ptr::new_reference (value);
1290 /* Below, we'll be comparing string rendering of old and new
1291 values. Don't get string rendering if the value is
1292 lazy -- if it is, the code above has decided that the value
1293 should not be fetched. */
1294 std::string print_value;
1295 if (value != NULL && !value_lazy (value)
1296 && var->dynamic->pretty_printer == NULL)
1297 print_value = varobj_value_get_print_value (value, var->format, var);
1299 /* If the type is changeable, compare the old and the new values.
1300 If this is the initial assignment, we don't have any old value
1301 to compare with. */
1302 if (!initial && changeable)
1304 /* If the value of the varobj was changed by -var-set-value,
1305 then the value in the varobj and in the target is the same.
1306 However, that value is different from the value that the
1307 varobj had after the previous -var-update. So need to the
1308 varobj as changed. */
1309 if (var->updated)
1310 changed = true;
1311 else if (var->dynamic->pretty_printer == NULL)
1313 /* Try to compare the values. That requires that both
1314 values are non-lazy. */
1315 if (var->not_fetched && value_lazy (var->value.get ()))
1317 /* This is a frozen varobj and the value was never read.
1318 Presumably, UI shows some "never read" indicator.
1319 Now that we've fetched the real value, we need to report
1320 this varobj as changed so that UI can show the real
1321 value. */
1322 changed = true;
1324 else if (var->value == NULL && value == NULL)
1325 /* Equal. */
1327 else if (var->value == NULL || value == NULL)
1329 changed = true;
1331 else
1333 gdb_assert (!value_lazy (var->value.get ()));
1334 gdb_assert (!value_lazy (value));
1336 gdb_assert (!var->print_value.empty () && !print_value.empty ());
1337 if (var->print_value != print_value)
1338 changed = true;
1343 if (!initial && !changeable)
1345 /* For values that are not changeable, we don't compare the values.
1346 However, we want to notice if a value was not NULL and now is NULL,
1347 or vise versa, so that we report when top-level varobjs come in scope
1348 and leave the scope. */
1349 changed = (var->value != NULL) != (value != NULL);
1352 /* We must always keep the new value, since children depend on it. */
1353 var->value = value_holder;
1354 if (value && value_lazy (value) && intentionally_not_fetched)
1355 var->not_fetched = true;
1356 else
1357 var->not_fetched = false;
1358 var->updated = false;
1360 install_new_value_visualizer (var);
1362 /* If we installed a pretty-printer, re-compare the printed version
1363 to see if the variable changed. */
1364 if (var->dynamic->pretty_printer != NULL)
1366 print_value = varobj_value_get_print_value (var->value.get (),
1367 var->format, var);
1368 if (var->print_value != print_value)
1369 changed = true;
1371 var->print_value = print_value;
1373 gdb_assert (var->value == nullptr || value_type (var->value.get ()));
1375 return changed;
1378 /* Return the requested range for a varobj. VAR is the varobj. FROM
1379 and TO are out parameters; *FROM and *TO will be set to the
1380 selected sub-range of VAR. If no range was selected using
1381 -var-set-update-range, then both will be -1. */
1382 void
1383 varobj_get_child_range (const struct varobj *var, int *from, int *to)
1385 *from = var->from;
1386 *to = var->to;
1389 /* Set the selected sub-range of children of VAR to start at index
1390 FROM and end at index TO. If either FROM or TO is less than zero,
1391 this is interpreted as a request for all children. */
1392 void
1393 varobj_set_child_range (struct varobj *var, int from, int to)
1395 var->from = from;
1396 var->to = to;
1399 void
1400 varobj_set_visualizer (struct varobj *var, const char *visualizer)
1402 #if HAVE_PYTHON
1403 PyObject *mainmod;
1405 if (!gdb_python_initialized)
1406 return;
1408 gdbpy_enter_varobj enter_py (var);
1410 mainmod = PyImport_AddModule ("__main__");
1411 gdbpy_ref<> globals
1412 = gdbpy_ref<>::new_reference (PyModule_GetDict (mainmod));
1413 gdbpy_ref<> constructor (PyRun_String (visualizer, Py_eval_input,
1414 globals.get (), globals.get ()));
1416 if (constructor == NULL)
1418 gdbpy_print_stack ();
1419 error (_("Could not evaluate visualizer expression: %s"), visualizer);
1422 construct_visualizer (var, constructor.get ());
1424 /* If there are any children now, wipe them. */
1425 varobj_delete (var, 1 /* children only */);
1426 var->num_children = -1;
1427 #else
1428 error (_("Python support required"));
1429 #endif
1432 /* If NEW_VALUE is the new value of the given varobj (var), return
1433 true if var has mutated. In other words, if the type of
1434 the new value is different from the type of the varobj's old
1435 value.
1437 NEW_VALUE may be NULL, if the varobj is now out of scope. */
1439 static bool
1440 varobj_value_has_mutated (const struct varobj *var, struct value *new_value,
1441 struct type *new_type)
1443 /* If we haven't previously computed the number of children in var,
1444 it does not matter from the front-end's perspective whether
1445 the type has mutated or not. For all intents and purposes,
1446 it has not mutated. */
1447 if (var->num_children < 0)
1448 return false;
1450 if (var->root->lang_ops->value_has_mutated != NULL)
1452 /* The varobj module, when installing new values, explicitly strips
1453 references, saying that we're not interested in those addresses.
1454 But detection of mutation happens before installing the new
1455 value, so our value may be a reference that we need to strip
1456 in order to remain consistent. */
1457 if (new_value != NULL)
1458 new_value = coerce_ref (new_value);
1459 return var->root->lang_ops->value_has_mutated (var, new_value, new_type);
1461 else
1462 return false;
1465 /* Update the values for a variable and its children. This is a
1466 two-pronged attack. First, re-parse the value for the root's
1467 expression to see if it's changed. Then go all the way
1468 through its children, reconstructing them and noting if they've
1469 changed.
1471 The IS_EXPLICIT parameter specifies if this call is result
1472 of MI request to update this specific variable, or
1473 result of implicit -var-update *. For implicit request, we don't
1474 update frozen variables.
1476 NOTE: This function may delete the caller's varobj. If it
1477 returns TYPE_CHANGED, then it has done this and VARP will be modified
1478 to point to the new varobj. */
1480 std::vector<varobj_update_result>
1481 varobj_update (struct varobj **varp, bool is_explicit)
1483 bool type_changed = false;
1484 struct value *newobj;
1485 std::vector<varobj_update_result> stack;
1486 std::vector<varobj_update_result> result;
1488 /* Frozen means frozen -- we don't check for any change in
1489 this varobj, including its going out of scope, or
1490 changing type. One use case for frozen varobjs is
1491 retaining previously evaluated expressions, and we don't
1492 want them to be reevaluated at all. */
1493 if (!is_explicit && (*varp)->frozen)
1494 return result;
1496 if (!(*varp)->root->is_valid)
1498 result.emplace_back (*varp, VAROBJ_INVALID);
1499 return result;
1502 if ((*varp)->root->rootvar == *varp)
1504 varobj_update_result r (*varp);
1506 /* Update the root variable. value_of_root can return NULL
1507 if the variable is no longer around, i.e. we stepped out of
1508 the frame in which a local existed. We are letting the
1509 value_of_root variable dispose of the varobj if the type
1510 has changed. */
1511 newobj = value_of_root (varp, &type_changed);
1512 if (update_type_if_necessary (*varp, newobj))
1513 type_changed = true;
1514 r.varobj = *varp;
1515 r.type_changed = type_changed;
1516 if (install_new_value ((*varp), newobj, type_changed))
1517 r.changed = true;
1519 if (newobj == NULL)
1520 r.status = VAROBJ_NOT_IN_SCOPE;
1521 r.value_installed = true;
1523 if (r.status == VAROBJ_NOT_IN_SCOPE)
1525 if (r.type_changed || r.changed)
1526 result.push_back (std::move (r));
1528 return result;
1531 stack.push_back (std::move (r));
1533 else
1534 stack.emplace_back (*varp);
1536 /* Walk through the children, reconstructing them all. */
1537 while (!stack.empty ())
1539 varobj_update_result r = std::move (stack.back ());
1540 stack.pop_back ();
1541 struct varobj *v = r.varobj;
1543 /* Update this variable, unless it's a root, which is already
1544 updated. */
1545 if (!r.value_installed)
1547 struct type *new_type;
1549 newobj = value_of_child (v->parent, v->index);
1550 if (update_type_if_necessary (v, newobj))
1551 r.type_changed = true;
1552 if (newobj)
1553 new_type = value_type (newobj);
1554 else
1555 new_type = v->root->lang_ops->type_of_child (v->parent, v->index);
1557 if (varobj_value_has_mutated (v, newobj, new_type))
1559 /* The children are no longer valid; delete them now.
1560 Report the fact that its type changed as well. */
1561 varobj_delete (v, 1 /* only_children */);
1562 v->num_children = -1;
1563 v->to = -1;
1564 v->from = -1;
1565 v->type = new_type;
1566 r.type_changed = true;
1569 if (install_new_value (v, newobj, r.type_changed))
1571 r.changed = true;
1572 v->updated = false;
1576 /* We probably should not get children of a dynamic varobj, but
1577 for which -var-list-children was never invoked. */
1578 if (varobj_is_dynamic_p (v))
1580 std::vector<varobj *> changed, type_changed_vec, unchanged, newobj_vec;
1581 bool children_changed = false;
1583 if (v->frozen)
1584 continue;
1586 if (!v->dynamic->children_requested)
1588 bool dummy;
1590 /* If we initially did not have potential children, but
1591 now we do, consider the varobj as changed.
1592 Otherwise, if children were never requested, consider
1593 it as unchanged -- presumably, such varobj is not yet
1594 expanded in the UI, so we need not bother getting
1595 it. */
1596 if (!varobj_has_more (v, 0))
1598 update_dynamic_varobj_children (v, NULL, NULL, NULL, NULL,
1599 &dummy, false, 0, 0);
1600 if (varobj_has_more (v, 0))
1601 r.changed = true;
1604 if (r.changed)
1605 result.push_back (std::move (r));
1607 continue;
1610 /* If update_dynamic_varobj_children returns false, then we have
1611 a non-conforming pretty-printer, so we skip it. */
1612 if (update_dynamic_varobj_children (v, &changed, &type_changed_vec,
1613 &newobj_vec,
1614 &unchanged, &children_changed,
1615 true, v->from, v->to))
1617 if (children_changed || !newobj_vec.empty ())
1619 r.children_changed = true;
1620 r.newobj = std::move (newobj_vec);
1622 /* Push in reverse order so that the first child is
1623 popped from the work stack first, and so will be
1624 added to result first. This does not affect
1625 correctness, just "nicer". */
1626 for (int i = type_changed_vec.size () - 1; i >= 0; --i)
1628 varobj_update_result item (type_changed_vec[i]);
1630 /* Type may change only if value was changed. */
1631 item.changed = true;
1632 item.type_changed = true;
1633 item.value_installed = true;
1635 stack.push_back (std::move (item));
1637 for (int i = changed.size () - 1; i >= 0; --i)
1639 varobj_update_result item (changed[i]);
1641 item.changed = true;
1642 item.value_installed = true;
1644 stack.push_back (std::move (item));
1646 for (int i = unchanged.size () - 1; i >= 0; --i)
1648 if (!unchanged[i]->frozen)
1650 varobj_update_result item (unchanged[i]);
1652 item.value_installed = true;
1654 stack.push_back (std::move (item));
1657 if (r.changed || r.children_changed)
1658 result.push_back (std::move (r));
1660 continue;
1664 /* Push any children. Use reverse order so that the first
1665 child is popped from the work stack first, and so
1666 will be added to result first. This does not
1667 affect correctness, just "nicer". */
1668 for (int i = v->children.size () - 1; i >= 0; --i)
1670 varobj *c = v->children[i];
1672 /* Child may be NULL if explicitly deleted by -var-delete. */
1673 if (c != NULL && !c->frozen)
1674 stack.emplace_back (c);
1677 if (r.changed || r.type_changed)
1678 result.push_back (std::move (r));
1681 return result;
1684 /* Helper functions */
1687 * Variable object construction/destruction
1690 static int
1691 delete_variable (struct varobj *var, bool only_children_p)
1693 int delcount = 0;
1695 delete_variable_1 (&delcount, var, only_children_p,
1696 true /* remove_from_parent_p */ );
1698 return delcount;
1701 /* Delete the variable object VAR and its children. */
1702 /* IMPORTANT NOTE: If we delete a variable which is a child
1703 and the parent is not removed we dump core. It must be always
1704 initially called with remove_from_parent_p set. */
1705 static void
1706 delete_variable_1 (int *delcountp, struct varobj *var, bool only_children_p,
1707 bool remove_from_parent_p)
1709 /* Delete any children of this variable, too. */
1710 for (varobj *child : var->children)
1712 if (!child)
1713 continue;
1715 if (!remove_from_parent_p)
1716 child->parent = NULL;
1718 delete_variable_1 (delcountp, child, false, only_children_p);
1720 var->children.clear ();
1722 /* if we were called to delete only the children we are done here. */
1723 if (only_children_p)
1724 return;
1726 /* Otherwise, add it to the list of deleted ones and proceed to do so. */
1727 /* If the name is empty, this is a temporary variable, that has not
1728 yet been installed, don't report it, it belongs to the caller... */
1729 if (!var->obj_name.empty ())
1731 *delcountp = *delcountp + 1;
1734 /* If this variable has a parent, remove it from its parent's list. */
1735 /* OPTIMIZATION: if the parent of this variable is also being deleted,
1736 (as indicated by remove_from_parent_p) we don't bother doing an
1737 expensive list search to find the element to remove when we are
1738 discarding the list afterwards. */
1739 if ((remove_from_parent_p) && (var->parent != NULL))
1740 var->parent->children[var->index] = NULL;
1742 if (!var->obj_name.empty ())
1743 uninstall_variable (var);
1745 /* Free memory associated with this variable. */
1746 delete var;
1749 /* Install the given variable VAR with the object name VAR->OBJ_NAME. */
1750 static void
1751 install_variable (struct varobj *var)
1753 hashval_t hash = htab_hash_string (var->obj_name.c_str ());
1754 void **slot = htab_find_slot_with_hash (varobj_table,
1755 var->obj_name.c_str (),
1756 hash, INSERT);
1757 if (*slot != nullptr)
1758 error (_("Duplicate variable object name"));
1760 /* Add varobj to hash table. */
1761 *slot = var;
1763 /* If root, add varobj to root list. */
1764 if (is_root_p (var))
1765 rootlist.push_front (var->root);
1768 /* Uninstall the object VAR. */
1769 static void
1770 uninstall_variable (struct varobj *var)
1772 hashval_t hash = htab_hash_string (var->obj_name.c_str ());
1773 htab_remove_elt_with_hash (varobj_table, var->obj_name.c_str (), hash);
1775 if (varobjdebug)
1776 gdb_printf (gdb_stdlog, "Deleting %s\n", var->obj_name.c_str ());
1778 /* If root, remove varobj from root list. */
1779 if (is_root_p (var))
1781 auto iter = std::find (rootlist.begin (), rootlist.end (), var->root);
1782 rootlist.erase (iter);
1786 /* Create and install a child of the parent of the given name.
1788 The created VAROBJ takes ownership of the allocated NAME. */
1790 static struct varobj *
1791 create_child (struct varobj *parent, int index, std::string &name)
1793 struct varobj_item item;
1795 std::swap (item.name, name);
1796 item.value = release_value (value_of_child (parent, index));
1798 return create_child_with_value (parent, index, &item);
1801 static struct varobj *
1802 create_child_with_value (struct varobj *parent, int index,
1803 struct varobj_item *item)
1805 varobj *child = new varobj (parent->root);
1807 /* NAME is allocated by caller. */
1808 std::swap (child->name, item->name);
1809 child->index = index;
1810 child->parent = parent;
1812 if (varobj_is_anonymous_child (child))
1813 child->obj_name = string_printf ("%s.%d_anonymous",
1814 parent->obj_name.c_str (), index);
1815 else
1816 child->obj_name = string_printf ("%s.%s",
1817 parent->obj_name.c_str (),
1818 child->name.c_str ());
1820 install_variable (child);
1822 /* Compute the type of the child. Must do this before
1823 calling install_new_value. */
1824 if (item->value != NULL)
1825 /* If the child had no evaluation errors, var->value
1826 will be non-NULL and contain a valid type. */
1827 child->type = value_actual_type (item->value.get (), 0, NULL);
1828 else
1829 /* Otherwise, we must compute the type. */
1830 child->type = (*child->root->lang_ops->type_of_child) (child->parent,
1831 child->index);
1832 install_new_value (child, item->value.get (), 1);
1834 return child;
1839 * Miscellaneous utility functions.
1842 /* Allocate memory and initialize a new variable. */
1843 varobj::varobj (varobj_root *root_)
1844 : root (root_), dynamic (new varobj_dynamic)
1848 /* Free any allocated memory associated with VAR. */
1850 varobj::~varobj ()
1852 varobj *var = this;
1854 #if HAVE_PYTHON
1855 if (var->dynamic->pretty_printer != NULL)
1857 gdbpy_enter_varobj enter_py (var);
1859 Py_XDECREF (var->dynamic->constructor);
1860 Py_XDECREF (var->dynamic->pretty_printer);
1862 #endif
1864 /* This must be deleted before the root object, because Python-based
1865 destructors need access to some components. */
1866 delete var->dynamic;
1868 if (is_root_p (var))
1869 delete var->root;
1872 /* Return the type of the value that's stored in VAR,
1873 or that would have being stored there if the
1874 value were accessible.
1876 This differs from VAR->type in that VAR->type is always
1877 the true type of the expression in the source language.
1878 The return value of this function is the type we're
1879 actually storing in varobj, and using for displaying
1880 the values and for comparing previous and new values.
1882 For example, top-level references are always stripped. */
1883 struct type *
1884 varobj_get_value_type (const struct varobj *var)
1886 struct type *type;
1888 if (var->value != nullptr)
1889 type = value_type (var->value.get ());
1890 else
1891 type = var->type;
1893 type = check_typedef (type);
1895 if (TYPE_IS_REFERENCE (type))
1896 type = get_target_type (type);
1898 type = check_typedef (type);
1900 return type;
1903 /* What is the default display for this variable? We assume that
1904 everything is "natural". Any exceptions? */
1905 static enum varobj_display_formats
1906 variable_default_display (struct varobj *var)
1908 return FORMAT_NATURAL;
1912 * Language-dependencies
1915 /* Common entry points */
1917 /* Return the number of children for a given variable.
1918 The result of this function is defined by the language
1919 implementation. The number of children returned by this function
1920 is the number of children that the user will see in the variable
1921 display. */
1922 static int
1923 number_of_children (const struct varobj *var)
1925 return (*var->root->lang_ops->number_of_children) (var);
1928 /* What is the expression for the root varobj VAR? */
1930 static std::string
1931 name_of_variable (const struct varobj *var)
1933 return (*var->root->lang_ops->name_of_variable) (var);
1936 /* What is the name of the INDEX'th child of VAR? */
1938 static std::string
1939 name_of_child (struct varobj *var, int index)
1941 return (*var->root->lang_ops->name_of_child) (var, index);
1944 /* If frame associated with VAR can be found, switch
1945 to it and return true. Otherwise, return false. */
1947 static bool
1948 check_scope (const struct varobj *var)
1950 struct frame_info *fi;
1951 bool scope;
1953 fi = frame_find_by_id (var->root->frame);
1954 scope = fi != NULL;
1956 if (fi)
1958 CORE_ADDR pc = get_frame_pc (fi);
1960 if (pc < var->root->valid_block->start () ||
1961 pc >= var->root->valid_block->end ())
1962 scope = false;
1963 else
1964 select_frame (fi);
1966 return scope;
1969 /* Helper function to value_of_root. */
1971 static struct value *
1972 value_of_root_1 (struct varobj **var_handle)
1974 struct value *new_val = NULL;
1975 struct varobj *var = *var_handle;
1976 bool within_scope = false;
1978 /* Only root variables can be updated... */
1979 if (!is_root_p (var))
1980 /* Not a root var. */
1981 return NULL;
1983 scoped_restore_current_thread restore_thread;
1985 /* Determine whether the variable is still around. */
1986 if (var->root->valid_block == NULL || var->root->floating)
1987 within_scope = true;
1988 else if (var->root->thread_id == 0)
1990 /* The program was single-threaded when the variable object was
1991 created. Technically, it's possible that the program became
1992 multi-threaded since then, but we don't support such
1993 scenario yet. */
1994 within_scope = check_scope (var);
1996 else
1998 thread_info *thread = find_thread_global_id (var->root->thread_id);
2000 if (thread != NULL)
2002 switch_to_thread (thread);
2003 within_scope = check_scope (var);
2007 if (within_scope)
2010 /* We need to catch errors here, because if evaluate
2011 expression fails we want to just return NULL. */
2014 new_val = evaluate_expression (var->root->exp.get ());
2016 catch (const gdb_exception_error &except)
2021 return new_val;
2024 /* What is the ``struct value *'' of the root variable VAR?
2025 For floating variable object, evaluation can get us a value
2026 of different type from what is stored in varobj already. In
2027 that case:
2028 - *type_changed will be set to 1
2029 - old varobj will be freed, and new one will be
2030 created, with the same name.
2031 - *var_handle will be set to the new varobj
2032 Otherwise, *type_changed will be set to 0. */
2033 static struct value *
2034 value_of_root (struct varobj **var_handle, bool *type_changed)
2036 struct varobj *var;
2038 if (var_handle == NULL)
2039 return NULL;
2041 var = *var_handle;
2043 /* This should really be an exception, since this should
2044 only get called with a root variable. */
2046 if (!is_root_p (var))
2047 return NULL;
2049 if (var->root->floating)
2051 struct varobj *tmp_var;
2053 tmp_var = varobj_create (NULL, var->name.c_str (), (CORE_ADDR) 0,
2054 USE_SELECTED_FRAME);
2055 if (tmp_var == NULL)
2057 return NULL;
2059 std::string old_type = varobj_get_type (var);
2060 std::string new_type = varobj_get_type (tmp_var);
2061 if (old_type == new_type)
2063 /* The expression presently stored inside var->root->exp
2064 remembers the locations of local variables relatively to
2065 the frame where the expression was created (in DWARF location
2066 button, for example). Naturally, those locations are not
2067 correct in other frames, so update the expression. */
2069 std::swap (var->root->exp, tmp_var->root->exp);
2071 varobj_delete (tmp_var, 0);
2072 *type_changed = 0;
2074 else
2076 tmp_var->obj_name = var->obj_name;
2077 tmp_var->from = var->from;
2078 tmp_var->to = var->to;
2079 varobj_delete (var, 0);
2081 install_variable (tmp_var);
2082 *var_handle = tmp_var;
2083 var = *var_handle;
2084 *type_changed = true;
2087 else
2089 *type_changed = 0;
2093 struct value *value;
2095 value = value_of_root_1 (var_handle);
2096 if (var->value == NULL || value == NULL)
2098 /* For root varobj-s, a NULL value indicates a scoping issue.
2099 So, nothing to do in terms of checking for mutations. */
2101 else if (varobj_value_has_mutated (var, value, value_type (value)))
2103 /* The type has mutated, so the children are no longer valid.
2104 Just delete them, and tell our caller that the type has
2105 changed. */
2106 varobj_delete (var, 1 /* only_children */);
2107 var->num_children = -1;
2108 var->to = -1;
2109 var->from = -1;
2110 *type_changed = true;
2112 return value;
2116 /* What is the ``struct value *'' for the INDEX'th child of PARENT? */
2117 static struct value *
2118 value_of_child (const struct varobj *parent, int index)
2120 struct value *value;
2122 value = (*parent->root->lang_ops->value_of_child) (parent, index);
2124 return value;
2127 /* GDB already has a command called "value_of_variable". Sigh. */
2128 static std::string
2129 my_value_of_variable (struct varobj *var, enum varobj_display_formats format)
2131 if (var->root->is_valid)
2133 if (var->dynamic->pretty_printer != NULL)
2134 return varobj_value_get_print_value (var->value.get (), var->format,
2135 var);
2136 return (*var->root->lang_ops->value_of_variable) (var, format);
2138 else
2139 return std::string ();
2142 void
2143 varobj_formatted_print_options (struct value_print_options *opts,
2144 enum varobj_display_formats format)
2146 get_formatted_print_options (opts, format_code[(int) format]);
2147 opts->deref_ref = 0;
2148 opts->raw = !pretty_printing;
2151 std::string
2152 varobj_value_get_print_value (struct value *value,
2153 enum varobj_display_formats format,
2154 const struct varobj *var)
2156 struct value_print_options opts;
2157 struct type *type = NULL;
2158 long len = 0;
2159 gdb::unique_xmalloc_ptr<char> encoding;
2160 /* Initialize it just to avoid a GCC false warning. */
2161 CORE_ADDR str_addr = 0;
2162 bool string_print = false;
2164 if (value == NULL)
2165 return std::string ();
2167 string_file stb;
2168 std::string thevalue;
2170 varobj_formatted_print_options (&opts, format);
2172 #if HAVE_PYTHON
2173 if (gdb_python_initialized)
2175 PyObject *value_formatter = var->dynamic->pretty_printer;
2177 gdbpy_enter_varobj enter_py (var);
2179 if (value_formatter)
2181 /* First check to see if we have any children at all. If so,
2182 we simply return {...}. */
2183 if (dynamic_varobj_has_child_method (var))
2184 return "{...}";
2186 if (PyObject_HasAttr (value_formatter, gdbpy_to_string_cst))
2188 struct value *replacement;
2190 gdbpy_ref<> output = apply_varobj_pretty_printer (value_formatter,
2191 &replacement,
2192 &stb,
2193 &opts);
2195 /* If we have string like output ... */
2196 if (output != NULL)
2198 /* If this is a lazy string, extract it. For lazy
2199 strings we always print as a string, so set
2200 string_print. */
2201 if (gdbpy_is_lazy_string (output.get ()))
2203 gdbpy_extract_lazy_string (output.get (), &str_addr,
2204 &type, &len, &encoding);
2205 string_print = true;
2207 else
2209 /* If it is a regular (non-lazy) string, extract
2210 it and copy the contents into THEVALUE. If the
2211 hint says to print it as a string, set
2212 string_print. Otherwise just return the extracted
2213 string as a value. */
2215 gdb::unique_xmalloc_ptr<char> s
2216 = python_string_to_target_string (output.get ());
2218 if (s)
2220 struct gdbarch *gdbarch;
2222 gdb::unique_xmalloc_ptr<char> hint
2223 = gdbpy_get_display_hint (value_formatter);
2224 if (hint)
2226 if (!strcmp (hint.get (), "string"))
2227 string_print = true;
2230 thevalue = std::string (s.get ());
2231 len = thevalue.size ();
2232 gdbarch = value_type (value)->arch ();
2233 type = builtin_type (gdbarch)->builtin_char;
2235 if (!string_print)
2236 return thevalue;
2238 else
2239 gdbpy_print_stack ();
2242 /* If the printer returned a replacement value, set VALUE
2243 to REPLACEMENT. If there is not a replacement value,
2244 just use the value passed to this function. */
2245 if (replacement)
2246 value = replacement;
2250 #endif
2252 /* If the THEVALUE has contents, it is a regular string. */
2253 if (!thevalue.empty ())
2254 current_language->printstr (&stb, type, (gdb_byte *) thevalue.c_str (),
2255 len, encoding.get (), 0, &opts);
2256 else if (string_print)
2257 /* Otherwise, if string_print is set, and it is not a regular
2258 string, it is a lazy string. */
2259 val_print_string (type, encoding.get (), str_addr, len, &stb, &opts);
2260 else
2261 /* All other cases. */
2262 common_val_print (value, &stb, 0, &opts, current_language);
2264 return stb.release ();
2267 bool
2268 varobj_editable_p (const struct varobj *var)
2270 struct type *type;
2272 if (!(var->root->is_valid && var->value != nullptr
2273 && VALUE_LVAL (var->value.get ())))
2274 return false;
2276 type = varobj_get_value_type (var);
2278 switch (type->code ())
2280 case TYPE_CODE_STRUCT:
2281 case TYPE_CODE_UNION:
2282 case TYPE_CODE_ARRAY:
2283 case TYPE_CODE_FUNC:
2284 case TYPE_CODE_METHOD:
2285 return false;
2286 break;
2288 default:
2289 return true;
2290 break;
2294 /* Call VAR's value_is_changeable_p language-specific callback. */
2296 bool
2297 varobj_value_is_changeable_p (const struct varobj *var)
2299 return var->root->lang_ops->value_is_changeable_p (var);
2302 /* Return true if that varobj is floating, that is is always evaluated in the
2303 selected frame, and not bound to thread/frame. Such variable objects
2304 are created using '@' as frame specifier to -var-create. */
2305 bool
2306 varobj_floating_p (const struct varobj *var)
2308 return var->root->floating;
2311 /* Implement the "value_is_changeable_p" varobj callback for most
2312 languages. */
2314 bool
2315 varobj_default_value_is_changeable_p (const struct varobj *var)
2317 bool r;
2318 struct type *type;
2320 if (CPLUS_FAKE_CHILD (var))
2321 return false;
2323 type = varobj_get_value_type (var);
2325 switch (type->code ())
2327 case TYPE_CODE_STRUCT:
2328 case TYPE_CODE_UNION:
2329 case TYPE_CODE_ARRAY:
2330 r = false;
2331 break;
2333 default:
2334 r = true;
2337 return r;
2340 /* Iterate all the existing _root_ VAROBJs and call the FUNC callback
2341 for each one. */
2343 void
2344 all_root_varobjs (gdb::function_view<void (struct varobj *var)> func)
2346 /* Iterate "safely" - handle if the callee deletes its passed VAROBJ. */
2347 auto iter = rootlist.begin ();
2348 auto end = rootlist.end ();
2349 while (iter != end)
2351 auto self = iter++;
2352 func ((*self)->rootvar);
2356 /* Invalidate varobj VAR if it is tied to locals and re-create it if it is
2357 defined on globals. It is a helper for varobj_invalidate.
2359 This function is called after changing the symbol file, in this case the
2360 pointers to "struct type" stored by the varobj are no longer valid. All
2361 varobj must be either re-evaluated, or marked as invalid here. */
2363 static void
2364 varobj_invalidate_iter (struct varobj *var)
2366 /* global and floating var must be re-evaluated. */
2367 if (var->root->floating || var->root->global)
2369 struct varobj *tmp_var;
2371 /* Try to create a varobj with same expression. If we succeed
2372 replace the old varobj, otherwise invalidate it. */
2373 tmp_var = varobj_create (nullptr, var->name.c_str (), (CORE_ADDR) 0,
2374 var->root->floating
2375 ? USE_SELECTED_FRAME : USE_CURRENT_FRAME);
2376 if (tmp_var != nullptr)
2378 gdb_assert (var->root->floating == tmp_var->root->floating);
2379 tmp_var->obj_name = var->obj_name;
2380 varobj_delete (var, 0);
2381 install_variable (tmp_var);
2383 else if (var->root->global)
2385 /* Only invalidate globals as floating vars might still be valid in
2386 some other frame. */
2387 var->root->is_valid = false;
2390 else /* locals must be invalidated. */
2391 var->root->is_valid = false;
2394 /* Invalidate the varobjs that are tied to locals and re-create the ones that
2395 are defined on globals.
2396 Invalidated varobjs will be always printed in_scope="invalid". */
2398 void
2399 varobj_invalidate (void)
2401 all_root_varobjs (varobj_invalidate_iter);
2404 /* Ensure that no varobj keep references to OBJFILE. */
2406 static void
2407 varobj_invalidate_if_uses_objfile (struct objfile *objfile)
2409 if (objfile->separate_debug_objfile_backlink != nullptr)
2410 objfile = objfile->separate_debug_objfile_backlink;
2412 all_root_varobjs ([objfile] (struct varobj *var)
2414 if (var->root->valid_block != nullptr)
2416 struct objfile *bl_objfile = block_objfile (var->root->valid_block);
2417 if (bl_objfile->separate_debug_objfile_backlink != nullptr)
2418 bl_objfile = bl_objfile->separate_debug_objfile_backlink;
2420 if (bl_objfile == objfile)
2422 /* The varobj is tied to a block which is going away. There is
2423 no way to reconstruct something later, so invalidate the
2424 varobj completly and drop the reference to the block which is
2425 being freed. */
2426 var->root->is_valid = false;
2427 var->root->valid_block = nullptr;
2431 if (var->root->exp != nullptr
2432 && exp_uses_objfile (var->root->exp.get (), objfile))
2434 /* The varobj's current expression references the objfile. For
2435 globals and floating, it is possible that when we try to
2436 re-evaluate the expression later it is still valid with
2437 whatever is in scope at that moment. Just invalidate the
2438 expression for now. */
2439 var->root->exp.reset ();
2441 /* It only makes sense to keep a floating varobj around. */
2442 if (!var->root->floating)
2443 var->root->is_valid = false;
2446 /* var->value->type and var->type might also reference the objfile.
2447 This is taken care of in value.c:preserve_values which deals with
2448 making sure that objfile-owend types are replaced with
2449 gdbarch-owned equivalents. */
2453 /* A hash function for a varobj. */
2455 static hashval_t
2456 hash_varobj (const void *a)
2458 const varobj *obj = (const varobj *) a;
2459 return htab_hash_string (obj->obj_name.c_str ());
2462 /* A hash table equality function for varobjs. */
2464 static int
2465 eq_varobj_and_string (const void *a, const void *b)
2467 const varobj *obj = (const varobj *) a;
2468 const char *name = (const char *) b;
2470 return obj->obj_name == name;
2473 void _initialize_varobj ();
2474 void
2475 _initialize_varobj ()
2477 varobj_table = htab_create_alloc (5, hash_varobj, eq_varobj_and_string,
2478 nullptr, xcalloc, xfree);
2480 add_setshow_zuinteger_cmd ("varobj", class_maintenance,
2481 &varobjdebug,
2482 _("Set varobj debugging."),
2483 _("Show varobj debugging."),
2484 _("When non-zero, varobj debugging is enabled."),
2485 NULL, show_varobjdebug,
2486 &setdebuglist, &showdebuglist);
2488 gdb::observers::free_objfile.attach (varobj_invalidate_if_uses_objfile,
2489 "varobj");