gdb/value.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Low level packing and unpacking of values for GDB, the GNU Debugger.

  2.    Copyright (C) 1986-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "arch-utils.h"
  16. #include "symtab.h"
  17. #include "gdbtypes.h"
  18. #include "value.h"
  19. #include "gdbcore.h"
  20. #include "command.h"
  21. #include "gdbcmd.h"
  22. #include "target.h"
  23. #include "language.h"
  24. #include "demangle.h"
  25. #include "doublest.h"
  26. #include "regcache.h"
  27. #include "block.h"
  28. #include "dfp.h"
  29. #include "objfiles.h"
  30. #include "valprint.h"
  31. #include "cli/cli-decode.h"
  32. #include "extension.h"
  33. #include <ctype.h>
  34. #include "tracepoint.h"
  35. #include "cp-abi.h"
  36. #include "user-regs.h"

  37. /* Prototypes for exported functions.  */

  38. void _initialize_values (void);

  39. /* Definition of a user function.  */
  40. struct internal_function
  41. {
  42.   /* The name of the function.  It is a bit odd to have this in the
  43.      function itself -- the user might use a differently-named
  44.      convenience variable to hold the function.  */
  45.   char *name;

  46.   /* The handler.  */
  47.   internal_function_fn handler;

  48.   /* User data for the handler.  */
  49.   void *cookie;
  50. };

  51. /* Defines an [OFFSET, OFFSET + LENGTH) range.  */

  52. struct range
  53. {
  54.   /* Lowest offset in the range.  */
  55.   int offset;

  56.   /* Length of the range.  */
  57.   int length;
  58. };

  59. typedef struct range range_s;

  60. DEF_VEC_O(range_s);

  61. /* Returns true if the ranges defined by [offset1, offset1+len1) and
  62.    [offset2, offset2+len2) overlap.  */

  63. static int
  64. ranges_overlap (int offset1, int len1,
  65.                 int offset2, int len2)
  66. {
  67.   ULONGEST h, l;

  68.   l = max (offset1, offset2);
  69.   h = min (offset1 + len1, offset2 + len2);
  70.   return (l < h);
  71. }

  72. /* Returns true if the first argument is strictly less than the
  73.    second, useful for VEC_lower_bound.  We keep ranges sorted by
  74.    offset and coalesce overlapping and contiguous ranges, so this just
  75.    compares the starting offset.  */

  76. static int
  77. range_lessthan (const range_s *r1, const range_s *r2)
  78. {
  79.   return r1->offset < r2->offset;
  80. }

  81. /* Returns true if RANGES contains any range that overlaps [OFFSET,
  82.    OFFSET+LENGTH).  */

  83. static int
  84. ranges_contain (VEC(range_s) *ranges, int offset, int length)
  85. {
  86.   range_s what;
  87.   int i;

  88.   what.offset = offset;
  89.   what.length = length;

  90.   /* We keep ranges sorted by offset and coalesce overlapping and
  91.      contiguous ranges, so to check if a range list contains a given
  92.      range, we can do a binary search for the position the given range
  93.      would be inserted if we only considered the starting OFFSET of
  94.      ranges.  We call that position I.  Since we also have LENGTH to
  95.      care for (this is a range afterall), we need to check if the
  96.      _previous_ range overlaps the I rangeE.g.,

  97.          R
  98.          |---|
  99.        |---|    |---|  |------| ... |--|
  100.        0        1      2            N

  101.        I=1

  102.      In the case above, the binary search would return `I=1', meaning,
  103.      this OFFSET should be inserted at position 1, and the current
  104.      position 1 should be pushed further (and before 2).  But, `0'
  105.      overlaps with R.

  106.      Then we need to check if the I range overlaps the I range itself.
  107.      E.g.,

  108.               R
  109.               |---|
  110.        |---|    |---|  |-------| ... |--|
  111.        0        1      2             N

  112.        I=1
  113.   */

  114.   i = VEC_lower_bound (range_s, ranges, &what, range_lessthan);

  115.   if (i > 0)
  116.     {
  117.       struct range *bef = VEC_index (range_s, ranges, i - 1);

  118.       if (ranges_overlap (bef->offset, bef->length, offset, length))
  119.         return 1;
  120.     }

  121.   if (i < VEC_length (range_s, ranges))
  122.     {
  123.       struct range *r = VEC_index (range_s, ranges, i);

  124.       if (ranges_overlap (r->offset, r->length, offset, length))
  125.         return 1;
  126.     }

  127.   return 0;
  128. }

  129. static struct cmd_list_element *functionlist;

  130. /* Note that the fields in this structure are arranged to save a bit
  131.    of memory.  */

  132. struct value
  133. {
  134.   /* Type of value; either not an lval, or one of the various
  135.      different possible kinds of lval.  */
  136.   enum lval_type lval;

  137.   /* Is it modifiable?  Only relevant if lval != not_lval.  */
  138.   unsigned int modifiable : 1;

  139.   /* If zero, contents of this value are in the contents field.  If
  140.      nonzero, contents are in inferior.  If the lval field is lval_memory,
  141.      the contents are in inferior memory at location.address plus offset.
  142.      The lval field may also be lval_register.

  143.      WARNING: This field is used by the code which handles watchpoints
  144.      (see breakpoint.c) to decide whether a particular value can be
  145.      watched by hardware watchpoints.  If the lazy flag is set for
  146.      some member of a value chain, it is assumed that this member of
  147.      the chain doesn't need to be watched as part of watching the
  148.      value itself.  This is how GDB avoids watching the entire struct
  149.      or array when the user wants to watch a single struct member or
  150.      array element.  If you ever change the way lazy flag is set and
  151.      reset, be sure to consider this use as well!  */
  152.   unsigned int lazy : 1;

  153.   /* If value is a variable, is it initialized or not.  */
  154.   unsigned int initialized : 1;

  155.   /* If value is from the stack.  If this is set, read_stack will be
  156.      used instead of read_memory to enable extra caching.  */
  157.   unsigned int stack : 1;

  158.   /* If the value has been released.  */
  159.   unsigned int released : 1;

  160.   /* Register number if the value is from a register.  */
  161.   short regnum;

  162.   /* Location of value (if lval).  */
  163.   union
  164.   {
  165.     /* If lval == lval_memory, this is the address in the inferior.
  166.        If lval == lval_register, this is the byte offset into the
  167.        registers structure.  */
  168.     CORE_ADDR address;

  169.     /* Pointer to internal variable.  */
  170.     struct internalvar *internalvar;

  171.     /* Pointer to xmethod worker.  */
  172.     struct xmethod_worker *xm_worker;

  173.     /* If lval == lval_computed, this is a set of function pointers
  174.        to use to access and describe the value, and a closure pointer
  175.        for them to use.  */
  176.     struct
  177.     {
  178.       /* Functions to call.  */
  179.       const struct lval_funcs *funcs;

  180.       /* Closure for those functions to use.  */
  181.       void *closure;
  182.     } computed;
  183.   } location;

  184.   /* Describes offset of a value within lval of a structure in bytes.
  185.      If lval == lval_memory, this is an offset to the address.  If
  186.      lval == lval_register, this is a further offset from
  187.      location.address within the registers structure.  Note also the
  188.      member embedded_offset below.  */
  189.   int offset;

  190.   /* Only used for bitfields; number of bits contained in them.  */
  191.   int bitsize;

  192.   /* Only used for bitfields; position of start of field.  For
  193.      gdbarch_bits_big_endian=0 targets, it is the position of the LSB.  For
  194.      gdbarch_bits_big_endian=1 targets, it is the position of the MSB.  */
  195.   int bitpos;

  196.   /* The number of references to this value.  When a value is created,
  197.      the value chain holds a reference, so REFERENCE_COUNT is 1.  If
  198.      release_value is called, this value is removed from the chain but
  199.      the caller of release_value now has a reference to this value.
  200.      The caller must arrange for a call to value_free later.  */
  201.   int reference_count;

  202.   /* Only used for bitfields; the containing value.  This allows a
  203.      single read from the target when displaying multiple
  204.      bitfields.  */
  205.   struct value *parent;

  206.   /* Frame register value is relative to.  This will be described in
  207.      the lval enum above as "lval_register".  */
  208.   struct frame_id frame_id;

  209.   /* Type of the value.  */
  210.   struct type *type;

  211.   /* If a value represents a C++ object, then the `type' field gives
  212.      the object's compile-time type.  If the object actually belongs
  213.      to some class derived from `type', perhaps with other base
  214.      classes and additional members, then `type' is just a subobject
  215.      of the real thing, and the full object is probably larger than
  216.      `type' would suggest.

  217.      If `type' is a dynamic class (i.e. one with a vtable), then GDB
  218.      can actually determine the object's run-time type by looking at
  219.      the run-time type information in the vtable.  When this
  220.      information is available, we may elect to read in the entire
  221.      object, for several reasons:

  222.      - When printing the value, the user would probably rather see the
  223.      full object, not just the limited portion apparent from the
  224.      compile-time type.

  225.      - If `type' has virtual base classes, then even printing `type'
  226.      alone may require reaching outside the `type' portion of the
  227.      object to wherever the virtual base class has been stored.

  228.      When we store the entire object, `enclosing_type' is the run-time
  229.      type -- the complete object -- and `embedded_offset' is the
  230.      offset of `type' within that larger type, in bytes.  The
  231.      value_contents() macro takes `embedded_offset' into account, so
  232.      most GDB code continues to see the `type' portion of the value,
  233.      just as the inferior would.

  234.      If `type' is a pointer to an object, then `enclosing_type' is a
  235.      pointer to the object's run-time type, and `pointed_to_offset' is
  236.      the offset in bytes from the full object to the pointed-to object
  237.      -- that is, the value `embedded_offset' would have if we followed
  238.      the pointer and fetched the complete object.  (I don't really see
  239.      the point.  Why not just determine the run-time type when you
  240.      indirect, and avoid the special case?  The contents don't matter
  241.      until you indirect anyway.)

  242.      If we're not doing anything fancy, `enclosing_type' is equal to
  243.      `type', and `embedded_offset' is zero, so everything works
  244.      normally.  */
  245.   struct type *enclosing_type;
  246.   int embedded_offset;
  247.   int pointed_to_offset;

  248.   /* Values are stored in a chain, so that they can be deleted easily
  249.      over calls to the inferior.  Values assigned to internal
  250.      variables, put into the value history or exposed to Python are
  251.      taken off this list.  */
  252.   struct value *next;

  253.   /* Actual contents of the value.  Target byte-order.  NULL or not
  254.      valid if lazy is nonzero.  */
  255.   gdb_byte *contents;

  256.   /* Unavailable ranges in CONTENTS.  We mark unavailable ranges,
  257.      rather than available, since the common and default case is for a
  258.      value to be available.  This is filled in at value read time.
  259.      The unavailable ranges are tracked in bits.  Note that a contents
  260.      bit that has been optimized out doesn't really exist in the
  261.      program, so it can't be marked unavailable either.  */
  262.   VEC(range_s) *unavailable;

  263.   /* Likewise, but for optimized out contents (a chunk of the value of
  264.      a variable that does not actually exist in the program).  If LVAL
  265.      is lval_register, this is a register ($pc, $sp, etc., never a
  266.      program variable) that has not been saved in the frame.  Not
  267.      saved registers and optimized-out program variables values are
  268.      treated pretty much the same, except not-saved registers have a
  269.      different string representation and related error strings.  */
  270.   VEC(range_s) *optimized_out;
  271. };

  272. int
  273. value_bits_available (const struct value *value, int offset, int length)
  274. {
  275.   gdb_assert (!value->lazy);

  276.   return !ranges_contain (value->unavailable, offset, length);
  277. }

  278. int
  279. value_bytes_available (const struct value *value, int offset, int length)
  280. {
  281.   return value_bits_available (value,
  282.                                offset * TARGET_CHAR_BIT,
  283.                                length * TARGET_CHAR_BIT);
  284. }

  285. int
  286. value_bits_any_optimized_out (const struct value *value, int bit_offset, int bit_length)
  287. {
  288.   gdb_assert (!value->lazy);

  289.   return ranges_contain (value->optimized_out, bit_offset, bit_length);
  290. }

  291. int
  292. value_entirely_available (struct value *value)
  293. {
  294.   /* We can only tell whether the whole value is available when we try
  295.      to read it.  */
  296.   if (value->lazy)
  297.     value_fetch_lazy (value);

  298.   if (VEC_empty (range_s, value->unavailable))
  299.     return 1;
  300.   return 0;
  301. }

  302. /* Returns true if VALUE is entirely covered by RANGES.  If the value
  303.    is lazy, it'll be read now.  Note that RANGE is a pointer to
  304.    pointer because reading the value might change *RANGE.  */

  305. static int
  306. value_entirely_covered_by_range_vector (struct value *value,
  307.                                         VEC(range_s) **ranges)
  308. {
  309.   /* We can only tell whether the whole value is optimized out /
  310.      unavailable when we try to read it.  */
  311.   if (value->lazy)
  312.     value_fetch_lazy (value);

  313.   if (VEC_length (range_s, *ranges) == 1)
  314.     {
  315.       struct range *t = VEC_index (range_s, *ranges, 0);

  316.       if (t->offset == 0
  317.           && t->length == (TARGET_CHAR_BIT
  318.                            * TYPE_LENGTH (value_enclosing_type (value))))
  319.         return 1;
  320.     }

  321.   return 0;
  322. }

  323. int
  324. value_entirely_unavailable (struct value *value)
  325. {
  326.   return value_entirely_covered_by_range_vector (value, &value->unavailable);
  327. }

  328. int
  329. value_entirely_optimized_out (struct value *value)
  330. {
  331.   return value_entirely_covered_by_range_vector (value, &value->optimized_out);
  332. }

  333. /* Insert into the vector pointed to by VECTORP the bit range starting of
  334.    OFFSET bits, and extending for the next LENGTH bits.  */

  335. static void
  336. insert_into_bit_range_vector (VEC(range_s) **vectorp, int offset, int length)
  337. {
  338.   range_s newr;
  339.   int i;

  340.   /* Insert the range sorted.  If there's overlap or the new range
  341.      would be contiguous with an existing range, merge.  */

  342.   newr.offset = offset;
  343.   newr.length = length;

  344.   /* Do a binary search for the position the given range would be
  345.      inserted if we only considered the starting OFFSET of ranges.
  346.      Call that position I.  Since we also have LENGTH to care for
  347.      (this is a range afterall), we need to check if the _previous_
  348.      range overlaps the I rangeE.g., calling R the new range:

  349.        #1 - overlaps with previous

  350.            R
  351.            |-...-|
  352.          |---|     |---|  |------| ... |--|
  353.          0         1      2            N

  354.          I=1

  355.      In the case #1 above, the binary search would return `I=1',
  356.      meaning, this OFFSET should be inserted at position 1, and the
  357.      current position 1 should be pushed further (and become 2).  But,
  358.      note that `0' overlaps with R, so we want to merge them.

  359.      A similar consideration needs to be taken if the new range would
  360.      be contiguous with the previous range:

  361.        #2 - contiguous with previous

  362.             R
  363.             |-...-|
  364.          |--|       |---|  |------| ... |--|
  365.          0          1      2            N

  366.          I=1

  367.      If there's no overlap with the previous range, as in:

  368.        #3 - not overlapping and not contiguous

  369.                R
  370.                |-...-|
  371.           |--|         |---|  |------| ... |--|
  372.           0            1      2            N

  373.          I=1

  374.      or if I is 0:

  375.        #4 - R is the range with lowest offset

  376.           R
  377.          |-...-|
  378.                  |--|       |---|  |------| ... |--|
  379.                  0          1      2            N

  380.          I=0

  381.      ... we just push the new range to I.

  382.      All the 4 cases above need to consider that the new range may
  383.      also overlap several of the ranges that follow, or that R may be
  384.      contiguous with the following range, and merge.  E.g.,

  385.        #5 - overlapping following ranges

  386.           R
  387.          |------------------------|
  388.                  |--|       |---|  |------| ... |--|
  389.                  0          1      2            N

  390.          I=0

  391.        or:

  392.             R
  393.             |-------|
  394.          |--|       |---|  |------| ... |--|
  395.          0          1      2            N

  396.          I=1

  397.   */

  398.   i = VEC_lower_bound (range_s, *vectorp, &newr, range_lessthan);
  399.   if (i > 0)
  400.     {
  401.       struct range *bef = VEC_index (range_s, *vectorp, i - 1);

  402.       if (ranges_overlap (bef->offset, bef->length, offset, length))
  403.         {
  404.           /* #1 */
  405.           ULONGEST l = min (bef->offset, offset);
  406.           ULONGEST h = max (bef->offset + bef->length, offset + length);

  407.           bef->offset = l;
  408.           bef->length = h - l;
  409.           i--;
  410.         }
  411.       else if (offset == bef->offset + bef->length)
  412.         {
  413.           /* #2 */
  414.           bef->length += length;
  415.           i--;
  416.         }
  417.       else
  418.         {
  419.           /* #3 */
  420.           VEC_safe_insert (range_s, *vectorp, i, &newr);
  421.         }
  422.     }
  423.   else
  424.     {
  425.       /* #4 */
  426.       VEC_safe_insert (range_s, *vectorp, i, &newr);
  427.     }

  428.   /* Check whether the ranges following the one we've just added or
  429.      touched can be folded in (#5 above).  */
  430.   if (i + 1 < VEC_length (range_s, *vectorp))
  431.     {
  432.       struct range *t;
  433.       struct range *r;
  434.       int removed = 0;
  435.       int next = i + 1;

  436.       /* Get the range we just touched.  */
  437.       t = VEC_index (range_s, *vectorp, i);
  438.       removed = 0;

  439.       i = next;
  440.       for (; VEC_iterate (range_s, *vectorp, i, r); i++)
  441.         if (r->offset <= t->offset + t->length)
  442.           {
  443.             ULONGEST l, h;

  444.             l = min (t->offset, r->offset);
  445.             h = max (t->offset + t->length, r->offset + r->length);

  446.             t->offset = l;
  447.             t->length = h - l;

  448.             removed++;
  449.           }
  450.         else
  451.           {
  452.             /* If we couldn't merge this one, we won't be able to
  453.                merge following ones either, since the ranges are
  454.                always sorted by OFFSET.  */
  455.             break;
  456.           }

  457.       if (removed != 0)
  458.         VEC_block_remove (range_s, *vectorp, next, removed);
  459.     }
  460. }

  461. void
  462. mark_value_bits_unavailable (struct value *value, int offset, int length)
  463. {
  464.   insert_into_bit_range_vector (&value->unavailable, offset, length);
  465. }

  466. void
  467. mark_value_bytes_unavailable (struct value *value, int offset, int length)
  468. {
  469.   mark_value_bits_unavailable (value,
  470.                                offset * TARGET_CHAR_BIT,
  471.                                length * TARGET_CHAR_BIT);
  472. }

  473. /* Find the first range in RANGES that overlaps the range defined by
  474.    OFFSET and LENGTH, starting at element POS in the RANGES vector,
  475.    Returns the index into RANGES where such overlapping range was
  476.    found, or -1 if none was found.  */

  477. static int
  478. find_first_range_overlap (VEC(range_s) *ranges, int pos,
  479.                           int offset, int length)
  480. {
  481.   range_s *r;
  482.   int i;

  483.   for (i = pos; VEC_iterate (range_s, ranges, i, r); i++)
  484.     if (ranges_overlap (r->offset, r->length, offset, length))
  485.       return i;

  486.   return -1;
  487. }

  488. /* Compare LENGTH_BITS of memory at PTR1 + OFFSET1_BITS with the memory at
  489.    PTR2 + OFFSET2_BITS.  Return 0 if the memory is the same, otherwise
  490.    return non-zero.

  491.    It must always be the case that:
  492.      OFFSET1_BITS % TARGET_CHAR_BIT == OFFSET2_BITS % TARGET_CHAR_BIT

  493.    It is assumed that memory can be accessed from:
  494.      PTR + (OFFSET_BITS / TARGET_CHAR_BIT)
  495.    to:
  496.      PTR + ((OFFSET_BITS + LENGTH_BITS + TARGET_CHAR_BIT - 1)
  497.             / TARGET_CHAR_BIT)  */
  498. static int
  499. memcmp_with_bit_offsets (const gdb_byte *ptr1, size_t offset1_bits,
  500.                          const gdb_byte *ptr2, size_t offset2_bits,
  501.                          size_t length_bits)
  502. {
  503.   gdb_assert (offset1_bits % TARGET_CHAR_BIT
  504.               == offset2_bits % TARGET_CHAR_BIT);

  505.   if (offset1_bits % TARGET_CHAR_BIT != 0)
  506.     {
  507.       size_t bits;
  508.       gdb_byte mask, b1, b2;

  509.       /* The offset from the base pointers PTR1 and PTR2 is not a complete
  510.          number of bytesA number of bits up to either the next exact
  511.          byte boundary, or LENGTH_BITS (which ever is sooner) will be
  512.          compared.  */
  513.       bits = TARGET_CHAR_BIT - offset1_bits % TARGET_CHAR_BIT;
  514.       gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
  515.       mask = (1 << bits) - 1;

  516.       if (length_bits < bits)
  517.         {
  518.           mask &= ~(gdb_byte) ((1 << (bits - length_bits)) - 1);
  519.           bits = length_bits;
  520.         }

  521.       /* Now load the two bytes and mask off the bits we care about.  */
  522.       b1 = *(ptr1 + offset1_bits / TARGET_CHAR_BIT) & mask;
  523.       b2 = *(ptr2 + offset2_bits / TARGET_CHAR_BIT) & mask;

  524.       if (b1 != b2)
  525.         return 1;

  526.       /* Now update the length and offsets to take account of the bits
  527.          we've just compared.  */
  528.       length_bits -= bits;
  529.       offset1_bits += bits;
  530.       offset2_bits += bits;
  531.     }

  532.   if (length_bits % TARGET_CHAR_BIT != 0)
  533.     {
  534.       size_t bits;
  535.       size_t o1, o2;
  536.       gdb_byte mask, b1, b2;

  537.       /* The length is not an exact number of bytes.  After the previous
  538.          IF.. block then the offsets are byte aligned, or the
  539.          length is zero (in which case this code is not reached).  Compare
  540.          a number of bits at the end of the region, starting from an exact
  541.          byte boundary.  */
  542.       bits = length_bits % TARGET_CHAR_BIT;
  543.       o1 = offset1_bits + length_bits - bits;
  544.       o2 = offset2_bits + length_bits - bits;

  545.       gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
  546.       mask = ((1 << bits) - 1) << (TARGET_CHAR_BIT - bits);

  547.       gdb_assert (o1 % TARGET_CHAR_BIT == 0);
  548.       gdb_assert (o2 % TARGET_CHAR_BIT == 0);

  549.       b1 = *(ptr1 + o1 / TARGET_CHAR_BIT) & mask;
  550.       b2 = *(ptr2 + o2 / TARGET_CHAR_BIT) & mask;

  551.       if (b1 != b2)
  552.         return 1;

  553.       length_bits -= bits;
  554.     }

  555.   if (length_bits > 0)
  556.     {
  557.       /* We've now taken care of any stray "bits" at the start, or end of
  558.          the region to compare, the remainder can be covered with a simple
  559.          memcmp.  */
  560.       gdb_assert (offset1_bits % TARGET_CHAR_BIT == 0);
  561.       gdb_assert (offset2_bits % TARGET_CHAR_BIT == 0);
  562.       gdb_assert (length_bits % TARGET_CHAR_BIT == 0);

  563.       return memcmp (ptr1 + offset1_bits / TARGET_CHAR_BIT,
  564.                      ptr2 + offset2_bits / TARGET_CHAR_BIT,
  565.                      length_bits / TARGET_CHAR_BIT);
  566.     }

  567.   /* Length is zero, regions match.  */
  568.   return 0;
  569. }

  570. /* Helper struct for find_first_range_overlap_and_match and
  571.    value_contents_bits_eq.  Keep track of which slot of a given ranges
  572.    vector have we last looked at.  */

  573. struct ranges_and_idx
  574. {
  575.   /* The ranges.  */
  576.   VEC(range_s) *ranges;

  577.   /* The range we've last found in RANGES.  Given ranges are sorted,
  578.      we can start the next lookup here.  */
  579.   int idx;
  580. };

  581. /* Helper function for value_contents_bits_eq.  Compare LENGTH bits of
  582.    RP1's ranges starting at OFFSET1 bits with LENGTH bits of RP2's
  583.    ranges starting at OFFSET2 bits.  Return true if the ranges match
  584.    and fill in *L and *H with the overlapping window relative to
  585.    (both) OFFSET1 or OFFSET2.  */

  586. static int
  587. find_first_range_overlap_and_match (struct ranges_and_idx *rp1,
  588.                                     struct ranges_and_idx *rp2,
  589.                                     int offset1, int offset2,
  590.                                     int length, ULONGEST *l, ULONGEST *h)
  591. {
  592.   rp1->idx = find_first_range_overlap (rp1->ranges, rp1->idx,
  593.                                        offset1, length);
  594.   rp2->idx = find_first_range_overlap (rp2->ranges, rp2->idx,
  595.                                        offset2, length);

  596.   if (rp1->idx == -1 && rp2->idx == -1)
  597.     {
  598.       *l = length;
  599.       *h = length;
  600.       return 1;
  601.     }
  602.   else if (rp1->idx == -1 || rp2->idx == -1)
  603.     return 0;
  604.   else
  605.     {
  606.       range_s *r1, *r2;
  607.       ULONGEST l1, h1;
  608.       ULONGEST l2, h2;

  609.       r1 = VEC_index (range_s, rp1->ranges, rp1->idx);
  610.       r2 = VEC_index (range_s, rp2->ranges, rp2->idx);

  611.       /* Get the unavailable windows intersected by the incoming
  612.          ranges.  The first and last ranges that overlap the argument
  613.          range may be wider than said incoming arguments ranges.  */
  614.       l1 = max (offset1, r1->offset);
  615.       h1 = min (offset1 + length, r1->offset + r1->length);

  616.       l2 = max (offset2, r2->offset);
  617.       h2 = min (offset2 + length, offset2 + r2->length);

  618.       /* Make them relative to the respective start offsets, so we can
  619.          compare them for equality.  */
  620.       l1 -= offset1;
  621.       h1 -= offset1;

  622.       l2 -= offset2;
  623.       h2 -= offset2;

  624.       /* Different ranges, no match.  */
  625.       if (l1 != l2 || h1 != h2)
  626.         return 0;

  627.       *h = h1;
  628.       *l = l1;
  629.       return 1;
  630.     }
  631. }

  632. /* Helper function for value_contents_eq.  The only difference is that
  633.    this function is bit rather than byte based.

  634.    Compare LENGTH bits of VAL1's contents starting at OFFSET1 bits
  635.    with LENGTH bits of VAL2's contents starting at OFFSET2 bits.
  636.    Return true if the available bits match.  */

  637. static int
  638. value_contents_bits_eq (const struct value *val1, int offset1,
  639.                         const struct value *val2, int offset2,
  640.                         int length)
  641. {
  642.   /* Each array element corresponds to a ranges source (unavailable,
  643.      optimized out).  '1' is for VAL1, '2' for VAL2.  */
  644.   struct ranges_and_idx rp1[2], rp2[2];

  645.   /* See function description in value.h.  */
  646.   gdb_assert (!val1->lazy && !val2->lazy);

  647.   /* We shouldn't be trying to compare past the end of the values.  */
  648.   gdb_assert (offset1 + length
  649.               <= TYPE_LENGTH (val1->enclosing_type) * TARGET_CHAR_BIT);
  650.   gdb_assert (offset2 + length
  651.               <= TYPE_LENGTH (val2->enclosing_type) * TARGET_CHAR_BIT);

  652.   memset (&rp1, 0, sizeof (rp1));
  653.   memset (&rp2, 0, sizeof (rp2));
  654.   rp1[0].ranges = val1->unavailable;
  655.   rp2[0].ranges = val2->unavailable;
  656.   rp1[1].ranges = val1->optimized_out;
  657.   rp2[1].ranges = val2->optimized_out;

  658.   while (length > 0)
  659.     {
  660.       ULONGEST l = 0, h = 0; /* init for gcc -Wall */
  661.       int i;

  662.       for (i = 0; i < 2; i++)
  663.         {
  664.           ULONGEST l_tmp, h_tmp;

  665.           /* The contents only match equal if the invalid/unavailable
  666.              contents ranges match as well.  */
  667.           if (!find_first_range_overlap_and_match (&rp1[i], &rp2[i],
  668.                                                    offset1, offset2, length,
  669.                                                    &l_tmp, &h_tmp))
  670.             return 0;

  671.           /* We're interested in the lowest/first range found.  */
  672.           if (i == 0 || l_tmp < l)
  673.             {
  674.               l = l_tmp;
  675.               h = h_tmp;
  676.             }
  677.         }

  678.       /* Compare the available/valid contents.  */
  679.       if (memcmp_with_bit_offsets (val1->contents, offset1,
  680.                                    val2->contents, offset2, l) != 0)
  681.         return 0;

  682.       length -= h;
  683.       offset1 += h;
  684.       offset2 += h;
  685.     }

  686.   return 1;
  687. }

  688. int
  689. value_contents_eq (const struct value *val1, int offset1,
  690.                    const struct value *val2, int offset2,
  691.                    int length)
  692. {
  693.   return value_contents_bits_eq (val1, offset1 * TARGET_CHAR_BIT,
  694.                                  val2, offset2 * TARGET_CHAR_BIT,
  695.                                  length * TARGET_CHAR_BIT);
  696. }

  697. /* Prototypes for local functions.  */

  698. static void show_values (char *, int);

  699. static void show_convenience (char *, int);


  700. /* The value-history records all the values printed
  701.    by print commands during this session.  Each chunk
  702.    records 60 consecutive values.  The first chunk on
  703.    the chain records the most recent values.
  704.    The total number of values is in value_history_count.  */

  705. #define VALUE_HISTORY_CHUNK 60

  706. struct value_history_chunk
  707.   {
  708.     struct value_history_chunk *next;
  709.     struct value *values[VALUE_HISTORY_CHUNK];
  710.   };

  711. /* Chain of chunks now in use.  */

  712. static struct value_history_chunk *value_history_chain;

  713. static int value_history_count;        /* Abs number of last entry stored.  */


  714. /* List of all value objects currently allocated
  715.    (except for those released by calls to release_value)
  716.    This is so they can be freed after each command.  */

  717. static struct value *all_values;

  718. /* Allocate a lazy value for type TYPE.  Its actual content is
  719.    "lazily" allocated too: the content field of the return value is
  720.    NULL; it will be allocated when it is fetched from the target.  */

  721. struct value *
  722. allocate_value_lazy (struct type *type)
  723. {
  724.   struct value *val;

  725.   /* Call check_typedef on our type to make sure that, if TYPE
  726.      is a TYPE_CODE_TYPEDEF, its length is set to the length
  727.      of the target type instead of zero.  However, we do not
  728.      replace the typedef type by the target type, because we want
  729.      to keep the typedef in order to be able to set the VAL's type
  730.      description correctly.  */
  731.   check_typedef (type);

  732.   val = (struct value *) xzalloc (sizeof (struct value));
  733.   val->contents = NULL;
  734.   val->next = all_values;
  735.   all_values = val;
  736.   val->type = type;
  737.   val->enclosing_type = type;
  738.   VALUE_LVAL (val) = not_lval;
  739.   val->location.address = 0;
  740.   VALUE_FRAME_ID (val) = null_frame_id;
  741.   val->offset = 0;
  742.   val->bitpos = 0;
  743.   val->bitsize = 0;
  744.   VALUE_REGNUM (val) = -1;
  745.   val->lazy = 1;
  746.   val->embedded_offset = 0;
  747.   val->pointed_to_offset = 0;
  748.   val->modifiable = 1;
  749.   val->initialized = 1/* Default to initialized.  */

  750.   /* Values start out on the all_values chain.  */
  751.   val->reference_count = 1;

  752.   return val;
  753. }

  754. /* Allocate the contents of VAL if it has not been allocated yet.  */

  755. static void
  756. allocate_value_contents (struct value *val)
  757. {
  758.   if (!val->contents)
  759.     val->contents = (gdb_byte *) xzalloc (TYPE_LENGTH (val->enclosing_type));
  760. }

  761. /* Allocate a  value  and its contents for type TYPE.  */

  762. struct value *
  763. allocate_value (struct type *type)
  764. {
  765.   struct value *val = allocate_value_lazy (type);

  766.   allocate_value_contents (val);
  767.   val->lazy = 0;
  768.   return val;
  769. }

  770. /* Allocate a  value  that has the correct length
  771.    for COUNT repetitions of type TYPE.  */

  772. struct value *
  773. allocate_repeat_value (struct type *type, int count)
  774. {
  775.   int low_bound = current_language->string_lower_bound;                /* ??? */
  776.   /* FIXME-type-allocation: need a way to free this type when we are
  777.      done with it.  */
  778.   struct type *array_type
  779.     = lookup_array_range_type (type, low_bound, count + low_bound - 1);

  780.   return allocate_value (array_type);
  781. }

  782. struct value *
  783. allocate_computed_value (struct type *type,
  784.                          const struct lval_funcs *funcs,
  785.                          void *closure)
  786. {
  787.   struct value *v = allocate_value_lazy (type);

  788.   VALUE_LVAL (v) = lval_computed;
  789.   v->location.computed.funcs = funcs;
  790.   v->location.computed.closure = closure;

  791.   return v;
  792. }

  793. /* Allocate NOT_LVAL value for type TYPE being OPTIMIZED_OUT.  */

  794. struct value *
  795. allocate_optimized_out_value (struct type *type)
  796. {
  797.   struct value *retval = allocate_value_lazy (type);

  798.   mark_value_bytes_optimized_out (retval, 0, TYPE_LENGTH (type));
  799.   set_value_lazy (retval, 0);
  800.   return retval;
  801. }

  802. /* Accessor methods.  */

  803. struct value *
  804. value_next (struct value *value)
  805. {
  806.   return value->next;
  807. }

  808. struct type *
  809. value_type (const struct value *value)
  810. {
  811.   return value->type;
  812. }
  813. void
  814. deprecated_set_value_type (struct value *value, struct type *type)
  815. {
  816.   value->type = type;
  817. }

  818. int
  819. value_offset (const struct value *value)
  820. {
  821.   return value->offset;
  822. }
  823. void
  824. set_value_offset (struct value *value, int offset)
  825. {
  826.   value->offset = offset;
  827. }

  828. int
  829. value_bitpos (const struct value *value)
  830. {
  831.   return value->bitpos;
  832. }
  833. void
  834. set_value_bitpos (struct value *value, int bit)
  835. {
  836.   value->bitpos = bit;
  837. }

  838. int
  839. value_bitsize (const struct value *value)
  840. {
  841.   return value->bitsize;
  842. }
  843. void
  844. set_value_bitsize (struct value *value, int bit)
  845. {
  846.   value->bitsize = bit;
  847. }

  848. struct value *
  849. value_parent (struct value *value)
  850. {
  851.   return value->parent;
  852. }

  853. /* See value.h.  */

  854. void
  855. set_value_parent (struct value *value, struct value *parent)
  856. {
  857.   struct value *old = value->parent;

  858.   value->parent = parent;
  859.   if (parent != NULL)
  860.     value_incref (parent);
  861.   value_free (old);
  862. }

  863. gdb_byte *
  864. value_contents_raw (struct value *value)
  865. {
  866.   allocate_value_contents (value);
  867.   return value->contents + value->embedded_offset;
  868. }

  869. gdb_byte *
  870. value_contents_all_raw (struct value *value)
  871. {
  872.   allocate_value_contents (value);
  873.   return value->contents;
  874. }

  875. struct type *
  876. value_enclosing_type (struct value *value)
  877. {
  878.   return value->enclosing_type;
  879. }

  880. /* Look at value.h for description.  */

  881. struct type *
  882. value_actual_type (struct value *value, int resolve_simple_types,
  883.                    int *real_type_found)
  884. {
  885.   struct value_print_options opts;
  886.   struct type *result;

  887.   get_user_print_options (&opts);

  888.   if (real_type_found)
  889.     *real_type_found = 0;
  890.   result = value_type (value);
  891.   if (opts.objectprint)
  892.     {
  893.       /* If result's target type is TYPE_CODE_STRUCT, proceed to
  894.          fetch its rtti type.  */
  895.       if ((TYPE_CODE (result) == TYPE_CODE_PTR
  896.           || TYPE_CODE (result) == TYPE_CODE_REF)
  897.           && TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (result)))
  898.              == TYPE_CODE_STRUCT)
  899.         {
  900.           struct type *real_type;

  901.           real_type = value_rtti_indirect_type (value, NULL, NULL, NULL);
  902.           if (real_type)
  903.             {
  904.               if (real_type_found)
  905.                 *real_type_found = 1;
  906.               result = real_type;
  907.             }
  908.         }
  909.       else if (resolve_simple_types)
  910.         {
  911.           if (real_type_found)
  912.             *real_type_found = 1;
  913.           result = value_enclosing_type (value);
  914.         }
  915.     }

  916.   return result;
  917. }

  918. void
  919. error_value_optimized_out (void)
  920. {
  921.   error (_("value has been optimized out"));
  922. }

  923. static void
  924. require_not_optimized_out (const struct value *value)
  925. {
  926.   if (!VEC_empty (range_s, value->optimized_out))
  927.     {
  928.       if (value->lval == lval_register)
  929.         error (_("register has not been saved in frame"));
  930.       else
  931.         error_value_optimized_out ();
  932.     }
  933. }

  934. static void
  935. require_available (const struct value *value)
  936. {
  937.   if (!VEC_empty (range_s, value->unavailable))
  938.     throw_error (NOT_AVAILABLE_ERROR, _("value is not available"));
  939. }

  940. const gdb_byte *
  941. value_contents_for_printing (struct value *value)
  942. {
  943.   if (value->lazy)
  944.     value_fetch_lazy (value);
  945.   return value->contents;
  946. }

  947. const gdb_byte *
  948. value_contents_for_printing_const (const struct value *value)
  949. {
  950.   gdb_assert (!value->lazy);
  951.   return value->contents;
  952. }

  953. const gdb_byte *
  954. value_contents_all (struct value *value)
  955. {
  956.   const gdb_byte *result = value_contents_for_printing (value);
  957.   require_not_optimized_out (value);
  958.   require_available (value);
  959.   return result;
  960. }

  961. /* Copy ranges in SRC_RANGE that overlap [SRC_BIT_OFFSET,
  962.    SRC_BIT_OFFSET+BIT_LENGTH) ranges into *DST_RANGE, adjusted.  */

  963. static void
  964. ranges_copy_adjusted (VEC (range_s) **dst_range, int dst_bit_offset,
  965.                       VEC (range_s) *src_range, int src_bit_offset,
  966.                       int bit_length)
  967. {
  968.   range_s *r;
  969.   int i;

  970.   for (i = 0; VEC_iterate (range_s, src_range, i, r); i++)
  971.     {
  972.       ULONGEST h, l;

  973.       l = max (r->offset, src_bit_offset);
  974.       h = min (r->offset + r->length, src_bit_offset + bit_length);

  975.       if (l < h)
  976.         insert_into_bit_range_vector (dst_range,
  977.                                       dst_bit_offset + (l - src_bit_offset),
  978.                                       h - l);
  979.     }
  980. }

  981. /* Copy the ranges metadata in SRC that overlaps [SRC_BIT_OFFSET,
  982.    SRC_BIT_OFFSET+BIT_LENGTH) into DST, adjusted.  */

  983. static void
  984. value_ranges_copy_adjusted (struct value *dst, int dst_bit_offset,
  985.                             const struct value *src, int src_bit_offset,
  986.                             int bit_length)
  987. {
  988.   ranges_copy_adjusted (&dst->unavailable, dst_bit_offset,
  989.                         src->unavailable, src_bit_offset,
  990.                         bit_length);
  991.   ranges_copy_adjusted (&dst->optimized_out, dst_bit_offset,
  992.                         src->optimized_out, src_bit_offset,
  993.                         bit_length);
  994. }

  995. /* Copy LENGTH bytes of SRC value's (all) contents
  996.    (value_contents_all) starting at SRC_OFFSET, into DST value's (all)
  997.    contents, starting at DST_OFFSET.  If unavailable contents are
  998.    being copied from SRC, the corresponding DST contents are marked
  999.    unavailable accordingly.  Neither DST nor SRC may be lazy
  1000.    values.

  1001.    It is assumed the contents of DST in the [DST_OFFSET,
  1002.    DST_OFFSET+LENGTH) range are wholly available.  */

  1003. void
  1004. value_contents_copy_raw (struct value *dst, int dst_offset,
  1005.                          struct value *src, int src_offset, int length)
  1006. {
  1007.   range_s *r;
  1008.   int i;
  1009.   int src_bit_offset, dst_bit_offset, bit_length;

  1010.   /* A lazy DST would make that this copy operation useless, since as
  1011.      soon as DST's contents were un-lazied (by a later value_contents
  1012.      call, say), the contents would be overwritten.  A lazy SRC would
  1013.      mean we'd be copying garbage.  */
  1014.   gdb_assert (!dst->lazy && !src->lazy);

  1015.   /* The overwritten DST range gets unavailability ORed in, not
  1016.      replaced.  Make sure to remember to implement replacing if it
  1017.      turns out actually necessary.  */
  1018.   gdb_assert (value_bytes_available (dst, dst_offset, length));
  1019.   gdb_assert (!value_bits_any_optimized_out (dst,
  1020.                                              TARGET_CHAR_BIT * dst_offset,
  1021.                                              TARGET_CHAR_BIT * length));

  1022.   /* Copy the data.  */
  1023.   memcpy (value_contents_all_raw (dst) + dst_offset,
  1024.           value_contents_all_raw (src) + src_offset,
  1025.           length);

  1026.   /* Copy the meta-data, adjusted.  */
  1027.   src_bit_offset = src_offset * TARGET_CHAR_BIT;
  1028.   dst_bit_offset = dst_offset * TARGET_CHAR_BIT;
  1029.   bit_length = length * TARGET_CHAR_BIT;

  1030.   value_ranges_copy_adjusted (dst, dst_bit_offset,
  1031.                               src, src_bit_offset,
  1032.                               bit_length);
  1033. }

  1034. /* Copy LENGTH bytes of SRC value's (all) contents
  1035.    (value_contents_all) starting at SRC_OFFSET byte, into DST value's
  1036.    (all) contents, starting at DST_OFFSET.  If unavailable contents
  1037.    are being copied from SRC, the corresponding DST contents are
  1038.    marked unavailable accordingly.  DST must not be lazy.  If SRC is
  1039.    lazy, it will be fetched now.

  1040.    It is assumed the contents of DST in the [DST_OFFSET,
  1041.    DST_OFFSET+LENGTH) range are wholly available.  */

  1042. void
  1043. value_contents_copy (struct value *dst, int dst_offset,
  1044.                      struct value *src, int src_offset, int length)
  1045. {
  1046.   if (src->lazy)
  1047.     value_fetch_lazy (src);

  1048.   value_contents_copy_raw (dst, dst_offset, src, src_offset, length);
  1049. }

  1050. int
  1051. value_lazy (struct value *value)
  1052. {
  1053.   return value->lazy;
  1054. }

  1055. void
  1056. set_value_lazy (struct value *value, int val)
  1057. {
  1058.   value->lazy = val;
  1059. }

  1060. int
  1061. value_stack (struct value *value)
  1062. {
  1063.   return value->stack;
  1064. }

  1065. void
  1066. set_value_stack (struct value *value, int val)
  1067. {
  1068.   value->stack = val;
  1069. }

  1070. const gdb_byte *
  1071. value_contents (struct value *value)
  1072. {
  1073.   const gdb_byte *result = value_contents_writeable (value);
  1074.   require_not_optimized_out (value);
  1075.   require_available (value);
  1076.   return result;
  1077. }

  1078. gdb_byte *
  1079. value_contents_writeable (struct value *value)
  1080. {
  1081.   if (value->lazy)
  1082.     value_fetch_lazy (value);
  1083.   return value_contents_raw (value);
  1084. }

  1085. int
  1086. value_optimized_out (struct value *value)
  1087. {
  1088.   /* We can only know if a value is optimized out once we have tried to
  1089.      fetch it.  */
  1090.   if (VEC_empty (range_s, value->optimized_out) && value->lazy)
  1091.     value_fetch_lazy (value);

  1092.   return !VEC_empty (range_s, value->optimized_out);
  1093. }

  1094. /* Mark contents of VALUE as optimized out, starting at OFFSET bytes, and
  1095.    the following LENGTH bytes.  */

  1096. void
  1097. mark_value_bytes_optimized_out (struct value *value, int offset, int length)
  1098. {
  1099.   mark_value_bits_optimized_out (value,
  1100.                                  offset * TARGET_CHAR_BIT,
  1101.                                  length * TARGET_CHAR_BIT);
  1102. }

  1103. /* See value.h.  */

  1104. void
  1105. mark_value_bits_optimized_out (struct value *value, int offset, int length)
  1106. {
  1107.   insert_into_bit_range_vector (&value->optimized_out, offset, length);
  1108. }

  1109. int
  1110. value_bits_synthetic_pointer (const struct value *value,
  1111.                               int offset, int length)
  1112. {
  1113.   if (value->lval != lval_computed
  1114.       || !value->location.computed.funcs->check_synthetic_pointer)
  1115.     return 0;
  1116.   return value->location.computed.funcs->check_synthetic_pointer (value,
  1117.                                                                   offset,
  1118.                                                                   length);
  1119. }

  1120. int
  1121. value_embedded_offset (struct value *value)
  1122. {
  1123.   return value->embedded_offset;
  1124. }

  1125. void
  1126. set_value_embedded_offset (struct value *value, int val)
  1127. {
  1128.   value->embedded_offset = val;
  1129. }

  1130. int
  1131. value_pointed_to_offset (struct value *value)
  1132. {
  1133.   return value->pointed_to_offset;
  1134. }

  1135. void
  1136. set_value_pointed_to_offset (struct value *value, int val)
  1137. {
  1138.   value->pointed_to_offset = val;
  1139. }

  1140. const struct lval_funcs *
  1141. value_computed_funcs (const struct value *v)
  1142. {
  1143.   gdb_assert (value_lval_const (v) == lval_computed);

  1144.   return v->location.computed.funcs;
  1145. }

  1146. void *
  1147. value_computed_closure (const struct value *v)
  1148. {
  1149.   gdb_assert (v->lval == lval_computed);

  1150.   return v->location.computed.closure;
  1151. }

  1152. enum lval_type *
  1153. deprecated_value_lval_hack (struct value *value)
  1154. {
  1155.   return &value->lval;
  1156. }

  1157. enum lval_type
  1158. value_lval_const (const struct value *value)
  1159. {
  1160.   return value->lval;
  1161. }

  1162. CORE_ADDR
  1163. value_address (const struct value *value)
  1164. {
  1165.   if (value->lval == lval_internalvar
  1166.       || value->lval == lval_internalvar_component
  1167.       || value->lval == lval_xcallable)
  1168.     return 0;
  1169.   if (value->parent != NULL)
  1170.     return value_address (value->parent) + value->offset;
  1171.   else
  1172.     return value->location.address + value->offset;
  1173. }

  1174. CORE_ADDR
  1175. value_raw_address (struct value *value)
  1176. {
  1177.   if (value->lval == lval_internalvar
  1178.       || value->lval == lval_internalvar_component
  1179.       || value->lval == lval_xcallable)
  1180.     return 0;
  1181.   return value->location.address;
  1182. }

  1183. void
  1184. set_value_address (struct value *value, CORE_ADDR addr)
  1185. {
  1186.   gdb_assert (value->lval != lval_internalvar
  1187.               && value->lval != lval_internalvar_component
  1188.               && value->lval != lval_xcallable);
  1189.   value->location.address = addr;
  1190. }

  1191. struct internalvar **
  1192. deprecated_value_internalvar_hack (struct value *value)
  1193. {
  1194.   return &value->location.internalvar;
  1195. }

  1196. struct frame_id *
  1197. deprecated_value_frame_id_hack (struct value *value)
  1198. {
  1199.   return &value->frame_id;
  1200. }

  1201. short *
  1202. deprecated_value_regnum_hack (struct value *value)
  1203. {
  1204.   return &value->regnum;
  1205. }

  1206. int
  1207. deprecated_value_modifiable (struct value *value)
  1208. {
  1209.   return value->modifiable;
  1210. }

  1211. /* Return a mark in the value chain.  All values allocated after the
  1212.    mark is obtained (except for those released) are subject to being freed
  1213.    if a subsequent value_free_to_mark is passed the mark.  */
  1214. struct value *
  1215. value_mark (void)
  1216. {
  1217.   return all_values;
  1218. }

  1219. /* Take a reference to VALVAL will not be deallocated until all
  1220.    references are released.  */

  1221. void
  1222. value_incref (struct value *val)
  1223. {
  1224.   val->reference_count++;
  1225. }

  1226. /* Release a reference to VAL, which was acquired with value_incref.
  1227.    This function is also called to deallocate values from the value
  1228.    chain.  */

  1229. void
  1230. value_free (struct value *val)
  1231. {
  1232.   if (val)
  1233.     {
  1234.       gdb_assert (val->reference_count > 0);
  1235.       val->reference_count--;
  1236.       if (val->reference_count > 0)
  1237.         return;

  1238.       /* If there's an associated parent value, drop our reference to
  1239.          it.  */
  1240.       if (val->parent != NULL)
  1241.         value_free (val->parent);

  1242.       if (VALUE_LVAL (val) == lval_computed)
  1243.         {
  1244.           const struct lval_funcs *funcs = val->location.computed.funcs;

  1245.           if (funcs->free_closure)
  1246.             funcs->free_closure (val);
  1247.         }
  1248.       else if (VALUE_LVAL (val) == lval_xcallable)
  1249.           free_xmethod_worker (val->location.xm_worker);

  1250.       xfree (val->contents);
  1251.       VEC_free (range_s, val->unavailable);
  1252.     }
  1253.   xfree (val);
  1254. }

  1255. /* Free all values allocated since MARK was obtained by value_mark
  1256.    (except for those released).  */
  1257. void
  1258. value_free_to_mark (struct value *mark)
  1259. {
  1260.   struct value *val;
  1261.   struct value *next;

  1262.   for (val = all_values; val && val != mark; val = next)
  1263.     {
  1264.       next = val->next;
  1265.       val->released = 1;
  1266.       value_free (val);
  1267.     }
  1268.   all_values = val;
  1269. }

  1270. /* Free all the values that have been allocated (except for those released).
  1271.    Call after each command, successful or not.
  1272.    In practice this is called before each command, which is sufficient.  */

  1273. void
  1274. free_all_values (void)
  1275. {
  1276.   struct value *val;
  1277.   struct value *next;

  1278.   for (val = all_values; val; val = next)
  1279.     {
  1280.       next = val->next;
  1281.       val->released = 1;
  1282.       value_free (val);
  1283.     }

  1284.   all_values = 0;
  1285. }

  1286. /* Frees all the elements in a chain of values.  */

  1287. void
  1288. free_value_chain (struct value *v)
  1289. {
  1290.   struct value *next;

  1291.   for (; v; v = next)
  1292.     {
  1293.       next = value_next (v);
  1294.       value_free (v);
  1295.     }
  1296. }

  1297. /* Remove VAL from the chain all_values
  1298.    so it will not be freed automatically.  */

  1299. void
  1300. release_value (struct value *val)
  1301. {
  1302.   struct value *v;

  1303.   if (all_values == val)
  1304.     {
  1305.       all_values = val->next;
  1306.       val->next = NULL;
  1307.       val->released = 1;
  1308.       return;
  1309.     }

  1310.   for (v = all_values; v; v = v->next)
  1311.     {
  1312.       if (v->next == val)
  1313.         {
  1314.           v->next = val->next;
  1315.           val->next = NULL;
  1316.           val->released = 1;
  1317.           break;
  1318.         }
  1319.     }
  1320. }

  1321. /* If the value is not already released, release it.
  1322.    If the value is already released, increment its reference count.
  1323.    That is, this function ensures that the value is released from the
  1324.    value chain and that the caller owns a reference to it.  */

  1325. void
  1326. release_value_or_incref (struct value *val)
  1327. {
  1328.   if (val->released)
  1329.     value_incref (val);
  1330.   else
  1331.     release_value (val);
  1332. }

  1333. /* Release all values up to mark  */
  1334. struct value *
  1335. value_release_to_mark (struct value *mark)
  1336. {
  1337.   struct value *val;
  1338.   struct value *next;

  1339.   for (val = next = all_values; next; next = next->next)
  1340.     {
  1341.       if (next->next == mark)
  1342.         {
  1343.           all_values = next->next;
  1344.           next->next = NULL;
  1345.           return val;
  1346.         }
  1347.       next->released = 1;
  1348.     }
  1349.   all_values = 0;
  1350.   return val;
  1351. }

  1352. /* Return a copy of the value ARG.
  1353.    It contains the same contents, for same memory address,
  1354.    but it's a different block of storage.  */

  1355. struct value *
  1356. value_copy (struct value *arg)
  1357. {
  1358.   struct type *encl_type = value_enclosing_type (arg);
  1359.   struct value *val;

  1360.   if (value_lazy (arg))
  1361.     val = allocate_value_lazy (encl_type);
  1362.   else
  1363.     val = allocate_value (encl_type);
  1364.   val->type = arg->type;
  1365.   VALUE_LVAL (val) = VALUE_LVAL (arg);
  1366.   val->location = arg->location;
  1367.   val->offset = arg->offset;
  1368.   val->bitpos = arg->bitpos;
  1369.   val->bitsize = arg->bitsize;
  1370.   VALUE_FRAME_ID (val) = VALUE_FRAME_ID (arg);
  1371.   VALUE_REGNUM (val) = VALUE_REGNUM (arg);
  1372.   val->lazy = arg->lazy;
  1373.   val->embedded_offset = value_embedded_offset (arg);
  1374.   val->pointed_to_offset = arg->pointed_to_offset;
  1375.   val->modifiable = arg->modifiable;
  1376.   if (!value_lazy (val))
  1377.     {
  1378.       memcpy (value_contents_all_raw (val), value_contents_all_raw (arg),
  1379.               TYPE_LENGTH (value_enclosing_type (arg)));

  1380.     }
  1381.   val->unavailable = VEC_copy (range_s, arg->unavailable);
  1382.   val->optimized_out = VEC_copy (range_s, arg->optimized_out);
  1383.   set_value_parent (val, arg->parent);
  1384.   if (VALUE_LVAL (val) == lval_computed)
  1385.     {
  1386.       const struct lval_funcs *funcs = val->location.computed.funcs;

  1387.       if (funcs->copy_closure)
  1388.         val->location.computed.closure = funcs->copy_closure (val);
  1389.     }
  1390.   return val;
  1391. }

  1392. /* Return a version of ARG that is non-lvalue.  */

  1393. struct value *
  1394. value_non_lval (struct value *arg)
  1395. {
  1396.   if (VALUE_LVAL (arg) != not_lval)
  1397.     {
  1398.       struct type *enc_type = value_enclosing_type (arg);
  1399.       struct value *val = allocate_value (enc_type);

  1400.       memcpy (value_contents_all_raw (val), value_contents_all (arg),
  1401.               TYPE_LENGTH (enc_type));
  1402.       val->type = arg->type;
  1403.       set_value_embedded_offset (val, value_embedded_offset (arg));
  1404.       set_value_pointed_to_offset (val, value_pointed_to_offset (arg));
  1405.       return val;
  1406.     }
  1407.    return arg;
  1408. }

  1409. /* Write contents of V at ADDR and set its lval type to be LVAL_MEMORY.  */

  1410. void
  1411. value_force_lval (struct value *v, CORE_ADDR addr)
  1412. {
  1413.   gdb_assert (VALUE_LVAL (v) == not_lval);

  1414.   write_memory (addr, value_contents_raw (v), TYPE_LENGTH (value_type (v)));
  1415.   v->lval = lval_memory;
  1416.   v->location.address = addr;
  1417. }

  1418. void
  1419. set_value_component_location (struct value *component,
  1420.                               const struct value *whole)
  1421. {
  1422.   gdb_assert (whole->lval != lval_xcallable);

  1423.   if (whole->lval == lval_internalvar)
  1424.     VALUE_LVAL (component) = lval_internalvar_component;
  1425.   else
  1426.     VALUE_LVAL (component) = whole->lval;

  1427.   component->location = whole->location;
  1428.   if (whole->lval == lval_computed)
  1429.     {
  1430.       const struct lval_funcs *funcs = whole->location.computed.funcs;

  1431.       if (funcs->copy_closure)
  1432.         component->location.computed.closure = funcs->copy_closure (whole);
  1433.     }
  1434. }


  1435. /* Access to the value history.  */

  1436. /* Record a new value in the value history.
  1437.    Returns the absolute history index of the entry.  */

  1438. int
  1439. record_latest_value (struct value *val)
  1440. {
  1441.   int i;

  1442.   /* We don't want this value to have anything to do with the inferior anymore.
  1443.      In particular, "set $1 = 50" should not affect the variable from which
  1444.      the value was taken, and fast watchpoints should be able to assume that
  1445.      a value on the value history never changes.  */
  1446.   if (value_lazy (val))
  1447.     value_fetch_lazy (val);
  1448.   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
  1449.      from.  This is a bit dubious, because then *&$1 does not just return $1
  1450.      but the current contents of that location.  c'est la vie...  */
  1451.   val->modifiable = 0;

  1452.   /* The value may have already been released, in which case we're adding a
  1453.      new reference for its entry in the history.  That is why we call
  1454.      release_value_or_incref here instead of release_value.  */
  1455.   release_value_or_incref (val);

  1456.   /* Here we treat value_history_count as origin-zero
  1457.      and applying to the value being stored now.  */

  1458.   i = value_history_count % VALUE_HISTORY_CHUNK;
  1459.   if (i == 0)
  1460.     {
  1461.       struct value_history_chunk *new
  1462.         = (struct value_history_chunk *)

  1463.       xmalloc (sizeof (struct value_history_chunk));
  1464.       memset (new->values, 0, sizeof new->values);
  1465.       new->next = value_history_chain;
  1466.       value_history_chain = new;
  1467.     }

  1468.   value_history_chain->values[i] = val;

  1469.   /* Now we regard value_history_count as origin-one
  1470.      and applying to the value just stored.  */

  1471.   return ++value_history_count;
  1472. }

  1473. /* Return a copy of the value in the history with sequence number NUM.  */

  1474. struct value *
  1475. access_value_history (int num)
  1476. {
  1477.   struct value_history_chunk *chunk;
  1478.   int i;
  1479.   int absnum = num;

  1480.   if (absnum <= 0)
  1481.     absnum += value_history_count;

  1482.   if (absnum <= 0)
  1483.     {
  1484.       if (num == 0)
  1485.         error (_("The history is empty."));
  1486.       else if (num == 1)
  1487.         error (_("There is only one value in the history."));
  1488.       else
  1489.         error (_("History does not go back to $$%d."), -num);
  1490.     }
  1491.   if (absnum > value_history_count)
  1492.     error (_("History has not yet reached $%d."), absnum);

  1493.   absnum--;

  1494.   /* Now absnum is always absolute and origin zero.  */

  1495.   chunk = value_history_chain;
  1496.   for (i = (value_history_count - 1) / VALUE_HISTORY_CHUNK
  1497.          - absnum / VALUE_HISTORY_CHUNK;
  1498.        i > 0; i--)
  1499.     chunk = chunk->next;

  1500.   return value_copy (chunk->values[absnum % VALUE_HISTORY_CHUNK]);
  1501. }

  1502. static void
  1503. show_values (char *num_exp, int from_tty)
  1504. {
  1505.   int i;
  1506.   struct value *val;
  1507.   static int num = 1;

  1508.   if (num_exp)
  1509.     {
  1510.       /* "show values +" should print from the stored position.
  1511.          "show values <exp>" should print around value number <exp>.  */
  1512.       if (num_exp[0] != '+' || num_exp[1] != '\0')
  1513.         num = parse_and_eval_long (num_exp) - 5;
  1514.     }
  1515.   else
  1516.     {
  1517.       /* "show values" means print the last 10 values.  */
  1518.       num = value_history_count - 9;
  1519.     }

  1520.   if (num <= 0)
  1521.     num = 1;

  1522.   for (i = num; i < num + 10 && i <= value_history_count; i++)
  1523.     {
  1524.       struct value_print_options opts;

  1525.       val = access_value_history (i);
  1526.       printf_filtered (("$%d = "), i);
  1527.       get_user_print_options (&opts);
  1528.       value_print (val, gdb_stdout, &opts);
  1529.       printf_filtered (("\n"));
  1530.     }

  1531.   /* The next "show values +" should start after what we just printed.  */
  1532.   num += 10;

  1533.   /* Hitting just return after this command should do the same thing as
  1534.      "show values +".  If num_exp is null, this is unnecessary, since
  1535.      "show values +" is not useful after "show values".  */
  1536.   if (from_tty && num_exp)
  1537.     {
  1538.       num_exp[0] = '+';
  1539.       num_exp[1] = '\0';
  1540.     }
  1541. }

  1542. /* Internal variables.  These are variables within the debugger
  1543.    that hold values assigned by debugger commands.
  1544.    The user refers to them with a '$' prefix
  1545.    that does not appear in the variable names stored internally.  */

  1546. struct internalvar
  1547. {
  1548.   struct internalvar *next;
  1549.   char *name;

  1550.   /* We support various different kinds of content of an internal variable.
  1551.      enum internalvar_kind specifies the kind, and union internalvar_data
  1552.      provides the data associated with this particular kind.  */

  1553.   enum internalvar_kind
  1554.     {
  1555.       /* The internal variable is empty.  */
  1556.       INTERNALVAR_VOID,

  1557.       /* The value of the internal variable is provided directly as
  1558.          a GDB value object.  */
  1559.       INTERNALVAR_VALUE,

  1560.       /* A fresh value is computed via a call-back routine on every
  1561.          access to the internal variable.  */
  1562.       INTERNALVAR_MAKE_VALUE,

  1563.       /* The internal variable holds a GDB internal convenience function.  */
  1564.       INTERNALVAR_FUNCTION,

  1565.       /* The variable holds an integer value.  */
  1566.       INTERNALVAR_INTEGER,

  1567.       /* The variable holds a GDB-provided string.  */
  1568.       INTERNALVAR_STRING,

  1569.     } kind;

  1570.   union internalvar_data
  1571.     {
  1572.       /* A value object used with INTERNALVAR_VALUE.  */
  1573.       struct value *value;

  1574.       /* The call-back routine used with INTERNALVAR_MAKE_VALUE.  */
  1575.       struct
  1576.         {
  1577.           /* The functions to call.  */
  1578.           const struct internalvar_funcs *functions;

  1579.           /* The function's user-data.  */
  1580.           void *data;
  1581.         } make_value;

  1582.       /* The internal function used with INTERNALVAR_FUNCTION.  */
  1583.       struct
  1584.         {
  1585.           struct internal_function *function;
  1586.           /* True if this is the canonical name for the function.  */
  1587.           int canonical;
  1588.         } fn;

  1589.       /* An integer value used with INTERNALVAR_INTEGER.  */
  1590.       struct
  1591.         {
  1592.           /* If type is non-NULL, it will be used as the type to generate
  1593.              a value for this internal variable.  If type is NULL, a default
  1594.              integer type for the architecture is used.  */
  1595.           struct type *type;
  1596.           LONGEST val;
  1597.         } integer;

  1598.       /* A string value used with INTERNALVAR_STRING.  */
  1599.       char *string;
  1600.     } u;
  1601. };

  1602. static struct internalvar *internalvars;

  1603. /* If the variable does not already exist create it and give it the
  1604.    value given.  If no value is given then the default is zero.  */
  1605. static void
  1606. init_if_undefined_command (char* args, int from_tty)
  1607. {
  1608.   struct internalvar* intvar;

  1609.   /* Parse the expression - this is taken from set_command().  */
  1610.   struct expression *expr = parse_expression (args);
  1611.   register struct cleanup *old_chain =
  1612.     make_cleanup (free_current_contents, &expr);

  1613.   /* Validate the expression.
  1614.      Was the expression an assignment?
  1615.      Or even an expression at all?  */
  1616.   if (expr->nelts == 0 || expr->elts[0].opcode != BINOP_ASSIGN)
  1617.     error (_("Init-if-undefined requires an assignment expression."));

  1618.   /* Extract the variable from the parsed expression.
  1619.      In the case of an assign the lvalue will be in elts[1] and elts[2].  */
  1620.   if (expr->elts[1].opcode != OP_INTERNALVAR)
  1621.     error (_("The first parameter to init-if-undefined "
  1622.              "should be a GDB variable."));
  1623.   intvar = expr->elts[2].internalvar;

  1624.   /* Only evaluate the expression if the lvalue is void.
  1625.      This may still fail if the expresssion is invalid.  */
  1626.   if (intvar->kind == INTERNALVAR_VOID)
  1627.     evaluate_expression (expr);

  1628.   do_cleanups (old_chain);
  1629. }


  1630. /* Look up an internal variable with name NAMENAME should not
  1631.    normally include a dollar sign.

  1632.    If the specified internal variable does not exist,
  1633.    the return value is NULL.  */

  1634. struct internalvar *
  1635. lookup_only_internalvar (const char *name)
  1636. {
  1637.   struct internalvar *var;

  1638.   for (var = internalvars; var; var = var->next)
  1639.     if (strcmp (var->name, name) == 0)
  1640.       return var;

  1641.   return NULL;
  1642. }

  1643. /* Complete NAME by comparing it to the names of internal variables.
  1644.    Returns a vector of newly allocated strings, or NULL if no matches
  1645.    were found.  */

  1646. VEC (char_ptr) *
  1647. complete_internalvar (const char *name)
  1648. {
  1649.   VEC (char_ptr) *result = NULL;
  1650.   struct internalvar *var;
  1651.   int len;

  1652.   len = strlen (name);

  1653.   for (var = internalvars; var; var = var->next)
  1654.     if (strncmp (var->name, name, len) == 0)
  1655.       {
  1656.         char *r = xstrdup (var->name);

  1657.         VEC_safe_push (char_ptr, result, r);
  1658.       }

  1659.   return result;
  1660. }

  1661. /* Create an internal variable with name NAME and with a void value.
  1662.    NAME should not normally include a dollar sign.  */

  1663. struct internalvar *
  1664. create_internalvar (const char *name)
  1665. {
  1666.   struct internalvar *var;

  1667.   var = (struct internalvar *) xmalloc (sizeof (struct internalvar));
  1668.   var->name = concat (name, (char *)NULL);
  1669.   var->kind = INTERNALVAR_VOID;
  1670.   var->next = internalvars;
  1671.   internalvars = var;
  1672.   return var;
  1673. }

  1674. /* Create an internal variable with name NAME and register FUN as the
  1675.    function that value_of_internalvar uses to create a value whenever
  1676.    this variable is referenced.  NAME should not normally include a
  1677.    dollar sign.  DATA is passed uninterpreted to FUN when it is
  1678.    called.  CLEANUP, if not NULL, is called when the internal variable
  1679.    is destroyed.  It is passed DATA as its only argument.  */

  1680. struct internalvar *
  1681. create_internalvar_type_lazy (const char *name,
  1682.                               const struct internalvar_funcs *funcs,
  1683.                               void *data)
  1684. {
  1685.   struct internalvar *var = create_internalvar (name);

  1686.   var->kind = INTERNALVAR_MAKE_VALUE;
  1687.   var->u.make_value.functions = funcs;
  1688.   var->u.make_value.data = data;
  1689.   return var;
  1690. }

  1691. /* See documentation in value.h.  */

  1692. int
  1693. compile_internalvar_to_ax (struct internalvar *var,
  1694.                            struct agent_expr *expr,
  1695.                            struct axs_value *value)
  1696. {
  1697.   if (var->kind != INTERNALVAR_MAKE_VALUE
  1698.       || var->u.make_value.functions->compile_to_ax == NULL)
  1699.     return 0;

  1700.   var->u.make_value.functions->compile_to_ax (var, expr, value,
  1701.                                               var->u.make_value.data);
  1702.   return 1;
  1703. }

  1704. /* Look up an internal variable with name NAMENAME should not
  1705.    normally include a dollar sign.

  1706.    If the specified internal variable does not exist,
  1707.    one is created, with a void value.  */

  1708. struct internalvar *
  1709. lookup_internalvar (const char *name)
  1710. {
  1711.   struct internalvar *var;

  1712.   var = lookup_only_internalvar (name);
  1713.   if (var)
  1714.     return var;

  1715.   return create_internalvar (name);
  1716. }

  1717. /* Return current value of internal variable VAR.  For variables that
  1718.    are not inherently typed, use a value type appropriate for GDBARCH.  */

  1719. struct value *
  1720. value_of_internalvar (struct gdbarch *gdbarch, struct internalvar *var)
  1721. {
  1722.   struct value *val;
  1723.   struct trace_state_variable *tsv;

  1724.   /* If there is a trace state variable of the same name, assume that
  1725.      is what we really want to see.  */
  1726.   tsv = find_trace_state_variable (var->name);
  1727.   if (tsv)
  1728.     {
  1729.       tsv->value_known = target_get_trace_state_variable_value (tsv->number,
  1730.                                                                 &(tsv->value));
  1731.       if (tsv->value_known)
  1732.         val = value_from_longest (builtin_type (gdbarch)->builtin_int64,
  1733.                                   tsv->value);
  1734.       else
  1735.         val = allocate_value (builtin_type (gdbarch)->builtin_void);
  1736.       return val;
  1737.     }

  1738.   switch (var->kind)
  1739.     {
  1740.     case INTERNALVAR_VOID:
  1741.       val = allocate_value (builtin_type (gdbarch)->builtin_void);
  1742.       break;

  1743.     case INTERNALVAR_FUNCTION:
  1744.       val = allocate_value (builtin_type (gdbarch)->internal_fn);
  1745.       break;

  1746.     case INTERNALVAR_INTEGER:
  1747.       if (!var->u.integer.type)
  1748.         val = value_from_longest (builtin_type (gdbarch)->builtin_int,
  1749.                                   var->u.integer.val);
  1750.       else
  1751.         val = value_from_longest (var->u.integer.type, var->u.integer.val);
  1752.       break;

  1753.     case INTERNALVAR_STRING:
  1754.       val = value_cstring (var->u.string, strlen (var->u.string),
  1755.                            builtin_type (gdbarch)->builtin_char);
  1756.       break;

  1757.     case INTERNALVAR_VALUE:
  1758.       val = value_copy (var->u.value);
  1759.       if (value_lazy (val))
  1760.         value_fetch_lazy (val);
  1761.       break;

  1762.     case INTERNALVAR_MAKE_VALUE:
  1763.       val = (*var->u.make_value.functions->make_value) (gdbarch, var,
  1764.                                                         var->u.make_value.data);
  1765.       break;

  1766.     default:
  1767.       internal_error (__FILE__, __LINE__, _("bad kind"));
  1768.     }

  1769.   /* Change the VALUE_LVAL to lval_internalvar so that future operations
  1770.      on this value go back to affect the original internal variable.

  1771.      Do not do this for INTERNALVAR_MAKE_VALUE variables, as those have
  1772.      no underlying modifyable state in the internal variable.

  1773.      Likewise, if the variable's value is a computed lvalue, we want
  1774.      references to it to produce another computed lvalue, where
  1775.      references and assignments actually operate through the
  1776.      computed value's functions.

  1777.      This means that internal variables with computed values
  1778.      behave a little differently from other internal variables:
  1779.      assignments to them don't just replace the previous value
  1780.      altogether.  At the moment, this seems like the behavior we
  1781.      want.  */

  1782.   if (var->kind != INTERNALVAR_MAKE_VALUE
  1783.       && val->lval != lval_computed)
  1784.     {
  1785.       VALUE_LVAL (val) = lval_internalvar;
  1786.       VALUE_INTERNALVAR (val) = var;
  1787.     }

  1788.   return val;
  1789. }

  1790. int
  1791. get_internalvar_integer (struct internalvar *var, LONGEST *result)
  1792. {
  1793.   if (var->kind == INTERNALVAR_INTEGER)
  1794.     {
  1795.       *result = var->u.integer.val;
  1796.       return 1;
  1797.     }

  1798.   if (var->kind == INTERNALVAR_VALUE)
  1799.     {
  1800.       struct type *type = check_typedef (value_type (var->u.value));

  1801.       if (TYPE_CODE (type) == TYPE_CODE_INT)
  1802.         {
  1803.           *result = value_as_long (var->u.value);
  1804.           return 1;
  1805.         }
  1806.     }

  1807.   return 0;
  1808. }

  1809. static int
  1810. get_internalvar_function (struct internalvar *var,
  1811.                           struct internal_function **result)
  1812. {
  1813.   switch (var->kind)
  1814.     {
  1815.     case INTERNALVAR_FUNCTION:
  1816.       *result = var->u.fn.function;
  1817.       return 1;

  1818.     default:
  1819.       return 0;
  1820.     }
  1821. }

  1822. void
  1823. set_internalvar_component (struct internalvar *var, int offset, int bitpos,
  1824.                            int bitsize, struct value *newval)
  1825. {
  1826.   gdb_byte *addr;

  1827.   switch (var->kind)
  1828.     {
  1829.     case INTERNALVAR_VALUE:
  1830.       addr = value_contents_writeable (var->u.value);

  1831.       if (bitsize)
  1832.         modify_field (value_type (var->u.value), addr + offset,
  1833.                       value_as_long (newval), bitpos, bitsize);
  1834.       else
  1835.         memcpy (addr + offset, value_contents (newval),
  1836.                 TYPE_LENGTH (value_type (newval)));
  1837.       break;

  1838.     default:
  1839.       /* We can never get a component of any other kind.  */
  1840.       internal_error (__FILE__, __LINE__, _("set_internalvar_component"));
  1841.     }
  1842. }

  1843. void
  1844. set_internalvar (struct internalvar *var, struct value *val)
  1845. {
  1846.   enum internalvar_kind new_kind;
  1847.   union internalvar_data new_data = { 0 };

  1848.   if (var->kind == INTERNALVAR_FUNCTION && var->u.fn.canonical)
  1849.     error (_("Cannot overwrite convenience function %s"), var->name);

  1850.   /* Prepare new contents.  */
  1851.   switch (TYPE_CODE (check_typedef (value_type (val))))
  1852.     {
  1853.     case TYPE_CODE_VOID:
  1854.       new_kind = INTERNALVAR_VOID;
  1855.       break;

  1856.     case TYPE_CODE_INTERNAL_FUNCTION:
  1857.       gdb_assert (VALUE_LVAL (val) == lval_internalvar);
  1858.       new_kind = INTERNALVAR_FUNCTION;
  1859.       get_internalvar_function (VALUE_INTERNALVAR (val),
  1860.                                 &new_data.fn.function);
  1861.       /* Copies created here are never canonical.  */
  1862.       break;

  1863.     default:
  1864.       new_kind = INTERNALVAR_VALUE;
  1865.       new_data.value = value_copy (val);
  1866.       new_data.value->modifiable = 1;

  1867.       /* Force the value to be fetched from the target now, to avoid problems
  1868.          later when this internalvar is referenced and the target is gone or
  1869.          has changed.  */
  1870.       if (value_lazy (new_data.value))
  1871.        value_fetch_lazy (new_data.value);

  1872.       /* Release the value from the value chain to prevent it from being
  1873.          deleted by free_all_values.  From here on this function should not
  1874.          call error () until new_data is installed into the var->u to avoid
  1875.          leaking memory.  */
  1876.       release_value (new_data.value);
  1877.       break;
  1878.     }

  1879.   /* Clean up old contents.  */
  1880.   clear_internalvar (var);

  1881.   /* Switch over.  */
  1882.   var->kind = new_kind;
  1883.   var->u = new_data;
  1884.   /* End code which must not call error().  */
  1885. }

  1886. void
  1887. set_internalvar_integer (struct internalvar *var, LONGEST l)
  1888. {
  1889.   /* Clean up old contents.  */
  1890.   clear_internalvar (var);

  1891.   var->kind = INTERNALVAR_INTEGER;
  1892.   var->u.integer.type = NULL;
  1893.   var->u.integer.val = l;
  1894. }

  1895. void
  1896. set_internalvar_string (struct internalvar *var, const char *string)
  1897. {
  1898.   /* Clean up old contents.  */
  1899.   clear_internalvar (var);

  1900.   var->kind = INTERNALVAR_STRING;
  1901.   var->u.string = xstrdup (string);
  1902. }

  1903. static void
  1904. set_internalvar_function (struct internalvar *var, struct internal_function *f)
  1905. {
  1906.   /* Clean up old contents.  */
  1907.   clear_internalvar (var);

  1908.   var->kind = INTERNALVAR_FUNCTION;
  1909.   var->u.fn.function = f;
  1910.   var->u.fn.canonical = 1;
  1911.   /* Variables installed here are always the canonical version.  */
  1912. }

  1913. void
  1914. clear_internalvar (struct internalvar *var)
  1915. {
  1916.   /* Clean up old contents.  */
  1917.   switch (var->kind)
  1918.     {
  1919.     case INTERNALVAR_VALUE:
  1920.       value_free (var->u.value);
  1921.       break;

  1922.     case INTERNALVAR_STRING:
  1923.       xfree (var->u.string);
  1924.       break;

  1925.     case INTERNALVAR_MAKE_VALUE:
  1926.       if (var->u.make_value.functions->destroy != NULL)
  1927.         var->u.make_value.functions->destroy (var->u.make_value.data);
  1928.       break;

  1929.     default:
  1930.       break;
  1931.     }

  1932.   /* Reset to void kind.  */
  1933.   var->kind = INTERNALVAR_VOID;
  1934. }

  1935. char *
  1936. internalvar_name (struct internalvar *var)
  1937. {
  1938.   return var->name;
  1939. }

  1940. static struct internal_function *
  1941. create_internal_function (const char *name,
  1942.                           internal_function_fn handler, void *cookie)
  1943. {
  1944.   struct internal_function *ifn = XNEW (struct internal_function);

  1945.   ifn->name = xstrdup (name);
  1946.   ifn->handler = handler;
  1947.   ifn->cookie = cookie;
  1948.   return ifn;
  1949. }

  1950. char *
  1951. value_internal_function_name (struct value *val)
  1952. {
  1953.   struct internal_function *ifn;
  1954.   int result;

  1955.   gdb_assert (VALUE_LVAL (val) == lval_internalvar);
  1956.   result = get_internalvar_function (VALUE_INTERNALVAR (val), &ifn);
  1957.   gdb_assert (result);

  1958.   return ifn->name;
  1959. }

  1960. struct value *
  1961. call_internal_function (struct gdbarch *gdbarch,
  1962.                         const struct language_defn *language,
  1963.                         struct value *func, int argc, struct value **argv)
  1964. {
  1965.   struct internal_function *ifn;
  1966.   int result;

  1967.   gdb_assert (VALUE_LVAL (func) == lval_internalvar);
  1968.   result = get_internalvar_function (VALUE_INTERNALVAR (func), &ifn);
  1969.   gdb_assert (result);

  1970.   return (*ifn->handler) (gdbarch, language, ifn->cookie, argc, argv);
  1971. }

  1972. /* The 'function' command.  This does nothing -- it is just a
  1973.    placeholder to let "help function NAME" work.  This is also used as
  1974.    the implementation of the sub-command that is created when
  1975.    registering an internal function.  */
  1976. static void
  1977. function_command (char *command, int from_tty)
  1978. {
  1979.   /* Do nothing.  */
  1980. }

  1981. /* Clean up if an internal function's command is destroyed.  */
  1982. static void
  1983. function_destroyer (struct cmd_list_element *self, void *ignore)
  1984. {
  1985.   xfree ((char *) self->name);
  1986.   xfree ((char *) self->doc);
  1987. }

  1988. /* Add a new internal functionNAME is the name of the function; DOC
  1989.    is a documentation string describing the function.  HANDLER is
  1990.    called when the function is invoked.  COOKIE is an arbitrary
  1991.    pointer which is passed to HANDLER and is intended for "user
  1992.    data".  */
  1993. void
  1994. add_internal_function (const char *name, const char *doc,
  1995.                        internal_function_fn handler, void *cookie)
  1996. {
  1997.   struct cmd_list_element *cmd;
  1998.   struct internal_function *ifn;
  1999.   struct internalvar *var = lookup_internalvar (name);

  2000.   ifn = create_internal_function (name, handler, cookie);
  2001.   set_internalvar_function (var, ifn);

  2002.   cmd = add_cmd (xstrdup (name), no_class, function_command, (char *) doc,
  2003.                  &functionlist);
  2004.   cmd->destroyer = function_destroyer;
  2005. }

  2006. /* Update VALUE before discarding OBJFILE.  COPIED_TYPES is used to
  2007.    prevent cycles / duplicates.  */

  2008. void
  2009. preserve_one_value (struct value *value, struct objfile *objfile,
  2010.                     htab_t copied_types)
  2011. {
  2012.   if (TYPE_OBJFILE (value->type) == objfile)
  2013.     value->type = copy_type_recursive (objfile, value->type, copied_types);

  2014.   if (TYPE_OBJFILE (value->enclosing_type) == objfile)
  2015.     value->enclosing_type = copy_type_recursive (objfile,
  2016.                                                  value->enclosing_type,
  2017.                                                  copied_types);
  2018. }

  2019. /* Likewise for internal variable VAR.  */

  2020. static void
  2021. preserve_one_internalvar (struct internalvar *var, struct objfile *objfile,
  2022.                           htab_t copied_types)
  2023. {
  2024.   switch (var->kind)
  2025.     {
  2026.     case INTERNALVAR_INTEGER:
  2027.       if (var->u.integer.type && TYPE_OBJFILE (var->u.integer.type) == objfile)
  2028.         var->u.integer.type
  2029.           = copy_type_recursive (objfile, var->u.integer.type, copied_types);
  2030.       break;

  2031.     case INTERNALVAR_VALUE:
  2032.       preserve_one_value (var->u.value, objfile, copied_types);
  2033.       break;
  2034.     }
  2035. }

  2036. /* Update the internal variables and value history when OBJFILE is
  2037.    discarded; we must copy the types out of the objfile.  New global types
  2038.    will be created for every convenience variable which currently points to
  2039.    this objfile's types, and the convenience variables will be adjusted to
  2040.    use the new global types.  */

  2041. void
  2042. preserve_values (struct objfile *objfile)
  2043. {
  2044.   htab_t copied_types;
  2045.   struct value_history_chunk *cur;
  2046.   struct internalvar *var;
  2047.   int i;

  2048.   /* Create the hash table.  We allocate on the objfile's obstack, since
  2049.      it is soon to be deleted.  */
  2050.   copied_types = create_copied_types_hash (objfile);

  2051.   for (cur = value_history_chain; cur; cur = cur->next)
  2052.     for (i = 0; i < VALUE_HISTORY_CHUNK; i++)
  2053.       if (cur->values[i])
  2054.         preserve_one_value (cur->values[i], objfile, copied_types);

  2055.   for (var = internalvars; var; var = var->next)
  2056.     preserve_one_internalvar (var, objfile, copied_types);

  2057.   preserve_ext_lang_values (objfile, copied_types);

  2058.   htab_delete (copied_types);
  2059. }

  2060. static void
  2061. show_convenience (char *ignore, int from_tty)
  2062. {
  2063.   struct gdbarch *gdbarch = get_current_arch ();
  2064.   struct internalvar *var;
  2065.   int varseen = 0;
  2066.   struct value_print_options opts;

  2067.   get_user_print_options (&opts);
  2068.   for (var = internalvars; var; var = var->next)
  2069.     {
  2070.       volatile struct gdb_exception ex;

  2071.       if (!varseen)
  2072.         {
  2073.           varseen = 1;
  2074.         }
  2075.       printf_filtered (("$%s = "), var->name);

  2076.       TRY_CATCH (ex, RETURN_MASK_ERROR)
  2077.         {
  2078.           struct value *val;

  2079.           val = value_of_internalvar (gdbarch, var);
  2080.           value_print (val, gdb_stdout, &opts);
  2081.         }
  2082.       if (ex.reason < 0)
  2083.         fprintf_filtered (gdb_stdout, _("<error: %s>"), ex.message);
  2084.       printf_filtered (("\n"));
  2085.     }
  2086.   if (!varseen)
  2087.     {
  2088.       /* This text does not mention convenience functions on purpose.
  2089.          The user can't create them except via Python, and if Python support
  2090.          is installed this message will never be printed ($_streq will
  2091.          exist).  */
  2092.       printf_unfiltered (_("No debugger convenience variables now defined.\n"
  2093.                            "Convenience variables have "
  2094.                            "names starting with \"$\";\n"
  2095.                            "use \"set\" as in \"set "
  2096.                            "$foo = 5\" to define them.\n"));
  2097.     }
  2098. }

  2099. /* Return the TYPE_CODE_XMETHOD value corresponding to WORKER.  */

  2100. struct value *
  2101. value_of_xmethod (struct xmethod_worker *worker)
  2102. {
  2103.   if (worker->value == NULL)
  2104.     {
  2105.       struct value *v;

  2106.       v = allocate_value (builtin_type (target_gdbarch ())->xmethod);
  2107.       v->lval = lval_xcallable;
  2108.       v->location.xm_worker = worker;
  2109.       v->modifiable = 0;
  2110.       worker->value = v;
  2111.     }

  2112.   return worker->value;
  2113. }

  2114. /* Call the xmethod corresponding to the TYPE_CODE_XMETHOD value METHOD.  */

  2115. struct value *
  2116. call_xmethod (struct value *method, int argc, struct value **argv)
  2117. {
  2118.   gdb_assert (TYPE_CODE (value_type (method)) == TYPE_CODE_XMETHOD
  2119.               && method->lval == lval_xcallable && argc > 0);

  2120.   return invoke_xmethod (method->location.xm_worker,
  2121.                          argv[0], argv + 1, argc - 1);
  2122. }

  2123. /* Extract a value as a C number (either long or double).
  2124.    Knows how to convert fixed values to double, or
  2125.    floating values to long.
  2126.    Does not deallocate the value.  */

  2127. LONGEST
  2128. value_as_long (struct value *val)
  2129. {
  2130.   /* This coerces arrays and functions, which is necessary (e.g.
  2131.      in disassemble_command).  It also dereferences references, which
  2132.      I suspect is the most logical thing to do.  */
  2133.   val = coerce_array (val);
  2134.   return unpack_long (value_type (val), value_contents (val));
  2135. }

  2136. DOUBLEST
  2137. value_as_double (struct value *val)
  2138. {
  2139.   DOUBLEST foo;
  2140.   int inv;

  2141.   foo = unpack_double (value_type (val), value_contents (val), &inv);
  2142.   if (inv)
  2143.     error (_("Invalid floating value found in program."));
  2144.   return foo;
  2145. }

  2146. /* Extract a value as a C pointer.  Does not deallocate the value.
  2147.    Note that val's type may not actually be a pointer; value_as_long
  2148.    handles all the cases.  */
  2149. CORE_ADDR
  2150. value_as_address (struct value *val)
  2151. {
  2152.   struct gdbarch *gdbarch = get_type_arch (value_type (val));

  2153.   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
  2154.      whether we want this to be true eventually.  */
  2155. #if 0
  2156.   /* gdbarch_addr_bits_remove is wrong if we are being called for a
  2157.      non-address (e.g. argument to "signal", "info break", etc.), or
  2158.      for pointers to char, in which the low bits *are* significant.  */
  2159.   return gdbarch_addr_bits_remove (gdbarch, value_as_long (val));
  2160. #else

  2161.   /* There are several targets (IA-64, PowerPC, and others) which
  2162.      don't represent pointers to functions as simply the address of
  2163.      the function's entry point.  For example, on the IA-64, a
  2164.      function pointer points to a two-word descriptor, generated by
  2165.      the linker, which contains the function's entry point, and the
  2166.      value the IA-64 "global pointer" register should have --- to
  2167.      support position-independent code.  The linker generates
  2168.      descriptors only for those functions whose addresses are taken.

  2169.      On such targets, it's difficult for GDB to convert an arbitrary
  2170.      function address into a function pointer; it has to either find
  2171.      an existing descriptor for that function, or call malloc and
  2172.      build its own.  On some targets, it is impossible for GDB to
  2173.      build a descriptor at all: the descriptor must contain a jump
  2174.      instruction; data memory cannot be executed; and code memory
  2175.      cannot be modified.

  2176.      Upon entry to this function, if VAL is a value of type `function'
  2177.      (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
  2178.      value_address (val) is the address of the function.  This is what
  2179.      you'll get if you evaluate an expression like `main'.  The call
  2180.      to COERCE_ARRAY below actually does all the usual unary
  2181.      conversions, which includes converting values of type `function'
  2182.      to `pointer to function'.  This is the challenging conversion
  2183.      discussed above.  Then, `unpack_long' will convert that pointer
  2184.      back into an address.

  2185.      So, suppose the user types `disassemble foo' on an architecture
  2186.      with a strange function pointer representation, on which GDB
  2187.      cannot build its own descriptors, and suppose further that `foo'
  2188.      has no linker-built descriptor.  The address->pointer conversion
  2189.      will signal an error and prevent the command from running, even
  2190.      though the next step would have been to convert the pointer
  2191.      directly back into the same address.

  2192.      The following shortcut avoids this whole mess.  If VAL is a
  2193.      function, just return its address directly.  */
  2194.   if (TYPE_CODE (value_type (val)) == TYPE_CODE_FUNC
  2195.       || TYPE_CODE (value_type (val)) == TYPE_CODE_METHOD)
  2196.     return value_address (val);

  2197.   val = coerce_array (val);

  2198.   /* Some architectures (e.g. Harvard), map instruction and data
  2199.      addresses onto a single large unified address space.  For
  2200.      instance: An architecture may consider a large integer in the
  2201.      range 0x10000000 .. 0x1000ffff to already represent a data
  2202.      addresses (hence not need a pointer to address conversion) while
  2203.      a small integer would still need to be converted integer to
  2204.      pointer to address.  Just assume such architectures handle all
  2205.      integer conversions in a single function.  */

  2206.   /* JimB writes:

  2207.      I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
  2208.      must admonish GDB hackers to make sure its behavior matches the
  2209.      compiler's, whenever possible.

  2210.      In general, I think GDB should evaluate expressions the same way
  2211.      the compiler does.  When the user copies an expression out of
  2212.      their source code and hands it to a `print' command, they should
  2213.      get the same value the compiler would have computed.  Any
  2214.      deviation from this rule can cause major confusion and annoyance,
  2215.      and needs to be justified carefully.  In other words, GDB doesn't
  2216.      really have the freedom to do these conversions in clever and
  2217.      useful ways.

  2218.      AndrewC pointed out that users aren't complaining about how GDB
  2219.      casts integers to pointers; they are complaining that they can't
  2220.      take an address from a disassembly listing and give it to `x/i'.
  2221.      This is certainly important.

  2222.      Adding an architecture method like integer_to_address() certainly
  2223.      makes it possible for GDB to "get it right" in all circumstances
  2224.      --- the target has complete control over how things get done, so
  2225.      people can Do The Right Thing for their target without breaking
  2226.      anyone else.  The standard doesn't specify how integers get
  2227.      converted to pointers; usually, the ABI doesn't either, but
  2228.      ABI-specific code is a more reasonable place to handle it.  */

  2229.   if (TYPE_CODE (value_type (val)) != TYPE_CODE_PTR
  2230.       && TYPE_CODE (value_type (val)) != TYPE_CODE_REF
  2231.       && gdbarch_integer_to_address_p (gdbarch))
  2232.     return gdbarch_integer_to_address (gdbarch, value_type (val),
  2233.                                        value_contents (val));

  2234.   return unpack_long (value_type (val), value_contents (val));
  2235. #endif
  2236. }

  2237. /* Unpack raw data (copied from debugee, target byte order) at VALADDR
  2238.    as a long, or as a double, assuming the raw data is described
  2239.    by type TYPE.  Knows how to convert different sizes of values
  2240.    and can convert between fixed and floating point.  We don't assume
  2241.    any alignment for the raw data.  Return value is in host byte order.

  2242.    If you want functions and arrays to be coerced to pointers, and
  2243.    references to be dereferenced, call value_as_long() instead.

  2244.    C++: It is assumed that the front-end has taken care of
  2245.    all matters concerning pointers to members.  A pointer
  2246.    to member which reaches here is considered to be equivalent
  2247.    to an INT (or some size).  After all, it is only an offset.  */

  2248. LONGEST
  2249. unpack_long (struct type *type, const gdb_byte *valaddr)
  2250. {
  2251.   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
  2252.   enum type_code code = TYPE_CODE (type);
  2253.   int len = TYPE_LENGTH (type);
  2254.   int nosign = TYPE_UNSIGNED (type);

  2255.   switch (code)
  2256.     {
  2257.     case TYPE_CODE_TYPEDEF:
  2258.       return unpack_long (check_typedef (type), valaddr);
  2259.     case TYPE_CODE_ENUM:
  2260.     case TYPE_CODE_FLAGS:
  2261.     case TYPE_CODE_BOOL:
  2262.     case TYPE_CODE_INT:
  2263.     case TYPE_CODE_CHAR:
  2264.     case TYPE_CODE_RANGE:
  2265.     case TYPE_CODE_MEMBERPTR:
  2266.       if (nosign)
  2267.         return extract_unsigned_integer (valaddr, len, byte_order);
  2268.       else
  2269.         return extract_signed_integer (valaddr, len, byte_order);

  2270.     case TYPE_CODE_FLT:
  2271.       return extract_typed_floating (valaddr, type);

  2272.     case TYPE_CODE_DECFLOAT:
  2273.       /* libdecnumber has a function to convert from decimal to integer, but
  2274.          it doesn't work when the decimal number has a fractional part.  */
  2275.       return decimal_to_doublest (valaddr, len, byte_order);

  2276.     case TYPE_CODE_PTR:
  2277.     case TYPE_CODE_REF:
  2278.       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
  2279.          whether we want this to be true eventually.  */
  2280.       return extract_typed_address (valaddr, type);

  2281.     default:
  2282.       error (_("Value can't be converted to integer."));
  2283.     }
  2284.   return 0;                        /* Placate lint.  */
  2285. }

  2286. /* Return a double value from the specified type and address.
  2287.    INVP points to an int which is set to 0 for valid value,
  2288.    1 for invalid value (bad float format).  In either case,
  2289.    the returned double is OK to use.  Argument is in target
  2290.    format, result is in host format.  */

  2291. DOUBLEST
  2292. unpack_double (struct type *type, const gdb_byte *valaddr, int *invp)
  2293. {
  2294.   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
  2295.   enum type_code code;
  2296.   int len;
  2297.   int nosign;

  2298.   *invp = 0;                        /* Assume valid.  */
  2299.   CHECK_TYPEDEF (type);
  2300.   code = TYPE_CODE (type);
  2301.   len = TYPE_LENGTH (type);
  2302.   nosign = TYPE_UNSIGNED (type);
  2303.   if (code == TYPE_CODE_FLT)
  2304.     {
  2305.       /* NOTE: cagney/2002-02-19: There was a test here to see if the
  2306.          floating-point value was valid (using the macro
  2307.          INVALID_FLOAT).  That test/macro have been removed.

  2308.          It turns out that only the VAX defined this macro and then
  2309.          only in a non-portable way.  Fixing the portability problem
  2310.          wouldn't help since the VAX floating-point code is also badly
  2311.          bit-rotten.  The target needs to add definitions for the
  2312.          methods gdbarch_float_format and gdbarch_double_format - these
  2313.          exactly describe the target floating-point format.  The
  2314.          problem here is that the corresponding floatformat_vax_f and
  2315.          floatformat_vax_d values these methods should be set to are
  2316.          also not defined either.  Oops!

  2317.          Hopefully someone will add both the missing floatformat
  2318.          definitions and the new cases for floatformat_is_valid ().  */

  2319.       if (!floatformat_is_valid (floatformat_from_type (type), valaddr))
  2320.         {
  2321.           *invp = 1;
  2322.           return 0.0;
  2323.         }

  2324.       return extract_typed_floating (valaddr, type);
  2325.     }
  2326.   else if (code == TYPE_CODE_DECFLOAT)
  2327.     return decimal_to_doublest (valaddr, len, byte_order);
  2328.   else if (nosign)
  2329.     {
  2330.       /* Unsigned -- be sure we compensate for signed LONGEST.  */
  2331.       return (ULONGEST) unpack_long (type, valaddr);
  2332.     }
  2333.   else
  2334.     {
  2335.       /* Signed -- we are OK with unpack_long.  */
  2336.       return unpack_long (type, valaddr);
  2337.     }
  2338. }

  2339. /* Unpack raw data (copied from debugee, target byte order) at VALADDR
  2340.    as a CORE_ADDR, assuming the raw data is described by type TYPE.
  2341.    We don't assume any alignment for the raw data.  Return value is in
  2342.    host byte order.

  2343.    If you want functions and arrays to be coerced to pointers, and
  2344.    references to be dereferenced, call value_as_address() instead.

  2345.    C++: It is assumed that the front-end has taken care of
  2346.    all matters concerning pointers to members.  A pointer
  2347.    to member which reaches here is considered to be equivalent
  2348.    to an INT (or some size).  After all, it is only an offset.  */

  2349. CORE_ADDR
  2350. unpack_pointer (struct type *type, const gdb_byte *valaddr)
  2351. {
  2352.   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
  2353.      whether we want this to be true eventually.  */
  2354.   return unpack_long (type, valaddr);
  2355. }


  2356. /* Get the value of the FIELDNO'th field (which must be static) of
  2357.    TYPE.  */

  2358. struct value *
  2359. value_static_field (struct type *type, int fieldno)
  2360. {
  2361.   struct value *retval;

  2362.   switch (TYPE_FIELD_LOC_KIND (type, fieldno))
  2363.     {
  2364.     case FIELD_LOC_KIND_PHYSADDR:
  2365.       retval = value_at_lazy (TYPE_FIELD_TYPE (type, fieldno),
  2366.                               TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
  2367.       break;
  2368.     case FIELD_LOC_KIND_PHYSNAME:
  2369.     {
  2370.       const char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
  2371.       /* TYPE_FIELD_NAME (type, fieldno); */
  2372.       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);

  2373.       if (sym == NULL)
  2374.         {
  2375.           /* With some compilers, e.g. HP aCC, static data members are
  2376.              reported as non-debuggable symbols.  */
  2377.           struct bound_minimal_symbol msym
  2378.             = lookup_minimal_symbol (phys_name, NULL, NULL);

  2379.           if (!msym.minsym)
  2380.             return allocate_optimized_out_value (type);
  2381.           else
  2382.             {
  2383.               retval = value_at_lazy (TYPE_FIELD_TYPE (type, fieldno),
  2384.                                       BMSYMBOL_VALUE_ADDRESS (msym));
  2385.             }
  2386.         }
  2387.       else
  2388.         retval = value_of_variable (sym, NULL);
  2389.       break;
  2390.     }
  2391.     default:
  2392.       gdb_assert_not_reached ("unexpected field location kind");
  2393.     }

  2394.   return retval;
  2395. }

  2396. /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.
  2397.    You have to be careful here, since the size of the data area for the value
  2398.    is set by the length of the enclosing type.  So if NEW_ENCL_TYPE is bigger
  2399.    than the old enclosing type, you have to allocate more space for the
  2400.    data.  */

  2401. void
  2402. set_value_enclosing_type (struct value *val, struct type *new_encl_type)
  2403. {
  2404.   if (TYPE_LENGTH (new_encl_type) > TYPE_LENGTH (value_enclosing_type (val)))
  2405.     val->contents =
  2406.       (gdb_byte *) xrealloc (val->contents, TYPE_LENGTH (new_encl_type));

  2407.   val->enclosing_type = new_encl_type;
  2408. }

  2409. /* Given a value ARG1 (offset by OFFSET bytes)
  2410.    of a struct or union type ARG_TYPE,
  2411.    extract and return the value of one of its (non-static) fields.
  2412.    FIELDNO says which field.  */

  2413. struct value *
  2414. value_primitive_field (struct value *arg1, int offset,
  2415.                        int fieldno, struct type *arg_type)
  2416. {
  2417.   struct value *v;
  2418.   struct type *type;

  2419.   CHECK_TYPEDEF (arg_type);
  2420.   type = TYPE_FIELD_TYPE (arg_type, fieldno);

  2421.   /* Call check_typedef on our type to make sure that, if TYPE
  2422.      is a TYPE_CODE_TYPEDEF, its length is set to the length
  2423.      of the target type instead of zero.  However, we do not
  2424.      replace the typedef type by the target type, because we want
  2425.      to keep the typedef in order to be able to print the type
  2426.      description correctly.  */
  2427.   check_typedef (type);

  2428.   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
  2429.     {
  2430.       /* Handle packed fields.

  2431.          Create a new value for the bitfield, with bitpos and bitsize
  2432.          set.  If possible, arrange offset and bitpos so that we can
  2433.          do a single aligned read of the size of the containing type.
  2434.          Otherwise, adjust offset to the byte containing the first
  2435.          bit.  Assume that the address, offset, and embedded offset
  2436.          are sufficiently aligned.  */

  2437.       int bitpos = TYPE_FIELD_BITPOS (arg_type, fieldno);
  2438.       int container_bitsize = TYPE_LENGTH (type) * 8;

  2439.       v = allocate_value_lazy (type);
  2440.       v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
  2441.       if ((bitpos % container_bitsize) + v->bitsize <= container_bitsize
  2442.           && TYPE_LENGTH (type) <= (int) sizeof (LONGEST))
  2443.         v->bitpos = bitpos % container_bitsize;
  2444.       else
  2445.         v->bitpos = bitpos % 8;
  2446.       v->offset = (value_embedded_offset (arg1)
  2447.                    + offset
  2448.                    + (bitpos - v->bitpos) / 8);
  2449.       set_value_parent (v, arg1);
  2450.       if (!value_lazy (arg1))
  2451.         value_fetch_lazy (v);
  2452.     }
  2453.   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
  2454.     {
  2455.       /* This field is actually a base subobject, so preserve the
  2456.          entire object's contents for later references to virtual
  2457.          bases, etc.  */
  2458.       int boffset;

  2459.       /* Lazy register values with offsets are not supported.  */
  2460.       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
  2461.         value_fetch_lazy (arg1);

  2462.       /* We special case virtual inheritance here because this
  2463.          requires access to the contents, which we would rather avoid
  2464.          for references to ordinary fields of unavailable values.  */
  2465.       if (BASETYPE_VIA_VIRTUAL (arg_type, fieldno))
  2466.         boffset = baseclass_offset (arg_type, fieldno,
  2467.                                     value_contents (arg1),
  2468.                                     value_embedded_offset (arg1),
  2469.                                     value_address (arg1),
  2470.                                     arg1);
  2471.       else
  2472.         boffset = TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;

  2473.       if (value_lazy (arg1))
  2474.         v = allocate_value_lazy (value_enclosing_type (arg1));
  2475.       else
  2476.         {
  2477.           v = allocate_value (value_enclosing_type (arg1));
  2478.           value_contents_copy_raw (v, 0, arg1, 0,
  2479.                                    TYPE_LENGTH (value_enclosing_type (arg1)));
  2480.         }
  2481.       v->type = type;
  2482.       v->offset = value_offset (arg1);
  2483.       v->embedded_offset = offset + value_embedded_offset (arg1) + boffset;
  2484.     }
  2485.   else
  2486.     {
  2487.       /* Plain old data member */
  2488.       offset += TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;

  2489.       /* Lazy register values with offsets are not supported.  */
  2490.       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
  2491.         value_fetch_lazy (arg1);

  2492.       if (value_lazy (arg1))
  2493.         v = allocate_value_lazy (type);
  2494.       else
  2495.         {
  2496.           v = allocate_value (type);
  2497.           value_contents_copy_raw (v, value_embedded_offset (v),
  2498.                                    arg1, value_embedded_offset (arg1) + offset,
  2499.                                    TYPE_LENGTH (type));
  2500.         }
  2501.       v->offset = (value_offset (arg1) + offset
  2502.                    + value_embedded_offset (arg1));
  2503.     }
  2504.   set_value_component_location (v, arg1);
  2505.   VALUE_REGNUM (v) = VALUE_REGNUM (arg1);
  2506.   VALUE_FRAME_ID (v) = VALUE_FRAME_ID (arg1);
  2507.   return v;
  2508. }

  2509. /* Given a value ARG1 of a struct or union type,
  2510.    extract and return the value of one of its (non-static) fields.
  2511.    FIELDNO says which field.  */

  2512. struct value *
  2513. value_field (struct value *arg1, int fieldno)
  2514. {
  2515.   return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
  2516. }

  2517. /* Return a non-virtual function as a value.
  2518.    F is the list of member functions which contains the desired method.
  2519.    J is an index into F which provides the desired method.

  2520.    We only use the symbol for its address, so be happy with either a
  2521.    full symbol or a minimal symbol.  */

  2522. struct value *
  2523. value_fn_field (struct value **arg1p, struct fn_field *f,
  2524.                 int j, struct type *type,
  2525.                 int offset)
  2526. {
  2527.   struct value *v;
  2528.   struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
  2529.   const char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
  2530.   struct symbol *sym;
  2531.   struct bound_minimal_symbol msym;

  2532.   sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0);
  2533.   if (sym != NULL)
  2534.     {
  2535.       memset (&msym, 0, sizeof (msym));
  2536.     }
  2537.   else
  2538.     {
  2539.       gdb_assert (sym == NULL);
  2540.       msym = lookup_bound_minimal_symbol (physname);
  2541.       if (msym.minsym == NULL)
  2542.         return NULL;
  2543.     }

  2544.   v = allocate_value (ftype);
  2545.   if (sym)
  2546.     {
  2547.       set_value_address (v, BLOCK_START (SYMBOL_BLOCK_VALUE (sym)));
  2548.     }
  2549.   else
  2550.     {
  2551.       /* The minimal symbol might point to a function descriptor;
  2552.          resolve it to the actual code address instead.  */
  2553.       struct objfile *objfile = msym.objfile;
  2554.       struct gdbarch *gdbarch = get_objfile_arch (objfile);

  2555.       set_value_address (v,
  2556.         gdbarch_convert_from_func_ptr_addr
  2557.            (gdbarch, BMSYMBOL_VALUE_ADDRESS (msym), &current_target));
  2558.     }

  2559.   if (arg1p)
  2560.     {
  2561.       if (type != value_type (*arg1p))
  2562.         *arg1p = value_ind (value_cast (lookup_pointer_type (type),
  2563.                                         value_addr (*arg1p)));

  2564.       /* Move the `this' pointer according to the offset.
  2565.          VALUE_OFFSET (*arg1p) += offset; */
  2566.     }

  2567.   return v;
  2568. }



  2569. /* Unpack a bitfield of the specified FIELD_TYPE, from the object at
  2570.    VALADDR, and store the result in *RESULT.
  2571.    The bitfield starts at BITPOS bits and contains BITSIZE bits.

  2572.    Extracting bits depends on endianness of the machine.  Compute the
  2573.    number of least significant bits to discard.  For big endian machines,
  2574.    we compute the total number of bits in the anonymous object, subtract
  2575.    off the bit count from the MSB of the object to the MSB of the
  2576.    bitfield, then the size of the bitfield, which leaves the LSB discard
  2577.    count.  For little endian machines, the discard count is simply the
  2578.    number of bits from the LSB of the anonymous object to the LSB of the
  2579.    bitfield.

  2580.    If the field is signed, we also do sign extension.  */

  2581. static LONGEST
  2582. unpack_bits_as_long (struct type *field_type, const gdb_byte *valaddr,
  2583.                      int bitpos, int bitsize)
  2584. {
  2585.   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (field_type));
  2586.   ULONGEST val;
  2587.   ULONGEST valmask;
  2588.   int lsbcount;
  2589.   int bytes_read;
  2590.   int read_offset;

  2591.   /* Read the minimum number of bytes required; there may not be
  2592.      enough bytes to read an entire ULONGEST.  */
  2593.   CHECK_TYPEDEF (field_type);
  2594.   if (bitsize)
  2595.     bytes_read = ((bitpos % 8) + bitsize + 7) / 8;
  2596.   else
  2597.     bytes_read = TYPE_LENGTH (field_type);

  2598.   read_offset = bitpos / 8;

  2599.   val = extract_unsigned_integer (valaddr + read_offset,
  2600.                                   bytes_read, byte_order);

  2601.   /* Extract bits.  See comment above.  */

  2602.   if (gdbarch_bits_big_endian (get_type_arch (field_type)))
  2603.     lsbcount = (bytes_read * 8 - bitpos % 8 - bitsize);
  2604.   else
  2605.     lsbcount = (bitpos % 8);
  2606.   val >>= lsbcount;

  2607.   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
  2608.      If the field is signed, and is negative, then sign extend.  */

  2609.   if ((bitsize > 0) && (bitsize < 8 * (int) sizeof (val)))
  2610.     {
  2611.       valmask = (((ULONGEST) 1) << bitsize) - 1;
  2612.       val &= valmask;
  2613.       if (!TYPE_UNSIGNED (field_type))
  2614.         {
  2615.           if (val & (valmask ^ (valmask >> 1)))
  2616.             {
  2617.               val |= ~valmask;
  2618.             }
  2619.         }
  2620.     }

  2621.   return val;
  2622. }

  2623. /* Unpack a field FIELDNO of the specified TYPE, from the object at
  2624.    VALADDR + EMBEDDED_OFFSET.  VALADDR points to the contents of
  2625.    ORIGINAL_VALUE, which must not be NULL.  See
  2626.    unpack_value_bits_as_long for more details.  */

  2627. int
  2628. unpack_value_field_as_long (struct type *type, const gdb_byte *valaddr,
  2629.                             int embedded_offset, int fieldno,
  2630.                             const struct value *val, LONGEST *result)
  2631. {
  2632.   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
  2633.   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
  2634.   struct type *field_type = TYPE_FIELD_TYPE (type, fieldno);
  2635.   int bit_offset;

  2636.   gdb_assert (val != NULL);

  2637.   bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
  2638.   if (value_bits_any_optimized_out (val, bit_offset, bitsize)
  2639.       || !value_bits_available (val, bit_offset, bitsize))
  2640.     return 0;

  2641.   *result = unpack_bits_as_long (field_type, valaddr + embedded_offset,
  2642.                                  bitpos, bitsize);
  2643.   return 1;
  2644. }

  2645. /* Unpack a field FIELDNO of the specified TYPE, from the anonymous
  2646.    object at VALADDR.  See unpack_bits_as_long for more details.  */

  2647. LONGEST
  2648. unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
  2649. {
  2650.   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
  2651.   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
  2652.   struct type *field_type = TYPE_FIELD_TYPE (type, fieldno);

  2653.   return unpack_bits_as_long (field_type, valaddr, bitpos, bitsize);
  2654. }

  2655. /* Unpack a bitfield of BITSIZE bits found at BITPOS in the object at
  2656.    VALADDR + EMBEDDEDOFFSET that has the type of DEST_VAL and store
  2657.    the contents in DEST_VAL, zero or sign extending if the type of
  2658.    DEST_VAL is wider than BITSIZE.  VALADDR points to the contents of
  2659.    VAL.  If the VAL's contents required to extract the bitfield from
  2660.    are unavailable/optimized out, DEST_VAL is correspondingly
  2661.    marked unavailable/optimized out.  */

  2662. void
  2663. unpack_value_bitfield (struct value *dest_val,
  2664.                        int bitpos, int bitsize,
  2665.                        const gdb_byte *valaddr, int embedded_offset,
  2666.                        const struct value *val)
  2667. {
  2668.   enum bfd_endian byte_order;
  2669.   int src_bit_offset;
  2670.   int dst_bit_offset;
  2671.   LONGEST num;
  2672.   struct type *field_type = value_type (dest_val);

  2673.   /* First, unpack and sign extend the bitfield as if it was wholly
  2674.      available.  Invalid/unavailable bits are read as zero, but that's
  2675.      OK, as they'll end up marked below.  */
  2676.   byte_order = gdbarch_byte_order (get_type_arch (field_type));
  2677.   num = unpack_bits_as_long (field_type, valaddr + embedded_offset,
  2678.                              bitpos, bitsize);
  2679.   store_signed_integer (value_contents_raw (dest_val),
  2680.                         TYPE_LENGTH (field_type), byte_order, num);

  2681.   /* Now copy the optimized out / unavailability ranges to the right
  2682.      bits.  */
  2683.   src_bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
  2684.   if (byte_order == BFD_ENDIAN_BIG)
  2685.     dst_bit_offset = TYPE_LENGTH (field_type) * TARGET_CHAR_BIT - bitsize;
  2686.   else
  2687.     dst_bit_offset = 0;
  2688.   value_ranges_copy_adjusted (dest_val, dst_bit_offset,
  2689.                               val, src_bit_offset, bitsize);
  2690. }

  2691. /* Return a new value with type TYPE, which is FIELDNO field of the
  2692.    object at VALADDR + EMBEDDEDOFFSET.  VALADDR points to the contents
  2693.    of VAL.  If the VAL's contents required to extract the bitfield
  2694.    from are unavailable/optimized out, the new value is
  2695.    correspondingly marked unavailable/optimized out.  */

  2696. struct value *
  2697. value_field_bitfield (struct type *type, int fieldno,
  2698.                       const gdb_byte *valaddr,
  2699.                       int embedded_offset, const struct value *val)
  2700. {
  2701.   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
  2702.   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
  2703.   struct value *res_val = allocate_value (TYPE_FIELD_TYPE (type, fieldno));

  2704.   unpack_value_bitfield (res_val, bitpos, bitsize,
  2705.                          valaddr, embedded_offset, val);

  2706.   return res_val;
  2707. }

  2708. /* Modify the value of a bitfield.  ADDR points to a block of memory in
  2709.    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
  2710.    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
  2711.    indicate which bits (in target bit order) comprise the bitfield.
  2712.    Requires 0 < BITSIZE <= lbits, 0 <= BITPOS % 8 + BITSIZE <= lbits, and
  2713.    0 <= BITPOS, where lbits is the size of a LONGEST in bits.  */

  2714. void
  2715. modify_field (struct type *type, gdb_byte *addr,
  2716.               LONGEST fieldval, int bitpos, int bitsize)
  2717. {
  2718.   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
  2719.   ULONGEST oword;
  2720.   ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
  2721.   int bytesize;

  2722.   /* Normalize BITPOS.  */
  2723.   addr += bitpos / 8;
  2724.   bitpos %= 8;

  2725.   /* If a negative fieldval fits in the field in question, chop
  2726.      off the sign extension bits.  */
  2727.   if ((~fieldval & ~(mask >> 1)) == 0)
  2728.     fieldval &= mask;

  2729.   /* Warn if value is too big to fit in the field in question.  */
  2730.   if (0 != (fieldval & ~mask))
  2731.     {
  2732.       /* FIXME: would like to include fieldval in the message, but
  2733.          we don't have a sprintf_longest.  */
  2734.       warning (_("Value does not fit in %d bits."), bitsize);

  2735.       /* Truncate it, otherwise adjoining fields may be corrupted.  */
  2736.       fieldval &= mask;
  2737.     }

  2738.   /* Ensure no bytes outside of the modified ones get accessed as it may cause
  2739.      false valgrind reports.  */

  2740.   bytesize = (bitpos + bitsize + 7) / 8;
  2741.   oword = extract_unsigned_integer (addr, bytesize, byte_order);

  2742.   /* Shifting for bit field depends on endianness of the target machine.  */
  2743.   if (gdbarch_bits_big_endian (get_type_arch (type)))
  2744.     bitpos = bytesize * 8 - bitpos - bitsize;

  2745.   oword &= ~(mask << bitpos);
  2746.   oword |= fieldval << bitpos;

  2747.   store_unsigned_integer (addr, bytesize, byte_order, oword);
  2748. }

  2749. /* Pack NUM into BUF using a target format of TYPE.  */

  2750. void
  2751. pack_long (gdb_byte *buf, struct type *type, LONGEST num)
  2752. {
  2753.   enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type));
  2754.   int len;

  2755.   type = check_typedef (type);
  2756.   len = TYPE_LENGTH (type);

  2757.   switch (TYPE_CODE (type))
  2758.     {
  2759.     case TYPE_CODE_INT:
  2760.     case TYPE_CODE_CHAR:
  2761.     case TYPE_CODE_ENUM:
  2762.     case TYPE_CODE_FLAGS:
  2763.     case TYPE_CODE_BOOL:
  2764.     case TYPE_CODE_RANGE:
  2765.     case TYPE_CODE_MEMBERPTR:
  2766.       store_signed_integer (buf, len, byte_order, num);
  2767.       break;

  2768.     case TYPE_CODE_REF:
  2769.     case TYPE_CODE_PTR:
  2770.       store_typed_address (buf, type, (CORE_ADDR) num);
  2771.       break;

  2772.     default:
  2773.       error (_("Unexpected type (%d) encountered for integer constant."),
  2774.              TYPE_CODE (type));
  2775.     }
  2776. }


  2777. /* Pack NUM into BUF using a target format of TYPE.  */

  2778. static void
  2779. pack_unsigned_long (gdb_byte *buf, struct type *type, ULONGEST num)
  2780. {
  2781.   int len;
  2782.   enum bfd_endian byte_order;

  2783.   type = check_typedef (type);
  2784.   len = TYPE_LENGTH (type);
  2785.   byte_order = gdbarch_byte_order (get_type_arch (type));

  2786.   switch (TYPE_CODE (type))
  2787.     {
  2788.     case TYPE_CODE_INT:
  2789.     case TYPE_CODE_CHAR:
  2790.     case TYPE_CODE_ENUM:
  2791.     case TYPE_CODE_FLAGS:
  2792.     case TYPE_CODE_BOOL:
  2793.     case TYPE_CODE_RANGE:
  2794.     case TYPE_CODE_MEMBERPTR:
  2795.       store_unsigned_integer (buf, len, byte_order, num);
  2796.       break;

  2797.     case TYPE_CODE_REF:
  2798.     case TYPE_CODE_PTR:
  2799.       store_typed_address (buf, type, (CORE_ADDR) num);
  2800.       break;

  2801.     default:
  2802.       error (_("Unexpected type (%d) encountered "
  2803.                "for unsigned integer constant."),
  2804.              TYPE_CODE (type));
  2805.     }
  2806. }


  2807. /* Convert C numbers into newly allocated values.  */

  2808. struct value *
  2809. value_from_longest (struct type *type, LONGEST num)
  2810. {
  2811.   struct value *val = allocate_value (type);

  2812.   pack_long (value_contents_raw (val), type, num);
  2813.   return val;
  2814. }


  2815. /* Convert C unsigned numbers into newly allocated values.  */

  2816. struct value *
  2817. value_from_ulongest (struct type *type, ULONGEST num)
  2818. {
  2819.   struct value *val = allocate_value (type);

  2820.   pack_unsigned_long (value_contents_raw (val), type, num);

  2821.   return val;
  2822. }


  2823. /* Create a value representing a pointer of type TYPE to the address
  2824.    ADDR.  */

  2825. struct value *
  2826. value_from_pointer (struct type *type, CORE_ADDR addr)
  2827. {
  2828.   struct value *val = allocate_value (type);

  2829.   store_typed_address (value_contents_raw (val),
  2830.                        check_typedef (type), addr);
  2831.   return val;
  2832. }


  2833. /* Create a value of type TYPE whose contents come from VALADDR, if it
  2834.    is non-null, and whose memory address (in the inferior) is
  2835.    ADDRESS.  The type of the created value may differ from the passed
  2836.    type TYPE.  Make sure to retrieve values new type after this call.
  2837.    Note that TYPE is not passed through resolve_dynamic_type; this is
  2838.    a special API intended for use only by Ada.  */

  2839. struct value *
  2840. value_from_contents_and_address_unresolved (struct type *type,
  2841.                                             const gdb_byte *valaddr,
  2842.                                             CORE_ADDR address)
  2843. {
  2844.   struct value *v;

  2845.   if (valaddr == NULL)
  2846.     v = allocate_value_lazy (type);
  2847.   else
  2848.     v = value_from_contents (type, valaddr);
  2849.   set_value_address (v, address);
  2850.   VALUE_LVAL (v) = lval_memory;
  2851.   return v;
  2852. }

  2853. /* Create a value of type TYPE whose contents come from VALADDR, if it
  2854.    is non-null, and whose memory address (in the inferior) is
  2855.    ADDRESS.  The type of the created value may differ from the passed
  2856.    type TYPE.  Make sure to retrieve values new type after this call.  */

  2857. struct value *
  2858. value_from_contents_and_address (struct type *type,
  2859.                                  const gdb_byte *valaddr,
  2860.                                  CORE_ADDR address)
  2861. {
  2862.   struct type *resolved_type = resolve_dynamic_type (type, address);
  2863.   struct type *resolved_type_no_typedef = check_typedef (resolved_type);
  2864.   struct value *v;

  2865.   if (valaddr == NULL)
  2866.     v = allocate_value_lazy (resolved_type);
  2867.   else
  2868.     v = value_from_contents (resolved_type, valaddr);
  2869.   if (TYPE_DATA_LOCATION (resolved_type_no_typedef) != NULL
  2870.       && TYPE_DATA_LOCATION_KIND (resolved_type_no_typedef) == PROP_CONST)
  2871.     address = TYPE_DATA_LOCATION_ADDR (resolved_type_no_typedef);
  2872.   set_value_address (v, address);
  2873.   VALUE_LVAL (v) = lval_memory;
  2874.   return v;
  2875. }

  2876. /* Create a value of type TYPE holding the contents CONTENTS.
  2877.    The new value is `not_lval'.  */

  2878. struct value *
  2879. value_from_contents (struct type *type, const gdb_byte *contents)
  2880. {
  2881.   struct value *result;

  2882.   result = allocate_value (type);
  2883.   memcpy (value_contents_raw (result), contents, TYPE_LENGTH (type));
  2884.   return result;
  2885. }

  2886. struct value *
  2887. value_from_double (struct type *type, DOUBLEST num)
  2888. {
  2889.   struct value *val = allocate_value (type);
  2890.   struct type *base_type = check_typedef (type);
  2891.   enum type_code code = TYPE_CODE (base_type);

  2892.   if (code == TYPE_CODE_FLT)
  2893.     {
  2894.       store_typed_floating (value_contents_raw (val), base_type, num);
  2895.     }
  2896.   else
  2897.     error (_("Unexpected type encountered for floating constant."));

  2898.   return val;
  2899. }

  2900. struct value *
  2901. value_from_decfloat (struct type *type, const gdb_byte *dec)
  2902. {
  2903.   struct value *val = allocate_value (type);

  2904.   memcpy (value_contents_raw (val), dec, TYPE_LENGTH (type));
  2905.   return val;
  2906. }

  2907. /* Extract a value from the history file.  Input will be of the form
  2908.    $digits or $$digits.  See block comment above 'write_dollar_variable'
  2909.    for details.  */

  2910. struct value *
  2911. value_from_history_ref (const char *h, const char **endp)
  2912. {
  2913.   int index, len;

  2914.   if (h[0] == '$')
  2915.     len = 1;
  2916.   else
  2917.     return NULL;

  2918.   if (h[1] == '$')
  2919.     len = 2;

  2920.   /* Find length of numeral string.  */
  2921.   for (; isdigit (h[len]); len++)
  2922.     ;

  2923.   /* Make sure numeral string is not part of an identifier.  */
  2924.   if (h[len] == '_' || isalpha (h[len]))
  2925.     return NULL;

  2926.   /* Now collect the index value.  */
  2927.   if (h[1] == '$')
  2928.     {
  2929.       if (len == 2)
  2930.         {
  2931.           /* For some bizarre reason, "$$" is equivalent to "$$1",
  2932.              rather than to "$$0" as it ought to be!  */
  2933.           index = -1;
  2934.           *endp += len;
  2935.         }
  2936.       else
  2937.         {
  2938.           char *local_end;

  2939.           index = -strtol (&h[2], &local_end, 10);
  2940.           *endp = local_end;
  2941.         }
  2942.     }
  2943.   else
  2944.     {
  2945.       if (len == 1)
  2946.         {
  2947.           /* "$" is equivalent to "$0".  */
  2948.           index = 0;
  2949.           *endp += len;
  2950.         }
  2951.       else
  2952.         {
  2953.           char *local_end;

  2954.           index = strtol (&h[1], &local_end, 10);
  2955.           *endp = local_end;
  2956.         }
  2957.     }

  2958.   return access_value_history (index);
  2959. }

  2960. struct value *
  2961. coerce_ref_if_computed (const struct value *arg)
  2962. {
  2963.   const struct lval_funcs *funcs;

  2964.   if (TYPE_CODE (check_typedef (value_type (arg))) != TYPE_CODE_REF)
  2965.     return NULL;

  2966.   if (value_lval_const (arg) != lval_computed)
  2967.     return NULL;

  2968.   funcs = value_computed_funcs (arg);
  2969.   if (funcs->coerce_ref == NULL)
  2970.     return NULL;

  2971.   return funcs->coerce_ref (arg);
  2972. }

  2973. /* Look at value.h for description.  */

  2974. struct value *
  2975. readjust_indirect_value_type (struct value *value, struct type *enc_type,
  2976.                               struct type *original_type,
  2977.                               struct value *original_value)
  2978. {
  2979.   /* Re-adjust type.  */
  2980.   deprecated_set_value_type (value, TYPE_TARGET_TYPE (original_type));

  2981.   /* Add embedding info.  */
  2982.   set_value_enclosing_type (value, enc_type);
  2983.   set_value_embedded_offset (value, value_pointed_to_offset (original_value));

  2984.   /* We may be pointing to an object of some derived type.  */
  2985.   return value_full_object (value, NULL, 0, 0, 0);
  2986. }

  2987. struct value *
  2988. coerce_ref (struct value *arg)
  2989. {
  2990.   struct type *value_type_arg_tmp = check_typedef (value_type (arg));
  2991.   struct value *retval;
  2992.   struct type *enc_type;

  2993.   retval = coerce_ref_if_computed (arg);
  2994.   if (retval)
  2995.     return retval;

  2996.   if (TYPE_CODE (value_type_arg_tmp) != TYPE_CODE_REF)
  2997.     return arg;

  2998.   enc_type = check_typedef (value_enclosing_type (arg));
  2999.   enc_type = TYPE_TARGET_TYPE (enc_type);

  3000.   retval = value_at_lazy (enc_type,
  3001.                           unpack_pointer (value_type (arg),
  3002.                                           value_contents (arg)));
  3003.   enc_type = value_type (retval);
  3004.   return readjust_indirect_value_type (retval, enc_type,
  3005.                                        value_type_arg_tmp, arg);
  3006. }

  3007. struct value *
  3008. coerce_array (struct value *arg)
  3009. {
  3010.   struct type *type;

  3011.   arg = coerce_ref (arg);
  3012.   type = check_typedef (value_type (arg));

  3013.   switch (TYPE_CODE (type))
  3014.     {
  3015.     case TYPE_CODE_ARRAY:
  3016.       if (!TYPE_VECTOR (type) && current_language->c_style_arrays)
  3017.         arg = value_coerce_array (arg);
  3018.       break;
  3019.     case TYPE_CODE_FUNC:
  3020.       arg = value_coerce_function (arg);
  3021.       break;
  3022.     }
  3023.   return arg;
  3024. }


  3025. /* Return the return value convention that will be used for the
  3026.    specified type.  */

  3027. enum return_value_convention
  3028. struct_return_convention (struct gdbarch *gdbarch,
  3029.                           struct value *function, struct type *value_type)
  3030. {
  3031.   enum type_code code = TYPE_CODE (value_type);

  3032.   if (code == TYPE_CODE_ERROR)
  3033.     error (_("Function return type unknown."));

  3034.   /* Probe the architecture for the return-value convention.  */
  3035.   return gdbarch_return_value (gdbarch, function, value_type,
  3036.                                NULL, NULL, NULL);
  3037. }

  3038. /* Return true if the function returning the specified type is using
  3039.    the convention of returning structures in memory (passing in the
  3040.    address as a hidden first parameter).  */

  3041. int
  3042. using_struct_return (struct gdbarch *gdbarch,
  3043.                      struct value *function, struct type *value_type)
  3044. {
  3045.   if (TYPE_CODE (value_type) == TYPE_CODE_VOID)
  3046.     /* A void return value is never in memory.  See also corresponding
  3047.        code in "print_return_value".  */
  3048.     return 0;

  3049.   return (struct_return_convention (gdbarch, function, value_type)
  3050.           != RETURN_VALUE_REGISTER_CONVENTION);
  3051. }

  3052. /* Set the initialized field in a value struct.  */

  3053. void
  3054. set_value_initialized (struct value *val, int status)
  3055. {
  3056.   val->initialized = status;
  3057. }

  3058. /* Return the initialized field in a value struct.  */

  3059. int
  3060. value_initialized (struct value *val)
  3061. {
  3062.   return val->initialized;
  3063. }

  3064. /* Called only from the value_contents and value_contents_all()
  3065.    macros, if the current data for a variable needs to be loaded into
  3066.    value_contents(VAL).  Fetches the data from the user's process, and
  3067.    clears the lazy flag to indicate that the data in the buffer is
  3068.    valid.

  3069.    If the value is zero-length, we avoid calling read_memory, which
  3070.    would abort.  We mark the value as fetched anyway -- all 0 bytes of
  3071.    it.

  3072.    This function returns a value because it is used in the
  3073.    value_contents macro as part of an expression, where a void would
  3074.    not work.  The value is ignored.  */

  3075. int
  3076. value_fetch_lazy (struct value *val)
  3077. {
  3078.   gdb_assert (value_lazy (val));
  3079.   allocate_value_contents (val);
  3080.   /* A value is either lazy, or fully fetched.  The
  3081.      availability/validity is only established as we try to fetch a
  3082.      value.  */
  3083.   gdb_assert (VEC_empty (range_s, val->optimized_out));
  3084.   gdb_assert (VEC_empty (range_s, val->unavailable));
  3085.   if (value_bitsize (val))
  3086.     {
  3087.       /* To read a lazy bitfield, read the entire enclosing value.  This
  3088.          prevents reading the same block of (possibly volatile) memory once
  3089.          per bitfield.  It would be even better to read only the containing
  3090.          word, but we have no way to record that just specific bits of a
  3091.          value have been fetched.  */
  3092.       struct type *type = check_typedef (value_type (val));
  3093.       struct value *parent = value_parent (val);

  3094.       if (value_lazy (parent))
  3095.         value_fetch_lazy (parent);

  3096.       unpack_value_bitfield (val,
  3097.                              value_bitpos (val), value_bitsize (val),
  3098.                              value_contents_for_printing (parent),
  3099.                              value_offset (val), parent);
  3100.     }
  3101.   else if (VALUE_LVAL (val) == lval_memory)
  3102.     {
  3103.       CORE_ADDR addr = value_address (val);
  3104.       struct type *type = check_typedef (value_enclosing_type (val));

  3105.       if (TYPE_LENGTH (type))
  3106.         read_value_memory (val, 0, value_stack (val),
  3107.                            addr, value_contents_all_raw (val),
  3108.                            TYPE_LENGTH (type));
  3109.     }
  3110.   else if (VALUE_LVAL (val) == lval_register)
  3111.     {
  3112.       struct frame_info *frame;
  3113.       int regnum;
  3114.       struct type *type = check_typedef (value_type (val));
  3115.       struct value *new_val = val, *mark = value_mark ();

  3116.       /* Offsets are not supported here; lazy register values must
  3117.          refer to the entire register.  */
  3118.       gdb_assert (value_offset (val) == 0);

  3119.       while (VALUE_LVAL (new_val) == lval_register && value_lazy (new_val))
  3120.         {
  3121.           struct frame_id frame_id = VALUE_FRAME_ID (new_val);

  3122.           frame = frame_find_by_id (frame_id);
  3123.           regnum = VALUE_REGNUM (new_val);

  3124.           gdb_assert (frame != NULL);

  3125.           /* Convertible register routines are used for multi-register
  3126.              values and for interpretation in different types
  3127.              (e.g. float or int from a double register).  Lazy
  3128.              register values should have the register's natural type,
  3129.              so they do not apply.  */
  3130.           gdb_assert (!gdbarch_convert_register_p (get_frame_arch (frame),
  3131.                                                    regnum, type));

  3132.           new_val = get_frame_register_value (frame, regnum);

  3133.           /* If we get another lazy lval_register value, it means the
  3134.              register is found by reading it from the next frame.
  3135.              get_frame_register_value should never return a value with
  3136.              the frame id pointing to FRAME.  If it does, it means we
  3137.              either have two consecutive frames with the same frame id
  3138.              in the frame chain, or some code is trying to unwind
  3139.              behind get_prev_frame's back (e.g., a frame unwind
  3140.              sniffer trying to unwind), bypassing its validations.  In
  3141.              any case, it should always be an internal error to end up
  3142.              in this situation.  */
  3143.           if (VALUE_LVAL (new_val) == lval_register
  3144.               && value_lazy (new_val)
  3145.               && frame_id_eq (VALUE_FRAME_ID (new_val), frame_id))
  3146.             internal_error (__FILE__, __LINE__,
  3147.                             _("infinite loop while fetching a register"));
  3148.         }

  3149.       /* If it's still lazy (for instance, a saved register on the
  3150.          stack), fetch it.  */
  3151.       if (value_lazy (new_val))
  3152.         value_fetch_lazy (new_val);

  3153.       /* Copy the contents and the unavailability/optimized-out
  3154.          meta-data from NEW_VAL to VAL.  */
  3155.       set_value_lazy (val, 0);
  3156.       value_contents_copy (val, value_embedded_offset (val),
  3157.                            new_val, value_embedded_offset (new_val),
  3158.                            TYPE_LENGTH (type));

  3159.       if (frame_debug)
  3160.         {
  3161.           struct gdbarch *gdbarch;
  3162.           frame = frame_find_by_id (VALUE_FRAME_ID (val));
  3163.           regnum = VALUE_REGNUM (val);
  3164.           gdbarch = get_frame_arch (frame);

  3165.           fprintf_unfiltered (gdb_stdlog,
  3166.                               "{ value_fetch_lazy "
  3167.                               "(frame=%d,regnum=%d(%s),...) ",
  3168.                               frame_relative_level (frame), regnum,
  3169.                               user_reg_map_regnum_to_name (gdbarch, regnum));

  3170.           fprintf_unfiltered (gdb_stdlog, "->");
  3171.           if (value_optimized_out (new_val))
  3172.             {
  3173.               fprintf_unfiltered (gdb_stdlog, " ");
  3174.               val_print_optimized_out (new_val, gdb_stdlog);
  3175.             }
  3176.           else
  3177.             {
  3178.               int i;
  3179.               const gdb_byte *buf = value_contents (new_val);

  3180.               if (VALUE_LVAL (new_val) == lval_register)
  3181.                 fprintf_unfiltered (gdb_stdlog, " register=%d",
  3182.                                     VALUE_REGNUM (new_val));
  3183.               else if (VALUE_LVAL (new_val) == lval_memory)
  3184.                 fprintf_unfiltered (gdb_stdlog, " address=%s",
  3185.                                     paddress (gdbarch,
  3186.                                               value_address (new_val)));
  3187.               else
  3188.                 fprintf_unfiltered (gdb_stdlog, " computed");

  3189.               fprintf_unfiltered (gdb_stdlog, " bytes=");
  3190.               fprintf_unfiltered (gdb_stdlog, "[");
  3191.               for (i = 0; i < register_size (gdbarch, regnum); i++)
  3192.                 fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
  3193.               fprintf_unfiltered (gdb_stdlog, "]");
  3194.             }

  3195.           fprintf_unfiltered (gdb_stdlog, " }\n");
  3196.         }

  3197.       /* Dispose of the intermediate values.  This prevents
  3198.          watchpoints from trying to watch the saved frame pointer.  */
  3199.       value_free_to_mark (mark);
  3200.     }
  3201.   else if (VALUE_LVAL (val) == lval_computed
  3202.            && value_computed_funcs (val)->read != NULL)
  3203.     value_computed_funcs (val)->read (val);
  3204.   else
  3205.     internal_error (__FILE__, __LINE__, _("Unexpected lazy value type."));

  3206.   set_value_lazy (val, 0);
  3207.   return 0;
  3208. }

  3209. /* Implementation of the convenience function $_isvoid.  */

  3210. static struct value *
  3211. isvoid_internal_fn (struct gdbarch *gdbarch,
  3212.                     const struct language_defn *language,
  3213.                     void *cookie, int argc, struct value **argv)
  3214. {
  3215.   int ret;

  3216.   if (argc != 1)
  3217.     error (_("You must provide one argument for $_isvoid."));

  3218.   ret = TYPE_CODE (value_type (argv[0])) == TYPE_CODE_VOID;

  3219.   return value_from_longest (builtin_type (gdbarch)->builtin_int, ret);
  3220. }

  3221. void
  3222. _initialize_values (void)
  3223. {
  3224.   add_cmd ("convenience", no_class, show_convenience, _("\
  3225. Debugger convenience (\"$foo\") variables and functions.\n\
  3226. Convenience variables are created when you assign them values;\n\
  3227. thus, \"set $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\
  3228. \n\
  3229. A few convenience variables are given values automatically:\n\
  3230. \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
  3231. \"$__\" holds the contents of the last address examined with \"x\"."
  3232. #ifdef HAVE_PYTHON
  3233. "\n\n\
  3234. Convenience functions are defined via the Python API."
  3235. #endif
  3236.            ), &showlist);
  3237.   add_alias_cmd ("conv", "convenience", no_class, 1, &showlist);

  3238.   add_cmd ("values", no_set_class, show_values, _("\
  3239. Elements of value history around item number IDX (or last ten)."),
  3240.            &showlist);

  3241.   add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
  3242. Initialize a convenience variable if necessary.\n\
  3243. init-if-undefined VARIABLE = EXPRESSION\n\
  3244. Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
  3245. exist or does not contain a value.  The EXPRESSION is not evaluated if the\n\
  3246. VARIABLE is already initialized."));

  3247.   add_prefix_cmd ("function", no_class, function_command, _("\
  3248. Placeholder command for showing help on convenience functions."),
  3249.                   &functionlist, "function ", 0, &cmdlist);

  3250.   add_internal_function ("_isvoid", _("\
  3251. Check whether an expression is void.\n\
  3252. Usage: $_isvoid (expression)\n\
  3253. Return 1 if the expression is void, zero otherwise."),
  3254.                          isvoid_internal_fn, NULL);
  3255. }