Update release README with new version numbers
[binutils-gdb.git] / gdb / varobj.c
blob1aca015a21ab13cbe4011a9a1446e31d105d7a43
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>
36 #if HAVE_PYTHON
37 #include "python/python.h"
38 #include "python/python-internal.h"
39 #else
40 typedef int PyObject;
41 #endif
43 /* See varobj.h. */
45 unsigned int varobjdebug = 0;
46 static void
47 show_varobjdebug (struct ui_file *file, int from_tty,
48 struct cmd_list_element *c, const char *value)
50 gdb_printf (file, _("Varobj debugging is %s.\n"), value);
53 /* String representations of gdb's format codes. */
54 const char *varobj_format_string[] =
55 { "natural", "binary", "decimal", "hexadecimal", "octal", "zero-hexadecimal" };
57 /* True if we want to allow Python-based pretty-printing. */
58 static bool pretty_printing = false;
60 void
61 varobj_enable_pretty_printing (void)
63 pretty_printing = true;
66 /* Data structures */
68 /* Every root variable has one of these structures saved in its
69 varobj. */
70 struct varobj_root
72 /* The expression for this parent. */
73 expression_up exp;
75 /* Block for which this expression is valid. */
76 const struct block *valid_block = NULL;
78 /* The frame for this expression. This field is set iff valid_block is
79 not NULL. */
80 struct frame_id frame = null_frame_id;
82 /* The global thread ID that this varobj_root belongs to. This field
83 is only valid if valid_block is not NULL.
84 When not 0, indicates which thread 'frame' belongs to.
85 When 0, indicates that the thread list was empty when the varobj_root
86 was created. */
87 int thread_id = 0;
89 /* If true, the -var-update always recomputes the value in the
90 current thread and frame. Otherwise, variable object is
91 always updated in the specific scope/thread/frame. */
92 bool floating = false;
94 /* Flag that indicates validity: set to false when this varobj_root refers
95 to symbols that do not exist anymore. */
96 bool is_valid = true;
98 /* Language-related operations for this variable and its
99 children. */
100 const struct lang_varobj_ops *lang_ops = NULL;
102 /* The varobj for this root node. */
103 struct varobj *rootvar = NULL;
106 /* Dynamic part of varobj. */
108 struct varobj_dynamic
110 /* Whether the children of this varobj were requested. This field is
111 used to decide if dynamic varobj should recompute their children.
112 In the event that the frontend never asked for the children, we
113 can avoid that. */
114 bool children_requested = false;
116 /* The pretty-printer constructor. If NULL, then the default
117 pretty-printer will be looked up. If None, then no
118 pretty-printer will be installed. */
119 PyObject *constructor = NULL;
121 /* The pretty-printer that has been constructed. If NULL, then a
122 new printer object is needed, and one will be constructed. */
123 PyObject *pretty_printer = NULL;
125 /* The iterator returned by the printer's 'children' method, or NULL
126 if not available. */
127 std::unique_ptr<varobj_iter> child_iter;
129 /* We request one extra item from the iterator, so that we can
130 report to the caller whether there are more items than we have
131 already reported. However, we don't want to install this value
132 when we read it, because that will mess up future updates. So,
133 we stash it here instead. */
134 std::unique_ptr<varobj_item> saved_item;
137 /* Private function prototypes */
139 /* Helper functions for the above subcommands. */
141 static int delete_variable (struct varobj *, bool);
143 static void delete_variable_1 (int *, struct varobj *, bool, bool);
145 static void install_variable (struct varobj *);
147 static void uninstall_variable (struct varobj *);
149 static struct varobj *create_child (struct varobj *, int, std::string &);
151 static struct varobj *
152 create_child_with_value (struct varobj *parent, int index,
153 struct varobj_item *item);
155 /* Utility routines */
157 static enum varobj_display_formats variable_default_display (struct varobj *);
159 static bool update_type_if_necessary (struct varobj *var,
160 struct value *new_value);
162 static bool install_new_value (struct varobj *var, struct value *value,
163 bool initial);
165 /* Language-specific routines. */
167 static int number_of_children (const struct varobj *);
169 static std::string name_of_variable (const struct varobj *);
171 static std::string name_of_child (struct varobj *, int);
173 static struct value *value_of_root (struct varobj **var_handle, bool *);
175 static struct value *value_of_child (const struct varobj *parent, int index);
177 static std::string my_value_of_variable (struct varobj *var,
178 enum varobj_display_formats format);
180 static bool is_root_p (const struct varobj *var);
182 static struct varobj *varobj_add_child (struct varobj *var,
183 struct varobj_item *item);
185 /* Private data */
187 /* Mappings of varobj_display_formats enums to gdb's format codes. */
188 static int format_code[] = { 0, 't', 'd', 'x', 'o', 'z' };
190 /* List of root variable objects. */
191 static std::list<struct varobj_root *> rootlist;
193 /* Pointer to the varobj hash table (built at run time). */
194 static htab_t varobj_table;
198 /* API Implementation */
199 static bool
200 is_root_p (const struct varobj *var)
202 return (var->root->rootvar == var);
205 #ifdef HAVE_PYTHON
207 /* See python-internal.h. */
208 gdbpy_enter_varobj::gdbpy_enter_varobj (const struct varobj *var)
209 : gdbpy_enter (var->root->exp->gdbarch, var->root->exp->language_defn)
213 #endif
215 /* Return the full FRAME which corresponds to the given CORE_ADDR
216 or NULL if no FRAME on the chain corresponds to CORE_ADDR. */
218 static struct frame_info *
219 find_frame_addr_in_frame_chain (CORE_ADDR frame_addr)
221 struct frame_info *frame = NULL;
223 if (frame_addr == (CORE_ADDR) 0)
224 return NULL;
226 for (frame = get_current_frame ();
227 frame != NULL;
228 frame = get_prev_frame (frame))
230 /* The CORE_ADDR we get as argument was parsed from a string GDB
231 output as $fp. This output got truncated to gdbarch_addr_bit.
232 Truncate the frame base address in the same manner before
233 comparing it against our argument. */
234 CORE_ADDR frame_base = get_frame_base_address (frame);
235 int addr_bit = gdbarch_addr_bit (get_frame_arch (frame));
237 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
238 frame_base &= ((CORE_ADDR) 1 << addr_bit) - 1;
240 if (frame_base == frame_addr)
241 return frame;
244 return NULL;
247 /* Creates a varobj (not its children). */
249 struct varobj *
250 varobj_create (const char *objname,
251 const char *expression, CORE_ADDR frame, enum varobj_type type)
253 /* Fill out a varobj structure for the (root) variable being constructed. */
254 std::unique_ptr<varobj> var (new varobj (new varobj_root));
256 if (expression != NULL)
258 struct frame_info *fi;
259 struct frame_id old_id = null_frame_id;
260 const struct block *block;
261 const char *p;
262 struct value *value = NULL;
263 CORE_ADDR pc;
265 /* Parse and evaluate the expression, filling in as much of the
266 variable's data as possible. */
268 if (has_stack_frames ())
270 /* Allow creator to specify context of variable. */
271 if ((type == USE_CURRENT_FRAME) || (type == USE_SELECTED_FRAME))
272 fi = get_selected_frame (NULL);
273 else
274 /* FIXME: cagney/2002-11-23: This code should be doing a
275 lookup using the frame ID and not just the frame's
276 ``address''. This, of course, means an interface
277 change. However, with out that interface change ISAs,
278 such as the ia64 with its two stacks, won't work.
279 Similar goes for the case where there is a frameless
280 function. */
281 fi = find_frame_addr_in_frame_chain (frame);
283 else
284 fi = NULL;
286 if (type == USE_SELECTED_FRAME)
287 var->root->floating = true;
289 pc = 0;
290 block = NULL;
291 if (fi != NULL)
293 block = get_frame_block (fi, 0);
294 pc = get_frame_pc (fi);
297 p = expression;
299 innermost_block_tracker tracker (INNERMOST_BLOCK_FOR_SYMBOLS
300 | INNERMOST_BLOCK_FOR_REGISTERS);
301 /* Wrap the call to parse expression, so we can
302 return a sensible error. */
305 var->root->exp = parse_exp_1 (&p, pc, block, 0, &tracker);
308 catch (const gdb_exception_error &except)
310 return NULL;
313 /* Don't allow variables to be created for types. */
314 enum exp_opcode opcode = var->root->exp->first_opcode ();
315 if (opcode == OP_TYPE
316 || opcode == OP_TYPEOF
317 || opcode == OP_DECLTYPE)
319 gdb_printf (gdb_stderr, "Attempt to use a type name"
320 " as an expression.\n");
321 return NULL;
324 var->format = variable_default_display (var.get ());
325 var->root->valid_block =
326 var->root->floating ? NULL : tracker.block ();
327 var->name = expression;
328 /* For a root var, the name and the expr are the same. */
329 var->path_expr = expression;
331 /* When the frame is different from the current frame,
332 we must select the appropriate frame before parsing
333 the expression, otherwise the value will not be current.
334 Since select_frame is so benign, just call it for all cases. */
335 if (var->root->valid_block)
337 /* User could specify explicit FRAME-ADDR which was not found but
338 EXPRESSION is frame specific and we would not be able to evaluate
339 it correctly next time. With VALID_BLOCK set we must also set
340 FRAME and THREAD_ID. */
341 if (fi == NULL)
342 error (_("Failed to find the specified frame"));
344 var->root->frame = get_frame_id (fi);
345 var->root->thread_id = inferior_thread ()->global_num;
346 old_id = get_frame_id (get_selected_frame (NULL));
347 select_frame (fi);
350 /* We definitely need to catch errors here.
351 If evaluate_expression succeeds we got the value we wanted.
352 But if it fails, we still go on with a call to evaluate_type(). */
355 value = evaluate_expression (var->root->exp.get ());
357 catch (const gdb_exception_error &except)
359 /* Error getting the value. Try to at least get the
360 right type. */
361 struct value *type_only_value = evaluate_type (var->root->exp.get ());
363 var->type = value_type (type_only_value);
366 if (value != NULL)
368 int real_type_found = 0;
370 var->type = value_actual_type (value, 0, &real_type_found);
371 if (real_type_found)
372 value = value_cast (var->type, value);
375 /* Set language info */
376 var->root->lang_ops = var->root->exp->language_defn->varobj_ops ();
378 install_new_value (var.get (), value, 1 /* Initial assignment */);
380 /* Set ourselves as our root. */
381 var->root->rootvar = var.get ();
383 /* Reset the selected frame. */
384 if (frame_id_p (old_id))
385 select_frame (frame_find_by_id (old_id));
388 /* If the variable object name is null, that means this
389 is a temporary variable, so don't install it. */
391 if ((var != NULL) && (objname != NULL))
393 var->obj_name = objname;
394 install_variable (var.get ());
397 return var.release ();
400 /* Generates an unique name that can be used for a varobj. */
402 std::string
403 varobj_gen_name (void)
405 static int id = 0;
407 /* Generate a name for this object. */
408 id++;
409 return string_printf ("var%d", id);
412 /* Given an OBJNAME, returns the pointer to the corresponding varobj. Call
413 error if OBJNAME cannot be found. */
415 struct varobj *
416 varobj_get_handle (const char *objname)
418 varobj *var = (varobj *) htab_find_with_hash (varobj_table, objname,
419 htab_hash_string (objname));
421 if (var == NULL)
422 error (_("Variable object not found"));
424 return var;
427 /* Given the handle, return the name of the object. */
429 const char *
430 varobj_get_objname (const struct varobj *var)
432 return var->obj_name.c_str ();
435 /* Given the handle, return the expression represented by the
436 object. */
438 std::string
439 varobj_get_expression (const struct varobj *var)
441 return name_of_variable (var);
444 /* See varobj.h. */
447 varobj_delete (struct varobj *var, bool only_children)
449 return delete_variable (var, only_children);
452 #if HAVE_PYTHON
454 /* Convenience function for varobj_set_visualizer. Instantiate a
455 pretty-printer for a given value. */
456 static PyObject *
457 instantiate_pretty_printer (PyObject *constructor, struct value *value)
459 gdbpy_ref<> val_obj (value_to_value_object (value));
460 if (val_obj == nullptr)
461 return NULL;
463 return PyObject_CallFunctionObjArgs (constructor, val_obj.get (), NULL);
466 #endif
468 /* Set/Get variable object display format. */
470 enum varobj_display_formats
471 varobj_set_display_format (struct varobj *var,
472 enum varobj_display_formats format)
474 switch (format)
476 case FORMAT_NATURAL:
477 case FORMAT_BINARY:
478 case FORMAT_DECIMAL:
479 case FORMAT_HEXADECIMAL:
480 case FORMAT_OCTAL:
481 case FORMAT_ZHEXADECIMAL:
482 var->format = format;
483 break;
485 default:
486 var->format = variable_default_display (var);
489 if (varobj_value_is_changeable_p (var)
490 && var->value != nullptr && !value_lazy (var->value.get ()))
492 var->print_value = varobj_value_get_print_value (var->value.get (),
493 var->format, var);
496 return var->format;
499 enum varobj_display_formats
500 varobj_get_display_format (const struct varobj *var)
502 return var->format;
505 gdb::unique_xmalloc_ptr<char>
506 varobj_get_display_hint (const struct varobj *var)
508 gdb::unique_xmalloc_ptr<char> result;
510 #if HAVE_PYTHON
511 if (!gdb_python_initialized)
512 return NULL;
514 gdbpy_enter_varobj enter_py (var);
516 if (var->dynamic->pretty_printer != NULL)
517 result = gdbpy_get_display_hint (var->dynamic->pretty_printer);
518 #endif
520 return result;
523 /* Return true if the varobj has items after TO, false otherwise. */
525 bool
526 varobj_has_more (const struct varobj *var, int to)
528 if (var->children.size () > to)
529 return true;
531 return ((to == -1 || var->children.size () == to)
532 && (var->dynamic->saved_item != NULL));
535 /* If the variable object is bound to a specific thread, that
536 is its evaluation can always be done in context of a frame
537 inside that thread, returns GDB id of the thread -- which
538 is always positive. Otherwise, returns -1. */
540 varobj_get_thread_id (const struct varobj *var)
542 if (var->root->valid_block && var->root->thread_id > 0)
543 return var->root->thread_id;
544 else
545 return -1;
548 void
549 varobj_set_frozen (struct varobj *var, bool frozen)
551 /* When a variable is unfrozen, we don't fetch its value.
552 The 'not_fetched' flag remains set, so next -var-update
553 won't complain.
555 We don't fetch the value, because for structures the client
556 should do -var-update anyway. It would be bad to have different
557 client-size logic for structure and other types. */
558 var->frozen = frozen;
561 bool
562 varobj_get_frozen (const struct varobj *var)
564 return var->frozen;
567 /* A helper function that updates the contents of FROM and TO based on the
568 size of the vector CHILDREN. If the contents of either FROM or TO are
569 negative the entire range is used. */
571 void
572 varobj_restrict_range (const std::vector<varobj *> &children,
573 int *from, int *to)
575 int len = children.size ();
577 if (*from < 0 || *to < 0)
579 *from = 0;
580 *to = len;
582 else
584 if (*from > len)
585 *from = len;
586 if (*to > len)
587 *to = len;
588 if (*from > *to)
589 *from = *to;
593 /* A helper for update_dynamic_varobj_children that installs a new
594 child when needed. */
596 static void
597 install_dynamic_child (struct varobj *var,
598 std::vector<varobj *> *changed,
599 std::vector<varobj *> *type_changed,
600 std::vector<varobj *> *newobj,
601 std::vector<varobj *> *unchanged,
602 bool *cchanged,
603 int index,
604 struct varobj_item *item)
606 if (var->children.size () < index + 1)
608 /* There's no child yet. */
609 struct varobj *child = varobj_add_child (var, item);
611 if (newobj != NULL)
613 newobj->push_back (child);
614 *cchanged = true;
617 else
619 varobj *existing = var->children[index];
620 bool type_updated = update_type_if_necessary (existing,
621 item->value.get ());
623 if (type_updated)
625 if (type_changed != NULL)
626 type_changed->push_back (existing);
628 if (install_new_value (existing, item->value.get (), 0))
630 if (!type_updated && changed != NULL)
631 changed->push_back (existing);
633 else if (!type_updated && unchanged != NULL)
634 unchanged->push_back (existing);
638 #if HAVE_PYTHON
640 static bool
641 dynamic_varobj_has_child_method (const struct varobj *var)
643 PyObject *printer = var->dynamic->pretty_printer;
645 if (!gdb_python_initialized)
646 return false;
648 gdbpy_enter_varobj enter_py (var);
649 return PyObject_HasAttr (printer, gdbpy_children_cst);
651 #endif
653 /* A factory for creating dynamic varobj's iterators. Returns an
654 iterator object suitable for iterating over VAR's children. */
656 static std::unique_ptr<varobj_iter>
657 varobj_get_iterator (struct varobj *var)
659 #if HAVE_PYTHON
660 if (var->dynamic->pretty_printer)
661 return py_varobj_get_iterator (var, var->dynamic->pretty_printer);
662 #endif
664 gdb_assert_not_reached ("requested an iterator from a non-dynamic varobj");
667 static bool
668 update_dynamic_varobj_children (struct varobj *var,
669 std::vector<varobj *> *changed,
670 std::vector<varobj *> *type_changed,
671 std::vector<varobj *> *newobj,
672 std::vector<varobj *> *unchanged,
673 bool *cchanged,
674 bool update_children,
675 int from,
676 int to)
678 int i;
680 *cchanged = false;
682 if (update_children || var->dynamic->child_iter == NULL)
684 var->dynamic->child_iter = varobj_get_iterator (var);
685 var->dynamic->saved_item.reset (nullptr);
687 i = 0;
689 if (var->dynamic->child_iter == NULL)
690 return false;
692 else
693 i = var->children.size ();
695 /* We ask for one extra child, so that MI can report whether there
696 are more children. */
697 for (; to < 0 || i < to + 1; ++i)
699 std::unique_ptr<varobj_item> item;
701 /* See if there was a leftover from last time. */
702 if (var->dynamic->saved_item != NULL)
703 item = std::move (var->dynamic->saved_item);
704 else
705 item = var->dynamic->child_iter->next ();
707 if (item == NULL)
709 /* Iteration is done. Remove iterator from VAR. */
710 var->dynamic->child_iter.reset (nullptr);
711 break;
713 /* We don't want to push the extra child on any report list. */
714 if (to < 0 || i < to)
716 bool can_mention = from < 0 || i >= from;
718 install_dynamic_child (var, can_mention ? changed : NULL,
719 can_mention ? type_changed : NULL,
720 can_mention ? newobj : NULL,
721 can_mention ? unchanged : NULL,
722 can_mention ? cchanged : NULL, i,
723 item.get ());
725 else
727 var->dynamic->saved_item = std::move (item);
729 /* We want to truncate the child list just before this
730 element. */
731 break;
735 if (i < var->children.size ())
737 *cchanged = true;
738 for (int j = i; j < var->children.size (); ++j)
739 varobj_delete (var->children[j], 0);
741 var->children.resize (i);
744 /* If there are fewer children than requested, note that the list of
745 children changed. */
746 if (to >= 0 && var->children.size () < to)
747 *cchanged = true;
749 var->num_children = var->children.size ();
751 return true;
755 varobj_get_num_children (struct varobj *var)
757 if (var->num_children == -1)
759 if (varobj_is_dynamic_p (var))
761 bool dummy;
763 /* If we have a dynamic varobj, don't report -1 children.
764 So, try to fetch some children first. */
765 update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL, &dummy,
766 false, 0, 0);
768 else
769 var->num_children = number_of_children (var);
772 return var->num_children >= 0 ? var->num_children : 0;
775 /* Creates a list of the immediate children of a variable object;
776 the return code is the number of such children or -1 on error. */
778 const std::vector<varobj *> &
779 varobj_list_children (struct varobj *var, int *from, int *to)
781 var->dynamic->children_requested = true;
783 if (varobj_is_dynamic_p (var))
785 bool children_changed;
787 /* This, in theory, can result in the number of children changing without
788 frontend noticing. But well, calling -var-list-children on the same
789 varobj twice is not something a sane frontend would do. */
790 update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL,
791 &children_changed, false, 0, *to);
792 varobj_restrict_range (var->children, from, to);
793 return var->children;
796 if (var->num_children == -1)
797 var->num_children = number_of_children (var);
799 /* If that failed, give up. */
800 if (var->num_children == -1)
801 return var->children;
803 /* If we're called when the list of children is not yet initialized,
804 allocate enough elements in it. */
805 while (var->children.size () < var->num_children)
806 var->children.push_back (NULL);
808 for (int i = 0; i < var->num_children; i++)
810 if (var->children[i] == NULL)
812 /* Either it's the first call to varobj_list_children for
813 this variable object, and the child was never created,
814 or it was explicitly deleted by the client. */
815 std::string name = name_of_child (var, i);
816 var->children[i] = create_child (var, i, name);
820 varobj_restrict_range (var->children, from, to);
821 return var->children;
824 static struct varobj *
825 varobj_add_child (struct varobj *var, struct varobj_item *item)
827 varobj *v = create_child_with_value (var, var->children.size (), item);
829 var->children.push_back (v);
831 return v;
834 /* Obtain the type of an object Variable as a string similar to the one gdb
835 prints on the console. The caller is responsible for freeing the string.
838 std::string
839 varobj_get_type (struct varobj *var)
841 /* For the "fake" variables, do not return a type. (Its type is
842 NULL, too.)
843 Do not return a type for invalid variables as well. */
844 if (CPLUS_FAKE_CHILD (var) || !var->root->is_valid)
845 return std::string ();
847 return type_to_string (var->type);
850 /* Obtain the type of an object variable. */
852 struct type *
853 varobj_get_gdb_type (const struct varobj *var)
855 return var->type;
858 /* Is VAR a path expression parent, i.e., can it be used to construct
859 a valid path expression? */
861 static bool
862 is_path_expr_parent (const struct varobj *var)
864 gdb_assert (var->root->lang_ops->is_path_expr_parent != NULL);
865 return var->root->lang_ops->is_path_expr_parent (var);
868 /* Is VAR a path expression parent, i.e., can it be used to construct
869 a valid path expression? By default we assume any VAR can be a path
870 parent. */
872 bool
873 varobj_default_is_path_expr_parent (const struct varobj *var)
875 return true;
878 /* Return the path expression parent for VAR. */
880 const struct varobj *
881 varobj_get_path_expr_parent (const struct varobj *var)
883 const struct varobj *parent = var;
885 while (!is_root_p (parent) && !is_path_expr_parent (parent))
886 parent = parent->parent;
888 /* Computation of full rooted expression for children of dynamic
889 varobjs is not supported. */
890 if (varobj_is_dynamic_p (parent))
891 error (_("Invalid variable object (child of a dynamic varobj)"));
893 return parent;
896 /* Return a pointer to the full rooted expression of varobj VAR.
897 If it has not been computed yet, compute it. */
899 const char *
900 varobj_get_path_expr (const struct varobj *var)
902 if (var->path_expr.empty ())
904 /* For root varobjs, we initialize path_expr
905 when creating varobj, so here it should be
906 child varobj. */
907 struct varobj *mutable_var = (struct varobj *) var;
908 gdb_assert (!is_root_p (var));
910 mutable_var->path_expr = (*var->root->lang_ops->path_expr_of_child) (var);
913 return var->path_expr.c_str ();
916 const struct language_defn *
917 varobj_get_language (const struct varobj *var)
919 return var->root->exp->language_defn;
923 varobj_get_attributes (const struct varobj *var)
925 int attributes = 0;
927 if (varobj_editable_p (var))
928 /* FIXME: define masks for attributes. */
929 attributes |= 0x00000001; /* Editable */
931 return attributes;
934 /* Return true if VAR is a dynamic varobj. */
936 bool
937 varobj_is_dynamic_p (const struct varobj *var)
939 return var->dynamic->pretty_printer != NULL;
942 std::string
943 varobj_get_formatted_value (struct varobj *var,
944 enum varobj_display_formats format)
946 return my_value_of_variable (var, format);
949 std::string
950 varobj_get_value (struct varobj *var)
952 return my_value_of_variable (var, var->format);
955 /* Set the value of an object variable (if it is editable) to the
956 value of the given expression. */
957 /* Note: Invokes functions that can call error(). */
959 bool
960 varobj_set_value (struct varobj *var, const char *expression)
962 struct value *val = NULL; /* Initialize to keep gcc happy. */
963 /* The argument "expression" contains the variable's new value.
964 We need to first construct a legal expression for this -- ugh! */
965 /* Does this cover all the bases? */
966 struct value *value = NULL; /* Initialize to keep gcc happy. */
967 int saved_input_radix = input_radix;
968 const char *s = expression;
970 gdb_assert (varobj_editable_p (var));
972 input_radix = 10; /* ALWAYS reset to decimal temporarily. */
973 expression_up exp = parse_exp_1 (&s, 0, 0, 0);
976 value = evaluate_expression (exp.get ());
979 catch (const gdb_exception_error &except)
981 /* We cannot proceed without a valid expression. */
982 return false;
985 /* All types that are editable must also be changeable. */
986 gdb_assert (varobj_value_is_changeable_p (var));
988 /* The value of a changeable variable object must not be lazy. */
989 gdb_assert (!value_lazy (var->value.get ()));
991 /* Need to coerce the input. We want to check if the
992 value of the variable object will be different
993 after assignment, and the first thing value_assign
994 does is coerce the input.
995 For example, if we are assigning an array to a pointer variable we
996 should compare the pointer with the array's address, not with the
997 array's content. */
998 value = coerce_array (value);
1000 /* The new value may be lazy. value_assign, or
1001 rather value_contents, will take care of this. */
1004 val = value_assign (var->value.get (), value);
1007 catch (const gdb_exception_error &except)
1009 return false;
1012 /* If the value has changed, record it, so that next -var-update can
1013 report this change. If a variable had a value of '1', we've set it
1014 to '333' and then set again to '1', when -var-update will report this
1015 variable as changed -- because the first assignment has set the
1016 'updated' flag. There's no need to optimize that, because return value
1017 of -var-update should be considered an approximation. */
1018 var->updated = install_new_value (var, val, false /* Compare values. */);
1019 input_radix = saved_input_radix;
1020 return true;
1023 #if HAVE_PYTHON
1025 /* A helper function to install a constructor function and visualizer
1026 in a varobj_dynamic. */
1028 static void
1029 install_visualizer (struct varobj_dynamic *var, PyObject *constructor,
1030 PyObject *visualizer)
1032 Py_XDECREF (var->constructor);
1033 var->constructor = constructor;
1035 Py_XDECREF (var->pretty_printer);
1036 var->pretty_printer = visualizer;
1038 var->child_iter.reset (nullptr);
1041 /* Install the default visualizer for VAR. */
1043 static void
1044 install_default_visualizer (struct varobj *var)
1046 /* Do not install a visualizer on a CPLUS_FAKE_CHILD. */
1047 if (CPLUS_FAKE_CHILD (var))
1048 return;
1050 if (pretty_printing)
1052 gdbpy_ref<> pretty_printer;
1054 if (var->value != nullptr)
1056 pretty_printer = gdbpy_get_varobj_pretty_printer (var->value.get ());
1057 if (pretty_printer == nullptr)
1059 gdbpy_print_stack ();
1060 error (_("Cannot instantiate printer for default visualizer"));
1064 if (pretty_printer == Py_None)
1065 pretty_printer.reset (nullptr);
1067 install_visualizer (var->dynamic, NULL, pretty_printer.release ());
1071 /* Instantiate and install a visualizer for VAR using CONSTRUCTOR to
1072 make a new object. */
1074 static void
1075 construct_visualizer (struct varobj *var, PyObject *constructor)
1077 PyObject *pretty_printer;
1079 /* Do not install a visualizer on a CPLUS_FAKE_CHILD. */
1080 if (CPLUS_FAKE_CHILD (var))
1081 return;
1083 Py_INCREF (constructor);
1084 if (constructor == Py_None)
1085 pretty_printer = NULL;
1086 else
1088 pretty_printer = instantiate_pretty_printer (constructor,
1089 var->value.get ());
1090 if (! pretty_printer)
1092 gdbpy_print_stack ();
1093 Py_DECREF (constructor);
1094 constructor = Py_None;
1095 Py_INCREF (constructor);
1098 if (pretty_printer == Py_None)
1100 Py_DECREF (pretty_printer);
1101 pretty_printer = NULL;
1105 install_visualizer (var->dynamic, constructor, pretty_printer);
1108 #endif /* HAVE_PYTHON */
1110 /* A helper function for install_new_value. This creates and installs
1111 a visualizer for VAR, if appropriate. */
1113 static void
1114 install_new_value_visualizer (struct varobj *var)
1116 #if HAVE_PYTHON
1117 /* If the constructor is None, then we want the raw value. If VAR
1118 does not have a value, just skip this. */
1119 if (!gdb_python_initialized)
1120 return;
1122 if (var->dynamic->constructor != Py_None && var->value != NULL)
1124 gdbpy_enter_varobj enter_py (var);
1126 if (var->dynamic->constructor == NULL)
1127 install_default_visualizer (var);
1128 else
1129 construct_visualizer (var, var->dynamic->constructor);
1131 #else
1132 /* Do nothing. */
1133 #endif
1136 /* When using RTTI to determine variable type it may be changed in runtime when
1137 the variable value is changed. This function checks whether type of varobj
1138 VAR will change when a new value NEW_VALUE is assigned and if it is so
1139 updates the type of VAR. */
1141 static bool
1142 update_type_if_necessary (struct varobj *var, struct value *new_value)
1144 if (new_value)
1146 struct value_print_options opts;
1148 get_user_print_options (&opts);
1149 if (opts.objectprint)
1151 struct type *new_type = value_actual_type (new_value, 0, 0);
1152 std::string new_type_str = type_to_string (new_type);
1153 std::string curr_type_str = varobj_get_type (var);
1155 /* Did the type name change? */
1156 if (curr_type_str != new_type_str)
1158 var->type = new_type;
1160 /* This information may be not valid for a new type. */
1161 varobj_delete (var, 1);
1162 var->children.clear ();
1163 var->num_children = -1;
1164 return true;
1169 return false;
1172 /* Assign a new value to a variable object. If INITIAL is true,
1173 this is the first assignment after the variable object was just
1174 created, or changed type. In that case, just assign the value
1175 and return false.
1176 Otherwise, assign the new value, and return true if the value is
1177 different from the current one, false otherwise. The comparison is
1178 done on textual representation of value. Therefore, some types
1179 need not be compared. E.g. for structures the reported value is
1180 always "{...}", so no comparison is necessary here. If the old
1181 value was NULL and new one is not, or vice versa, we always return true.
1183 The VALUE parameter should not be released -- the function will
1184 take care of releasing it when needed. */
1185 static bool
1186 install_new_value (struct varobj *var, struct value *value, bool initial)
1188 bool changeable;
1189 bool need_to_fetch;
1190 bool changed = false;
1191 bool intentionally_not_fetched = false;
1193 /* We need to know the varobj's type to decide if the value should
1194 be fetched or not. C++ fake children (public/protected/private)
1195 don't have a type. */
1196 gdb_assert (var->type || CPLUS_FAKE_CHILD (var));
1197 changeable = varobj_value_is_changeable_p (var);
1199 /* If the type has custom visualizer, we consider it to be always
1200 changeable. FIXME: need to make sure this behaviour will not
1201 mess up read-sensitive values. */
1202 if (var->dynamic->pretty_printer != NULL)
1203 changeable = true;
1205 need_to_fetch = changeable;
1207 /* We are not interested in the address of references, and given
1208 that in C++ a reference is not rebindable, it cannot
1209 meaningfully change. So, get hold of the real value. */
1210 if (value)
1211 value = coerce_ref (value);
1213 if (var->type && var->type->code () == TYPE_CODE_UNION)
1214 /* For unions, we need to fetch the value implicitly because
1215 of implementation of union member fetch. When gdb
1216 creates a value for a field and the value of the enclosing
1217 structure is not lazy, it immediately copies the necessary
1218 bytes from the enclosing values. If the enclosing value is
1219 lazy, the call to value_fetch_lazy on the field will read
1220 the data from memory. For unions, that means we'll read the
1221 same memory more than once, which is not desirable. So
1222 fetch now. */
1223 need_to_fetch = true;
1225 /* The new value might be lazy. If the type is changeable,
1226 that is we'll be comparing values of this type, fetch the
1227 value now. Otherwise, on the next update the old value
1228 will be lazy, which means we've lost that old value. */
1229 if (need_to_fetch && value && value_lazy (value))
1231 const struct varobj *parent = var->parent;
1232 bool frozen = var->frozen;
1234 for (; !frozen && parent; parent = parent->parent)
1235 frozen |= parent->frozen;
1237 if (frozen && initial)
1239 /* For variables that are frozen, or are children of frozen
1240 variables, we don't do fetch on initial assignment.
1241 For non-initial assignment we do the fetch, since it means we're
1242 explicitly asked to compare the new value with the old one. */
1243 intentionally_not_fetched = true;
1245 else
1250 value_fetch_lazy (value);
1253 catch (const gdb_exception_error &except)
1255 /* Set the value to NULL, so that for the next -var-update,
1256 we don't try to compare the new value with this value,
1257 that we couldn't even read. */
1258 value = NULL;
1263 /* Get a reference now, before possibly passing it to any Python
1264 code that might release it. */
1265 value_ref_ptr value_holder;
1266 if (value != NULL)
1267 value_holder = value_ref_ptr::new_reference (value);
1269 /* Below, we'll be comparing string rendering of old and new
1270 values. Don't get string rendering if the value is
1271 lazy -- if it is, the code above has decided that the value
1272 should not be fetched. */
1273 std::string print_value;
1274 if (value != NULL && !value_lazy (value)
1275 && var->dynamic->pretty_printer == NULL)
1276 print_value = varobj_value_get_print_value (value, var->format, var);
1278 /* If the type is changeable, compare the old and the new values.
1279 If this is the initial assignment, we don't have any old value
1280 to compare with. */
1281 if (!initial && changeable)
1283 /* If the value of the varobj was changed by -var-set-value,
1284 then the value in the varobj and in the target is the same.
1285 However, that value is different from the value that the
1286 varobj had after the previous -var-update. So need to the
1287 varobj as changed. */
1288 if (var->updated)
1289 changed = true;
1290 else if (var->dynamic->pretty_printer == NULL)
1292 /* Try to compare the values. That requires that both
1293 values are non-lazy. */
1294 if (var->not_fetched && value_lazy (var->value.get ()))
1296 /* This is a frozen varobj and the value was never read.
1297 Presumably, UI shows some "never read" indicator.
1298 Now that we've fetched the real value, we need to report
1299 this varobj as changed so that UI can show the real
1300 value. */
1301 changed = true;
1303 else if (var->value == NULL && value == NULL)
1304 /* Equal. */
1306 else if (var->value == NULL || value == NULL)
1308 changed = true;
1310 else
1312 gdb_assert (!value_lazy (var->value.get ()));
1313 gdb_assert (!value_lazy (value));
1315 gdb_assert (!var->print_value.empty () && !print_value.empty ());
1316 if (var->print_value != print_value)
1317 changed = true;
1322 if (!initial && !changeable)
1324 /* For values that are not changeable, we don't compare the values.
1325 However, we want to notice if a value was not NULL and now is NULL,
1326 or vise versa, so that we report when top-level varobjs come in scope
1327 and leave the scope. */
1328 changed = (var->value != NULL) != (value != NULL);
1331 /* We must always keep the new value, since children depend on it. */
1332 var->value = value_holder;
1333 if (value && value_lazy (value) && intentionally_not_fetched)
1334 var->not_fetched = true;
1335 else
1336 var->not_fetched = false;
1337 var->updated = false;
1339 install_new_value_visualizer (var);
1341 /* If we installed a pretty-printer, re-compare the printed version
1342 to see if the variable changed. */
1343 if (var->dynamic->pretty_printer != NULL)
1345 print_value = varobj_value_get_print_value (var->value.get (),
1346 var->format, var);
1347 if (var->print_value != print_value)
1348 changed = true;
1350 var->print_value = print_value;
1352 gdb_assert (var->value == nullptr || value_type (var->value.get ()));
1354 return changed;
1357 /* Return the requested range for a varobj. VAR is the varobj. FROM
1358 and TO are out parameters; *FROM and *TO will be set to the
1359 selected sub-range of VAR. If no range was selected using
1360 -var-set-update-range, then both will be -1. */
1361 void
1362 varobj_get_child_range (const struct varobj *var, int *from, int *to)
1364 *from = var->from;
1365 *to = var->to;
1368 /* Set the selected sub-range of children of VAR to start at index
1369 FROM and end at index TO. If either FROM or TO is less than zero,
1370 this is interpreted as a request for all children. */
1371 void
1372 varobj_set_child_range (struct varobj *var, int from, int to)
1374 var->from = from;
1375 var->to = to;
1378 void
1379 varobj_set_visualizer (struct varobj *var, const char *visualizer)
1381 #if HAVE_PYTHON
1382 PyObject *mainmod;
1384 if (!gdb_python_initialized)
1385 return;
1387 gdbpy_enter_varobj enter_py (var);
1389 mainmod = PyImport_AddModule ("__main__");
1390 gdbpy_ref<> globals
1391 = gdbpy_ref<>::new_reference (PyModule_GetDict (mainmod));
1392 gdbpy_ref<> constructor (PyRun_String (visualizer, Py_eval_input,
1393 globals.get (), globals.get ()));
1395 if (constructor == NULL)
1397 gdbpy_print_stack ();
1398 error (_("Could not evaluate visualizer expression: %s"), visualizer);
1401 construct_visualizer (var, constructor.get ());
1403 /* If there are any children now, wipe them. */
1404 varobj_delete (var, 1 /* children only */);
1405 var->num_children = -1;
1406 #else
1407 error (_("Python support required"));
1408 #endif
1411 /* If NEW_VALUE is the new value of the given varobj (var), return
1412 true if var has mutated. In other words, if the type of
1413 the new value is different from the type of the varobj's old
1414 value.
1416 NEW_VALUE may be NULL, if the varobj is now out of scope. */
1418 static bool
1419 varobj_value_has_mutated (const struct varobj *var, struct value *new_value,
1420 struct type *new_type)
1422 /* If we haven't previously computed the number of children in var,
1423 it does not matter from the front-end's perspective whether
1424 the type has mutated or not. For all intents and purposes,
1425 it has not mutated. */
1426 if (var->num_children < 0)
1427 return false;
1429 if (var->root->lang_ops->value_has_mutated != NULL)
1431 /* The varobj module, when installing new values, explicitly strips
1432 references, saying that we're not interested in those addresses.
1433 But detection of mutation happens before installing the new
1434 value, so our value may be a reference that we need to strip
1435 in order to remain consistent. */
1436 if (new_value != NULL)
1437 new_value = coerce_ref (new_value);
1438 return var->root->lang_ops->value_has_mutated (var, new_value, new_type);
1440 else
1441 return false;
1444 /* Update the values for a variable and its children. This is a
1445 two-pronged attack. First, re-parse the value for the root's
1446 expression to see if it's changed. Then go all the way
1447 through its children, reconstructing them and noting if they've
1448 changed.
1450 The IS_EXPLICIT parameter specifies if this call is result
1451 of MI request to update this specific variable, or
1452 result of implicit -var-update *. For implicit request, we don't
1453 update frozen variables.
1455 NOTE: This function may delete the caller's varobj. If it
1456 returns TYPE_CHANGED, then it has done this and VARP will be modified
1457 to point to the new varobj. */
1459 std::vector<varobj_update_result>
1460 varobj_update (struct varobj **varp, bool is_explicit)
1462 bool type_changed = false;
1463 struct value *newobj;
1464 std::vector<varobj_update_result> stack;
1465 std::vector<varobj_update_result> result;
1467 /* Frozen means frozen -- we don't check for any change in
1468 this varobj, including its going out of scope, or
1469 changing type. One use case for frozen varobjs is
1470 retaining previously evaluated expressions, and we don't
1471 want them to be reevaluated at all. */
1472 if (!is_explicit && (*varp)->frozen)
1473 return result;
1475 if (!(*varp)->root->is_valid)
1477 result.emplace_back (*varp, VAROBJ_INVALID);
1478 return result;
1481 if ((*varp)->root->rootvar == *varp)
1483 varobj_update_result r (*varp);
1485 /* Update the root variable. value_of_root can return NULL
1486 if the variable is no longer around, i.e. we stepped out of
1487 the frame in which a local existed. We are letting the
1488 value_of_root variable dispose of the varobj if the type
1489 has changed. */
1490 newobj = value_of_root (varp, &type_changed);
1491 if (update_type_if_necessary (*varp, newobj))
1492 type_changed = true;
1493 r.varobj = *varp;
1494 r.type_changed = type_changed;
1495 if (install_new_value ((*varp), newobj, type_changed))
1496 r.changed = true;
1498 if (newobj == NULL)
1499 r.status = VAROBJ_NOT_IN_SCOPE;
1500 r.value_installed = true;
1502 if (r.status == VAROBJ_NOT_IN_SCOPE)
1504 if (r.type_changed || r.changed)
1505 result.push_back (std::move (r));
1507 return result;
1510 stack.push_back (std::move (r));
1512 else
1513 stack.emplace_back (*varp);
1515 /* Walk through the children, reconstructing them all. */
1516 while (!stack.empty ())
1518 varobj_update_result r = std::move (stack.back ());
1519 stack.pop_back ();
1520 struct varobj *v = r.varobj;
1522 /* Update this variable, unless it's a root, which is already
1523 updated. */
1524 if (!r.value_installed)
1526 struct type *new_type;
1528 newobj = value_of_child (v->parent, v->index);
1529 if (update_type_if_necessary (v, newobj))
1530 r.type_changed = true;
1531 if (newobj)
1532 new_type = value_type (newobj);
1533 else
1534 new_type = v->root->lang_ops->type_of_child (v->parent, v->index);
1536 if (varobj_value_has_mutated (v, newobj, new_type))
1538 /* The children are no longer valid; delete them now.
1539 Report the fact that its type changed as well. */
1540 varobj_delete (v, 1 /* only_children */);
1541 v->num_children = -1;
1542 v->to = -1;
1543 v->from = -1;
1544 v->type = new_type;
1545 r.type_changed = true;
1548 if (install_new_value (v, newobj, r.type_changed))
1550 r.changed = true;
1551 v->updated = false;
1555 /* We probably should not get children of a dynamic varobj, but
1556 for which -var-list-children was never invoked. */
1557 if (varobj_is_dynamic_p (v))
1559 std::vector<varobj *> changed, type_changed_vec, unchanged, newobj_vec;
1560 bool children_changed = false;
1562 if (v->frozen)
1563 continue;
1565 if (!v->dynamic->children_requested)
1567 bool dummy;
1569 /* If we initially did not have potential children, but
1570 now we do, consider the varobj as changed.
1571 Otherwise, if children were never requested, consider
1572 it as unchanged -- presumably, such varobj is not yet
1573 expanded in the UI, so we need not bother getting
1574 it. */
1575 if (!varobj_has_more (v, 0))
1577 update_dynamic_varobj_children (v, NULL, NULL, NULL, NULL,
1578 &dummy, false, 0, 0);
1579 if (varobj_has_more (v, 0))
1580 r.changed = true;
1583 if (r.changed)
1584 result.push_back (std::move (r));
1586 continue;
1589 /* If update_dynamic_varobj_children returns false, then we have
1590 a non-conforming pretty-printer, so we skip it. */
1591 if (update_dynamic_varobj_children (v, &changed, &type_changed_vec,
1592 &newobj_vec,
1593 &unchanged, &children_changed,
1594 true, v->from, v->to))
1596 if (children_changed || !newobj_vec.empty ())
1598 r.children_changed = true;
1599 r.newobj = std::move (newobj_vec);
1601 /* Push in reverse order so that the first child is
1602 popped from the work stack first, and so will be
1603 added to result first. This does not affect
1604 correctness, just "nicer". */
1605 for (int i = type_changed_vec.size () - 1; i >= 0; --i)
1607 varobj_update_result item (type_changed_vec[i]);
1609 /* Type may change only if value was changed. */
1610 item.changed = true;
1611 item.type_changed = true;
1612 item.value_installed = true;
1614 stack.push_back (std::move (item));
1616 for (int i = changed.size () - 1; i >= 0; --i)
1618 varobj_update_result item (changed[i]);
1620 item.changed = true;
1621 item.value_installed = true;
1623 stack.push_back (std::move (item));
1625 for (int i = unchanged.size () - 1; i >= 0; --i)
1627 if (!unchanged[i]->frozen)
1629 varobj_update_result item (unchanged[i]);
1631 item.value_installed = true;
1633 stack.push_back (std::move (item));
1636 if (r.changed || r.children_changed)
1637 result.push_back (std::move (r));
1639 continue;
1643 /* Push any children. Use reverse order so that the first
1644 child is popped from the work stack first, and so
1645 will be added to result first. This does not
1646 affect correctness, just "nicer". */
1647 for (int i = v->children.size () - 1; i >= 0; --i)
1649 varobj *c = v->children[i];
1651 /* Child may be NULL if explicitly deleted by -var-delete. */
1652 if (c != NULL && !c->frozen)
1653 stack.emplace_back (c);
1656 if (r.changed || r.type_changed)
1657 result.push_back (std::move (r));
1660 return result;
1663 /* Helper functions */
1666 * Variable object construction/destruction
1669 static int
1670 delete_variable (struct varobj *var, bool only_children_p)
1672 int delcount = 0;
1674 delete_variable_1 (&delcount, var, only_children_p,
1675 true /* remove_from_parent_p */ );
1677 return delcount;
1680 /* Delete the variable object VAR and its children. */
1681 /* IMPORTANT NOTE: If we delete a variable which is a child
1682 and the parent is not removed we dump core. It must be always
1683 initially called with remove_from_parent_p set. */
1684 static void
1685 delete_variable_1 (int *delcountp, struct varobj *var, bool only_children_p,
1686 bool remove_from_parent_p)
1688 /* Delete any children of this variable, too. */
1689 for (varobj *child : var->children)
1691 if (!child)
1692 continue;
1694 if (!remove_from_parent_p)
1695 child->parent = NULL;
1697 delete_variable_1 (delcountp, child, false, only_children_p);
1699 var->children.clear ();
1701 /* if we were called to delete only the children we are done here. */
1702 if (only_children_p)
1703 return;
1705 /* Otherwise, add it to the list of deleted ones and proceed to do so. */
1706 /* If the name is empty, this is a temporary variable, that has not
1707 yet been installed, don't report it, it belongs to the caller... */
1708 if (!var->obj_name.empty ())
1710 *delcountp = *delcountp + 1;
1713 /* If this variable has a parent, remove it from its parent's list. */
1714 /* OPTIMIZATION: if the parent of this variable is also being deleted,
1715 (as indicated by remove_from_parent_p) we don't bother doing an
1716 expensive list search to find the element to remove when we are
1717 discarding the list afterwards. */
1718 if ((remove_from_parent_p) && (var->parent != NULL))
1719 var->parent->children[var->index] = NULL;
1721 if (!var->obj_name.empty ())
1722 uninstall_variable (var);
1724 /* Free memory associated with this variable. */
1725 delete var;
1728 /* Install the given variable VAR with the object name VAR->OBJ_NAME. */
1729 static void
1730 install_variable (struct varobj *var)
1732 hashval_t hash = htab_hash_string (var->obj_name.c_str ());
1733 void **slot = htab_find_slot_with_hash (varobj_table,
1734 var->obj_name.c_str (),
1735 hash, INSERT);
1736 if (*slot != nullptr)
1737 error (_("Duplicate variable object name"));
1739 /* Add varobj to hash table. */
1740 *slot = var;
1742 /* If root, add varobj to root list. */
1743 if (is_root_p (var))
1744 rootlist.push_front (var->root);
1747 /* Uninstall the object VAR. */
1748 static void
1749 uninstall_variable (struct varobj *var)
1751 hashval_t hash = htab_hash_string (var->obj_name.c_str ());
1752 htab_remove_elt_with_hash (varobj_table, var->obj_name.c_str (), hash);
1754 if (varobjdebug)
1755 gdb_printf (gdb_stdlog, "Deleting %s\n", var->obj_name.c_str ());
1757 /* If root, remove varobj from root list. */
1758 if (is_root_p (var))
1760 auto iter = std::find (rootlist.begin (), rootlist.end (), var->root);
1761 rootlist.erase (iter);
1765 /* Create and install a child of the parent of the given name.
1767 The created VAROBJ takes ownership of the allocated NAME. */
1769 static struct varobj *
1770 create_child (struct varobj *parent, int index, std::string &name)
1772 struct varobj_item item;
1774 std::swap (item.name, name);
1775 item.value = release_value (value_of_child (parent, index));
1777 return create_child_with_value (parent, index, &item);
1780 static struct varobj *
1781 create_child_with_value (struct varobj *parent, int index,
1782 struct varobj_item *item)
1784 varobj *child = new varobj (parent->root);
1786 /* NAME is allocated by caller. */
1787 std::swap (child->name, item->name);
1788 child->index = index;
1789 child->parent = parent;
1791 if (varobj_is_anonymous_child (child))
1792 child->obj_name = string_printf ("%s.%d_anonymous",
1793 parent->obj_name.c_str (), index);
1794 else
1795 child->obj_name = string_printf ("%s.%s",
1796 parent->obj_name.c_str (),
1797 child->name.c_str ());
1799 install_variable (child);
1801 /* Compute the type of the child. Must do this before
1802 calling install_new_value. */
1803 if (item->value != NULL)
1804 /* If the child had no evaluation errors, var->value
1805 will be non-NULL and contain a valid type. */
1806 child->type = value_actual_type (item->value.get (), 0, NULL);
1807 else
1808 /* Otherwise, we must compute the type. */
1809 child->type = (*child->root->lang_ops->type_of_child) (child->parent,
1810 child->index);
1811 install_new_value (child, item->value.get (), 1);
1813 return child;
1818 * Miscellaneous utility functions.
1821 /* Allocate memory and initialize a new variable. */
1822 varobj::varobj (varobj_root *root_)
1823 : root (root_), dynamic (new varobj_dynamic)
1827 /* Free any allocated memory associated with VAR. */
1829 varobj::~varobj ()
1831 varobj *var = this;
1833 #if HAVE_PYTHON
1834 if (var->dynamic->pretty_printer != NULL)
1836 gdbpy_enter_varobj enter_py (var);
1838 Py_XDECREF (var->dynamic->constructor);
1839 Py_XDECREF (var->dynamic->pretty_printer);
1841 #endif
1843 /* This must be deleted before the root object, because Python-based
1844 destructors need access to some components. */
1845 delete var->dynamic;
1847 if (is_root_p (var))
1848 delete var->root;
1851 /* Return the type of the value that's stored in VAR,
1852 or that would have being stored there if the
1853 value were accessible.
1855 This differs from VAR->type in that VAR->type is always
1856 the true type of the expression in the source language.
1857 The return value of this function is the type we're
1858 actually storing in varobj, and using for displaying
1859 the values and for comparing previous and new values.
1861 For example, top-level references are always stripped. */
1862 struct type *
1863 varobj_get_value_type (const struct varobj *var)
1865 struct type *type;
1867 if (var->value != nullptr)
1868 type = value_type (var->value.get ());
1869 else
1870 type = var->type;
1872 type = check_typedef (type);
1874 if (TYPE_IS_REFERENCE (type))
1875 type = get_target_type (type);
1877 type = check_typedef (type);
1879 return type;
1882 /* What is the default display for this variable? We assume that
1883 everything is "natural". Any exceptions? */
1884 static enum varobj_display_formats
1885 variable_default_display (struct varobj *var)
1887 return FORMAT_NATURAL;
1891 * Language-dependencies
1894 /* Common entry points */
1896 /* Return the number of children for a given variable.
1897 The result of this function is defined by the language
1898 implementation. The number of children returned by this function
1899 is the number of children that the user will see in the variable
1900 display. */
1901 static int
1902 number_of_children (const struct varobj *var)
1904 return (*var->root->lang_ops->number_of_children) (var);
1907 /* What is the expression for the root varobj VAR? */
1909 static std::string
1910 name_of_variable (const struct varobj *var)
1912 return (*var->root->lang_ops->name_of_variable) (var);
1915 /* What is the name of the INDEX'th child of VAR? */
1917 static std::string
1918 name_of_child (struct varobj *var, int index)
1920 return (*var->root->lang_ops->name_of_child) (var, index);
1923 /* If frame associated with VAR can be found, switch
1924 to it and return true. Otherwise, return false. */
1926 static bool
1927 check_scope (const struct varobj *var)
1929 struct frame_info *fi;
1930 bool scope;
1932 fi = frame_find_by_id (var->root->frame);
1933 scope = fi != NULL;
1935 if (fi)
1937 CORE_ADDR pc = get_frame_pc (fi);
1939 if (pc < var->root->valid_block->start () ||
1940 pc >= var->root->valid_block->end ())
1941 scope = false;
1942 else
1943 select_frame (fi);
1945 return scope;
1948 /* Helper function to value_of_root. */
1950 static struct value *
1951 value_of_root_1 (struct varobj **var_handle)
1953 struct value *new_val = NULL;
1954 struct varobj *var = *var_handle;
1955 bool within_scope = false;
1957 /* Only root variables can be updated... */
1958 if (!is_root_p (var))
1959 /* Not a root var. */
1960 return NULL;
1962 scoped_restore_current_thread restore_thread;
1964 /* Determine whether the variable is still around. */
1965 if (var->root->valid_block == NULL || var->root->floating)
1966 within_scope = true;
1967 else if (var->root->thread_id == 0)
1969 /* The program was single-threaded when the variable object was
1970 created. Technically, it's possible that the program became
1971 multi-threaded since then, but we don't support such
1972 scenario yet. */
1973 within_scope = check_scope (var);
1975 else
1977 thread_info *thread = find_thread_global_id (var->root->thread_id);
1979 if (thread != NULL)
1981 switch_to_thread (thread);
1982 within_scope = check_scope (var);
1986 if (within_scope)
1989 /* We need to catch errors here, because if evaluate
1990 expression fails we want to just return NULL. */
1993 new_val = evaluate_expression (var->root->exp.get ());
1995 catch (const gdb_exception_error &except)
2000 return new_val;
2003 /* What is the ``struct value *'' of the root variable VAR?
2004 For floating variable object, evaluation can get us a value
2005 of different type from what is stored in varobj already. In
2006 that case:
2007 - *type_changed will be set to 1
2008 - old varobj will be freed, and new one will be
2009 created, with the same name.
2010 - *var_handle will be set to the new varobj
2011 Otherwise, *type_changed will be set to 0. */
2012 static struct value *
2013 value_of_root (struct varobj **var_handle, bool *type_changed)
2015 struct varobj *var;
2017 if (var_handle == NULL)
2018 return NULL;
2020 var = *var_handle;
2022 /* This should really be an exception, since this should
2023 only get called with a root variable. */
2025 if (!is_root_p (var))
2026 return NULL;
2028 if (var->root->floating)
2030 struct varobj *tmp_var;
2032 tmp_var = varobj_create (NULL, var->name.c_str (), (CORE_ADDR) 0,
2033 USE_SELECTED_FRAME);
2034 if (tmp_var == NULL)
2036 return NULL;
2038 std::string old_type = varobj_get_type (var);
2039 std::string new_type = varobj_get_type (tmp_var);
2040 if (old_type == new_type)
2042 /* The expression presently stored inside var->root->exp
2043 remembers the locations of local variables relatively to
2044 the frame where the expression was created (in DWARF location
2045 button, for example). Naturally, those locations are not
2046 correct in other frames, so update the expression. */
2048 std::swap (var->root->exp, tmp_var->root->exp);
2050 varobj_delete (tmp_var, 0);
2051 *type_changed = 0;
2053 else
2055 tmp_var->obj_name = var->obj_name;
2056 tmp_var->from = var->from;
2057 tmp_var->to = var->to;
2058 varobj_delete (var, 0);
2060 install_variable (tmp_var);
2061 *var_handle = tmp_var;
2062 var = *var_handle;
2063 *type_changed = true;
2066 else
2068 *type_changed = 0;
2072 struct value *value;
2074 value = value_of_root_1 (var_handle);
2075 if (var->value == NULL || value == NULL)
2077 /* For root varobj-s, a NULL value indicates a scoping issue.
2078 So, nothing to do in terms of checking for mutations. */
2080 else if (varobj_value_has_mutated (var, value, value_type (value)))
2082 /* The type has mutated, so the children are no longer valid.
2083 Just delete them, and tell our caller that the type has
2084 changed. */
2085 varobj_delete (var, 1 /* only_children */);
2086 var->num_children = -1;
2087 var->to = -1;
2088 var->from = -1;
2089 *type_changed = true;
2091 return value;
2095 /* What is the ``struct value *'' for the INDEX'th child of PARENT? */
2096 static struct value *
2097 value_of_child (const struct varobj *parent, int index)
2099 struct value *value;
2101 value = (*parent->root->lang_ops->value_of_child) (parent, index);
2103 return value;
2106 /* GDB already has a command called "value_of_variable". Sigh. */
2107 static std::string
2108 my_value_of_variable (struct varobj *var, enum varobj_display_formats format)
2110 if (var->root->is_valid)
2112 if (var->dynamic->pretty_printer != NULL)
2113 return varobj_value_get_print_value (var->value.get (), var->format,
2114 var);
2115 return (*var->root->lang_ops->value_of_variable) (var, format);
2117 else
2118 return std::string ();
2121 void
2122 varobj_formatted_print_options (struct value_print_options *opts,
2123 enum varobj_display_formats format)
2125 get_formatted_print_options (opts, format_code[(int) format]);
2126 opts->deref_ref = 0;
2127 opts->raw = !pretty_printing;
2130 std::string
2131 varobj_value_get_print_value (struct value *value,
2132 enum varobj_display_formats format,
2133 const struct varobj *var)
2135 struct value_print_options opts;
2136 struct type *type = NULL;
2137 long len = 0;
2138 gdb::unique_xmalloc_ptr<char> encoding;
2139 /* Initialize it just to avoid a GCC false warning. */
2140 CORE_ADDR str_addr = 0;
2141 bool string_print = false;
2143 if (value == NULL)
2144 return std::string ();
2146 string_file stb;
2147 std::string thevalue;
2149 #if HAVE_PYTHON
2150 if (gdb_python_initialized)
2152 PyObject *value_formatter = var->dynamic->pretty_printer;
2154 gdbpy_enter_varobj enter_py (var);
2156 if (value_formatter)
2158 /* First check to see if we have any children at all. If so,
2159 we simply return {...}. */
2160 if (dynamic_varobj_has_child_method (var))
2161 return "{...}";
2163 if (PyObject_HasAttr (value_formatter, gdbpy_to_string_cst))
2165 struct value *replacement;
2167 gdbpy_ref<> output = apply_varobj_pretty_printer (value_formatter,
2168 &replacement,
2169 &stb);
2171 /* If we have string like output ... */
2172 if (output != NULL)
2174 /* If this is a lazy string, extract it. For lazy
2175 strings we always print as a string, so set
2176 string_print. */
2177 if (gdbpy_is_lazy_string (output.get ()))
2179 gdbpy_extract_lazy_string (output.get (), &str_addr,
2180 &type, &len, &encoding);
2181 string_print = true;
2183 else
2185 /* If it is a regular (non-lazy) string, extract
2186 it and copy the contents into THEVALUE. If the
2187 hint says to print it as a string, set
2188 string_print. Otherwise just return the extracted
2189 string as a value. */
2191 gdb::unique_xmalloc_ptr<char> s
2192 = python_string_to_target_string (output.get ());
2194 if (s)
2196 struct gdbarch *gdbarch;
2198 gdb::unique_xmalloc_ptr<char> hint
2199 = gdbpy_get_display_hint (value_formatter);
2200 if (hint)
2202 if (!strcmp (hint.get (), "string"))
2203 string_print = true;
2206 thevalue = std::string (s.get ());
2207 len = thevalue.size ();
2208 gdbarch = value_type (value)->arch ();
2209 type = builtin_type (gdbarch)->builtin_char;
2211 if (!string_print)
2212 return thevalue;
2214 else
2215 gdbpy_print_stack ();
2218 /* If the printer returned a replacement value, set VALUE
2219 to REPLACEMENT. If there is not a replacement value,
2220 just use the value passed to this function. */
2221 if (replacement)
2222 value = replacement;
2226 #endif
2228 varobj_formatted_print_options (&opts, format);
2230 /* If the THEVALUE has contents, it is a regular string. */
2231 if (!thevalue.empty ())
2232 current_language->printstr (&stb, type, (gdb_byte *) thevalue.c_str (),
2233 len, encoding.get (), 0, &opts);
2234 else if (string_print)
2235 /* Otherwise, if string_print is set, and it is not a regular
2236 string, it is a lazy string. */
2237 val_print_string (type, encoding.get (), str_addr, len, &stb, &opts);
2238 else
2239 /* All other cases. */
2240 common_val_print (value, &stb, 0, &opts, current_language);
2242 return stb.release ();
2245 bool
2246 varobj_editable_p (const struct varobj *var)
2248 struct type *type;
2250 if (!(var->root->is_valid && var->value != nullptr
2251 && VALUE_LVAL (var->value.get ())))
2252 return false;
2254 type = varobj_get_value_type (var);
2256 switch (type->code ())
2258 case TYPE_CODE_STRUCT:
2259 case TYPE_CODE_UNION:
2260 case TYPE_CODE_ARRAY:
2261 case TYPE_CODE_FUNC:
2262 case TYPE_CODE_METHOD:
2263 return false;
2264 break;
2266 default:
2267 return true;
2268 break;
2272 /* Call VAR's value_is_changeable_p language-specific callback. */
2274 bool
2275 varobj_value_is_changeable_p (const struct varobj *var)
2277 return var->root->lang_ops->value_is_changeable_p (var);
2280 /* Return true if that varobj is floating, that is is always evaluated in the
2281 selected frame, and not bound to thread/frame. Such variable objects
2282 are created using '@' as frame specifier to -var-create. */
2283 bool
2284 varobj_floating_p (const struct varobj *var)
2286 return var->root->floating;
2289 /* Implement the "value_is_changeable_p" varobj callback for most
2290 languages. */
2292 bool
2293 varobj_default_value_is_changeable_p (const struct varobj *var)
2295 bool r;
2296 struct type *type;
2298 if (CPLUS_FAKE_CHILD (var))
2299 return false;
2301 type = varobj_get_value_type (var);
2303 switch (type->code ())
2305 case TYPE_CODE_STRUCT:
2306 case TYPE_CODE_UNION:
2307 case TYPE_CODE_ARRAY:
2308 r = false;
2309 break;
2311 default:
2312 r = true;
2315 return r;
2318 /* Iterate all the existing _root_ VAROBJs and call the FUNC callback
2319 for each one. */
2321 void
2322 all_root_varobjs (gdb::function_view<void (struct varobj *var)> func)
2324 /* Iterate "safely" - handle if the callee deletes its passed VAROBJ. */
2325 auto iter = rootlist.begin ();
2326 auto end = rootlist.end ();
2327 while (iter != end)
2329 auto self = iter++;
2330 func ((*self)->rootvar);
2334 /* Invalidate varobj VAR if it is tied to locals and re-create it if it is
2335 defined on globals. It is a helper for varobj_invalidate.
2337 This function is called after changing the symbol file, in this case the
2338 pointers to "struct type" stored by the varobj are no longer valid. All
2339 varobj must be either re-evaluated, or marked as invalid here. */
2341 static void
2342 varobj_invalidate_iter (struct varobj *var)
2344 /* global and floating var must be re-evaluated. */
2345 if (var->root->floating || var->root->valid_block == NULL)
2347 struct varobj *tmp_var;
2349 /* Try to create a varobj with same expression. If we succeed
2350 replace the old varobj, otherwise invalidate it. */
2351 tmp_var = varobj_create (NULL, var->name.c_str (), (CORE_ADDR) 0,
2352 USE_CURRENT_FRAME);
2353 if (tmp_var != NULL)
2355 tmp_var->obj_name = var->obj_name;
2356 varobj_delete (var, 0);
2357 install_variable (tmp_var);
2359 else
2360 var->root->is_valid = false;
2362 else /* locals must be invalidated. */
2363 var->root->is_valid = false;
2366 /* Invalidate the varobjs that are tied to locals and re-create the ones that
2367 are defined on globals.
2368 Invalidated varobjs will be always printed in_scope="invalid". */
2370 void
2371 varobj_invalidate (void)
2373 all_root_varobjs (varobj_invalidate_iter);
2376 /* A hash function for a varobj. */
2378 static hashval_t
2379 hash_varobj (const void *a)
2381 const varobj *obj = (const varobj *) a;
2382 return htab_hash_string (obj->obj_name.c_str ());
2385 /* A hash table equality function for varobjs. */
2387 static int
2388 eq_varobj_and_string (const void *a, const void *b)
2390 const varobj *obj = (const varobj *) a;
2391 const char *name = (const char *) b;
2393 return obj->obj_name == name;
2396 void _initialize_varobj ();
2397 void
2398 _initialize_varobj ()
2400 varobj_table = htab_create_alloc (5, hash_varobj, eq_varobj_and_string,
2401 nullptr, xcalloc, xfree);
2403 add_setshow_zuinteger_cmd ("varobj", class_maintenance,
2404 &varobjdebug,
2405 _("Set varobj debugging."),
2406 _("Show varobj debugging."),
2407 _("When non-zero, varobj debugging is enabled."),
2408 NULL, show_varobjdebug,
2409 &setdebuglist, &showdebuglist);