gdb/
[platform/upstream/binutils.git] / gdb / varobj.c
1 /* Implementation of the GDB variable objects API.
2
3    Copyright (C) 1999-2013 Free Software Foundation, Inc.
4
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.
9
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.
14
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/>.  */
17
18 #include "defs.h"
19 #include "exceptions.h"
20 #include "value.h"
21 #include "expression.h"
22 #include "frame.h"
23 #include "language.h"
24 #include "gdbcmd.h"
25 #include "block.h"
26 #include "valprint.h"
27
28 #include "gdb_assert.h"
29 #include "gdb_string.h"
30 #include "gdb_regex.h"
31
32 #include "varobj.h"
33 #include "vec.h"
34 #include "gdbthread.h"
35 #include "inferior.h"
36
37 #if HAVE_PYTHON
38 #include "python/python.h"
39 #include "python/python-internal.h"
40 #else
41 typedef int PyObject;
42 #endif
43
44 /* Non-zero if we want to see trace of varobj level stuff.  */
45
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)
50 {
51   fprintf_filtered (file, _("Varobj debugging is %s.\n"), value);
52 }
53
54 /* String representations of gdb's format codes.  */
55 char *varobj_format_string[] =
56   { "natural", "binary", "decimal", "hexadecimal", "octal" };
57
58 /* String representations of gdb's known languages.  */
59 char *varobj_language_string[] = { "C", "C++", "Java" };
60
61 /* True if we want to allow Python-based pretty-printing.  */
62 static int pretty_printing = 0;
63
64 void
65 varobj_enable_pretty_printing (void)
66 {
67   pretty_printing = 1;
68 }
69
70 /* Data structures */
71
72 /* Every root variable has one of these structures saved in its
73    varobj.  Members which must be free'd are noted.  */
74 struct varobj_root
75 {
76
77   /* Alloc'd expression for this parent.  */
78   struct expression *exp;
79
80   /* Block for which this expression is valid.  */
81   const struct block *valid_block;
82
83   /* The frame for this expression.  This field is set iff valid_block is
84      not NULL.  */
85   struct frame_id frame;
86
87   /* The thread ID that this varobj_root belong to.  This field
88      is only valid if valid_block is not NULL.
89      When not 0, indicates which thread 'frame' belongs to.
90      When 0, indicates that the thread list was empty when the varobj_root
91      was created.  */
92   int thread_id;
93
94   /* If 1, the -var-update always recomputes the value in the
95      current thread and frame.  Otherwise, variable object is
96      always updated in the specific scope/thread/frame.  */
97   int floating;
98
99   /* Flag that indicates validity: set to 0 when this varobj_root refers 
100      to symbols that do not exist anymore.  */
101   int is_valid;
102
103   /* Language-related operations for this variable and its
104      children.  */
105   const struct lang_varobj_ops *lang;
106
107   /* The varobj for this root node.  */
108   struct varobj *rootvar;
109
110   /* Next root variable */
111   struct varobj_root *next;
112 };
113
114 /* Dynamic part of varobj.  */
115
116 struct varobj_dynamic
117 {
118   /* Whether the children of this varobj were requested.  This field is
119      used to decide if dynamic varobj should recompute their children.
120      In the event that the frontend never asked for the children, we
121      can avoid that.  */
122   int children_requested;
123
124   /* The pretty-printer constructor.  If NULL, then the default
125      pretty-printer will be looked up.  If None, then no
126      pretty-printer will be installed.  */
127   PyObject *constructor;
128
129   /* The pretty-printer that has been constructed.  If NULL, then a
130      new printer object is needed, and one will be constructed.  */
131   PyObject *pretty_printer;
132
133   /* The iterator returned by the printer's 'children' method, or NULL
134      if not available.  */
135   PyObject *child_iter;
136
137   /* We request one extra item from the iterator, so that we can
138      report to the caller whether there are more items than we have
139      already reported.  However, we don't want to install this value
140      when we read it, because that will mess up future updates.  So,
141      we stash it here instead.  */
142   PyObject *saved_item;
143 };
144
145 struct cpstack
146 {
147   char *name;
148   struct cpstack *next;
149 };
150
151 /* A list of varobjs */
152
153 struct vlist
154 {
155   struct varobj *var;
156   struct vlist *next;
157 };
158
159 /* Private function prototypes */
160
161 /* Helper functions for the above subcommands.  */
162
163 static int delete_variable (struct cpstack **, struct varobj *, int);
164
165 static void delete_variable_1 (struct cpstack **, int *,
166                                struct varobj *, int, int);
167
168 static int install_variable (struct varobj *);
169
170 static void uninstall_variable (struct varobj *);
171
172 static struct varobj *create_child (struct varobj *, int, char *);
173
174 static struct varobj *
175 create_child_with_value (struct varobj *parent, int index, char *name,
176                          struct value *value);
177
178 /* Utility routines */
179
180 static struct varobj *new_variable (void);
181
182 static struct varobj *new_root_variable (void);
183
184 static void free_variable (struct varobj *var);
185
186 static struct cleanup *make_cleanup_free_variable (struct varobj *var);
187
188 static enum varobj_display_formats variable_default_display (struct varobj *);
189
190 static void cppush (struct cpstack **pstack, char *name);
191
192 static char *cppop (struct cpstack **pstack);
193
194 static int update_type_if_necessary (struct varobj *var,
195                                      struct value *new_value);
196
197 static int install_new_value (struct varobj *var, struct value *value, 
198                               int initial);
199
200 /* Language-specific routines.  */
201
202 static enum varobj_languages variable_language (struct varobj *var);
203
204 static int number_of_children (struct varobj *);
205
206 static char *name_of_variable (struct varobj *);
207
208 static char *name_of_child (struct varobj *, int);
209
210 static struct value *value_of_root (struct varobj **var_handle, int *);
211
212 static struct value *value_of_child (struct varobj *parent, int index);
213
214 static char *my_value_of_variable (struct varobj *var,
215                                    enum varobj_display_formats format);
216
217 static int is_root_p (struct varobj *var);
218
219 #if HAVE_PYTHON
220
221 static struct varobj *varobj_add_child (struct varobj *var,
222                                         char *name,
223                                         struct value *value);
224
225 #endif /* HAVE_PYTHON */
226
227 /* Array of known source language routines.  */
228 static const struct lang_varobj_ops *languages[vlang_end] = {
229   &c_varobj_ops,
230   &cplus_varobj_ops,
231   &java_varobj_ops,
232   &ada_varobj_ops,
233 };
234
235 /* Private data */
236
237 /* Mappings of varobj_display_formats enums to gdb's format codes.  */
238 static int format_code[] = { 0, 't', 'd', 'x', 'o' };
239
240 /* Header of the list of root variable objects.  */
241 static struct varobj_root *rootlist;
242
243 /* Prime number indicating the number of buckets in the hash table.  */
244 /* A prime large enough to avoid too many colisions.  */
245 #define VAROBJ_TABLE_SIZE 227
246
247 /* Pointer to the varobj hash table (built at run time).  */
248 static struct vlist **varobj_table;
249
250 \f
251
252 /* API Implementation */
253 static int
254 is_root_p (struct varobj *var)
255 {
256   return (var->root->rootvar == var);
257 }
258
259 #ifdef HAVE_PYTHON
260 /* Helper function to install a Python environment suitable for
261    use during operations on VAR.  */
262 static struct cleanup *
263 varobj_ensure_python_env (struct varobj *var)
264 {
265   return ensure_python_env (var->root->exp->gdbarch,
266                             var->root->exp->language_defn);
267 }
268 #endif
269
270 /* Creates a varobj (not its children).  */
271
272 /* Return the full FRAME which corresponds to the given CORE_ADDR
273    or NULL if no FRAME on the chain corresponds to CORE_ADDR.  */
274
275 static struct frame_info *
276 find_frame_addr_in_frame_chain (CORE_ADDR frame_addr)
277 {
278   struct frame_info *frame = NULL;
279
280   if (frame_addr == (CORE_ADDR) 0)
281     return NULL;
282
283   for (frame = get_current_frame ();
284        frame != NULL;
285        frame = get_prev_frame (frame))
286     {
287       /* The CORE_ADDR we get as argument was parsed from a string GDB
288          output as $fp.  This output got truncated to gdbarch_addr_bit.
289          Truncate the frame base address in the same manner before
290          comparing it against our argument.  */
291       CORE_ADDR frame_base = get_frame_base_address (frame);
292       int addr_bit = gdbarch_addr_bit (get_frame_arch (frame));
293
294       if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
295         frame_base &= ((CORE_ADDR) 1 << addr_bit) - 1;
296
297       if (frame_base == frame_addr)
298         return frame;
299     }
300
301   return NULL;
302 }
303
304 struct varobj *
305 varobj_create (char *objname,
306                char *expression, CORE_ADDR frame, enum varobj_type type)
307 {
308   struct varobj *var;
309   struct cleanup *old_chain;
310
311   /* Fill out a varobj structure for the (root) variable being constructed.  */
312   var = new_root_variable ();
313   old_chain = make_cleanup_free_variable (var);
314
315   if (expression != NULL)
316     {
317       struct frame_info *fi;
318       struct frame_id old_id = null_frame_id;
319       struct block *block;
320       const char *p;
321       enum varobj_languages lang;
322       struct value *value = NULL;
323       volatile struct gdb_exception except;
324       CORE_ADDR pc;
325
326       /* Parse and evaluate the expression, filling in as much of the
327          variable's data as possible.  */
328
329       if (has_stack_frames ())
330         {
331           /* Allow creator to specify context of variable.  */
332           if ((type == USE_CURRENT_FRAME) || (type == USE_SELECTED_FRAME))
333             fi = get_selected_frame (NULL);
334           else
335             /* FIXME: cagney/2002-11-23: This code should be doing a
336                lookup using the frame ID and not just the frame's
337                ``address''.  This, of course, means an interface
338                change.  However, with out that interface change ISAs,
339                such as the ia64 with its two stacks, won't work.
340                Similar goes for the case where there is a frameless
341                function.  */
342             fi = find_frame_addr_in_frame_chain (frame);
343         }
344       else
345         fi = NULL;
346
347       /* frame = -2 means always use selected frame.  */
348       if (type == USE_SELECTED_FRAME)
349         var->root->floating = 1;
350
351       pc = 0;
352       block = NULL;
353       if (fi != NULL)
354         {
355           block = get_frame_block (fi, 0);
356           pc = get_frame_pc (fi);
357         }
358
359       p = expression;
360       innermost_block = NULL;
361       /* Wrap the call to parse expression, so we can 
362          return a sensible error.  */
363       TRY_CATCH (except, RETURN_MASK_ERROR)
364         {
365           var->root->exp = parse_exp_1 (&p, pc, block, 0);
366         }
367
368       if (except.reason < 0)
369         {
370           do_cleanups (old_chain);
371           return NULL;
372         }
373
374       /* Don't allow variables to be created for types.  */
375       if (var->root->exp->elts[0].opcode == OP_TYPE
376           || var->root->exp->elts[0].opcode == OP_TYPEOF
377           || var->root->exp->elts[0].opcode == OP_DECLTYPE)
378         {
379           do_cleanups (old_chain);
380           fprintf_unfiltered (gdb_stderr, "Attempt to use a type name"
381                               " as an expression.\n");
382           return NULL;
383         }
384
385       var->format = variable_default_display (var);
386       var->root->valid_block = innermost_block;
387       var->name = xstrdup (expression);
388       /* For a root var, the name and the expr are the same.  */
389       var->path_expr = xstrdup (expression);
390
391       /* When the frame is different from the current frame, 
392          we must select the appropriate frame before parsing
393          the expression, otherwise the value will not be current.
394          Since select_frame is so benign, just call it for all cases.  */
395       if (innermost_block)
396         {
397           /* User could specify explicit FRAME-ADDR which was not found but
398              EXPRESSION is frame specific and we would not be able to evaluate
399              it correctly next time.  With VALID_BLOCK set we must also set
400              FRAME and THREAD_ID.  */
401           if (fi == NULL)
402             error (_("Failed to find the specified frame"));
403
404           var->root->frame = get_frame_id (fi);
405           var->root->thread_id = pid_to_thread_id (inferior_ptid);
406           old_id = get_frame_id (get_selected_frame (NULL));
407           select_frame (fi);     
408         }
409
410       /* We definitely need to catch errors here.
411          If evaluate_expression succeeds we got the value we wanted.
412          But if it fails, we still go on with a call to evaluate_type().  */
413       TRY_CATCH (except, RETURN_MASK_ERROR)
414         {
415           value = evaluate_expression (var->root->exp);
416         }
417
418       if (except.reason < 0)
419         {
420           /* Error getting the value.  Try to at least get the
421              right type.  */
422           struct value *type_only_value = evaluate_type (var->root->exp);
423
424           var->type = value_type (type_only_value);
425         }
426         else
427           {
428             int real_type_found = 0;
429
430             var->type = value_actual_type (value, 0, &real_type_found);
431             if (real_type_found)
432               value = value_cast (var->type, value);
433           }
434
435       /* Set language info */
436       lang = variable_language (var);
437       var->root->lang = languages[lang];
438
439       install_new_value (var, value, 1 /* Initial assignment */);
440
441       /* Set ourselves as our root.  */
442       var->root->rootvar = var;
443
444       /* Reset the selected frame.  */
445       if (frame_id_p (old_id))
446         select_frame (frame_find_by_id (old_id));
447     }
448
449   /* If the variable object name is null, that means this
450      is a temporary variable, so don't install it.  */
451
452   if ((var != NULL) && (objname != NULL))
453     {
454       var->obj_name = xstrdup (objname);
455
456       /* If a varobj name is duplicated, the install will fail so
457          we must cleanup.  */
458       if (!install_variable (var))
459         {
460           do_cleanups (old_chain);
461           return NULL;
462         }
463     }
464
465   discard_cleanups (old_chain);
466   return var;
467 }
468
469 /* Generates an unique name that can be used for a varobj.  */
470
471 char *
472 varobj_gen_name (void)
473 {
474   static int id = 0;
475   char *obj_name;
476
477   /* Generate a name for this object.  */
478   id++;
479   obj_name = xstrprintf ("var%d", id);
480
481   return obj_name;
482 }
483
484 /* Given an OBJNAME, returns the pointer to the corresponding varobj.  Call
485    error if OBJNAME cannot be found.  */
486
487 struct varobj *
488 varobj_get_handle (char *objname)
489 {
490   struct vlist *cv;
491   const char *chp;
492   unsigned int index = 0;
493   unsigned int i = 1;
494
495   for (chp = objname; *chp; chp++)
496     {
497       index = (index + (i++ * (unsigned int) *chp)) % VAROBJ_TABLE_SIZE;
498     }
499
500   cv = *(varobj_table + index);
501   while ((cv != NULL) && (strcmp (cv->var->obj_name, objname) != 0))
502     cv = cv->next;
503
504   if (cv == NULL)
505     error (_("Variable object not found"));
506
507   return cv->var;
508 }
509
510 /* Given the handle, return the name of the object.  */
511
512 char *
513 varobj_get_objname (struct varobj *var)
514 {
515   return var->obj_name;
516 }
517
518 /* Given the handle, return the expression represented by the object.  */
519
520 char *
521 varobj_get_expression (struct varobj *var)
522 {
523   return name_of_variable (var);
524 }
525
526 /* Deletes a varobj and all its children if only_children == 0,
527    otherwise deletes only the children; returns a malloc'ed list of
528    all the (malloc'ed) names of the variables that have been deleted
529    (NULL terminated).  */
530
531 int
532 varobj_delete (struct varobj *var, char ***dellist, int only_children)
533 {
534   int delcount;
535   int mycount;
536   struct cpstack *result = NULL;
537   char **cp;
538
539   /* Initialize a stack for temporary results.  */
540   cppush (&result, NULL);
541
542   if (only_children)
543     /* Delete only the variable children.  */
544     delcount = delete_variable (&result, var, 1 /* only the children */ );
545   else
546     /* Delete the variable and all its children.  */
547     delcount = delete_variable (&result, var, 0 /* parent+children */ );
548
549   /* We may have been asked to return a list of what has been deleted.  */
550   if (dellist != NULL)
551     {
552       *dellist = xmalloc ((delcount + 1) * sizeof (char *));
553
554       cp = *dellist;
555       mycount = delcount;
556       *cp = cppop (&result);
557       while ((*cp != NULL) && (mycount > 0))
558         {
559           mycount--;
560           cp++;
561           *cp = cppop (&result);
562         }
563
564       if (mycount || (*cp != NULL))
565         warning (_("varobj_delete: assertion failed - mycount(=%d) <> 0"),
566                  mycount);
567     }
568
569   return delcount;
570 }
571
572 #if HAVE_PYTHON
573
574 /* Convenience function for varobj_set_visualizer.  Instantiate a
575    pretty-printer for a given value.  */
576 static PyObject *
577 instantiate_pretty_printer (PyObject *constructor, struct value *value)
578 {
579   PyObject *val_obj = NULL; 
580   PyObject *printer;
581
582   val_obj = value_to_value_object (value);
583   if (! val_obj)
584     return NULL;
585
586   printer = PyObject_CallFunctionObjArgs (constructor, val_obj, NULL);
587   Py_DECREF (val_obj);
588   return printer;
589 }
590
591 #endif
592
593 /* Set/Get variable object display format.  */
594
595 enum varobj_display_formats
596 varobj_set_display_format (struct varobj *var,
597                            enum varobj_display_formats format)
598 {
599   switch (format)
600     {
601     case FORMAT_NATURAL:
602     case FORMAT_BINARY:
603     case FORMAT_DECIMAL:
604     case FORMAT_HEXADECIMAL:
605     case FORMAT_OCTAL:
606       var->format = format;
607       break;
608
609     default:
610       var->format = variable_default_display (var);
611     }
612
613   if (varobj_value_is_changeable_p (var) 
614       && var->value && !value_lazy (var->value))
615     {
616       xfree (var->print_value);
617       var->print_value = varobj_value_get_print_value (var->value,
618                                                        var->format, var);
619     }
620
621   return var->format;
622 }
623
624 enum varobj_display_formats
625 varobj_get_display_format (struct varobj *var)
626 {
627   return var->format;
628 }
629
630 char *
631 varobj_get_display_hint (struct varobj *var)
632 {
633   char *result = NULL;
634
635 #if HAVE_PYTHON
636   struct cleanup *back_to;
637
638   if (!gdb_python_initialized)
639     return NULL;
640
641   back_to = varobj_ensure_python_env (var);
642
643   if (var->dynamic->pretty_printer != NULL)
644     result = gdbpy_get_display_hint (var->dynamic->pretty_printer);
645
646   do_cleanups (back_to);
647 #endif
648
649   return result;
650 }
651
652 /* Return true if the varobj has items after TO, false otherwise.  */
653
654 int
655 varobj_has_more (struct varobj *var, int to)
656 {
657   if (VEC_length (varobj_p, var->children) > to)
658     return 1;
659   return ((to == -1 || VEC_length (varobj_p, var->children) == to)
660           && (var->dynamic->saved_item != NULL));
661 }
662
663 /* If the variable object is bound to a specific thread, that
664    is its evaluation can always be done in context of a frame
665    inside that thread, returns GDB id of the thread -- which
666    is always positive.  Otherwise, returns -1.  */
667 int
668 varobj_get_thread_id (struct varobj *var)
669 {
670   if (var->root->valid_block && var->root->thread_id > 0)
671     return var->root->thread_id;
672   else
673     return -1;
674 }
675
676 void
677 varobj_set_frozen (struct varobj *var, int frozen)
678 {
679   /* When a variable is unfrozen, we don't fetch its value.
680      The 'not_fetched' flag remains set, so next -var-update
681      won't complain.
682
683      We don't fetch the value, because for structures the client
684      should do -var-update anyway.  It would be bad to have different
685      client-size logic for structure and other types.  */
686   var->frozen = frozen;
687 }
688
689 int
690 varobj_get_frozen (struct varobj *var)
691 {
692   return var->frozen;
693 }
694
695 /* A helper function that restricts a range to what is actually
696    available in a VEC.  This follows the usual rules for the meaning
697    of FROM and TO -- if either is negative, the entire range is
698    used.  */
699
700 void
701 varobj_restrict_range (VEC (varobj_p) *children, int *from, int *to)
702 {
703   if (*from < 0 || *to < 0)
704     {
705       *from = 0;
706       *to = VEC_length (varobj_p, children);
707     }
708   else
709     {
710       if (*from > VEC_length (varobj_p, children))
711         *from = VEC_length (varobj_p, children);
712       if (*to > VEC_length (varobj_p, children))
713         *to = VEC_length (varobj_p, children);
714       if (*from > *to)
715         *from = *to;
716     }
717 }
718
719 #if HAVE_PYTHON
720
721 /* A helper for update_dynamic_varobj_children that installs a new
722    child when needed.  */
723
724 static void
725 install_dynamic_child (struct varobj *var,
726                        VEC (varobj_p) **changed,
727                        VEC (varobj_p) **type_changed,
728                        VEC (varobj_p) **new,
729                        VEC (varobj_p) **unchanged,
730                        int *cchanged,
731                        int index,
732                        char *name,
733                        struct value *value)
734 {
735   if (VEC_length (varobj_p, var->children) < index + 1)
736     {
737       /* There's no child yet.  */
738       struct varobj *child = varobj_add_child (var, name, value);
739
740       if (new)
741         {
742           VEC_safe_push (varobj_p, *new, child);
743           *cchanged = 1;
744         }
745     }
746   else
747     {
748       varobj_p existing = VEC_index (varobj_p, var->children, index);
749       int type_updated = update_type_if_necessary (existing, value);
750
751       if (type_updated)
752         {
753           if (type_changed)
754             VEC_safe_push (varobj_p, *type_changed, existing);
755         }
756       if (install_new_value (existing, value, 0))
757         {
758           if (!type_updated && changed)
759             VEC_safe_push (varobj_p, *changed, existing);
760         }
761       else if (!type_updated && unchanged)
762         VEC_safe_push (varobj_p, *unchanged, existing);
763     }
764 }
765
766 static int
767 dynamic_varobj_has_child_method (struct varobj *var)
768 {
769   struct cleanup *back_to;
770   PyObject *printer = var->dynamic->pretty_printer;
771   int result;
772
773   if (!gdb_python_initialized)
774     return 0;
775
776   back_to = varobj_ensure_python_env (var);
777   result = PyObject_HasAttr (printer, gdbpy_children_cst);
778   do_cleanups (back_to);
779   return result;
780 }
781
782 #endif
783
784 static int
785 update_dynamic_varobj_children (struct varobj *var,
786                                 VEC (varobj_p) **changed,
787                                 VEC (varobj_p) **type_changed,
788                                 VEC (varobj_p) **new,
789                                 VEC (varobj_p) **unchanged,
790                                 int *cchanged,
791                                 int update_children,
792                                 int from,
793                                 int to)
794 {
795 #if HAVE_PYTHON
796   struct cleanup *back_to;
797   PyObject *children;
798   int i;
799   PyObject *printer = var->dynamic->pretty_printer;
800
801   if (!gdb_python_initialized)
802     return 0;
803
804   back_to = varobj_ensure_python_env (var);
805
806   *cchanged = 0;
807   if (!PyObject_HasAttr (printer, gdbpy_children_cst))
808     {
809       do_cleanups (back_to);
810       return 0;
811     }
812
813   if (update_children || var->dynamic->child_iter == NULL)
814     {
815       children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
816                                              NULL);
817
818       if (!children)
819         {
820           gdbpy_print_stack ();
821           error (_("Null value returned for children"));
822         }
823
824       make_cleanup_py_decref (children);
825
826       Py_XDECREF (var->dynamic->child_iter);
827       var->dynamic->child_iter = PyObject_GetIter (children);
828       if (var->dynamic->child_iter == NULL)
829         {
830           gdbpy_print_stack ();
831           error (_("Could not get children iterator"));
832         }
833
834       Py_XDECREF (var->dynamic->saved_item);
835       var->dynamic->saved_item = NULL;
836
837       i = 0;
838     }
839   else
840     i = VEC_length (varobj_p, var->children);
841
842   /* We ask for one extra child, so that MI can report whether there
843      are more children.  */
844   for (; to < 0 || i < to + 1; ++i)
845     {
846       PyObject *item;
847       int force_done = 0;
848
849       /* See if there was a leftover from last time.  */
850       if (var->dynamic->saved_item)
851         {
852           item = var->dynamic->saved_item;
853           var->dynamic->saved_item = NULL;
854         }
855       else
856         item = PyIter_Next (var->dynamic->child_iter);
857
858       if (!item)
859         {
860           /* Normal end of iteration.  */
861           if (!PyErr_Occurred ())
862             break;
863
864           /* If we got a memory error, just use the text as the
865              item.  */
866           if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
867             {
868               PyObject *type, *value, *trace;
869               char *name_str, *value_str;
870
871               PyErr_Fetch (&type, &value, &trace);
872               value_str = gdbpy_exception_to_string (type, value);
873               Py_XDECREF (type);
874               Py_XDECREF (value);
875               Py_XDECREF (trace);
876               if (!value_str)
877                 {
878                   gdbpy_print_stack ();
879                   break;
880                 }
881
882               name_str = xstrprintf ("<error at %d>", i);
883               item = Py_BuildValue ("(ss)", name_str, value_str);
884               xfree (name_str);
885               xfree (value_str);
886               if (!item)
887                 {
888                   gdbpy_print_stack ();
889                   break;
890                 }
891
892               force_done = 1;
893             }
894           else
895             {
896               /* Any other kind of error.  */
897               gdbpy_print_stack ();
898               break;
899             }
900         }
901
902       /* We don't want to push the extra child on any report list.  */
903       if (to < 0 || i < to)
904         {
905           PyObject *py_v;
906           const char *name;
907           struct value *v;
908           struct cleanup *inner;
909           int can_mention = from < 0 || i >= from;
910
911           inner = make_cleanup_py_decref (item);
912
913           if (!PyArg_ParseTuple (item, "sO", &name, &py_v))
914             {
915               gdbpy_print_stack ();
916               error (_("Invalid item from the child list"));
917             }
918
919           v = convert_value_from_python (py_v);
920           if (v == NULL)
921             gdbpy_print_stack ();
922           install_dynamic_child (var, can_mention ? changed : NULL,
923                                  can_mention ? type_changed : NULL,
924                                  can_mention ? new : NULL,
925                                  can_mention ? unchanged : NULL,
926                                  can_mention ? cchanged : NULL, i,
927                                  xstrdup (name), v);
928           do_cleanups (inner);
929         }
930       else
931         {
932           Py_XDECREF (var->dynamic->saved_item);
933           var->dynamic->saved_item = item;
934
935           /* We want to truncate the child list just before this
936              element.  */
937           break;
938         }
939
940       if (force_done)
941         break;
942     }
943
944   if (i < VEC_length (varobj_p, var->children))
945     {
946       int j;
947
948       *cchanged = 1;
949       for (j = i; j < VEC_length (varobj_p, var->children); ++j)
950         varobj_delete (VEC_index (varobj_p, var->children, j), NULL, 0);
951       VEC_truncate (varobj_p, var->children, i);
952     }
953
954   /* If there are fewer children than requested, note that the list of
955      children changed.  */
956   if (to >= 0 && VEC_length (varobj_p, var->children) < to)
957     *cchanged = 1;
958
959   var->num_children = VEC_length (varobj_p, var->children);
960  
961   do_cleanups (back_to);
962
963   return 1;
964 #else
965   gdb_assert_not_reached ("should never be called if Python is not enabled");
966 #endif
967 }
968
969 int
970 varobj_get_num_children (struct varobj *var)
971 {
972   if (var->num_children == -1)
973     {
974       if (var->dynamic->pretty_printer != NULL)
975         {
976           int dummy;
977
978           /* If we have a dynamic varobj, don't report -1 children.
979              So, try to fetch some children first.  */
980           update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL, &dummy,
981                                           0, 0, 0);
982         }
983       else
984         var->num_children = number_of_children (var);
985     }
986
987   return var->num_children >= 0 ? var->num_children : 0;
988 }
989
990 /* Creates a list of the immediate children of a variable object;
991    the return code is the number of such children or -1 on error.  */
992
993 VEC (varobj_p)*
994 varobj_list_children (struct varobj *var, int *from, int *to)
995 {
996   char *name;
997   int i, children_changed;
998
999   var->dynamic->children_requested = 1;
1000
1001   if (var->dynamic->pretty_printer != NULL)
1002     {
1003       /* This, in theory, can result in the number of children changing without
1004          frontend noticing.  But well, calling -var-list-children on the same
1005          varobj twice is not something a sane frontend would do.  */
1006       update_dynamic_varobj_children (var, NULL, NULL, NULL, NULL,
1007                                       &children_changed, 0, 0, *to);
1008       varobj_restrict_range (var->children, from, to);
1009       return var->children;
1010     }
1011
1012   if (var->num_children == -1)
1013     var->num_children = number_of_children (var);
1014
1015   /* If that failed, give up.  */
1016   if (var->num_children == -1)
1017     return var->children;
1018
1019   /* If we're called when the list of children is not yet initialized,
1020      allocate enough elements in it.  */
1021   while (VEC_length (varobj_p, var->children) < var->num_children)
1022     VEC_safe_push (varobj_p, var->children, NULL);
1023
1024   for (i = 0; i < var->num_children; i++)
1025     {
1026       varobj_p existing = VEC_index (varobj_p, var->children, i);
1027
1028       if (existing == NULL)
1029         {
1030           /* Either it's the first call to varobj_list_children for
1031              this variable object, and the child was never created,
1032              or it was explicitly deleted by the client.  */
1033           name = name_of_child (var, i);
1034           existing = create_child (var, i, name);
1035           VEC_replace (varobj_p, var->children, i, existing);
1036         }
1037     }
1038
1039   varobj_restrict_range (var->children, from, to);
1040   return var->children;
1041 }
1042
1043 #if HAVE_PYTHON
1044
1045 static struct varobj *
1046 varobj_add_child (struct varobj *var, char *name, struct value *value)
1047 {
1048   varobj_p v = create_child_with_value (var, 
1049                                         VEC_length (varobj_p, var->children), 
1050                                         name, value);
1051
1052   VEC_safe_push (varobj_p, var->children, v);
1053   return v;
1054 }
1055
1056 #endif /* HAVE_PYTHON */
1057
1058 /* Obtain the type of an object Variable as a string similar to the one gdb
1059    prints on the console.  */
1060
1061 char *
1062 varobj_get_type (struct varobj *var)
1063 {
1064   /* For the "fake" variables, do not return a type.  (It's type is
1065      NULL, too.)
1066      Do not return a type for invalid variables as well.  */
1067   if (CPLUS_FAKE_CHILD (var) || !var->root->is_valid)
1068     return NULL;
1069
1070   return type_to_string (var->type);
1071 }
1072
1073 /* Obtain the type of an object variable.  */
1074
1075 struct type *
1076 varobj_get_gdb_type (struct varobj *var)
1077 {
1078   return var->type;
1079 }
1080
1081 /* Is VAR a path expression parent, i.e., can it be used to construct
1082    a valid path expression?  */
1083
1084 static int
1085 is_path_expr_parent (struct varobj *var)
1086 {
1087   struct type *type;
1088
1089   /* "Fake" children are not path_expr parents.  */
1090   if (CPLUS_FAKE_CHILD (var))
1091     return 0;
1092
1093   type = varobj_get_value_type (var);
1094
1095   /* Anonymous unions and structs are also not path_expr parents.  */
1096   return !((TYPE_CODE (type) == TYPE_CODE_STRUCT
1097             || TYPE_CODE (type) == TYPE_CODE_UNION)
1098            && TYPE_NAME (type) == NULL);
1099 }
1100
1101 /* Return the path expression parent for VAR.  */
1102
1103 struct varobj *
1104 varobj_get_path_expr_parent (struct varobj *var)
1105 {
1106   struct varobj *parent = var;
1107
1108   while (!is_root_p (parent) && !is_path_expr_parent (parent))
1109     parent = parent->parent;
1110
1111   return parent;
1112 }
1113
1114 /* Return a pointer to the full rooted expression of varobj VAR.
1115    If it has not been computed yet, compute it.  */
1116 char *
1117 varobj_get_path_expr (struct varobj *var)
1118 {
1119   if (var->path_expr != NULL)
1120     return var->path_expr;
1121   else 
1122     {
1123       /* For root varobjs, we initialize path_expr
1124          when creating varobj, so here it should be
1125          child varobj.  */
1126       gdb_assert (!is_root_p (var));
1127       return (*var->root->lang->path_expr_of_child) (var);
1128     }
1129 }
1130
1131 enum varobj_languages
1132 varobj_get_language (struct varobj *var)
1133 {
1134   return variable_language (var);
1135 }
1136
1137 int
1138 varobj_get_attributes (struct varobj *var)
1139 {
1140   int attributes = 0;
1141
1142   if (varobj_editable_p (var))
1143     /* FIXME: define masks for attributes.  */
1144     attributes |= 0x00000001;   /* Editable */
1145
1146   return attributes;
1147 }
1148
1149 int
1150 varobj_pretty_printed_p (struct varobj *var)
1151 {
1152   return var->dynamic->pretty_printer != NULL;
1153 }
1154
1155 char *
1156 varobj_get_formatted_value (struct varobj *var,
1157                             enum varobj_display_formats format)
1158 {
1159   return my_value_of_variable (var, format);
1160 }
1161
1162 char *
1163 varobj_get_value (struct varobj *var)
1164 {
1165   return my_value_of_variable (var, var->format);
1166 }
1167
1168 /* Set the value of an object variable (if it is editable) to the
1169    value of the given expression.  */
1170 /* Note: Invokes functions that can call error().  */
1171
1172 int
1173 varobj_set_value (struct varobj *var, char *expression)
1174 {
1175   struct value *val = NULL; /* Initialize to keep gcc happy.  */
1176   /* The argument "expression" contains the variable's new value.
1177      We need to first construct a legal expression for this -- ugh!  */
1178   /* Does this cover all the bases?  */
1179   struct expression *exp;
1180   struct value *value = NULL; /* Initialize to keep gcc happy.  */
1181   int saved_input_radix = input_radix;
1182   const char *s = expression;
1183   volatile struct gdb_exception except;
1184
1185   gdb_assert (varobj_editable_p (var));
1186
1187   input_radix = 10;             /* ALWAYS reset to decimal temporarily.  */
1188   exp = parse_exp_1 (&s, 0, 0, 0);
1189   TRY_CATCH (except, RETURN_MASK_ERROR)
1190     {
1191       value = evaluate_expression (exp);
1192     }
1193
1194   if (except.reason < 0)
1195     {
1196       /* We cannot proceed without a valid expression.  */
1197       xfree (exp);
1198       return 0;
1199     }
1200
1201   /* All types that are editable must also be changeable.  */
1202   gdb_assert (varobj_value_is_changeable_p (var));
1203
1204   /* The value of a changeable variable object must not be lazy.  */
1205   gdb_assert (!value_lazy (var->value));
1206
1207   /* Need to coerce the input.  We want to check if the
1208      value of the variable object will be different
1209      after assignment, and the first thing value_assign
1210      does is coerce the input.
1211      For example, if we are assigning an array to a pointer variable we
1212      should compare the pointer with the array's address, not with the
1213      array's content.  */
1214   value = coerce_array (value);
1215
1216   /* The new value may be lazy.  value_assign, or
1217      rather value_contents, will take care of this.  */
1218   TRY_CATCH (except, RETURN_MASK_ERROR)
1219     {
1220       val = value_assign (var->value, value);
1221     }
1222
1223   if (except.reason < 0)
1224     return 0;
1225
1226   /* If the value has changed, record it, so that next -var-update can
1227      report this change.  If a variable had a value of '1', we've set it
1228      to '333' and then set again to '1', when -var-update will report this
1229      variable as changed -- because the first assignment has set the
1230      'updated' flag.  There's no need to optimize that, because return value
1231      of -var-update should be considered an approximation.  */
1232   var->updated = install_new_value (var, val, 0 /* Compare values.  */);
1233   input_radix = saved_input_radix;
1234   return 1;
1235 }
1236
1237 #if HAVE_PYTHON
1238
1239 /* A helper function to install a constructor function and visualizer
1240    in a varobj_dynamic.  */
1241
1242 static void
1243 install_visualizer (struct varobj_dynamic *var, PyObject *constructor,
1244                     PyObject *visualizer)
1245 {
1246   Py_XDECREF (var->constructor);
1247   var->constructor = constructor;
1248
1249   Py_XDECREF (var->pretty_printer);
1250   var->pretty_printer = visualizer;
1251
1252   Py_XDECREF (var->child_iter);
1253   var->child_iter = NULL;
1254 }
1255
1256 /* Install the default visualizer for VAR.  */
1257
1258 static void
1259 install_default_visualizer (struct varobj *var)
1260 {
1261   /* Do not install a visualizer on a CPLUS_FAKE_CHILD.  */
1262   if (CPLUS_FAKE_CHILD (var))
1263     return;
1264
1265   if (pretty_printing)
1266     {
1267       PyObject *pretty_printer = NULL;
1268
1269       if (var->value)
1270         {
1271           pretty_printer = gdbpy_get_varobj_pretty_printer (var->value);
1272           if (! pretty_printer)
1273             {
1274               gdbpy_print_stack ();
1275               error (_("Cannot instantiate printer for default visualizer"));
1276             }
1277         }
1278       
1279       if (pretty_printer == Py_None)
1280         {
1281           Py_DECREF (pretty_printer);
1282           pretty_printer = NULL;
1283         }
1284   
1285       install_visualizer (var->dynamic, NULL, pretty_printer);
1286     }
1287 }
1288
1289 /* Instantiate and install a visualizer for VAR using CONSTRUCTOR to
1290    make a new object.  */
1291
1292 static void
1293 construct_visualizer (struct varobj *var, PyObject *constructor)
1294 {
1295   PyObject *pretty_printer;
1296
1297   /* Do not install a visualizer on a CPLUS_FAKE_CHILD.  */
1298   if (CPLUS_FAKE_CHILD (var))
1299     return;
1300
1301   Py_INCREF (constructor);
1302   if (constructor == Py_None)
1303     pretty_printer = NULL;
1304   else
1305     {
1306       pretty_printer = instantiate_pretty_printer (constructor, var->value);
1307       if (! pretty_printer)
1308         {
1309           gdbpy_print_stack ();
1310           Py_DECREF (constructor);
1311           constructor = Py_None;
1312           Py_INCREF (constructor);
1313         }
1314
1315       if (pretty_printer == Py_None)
1316         {
1317           Py_DECREF (pretty_printer);
1318           pretty_printer = NULL;
1319         }
1320     }
1321
1322   install_visualizer (var->dynamic, constructor, pretty_printer);
1323 }
1324
1325 #endif /* HAVE_PYTHON */
1326
1327 /* A helper function for install_new_value.  This creates and installs
1328    a visualizer for VAR, if appropriate.  */
1329
1330 static void
1331 install_new_value_visualizer (struct varobj *var)
1332 {
1333 #if HAVE_PYTHON
1334   /* If the constructor is None, then we want the raw value.  If VAR
1335      does not have a value, just skip this.  */
1336   if (!gdb_python_initialized)
1337     return;
1338
1339   if (var->dynamic->constructor != Py_None && var->value != NULL)
1340     {
1341       struct cleanup *cleanup;
1342
1343       cleanup = varobj_ensure_python_env (var);
1344
1345       if (var->dynamic->constructor == NULL)
1346         install_default_visualizer (var);
1347       else
1348         construct_visualizer (var, var->dynamic->constructor);
1349
1350       do_cleanups (cleanup);
1351     }
1352 #else
1353   /* Do nothing.  */
1354 #endif
1355 }
1356
1357 /* When using RTTI to determine variable type it may be changed in runtime when
1358    the variable value is changed.  This function checks whether type of varobj
1359    VAR will change when a new value NEW_VALUE is assigned and if it is so
1360    updates the type of VAR.  */
1361
1362 static int
1363 update_type_if_necessary (struct varobj *var, struct value *new_value)
1364 {
1365   if (new_value)
1366     {
1367       struct value_print_options opts;
1368
1369       get_user_print_options (&opts);
1370       if (opts.objectprint)
1371         {
1372           struct type *new_type;
1373           char *curr_type_str, *new_type_str;
1374
1375           new_type = value_actual_type (new_value, 0, 0);
1376           new_type_str = type_to_string (new_type);
1377           curr_type_str = varobj_get_type (var);
1378           if (strcmp (curr_type_str, new_type_str) != 0)
1379             {
1380               var->type = new_type;
1381
1382               /* This information may be not valid for a new type.  */
1383               varobj_delete (var, NULL, 1);
1384               VEC_free (varobj_p, var->children);
1385               var->num_children = -1;
1386               return 1;
1387             }
1388         }
1389     }
1390
1391   return 0;
1392 }
1393
1394 /* Assign a new value to a variable object.  If INITIAL is non-zero,
1395    this is the first assignement after the variable object was just
1396    created, or changed type.  In that case, just assign the value 
1397    and return 0.
1398    Otherwise, assign the new value, and return 1 if the value is
1399    different from the current one, 0 otherwise.  The comparison is
1400    done on textual representation of value.  Therefore, some types
1401    need not be compared.  E.g.  for structures the reported value is
1402    always "{...}", so no comparison is necessary here.  If the old
1403    value was NULL and new one is not, or vice versa, we always return 1.
1404
1405    The VALUE parameter should not be released -- the function will
1406    take care of releasing it when needed.  */
1407 static int
1408 install_new_value (struct varobj *var, struct value *value, int initial)
1409
1410   int changeable;
1411   int need_to_fetch;
1412   int changed = 0;
1413   int intentionally_not_fetched = 0;
1414   char *print_value = NULL;
1415
1416   /* We need to know the varobj's type to decide if the value should
1417      be fetched or not.  C++ fake children (public/protected/private)
1418      don't have a type.  */
1419   gdb_assert (var->type || CPLUS_FAKE_CHILD (var));
1420   changeable = varobj_value_is_changeable_p (var);
1421
1422   /* If the type has custom visualizer, we consider it to be always
1423      changeable.  FIXME: need to make sure this behaviour will not
1424      mess up read-sensitive values.  */
1425   if (var->dynamic->pretty_printer != NULL)
1426     changeable = 1;
1427
1428   need_to_fetch = changeable;
1429
1430   /* We are not interested in the address of references, and given
1431      that in C++ a reference is not rebindable, it cannot
1432      meaningfully change.  So, get hold of the real value.  */
1433   if (value)
1434     value = coerce_ref (value);
1435
1436   if (var->type && TYPE_CODE (var->type) == TYPE_CODE_UNION)
1437     /* For unions, we need to fetch the value implicitly because
1438        of implementation of union member fetch.  When gdb
1439        creates a value for a field and the value of the enclosing
1440        structure is not lazy,  it immediately copies the necessary
1441        bytes from the enclosing values.  If the enclosing value is
1442        lazy, the call to value_fetch_lazy on the field will read
1443        the data from memory.  For unions, that means we'll read the
1444        same memory more than once, which is not desirable.  So
1445        fetch now.  */
1446     need_to_fetch = 1;
1447
1448   /* The new value might be lazy.  If the type is changeable,
1449      that is we'll be comparing values of this type, fetch the
1450      value now.  Otherwise, on the next update the old value
1451      will be lazy, which means we've lost that old value.  */
1452   if (need_to_fetch && value && value_lazy (value))
1453     {
1454       struct varobj *parent = var->parent;
1455       int frozen = var->frozen;
1456
1457       for (; !frozen && parent; parent = parent->parent)
1458         frozen |= parent->frozen;
1459
1460       if (frozen && initial)
1461         {
1462           /* For variables that are frozen, or are children of frozen
1463              variables, we don't do fetch on initial assignment.
1464              For non-initial assignemnt we do the fetch, since it means we're
1465              explicitly asked to compare the new value with the old one.  */
1466           intentionally_not_fetched = 1;
1467         }
1468       else
1469         {
1470           volatile struct gdb_exception except;
1471
1472           TRY_CATCH (except, RETURN_MASK_ERROR)
1473             {
1474               value_fetch_lazy (value);
1475             }
1476
1477           if (except.reason < 0)
1478             {
1479               /* Set the value to NULL, so that for the next -var-update,
1480                  we don't try to compare the new value with this value,
1481                  that we couldn't even read.  */
1482               value = NULL;
1483             }
1484         }
1485     }
1486
1487   /* Get a reference now, before possibly passing it to any Python
1488      code that might release it.  */
1489   if (value != NULL)
1490     value_incref (value);
1491
1492   /* Below, we'll be comparing string rendering of old and new
1493      values.  Don't get string rendering if the value is
1494      lazy -- if it is, the code above has decided that the value
1495      should not be fetched.  */
1496   if (value != NULL && !value_lazy (value)
1497       && var->dynamic->pretty_printer == NULL)
1498     print_value = varobj_value_get_print_value (value, var->format, var);
1499
1500   /* If the type is changeable, compare the old and the new values.
1501      If this is the initial assignment, we don't have any old value
1502      to compare with.  */
1503   if (!initial && changeable)
1504     {
1505       /* If the value of the varobj was changed by -var-set-value,
1506          then the value in the varobj and in the target is the same.
1507          However, that value is different from the value that the
1508          varobj had after the previous -var-update.  So need to the
1509          varobj as changed.  */
1510       if (var->updated)
1511         {
1512           changed = 1;
1513         }
1514       else if (var->dynamic->pretty_printer == NULL)
1515         {
1516           /* Try to compare the values.  That requires that both
1517              values are non-lazy.  */
1518           if (var->not_fetched && value_lazy (var->value))
1519             {
1520               /* This is a frozen varobj and the value was never read.
1521                  Presumably, UI shows some "never read" indicator.
1522                  Now that we've fetched the real value, we need to report
1523                  this varobj as changed so that UI can show the real
1524                  value.  */
1525               changed = 1;
1526             }
1527           else  if (var->value == NULL && value == NULL)
1528             /* Equal.  */
1529             ;
1530           else if (var->value == NULL || value == NULL)
1531             {
1532               changed = 1;
1533             }
1534           else
1535             {
1536               gdb_assert (!value_lazy (var->value));
1537               gdb_assert (!value_lazy (value));
1538
1539               gdb_assert (var->print_value != NULL && print_value != NULL);
1540               if (strcmp (var->print_value, print_value) != 0)
1541                 changed = 1;
1542             }
1543         }
1544     }
1545
1546   if (!initial && !changeable)
1547     {
1548       /* For values that are not changeable, we don't compare the values.
1549          However, we want to notice if a value was not NULL and now is NULL,
1550          or vise versa, so that we report when top-level varobjs come in scope
1551          and leave the scope.  */
1552       changed = (var->value != NULL) != (value != NULL);
1553     }
1554
1555   /* We must always keep the new value, since children depend on it.  */
1556   if (var->value != NULL && var->value != value)
1557     value_free (var->value);
1558   var->value = value;
1559   if (value && value_lazy (value) && intentionally_not_fetched)
1560     var->not_fetched = 1;
1561   else
1562     var->not_fetched = 0;
1563   var->updated = 0;
1564
1565   install_new_value_visualizer (var);
1566
1567   /* If we installed a pretty-printer, re-compare the printed version
1568      to see if the variable changed.  */
1569   if (var->dynamic->pretty_printer != NULL)
1570     {
1571       xfree (print_value);
1572       print_value = varobj_value_get_print_value (var->value, var->format,
1573                                                   var);
1574       if ((var->print_value == NULL && print_value != NULL)
1575           || (var->print_value != NULL && print_value == NULL)
1576           || (var->print_value != NULL && print_value != NULL
1577               && strcmp (var->print_value, print_value) != 0))
1578         changed = 1;
1579     }
1580   if (var->print_value)
1581     xfree (var->print_value);
1582   var->print_value = print_value;
1583
1584   gdb_assert (!var->value || value_type (var->value));
1585
1586   return changed;
1587 }
1588
1589 /* Return the requested range for a varobj.  VAR is the varobj.  FROM
1590    and TO are out parameters; *FROM and *TO will be set to the
1591    selected sub-range of VAR.  If no range was selected using
1592    -var-set-update-range, then both will be -1.  */
1593 void
1594 varobj_get_child_range (struct varobj *var, int *from, int *to)
1595 {
1596   *from = var->from;
1597   *to = var->to;
1598 }
1599
1600 /* Set the selected sub-range of children of VAR to start at index
1601    FROM and end at index TO.  If either FROM or TO is less than zero,
1602    this is interpreted as a request for all children.  */
1603 void
1604 varobj_set_child_range (struct varobj *var, int from, int to)
1605 {
1606   var->from = from;
1607   var->to = to;
1608 }
1609
1610 void 
1611 varobj_set_visualizer (struct varobj *var, const char *visualizer)
1612 {
1613 #if HAVE_PYTHON
1614   PyObject *mainmod, *globals, *constructor;
1615   struct cleanup *back_to;
1616
1617   if (!gdb_python_initialized)
1618     return;
1619
1620   back_to = varobj_ensure_python_env (var);
1621
1622   mainmod = PyImport_AddModule ("__main__");
1623   globals = PyModule_GetDict (mainmod);
1624   Py_INCREF (globals);
1625   make_cleanup_py_decref (globals);
1626
1627   constructor = PyRun_String (visualizer, Py_eval_input, globals, globals);
1628
1629   if (! constructor)
1630     {
1631       gdbpy_print_stack ();
1632       error (_("Could not evaluate visualizer expression: %s"), visualizer);
1633     }
1634
1635   construct_visualizer (var, constructor);
1636   Py_XDECREF (constructor);
1637
1638   /* If there are any children now, wipe them.  */
1639   varobj_delete (var, NULL, 1 /* children only */);
1640   var->num_children = -1;
1641
1642   do_cleanups (back_to);
1643 #else
1644   error (_("Python support required"));
1645 #endif
1646 }
1647
1648 /* If NEW_VALUE is the new value of the given varobj (var), return
1649    non-zero if var has mutated.  In other words, if the type of
1650    the new value is different from the type of the varobj's old
1651    value.
1652
1653    NEW_VALUE may be NULL, if the varobj is now out of scope.  */
1654
1655 static int
1656 varobj_value_has_mutated (struct varobj *var, struct value *new_value,
1657                           struct type *new_type)
1658 {
1659   /* If we haven't previously computed the number of children in var,
1660      it does not matter from the front-end's perspective whether
1661      the type has mutated or not.  For all intents and purposes,
1662      it has not mutated.  */
1663   if (var->num_children < 0)
1664     return 0;
1665
1666   if (var->root->lang->value_has_mutated)
1667     return var->root->lang->value_has_mutated (var, new_value, new_type);
1668   else
1669     return 0;
1670 }
1671
1672 /* Update the values for a variable and its children.  This is a
1673    two-pronged attack.  First, re-parse the value for the root's
1674    expression to see if it's changed.  Then go all the way
1675    through its children, reconstructing them and noting if they've
1676    changed.
1677
1678    The EXPLICIT parameter specifies if this call is result
1679    of MI request to update this specific variable, or 
1680    result of implicit -var-update *.  For implicit request, we don't
1681    update frozen variables.
1682
1683    NOTE: This function may delete the caller's varobj.  If it
1684    returns TYPE_CHANGED, then it has done this and VARP will be modified
1685    to point to the new varobj.  */
1686
1687 VEC(varobj_update_result) *
1688 varobj_update (struct varobj **varp, int explicit)
1689 {
1690   int type_changed = 0;
1691   int i;
1692   struct value *new;
1693   VEC (varobj_update_result) *stack = NULL;
1694   VEC (varobj_update_result) *result = NULL;
1695
1696   /* Frozen means frozen -- we don't check for any change in
1697      this varobj, including its going out of scope, or
1698      changing type.  One use case for frozen varobjs is
1699      retaining previously evaluated expressions, and we don't
1700      want them to be reevaluated at all.  */
1701   if (!explicit && (*varp)->frozen)
1702     return result;
1703
1704   if (!(*varp)->root->is_valid)
1705     {
1706       varobj_update_result r = {0};
1707
1708       r.varobj = *varp;
1709       r.status = VAROBJ_INVALID;
1710       VEC_safe_push (varobj_update_result, result, &r);
1711       return result;
1712     }
1713
1714   if ((*varp)->root->rootvar == *varp)
1715     {
1716       varobj_update_result r = {0};
1717
1718       r.varobj = *varp;
1719       r.status = VAROBJ_IN_SCOPE;
1720
1721       /* Update the root variable.  value_of_root can return NULL
1722          if the variable is no longer around, i.e. we stepped out of
1723          the frame in which a local existed.  We are letting the 
1724          value_of_root variable dispose of the varobj if the type
1725          has changed.  */
1726       new = value_of_root (varp, &type_changed);
1727       if (update_type_if_necessary(*varp, new))
1728           type_changed = 1;
1729       r.varobj = *varp;
1730       r.type_changed = type_changed;
1731       if (install_new_value ((*varp), new, type_changed))
1732         r.changed = 1;
1733       
1734       if (new == NULL)
1735         r.status = VAROBJ_NOT_IN_SCOPE;
1736       r.value_installed = 1;
1737
1738       if (r.status == VAROBJ_NOT_IN_SCOPE)
1739         {
1740           if (r.type_changed || r.changed)
1741             VEC_safe_push (varobj_update_result, result, &r);
1742           return result;
1743         }
1744             
1745       VEC_safe_push (varobj_update_result, stack, &r);
1746     }
1747   else
1748     {
1749       varobj_update_result r = {0};
1750
1751       r.varobj = *varp;
1752       VEC_safe_push (varobj_update_result, stack, &r);
1753     }
1754
1755   /* Walk through the children, reconstructing them all.  */
1756   while (!VEC_empty (varobj_update_result, stack))
1757     {
1758       varobj_update_result r = *(VEC_last (varobj_update_result, stack));
1759       struct varobj *v = r.varobj;
1760
1761       VEC_pop (varobj_update_result, stack);
1762
1763       /* Update this variable, unless it's a root, which is already
1764          updated.  */
1765       if (!r.value_installed)
1766         {
1767           struct type *new_type;
1768
1769           new = value_of_child (v->parent, v->index);
1770           if (update_type_if_necessary(v, new))
1771             r.type_changed = 1;
1772           if (new)
1773             new_type = value_type (new);
1774           else
1775             new_type = v->root->lang->type_of_child (v->parent, v->index);
1776
1777           if (varobj_value_has_mutated (v, new, new_type))
1778             {
1779               /* The children are no longer valid; delete them now.
1780                  Report the fact that its type changed as well.  */
1781               varobj_delete (v, NULL, 1 /* only_children */);
1782               v->num_children = -1;
1783               v->to = -1;
1784               v->from = -1;
1785               v->type = new_type;
1786               r.type_changed = 1;
1787             }
1788
1789           if (install_new_value (v, new, r.type_changed))
1790             {
1791               r.changed = 1;
1792               v->updated = 0;
1793             }
1794         }
1795
1796       /* We probably should not get children of a varobj that has a
1797          pretty-printer, but for which -var-list-children was never
1798          invoked.  */
1799       if (v->dynamic->pretty_printer != NULL)
1800         {
1801           VEC (varobj_p) *changed = 0, *type_changed = 0, *unchanged = 0;
1802           VEC (varobj_p) *new = 0;
1803           int i, children_changed = 0;
1804
1805           if (v->frozen)
1806             continue;
1807
1808           if (!v->dynamic->children_requested)
1809             {
1810               int dummy;
1811
1812               /* If we initially did not have potential children, but
1813                  now we do, consider the varobj as changed.
1814                  Otherwise, if children were never requested, consider
1815                  it as unchanged -- presumably, such varobj is not yet
1816                  expanded in the UI, so we need not bother getting
1817                  it.  */
1818               if (!varobj_has_more (v, 0))
1819                 {
1820                   update_dynamic_varobj_children (v, NULL, NULL, NULL, NULL,
1821                                                   &dummy, 0, 0, 0);
1822                   if (varobj_has_more (v, 0))
1823                     r.changed = 1;
1824                 }
1825
1826               if (r.changed)
1827                 VEC_safe_push (varobj_update_result, result, &r);
1828
1829               continue;
1830             }
1831
1832           /* If update_dynamic_varobj_children returns 0, then we have
1833              a non-conforming pretty-printer, so we skip it.  */
1834           if (update_dynamic_varobj_children (v, &changed, &type_changed, &new,
1835                                               &unchanged, &children_changed, 1,
1836                                               v->from, v->to))
1837             {
1838               if (children_changed || new)
1839                 {
1840                   r.children_changed = 1;
1841                   r.new = new;
1842                 }
1843               /* Push in reverse order so that the first child is
1844                  popped from the work stack first, and so will be
1845                  added to result first.  This does not affect
1846                  correctness, just "nicer".  */
1847               for (i = VEC_length (varobj_p, type_changed) - 1; i >= 0; --i)
1848                 {
1849                   varobj_p tmp = VEC_index (varobj_p, type_changed, i);
1850                   varobj_update_result r = {0};
1851
1852                   /* Type may change only if value was changed.  */
1853                   r.varobj = tmp;
1854                   r.changed = 1;
1855                   r.type_changed = 1;
1856                   r.value_installed = 1;
1857                   VEC_safe_push (varobj_update_result, stack, &r);
1858                 }
1859               for (i = VEC_length (varobj_p, changed) - 1; i >= 0; --i)
1860                 {
1861                   varobj_p tmp = VEC_index (varobj_p, changed, i);
1862                   varobj_update_result r = {0};
1863
1864                   r.varobj = tmp;
1865                   r.changed = 1;
1866                   r.value_installed = 1;
1867                   VEC_safe_push (varobj_update_result, stack, &r);
1868                 }
1869               for (i = VEC_length (varobj_p, unchanged) - 1; i >= 0; --i)
1870                 {
1871                   varobj_p tmp = VEC_index (varobj_p, unchanged, i);
1872
1873                   if (!tmp->frozen)
1874                     {
1875                       varobj_update_result r = {0};
1876
1877                       r.varobj = tmp;
1878                       r.value_installed = 1;
1879                       VEC_safe_push (varobj_update_result, stack, &r);
1880                     }
1881                 }
1882               if (r.changed || r.children_changed)
1883                 VEC_safe_push (varobj_update_result, result, &r);
1884
1885               /* Free CHANGED, TYPE_CHANGED and UNCHANGED, but not NEW,
1886                  because NEW has been put into the result vector.  */
1887               VEC_free (varobj_p, changed);
1888               VEC_free (varobj_p, type_changed);
1889               VEC_free (varobj_p, unchanged);
1890
1891               continue;
1892             }
1893         }
1894
1895       /* Push any children.  Use reverse order so that the first
1896          child is popped from the work stack first, and so
1897          will be added to result first.  This does not
1898          affect correctness, just "nicer".  */
1899       for (i = VEC_length (varobj_p, v->children)-1; i >= 0; --i)
1900         {
1901           varobj_p c = VEC_index (varobj_p, v->children, i);
1902
1903           /* Child may be NULL if explicitly deleted by -var-delete.  */
1904           if (c != NULL && !c->frozen)
1905             {
1906               varobj_update_result r = {0};
1907
1908               r.varobj = c;
1909               VEC_safe_push (varobj_update_result, stack, &r);
1910             }
1911         }
1912
1913       if (r.changed || r.type_changed)
1914         VEC_safe_push (varobj_update_result, result, &r);
1915     }
1916
1917   VEC_free (varobj_update_result, stack);
1918
1919   return result;
1920 }
1921 \f
1922
1923 /* Helper functions */
1924
1925 /*
1926  * Variable object construction/destruction
1927  */
1928
1929 static int
1930 delete_variable (struct cpstack **resultp, struct varobj *var,
1931                  int only_children_p)
1932 {
1933   int delcount = 0;
1934
1935   delete_variable_1 (resultp, &delcount, var,
1936                      only_children_p, 1 /* remove_from_parent_p */ );
1937
1938   return delcount;
1939 }
1940
1941 /* Delete the variable object VAR and its children.  */
1942 /* IMPORTANT NOTE: If we delete a variable which is a child
1943    and the parent is not removed we dump core.  It must be always
1944    initially called with remove_from_parent_p set.  */
1945 static void
1946 delete_variable_1 (struct cpstack **resultp, int *delcountp,
1947                    struct varobj *var, int only_children_p,
1948                    int remove_from_parent_p)
1949 {
1950   int i;
1951
1952   /* Delete any children of this variable, too.  */
1953   for (i = 0; i < VEC_length (varobj_p, var->children); ++i)
1954     {   
1955       varobj_p child = VEC_index (varobj_p, var->children, i);
1956
1957       if (!child)
1958         continue;
1959       if (!remove_from_parent_p)
1960         child->parent = NULL;
1961       delete_variable_1 (resultp, delcountp, child, 0, only_children_p);
1962     }
1963   VEC_free (varobj_p, var->children);
1964
1965   /* if we were called to delete only the children we are done here.  */
1966   if (only_children_p)
1967     return;
1968
1969   /* Otherwise, add it to the list of deleted ones and proceed to do so.  */
1970   /* If the name is null, this is a temporary variable, that has not
1971      yet been installed, don't report it, it belongs to the caller...  */
1972   if (var->obj_name != NULL)
1973     {
1974       cppush (resultp, xstrdup (var->obj_name));
1975       *delcountp = *delcountp + 1;
1976     }
1977
1978   /* If this variable has a parent, remove it from its parent's list.  */
1979   /* OPTIMIZATION: if the parent of this variable is also being deleted, 
1980      (as indicated by remove_from_parent_p) we don't bother doing an
1981      expensive list search to find the element to remove when we are
1982      discarding the list afterwards.  */
1983   if ((remove_from_parent_p) && (var->parent != NULL))
1984     {
1985       VEC_replace (varobj_p, var->parent->children, var->index, NULL);
1986     }
1987
1988   if (var->obj_name != NULL)
1989     uninstall_variable (var);
1990
1991   /* Free memory associated with this variable.  */
1992   free_variable (var);
1993 }
1994
1995 /* Install the given variable VAR with the object name VAR->OBJ_NAME.  */
1996 static int
1997 install_variable (struct varobj *var)
1998 {
1999   struct vlist *cv;
2000   struct vlist *newvl;
2001   const char *chp;
2002   unsigned int index = 0;
2003   unsigned int i = 1;
2004
2005   for (chp = var->obj_name; *chp; chp++)
2006     {
2007       index = (index + (i++ * (unsigned int) *chp)) % VAROBJ_TABLE_SIZE;
2008     }
2009
2010   cv = *(varobj_table + index);
2011   while ((cv != NULL) && (strcmp (cv->var->obj_name, var->obj_name) != 0))
2012     cv = cv->next;
2013
2014   if (cv != NULL)
2015     error (_("Duplicate variable object name"));
2016
2017   /* Add varobj to hash table.  */
2018   newvl = xmalloc (sizeof (struct vlist));
2019   newvl->next = *(varobj_table + index);
2020   newvl->var = var;
2021   *(varobj_table + index) = newvl;
2022
2023   /* If root, add varobj to root list.  */
2024   if (is_root_p (var))
2025     {
2026       /* Add to list of root variables.  */
2027       if (rootlist == NULL)
2028         var->root->next = NULL;
2029       else
2030         var->root->next = rootlist;
2031       rootlist = var->root;
2032     }
2033
2034   return 1;                     /* OK */
2035 }
2036
2037 /* Unistall the object VAR.  */
2038 static void
2039 uninstall_variable (struct varobj *var)
2040 {
2041   struct vlist *cv;
2042   struct vlist *prev;
2043   struct varobj_root *cr;
2044   struct varobj_root *prer;
2045   const char *chp;
2046   unsigned int index = 0;
2047   unsigned int i = 1;
2048
2049   /* Remove varobj from hash table.  */
2050   for (chp = var->obj_name; *chp; chp++)
2051     {
2052       index = (index + (i++ * (unsigned int) *chp)) % VAROBJ_TABLE_SIZE;
2053     }
2054
2055   cv = *(varobj_table + index);
2056   prev = NULL;
2057   while ((cv != NULL) && (strcmp (cv->var->obj_name, var->obj_name) != 0))
2058     {
2059       prev = cv;
2060       cv = cv->next;
2061     }
2062
2063   if (varobjdebug)
2064     fprintf_unfiltered (gdb_stdlog, "Deleting %s\n", var->obj_name);
2065
2066   if (cv == NULL)
2067     {
2068       warning
2069         ("Assertion failed: Could not find variable object \"%s\" to delete",
2070          var->obj_name);
2071       return;
2072     }
2073
2074   if (prev == NULL)
2075     *(varobj_table + index) = cv->next;
2076   else
2077     prev->next = cv->next;
2078
2079   xfree (cv);
2080
2081   /* If root, remove varobj from root list.  */
2082   if (is_root_p (var))
2083     {
2084       /* Remove from list of root variables.  */
2085       if (rootlist == var->root)
2086         rootlist = var->root->next;
2087       else
2088         {
2089           prer = NULL;
2090           cr = rootlist;
2091           while ((cr != NULL) && (cr->rootvar != var))
2092             {
2093               prer = cr;
2094               cr = cr->next;
2095             }
2096           if (cr == NULL)
2097             {
2098               warning (_("Assertion failed: Could not find "
2099                          "varobj \"%s\" in root list"),
2100                        var->obj_name);
2101               return;
2102             }
2103           if (prer == NULL)
2104             rootlist = NULL;
2105           else
2106             prer->next = cr->next;
2107         }
2108     }
2109
2110 }
2111
2112 /* Create and install a child of the parent of the given name.  */
2113 static struct varobj *
2114 create_child (struct varobj *parent, int index, char *name)
2115 {
2116   return create_child_with_value (parent, index, name, 
2117                                   value_of_child (parent, index));
2118 }
2119
2120 static struct varobj *
2121 create_child_with_value (struct varobj *parent, int index, char *name,
2122                          struct value *value)
2123 {
2124   struct varobj *child;
2125   char *childs_name;
2126
2127   child = new_variable ();
2128
2129   /* NAME is allocated by caller.  */
2130   child->name = name;
2131   child->index = index;
2132   child->parent = parent;
2133   child->root = parent->root;
2134
2135   if (varobj_is_anonymous_child (child))
2136     childs_name = xstrprintf ("%s.%d_anonymous", parent->obj_name, index);
2137   else
2138     childs_name = xstrprintf ("%s.%s", parent->obj_name, name);
2139   child->obj_name = childs_name;
2140
2141   install_variable (child);
2142
2143   /* Compute the type of the child.  Must do this before
2144      calling install_new_value.  */
2145   if (value != NULL)
2146     /* If the child had no evaluation errors, var->value
2147        will be non-NULL and contain a valid type.  */
2148     child->type = value_actual_type (value, 0, NULL);
2149   else
2150     /* Otherwise, we must compute the type.  */
2151     child->type = (*child->root->lang->type_of_child) (child->parent, 
2152                                                        child->index);
2153   install_new_value (child, value, 1);
2154
2155   return child;
2156 }
2157 \f
2158
2159 /*
2160  * Miscellaneous utility functions.
2161  */
2162
2163 /* Allocate memory and initialize a new variable.  */
2164 static struct varobj *
2165 new_variable (void)
2166 {
2167   struct varobj *var;
2168
2169   var = (struct varobj *) xmalloc (sizeof (struct varobj));
2170   var->name = NULL;
2171   var->path_expr = NULL;
2172   var->obj_name = NULL;
2173   var->index = -1;
2174   var->type = NULL;
2175   var->value = NULL;
2176   var->num_children = -1;
2177   var->parent = NULL;
2178   var->children = NULL;
2179   var->format = 0;
2180   var->root = NULL;
2181   var->updated = 0;
2182   var->print_value = NULL;
2183   var->frozen = 0;
2184   var->not_fetched = 0;
2185   var->dynamic
2186     = (struct varobj_dynamic *) xmalloc (sizeof (struct varobj_dynamic));
2187   var->dynamic->children_requested = 0;
2188   var->from = -1;
2189   var->to = -1;
2190   var->dynamic->constructor = 0;
2191   var->dynamic->pretty_printer = 0;
2192   var->dynamic->child_iter = 0;
2193   var->dynamic->saved_item = 0;
2194
2195   return var;
2196 }
2197
2198 /* Allocate memory and initialize a new root variable.  */
2199 static struct varobj *
2200 new_root_variable (void)
2201 {
2202   struct varobj *var = new_variable ();
2203
2204   var->root = (struct varobj_root *) xmalloc (sizeof (struct varobj_root));
2205   var->root->lang = NULL;
2206   var->root->exp = NULL;
2207   var->root->valid_block = NULL;
2208   var->root->frame = null_frame_id;
2209   var->root->floating = 0;
2210   var->root->rootvar = NULL;
2211   var->root->is_valid = 1;
2212
2213   return var;
2214 }
2215
2216 /* Free any allocated memory associated with VAR.  */
2217 static void
2218 free_variable (struct varobj *var)
2219 {
2220 #if HAVE_PYTHON
2221   if (var->dynamic->pretty_printer != NULL)
2222     {
2223       struct cleanup *cleanup = varobj_ensure_python_env (var);
2224
2225       Py_XDECREF (var->dynamic->constructor);
2226       Py_XDECREF (var->dynamic->pretty_printer);
2227       Py_XDECREF (var->dynamic->child_iter);
2228       Py_XDECREF (var->dynamic->saved_item);
2229       do_cleanups (cleanup);
2230     }
2231 #endif
2232
2233   value_free (var->value);
2234
2235   /* Free the expression if this is a root variable.  */
2236   if (is_root_p (var))
2237     {
2238       xfree (var->root->exp);
2239       xfree (var->root);
2240     }
2241
2242   xfree (var->name);
2243   xfree (var->obj_name);
2244   xfree (var->print_value);
2245   xfree (var->path_expr);
2246   xfree (var->dynamic);
2247   xfree (var);
2248 }
2249
2250 static void
2251 do_free_variable_cleanup (void *var)
2252 {
2253   free_variable (var);
2254 }
2255
2256 static struct cleanup *
2257 make_cleanup_free_variable (struct varobj *var)
2258 {
2259   return make_cleanup (do_free_variable_cleanup, var);
2260 }
2261
2262 /* Return the type of the value that's stored in VAR,
2263    or that would have being stored there if the
2264    value were accessible.
2265
2266    This differs from VAR->type in that VAR->type is always
2267    the true type of the expession in the source language.
2268    The return value of this function is the type we're
2269    actually storing in varobj, and using for displaying
2270    the values and for comparing previous and new values.
2271
2272    For example, top-level references are always stripped.  */
2273 struct type *
2274 varobj_get_value_type (struct varobj *var)
2275 {
2276   struct type *type;
2277
2278   if (var->value)
2279     type = value_type (var->value);
2280   else
2281     type = var->type;
2282
2283   type = check_typedef (type);
2284
2285   if (TYPE_CODE (type) == TYPE_CODE_REF)
2286     type = get_target_type (type);
2287
2288   type = check_typedef (type);
2289
2290   return type;
2291 }
2292
2293 /* What is the default display for this variable? We assume that
2294    everything is "natural".  Any exceptions?  */
2295 static enum varobj_display_formats
2296 variable_default_display (struct varobj *var)
2297 {
2298   return FORMAT_NATURAL;
2299 }
2300
2301 /* FIXME: The following should be generic for any pointer.  */
2302 static void
2303 cppush (struct cpstack **pstack, char *name)
2304 {
2305   struct cpstack *s;
2306
2307   s = (struct cpstack *) xmalloc (sizeof (struct cpstack));
2308   s->name = name;
2309   s->next = *pstack;
2310   *pstack = s;
2311 }
2312
2313 /* FIXME: The following should be generic for any pointer.  */
2314 static char *
2315 cppop (struct cpstack **pstack)
2316 {
2317   struct cpstack *s;
2318   char *v;
2319
2320   if ((*pstack)->name == NULL && (*pstack)->next == NULL)
2321     return NULL;
2322
2323   s = *pstack;
2324   v = s->name;
2325   *pstack = (*pstack)->next;
2326   xfree (s);
2327
2328   return v;
2329 }
2330 \f
2331 /*
2332  * Language-dependencies
2333  */
2334
2335 /* Common entry points */
2336
2337 /* Get the language of variable VAR.  */
2338 static enum varobj_languages
2339 variable_language (struct varobj *var)
2340 {
2341   enum varobj_languages lang;
2342
2343   switch (var->root->exp->language_defn->la_language)
2344     {
2345     default:
2346     case language_c:
2347       lang = vlang_c;
2348       break;
2349     case language_cplus:
2350       lang = vlang_cplus;
2351       break;
2352     case language_java:
2353       lang = vlang_java;
2354       break;
2355     case language_ada:
2356       lang = vlang_ada;
2357       break;
2358     }
2359
2360   return lang;
2361 }
2362
2363 /* Return the number of children for a given variable.
2364    The result of this function is defined by the language
2365    implementation.  The number of children returned by this function
2366    is the number of children that the user will see in the variable
2367    display.  */
2368 static int
2369 number_of_children (struct varobj *var)
2370 {
2371   return (*var->root->lang->number_of_children) (var);
2372 }
2373
2374 /* What is the expression for the root varobj VAR? Returns a malloc'd
2375    string.  */
2376 static char *
2377 name_of_variable (struct varobj *var)
2378 {
2379   return (*var->root->lang->name_of_variable) (var);
2380 }
2381
2382 /* What is the name of the INDEX'th child of VAR? Returns a malloc'd
2383    string.  */
2384 static char *
2385 name_of_child (struct varobj *var, int index)
2386 {
2387   return (*var->root->lang->name_of_child) (var, index);
2388 }
2389
2390 /* If frame associated with VAR can be found, switch
2391    to it and return 1.  Otherwise, return 0.  */
2392
2393 static int
2394 check_scope (struct varobj *var)
2395 {
2396   struct frame_info *fi;
2397   int scope;
2398
2399   fi = frame_find_by_id (var->root->frame);
2400   scope = fi != NULL;
2401
2402   if (fi)
2403     {
2404       CORE_ADDR pc = get_frame_pc (fi);
2405
2406       if (pc <  BLOCK_START (var->root->valid_block) ||
2407           pc >= BLOCK_END (var->root->valid_block))
2408         scope = 0;
2409       else
2410         select_frame (fi);
2411     }
2412   return scope;
2413 }
2414
2415 /* Helper function to value_of_root.  */
2416
2417 static struct value *
2418 value_of_root_1 (struct varobj **var_handle)
2419 {
2420   struct value *new_val = NULL;
2421   struct varobj *var = *var_handle;
2422   int within_scope = 0;
2423   struct cleanup *back_to;
2424                                                                  
2425   /*  Only root variables can be updated...  */
2426   if (!is_root_p (var))
2427     /* Not a root var.  */
2428     return NULL;
2429
2430   back_to = make_cleanup_restore_current_thread ();
2431
2432   /* Determine whether the variable is still around.  */
2433   if (var->root->valid_block == NULL || var->root->floating)
2434     within_scope = 1;
2435   else if (var->root->thread_id == 0)
2436     {
2437       /* The program was single-threaded when the variable object was
2438          created.  Technically, it's possible that the program became
2439          multi-threaded since then, but we don't support such
2440          scenario yet.  */
2441       within_scope = check_scope (var);   
2442     }
2443   else
2444     {
2445       ptid_t ptid = thread_id_to_pid (var->root->thread_id);
2446       if (in_thread_list (ptid))
2447         {
2448           switch_to_thread (ptid);
2449           within_scope = check_scope (var);
2450         }
2451     }
2452
2453   if (within_scope)
2454     {
2455       volatile struct gdb_exception except;
2456
2457       /* We need to catch errors here, because if evaluate
2458          expression fails we want to just return NULL.  */
2459       TRY_CATCH (except, RETURN_MASK_ERROR)
2460         {
2461           new_val = evaluate_expression (var->root->exp);
2462         }
2463     }
2464
2465   do_cleanups (back_to);
2466
2467   return new_val;
2468 }
2469
2470 /* What is the ``struct value *'' of the root variable VAR?
2471    For floating variable object, evaluation can get us a value
2472    of different type from what is stored in varobj already.  In
2473    that case:
2474    - *type_changed will be set to 1
2475    - old varobj will be freed, and new one will be
2476    created, with the same name.
2477    - *var_handle will be set to the new varobj 
2478    Otherwise, *type_changed will be set to 0.  */
2479 static struct value *
2480 value_of_root (struct varobj **var_handle, int *type_changed)
2481 {
2482   struct varobj *var;
2483
2484   if (var_handle == NULL)
2485     return NULL;
2486
2487   var = *var_handle;
2488
2489   /* This should really be an exception, since this should
2490      only get called with a root variable.  */
2491
2492   if (!is_root_p (var))
2493     return NULL;
2494
2495   if (var->root->floating)
2496     {
2497       struct varobj *tmp_var;
2498       char *old_type, *new_type;
2499
2500       tmp_var = varobj_create (NULL, var->name, (CORE_ADDR) 0,
2501                                USE_SELECTED_FRAME);
2502       if (tmp_var == NULL)
2503         {
2504           return NULL;
2505         }
2506       old_type = varobj_get_type (var);
2507       new_type = varobj_get_type (tmp_var);
2508       if (strcmp (old_type, new_type) == 0)
2509         {
2510           /* The expression presently stored inside var->root->exp
2511              remembers the locations of local variables relatively to
2512              the frame where the expression was created (in DWARF location
2513              button, for example).  Naturally, those locations are not
2514              correct in other frames, so update the expression.  */
2515
2516          struct expression *tmp_exp = var->root->exp;
2517
2518          var->root->exp = tmp_var->root->exp;
2519          tmp_var->root->exp = tmp_exp;
2520
2521           varobj_delete (tmp_var, NULL, 0);
2522           *type_changed = 0;
2523         }
2524       else
2525         {
2526           tmp_var->obj_name = xstrdup (var->obj_name);
2527           tmp_var->from = var->from;
2528           tmp_var->to = var->to;
2529           varobj_delete (var, NULL, 0);
2530
2531           install_variable (tmp_var);
2532           *var_handle = tmp_var;
2533           var = *var_handle;
2534           *type_changed = 1;
2535         }
2536       xfree (old_type);
2537       xfree (new_type);
2538     }
2539   else
2540     {
2541       *type_changed = 0;
2542     }
2543
2544   {
2545     struct value *value;
2546
2547     value = value_of_root_1 (var_handle);
2548     if (var->value == NULL || value == NULL)
2549       {
2550         /* For root varobj-s, a NULL value indicates a scoping issue.
2551            So, nothing to do in terms of checking for mutations.  */
2552       }
2553     else if (varobj_value_has_mutated (var, value, value_type (value)))
2554       {
2555         /* The type has mutated, so the children are no longer valid.
2556            Just delete them, and tell our caller that the type has
2557            changed.  */
2558         varobj_delete (var, NULL, 1 /* only_children */);
2559         var->num_children = -1;
2560         var->to = -1;
2561         var->from = -1;
2562         *type_changed = 1;
2563       }
2564     return value;
2565   }
2566 }
2567
2568 /* What is the ``struct value *'' for the INDEX'th child of PARENT?  */
2569 static struct value *
2570 value_of_child (struct varobj *parent, int index)
2571 {
2572   struct value *value;
2573
2574   value = (*parent->root->lang->value_of_child) (parent, index);
2575
2576   return value;
2577 }
2578
2579 /* GDB already has a command called "value_of_variable".  Sigh.  */
2580 static char *
2581 my_value_of_variable (struct varobj *var, enum varobj_display_formats format)
2582 {
2583   if (var->root->is_valid)
2584     {
2585       if (var->dynamic->pretty_printer != NULL)
2586         return varobj_value_get_print_value (var->value, var->format, var);
2587       return (*var->root->lang->value_of_variable) (var, format);
2588     }
2589   else
2590     return NULL;
2591 }
2592
2593 void
2594 varobj_formatted_print_options (struct value_print_options *opts,
2595                                 enum varobj_display_formats format)
2596 {
2597   get_formatted_print_options (opts, format_code[(int) format]);
2598   opts->deref_ref = 0;
2599   opts->raw = 1;
2600 }
2601
2602 char *
2603 varobj_value_get_print_value (struct value *value,
2604                               enum varobj_display_formats format,
2605                               struct varobj *var)
2606 {
2607   struct ui_file *stb;
2608   struct cleanup *old_chain;
2609   char *thevalue = NULL;
2610   struct value_print_options opts;
2611   struct type *type = NULL;
2612   long len = 0;
2613   char *encoding = NULL;
2614   struct gdbarch *gdbarch = NULL;
2615   /* Initialize it just to avoid a GCC false warning.  */
2616   CORE_ADDR str_addr = 0;
2617   int string_print = 0;
2618
2619   if (value == NULL)
2620     return NULL;
2621
2622   stb = mem_fileopen ();
2623   old_chain = make_cleanup_ui_file_delete (stb);
2624
2625   gdbarch = get_type_arch (value_type (value));
2626 #if HAVE_PYTHON
2627   if (gdb_python_initialized)
2628     {
2629       PyObject *value_formatter =  var->dynamic->pretty_printer;
2630
2631       varobj_ensure_python_env (var);
2632
2633       if (value_formatter)
2634         {
2635           /* First check to see if we have any children at all.  If so,
2636              we simply return {...}.  */
2637           if (dynamic_varobj_has_child_method (var))
2638             {
2639               do_cleanups (old_chain);
2640               return xstrdup ("{...}");
2641             }
2642
2643           if (PyObject_HasAttr (value_formatter, gdbpy_to_string_cst))
2644             {
2645               struct value *replacement;
2646               PyObject *output = NULL;
2647
2648               output = apply_varobj_pretty_printer (value_formatter,
2649                                                     &replacement,
2650                                                     stb);
2651
2652               /* If we have string like output ...  */
2653               if (output)
2654                 {
2655                   make_cleanup_py_decref (output);
2656
2657                   /* If this is a lazy string, extract it.  For lazy
2658                      strings we always print as a string, so set
2659                      string_print.  */
2660                   if (gdbpy_is_lazy_string (output))
2661                     {
2662                       gdbpy_extract_lazy_string (output, &str_addr, &type,
2663                                                  &len, &encoding);
2664                       make_cleanup (free_current_contents, &encoding);
2665                       string_print = 1;
2666                     }
2667                   else
2668                     {
2669                       /* If it is a regular (non-lazy) string, extract
2670                          it and copy the contents into THEVALUE.  If the
2671                          hint says to print it as a string, set
2672                          string_print.  Otherwise just return the extracted
2673                          string as a value.  */
2674
2675                       char *s = python_string_to_target_string (output);
2676
2677                       if (s)
2678                         {
2679                           char *hint;
2680
2681                           hint = gdbpy_get_display_hint (value_formatter);
2682                           if (hint)
2683                             {
2684                               if (!strcmp (hint, "string"))
2685                                 string_print = 1;
2686                               xfree (hint);
2687                             }
2688
2689                           len = strlen (s);
2690                           thevalue = xmemdup (s, len + 1, len + 1);
2691                           type = builtin_type (gdbarch)->builtin_char;
2692                           xfree (s);
2693
2694                           if (!string_print)
2695                             {
2696                               do_cleanups (old_chain);
2697                               return thevalue;
2698                             }
2699
2700                           make_cleanup (xfree, thevalue);
2701                         }
2702                       else
2703                         gdbpy_print_stack ();
2704                     }
2705                 }
2706               /* If the printer returned a replacement value, set VALUE
2707                  to REPLACEMENT.  If there is not a replacement value,
2708                  just use the value passed to this function.  */
2709               if (replacement)
2710                 value = replacement;
2711             }
2712         }
2713     }
2714 #endif
2715
2716   varobj_formatted_print_options (&opts, format);
2717
2718   /* If the THEVALUE has contents, it is a regular string.  */
2719   if (thevalue)
2720     LA_PRINT_STRING (stb, type, (gdb_byte *) thevalue, len, encoding, 0, &opts);
2721   else if (string_print)
2722     /* Otherwise, if string_print is set, and it is not a regular
2723        string, it is a lazy string.  */
2724     val_print_string (type, encoding, str_addr, len, stb, &opts);
2725   else
2726     /* All other cases.  */
2727     common_val_print (value, stb, 0, &opts, current_language);
2728
2729   thevalue = ui_file_xstrdup (stb, NULL);
2730
2731   do_cleanups (old_chain);
2732   return thevalue;
2733 }
2734
2735 int
2736 varobj_editable_p (struct varobj *var)
2737 {
2738   struct type *type;
2739
2740   if (!(var->root->is_valid && var->value && VALUE_LVAL (var->value)))
2741     return 0;
2742
2743   type = varobj_get_value_type (var);
2744
2745   switch (TYPE_CODE (type))
2746     {
2747     case TYPE_CODE_STRUCT:
2748     case TYPE_CODE_UNION:
2749     case TYPE_CODE_ARRAY:
2750     case TYPE_CODE_FUNC:
2751     case TYPE_CODE_METHOD:
2752       return 0;
2753       break;
2754
2755     default:
2756       return 1;
2757       break;
2758     }
2759 }
2760
2761 /* Call VAR's value_is_changeable_p language-specific callback.  */
2762
2763 int
2764 varobj_value_is_changeable_p (struct varobj *var)
2765 {
2766   return var->root->lang->value_is_changeable_p (var);
2767 }
2768
2769 /* Return 1 if that varobj is floating, that is is always evaluated in the
2770    selected frame, and not bound to thread/frame.  Such variable objects
2771    are created using '@' as frame specifier to -var-create.  */
2772 int
2773 varobj_floating_p (struct varobj *var)
2774 {
2775   return var->root->floating;
2776 }
2777
2778 /* Implement the "value_is_changeable_p" varobj callback for most
2779    languages.  */
2780
2781 int
2782 varobj_default_value_is_changeable_p (struct varobj *var)
2783 {
2784   int r;
2785   struct type *type;
2786
2787   if (CPLUS_FAKE_CHILD (var))
2788     return 0;
2789
2790   type = varobj_get_value_type (var);
2791
2792   switch (TYPE_CODE (type))
2793     {
2794     case TYPE_CODE_STRUCT:
2795     case TYPE_CODE_UNION:
2796     case TYPE_CODE_ARRAY:
2797       r = 0;
2798       break;
2799
2800     default:
2801       r = 1;
2802     }
2803
2804   return r;
2805 }
2806
2807 /* Iterate all the existing _root_ VAROBJs and call the FUNC callback for them
2808    with an arbitrary caller supplied DATA pointer.  */
2809
2810 void
2811 all_root_varobjs (void (*func) (struct varobj *var, void *data), void *data)
2812 {
2813   struct varobj_root *var_root, *var_root_next;
2814
2815   /* Iterate "safely" - handle if the callee deletes its passed VAROBJ.  */
2816
2817   for (var_root = rootlist; var_root != NULL; var_root = var_root_next)
2818     {
2819       var_root_next = var_root->next;
2820
2821       (*func) (var_root->rootvar, data);
2822     }
2823 }
2824 \f
2825 extern void _initialize_varobj (void);
2826 void
2827 _initialize_varobj (void)
2828 {
2829   int sizeof_table = sizeof (struct vlist *) * VAROBJ_TABLE_SIZE;
2830
2831   varobj_table = xmalloc (sizeof_table);
2832   memset (varobj_table, 0, sizeof_table);
2833
2834   add_setshow_zuinteger_cmd ("debugvarobj", class_maintenance,
2835                              &varobjdebug,
2836                              _("Set varobj debugging."),
2837                              _("Show varobj debugging."),
2838                              _("When non-zero, varobj debugging is enabled."),
2839                              NULL, show_varobjdebug,
2840                              &setlist, &showlist);
2841 }
2842
2843 /* Invalidate varobj VAR if it is tied to locals and re-create it if it is
2844    defined on globals.  It is a helper for varobj_invalidate.
2845
2846    This function is called after changing the symbol file, in this case the
2847    pointers to "struct type" stored by the varobj are no longer valid.  All
2848    varobj must be either re-evaluated, or marked as invalid here.  */
2849
2850 static void
2851 varobj_invalidate_iter (struct varobj *var, void *unused)
2852 {
2853   /* global and floating var must be re-evaluated.  */
2854   if (var->root->floating || var->root->valid_block == NULL)
2855     {
2856       struct varobj *tmp_var;
2857
2858       /* Try to create a varobj with same expression.  If we succeed
2859          replace the old varobj, otherwise invalidate it.  */
2860       tmp_var = varobj_create (NULL, var->name, (CORE_ADDR) 0,
2861                                USE_CURRENT_FRAME);
2862       if (tmp_var != NULL) 
2863         { 
2864           tmp_var->obj_name = xstrdup (var->obj_name);
2865           varobj_delete (var, NULL, 0);
2866           install_variable (tmp_var);
2867         }
2868       else
2869         var->root->is_valid = 0;
2870     }
2871   else /* locals must be invalidated.  */
2872     var->root->is_valid = 0;
2873 }
2874
2875 /* Invalidate the varobjs that are tied to locals and re-create the ones that
2876    are defined on globals.
2877    Invalidated varobjs will be always printed in_scope="invalid".  */
2878
2879 void 
2880 varobj_invalidate (void)
2881 {
2882   all_root_varobjs (varobj_invalidate_iter, NULL);
2883 }