cleanup: make allocate_value_contents static
[external/binutils.git] / gdb / value.c
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "gdb_string.h"
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "value.h"
26 #include "gdbcore.h"
27 #include "command.h"
28 #include "gdbcmd.h"
29 #include "target.h"
30 #include "language.h"
31 #include "demangle.h"
32 #include "doublest.h"
33 #include "gdb_assert.h"
34 #include "regcache.h"
35 #include "block.h"
36 #include "dfp.h"
37 #include "objfiles.h"
38 #include "valprint.h"
39 #include "cli/cli-decode.h"
40 #include "exceptions.h"
41 #include "python/python.h"
42 #include <ctype.h>
43 #include "tracepoint.h"
44 #include "cp-abi.h"
45 #include "user-regs.h"
46
47 /* Prototypes for exported functions.  */
48
49 void _initialize_values (void);
50
51 /* Definition of a user function.  */
52 struct internal_function
53 {
54   /* The name of the function.  It is a bit odd to have this in the
55      function itself -- the user might use a differently-named
56      convenience variable to hold the function.  */
57   char *name;
58
59   /* The handler.  */
60   internal_function_fn handler;
61
62   /* User data for the handler.  */
63   void *cookie;
64 };
65
66 /* Defines an [OFFSET, OFFSET + LENGTH) range.  */
67
68 struct range
69 {
70   /* Lowest offset in the range.  */
71   int offset;
72
73   /* Length of the range.  */
74   int length;
75 };
76
77 typedef struct range range_s;
78
79 DEF_VEC_O(range_s);
80
81 /* Returns true if the ranges defined by [offset1, offset1+len1) and
82    [offset2, offset2+len2) overlap.  */
83
84 static int
85 ranges_overlap (int offset1, int len1,
86                 int offset2, int len2)
87 {
88   ULONGEST h, l;
89
90   l = max (offset1, offset2);
91   h = min (offset1 + len1, offset2 + len2);
92   return (l < h);
93 }
94
95 /* Returns true if the first argument is strictly less than the
96    second, useful for VEC_lower_bound.  We keep ranges sorted by
97    offset and coalesce overlapping and contiguous ranges, so this just
98    compares the starting offset.  */
99
100 static int
101 range_lessthan (const range_s *r1, const range_s *r2)
102 {
103   return r1->offset < r2->offset;
104 }
105
106 /* Returns true if RANGES contains any range that overlaps [OFFSET,
107    OFFSET+LENGTH).  */
108
109 static int
110 ranges_contain (VEC(range_s) *ranges, int offset, int length)
111 {
112   range_s what;
113   int i;
114
115   what.offset = offset;
116   what.length = length;
117
118   /* We keep ranges sorted by offset and coalesce overlapping and
119      contiguous ranges, so to check if a range list contains a given
120      range, we can do a binary search for the position the given range
121      would be inserted if we only considered the starting OFFSET of
122      ranges.  We call that position I.  Since we also have LENGTH to
123      care for (this is a range afterall), we need to check if the
124      _previous_ range overlaps the I range.  E.g.,
125
126          R
127          |---|
128        |---|    |---|  |------| ... |--|
129        0        1      2            N
130
131        I=1
132
133      In the case above, the binary search would return `I=1', meaning,
134      this OFFSET should be inserted at position 1, and the current
135      position 1 should be pushed further (and before 2).  But, `0'
136      overlaps with R.
137
138      Then we need to check if the I range overlaps the I range itself.
139      E.g.,
140
141               R
142               |---|
143        |---|    |---|  |-------| ... |--|
144        0        1      2             N
145
146        I=1
147   */
148
149   i = VEC_lower_bound (range_s, ranges, &what, range_lessthan);
150
151   if (i > 0)
152     {
153       struct range *bef = VEC_index (range_s, ranges, i - 1);
154
155       if (ranges_overlap (bef->offset, bef->length, offset, length))
156         return 1;
157     }
158
159   if (i < VEC_length (range_s, ranges))
160     {
161       struct range *r = VEC_index (range_s, ranges, i);
162
163       if (ranges_overlap (r->offset, r->length, offset, length))
164         return 1;
165     }
166
167   return 0;
168 }
169
170 static struct cmd_list_element *functionlist;
171
172 /* Note that the fields in this structure are arranged to save a bit
173    of memory.  */
174
175 struct value
176 {
177   /* Type of value; either not an lval, or one of the various
178      different possible kinds of lval.  */
179   enum lval_type lval;
180
181   /* Is it modifiable?  Only relevant if lval != not_lval.  */
182   unsigned int modifiable : 1;
183
184   /* If zero, contents of this value are in the contents field.  If
185      nonzero, contents are in inferior.  If the lval field is lval_memory,
186      the contents are in inferior memory at location.address plus offset.
187      The lval field may also be lval_register.
188
189      WARNING: This field is used by the code which handles watchpoints
190      (see breakpoint.c) to decide whether a particular value can be
191      watched by hardware watchpoints.  If the lazy flag is set for
192      some member of a value chain, it is assumed that this member of
193      the chain doesn't need to be watched as part of watching the
194      value itself.  This is how GDB avoids watching the entire struct
195      or array when the user wants to watch a single struct member or
196      array element.  If you ever change the way lazy flag is set and
197      reset, be sure to consider this use as well!  */
198   unsigned int lazy : 1;
199
200   /* If nonzero, this is the value of a variable which does not
201      actually exist in the program.  */
202   unsigned int optimized_out : 1;
203
204   /* If value is a variable, is it initialized or not.  */
205   unsigned int initialized : 1;
206
207   /* If value is from the stack.  If this is set, read_stack will be
208      used instead of read_memory to enable extra caching.  */
209   unsigned int stack : 1;
210
211   /* If the value has been released.  */
212   unsigned int released : 1;
213
214   /* Location of value (if lval).  */
215   union
216   {
217     /* If lval == lval_memory, this is the address in the inferior.
218        If lval == lval_register, this is the byte offset into the
219        registers structure.  */
220     CORE_ADDR address;
221
222     /* Pointer to internal variable.  */
223     struct internalvar *internalvar;
224
225     /* If lval == lval_computed, this is a set of function pointers
226        to use to access and describe the value, and a closure pointer
227        for them to use.  */
228     struct
229     {
230       /* Functions to call.  */
231       const struct lval_funcs *funcs;
232
233       /* Closure for those functions to use.  */
234       void *closure;
235     } computed;
236   } location;
237
238   /* Describes offset of a value within lval of a structure in bytes.
239      If lval == lval_memory, this is an offset to the address.  If
240      lval == lval_register, this is a further offset from
241      location.address within the registers structure.  Note also the
242      member embedded_offset below.  */
243   int offset;
244
245   /* Only used for bitfields; number of bits contained in them.  */
246   int bitsize;
247
248   /* Only used for bitfields; position of start of field.  For
249      gdbarch_bits_big_endian=0 targets, it is the position of the LSB.  For
250      gdbarch_bits_big_endian=1 targets, it is the position of the MSB.  */
251   int bitpos;
252
253   /* The number of references to this value.  When a value is created,
254      the value chain holds a reference, so REFERENCE_COUNT is 1.  If
255      release_value is called, this value is removed from the chain but
256      the caller of release_value now has a reference to this value.
257      The caller must arrange for a call to value_free later.  */
258   int reference_count;
259
260   /* Only used for bitfields; the containing value.  This allows a
261      single read from the target when displaying multiple
262      bitfields.  */
263   struct value *parent;
264
265   /* Frame register value is relative to.  This will be described in
266      the lval enum above as "lval_register".  */
267   struct frame_id frame_id;
268
269   /* Type of the value.  */
270   struct type *type;
271
272   /* If a value represents a C++ object, then the `type' field gives
273      the object's compile-time type.  If the object actually belongs
274      to some class derived from `type', perhaps with other base
275      classes and additional members, then `type' is just a subobject
276      of the real thing, and the full object is probably larger than
277      `type' would suggest.
278
279      If `type' is a dynamic class (i.e. one with a vtable), then GDB
280      can actually determine the object's run-time type by looking at
281      the run-time type information in the vtable.  When this
282      information is available, we may elect to read in the entire
283      object, for several reasons:
284
285      - When printing the value, the user would probably rather see the
286      full object, not just the limited portion apparent from the
287      compile-time type.
288
289      - If `type' has virtual base classes, then even printing `type'
290      alone may require reaching outside the `type' portion of the
291      object to wherever the virtual base class has been stored.
292
293      When we store the entire object, `enclosing_type' is the run-time
294      type -- the complete object -- and `embedded_offset' is the
295      offset of `type' within that larger type, in bytes.  The
296      value_contents() macro takes `embedded_offset' into account, so
297      most GDB code continues to see the `type' portion of the value,
298      just as the inferior would.
299
300      If `type' is a pointer to an object, then `enclosing_type' is a
301      pointer to the object's run-time type, and `pointed_to_offset' is
302      the offset in bytes from the full object to the pointed-to object
303      -- that is, the value `embedded_offset' would have if we followed
304      the pointer and fetched the complete object.  (I don't really see
305      the point.  Why not just determine the run-time type when you
306      indirect, and avoid the special case?  The contents don't matter
307      until you indirect anyway.)
308
309      If we're not doing anything fancy, `enclosing_type' is equal to
310      `type', and `embedded_offset' is zero, so everything works
311      normally.  */
312   struct type *enclosing_type;
313   int embedded_offset;
314   int pointed_to_offset;
315
316   /* Values are stored in a chain, so that they can be deleted easily
317      over calls to the inferior.  Values assigned to internal
318      variables, put into the value history or exposed to Python are
319      taken off this list.  */
320   struct value *next;
321
322   /* Register number if the value is from a register.  */
323   short regnum;
324
325   /* Actual contents of the value.  Target byte-order.  NULL or not
326      valid if lazy is nonzero.  */
327   gdb_byte *contents;
328
329   /* Unavailable ranges in CONTENTS.  We mark unavailable ranges,
330      rather than available, since the common and default case is for a
331      value to be available.  This is filled in at value read time.  */
332   VEC(range_s) *unavailable;
333 };
334
335 int
336 value_bytes_available (const struct value *value, int offset, int length)
337 {
338   gdb_assert (!value->lazy);
339
340   return !ranges_contain (value->unavailable, offset, length);
341 }
342
343 int
344 value_entirely_available (struct value *value)
345 {
346   /* We can only tell whether the whole value is available when we try
347      to read it.  */
348   if (value->lazy)
349     value_fetch_lazy (value);
350
351   if (VEC_empty (range_s, value->unavailable))
352     return 1;
353   return 0;
354 }
355
356 int
357 value_entirely_unavailable (struct value *value)
358 {
359   /* We can only tell whether the whole value is available when we try
360      to read it.  */
361   if (value->lazy)
362     value_fetch_lazy (value);
363
364   if (VEC_length (range_s, value->unavailable) == 1)
365     {
366       struct range *t = VEC_index (range_s, value->unavailable, 0);
367
368       if (t->offset == 0
369           && t->length == TYPE_LENGTH (value_enclosing_type (value)))
370         return 1;
371     }
372
373   return 0;
374 }
375
376 void
377 mark_value_bytes_unavailable (struct value *value, int offset, int length)
378 {
379   range_s newr;
380   int i;
381
382   /* Insert the range sorted.  If there's overlap or the new range
383      would be contiguous with an existing range, merge.  */
384
385   newr.offset = offset;
386   newr.length = length;
387
388   /* Do a binary search for the position the given range would be
389      inserted if we only considered the starting OFFSET of ranges.
390      Call that position I.  Since we also have LENGTH to care for
391      (this is a range afterall), we need to check if the _previous_
392      range overlaps the I range.  E.g., calling R the new range:
393
394        #1 - overlaps with previous
395
396            R
397            |-...-|
398          |---|     |---|  |------| ... |--|
399          0         1      2            N
400
401          I=1
402
403      In the case #1 above, the binary search would return `I=1',
404      meaning, this OFFSET should be inserted at position 1, and the
405      current position 1 should be pushed further (and become 2).  But,
406      note that `0' overlaps with R, so we want to merge them.
407
408      A similar consideration needs to be taken if the new range would
409      be contiguous with the previous range:
410
411        #2 - contiguous with previous
412
413             R
414             |-...-|
415          |--|       |---|  |------| ... |--|
416          0          1      2            N
417
418          I=1
419
420      If there's no overlap with the previous range, as in:
421
422        #3 - not overlapping and not contiguous
423
424                R
425                |-...-|
426           |--|         |---|  |------| ... |--|
427           0            1      2            N
428
429          I=1
430
431      or if I is 0:
432
433        #4 - R is the range with lowest offset
434
435           R
436          |-...-|
437                  |--|       |---|  |------| ... |--|
438                  0          1      2            N
439
440          I=0
441
442      ... we just push the new range to I.
443
444      All the 4 cases above need to consider that the new range may
445      also overlap several of the ranges that follow, or that R may be
446      contiguous with the following range, and merge.  E.g.,
447
448        #5 - overlapping following ranges
449
450           R
451          |------------------------|
452                  |--|       |---|  |------| ... |--|
453                  0          1      2            N
454
455          I=0
456
457        or:
458
459             R
460             |-------|
461          |--|       |---|  |------| ... |--|
462          0          1      2            N
463
464          I=1
465
466   */
467
468   i = VEC_lower_bound (range_s, value->unavailable, &newr, range_lessthan);
469   if (i > 0)
470     {
471       struct range *bef = VEC_index (range_s, value->unavailable, i - 1);
472
473       if (ranges_overlap (bef->offset, bef->length, offset, length))
474         {
475           /* #1 */
476           ULONGEST l = min (bef->offset, offset);
477           ULONGEST h = max (bef->offset + bef->length, offset + length);
478
479           bef->offset = l;
480           bef->length = h - l;
481           i--;
482         }
483       else if (offset == bef->offset + bef->length)
484         {
485           /* #2 */
486           bef->length += length;
487           i--;
488         }
489       else
490         {
491           /* #3 */
492           VEC_safe_insert (range_s, value->unavailable, i, &newr);
493         }
494     }
495   else
496     {
497       /* #4 */
498       VEC_safe_insert (range_s, value->unavailable, i, &newr);
499     }
500
501   /* Check whether the ranges following the one we've just added or
502      touched can be folded in (#5 above).  */
503   if (i + 1 < VEC_length (range_s, value->unavailable))
504     {
505       struct range *t;
506       struct range *r;
507       int removed = 0;
508       int next = i + 1;
509
510       /* Get the range we just touched.  */
511       t = VEC_index (range_s, value->unavailable, i);
512       removed = 0;
513
514       i = next;
515       for (; VEC_iterate (range_s, value->unavailable, i, r); i++)
516         if (r->offset <= t->offset + t->length)
517           {
518             ULONGEST l, h;
519
520             l = min (t->offset, r->offset);
521             h = max (t->offset + t->length, r->offset + r->length);
522
523             t->offset = l;
524             t->length = h - l;
525
526             removed++;
527           }
528         else
529           {
530             /* If we couldn't merge this one, we won't be able to
531                merge following ones either, since the ranges are
532                always sorted by OFFSET.  */
533             break;
534           }
535
536       if (removed != 0)
537         VEC_block_remove (range_s, value->unavailable, next, removed);
538     }
539 }
540
541 /* Find the first range in RANGES that overlaps the range defined by
542    OFFSET and LENGTH, starting at element POS in the RANGES vector,
543    Returns the index into RANGES where such overlapping range was
544    found, or -1 if none was found.  */
545
546 static int
547 find_first_range_overlap (VEC(range_s) *ranges, int pos,
548                           int offset, int length)
549 {
550   range_s *r;
551   int i;
552
553   for (i = pos; VEC_iterate (range_s, ranges, i, r); i++)
554     if (ranges_overlap (r->offset, r->length, offset, length))
555       return i;
556
557   return -1;
558 }
559
560 int
561 value_available_contents_eq (const struct value *val1, int offset1,
562                              const struct value *val2, int offset2,
563                              int length)
564 {
565   int idx1 = 0, idx2 = 0;
566
567   /* See function description in value.h.  */
568   gdb_assert (!val1->lazy && !val2->lazy);
569
570   while (length > 0)
571     {
572       range_s *r1, *r2;
573       ULONGEST l1, h1;
574       ULONGEST l2, h2;
575
576       idx1 = find_first_range_overlap (val1->unavailable, idx1,
577                                        offset1, length);
578       idx2 = find_first_range_overlap (val2->unavailable, idx2,
579                                        offset2, length);
580
581       /* The usual case is for both values to be completely available.  */
582       if (idx1 == -1 && idx2 == -1)
583         return (memcmp (val1->contents + offset1,
584                         val2->contents + offset2,
585                         length) == 0);
586       /* The contents only match equal if the available set matches as
587          well.  */
588       else if (idx1 == -1 || idx2 == -1)
589         return 0;
590
591       gdb_assert (idx1 != -1 && idx2 != -1);
592
593       r1 = VEC_index (range_s, val1->unavailable, idx1);
594       r2 = VEC_index (range_s, val2->unavailable, idx2);
595
596       /* Get the unavailable windows intersected by the incoming
597          ranges.  The first and last ranges that overlap the argument
598          range may be wider than said incoming arguments ranges.  */
599       l1 = max (offset1, r1->offset);
600       h1 = min (offset1 + length, r1->offset + r1->length);
601
602       l2 = max (offset2, r2->offset);
603       h2 = min (offset2 + length, r2->offset + r2->length);
604
605       /* Make them relative to the respective start offsets, so we can
606          compare them for equality.  */
607       l1 -= offset1;
608       h1 -= offset1;
609
610       l2 -= offset2;
611       h2 -= offset2;
612
613       /* Different availability, no match.  */
614       if (l1 != l2 || h1 != h2)
615         return 0;
616
617       /* Compare the _available_ contents.  */
618       if (memcmp (val1->contents + offset1,
619                   val2->contents + offset2,
620                   l1) != 0)
621         return 0;
622
623       length -= h1;
624       offset1 += h1;
625       offset2 += h1;
626     }
627
628   return 1;
629 }
630
631 /* Prototypes for local functions.  */
632
633 static void show_values (char *, int);
634
635 static void show_convenience (char *, int);
636
637
638 /* The value-history records all the values printed
639    by print commands during this session.  Each chunk
640    records 60 consecutive values.  The first chunk on
641    the chain records the most recent values.
642    The total number of values is in value_history_count.  */
643
644 #define VALUE_HISTORY_CHUNK 60
645
646 struct value_history_chunk
647   {
648     struct value_history_chunk *next;
649     struct value *values[VALUE_HISTORY_CHUNK];
650   };
651
652 /* Chain of chunks now in use.  */
653
654 static struct value_history_chunk *value_history_chain;
655
656 static int value_history_count; /* Abs number of last entry stored.  */
657
658 \f
659 /* List of all value objects currently allocated
660    (except for those released by calls to release_value)
661    This is so they can be freed after each command.  */
662
663 static struct value *all_values;
664
665 /* Allocate a lazy value for type TYPE.  Its actual content is
666    "lazily" allocated too: the content field of the return value is
667    NULL; it will be allocated when it is fetched from the target.  */
668
669 struct value *
670 allocate_value_lazy (struct type *type)
671 {
672   struct value *val;
673
674   /* Call check_typedef on our type to make sure that, if TYPE
675      is a TYPE_CODE_TYPEDEF, its length is set to the length
676      of the target type instead of zero.  However, we do not
677      replace the typedef type by the target type, because we want
678      to keep the typedef in order to be able to set the VAL's type
679      description correctly.  */
680   check_typedef (type);
681
682   val = (struct value *) xzalloc (sizeof (struct value));
683   val->contents = NULL;
684   val->next = all_values;
685   all_values = val;
686   val->type = type;
687   val->enclosing_type = type;
688   VALUE_LVAL (val) = not_lval;
689   val->location.address = 0;
690   VALUE_FRAME_ID (val) = null_frame_id;
691   val->offset = 0;
692   val->bitpos = 0;
693   val->bitsize = 0;
694   VALUE_REGNUM (val) = -1;
695   val->lazy = 1;
696   val->optimized_out = 0;
697   val->embedded_offset = 0;
698   val->pointed_to_offset = 0;
699   val->modifiable = 1;
700   val->initialized = 1;  /* Default to initialized.  */
701
702   /* Values start out on the all_values chain.  */
703   val->reference_count = 1;
704
705   return val;
706 }
707
708 /* Allocate the contents of VAL if it has not been allocated yet.  */
709
710 static void
711 allocate_value_contents (struct value *val)
712 {
713   if (!val->contents)
714     val->contents = (gdb_byte *) xzalloc (TYPE_LENGTH (val->enclosing_type));
715 }
716
717 /* Allocate a  value  and its contents for type TYPE.  */
718
719 struct value *
720 allocate_value (struct type *type)
721 {
722   struct value *val = allocate_value_lazy (type);
723
724   allocate_value_contents (val);
725   val->lazy = 0;
726   return val;
727 }
728
729 /* Allocate a  value  that has the correct length
730    for COUNT repetitions of type TYPE.  */
731
732 struct value *
733 allocate_repeat_value (struct type *type, int count)
734 {
735   int low_bound = current_language->string_lower_bound;         /* ??? */
736   /* FIXME-type-allocation: need a way to free this type when we are
737      done with it.  */
738   struct type *array_type
739     = lookup_array_range_type (type, low_bound, count + low_bound - 1);
740
741   return allocate_value (array_type);
742 }
743
744 struct value *
745 allocate_computed_value (struct type *type,
746                          const struct lval_funcs *funcs,
747                          void *closure)
748 {
749   struct value *v = allocate_value_lazy (type);
750
751   VALUE_LVAL (v) = lval_computed;
752   v->location.computed.funcs = funcs;
753   v->location.computed.closure = closure;
754
755   return v;
756 }
757
758 /* Allocate NOT_LVAL value for type TYPE being OPTIMIZED_OUT.  */
759
760 struct value *
761 allocate_optimized_out_value (struct type *type)
762 {
763   struct value *retval = allocate_value_lazy (type);
764
765   set_value_optimized_out (retval, 1);
766
767   return retval;
768 }
769
770 /* Accessor methods.  */
771
772 struct value *
773 value_next (struct value *value)
774 {
775   return value->next;
776 }
777
778 struct type *
779 value_type (const struct value *value)
780 {
781   return value->type;
782 }
783 void
784 deprecated_set_value_type (struct value *value, struct type *type)
785 {
786   value->type = type;
787 }
788
789 int
790 value_offset (const struct value *value)
791 {
792   return value->offset;
793 }
794 void
795 set_value_offset (struct value *value, int offset)
796 {
797   value->offset = offset;
798 }
799
800 int
801 value_bitpos (const struct value *value)
802 {
803   return value->bitpos;
804 }
805 void
806 set_value_bitpos (struct value *value, int bit)
807 {
808   value->bitpos = bit;
809 }
810
811 int
812 value_bitsize (const struct value *value)
813 {
814   return value->bitsize;
815 }
816 void
817 set_value_bitsize (struct value *value, int bit)
818 {
819   value->bitsize = bit;
820 }
821
822 struct value *
823 value_parent (struct value *value)
824 {
825   return value->parent;
826 }
827
828 /* See value.h.  */
829
830 void
831 set_value_parent (struct value *value, struct value *parent)
832 {
833   struct value *old = value->parent;
834
835   value->parent = parent;
836   if (parent != NULL)
837     value_incref (parent);
838   value_free (old);
839 }
840
841 gdb_byte *
842 value_contents_raw (struct value *value)
843 {
844   allocate_value_contents (value);
845   return value->contents + value->embedded_offset;
846 }
847
848 gdb_byte *
849 value_contents_all_raw (struct value *value)
850 {
851   allocate_value_contents (value);
852   return value->contents;
853 }
854
855 struct type *
856 value_enclosing_type (struct value *value)
857 {
858   return value->enclosing_type;
859 }
860
861 /* Look at value.h for description.  */
862
863 struct type *
864 value_actual_type (struct value *value, int resolve_simple_types,
865                    int *real_type_found)
866 {
867   struct value_print_options opts;
868   struct type *result;
869
870   get_user_print_options (&opts);
871
872   if (real_type_found)
873     *real_type_found = 0;
874   result = value_type (value);
875   if (opts.objectprint)
876     {
877       /* If result's target type is TYPE_CODE_STRUCT, proceed to
878          fetch its rtti type.  */
879       if ((TYPE_CODE (result) == TYPE_CODE_PTR
880           || TYPE_CODE (result) == TYPE_CODE_REF)
881           && TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (result)))
882              == TYPE_CODE_STRUCT)
883         {
884           struct type *real_type;
885
886           real_type = value_rtti_indirect_type (value, NULL, NULL, NULL);
887           if (real_type)
888             {
889               if (real_type_found)
890                 *real_type_found = 1;
891               result = real_type;
892             }
893         }
894       else if (resolve_simple_types)
895         {
896           if (real_type_found)
897             *real_type_found = 1;
898           result = value_enclosing_type (value);
899         }
900     }
901
902   return result;
903 }
904
905 static void
906 require_not_optimized_out (const struct value *value)
907 {
908   if (value->optimized_out)
909     error (_("value has been optimized out"));
910 }
911
912 static void
913 require_available (const struct value *value)
914 {
915   if (!VEC_empty (range_s, value->unavailable))
916     throw_error (NOT_AVAILABLE_ERROR, _("value is not available"));
917 }
918
919 const gdb_byte *
920 value_contents_for_printing (struct value *value)
921 {
922   if (value->lazy)
923     value_fetch_lazy (value);
924   return value->contents;
925 }
926
927 const gdb_byte *
928 value_contents_for_printing_const (const struct value *value)
929 {
930   gdb_assert (!value->lazy);
931   return value->contents;
932 }
933
934 const gdb_byte *
935 value_contents_all (struct value *value)
936 {
937   const gdb_byte *result = value_contents_for_printing (value);
938   require_not_optimized_out (value);
939   require_available (value);
940   return result;
941 }
942
943 /* Copy LENGTH bytes of SRC value's (all) contents
944    (value_contents_all) starting at SRC_OFFSET, into DST value's (all)
945    contents, starting at DST_OFFSET.  If unavailable contents are
946    being copied from SRC, the corresponding DST contents are marked
947    unavailable accordingly.  Neither DST nor SRC may be lazy
948    values.
949
950    It is assumed the contents of DST in the [DST_OFFSET,
951    DST_OFFSET+LENGTH) range are wholly available.  */
952
953 void
954 value_contents_copy_raw (struct value *dst, int dst_offset,
955                          struct value *src, int src_offset, int length)
956 {
957   range_s *r;
958   int i;
959
960   /* A lazy DST would make that this copy operation useless, since as
961      soon as DST's contents were un-lazied (by a later value_contents
962      call, say), the contents would be overwritten.  A lazy SRC would
963      mean we'd be copying garbage.  */
964   gdb_assert (!dst->lazy && !src->lazy);
965
966   /* The overwritten DST range gets unavailability ORed in, not
967      replaced.  Make sure to remember to implement replacing if it
968      turns out actually necessary.  */
969   gdb_assert (value_bytes_available (dst, dst_offset, length));
970
971   /* Copy the data.  */
972   memcpy (value_contents_all_raw (dst) + dst_offset,
973           value_contents_all_raw (src) + src_offset,
974           length);
975
976   /* Copy the meta-data, adjusted.  */
977   for (i = 0; VEC_iterate (range_s, src->unavailable, i, r); i++)
978     {
979       ULONGEST h, l;
980
981       l = max (r->offset, src_offset);
982       h = min (r->offset + r->length, src_offset + length);
983
984       if (l < h)
985         mark_value_bytes_unavailable (dst,
986                                       dst_offset + (l - src_offset),
987                                       h - l);
988     }
989 }
990
991 /* Copy LENGTH bytes of SRC value's (all) contents
992    (value_contents_all) starting at SRC_OFFSET byte, into DST value's
993    (all) contents, starting at DST_OFFSET.  If unavailable contents
994    are being copied from SRC, the corresponding DST contents are
995    marked unavailable accordingly.  DST must not be lazy.  If SRC is
996    lazy, it will be fetched now.  If SRC is not valid (is optimized
997    out), an error is thrown.
998
999    It is assumed the contents of DST in the [DST_OFFSET,
1000    DST_OFFSET+LENGTH) range are wholly available.  */
1001
1002 void
1003 value_contents_copy (struct value *dst, int dst_offset,
1004                      struct value *src, int src_offset, int length)
1005 {
1006   require_not_optimized_out (src);
1007
1008   if (src->lazy)
1009     value_fetch_lazy (src);
1010
1011   value_contents_copy_raw (dst, dst_offset, src, src_offset, length);
1012 }
1013
1014 int
1015 value_lazy (struct value *value)
1016 {
1017   return value->lazy;
1018 }
1019
1020 void
1021 set_value_lazy (struct value *value, int val)
1022 {
1023   value->lazy = val;
1024 }
1025
1026 int
1027 value_stack (struct value *value)
1028 {
1029   return value->stack;
1030 }
1031
1032 void
1033 set_value_stack (struct value *value, int val)
1034 {
1035   value->stack = val;
1036 }
1037
1038 const gdb_byte *
1039 value_contents (struct value *value)
1040 {
1041   const gdb_byte *result = value_contents_writeable (value);
1042   require_not_optimized_out (value);
1043   require_available (value);
1044   return result;
1045 }
1046
1047 gdb_byte *
1048 value_contents_writeable (struct value *value)
1049 {
1050   if (value->lazy)
1051     value_fetch_lazy (value);
1052   return value_contents_raw (value);
1053 }
1054
1055 /* Return non-zero if VAL1 and VAL2 have the same contents.  Note that
1056    this function is different from value_equal; in C the operator ==
1057    can return 0 even if the two values being compared are equal.  */
1058
1059 int
1060 value_contents_equal (struct value *val1, struct value *val2)
1061 {
1062   struct type *type1;
1063   struct type *type2;
1064
1065   type1 = check_typedef (value_type (val1));
1066   type2 = check_typedef (value_type (val2));
1067   if (TYPE_LENGTH (type1) != TYPE_LENGTH (type2))
1068     return 0;
1069
1070   return (memcmp (value_contents (val1), value_contents (val2),
1071                   TYPE_LENGTH (type1)) == 0);
1072 }
1073
1074 int
1075 value_optimized_out (struct value *value)
1076 {
1077   /* We can only know if a value is optimized out once we have tried to
1078      fetch it.  */
1079   if (!value->optimized_out && value->lazy)
1080     value_fetch_lazy (value);
1081
1082   return value->optimized_out;
1083 }
1084
1085 int
1086 value_optimized_out_const (const struct value *value)
1087 {
1088   return value->optimized_out;
1089 }
1090
1091 void
1092 set_value_optimized_out (struct value *value, int val)
1093 {
1094   value->optimized_out = val;
1095 }
1096
1097 int
1098 value_entirely_optimized_out (const struct value *value)
1099 {
1100   if (!value->optimized_out)
1101     return 0;
1102   if (value->lval != lval_computed
1103       || !value->location.computed.funcs->check_any_valid)
1104     return 1;
1105   return !value->location.computed.funcs->check_any_valid (value);
1106 }
1107
1108 int
1109 value_bits_valid (const struct value *value, int offset, int length)
1110 {
1111   if (!value->optimized_out)
1112     return 1;
1113   if (value->lval != lval_computed
1114       || !value->location.computed.funcs->check_validity)
1115     return 0;
1116   return value->location.computed.funcs->check_validity (value, offset,
1117                                                          length);
1118 }
1119
1120 int
1121 value_bits_synthetic_pointer (const struct value *value,
1122                               int offset, int length)
1123 {
1124   if (value->lval != lval_computed
1125       || !value->location.computed.funcs->check_synthetic_pointer)
1126     return 0;
1127   return value->location.computed.funcs->check_synthetic_pointer (value,
1128                                                                   offset,
1129                                                                   length);
1130 }
1131
1132 int
1133 value_embedded_offset (struct value *value)
1134 {
1135   return value->embedded_offset;
1136 }
1137
1138 void
1139 set_value_embedded_offset (struct value *value, int val)
1140 {
1141   value->embedded_offset = val;
1142 }
1143
1144 int
1145 value_pointed_to_offset (struct value *value)
1146 {
1147   return value->pointed_to_offset;
1148 }
1149
1150 void
1151 set_value_pointed_to_offset (struct value *value, int val)
1152 {
1153   value->pointed_to_offset = val;
1154 }
1155
1156 const struct lval_funcs *
1157 value_computed_funcs (const struct value *v)
1158 {
1159   gdb_assert (value_lval_const (v) == lval_computed);
1160
1161   return v->location.computed.funcs;
1162 }
1163
1164 void *
1165 value_computed_closure (const struct value *v)
1166 {
1167   gdb_assert (v->lval == lval_computed);
1168
1169   return v->location.computed.closure;
1170 }
1171
1172 enum lval_type *
1173 deprecated_value_lval_hack (struct value *value)
1174 {
1175   return &value->lval;
1176 }
1177
1178 enum lval_type
1179 value_lval_const (const struct value *value)
1180 {
1181   return value->lval;
1182 }
1183
1184 CORE_ADDR
1185 value_address (const struct value *value)
1186 {
1187   if (value->lval == lval_internalvar
1188       || value->lval == lval_internalvar_component)
1189     return 0;
1190   if (value->parent != NULL)
1191     return value_address (value->parent) + value->offset;
1192   else
1193     return value->location.address + value->offset;
1194 }
1195
1196 CORE_ADDR
1197 value_raw_address (struct value *value)
1198 {
1199   if (value->lval == lval_internalvar
1200       || value->lval == lval_internalvar_component)
1201     return 0;
1202   return value->location.address;
1203 }
1204
1205 void
1206 set_value_address (struct value *value, CORE_ADDR addr)
1207 {
1208   gdb_assert (value->lval != lval_internalvar
1209               && value->lval != lval_internalvar_component);
1210   value->location.address = addr;
1211 }
1212
1213 struct internalvar **
1214 deprecated_value_internalvar_hack (struct value *value)
1215 {
1216   return &value->location.internalvar;
1217 }
1218
1219 struct frame_id *
1220 deprecated_value_frame_id_hack (struct value *value)
1221 {
1222   return &value->frame_id;
1223 }
1224
1225 short *
1226 deprecated_value_regnum_hack (struct value *value)
1227 {
1228   return &value->regnum;
1229 }
1230
1231 int
1232 deprecated_value_modifiable (struct value *value)
1233 {
1234   return value->modifiable;
1235 }
1236 \f
1237 /* Return a mark in the value chain.  All values allocated after the
1238    mark is obtained (except for those released) are subject to being freed
1239    if a subsequent value_free_to_mark is passed the mark.  */
1240 struct value *
1241 value_mark (void)
1242 {
1243   return all_values;
1244 }
1245
1246 /* Take a reference to VAL.  VAL will not be deallocated until all
1247    references are released.  */
1248
1249 void
1250 value_incref (struct value *val)
1251 {
1252   val->reference_count++;
1253 }
1254
1255 /* Release a reference to VAL, which was acquired with value_incref.
1256    This function is also called to deallocate values from the value
1257    chain.  */
1258
1259 void
1260 value_free (struct value *val)
1261 {
1262   if (val)
1263     {
1264       gdb_assert (val->reference_count > 0);
1265       val->reference_count--;
1266       if (val->reference_count > 0)
1267         return;
1268
1269       /* If there's an associated parent value, drop our reference to
1270          it.  */
1271       if (val->parent != NULL)
1272         value_free (val->parent);
1273
1274       if (VALUE_LVAL (val) == lval_computed)
1275         {
1276           const struct lval_funcs *funcs = val->location.computed.funcs;
1277
1278           if (funcs->free_closure)
1279             funcs->free_closure (val);
1280         }
1281
1282       xfree (val->contents);
1283       VEC_free (range_s, val->unavailable);
1284     }
1285   xfree (val);
1286 }
1287
1288 /* Free all values allocated since MARK was obtained by value_mark
1289    (except for those released).  */
1290 void
1291 value_free_to_mark (struct value *mark)
1292 {
1293   struct value *val;
1294   struct value *next;
1295
1296   for (val = all_values; val && val != mark; val = next)
1297     {
1298       next = val->next;
1299       val->released = 1;
1300       value_free (val);
1301     }
1302   all_values = val;
1303 }
1304
1305 /* Free all the values that have been allocated (except for those released).
1306    Call after each command, successful or not.
1307    In practice this is called before each command, which is sufficient.  */
1308
1309 void
1310 free_all_values (void)
1311 {
1312   struct value *val;
1313   struct value *next;
1314
1315   for (val = all_values; val; val = next)
1316     {
1317       next = val->next;
1318       val->released = 1;
1319       value_free (val);
1320     }
1321
1322   all_values = 0;
1323 }
1324
1325 /* Frees all the elements in a chain of values.  */
1326
1327 void
1328 free_value_chain (struct value *v)
1329 {
1330   struct value *next;
1331
1332   for (; v; v = next)
1333     {
1334       next = value_next (v);
1335       value_free (v);
1336     }
1337 }
1338
1339 /* Remove VAL from the chain all_values
1340    so it will not be freed automatically.  */
1341
1342 void
1343 release_value (struct value *val)
1344 {
1345   struct value *v;
1346
1347   if (all_values == val)
1348     {
1349       all_values = val->next;
1350       val->next = NULL;
1351       val->released = 1;
1352       return;
1353     }
1354
1355   for (v = all_values; v; v = v->next)
1356     {
1357       if (v->next == val)
1358         {
1359           v->next = val->next;
1360           val->next = NULL;
1361           val->released = 1;
1362           break;
1363         }
1364     }
1365 }
1366
1367 /* If the value is not already released, release it.
1368    If the value is already released, increment its reference count.
1369    That is, this function ensures that the value is released from the
1370    value chain and that the caller owns a reference to it.  */
1371
1372 void
1373 release_value_or_incref (struct value *val)
1374 {
1375   if (val->released)
1376     value_incref (val);
1377   else
1378     release_value (val);
1379 }
1380
1381 /* Release all values up to mark  */
1382 struct value *
1383 value_release_to_mark (struct value *mark)
1384 {
1385   struct value *val;
1386   struct value *next;
1387
1388   for (val = next = all_values; next; next = next->next)
1389     {
1390       if (next->next == mark)
1391         {
1392           all_values = next->next;
1393           next->next = NULL;
1394           return val;
1395         }
1396       next->released = 1;
1397     }
1398   all_values = 0;
1399   return val;
1400 }
1401
1402 /* Return a copy of the value ARG.
1403    It contains the same contents, for same memory address,
1404    but it's a different block of storage.  */
1405
1406 struct value *
1407 value_copy (struct value *arg)
1408 {
1409   struct type *encl_type = value_enclosing_type (arg);
1410   struct value *val;
1411
1412   if (value_lazy (arg))
1413     val = allocate_value_lazy (encl_type);
1414   else
1415     val = allocate_value (encl_type);
1416   val->type = arg->type;
1417   VALUE_LVAL (val) = VALUE_LVAL (arg);
1418   val->location = arg->location;
1419   val->offset = arg->offset;
1420   val->bitpos = arg->bitpos;
1421   val->bitsize = arg->bitsize;
1422   VALUE_FRAME_ID (val) = VALUE_FRAME_ID (arg);
1423   VALUE_REGNUM (val) = VALUE_REGNUM (arg);
1424   val->lazy = arg->lazy;
1425   val->optimized_out = arg->optimized_out;
1426   val->embedded_offset = value_embedded_offset (arg);
1427   val->pointed_to_offset = arg->pointed_to_offset;
1428   val->modifiable = arg->modifiable;
1429   if (!value_lazy (val))
1430     {
1431       memcpy (value_contents_all_raw (val), value_contents_all_raw (arg),
1432               TYPE_LENGTH (value_enclosing_type (arg)));
1433
1434     }
1435   val->unavailable = VEC_copy (range_s, arg->unavailable);
1436   set_value_parent (val, arg->parent);
1437   if (VALUE_LVAL (val) == lval_computed)
1438     {
1439       const struct lval_funcs *funcs = val->location.computed.funcs;
1440
1441       if (funcs->copy_closure)
1442         val->location.computed.closure = funcs->copy_closure (val);
1443     }
1444   return val;
1445 }
1446
1447 /* Return a version of ARG that is non-lvalue.  */
1448
1449 struct value *
1450 value_non_lval (struct value *arg)
1451 {
1452   if (VALUE_LVAL (arg) != not_lval)
1453     {
1454       struct type *enc_type = value_enclosing_type (arg);
1455       struct value *val = allocate_value (enc_type);
1456
1457       memcpy (value_contents_all_raw (val), value_contents_all (arg),
1458               TYPE_LENGTH (enc_type));
1459       val->type = arg->type;
1460       set_value_embedded_offset (val, value_embedded_offset (arg));
1461       set_value_pointed_to_offset (val, value_pointed_to_offset (arg));
1462       return val;
1463     }
1464    return arg;
1465 }
1466
1467 void
1468 set_value_component_location (struct value *component,
1469                               const struct value *whole)
1470 {
1471   if (whole->lval == lval_internalvar)
1472     VALUE_LVAL (component) = lval_internalvar_component;
1473   else
1474     VALUE_LVAL (component) = whole->lval;
1475
1476   component->location = whole->location;
1477   if (whole->lval == lval_computed)
1478     {
1479       const struct lval_funcs *funcs = whole->location.computed.funcs;
1480
1481       if (funcs->copy_closure)
1482         component->location.computed.closure = funcs->copy_closure (whole);
1483     }
1484 }
1485
1486 \f
1487 /* Access to the value history.  */
1488
1489 /* Record a new value in the value history.
1490    Returns the absolute history index of the entry.
1491    Result of -1 indicates the value was not saved; otherwise it is the
1492    value history index of this new item.  */
1493
1494 int
1495 record_latest_value (struct value *val)
1496 {
1497   int i;
1498
1499   /* We don't want this value to have anything to do with the inferior anymore.
1500      In particular, "set $1 = 50" should not affect the variable from which
1501      the value was taken, and fast watchpoints should be able to assume that
1502      a value on the value history never changes.  */
1503   if (value_lazy (val))
1504     value_fetch_lazy (val);
1505   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
1506      from.  This is a bit dubious, because then *&$1 does not just return $1
1507      but the current contents of that location.  c'est la vie...  */
1508   val->modifiable = 0;
1509   release_value (val);
1510
1511   /* Here we treat value_history_count as origin-zero
1512      and applying to the value being stored now.  */
1513
1514   i = value_history_count % VALUE_HISTORY_CHUNK;
1515   if (i == 0)
1516     {
1517       struct value_history_chunk *new
1518         = (struct value_history_chunk *)
1519
1520       xmalloc (sizeof (struct value_history_chunk));
1521       memset (new->values, 0, sizeof new->values);
1522       new->next = value_history_chain;
1523       value_history_chain = new;
1524     }
1525
1526   value_history_chain->values[i] = val;
1527
1528   /* Now we regard value_history_count as origin-one
1529      and applying to the value just stored.  */
1530
1531   return ++value_history_count;
1532 }
1533
1534 /* Return a copy of the value in the history with sequence number NUM.  */
1535
1536 struct value *
1537 access_value_history (int num)
1538 {
1539   struct value_history_chunk *chunk;
1540   int i;
1541   int absnum = num;
1542
1543   if (absnum <= 0)
1544     absnum += value_history_count;
1545
1546   if (absnum <= 0)
1547     {
1548       if (num == 0)
1549         error (_("The history is empty."));
1550       else if (num == 1)
1551         error (_("There is only one value in the history."));
1552       else
1553         error (_("History does not go back to $$%d."), -num);
1554     }
1555   if (absnum > value_history_count)
1556     error (_("History has not yet reached $%d."), absnum);
1557
1558   absnum--;
1559
1560   /* Now absnum is always absolute and origin zero.  */
1561
1562   chunk = value_history_chain;
1563   for (i = (value_history_count - 1) / VALUE_HISTORY_CHUNK
1564          - absnum / VALUE_HISTORY_CHUNK;
1565        i > 0; i--)
1566     chunk = chunk->next;
1567
1568   return value_copy (chunk->values[absnum % VALUE_HISTORY_CHUNK]);
1569 }
1570
1571 static void
1572 show_values (char *num_exp, int from_tty)
1573 {
1574   int i;
1575   struct value *val;
1576   static int num = 1;
1577
1578   if (num_exp)
1579     {
1580       /* "show values +" should print from the stored position.
1581          "show values <exp>" should print around value number <exp>.  */
1582       if (num_exp[0] != '+' || num_exp[1] != '\0')
1583         num = parse_and_eval_long (num_exp) - 5;
1584     }
1585   else
1586     {
1587       /* "show values" means print the last 10 values.  */
1588       num = value_history_count - 9;
1589     }
1590
1591   if (num <= 0)
1592     num = 1;
1593
1594   for (i = num; i < num + 10 && i <= value_history_count; i++)
1595     {
1596       struct value_print_options opts;
1597
1598       val = access_value_history (i);
1599       printf_filtered (("$%d = "), i);
1600       get_user_print_options (&opts);
1601       value_print (val, gdb_stdout, &opts);
1602       printf_filtered (("\n"));
1603     }
1604
1605   /* The next "show values +" should start after what we just printed.  */
1606   num += 10;
1607
1608   /* Hitting just return after this command should do the same thing as
1609      "show values +".  If num_exp is null, this is unnecessary, since
1610      "show values +" is not useful after "show values".  */
1611   if (from_tty && num_exp)
1612     {
1613       num_exp[0] = '+';
1614       num_exp[1] = '\0';
1615     }
1616 }
1617 \f
1618 /* Internal variables.  These are variables within the debugger
1619    that hold values assigned by debugger commands.
1620    The user refers to them with a '$' prefix
1621    that does not appear in the variable names stored internally.  */
1622
1623 struct internalvar
1624 {
1625   struct internalvar *next;
1626   char *name;
1627
1628   /* We support various different kinds of content of an internal variable.
1629      enum internalvar_kind specifies the kind, and union internalvar_data
1630      provides the data associated with this particular kind.  */
1631
1632   enum internalvar_kind
1633     {
1634       /* The internal variable is empty.  */
1635       INTERNALVAR_VOID,
1636
1637       /* The value of the internal variable is provided directly as
1638          a GDB value object.  */
1639       INTERNALVAR_VALUE,
1640
1641       /* A fresh value is computed via a call-back routine on every
1642          access to the internal variable.  */
1643       INTERNALVAR_MAKE_VALUE,
1644
1645       /* The internal variable holds a GDB internal convenience function.  */
1646       INTERNALVAR_FUNCTION,
1647
1648       /* The variable holds an integer value.  */
1649       INTERNALVAR_INTEGER,
1650
1651       /* The variable holds a GDB-provided string.  */
1652       INTERNALVAR_STRING,
1653
1654     } kind;
1655
1656   union internalvar_data
1657     {
1658       /* A value object used with INTERNALVAR_VALUE.  */
1659       struct value *value;
1660
1661       /* The call-back routine used with INTERNALVAR_MAKE_VALUE.  */
1662       struct
1663         {
1664           /* The functions to call.  */
1665           const struct internalvar_funcs *functions;
1666
1667           /* The function's user-data.  */
1668           void *data;
1669         } make_value;
1670
1671       /* The internal function used with INTERNALVAR_FUNCTION.  */
1672       struct
1673         {
1674           struct internal_function *function;
1675           /* True if this is the canonical name for the function.  */
1676           int canonical;
1677         } fn;
1678
1679       /* An integer value used with INTERNALVAR_INTEGER.  */
1680       struct
1681         {
1682           /* If type is non-NULL, it will be used as the type to generate
1683              a value for this internal variable.  If type is NULL, a default
1684              integer type for the architecture is used.  */
1685           struct type *type;
1686           LONGEST val;
1687         } integer;
1688
1689       /* A string value used with INTERNALVAR_STRING.  */
1690       char *string;
1691     } u;
1692 };
1693
1694 static struct internalvar *internalvars;
1695
1696 /* If the variable does not already exist create it and give it the
1697    value given.  If no value is given then the default is zero.  */
1698 static void
1699 init_if_undefined_command (char* args, int from_tty)
1700 {
1701   struct internalvar* intvar;
1702
1703   /* Parse the expression - this is taken from set_command().  */
1704   struct expression *expr = parse_expression (args);
1705   register struct cleanup *old_chain =
1706     make_cleanup (free_current_contents, &expr);
1707
1708   /* Validate the expression.
1709      Was the expression an assignment?
1710      Or even an expression at all?  */
1711   if (expr->nelts == 0 || expr->elts[0].opcode != BINOP_ASSIGN)
1712     error (_("Init-if-undefined requires an assignment expression."));
1713
1714   /* Extract the variable from the parsed expression.
1715      In the case of an assign the lvalue will be in elts[1] and elts[2].  */
1716   if (expr->elts[1].opcode != OP_INTERNALVAR)
1717     error (_("The first parameter to init-if-undefined "
1718              "should be a GDB variable."));
1719   intvar = expr->elts[2].internalvar;
1720
1721   /* Only evaluate the expression if the lvalue is void.
1722      This may still fail if the expresssion is invalid.  */
1723   if (intvar->kind == INTERNALVAR_VOID)
1724     evaluate_expression (expr);
1725
1726   do_cleanups (old_chain);
1727 }
1728
1729
1730 /* Look up an internal variable with name NAME.  NAME should not
1731    normally include a dollar sign.
1732
1733    If the specified internal variable does not exist,
1734    the return value is NULL.  */
1735
1736 struct internalvar *
1737 lookup_only_internalvar (const char *name)
1738 {
1739   struct internalvar *var;
1740
1741   for (var = internalvars; var; var = var->next)
1742     if (strcmp (var->name, name) == 0)
1743       return var;
1744
1745   return NULL;
1746 }
1747
1748 /* Complete NAME by comparing it to the names of internal variables.
1749    Returns a vector of newly allocated strings, or NULL if no matches
1750    were found.  */
1751
1752 VEC (char_ptr) *
1753 complete_internalvar (const char *name)
1754 {
1755   VEC (char_ptr) *result = NULL;
1756   struct internalvar *var;
1757   int len;
1758
1759   len = strlen (name);
1760
1761   for (var = internalvars; var; var = var->next)
1762     if (strncmp (var->name, name, len) == 0)
1763       {
1764         char *r = xstrdup (var->name);
1765
1766         VEC_safe_push (char_ptr, result, r);
1767       }
1768
1769   return result;
1770 }
1771
1772 /* Create an internal variable with name NAME and with a void value.
1773    NAME should not normally include a dollar sign.  */
1774
1775 struct internalvar *
1776 create_internalvar (const char *name)
1777 {
1778   struct internalvar *var;
1779
1780   var = (struct internalvar *) xmalloc (sizeof (struct internalvar));
1781   var->name = concat (name, (char *)NULL);
1782   var->kind = INTERNALVAR_VOID;
1783   var->next = internalvars;
1784   internalvars = var;
1785   return var;
1786 }
1787
1788 /* Create an internal variable with name NAME and register FUN as the
1789    function that value_of_internalvar uses to create a value whenever
1790    this variable is referenced.  NAME should not normally include a
1791    dollar sign.  DATA is passed uninterpreted to FUN when it is
1792    called.  CLEANUP, if not NULL, is called when the internal variable
1793    is destroyed.  It is passed DATA as its only argument.  */
1794
1795 struct internalvar *
1796 create_internalvar_type_lazy (const char *name,
1797                               const struct internalvar_funcs *funcs,
1798                               void *data)
1799 {
1800   struct internalvar *var = create_internalvar (name);
1801
1802   var->kind = INTERNALVAR_MAKE_VALUE;
1803   var->u.make_value.functions = funcs;
1804   var->u.make_value.data = data;
1805   return var;
1806 }
1807
1808 /* See documentation in value.h.  */
1809
1810 int
1811 compile_internalvar_to_ax (struct internalvar *var,
1812                            struct agent_expr *expr,
1813                            struct axs_value *value)
1814 {
1815   if (var->kind != INTERNALVAR_MAKE_VALUE
1816       || var->u.make_value.functions->compile_to_ax == NULL)
1817     return 0;
1818
1819   var->u.make_value.functions->compile_to_ax (var, expr, value,
1820                                               var->u.make_value.data);
1821   return 1;
1822 }
1823
1824 /* Look up an internal variable with name NAME.  NAME should not
1825    normally include a dollar sign.
1826
1827    If the specified internal variable does not exist,
1828    one is created, with a void value.  */
1829
1830 struct internalvar *
1831 lookup_internalvar (const char *name)
1832 {
1833   struct internalvar *var;
1834
1835   var = lookup_only_internalvar (name);
1836   if (var)
1837     return var;
1838
1839   return create_internalvar (name);
1840 }
1841
1842 /* Return current value of internal variable VAR.  For variables that
1843    are not inherently typed, use a value type appropriate for GDBARCH.  */
1844
1845 struct value *
1846 value_of_internalvar (struct gdbarch *gdbarch, struct internalvar *var)
1847 {
1848   struct value *val;
1849   struct trace_state_variable *tsv;
1850
1851   /* If there is a trace state variable of the same name, assume that
1852      is what we really want to see.  */
1853   tsv = find_trace_state_variable (var->name);
1854   if (tsv)
1855     {
1856       tsv->value_known = target_get_trace_state_variable_value (tsv->number,
1857                                                                 &(tsv->value));
1858       if (tsv->value_known)
1859         val = value_from_longest (builtin_type (gdbarch)->builtin_int64,
1860                                   tsv->value);
1861       else
1862         val = allocate_value (builtin_type (gdbarch)->builtin_void);
1863       return val;
1864     }
1865
1866   switch (var->kind)
1867     {
1868     case INTERNALVAR_VOID:
1869       val = allocate_value (builtin_type (gdbarch)->builtin_void);
1870       break;
1871
1872     case INTERNALVAR_FUNCTION:
1873       val = allocate_value (builtin_type (gdbarch)->internal_fn);
1874       break;
1875
1876     case INTERNALVAR_INTEGER:
1877       if (!var->u.integer.type)
1878         val = value_from_longest (builtin_type (gdbarch)->builtin_int,
1879                                   var->u.integer.val);
1880       else
1881         val = value_from_longest (var->u.integer.type, var->u.integer.val);
1882       break;
1883
1884     case INTERNALVAR_STRING:
1885       val = value_cstring (var->u.string, strlen (var->u.string),
1886                            builtin_type (gdbarch)->builtin_char);
1887       break;
1888
1889     case INTERNALVAR_VALUE:
1890       val = value_copy (var->u.value);
1891       if (value_lazy (val))
1892         value_fetch_lazy (val);
1893       break;
1894
1895     case INTERNALVAR_MAKE_VALUE:
1896       val = (*var->u.make_value.functions->make_value) (gdbarch, var,
1897                                                         var->u.make_value.data);
1898       break;
1899
1900     default:
1901       internal_error (__FILE__, __LINE__, _("bad kind"));
1902     }
1903
1904   /* Change the VALUE_LVAL to lval_internalvar so that future operations
1905      on this value go back to affect the original internal variable.
1906
1907      Do not do this for INTERNALVAR_MAKE_VALUE variables, as those have
1908      no underlying modifyable state in the internal variable.
1909
1910      Likewise, if the variable's value is a computed lvalue, we want
1911      references to it to produce another computed lvalue, where
1912      references and assignments actually operate through the
1913      computed value's functions.
1914
1915      This means that internal variables with computed values
1916      behave a little differently from other internal variables:
1917      assignments to them don't just replace the previous value
1918      altogether.  At the moment, this seems like the behavior we
1919      want.  */
1920
1921   if (var->kind != INTERNALVAR_MAKE_VALUE
1922       && val->lval != lval_computed)
1923     {
1924       VALUE_LVAL (val) = lval_internalvar;
1925       VALUE_INTERNALVAR (val) = var;
1926     }
1927
1928   return val;
1929 }
1930
1931 int
1932 get_internalvar_integer (struct internalvar *var, LONGEST *result)
1933 {
1934   if (var->kind == INTERNALVAR_INTEGER)
1935     {
1936       *result = var->u.integer.val;
1937       return 1;
1938     }
1939
1940   if (var->kind == INTERNALVAR_VALUE)
1941     {
1942       struct type *type = check_typedef (value_type (var->u.value));
1943
1944       if (TYPE_CODE (type) == TYPE_CODE_INT)
1945         {
1946           *result = value_as_long (var->u.value);
1947           return 1;
1948         }
1949     }
1950
1951   return 0;
1952 }
1953
1954 static int
1955 get_internalvar_function (struct internalvar *var,
1956                           struct internal_function **result)
1957 {
1958   switch (var->kind)
1959     {
1960     case INTERNALVAR_FUNCTION:
1961       *result = var->u.fn.function;
1962       return 1;
1963
1964     default:
1965       return 0;
1966     }
1967 }
1968
1969 void
1970 set_internalvar_component (struct internalvar *var, int offset, int bitpos,
1971                            int bitsize, struct value *newval)
1972 {
1973   gdb_byte *addr;
1974
1975   switch (var->kind)
1976     {
1977     case INTERNALVAR_VALUE:
1978       addr = value_contents_writeable (var->u.value);
1979
1980       if (bitsize)
1981         modify_field (value_type (var->u.value), addr + offset,
1982                       value_as_long (newval), bitpos, bitsize);
1983       else
1984         memcpy (addr + offset, value_contents (newval),
1985                 TYPE_LENGTH (value_type (newval)));
1986       break;
1987
1988     default:
1989       /* We can never get a component of any other kind.  */
1990       internal_error (__FILE__, __LINE__, _("set_internalvar_component"));
1991     }
1992 }
1993
1994 void
1995 set_internalvar (struct internalvar *var, struct value *val)
1996 {
1997   enum internalvar_kind new_kind;
1998   union internalvar_data new_data = { 0 };
1999
2000   if (var->kind == INTERNALVAR_FUNCTION && var->u.fn.canonical)
2001     error (_("Cannot overwrite convenience function %s"), var->name);
2002
2003   /* Prepare new contents.  */
2004   switch (TYPE_CODE (check_typedef (value_type (val))))
2005     {
2006     case TYPE_CODE_VOID:
2007       new_kind = INTERNALVAR_VOID;
2008       break;
2009
2010     case TYPE_CODE_INTERNAL_FUNCTION:
2011       gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2012       new_kind = INTERNALVAR_FUNCTION;
2013       get_internalvar_function (VALUE_INTERNALVAR (val),
2014                                 &new_data.fn.function);
2015       /* Copies created here are never canonical.  */
2016       break;
2017
2018     default:
2019       new_kind = INTERNALVAR_VALUE;
2020       new_data.value = value_copy (val);
2021       new_data.value->modifiable = 1;
2022
2023       /* Force the value to be fetched from the target now, to avoid problems
2024          later when this internalvar is referenced and the target is gone or
2025          has changed.  */
2026       if (value_lazy (new_data.value))
2027        value_fetch_lazy (new_data.value);
2028
2029       /* Release the value from the value chain to prevent it from being
2030          deleted by free_all_values.  From here on this function should not
2031          call error () until new_data is installed into the var->u to avoid
2032          leaking memory.  */
2033       release_value (new_data.value);
2034       break;
2035     }
2036
2037   /* Clean up old contents.  */
2038   clear_internalvar (var);
2039
2040   /* Switch over.  */
2041   var->kind = new_kind;
2042   var->u = new_data;
2043   /* End code which must not call error().  */
2044 }
2045
2046 void
2047 set_internalvar_integer (struct internalvar *var, LONGEST l)
2048 {
2049   /* Clean up old contents.  */
2050   clear_internalvar (var);
2051
2052   var->kind = INTERNALVAR_INTEGER;
2053   var->u.integer.type = NULL;
2054   var->u.integer.val = l;
2055 }
2056
2057 void
2058 set_internalvar_string (struct internalvar *var, const char *string)
2059 {
2060   /* Clean up old contents.  */
2061   clear_internalvar (var);
2062
2063   var->kind = INTERNALVAR_STRING;
2064   var->u.string = xstrdup (string);
2065 }
2066
2067 static void
2068 set_internalvar_function (struct internalvar *var, struct internal_function *f)
2069 {
2070   /* Clean up old contents.  */
2071   clear_internalvar (var);
2072
2073   var->kind = INTERNALVAR_FUNCTION;
2074   var->u.fn.function = f;
2075   var->u.fn.canonical = 1;
2076   /* Variables installed here are always the canonical version.  */
2077 }
2078
2079 void
2080 clear_internalvar (struct internalvar *var)
2081 {
2082   /* Clean up old contents.  */
2083   switch (var->kind)
2084     {
2085     case INTERNALVAR_VALUE:
2086       value_free (var->u.value);
2087       break;
2088
2089     case INTERNALVAR_STRING:
2090       xfree (var->u.string);
2091       break;
2092
2093     case INTERNALVAR_MAKE_VALUE:
2094       if (var->u.make_value.functions->destroy != NULL)
2095         var->u.make_value.functions->destroy (var->u.make_value.data);
2096       break;
2097
2098     default:
2099       break;
2100     }
2101
2102   /* Reset to void kind.  */
2103   var->kind = INTERNALVAR_VOID;
2104 }
2105
2106 char *
2107 internalvar_name (struct internalvar *var)
2108 {
2109   return var->name;
2110 }
2111
2112 static struct internal_function *
2113 create_internal_function (const char *name,
2114                           internal_function_fn handler, void *cookie)
2115 {
2116   struct internal_function *ifn = XNEW (struct internal_function);
2117
2118   ifn->name = xstrdup (name);
2119   ifn->handler = handler;
2120   ifn->cookie = cookie;
2121   return ifn;
2122 }
2123
2124 char *
2125 value_internal_function_name (struct value *val)
2126 {
2127   struct internal_function *ifn;
2128   int result;
2129
2130   gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2131   result = get_internalvar_function (VALUE_INTERNALVAR (val), &ifn);
2132   gdb_assert (result);
2133
2134   return ifn->name;
2135 }
2136
2137 struct value *
2138 call_internal_function (struct gdbarch *gdbarch,
2139                         const struct language_defn *language,
2140                         struct value *func, int argc, struct value **argv)
2141 {
2142   struct internal_function *ifn;
2143   int result;
2144
2145   gdb_assert (VALUE_LVAL (func) == lval_internalvar);
2146   result = get_internalvar_function (VALUE_INTERNALVAR (func), &ifn);
2147   gdb_assert (result);
2148
2149   return (*ifn->handler) (gdbarch, language, ifn->cookie, argc, argv);
2150 }
2151
2152 /* The 'function' command.  This does nothing -- it is just a
2153    placeholder to let "help function NAME" work.  This is also used as
2154    the implementation of the sub-command that is created when
2155    registering an internal function.  */
2156 static void
2157 function_command (char *command, int from_tty)
2158 {
2159   /* Do nothing.  */
2160 }
2161
2162 /* Clean up if an internal function's command is destroyed.  */
2163 static void
2164 function_destroyer (struct cmd_list_element *self, void *ignore)
2165 {
2166   xfree ((char *) self->name);
2167   xfree (self->doc);
2168 }
2169
2170 /* Add a new internal function.  NAME is the name of the function; DOC
2171    is a documentation string describing the function.  HANDLER is
2172    called when the function is invoked.  COOKIE is an arbitrary
2173    pointer which is passed to HANDLER and is intended for "user
2174    data".  */
2175 void
2176 add_internal_function (const char *name, const char *doc,
2177                        internal_function_fn handler, void *cookie)
2178 {
2179   struct cmd_list_element *cmd;
2180   struct internal_function *ifn;
2181   struct internalvar *var = lookup_internalvar (name);
2182
2183   ifn = create_internal_function (name, handler, cookie);
2184   set_internalvar_function (var, ifn);
2185
2186   cmd = add_cmd (xstrdup (name), no_class, function_command, (char *) doc,
2187                  &functionlist);
2188   cmd->destroyer = function_destroyer;
2189 }
2190
2191 /* Update VALUE before discarding OBJFILE.  COPIED_TYPES is used to
2192    prevent cycles / duplicates.  */
2193
2194 void
2195 preserve_one_value (struct value *value, struct objfile *objfile,
2196                     htab_t copied_types)
2197 {
2198   if (TYPE_OBJFILE (value->type) == objfile)
2199     value->type = copy_type_recursive (objfile, value->type, copied_types);
2200
2201   if (TYPE_OBJFILE (value->enclosing_type) == objfile)
2202     value->enclosing_type = copy_type_recursive (objfile,
2203                                                  value->enclosing_type,
2204                                                  copied_types);
2205 }
2206
2207 /* Likewise for internal variable VAR.  */
2208
2209 static void
2210 preserve_one_internalvar (struct internalvar *var, struct objfile *objfile,
2211                           htab_t copied_types)
2212 {
2213   switch (var->kind)
2214     {
2215     case INTERNALVAR_INTEGER:
2216       if (var->u.integer.type && TYPE_OBJFILE (var->u.integer.type) == objfile)
2217         var->u.integer.type
2218           = copy_type_recursive (objfile, var->u.integer.type, copied_types);
2219       break;
2220
2221     case INTERNALVAR_VALUE:
2222       preserve_one_value (var->u.value, objfile, copied_types);
2223       break;
2224     }
2225 }
2226
2227 /* Update the internal variables and value history when OBJFILE is
2228    discarded; we must copy the types out of the objfile.  New global types
2229    will be created for every convenience variable which currently points to
2230    this objfile's types, and the convenience variables will be adjusted to
2231    use the new global types.  */
2232
2233 void
2234 preserve_values (struct objfile *objfile)
2235 {
2236   htab_t copied_types;
2237   struct value_history_chunk *cur;
2238   struct internalvar *var;
2239   int i;
2240
2241   /* Create the hash table.  We allocate on the objfile's obstack, since
2242      it is soon to be deleted.  */
2243   copied_types = create_copied_types_hash (objfile);
2244
2245   for (cur = value_history_chain; cur; cur = cur->next)
2246     for (i = 0; i < VALUE_HISTORY_CHUNK; i++)
2247       if (cur->values[i])
2248         preserve_one_value (cur->values[i], objfile, copied_types);
2249
2250   for (var = internalvars; var; var = var->next)
2251     preserve_one_internalvar (var, objfile, copied_types);
2252
2253   preserve_python_values (objfile, copied_types);
2254
2255   htab_delete (copied_types);
2256 }
2257
2258 static void
2259 show_convenience (char *ignore, int from_tty)
2260 {
2261   struct gdbarch *gdbarch = get_current_arch ();
2262   struct internalvar *var;
2263   int varseen = 0;
2264   struct value_print_options opts;
2265
2266   get_user_print_options (&opts);
2267   for (var = internalvars; var; var = var->next)
2268     {
2269       volatile struct gdb_exception ex;
2270
2271       if (!varseen)
2272         {
2273           varseen = 1;
2274         }
2275       printf_filtered (("$%s = "), var->name);
2276
2277       TRY_CATCH (ex, RETURN_MASK_ERROR)
2278         {
2279           struct value *val;
2280
2281           val = value_of_internalvar (gdbarch, var);
2282           value_print (val, gdb_stdout, &opts);
2283         }
2284       if (ex.reason < 0)
2285         fprintf_filtered (gdb_stdout, _("<error: %s>"), ex.message);
2286       printf_filtered (("\n"));
2287     }
2288   if (!varseen)
2289     {
2290       /* This text does not mention convenience functions on purpose.
2291          The user can't create them except via Python, and if Python support
2292          is installed this message will never be printed ($_streq will
2293          exist).  */
2294       printf_unfiltered (_("No debugger convenience variables now defined.\n"
2295                            "Convenience variables have "
2296                            "names starting with \"$\";\n"
2297                            "use \"set\" as in \"set "
2298                            "$foo = 5\" to define them.\n"));
2299     }
2300 }
2301 \f
2302 /* Extract a value as a C number (either long or double).
2303    Knows how to convert fixed values to double, or
2304    floating values to long.
2305    Does not deallocate the value.  */
2306
2307 LONGEST
2308 value_as_long (struct value *val)
2309 {
2310   /* This coerces arrays and functions, which is necessary (e.g.
2311      in disassemble_command).  It also dereferences references, which
2312      I suspect is the most logical thing to do.  */
2313   val = coerce_array (val);
2314   return unpack_long (value_type (val), value_contents (val));
2315 }
2316
2317 DOUBLEST
2318 value_as_double (struct value *val)
2319 {
2320   DOUBLEST foo;
2321   int inv;
2322
2323   foo = unpack_double (value_type (val), value_contents (val), &inv);
2324   if (inv)
2325     error (_("Invalid floating value found in program."));
2326   return foo;
2327 }
2328
2329 /* Extract a value as a C pointer.  Does not deallocate the value.
2330    Note that val's type may not actually be a pointer; value_as_long
2331    handles all the cases.  */
2332 CORE_ADDR
2333 value_as_address (struct value *val)
2334 {
2335   struct gdbarch *gdbarch = get_type_arch (value_type (val));
2336
2337   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2338      whether we want this to be true eventually.  */
2339 #if 0
2340   /* gdbarch_addr_bits_remove is wrong if we are being called for a
2341      non-address (e.g. argument to "signal", "info break", etc.), or
2342      for pointers to char, in which the low bits *are* significant.  */
2343   return gdbarch_addr_bits_remove (gdbarch, value_as_long (val));
2344 #else
2345
2346   /* There are several targets (IA-64, PowerPC, and others) which
2347      don't represent pointers to functions as simply the address of
2348      the function's entry point.  For example, on the IA-64, a
2349      function pointer points to a two-word descriptor, generated by
2350      the linker, which contains the function's entry point, and the
2351      value the IA-64 "global pointer" register should have --- to
2352      support position-independent code.  The linker generates
2353      descriptors only for those functions whose addresses are taken.
2354
2355      On such targets, it's difficult for GDB to convert an arbitrary
2356      function address into a function pointer; it has to either find
2357      an existing descriptor for that function, or call malloc and
2358      build its own.  On some targets, it is impossible for GDB to
2359      build a descriptor at all: the descriptor must contain a jump
2360      instruction; data memory cannot be executed; and code memory
2361      cannot be modified.
2362
2363      Upon entry to this function, if VAL is a value of type `function'
2364      (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
2365      value_address (val) is the address of the function.  This is what
2366      you'll get if you evaluate an expression like `main'.  The call
2367      to COERCE_ARRAY below actually does all the usual unary
2368      conversions, which includes converting values of type `function'
2369      to `pointer to function'.  This is the challenging conversion
2370      discussed above.  Then, `unpack_long' will convert that pointer
2371      back into an address.
2372
2373      So, suppose the user types `disassemble foo' on an architecture
2374      with a strange function pointer representation, on which GDB
2375      cannot build its own descriptors, and suppose further that `foo'
2376      has no linker-built descriptor.  The address->pointer conversion
2377      will signal an error and prevent the command from running, even
2378      though the next step would have been to convert the pointer
2379      directly back into the same address.
2380
2381      The following shortcut avoids this whole mess.  If VAL is a
2382      function, just return its address directly.  */
2383   if (TYPE_CODE (value_type (val)) == TYPE_CODE_FUNC
2384       || TYPE_CODE (value_type (val)) == TYPE_CODE_METHOD)
2385     return value_address (val);
2386
2387   val = coerce_array (val);
2388
2389   /* Some architectures (e.g. Harvard), map instruction and data
2390      addresses onto a single large unified address space.  For
2391      instance: An architecture may consider a large integer in the
2392      range 0x10000000 .. 0x1000ffff to already represent a data
2393      addresses (hence not need a pointer to address conversion) while
2394      a small integer would still need to be converted integer to
2395      pointer to address.  Just assume such architectures handle all
2396      integer conversions in a single function.  */
2397
2398   /* JimB writes:
2399
2400      I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
2401      must admonish GDB hackers to make sure its behavior matches the
2402      compiler's, whenever possible.
2403
2404      In general, I think GDB should evaluate expressions the same way
2405      the compiler does.  When the user copies an expression out of
2406      their source code and hands it to a `print' command, they should
2407      get the same value the compiler would have computed.  Any
2408      deviation from this rule can cause major confusion and annoyance,
2409      and needs to be justified carefully.  In other words, GDB doesn't
2410      really have the freedom to do these conversions in clever and
2411      useful ways.
2412
2413      AndrewC pointed out that users aren't complaining about how GDB
2414      casts integers to pointers; they are complaining that they can't
2415      take an address from a disassembly listing and give it to `x/i'.
2416      This is certainly important.
2417
2418      Adding an architecture method like integer_to_address() certainly
2419      makes it possible for GDB to "get it right" in all circumstances
2420      --- the target has complete control over how things get done, so
2421      people can Do The Right Thing for their target without breaking
2422      anyone else.  The standard doesn't specify how integers get
2423      converted to pointers; usually, the ABI doesn't either, but
2424      ABI-specific code is a more reasonable place to handle it.  */
2425
2426   if (TYPE_CODE (value_type (val)) != TYPE_CODE_PTR
2427       && TYPE_CODE (value_type (val)) != TYPE_CODE_REF
2428       && gdbarch_integer_to_address_p (gdbarch))
2429     return gdbarch_integer_to_address (gdbarch, value_type (val),
2430                                        value_contents (val));
2431
2432   return unpack_long (value_type (val), value_contents (val));
2433 #endif
2434 }
2435 \f
2436 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2437    as a long, or as a double, assuming the raw data is described
2438    by type TYPE.  Knows how to convert different sizes of values
2439    and can convert between fixed and floating point.  We don't assume
2440    any alignment for the raw data.  Return value is in host byte order.
2441
2442    If you want functions and arrays to be coerced to pointers, and
2443    references to be dereferenced, call value_as_long() instead.
2444
2445    C++: It is assumed that the front-end has taken care of
2446    all matters concerning pointers to members.  A pointer
2447    to member which reaches here is considered to be equivalent
2448    to an INT (or some size).  After all, it is only an offset.  */
2449
2450 LONGEST
2451 unpack_long (struct type *type, const gdb_byte *valaddr)
2452 {
2453   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
2454   enum type_code code = TYPE_CODE (type);
2455   int len = TYPE_LENGTH (type);
2456   int nosign = TYPE_UNSIGNED (type);
2457
2458   switch (code)
2459     {
2460     case TYPE_CODE_TYPEDEF:
2461       return unpack_long (check_typedef (type), valaddr);
2462     case TYPE_CODE_ENUM:
2463     case TYPE_CODE_FLAGS:
2464     case TYPE_CODE_BOOL:
2465     case TYPE_CODE_INT:
2466     case TYPE_CODE_CHAR:
2467     case TYPE_CODE_RANGE:
2468     case TYPE_CODE_MEMBERPTR:
2469       if (nosign)
2470         return extract_unsigned_integer (valaddr, len, byte_order);
2471       else
2472         return extract_signed_integer (valaddr, len, byte_order);
2473
2474     case TYPE_CODE_FLT:
2475       return extract_typed_floating (valaddr, type);
2476
2477     case TYPE_CODE_DECFLOAT:
2478       /* libdecnumber has a function to convert from decimal to integer, but
2479          it doesn't work when the decimal number has a fractional part.  */
2480       return decimal_to_doublest (valaddr, len, byte_order);
2481
2482     case TYPE_CODE_PTR:
2483     case TYPE_CODE_REF:
2484       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2485          whether we want this to be true eventually.  */
2486       return extract_typed_address (valaddr, type);
2487
2488     default:
2489       error (_("Value can't be converted to integer."));
2490     }
2491   return 0;                     /* Placate lint.  */
2492 }
2493
2494 /* Return a double value from the specified type and address.
2495    INVP points to an int which is set to 0 for valid value,
2496    1 for invalid value (bad float format).  In either case,
2497    the returned double is OK to use.  Argument is in target
2498    format, result is in host format.  */
2499
2500 DOUBLEST
2501 unpack_double (struct type *type, const gdb_byte *valaddr, int *invp)
2502 {
2503   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
2504   enum type_code code;
2505   int len;
2506   int nosign;
2507
2508   *invp = 0;                    /* Assume valid.  */
2509   CHECK_TYPEDEF (type);
2510   code = TYPE_CODE (type);
2511   len = TYPE_LENGTH (type);
2512   nosign = TYPE_UNSIGNED (type);
2513   if (code == TYPE_CODE_FLT)
2514     {
2515       /* NOTE: cagney/2002-02-19: There was a test here to see if the
2516          floating-point value was valid (using the macro
2517          INVALID_FLOAT).  That test/macro have been removed.
2518
2519          It turns out that only the VAX defined this macro and then
2520          only in a non-portable way.  Fixing the portability problem
2521          wouldn't help since the VAX floating-point code is also badly
2522          bit-rotten.  The target needs to add definitions for the
2523          methods gdbarch_float_format and gdbarch_double_format - these
2524          exactly describe the target floating-point format.  The
2525          problem here is that the corresponding floatformat_vax_f and
2526          floatformat_vax_d values these methods should be set to are
2527          also not defined either.  Oops!
2528
2529          Hopefully someone will add both the missing floatformat
2530          definitions and the new cases for floatformat_is_valid ().  */
2531
2532       if (!floatformat_is_valid (floatformat_from_type (type), valaddr))
2533         {
2534           *invp = 1;
2535           return 0.0;
2536         }
2537
2538       return extract_typed_floating (valaddr, type);
2539     }
2540   else if (code == TYPE_CODE_DECFLOAT)
2541     return decimal_to_doublest (valaddr, len, byte_order);
2542   else if (nosign)
2543     {
2544       /* Unsigned -- be sure we compensate for signed LONGEST.  */
2545       return (ULONGEST) unpack_long (type, valaddr);
2546     }
2547   else
2548     {
2549       /* Signed -- we are OK with unpack_long.  */
2550       return unpack_long (type, valaddr);
2551     }
2552 }
2553
2554 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2555    as a CORE_ADDR, assuming the raw data is described by type TYPE.
2556    We don't assume any alignment for the raw data.  Return value is in
2557    host byte order.
2558
2559    If you want functions and arrays to be coerced to pointers, and
2560    references to be dereferenced, call value_as_address() instead.
2561
2562    C++: It is assumed that the front-end has taken care of
2563    all matters concerning pointers to members.  A pointer
2564    to member which reaches here is considered to be equivalent
2565    to an INT (or some size).  After all, it is only an offset.  */
2566
2567 CORE_ADDR
2568 unpack_pointer (struct type *type, const gdb_byte *valaddr)
2569 {
2570   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2571      whether we want this to be true eventually.  */
2572   return unpack_long (type, valaddr);
2573 }
2574
2575 \f
2576 /* Get the value of the FIELDNO'th field (which must be static) of
2577    TYPE.  Return NULL if the field doesn't exist or has been
2578    optimized out.  */
2579
2580 struct value *
2581 value_static_field (struct type *type, int fieldno)
2582 {
2583   struct value *retval;
2584
2585   switch (TYPE_FIELD_LOC_KIND (type, fieldno))
2586     {
2587     case FIELD_LOC_KIND_PHYSADDR:
2588       retval = value_at_lazy (TYPE_FIELD_TYPE (type, fieldno),
2589                               TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
2590       break;
2591     case FIELD_LOC_KIND_PHYSNAME:
2592     {
2593       const char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
2594       /* TYPE_FIELD_NAME (type, fieldno); */
2595       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
2596
2597       if (sym == NULL)
2598         {
2599           /* With some compilers, e.g. HP aCC, static data members are
2600              reported as non-debuggable symbols.  */
2601           struct minimal_symbol *msym = lookup_minimal_symbol (phys_name,
2602                                                                NULL, NULL);
2603
2604           if (!msym)
2605             return NULL;
2606           else
2607             {
2608               retval = value_at_lazy (TYPE_FIELD_TYPE (type, fieldno),
2609                                       SYMBOL_VALUE_ADDRESS (msym));
2610             }
2611         }
2612       else
2613         retval = value_of_variable (sym, NULL);
2614       break;
2615     }
2616     default:
2617       gdb_assert_not_reached ("unexpected field location kind");
2618     }
2619
2620   return retval;
2621 }
2622
2623 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.
2624    You have to be careful here, since the size of the data area for the value
2625    is set by the length of the enclosing type.  So if NEW_ENCL_TYPE is bigger
2626    than the old enclosing type, you have to allocate more space for the
2627    data.  */
2628
2629 void
2630 set_value_enclosing_type (struct value *val, struct type *new_encl_type)
2631 {
2632   if (TYPE_LENGTH (new_encl_type) > TYPE_LENGTH (value_enclosing_type (val))) 
2633     val->contents =
2634       (gdb_byte *) xrealloc (val->contents, TYPE_LENGTH (new_encl_type));
2635
2636   val->enclosing_type = new_encl_type;
2637 }
2638
2639 /* Given a value ARG1 (offset by OFFSET bytes)
2640    of a struct or union type ARG_TYPE,
2641    extract and return the value of one of its (non-static) fields.
2642    FIELDNO says which field.  */
2643
2644 struct value *
2645 value_primitive_field (struct value *arg1, int offset,
2646                        int fieldno, struct type *arg_type)
2647 {
2648   struct value *v;
2649   struct type *type;
2650
2651   CHECK_TYPEDEF (arg_type);
2652   type = TYPE_FIELD_TYPE (arg_type, fieldno);
2653
2654   /* Call check_typedef on our type to make sure that, if TYPE
2655      is a TYPE_CODE_TYPEDEF, its length is set to the length
2656      of the target type instead of zero.  However, we do not
2657      replace the typedef type by the target type, because we want
2658      to keep the typedef in order to be able to print the type
2659      description correctly.  */
2660   check_typedef (type);
2661
2662   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
2663     {
2664       /* Handle packed fields.
2665
2666          Create a new value for the bitfield, with bitpos and bitsize
2667          set.  If possible, arrange offset and bitpos so that we can
2668          do a single aligned read of the size of the containing type.
2669          Otherwise, adjust offset to the byte containing the first
2670          bit.  Assume that the address, offset, and embedded offset
2671          are sufficiently aligned.  */
2672
2673       int bitpos = TYPE_FIELD_BITPOS (arg_type, fieldno);
2674       int container_bitsize = TYPE_LENGTH (type) * 8;
2675
2676       if (arg1->optimized_out)
2677         v = allocate_optimized_out_value (type);
2678       else
2679         {
2680           v = allocate_value_lazy (type);
2681           v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
2682           if ((bitpos % container_bitsize) + v->bitsize <= container_bitsize
2683               && TYPE_LENGTH (type) <= (int) sizeof (LONGEST))
2684             v->bitpos = bitpos % container_bitsize;
2685           else
2686             v->bitpos = bitpos % 8;
2687           v->offset = (value_embedded_offset (arg1)
2688                        + offset
2689                        + (bitpos - v->bitpos) / 8);
2690           set_value_parent (v, arg1);
2691           if (!value_lazy (arg1))
2692             value_fetch_lazy (v);
2693         }
2694     }
2695   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
2696     {
2697       /* This field is actually a base subobject, so preserve the
2698          entire object's contents for later references to virtual
2699          bases, etc.  */
2700       int boffset;
2701
2702       /* Lazy register values with offsets are not supported.  */
2703       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
2704         value_fetch_lazy (arg1);
2705
2706       /* The optimized_out flag is only set correctly once a lazy value is
2707          loaded, having just loaded some lazy values we should check the
2708          optimized out case now.  */
2709       if (arg1->optimized_out)
2710         v = allocate_optimized_out_value (type);
2711       else
2712         {
2713           /* We special case virtual inheritance here because this
2714              requires access to the contents, which we would rather avoid
2715              for references to ordinary fields of unavailable values.  */
2716           if (BASETYPE_VIA_VIRTUAL (arg_type, fieldno))
2717             boffset = baseclass_offset (arg_type, fieldno,
2718                                         value_contents (arg1),
2719                                         value_embedded_offset (arg1),
2720                                         value_address (arg1),
2721                                         arg1);
2722           else
2723             boffset = TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
2724
2725           if (value_lazy (arg1))
2726             v = allocate_value_lazy (value_enclosing_type (arg1));
2727           else
2728             {
2729               v = allocate_value (value_enclosing_type (arg1));
2730               value_contents_copy_raw (v, 0, arg1, 0,
2731                                        TYPE_LENGTH (value_enclosing_type (arg1)));
2732             }
2733           v->type = type;
2734           v->offset = value_offset (arg1);
2735           v->embedded_offset = offset + value_embedded_offset (arg1) + boffset;
2736         }
2737     }
2738   else
2739     {
2740       /* Plain old data member */
2741       offset += TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
2742
2743       /* Lazy register values with offsets are not supported.  */
2744       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
2745         value_fetch_lazy (arg1);
2746
2747       /* The optimized_out flag is only set correctly once a lazy value is
2748          loaded, having just loaded some lazy values we should check for
2749          the optimized out case now.  */
2750       if (arg1->optimized_out)
2751         v = allocate_optimized_out_value (type);
2752       else if (value_lazy (arg1))
2753         v = allocate_value_lazy (type);
2754       else
2755         {
2756           v = allocate_value (type);
2757           value_contents_copy_raw (v, value_embedded_offset (v),
2758                                    arg1, value_embedded_offset (arg1) + offset,
2759                                    TYPE_LENGTH (type));
2760         }
2761       v->offset = (value_offset (arg1) + offset
2762                    + value_embedded_offset (arg1));
2763     }
2764   set_value_component_location (v, arg1);
2765   VALUE_REGNUM (v) = VALUE_REGNUM (arg1);
2766   VALUE_FRAME_ID (v) = VALUE_FRAME_ID (arg1);
2767   return v;
2768 }
2769
2770 /* Given a value ARG1 of a struct or union type,
2771    extract and return the value of one of its (non-static) fields.
2772    FIELDNO says which field.  */
2773
2774 struct value *
2775 value_field (struct value *arg1, int fieldno)
2776 {
2777   return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
2778 }
2779
2780 /* Return a non-virtual function as a value.
2781    F is the list of member functions which contains the desired method.
2782    J is an index into F which provides the desired method.
2783
2784    We only use the symbol for its address, so be happy with either a
2785    full symbol or a minimal symbol.  */
2786
2787 struct value *
2788 value_fn_field (struct value **arg1p, struct fn_field *f,
2789                 int j, struct type *type,
2790                 int offset)
2791 {
2792   struct value *v;
2793   struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
2794   const char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
2795   struct symbol *sym;
2796   struct bound_minimal_symbol msym;
2797
2798   sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0);
2799   if (sym != NULL)
2800     {
2801       memset (&msym, 0, sizeof (msym));
2802     }
2803   else
2804     {
2805       gdb_assert (sym == NULL);
2806       msym = lookup_bound_minimal_symbol (physname);
2807       if (msym.minsym == NULL)
2808         return NULL;
2809     }
2810
2811   v = allocate_value (ftype);
2812   if (sym)
2813     {
2814       set_value_address (v, BLOCK_START (SYMBOL_BLOCK_VALUE (sym)));
2815     }
2816   else
2817     {
2818       /* The minimal symbol might point to a function descriptor;
2819          resolve it to the actual code address instead.  */
2820       struct objfile *objfile = msym.objfile;
2821       struct gdbarch *gdbarch = get_objfile_arch (objfile);
2822
2823       set_value_address (v,
2824         gdbarch_convert_from_func_ptr_addr
2825            (gdbarch, SYMBOL_VALUE_ADDRESS (msym.minsym), &current_target));
2826     }
2827
2828   if (arg1p)
2829     {
2830       if (type != value_type (*arg1p))
2831         *arg1p = value_ind (value_cast (lookup_pointer_type (type),
2832                                         value_addr (*arg1p)));
2833
2834       /* Move the `this' pointer according to the offset.
2835          VALUE_OFFSET (*arg1p) += offset; */
2836     }
2837
2838   return v;
2839 }
2840
2841 \f
2842
2843 /* Helper function for both unpack_value_bits_as_long and
2844    unpack_bits_as_long.  See those functions for more details on the
2845    interface; the only difference is that this function accepts either
2846    a NULL or a non-NULL ORIGINAL_VALUE.  */
2847
2848 static int
2849 unpack_value_bits_as_long_1 (struct type *field_type, const gdb_byte *valaddr,
2850                              int embedded_offset, int bitpos, int bitsize,
2851                              const struct value *original_value,
2852                              LONGEST *result)
2853 {
2854   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (field_type));
2855   ULONGEST val;
2856   ULONGEST valmask;
2857   int lsbcount;
2858   int bytes_read;
2859   int read_offset;
2860
2861   /* Read the minimum number of bytes required; there may not be
2862      enough bytes to read an entire ULONGEST.  */
2863   CHECK_TYPEDEF (field_type);
2864   if (bitsize)
2865     bytes_read = ((bitpos % 8) + bitsize + 7) / 8;
2866   else
2867     bytes_read = TYPE_LENGTH (field_type);
2868
2869   read_offset = bitpos / 8;
2870
2871   if (original_value != NULL
2872       && !value_bytes_available (original_value, embedded_offset + read_offset,
2873                                  bytes_read))
2874     return 0;
2875
2876   val = extract_unsigned_integer (valaddr + embedded_offset + read_offset,
2877                                   bytes_read, byte_order);
2878
2879   /* Extract bits.  See comment above.  */
2880
2881   if (gdbarch_bits_big_endian (get_type_arch (field_type)))
2882     lsbcount = (bytes_read * 8 - bitpos % 8 - bitsize);
2883   else
2884     lsbcount = (bitpos % 8);
2885   val >>= lsbcount;
2886
2887   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
2888      If the field is signed, and is negative, then sign extend.  */
2889
2890   if ((bitsize > 0) && (bitsize < 8 * (int) sizeof (val)))
2891     {
2892       valmask = (((ULONGEST) 1) << bitsize) - 1;
2893       val &= valmask;
2894       if (!TYPE_UNSIGNED (field_type))
2895         {
2896           if (val & (valmask ^ (valmask >> 1)))
2897             {
2898               val |= ~valmask;
2899             }
2900         }
2901     }
2902
2903   *result = val;
2904   return 1;
2905 }
2906
2907 /* Unpack a bitfield of the specified FIELD_TYPE, from the object at
2908    VALADDR + EMBEDDED_OFFSET, and store the result in *RESULT.
2909    VALADDR points to the contents of ORIGINAL_VALUE, which must not be
2910    NULL.  The bitfield starts at BITPOS bits and contains BITSIZE
2911    bits.
2912
2913    Returns false if the value contents are unavailable, otherwise
2914    returns true, indicating a valid value has been stored in *RESULT.
2915
2916    Extracting bits depends on endianness of the machine.  Compute the
2917    number of least significant bits to discard.  For big endian machines,
2918    we compute the total number of bits in the anonymous object, subtract
2919    off the bit count from the MSB of the object to the MSB of the
2920    bitfield, then the size of the bitfield, which leaves the LSB discard
2921    count.  For little endian machines, the discard count is simply the
2922    number of bits from the LSB of the anonymous object to the LSB of the
2923    bitfield.
2924
2925    If the field is signed, we also do sign extension.  */
2926
2927 int
2928 unpack_value_bits_as_long (struct type *field_type, const gdb_byte *valaddr,
2929                            int embedded_offset, int bitpos, int bitsize,
2930                            const struct value *original_value,
2931                            LONGEST *result)
2932 {
2933   gdb_assert (original_value != NULL);
2934
2935   return unpack_value_bits_as_long_1 (field_type, valaddr, embedded_offset,
2936                                       bitpos, bitsize, original_value, result);
2937
2938 }
2939
2940 /* Unpack a field FIELDNO of the specified TYPE, from the object at
2941    VALADDR + EMBEDDED_OFFSET.  VALADDR points to the contents of
2942    ORIGINAL_VALUE.  See unpack_value_bits_as_long for more
2943    details.  */
2944
2945 static int
2946 unpack_value_field_as_long_1 (struct type *type, const gdb_byte *valaddr,
2947                               int embedded_offset, int fieldno,
2948                               const struct value *val, LONGEST *result)
2949 {
2950   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
2951   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
2952   struct type *field_type = TYPE_FIELD_TYPE (type, fieldno);
2953
2954   return unpack_value_bits_as_long_1 (field_type, valaddr, embedded_offset,
2955                                       bitpos, bitsize, val,
2956                                       result);
2957 }
2958
2959 /* Unpack a field FIELDNO of the specified TYPE, from the object at
2960    VALADDR + EMBEDDED_OFFSET.  VALADDR points to the contents of
2961    ORIGINAL_VALUE, which must not be NULL.  See
2962    unpack_value_bits_as_long for more details.  */
2963
2964 int
2965 unpack_value_field_as_long (struct type *type, const gdb_byte *valaddr,
2966                             int embedded_offset, int fieldno,
2967                             const struct value *val, LONGEST *result)
2968 {
2969   gdb_assert (val != NULL);
2970
2971   return unpack_value_field_as_long_1 (type, valaddr, embedded_offset,
2972                                        fieldno, val, result);
2973 }
2974
2975 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous
2976    object at VALADDR.  See unpack_value_bits_as_long for more details.
2977    This function differs from unpack_value_field_as_long in that it
2978    operates without a struct value object.  */
2979
2980 LONGEST
2981 unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
2982 {
2983   LONGEST result;
2984
2985   unpack_value_field_as_long_1 (type, valaddr, 0, fieldno, NULL, &result);
2986   return result;
2987 }
2988
2989 /* Return a new value with type TYPE, which is FIELDNO field of the
2990    object at VALADDR + EMBEDDEDOFFSET.  VALADDR points to the contents
2991    of VAL.  If the VAL's contents required to extract the bitfield
2992    from are unavailable, the new value is correspondingly marked as
2993    unavailable.  */
2994
2995 struct value *
2996 value_field_bitfield (struct type *type, int fieldno,
2997                       const gdb_byte *valaddr,
2998                       int embedded_offset, const struct value *val)
2999 {
3000   LONGEST l;
3001
3002   if (!unpack_value_field_as_long (type, valaddr, embedded_offset, fieldno,
3003                                    val, &l))
3004     {
3005       struct type *field_type = TYPE_FIELD_TYPE (type, fieldno);
3006       struct value *retval = allocate_value (field_type);
3007       mark_value_bytes_unavailable (retval, 0, TYPE_LENGTH (field_type));
3008       return retval;
3009     }
3010   else
3011     {
3012       return value_from_longest (TYPE_FIELD_TYPE (type, fieldno), l);
3013     }
3014 }
3015
3016 /* Modify the value of a bitfield.  ADDR points to a block of memory in
3017    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
3018    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
3019    indicate which bits (in target bit order) comprise the bitfield.
3020    Requires 0 < BITSIZE <= lbits, 0 <= BITPOS % 8 + BITSIZE <= lbits, and
3021    0 <= BITPOS, where lbits is the size of a LONGEST in bits.  */
3022
3023 void
3024 modify_field (struct type *type, gdb_byte *addr,
3025               LONGEST fieldval, int bitpos, int bitsize)
3026 {
3027   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
3028   ULONGEST oword;
3029   ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
3030   int bytesize;
3031
3032   /* Normalize BITPOS.  */
3033   addr += bitpos / 8;
3034   bitpos %= 8;
3035
3036   /* If a negative fieldval fits in the field in question, chop
3037      off the sign extension bits.  */
3038   if ((~fieldval & ~(mask >> 1)) == 0)
3039     fieldval &= mask;
3040
3041   /* Warn if value is too big to fit in the field in question.  */
3042   if (0 != (fieldval & ~mask))
3043     {
3044       /* FIXME: would like to include fieldval in the message, but
3045          we don't have a sprintf_longest.  */
3046       warning (_("Value does not fit in %d bits."), bitsize);
3047
3048       /* Truncate it, otherwise adjoining fields may be corrupted.  */
3049       fieldval &= mask;
3050     }
3051
3052   /* Ensure no bytes outside of the modified ones get accessed as it may cause
3053      false valgrind reports.  */
3054
3055   bytesize = (bitpos + bitsize + 7) / 8;
3056   oword = extract_unsigned_integer (addr, bytesize, byte_order);
3057
3058   /* Shifting for bit field depends on endianness of the target machine.  */
3059   if (gdbarch_bits_big_endian (get_type_arch (type)))
3060     bitpos = bytesize * 8 - bitpos - bitsize;
3061
3062   oword &= ~(mask << bitpos);
3063   oword |= fieldval << bitpos;
3064
3065   store_unsigned_integer (addr, bytesize, byte_order, oword);
3066 }
3067 \f
3068 /* Pack NUM into BUF using a target format of TYPE.  */
3069
3070 void
3071 pack_long (gdb_byte *buf, struct type *type, LONGEST num)
3072 {
3073   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
3074   int len;
3075
3076   type = check_typedef (type);
3077   len = TYPE_LENGTH (type);
3078
3079   switch (TYPE_CODE (type))
3080     {
3081     case TYPE_CODE_INT:
3082     case TYPE_CODE_CHAR:
3083     case TYPE_CODE_ENUM:
3084     case TYPE_CODE_FLAGS:
3085     case TYPE_CODE_BOOL:
3086     case TYPE_CODE_RANGE:
3087     case TYPE_CODE_MEMBERPTR:
3088       store_signed_integer (buf, len, byte_order, num);
3089       break;
3090
3091     case TYPE_CODE_REF:
3092     case TYPE_CODE_PTR:
3093       store_typed_address (buf, type, (CORE_ADDR) num);
3094       break;
3095
3096     default:
3097       error (_("Unexpected type (%d) encountered for integer constant."),
3098              TYPE_CODE (type));
3099     }
3100 }
3101
3102
3103 /* Pack NUM into BUF using a target format of TYPE.  */
3104
3105 static void
3106 pack_unsigned_long (gdb_byte *buf, struct type *type, ULONGEST num)
3107 {
3108   int len;
3109   enum bfd_endian byte_order;
3110
3111   type = check_typedef (type);
3112   len = TYPE_LENGTH (type);
3113   byte_order = gdbarch_byte_order (get_type_arch (type));
3114
3115   switch (TYPE_CODE (type))
3116     {
3117     case TYPE_CODE_INT:
3118     case TYPE_CODE_CHAR:
3119     case TYPE_CODE_ENUM:
3120     case TYPE_CODE_FLAGS:
3121     case TYPE_CODE_BOOL:
3122     case TYPE_CODE_RANGE:
3123     case TYPE_CODE_MEMBERPTR:
3124       store_unsigned_integer (buf, len, byte_order, num);
3125       break;
3126
3127     case TYPE_CODE_REF:
3128     case TYPE_CODE_PTR:
3129       store_typed_address (buf, type, (CORE_ADDR) num);
3130       break;
3131
3132     default:
3133       error (_("Unexpected type (%d) encountered "
3134                "for unsigned integer constant."),
3135              TYPE_CODE (type));
3136     }
3137 }
3138
3139
3140 /* Convert C numbers into newly allocated values.  */
3141
3142 struct value *
3143 value_from_longest (struct type *type, LONGEST num)
3144 {
3145   struct value *val = allocate_value (type);
3146
3147   pack_long (value_contents_raw (val), type, num);
3148   return val;
3149 }
3150
3151
3152 /* Convert C unsigned numbers into newly allocated values.  */
3153
3154 struct value *
3155 value_from_ulongest (struct type *type, ULONGEST num)
3156 {
3157   struct value *val = allocate_value (type);
3158
3159   pack_unsigned_long (value_contents_raw (val), type, num);
3160
3161   return val;
3162 }
3163
3164
3165 /* Create a value representing a pointer of type TYPE to the address
3166    ADDR.  */
3167 struct value *
3168 value_from_pointer (struct type *type, CORE_ADDR addr)
3169 {
3170   struct value *val = allocate_value (type);
3171
3172   store_typed_address (value_contents_raw (val), check_typedef (type), addr);
3173   return val;
3174 }
3175
3176
3177 /* Create a value of type TYPE whose contents come from VALADDR, if it
3178    is non-null, and whose memory address (in the inferior) is
3179    ADDRESS.  */
3180
3181 struct value *
3182 value_from_contents_and_address (struct type *type,
3183                                  const gdb_byte *valaddr,
3184                                  CORE_ADDR address)
3185 {
3186   struct value *v;
3187
3188   if (valaddr == NULL)
3189     v = allocate_value_lazy (type);
3190   else
3191     v = value_from_contents (type, valaddr);
3192   set_value_address (v, address);
3193   VALUE_LVAL (v) = lval_memory;
3194   return v;
3195 }
3196
3197 /* Create a value of type TYPE holding the contents CONTENTS.
3198    The new value is `not_lval'.  */
3199
3200 struct value *
3201 value_from_contents (struct type *type, const gdb_byte *contents)
3202 {
3203   struct value *result;
3204
3205   result = allocate_value (type);
3206   memcpy (value_contents_raw (result), contents, TYPE_LENGTH (type));
3207   return result;
3208 }
3209
3210 struct value *
3211 value_from_double (struct type *type, DOUBLEST num)
3212 {
3213   struct value *val = allocate_value (type);
3214   struct type *base_type = check_typedef (type);
3215   enum type_code code = TYPE_CODE (base_type);
3216
3217   if (code == TYPE_CODE_FLT)
3218     {
3219       store_typed_floating (value_contents_raw (val), base_type, num);
3220     }
3221   else
3222     error (_("Unexpected type encountered for floating constant."));
3223
3224   return val;
3225 }
3226
3227 struct value *
3228 value_from_decfloat (struct type *type, const gdb_byte *dec)
3229 {
3230   struct value *val = allocate_value (type);
3231
3232   memcpy (value_contents_raw (val), dec, TYPE_LENGTH (type));
3233   return val;
3234 }
3235
3236 /* Extract a value from the history file.  Input will be of the form
3237    $digits or $$digits.  See block comment above 'write_dollar_variable'
3238    for details.  */
3239
3240 struct value *
3241 value_from_history_ref (char *h, char **endp)
3242 {
3243   int index, len;
3244
3245   if (h[0] == '$')
3246     len = 1;
3247   else
3248     return NULL;
3249
3250   if (h[1] == '$')
3251     len = 2;
3252
3253   /* Find length of numeral string.  */
3254   for (; isdigit (h[len]); len++)
3255     ;
3256
3257   /* Make sure numeral string is not part of an identifier.  */
3258   if (h[len] == '_' || isalpha (h[len]))
3259     return NULL;
3260
3261   /* Now collect the index value.  */
3262   if (h[1] == '$')
3263     {
3264       if (len == 2)
3265         {
3266           /* For some bizarre reason, "$$" is equivalent to "$$1", 
3267              rather than to "$$0" as it ought to be!  */
3268           index = -1;
3269           *endp += len;
3270         }
3271       else
3272         index = -strtol (&h[2], endp, 10);
3273     }
3274   else
3275     {
3276       if (len == 1)
3277         {
3278           /* "$" is equivalent to "$0".  */
3279           index = 0;
3280           *endp += len;
3281         }
3282       else
3283         index = strtol (&h[1], endp, 10);
3284     }
3285
3286   return access_value_history (index);
3287 }
3288
3289 struct value *
3290 coerce_ref_if_computed (const struct value *arg)
3291 {
3292   const struct lval_funcs *funcs;
3293
3294   if (TYPE_CODE (check_typedef (value_type (arg))) != TYPE_CODE_REF)
3295     return NULL;
3296
3297   if (value_lval_const (arg) != lval_computed)
3298     return NULL;
3299
3300   funcs = value_computed_funcs (arg);
3301   if (funcs->coerce_ref == NULL)
3302     return NULL;
3303
3304   return funcs->coerce_ref (arg);
3305 }
3306
3307 /* Look at value.h for description.  */
3308
3309 struct value *
3310 readjust_indirect_value_type (struct value *value, struct type *enc_type,
3311                               struct type *original_type,
3312                               struct value *original_value)
3313 {
3314   /* Re-adjust type.  */
3315   deprecated_set_value_type (value, TYPE_TARGET_TYPE (original_type));
3316
3317   /* Add embedding info.  */
3318   set_value_enclosing_type (value, enc_type);
3319   set_value_embedded_offset (value, value_pointed_to_offset (original_value));
3320
3321   /* We may be pointing to an object of some derived type.  */
3322   return value_full_object (value, NULL, 0, 0, 0);
3323 }
3324
3325 struct value *
3326 coerce_ref (struct value *arg)
3327 {
3328   struct type *value_type_arg_tmp = check_typedef (value_type (arg));
3329   struct value *retval;
3330   struct type *enc_type;
3331
3332   retval = coerce_ref_if_computed (arg);
3333   if (retval)
3334     return retval;
3335
3336   if (TYPE_CODE (value_type_arg_tmp) != TYPE_CODE_REF)
3337     return arg;
3338
3339   enc_type = check_typedef (value_enclosing_type (arg));
3340   enc_type = TYPE_TARGET_TYPE (enc_type);
3341
3342   retval = value_at_lazy (enc_type,
3343                           unpack_pointer (value_type (arg),
3344                                           value_contents (arg)));
3345   return readjust_indirect_value_type (retval, enc_type,
3346                                        value_type_arg_tmp, arg);
3347 }
3348
3349 struct value *
3350 coerce_array (struct value *arg)
3351 {
3352   struct type *type;
3353
3354   arg = coerce_ref (arg);
3355   type = check_typedef (value_type (arg));
3356
3357   switch (TYPE_CODE (type))
3358     {
3359     case TYPE_CODE_ARRAY:
3360       if (!TYPE_VECTOR (type) && current_language->c_style_arrays)
3361         arg = value_coerce_array (arg);
3362       break;
3363     case TYPE_CODE_FUNC:
3364       arg = value_coerce_function (arg);
3365       break;
3366     }
3367   return arg;
3368 }
3369 \f
3370
3371 /* Return the return value convention that will be used for the
3372    specified type.  */
3373
3374 enum return_value_convention
3375 struct_return_convention (struct gdbarch *gdbarch,
3376                           struct value *function, struct type *value_type)
3377 {
3378   enum type_code code = TYPE_CODE (value_type);
3379
3380   if (code == TYPE_CODE_ERROR)
3381     error (_("Function return type unknown."));
3382
3383   /* Probe the architecture for the return-value convention.  */
3384   return gdbarch_return_value (gdbarch, function, value_type,
3385                                NULL, NULL, NULL);
3386 }
3387
3388 /* Return true if the function returning the specified type is using
3389    the convention of returning structures in memory (passing in the
3390    address as a hidden first parameter).  */
3391
3392 int
3393 using_struct_return (struct gdbarch *gdbarch,
3394                      struct value *function, struct type *value_type)
3395 {
3396   if (TYPE_CODE (value_type) == TYPE_CODE_VOID)
3397     /* A void return value is never in memory.  See also corresponding
3398        code in "print_return_value".  */
3399     return 0;
3400
3401   return (struct_return_convention (gdbarch, function, value_type)
3402           != RETURN_VALUE_REGISTER_CONVENTION);
3403 }
3404
3405 /* Set the initialized field in a value struct.  */
3406
3407 void
3408 set_value_initialized (struct value *val, int status)
3409 {
3410   val->initialized = status;
3411 }
3412
3413 /* Return the initialized field in a value struct.  */
3414
3415 int
3416 value_initialized (struct value *val)
3417 {
3418   return val->initialized;
3419 }
3420
3421 /* Called only from the value_contents and value_contents_all()
3422    macros, if the current data for a variable needs to be loaded into
3423    value_contents(VAL).  Fetches the data from the user's process, and
3424    clears the lazy flag to indicate that the data in the buffer is
3425    valid.
3426
3427    If the value is zero-length, we avoid calling read_memory, which
3428    would abort.  We mark the value as fetched anyway -- all 0 bytes of
3429    it.
3430
3431    This function returns a value because it is used in the
3432    value_contents macro as part of an expression, where a void would
3433    not work.  The value is ignored.  */
3434
3435 int
3436 value_fetch_lazy (struct value *val)
3437 {
3438   gdb_assert (value_lazy (val));
3439   allocate_value_contents (val);
3440   if (value_bitsize (val))
3441     {
3442       /* To read a lazy bitfield, read the entire enclosing value.  This
3443          prevents reading the same block of (possibly volatile) memory once
3444          per bitfield.  It would be even better to read only the containing
3445          word, but we have no way to record that just specific bits of a
3446          value have been fetched.  */
3447       struct type *type = check_typedef (value_type (val));
3448       enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
3449       struct value *parent = value_parent (val);
3450       LONGEST offset = value_offset (val);
3451       LONGEST num;
3452
3453       if (value_lazy (parent))
3454         value_fetch_lazy (parent);
3455
3456       if (!value_bits_valid (parent,
3457                              TARGET_CHAR_BIT * offset + value_bitpos (val),
3458                              value_bitsize (val)))
3459         set_value_optimized_out (val, 1);
3460       else if (!unpack_value_bits_as_long (value_type (val),
3461                                       value_contents_for_printing (parent),
3462                                       offset,
3463                                       value_bitpos (val),
3464                                       value_bitsize (val), parent, &num))
3465         mark_value_bytes_unavailable (val,
3466                                       value_embedded_offset (val),
3467                                       TYPE_LENGTH (type));
3468       else
3469         store_signed_integer (value_contents_raw (val), TYPE_LENGTH (type),
3470                               byte_order, num);
3471     }
3472   else if (VALUE_LVAL (val) == lval_memory)
3473     {
3474       CORE_ADDR addr = value_address (val);
3475       struct type *type = check_typedef (value_enclosing_type (val));
3476
3477       if (TYPE_LENGTH (type))
3478         read_value_memory (val, 0, value_stack (val),
3479                            addr, value_contents_all_raw (val),
3480                            TYPE_LENGTH (type));
3481     }
3482   else if (VALUE_LVAL (val) == lval_register)
3483     {
3484       struct frame_info *frame;
3485       int regnum;
3486       struct type *type = check_typedef (value_type (val));
3487       struct value *new_val = val, *mark = value_mark ();
3488
3489       /* Offsets are not supported here; lazy register values must
3490          refer to the entire register.  */
3491       gdb_assert (value_offset (val) == 0);
3492
3493       while (VALUE_LVAL (new_val) == lval_register && value_lazy (new_val))
3494         {
3495           frame = frame_find_by_id (VALUE_FRAME_ID (new_val));
3496           regnum = VALUE_REGNUM (new_val);
3497
3498           gdb_assert (frame != NULL);
3499
3500           /* Convertible register routines are used for multi-register
3501              values and for interpretation in different types
3502              (e.g. float or int from a double register).  Lazy
3503              register values should have the register's natural type,
3504              so they do not apply.  */
3505           gdb_assert (!gdbarch_convert_register_p (get_frame_arch (frame),
3506                                                    regnum, type));
3507
3508           new_val = get_frame_register_value (frame, regnum);
3509         }
3510
3511       /* If it's still lazy (for instance, a saved register on the
3512          stack), fetch it.  */
3513       if (value_lazy (new_val))
3514         value_fetch_lazy (new_val);
3515
3516       /* If the register was not saved, mark it optimized out.  */
3517       if (value_optimized_out (new_val))
3518         set_value_optimized_out (val, 1);
3519       else
3520         {
3521           set_value_lazy (val, 0);
3522           value_contents_copy (val, value_embedded_offset (val),
3523                                new_val, value_embedded_offset (new_val),
3524                                TYPE_LENGTH (type));
3525         }
3526
3527       if (frame_debug)
3528         {
3529           struct gdbarch *gdbarch;
3530           frame = frame_find_by_id (VALUE_FRAME_ID (val));
3531           regnum = VALUE_REGNUM (val);
3532           gdbarch = get_frame_arch (frame);
3533
3534           fprintf_unfiltered (gdb_stdlog,
3535                               "{ value_fetch_lazy "
3536                               "(frame=%d,regnum=%d(%s),...) ",
3537                               frame_relative_level (frame), regnum,
3538                               user_reg_map_regnum_to_name (gdbarch, regnum));
3539
3540           fprintf_unfiltered (gdb_stdlog, "->");
3541           if (value_optimized_out (new_val))
3542             fprintf_unfiltered (gdb_stdlog, " optimized out");
3543           else
3544             {
3545               int i;
3546               const gdb_byte *buf = value_contents (new_val);
3547
3548               if (VALUE_LVAL (new_val) == lval_register)
3549                 fprintf_unfiltered (gdb_stdlog, " register=%d",
3550                                     VALUE_REGNUM (new_val));
3551               else if (VALUE_LVAL (new_val) == lval_memory)
3552                 fprintf_unfiltered (gdb_stdlog, " address=%s",
3553                                     paddress (gdbarch,
3554                                               value_address (new_val)));
3555               else
3556                 fprintf_unfiltered (gdb_stdlog, " computed");
3557
3558               fprintf_unfiltered (gdb_stdlog, " bytes=");
3559               fprintf_unfiltered (gdb_stdlog, "[");
3560               for (i = 0; i < register_size (gdbarch, regnum); i++)
3561                 fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
3562               fprintf_unfiltered (gdb_stdlog, "]");
3563             }
3564
3565           fprintf_unfiltered (gdb_stdlog, " }\n");
3566         }
3567
3568       /* Dispose of the intermediate values.  This prevents
3569          watchpoints from trying to watch the saved frame pointer.  */
3570       value_free_to_mark (mark);
3571     }
3572   else if (VALUE_LVAL (val) == lval_computed
3573            && value_computed_funcs (val)->read != NULL)
3574     value_computed_funcs (val)->read (val);
3575   /* Don't call value_optimized_out on val, doing so would result in a
3576      recursive call back to value_fetch_lazy, instead check the
3577      optimized_out flag directly.  */
3578   else if (val->optimized_out)
3579     /* Keep it optimized out.  */;
3580   else
3581     internal_error (__FILE__, __LINE__, _("Unexpected lazy value type."));
3582
3583   set_value_lazy (val, 0);
3584   return 0;
3585 }
3586
3587 void
3588 _initialize_values (void)
3589 {
3590   add_cmd ("convenience", no_class, show_convenience, _("\
3591 Debugger convenience (\"$foo\") variables and functions.\n\
3592 Convenience variables are created when you assign them values;\n\
3593 thus, \"set $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\
3594 \n\
3595 A few convenience variables are given values automatically:\n\
3596 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
3597 \"$__\" holds the contents of the last address examined with \"x\"."
3598 #ifdef HAVE_PYTHON
3599 "\n\n\
3600 Convenience functions are defined via the Python API."
3601 #endif
3602            ), &showlist);
3603   add_alias_cmd ("conv", "convenience", no_class, 1, &showlist);
3604
3605   add_cmd ("values", no_set_class, show_values, _("\
3606 Elements of value history around item number IDX (or last ten)."),
3607            &showlist);
3608
3609   add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
3610 Initialize a convenience variable if necessary.\n\
3611 init-if-undefined VARIABLE = EXPRESSION\n\
3612 Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
3613 exist or does not contain a value.  The EXPRESSION is not evaluated if the\n\
3614 VARIABLE is already initialized."));
3615
3616   add_prefix_cmd ("function", no_class, function_command, _("\
3617 Placeholder command for showing help on convenience functions."),
3618                   &functionlist, "function ", 0, &cmdlist);
3619 }