OSDN Git Service

2005-02-02 Andrew Cagney <cagney@gnu.org>
[pf3gnuchains/pf3gnuchains3x.git] / gdb / value.c
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
2
3    Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
4    1995, 1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005 Free
5    Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24 #include "defs.h"
25 #include "gdb_string.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "value.h"
29 #include "gdbcore.h"
30 #include "command.h"
31 #include "gdbcmd.h"
32 #include "target.h"
33 #include "language.h"
34 #include "scm-lang.h"
35 #include "demangle.h"
36 #include "doublest.h"
37 #include "gdb_assert.h"
38 #include "regcache.h"
39 #include "block.h"
40
41 /* Prototypes for exported functions. */
42
43 void _initialize_values (void);
44
45 /* Prototypes for local functions. */
46
47 static void show_values (char *, int);
48
49 static void show_convenience (char *, int);
50
51
52 /* The value-history records all the values printed
53    by print commands during this session.  Each chunk
54    records 60 consecutive values.  The first chunk on
55    the chain records the most recent values.
56    The total number of values is in value_history_count.  */
57
58 #define VALUE_HISTORY_CHUNK 60
59
60 struct value_history_chunk
61   {
62     struct value_history_chunk *next;
63     struct value *values[VALUE_HISTORY_CHUNK];
64   };
65
66 /* Chain of chunks now in use.  */
67
68 static struct value_history_chunk *value_history_chain;
69
70 static int value_history_count; /* Abs number of last entry stored */
71 \f
72 /* List of all value objects currently allocated
73    (except for those released by calls to release_value)
74    This is so they can be freed after each command.  */
75
76 static struct value *all_values;
77
78 /* Allocate a  value  that has the correct length for type TYPE.  */
79
80 struct value *
81 allocate_value (struct type *type)
82 {
83   struct value *val;
84   struct type *atype = check_typedef (type);
85
86   val = (struct value *) xmalloc (sizeof (struct value) + TYPE_LENGTH (atype));
87   val->next = all_values;
88   all_values = val;
89   val->type = type;
90   val->enclosing_type = type;
91   VALUE_LVAL (val) = not_lval;
92   VALUE_ADDRESS (val) = 0;
93   VALUE_FRAME_ID (val) = null_frame_id;
94   val->offset = 0;
95   val->bitpos = 0;
96   val->bitsize = 0;
97   VALUE_REGNUM (val) = -1;
98   VALUE_LAZY (val) = 0;
99   VALUE_OPTIMIZED_OUT (val) = 0;
100   VALUE_EMBEDDED_OFFSET (val) = 0;
101   VALUE_POINTED_TO_OFFSET (val) = 0;
102   val->modifiable = 1;
103   return val;
104 }
105
106 /* Allocate a  value  that has the correct length
107    for COUNT repetitions type TYPE.  */
108
109 struct value *
110 allocate_repeat_value (struct type *type, int count)
111 {
112   int low_bound = current_language->string_lower_bound;         /* ??? */
113   /* FIXME-type-allocation: need a way to free this type when we are
114      done with it.  */
115   struct type *range_type
116   = create_range_type ((struct type *) NULL, builtin_type_int,
117                        low_bound, count + low_bound - 1);
118   /* FIXME-type-allocation: need a way to free this type when we are
119      done with it.  */
120   return allocate_value (create_array_type ((struct type *) NULL,
121                                             type, range_type));
122 }
123
124 /* Accessor methods.  */
125
126 struct type *
127 value_type (struct value *value)
128 {
129   return value->type;
130 }
131
132 int
133 value_offset (struct value *value)
134 {
135   return value->offset;
136 }
137
138 int
139 value_bitpos (struct value *value)
140 {
141   return value->bitpos;
142 }
143
144 int
145 value_bitsize (struct value *value)
146 {
147   return value->bitsize;
148 }
149
150 bfd_byte *
151 value_contents_raw (struct value *value)
152 {
153   return value->aligner.contents + value->embedded_offset;
154 }
155
156 bfd_byte *
157 value_contents_all_raw (struct value *value)
158 {
159   return value->aligner.contents;
160 }
161
162 struct type *
163 value_enclosing_type (struct value *value)
164 {
165   return value->enclosing_type;
166 }
167
168 const bfd_byte *
169 value_contents_all (struct value *value)
170 {
171   if (value->lazy)
172     value_fetch_lazy (value);
173   return value->aligner.contents;
174 }
175
176 \f
177 /* Return a mark in the value chain.  All values allocated after the
178    mark is obtained (except for those released) are subject to being freed
179    if a subsequent value_free_to_mark is passed the mark.  */
180 struct value *
181 value_mark (void)
182 {
183   return all_values;
184 }
185
186 /* Free all values allocated since MARK was obtained by value_mark
187    (except for those released).  */
188 void
189 value_free_to_mark (struct value *mark)
190 {
191   struct value *val;
192   struct value *next;
193
194   for (val = all_values; val && val != mark; val = next)
195     {
196       next = val->next;
197       value_free (val);
198     }
199   all_values = val;
200 }
201
202 /* Free all the values that have been allocated (except for those released).
203    Called after each command, successful or not.  */
204
205 void
206 free_all_values (void)
207 {
208   struct value *val;
209   struct value *next;
210
211   for (val = all_values; val; val = next)
212     {
213       next = val->next;
214       value_free (val);
215     }
216
217   all_values = 0;
218 }
219
220 /* Remove VAL from the chain all_values
221    so it will not be freed automatically.  */
222
223 void
224 release_value (struct value *val)
225 {
226   struct value *v;
227
228   if (all_values == val)
229     {
230       all_values = val->next;
231       return;
232     }
233
234   for (v = all_values; v; v = v->next)
235     {
236       if (v->next == val)
237         {
238           v->next = val->next;
239           break;
240         }
241     }
242 }
243
244 /* Release all values up to mark  */
245 struct value *
246 value_release_to_mark (struct value *mark)
247 {
248   struct value *val;
249   struct value *next;
250
251   for (val = next = all_values; next; next = next->next)
252     if (next->next == mark)
253       {
254         all_values = next->next;
255         next->next = NULL;
256         return val;
257       }
258   all_values = 0;
259   return val;
260 }
261
262 /* Return a copy of the value ARG.
263    It contains the same contents, for same memory address,
264    but it's a different block of storage.  */
265
266 struct value *
267 value_copy (struct value *arg)
268 {
269   struct type *encl_type = value_enclosing_type (arg);
270   struct value *val = allocate_value (encl_type);
271   val->type = arg->type;
272   VALUE_LVAL (val) = VALUE_LVAL (arg);
273   VALUE_ADDRESS (val) = VALUE_ADDRESS (arg);
274   val->offset = arg->offset;
275   val->bitpos = arg->bitpos;
276   val->bitsize = arg->bitsize;
277   VALUE_FRAME_ID (val) = VALUE_FRAME_ID (arg);
278   VALUE_REGNUM (val) = VALUE_REGNUM (arg);
279   VALUE_LAZY (val) = VALUE_LAZY (arg);
280   VALUE_OPTIMIZED_OUT (val) = VALUE_OPTIMIZED_OUT (arg);
281   VALUE_EMBEDDED_OFFSET (val) = VALUE_EMBEDDED_OFFSET (arg);
282   VALUE_POINTED_TO_OFFSET (val) = VALUE_POINTED_TO_OFFSET (arg);
283   val->modifiable = arg->modifiable;
284   if (!VALUE_LAZY (val))
285     {
286       memcpy (value_contents_all_raw (val), value_contents_all_raw (arg),
287               TYPE_LENGTH (value_enclosing_type (arg)));
288
289     }
290   return val;
291 }
292 \f
293 /* Access to the value history.  */
294
295 /* Record a new value in the value history.
296    Returns the absolute history index of the entry.
297    Result of -1 indicates the value was not saved; otherwise it is the
298    value history index of this new item.  */
299
300 int
301 record_latest_value (struct value *val)
302 {
303   int i;
304
305   /* We don't want this value to have anything to do with the inferior anymore.
306      In particular, "set $1 = 50" should not affect the variable from which
307      the value was taken, and fast watchpoints should be able to assume that
308      a value on the value history never changes.  */
309   if (VALUE_LAZY (val))
310     value_fetch_lazy (val);
311   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
312      from.  This is a bit dubious, because then *&$1 does not just return $1
313      but the current contents of that location.  c'est la vie...  */
314   val->modifiable = 0;
315   release_value (val);
316
317   /* Here we treat value_history_count as origin-zero
318      and applying to the value being stored now.  */
319
320   i = value_history_count % VALUE_HISTORY_CHUNK;
321   if (i == 0)
322     {
323       struct value_history_chunk *new
324       = (struct value_history_chunk *)
325       xmalloc (sizeof (struct value_history_chunk));
326       memset (new->values, 0, sizeof new->values);
327       new->next = value_history_chain;
328       value_history_chain = new;
329     }
330
331   value_history_chain->values[i] = val;
332
333   /* Now we regard value_history_count as origin-one
334      and applying to the value just stored.  */
335
336   return ++value_history_count;
337 }
338
339 /* Return a copy of the value in the history with sequence number NUM.  */
340
341 struct value *
342 access_value_history (int num)
343 {
344   struct value_history_chunk *chunk;
345   int i;
346   int absnum = num;
347
348   if (absnum <= 0)
349     absnum += value_history_count;
350
351   if (absnum <= 0)
352     {
353       if (num == 0)
354         error ("The history is empty.");
355       else if (num == 1)
356         error ("There is only one value in the history.");
357       else
358         error ("History does not go back to $$%d.", -num);
359     }
360   if (absnum > value_history_count)
361     error ("History has not yet reached $%d.", absnum);
362
363   absnum--;
364
365   /* Now absnum is always absolute and origin zero.  */
366
367   chunk = value_history_chain;
368   for (i = (value_history_count - 1) / VALUE_HISTORY_CHUNK - absnum / VALUE_HISTORY_CHUNK;
369        i > 0; i--)
370     chunk = chunk->next;
371
372   return value_copy (chunk->values[absnum % VALUE_HISTORY_CHUNK]);
373 }
374
375 /* Clear the value history entirely.
376    Must be done when new symbol tables are loaded,
377    because the type pointers become invalid.  */
378
379 void
380 clear_value_history (void)
381 {
382   struct value_history_chunk *next;
383   int i;
384   struct value *val;
385
386   while (value_history_chain)
387     {
388       for (i = 0; i < VALUE_HISTORY_CHUNK; i++)
389         if ((val = value_history_chain->values[i]) != NULL)
390           xfree (val);
391       next = value_history_chain->next;
392       xfree (value_history_chain);
393       value_history_chain = next;
394     }
395   value_history_count = 0;
396 }
397
398 static void
399 show_values (char *num_exp, int from_tty)
400 {
401   int i;
402   struct value *val;
403   static int num = 1;
404
405   if (num_exp)
406     {
407       /* "info history +" should print from the stored position.
408          "info history <exp>" should print around value number <exp>.  */
409       if (num_exp[0] != '+' || num_exp[1] != '\0')
410         num = parse_and_eval_long (num_exp) - 5;
411     }
412   else
413     {
414       /* "info history" means print the last 10 values.  */
415       num = value_history_count - 9;
416     }
417
418   if (num <= 0)
419     num = 1;
420
421   for (i = num; i < num + 10 && i <= value_history_count; i++)
422     {
423       val = access_value_history (i);
424       printf_filtered ("$%d = ", i);
425       value_print (val, gdb_stdout, 0, Val_pretty_default);
426       printf_filtered ("\n");
427     }
428
429   /* The next "info history +" should start after what we just printed.  */
430   num += 10;
431
432   /* Hitting just return after this command should do the same thing as
433      "info history +".  If num_exp is null, this is unnecessary, since
434      "info history +" is not useful after "info history".  */
435   if (from_tty && num_exp)
436     {
437       num_exp[0] = '+';
438       num_exp[1] = '\0';
439     }
440 }
441 \f
442 /* Internal variables.  These are variables within the debugger
443    that hold values assigned by debugger commands.
444    The user refers to them with a '$' prefix
445    that does not appear in the variable names stored internally.  */
446
447 static struct internalvar *internalvars;
448
449 /* Look up an internal variable with name NAME.  NAME should not
450    normally include a dollar sign.
451
452    If the specified internal variable does not exist,
453    one is created, with a void value.  */
454
455 struct internalvar *
456 lookup_internalvar (char *name)
457 {
458   struct internalvar *var;
459
460   for (var = internalvars; var; var = var->next)
461     if (strcmp (var->name, name) == 0)
462       return var;
463
464   var = (struct internalvar *) xmalloc (sizeof (struct internalvar));
465   var->name = concat (name, NULL);
466   var->value = allocate_value (builtin_type_void);
467   release_value (var->value);
468   var->next = internalvars;
469   internalvars = var;
470   return var;
471 }
472
473 struct value *
474 value_of_internalvar (struct internalvar *var)
475 {
476   struct value *val;
477
478   val = value_copy (var->value);
479   if (VALUE_LAZY (val))
480     value_fetch_lazy (val);
481   VALUE_LVAL (val) = lval_internalvar;
482   VALUE_INTERNALVAR (val) = var;
483   return val;
484 }
485
486 void
487 set_internalvar_component (struct internalvar *var, int offset, int bitpos,
488                            int bitsize, struct value *newval)
489 {
490   char *addr = VALUE_CONTENTS (var->value) + offset;
491
492   if (bitsize)
493     modify_field (addr, value_as_long (newval),
494                   bitpos, bitsize);
495   else
496     memcpy (addr, VALUE_CONTENTS (newval), TYPE_LENGTH (value_type (newval)));
497 }
498
499 void
500 set_internalvar (struct internalvar *var, struct value *val)
501 {
502   struct value *newval;
503
504   newval = value_copy (val);
505   newval->modifiable = 1;
506
507   /* Force the value to be fetched from the target now, to avoid problems
508      later when this internalvar is referenced and the target is gone or
509      has changed.  */
510   if (VALUE_LAZY (newval))
511     value_fetch_lazy (newval);
512
513   /* Begin code which must not call error().  If var->value points to
514      something free'd, an error() obviously leaves a dangling pointer.
515      But we also get a danling pointer if var->value points to
516      something in the value chain (i.e., before release_value is
517      called), because after the error free_all_values will get called before
518      long.  */
519   xfree (var->value);
520   var->value = newval;
521   release_value (newval);
522   /* End code which must not call error().  */
523 }
524
525 char *
526 internalvar_name (struct internalvar *var)
527 {
528   return var->name;
529 }
530
531 /* Free all internalvars.  Done when new symtabs are loaded,
532    because that makes the values invalid.  */
533
534 void
535 clear_internalvars (void)
536 {
537   struct internalvar *var;
538
539   while (internalvars)
540     {
541       var = internalvars;
542       internalvars = var->next;
543       xfree (var->name);
544       xfree (var->value);
545       xfree (var);
546     }
547 }
548
549 static void
550 show_convenience (char *ignore, int from_tty)
551 {
552   struct internalvar *var;
553   int varseen = 0;
554
555   for (var = internalvars; var; var = var->next)
556     {
557       if (!varseen)
558         {
559           varseen = 1;
560         }
561       printf_filtered ("$%s = ", var->name);
562       value_print (var->value, gdb_stdout, 0, Val_pretty_default);
563       printf_filtered ("\n");
564     }
565   if (!varseen)
566     printf_unfiltered ("No debugger convenience variables now defined.\n\
567 Convenience variables have names starting with \"$\";\n\
568 use \"set\" as in \"set $foo = 5\" to define them.\n");
569 }
570 \f
571 /* Extract a value as a C number (either long or double).
572    Knows how to convert fixed values to double, or
573    floating values to long.
574    Does not deallocate the value.  */
575
576 LONGEST
577 value_as_long (struct value *val)
578 {
579   /* This coerces arrays and functions, which is necessary (e.g.
580      in disassemble_command).  It also dereferences references, which
581      I suspect is the most logical thing to do.  */
582   val = coerce_array (val);
583   return unpack_long (value_type (val), VALUE_CONTENTS (val));
584 }
585
586 DOUBLEST
587 value_as_double (struct value *val)
588 {
589   DOUBLEST foo;
590   int inv;
591
592   foo = unpack_double (value_type (val), VALUE_CONTENTS (val), &inv);
593   if (inv)
594     error ("Invalid floating value found in program.");
595   return foo;
596 }
597 /* Extract a value as a C pointer. Does not deallocate the value.  
598    Note that val's type may not actually be a pointer; value_as_long
599    handles all the cases.  */
600 CORE_ADDR
601 value_as_address (struct value *val)
602 {
603   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
604      whether we want this to be true eventually.  */
605 #if 0
606   /* ADDR_BITS_REMOVE is wrong if we are being called for a
607      non-address (e.g. argument to "signal", "info break", etc.), or
608      for pointers to char, in which the low bits *are* significant.  */
609   return ADDR_BITS_REMOVE (value_as_long (val));
610 #else
611
612   /* There are several targets (IA-64, PowerPC, and others) which
613      don't represent pointers to functions as simply the address of
614      the function's entry point.  For example, on the IA-64, a
615      function pointer points to a two-word descriptor, generated by
616      the linker, which contains the function's entry point, and the
617      value the IA-64 "global pointer" register should have --- to
618      support position-independent code.  The linker generates
619      descriptors only for those functions whose addresses are taken.
620
621      On such targets, it's difficult for GDB to convert an arbitrary
622      function address into a function pointer; it has to either find
623      an existing descriptor for that function, or call malloc and
624      build its own.  On some targets, it is impossible for GDB to
625      build a descriptor at all: the descriptor must contain a jump
626      instruction; data memory cannot be executed; and code memory
627      cannot be modified.
628
629      Upon entry to this function, if VAL is a value of type `function'
630      (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
631      VALUE_ADDRESS (val) is the address of the function.  This is what
632      you'll get if you evaluate an expression like `main'.  The call
633      to COERCE_ARRAY below actually does all the usual unary
634      conversions, which includes converting values of type `function'
635      to `pointer to function'.  This is the challenging conversion
636      discussed above.  Then, `unpack_long' will convert that pointer
637      back into an address.
638
639      So, suppose the user types `disassemble foo' on an architecture
640      with a strange function pointer representation, on which GDB
641      cannot build its own descriptors, and suppose further that `foo'
642      has no linker-built descriptor.  The address->pointer conversion
643      will signal an error and prevent the command from running, even
644      though the next step would have been to convert the pointer
645      directly back into the same address.
646
647      The following shortcut avoids this whole mess.  If VAL is a
648      function, just return its address directly.  */
649   if (TYPE_CODE (value_type (val)) == TYPE_CODE_FUNC
650       || TYPE_CODE (value_type (val)) == TYPE_CODE_METHOD)
651     return VALUE_ADDRESS (val);
652
653   val = coerce_array (val);
654
655   /* Some architectures (e.g. Harvard), map instruction and data
656      addresses onto a single large unified address space.  For
657      instance: An architecture may consider a large integer in the
658      range 0x10000000 .. 0x1000ffff to already represent a data
659      addresses (hence not need a pointer to address conversion) while
660      a small integer would still need to be converted integer to
661      pointer to address.  Just assume such architectures handle all
662      integer conversions in a single function.  */
663
664   /* JimB writes:
665
666      I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
667      must admonish GDB hackers to make sure its behavior matches the
668      compiler's, whenever possible.
669
670      In general, I think GDB should evaluate expressions the same way
671      the compiler does.  When the user copies an expression out of
672      their source code and hands it to a `print' command, they should
673      get the same value the compiler would have computed.  Any
674      deviation from this rule can cause major confusion and annoyance,
675      and needs to be justified carefully.  In other words, GDB doesn't
676      really have the freedom to do these conversions in clever and
677      useful ways.
678
679      AndrewC pointed out that users aren't complaining about how GDB
680      casts integers to pointers; they are complaining that they can't
681      take an address from a disassembly listing and give it to `x/i'.
682      This is certainly important.
683
684      Adding an architecture method like integer_to_address() certainly
685      makes it possible for GDB to "get it right" in all circumstances
686      --- the target has complete control over how things get done, so
687      people can Do The Right Thing for their target without breaking
688      anyone else.  The standard doesn't specify how integers get
689      converted to pointers; usually, the ABI doesn't either, but
690      ABI-specific code is a more reasonable place to handle it.  */
691
692   if (TYPE_CODE (value_type (val)) != TYPE_CODE_PTR
693       && TYPE_CODE (value_type (val)) != TYPE_CODE_REF
694       && gdbarch_integer_to_address_p (current_gdbarch))
695     return gdbarch_integer_to_address (current_gdbarch, value_type (val),
696                                        VALUE_CONTENTS (val));
697
698   return unpack_long (value_type (val), VALUE_CONTENTS (val));
699 #endif
700 }
701 \f
702 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
703    as a long, or as a double, assuming the raw data is described
704    by type TYPE.  Knows how to convert different sizes of values
705    and can convert between fixed and floating point.  We don't assume
706    any alignment for the raw data.  Return value is in host byte order.
707
708    If you want functions and arrays to be coerced to pointers, and
709    references to be dereferenced, call value_as_long() instead.
710
711    C++: It is assumed that the front-end has taken care of
712    all matters concerning pointers to members.  A pointer
713    to member which reaches here is considered to be equivalent
714    to an INT (or some size).  After all, it is only an offset.  */
715
716 LONGEST
717 unpack_long (struct type *type, const char *valaddr)
718 {
719   enum type_code code = TYPE_CODE (type);
720   int len = TYPE_LENGTH (type);
721   int nosign = TYPE_UNSIGNED (type);
722
723   if (current_language->la_language == language_scm
724       && is_scmvalue_type (type))
725     return scm_unpack (type, valaddr, TYPE_CODE_INT);
726
727   switch (code)
728     {
729     case TYPE_CODE_TYPEDEF:
730       return unpack_long (check_typedef (type), valaddr);
731     case TYPE_CODE_ENUM:
732     case TYPE_CODE_BOOL:
733     case TYPE_CODE_INT:
734     case TYPE_CODE_CHAR:
735     case TYPE_CODE_RANGE:
736       if (nosign)
737         return extract_unsigned_integer (valaddr, len);
738       else
739         return extract_signed_integer (valaddr, len);
740
741     case TYPE_CODE_FLT:
742       return extract_typed_floating (valaddr, type);
743
744     case TYPE_CODE_PTR:
745     case TYPE_CODE_REF:
746       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
747          whether we want this to be true eventually.  */
748       return extract_typed_address (valaddr, type);
749
750     case TYPE_CODE_MEMBER:
751       error ("not implemented: member types in unpack_long");
752
753     default:
754       error ("Value can't be converted to integer.");
755     }
756   return 0;                     /* Placate lint.  */
757 }
758
759 /* Return a double value from the specified type and address.
760    INVP points to an int which is set to 0 for valid value,
761    1 for invalid value (bad float format).  In either case,
762    the returned double is OK to use.  Argument is in target
763    format, result is in host format.  */
764
765 DOUBLEST
766 unpack_double (struct type *type, const char *valaddr, int *invp)
767 {
768   enum type_code code;
769   int len;
770   int nosign;
771
772   *invp = 0;                    /* Assume valid.   */
773   CHECK_TYPEDEF (type);
774   code = TYPE_CODE (type);
775   len = TYPE_LENGTH (type);
776   nosign = TYPE_UNSIGNED (type);
777   if (code == TYPE_CODE_FLT)
778     {
779       /* NOTE: cagney/2002-02-19: There was a test here to see if the
780          floating-point value was valid (using the macro
781          INVALID_FLOAT).  That test/macro have been removed.
782
783          It turns out that only the VAX defined this macro and then
784          only in a non-portable way.  Fixing the portability problem
785          wouldn't help since the VAX floating-point code is also badly
786          bit-rotten.  The target needs to add definitions for the
787          methods TARGET_FLOAT_FORMAT and TARGET_DOUBLE_FORMAT - these
788          exactly describe the target floating-point format.  The
789          problem here is that the corresponding floatformat_vax_f and
790          floatformat_vax_d values these methods should be set to are
791          also not defined either.  Oops!
792
793          Hopefully someone will add both the missing floatformat
794          definitions and the new cases for floatformat_is_valid ().  */
795
796       if (!floatformat_is_valid (floatformat_from_type (type), valaddr))
797         {
798           *invp = 1;
799           return 0.0;
800         }
801
802       return extract_typed_floating (valaddr, type);
803     }
804   else if (nosign)
805     {
806       /* Unsigned -- be sure we compensate for signed LONGEST.  */
807       return (ULONGEST) unpack_long (type, valaddr);
808     }
809   else
810     {
811       /* Signed -- we are OK with unpack_long.  */
812       return unpack_long (type, valaddr);
813     }
814 }
815
816 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
817    as a CORE_ADDR, assuming the raw data is described by type TYPE.
818    We don't assume any alignment for the raw data.  Return value is in
819    host byte order.
820
821    If you want functions and arrays to be coerced to pointers, and
822    references to be dereferenced, call value_as_address() instead.
823
824    C++: It is assumed that the front-end has taken care of
825    all matters concerning pointers to members.  A pointer
826    to member which reaches here is considered to be equivalent
827    to an INT (or some size).  After all, it is only an offset.  */
828
829 CORE_ADDR
830 unpack_pointer (struct type *type, const char *valaddr)
831 {
832   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
833      whether we want this to be true eventually.  */
834   return unpack_long (type, valaddr);
835 }
836
837 \f
838 /* Get the value of the FIELDN'th field (which must be static) of
839    TYPE.  Return NULL if the field doesn't exist or has been
840    optimized out. */
841
842 struct value *
843 value_static_field (struct type *type, int fieldno)
844 {
845   struct value *retval;
846
847   if (TYPE_FIELD_STATIC_HAS_ADDR (type, fieldno))
848     {
849       retval = value_at (TYPE_FIELD_TYPE (type, fieldno),
850                          TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
851     }
852   else
853     {
854       char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
855       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0, NULL);
856       if (sym == NULL)
857         {
858           /* With some compilers, e.g. HP aCC, static data members are reported
859              as non-debuggable symbols */
860           struct minimal_symbol *msym = lookup_minimal_symbol (phys_name, NULL, NULL);
861           if (!msym)
862             return NULL;
863           else
864             {
865               retval = value_at (TYPE_FIELD_TYPE (type, fieldno),
866                                  SYMBOL_VALUE_ADDRESS (msym));
867             }
868         }
869       else
870         {
871           /* SYM should never have a SYMBOL_CLASS which will require
872              read_var_value to use the FRAME parameter.  */
873           if (symbol_read_needs_frame (sym))
874             warning ("static field's value depends on the current "
875                      "frame - bad debug info?");
876           retval = read_var_value (sym, NULL);
877         }
878       if (retval && VALUE_LVAL (retval) == lval_memory)
879         SET_FIELD_PHYSADDR (TYPE_FIELD (type, fieldno),
880                             VALUE_ADDRESS (retval));
881     }
882   return retval;
883 }
884
885 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.  
886    You have to be careful here, since the size of the data area for the value 
887    is set by the length of the enclosing type.  So if NEW_ENCL_TYPE is bigger 
888    than the old enclosing type, you have to allocate more space for the data.  
889    The return value is a pointer to the new version of this value structure. */
890
891 struct value *
892 value_change_enclosing_type (struct value *val, struct type *new_encl_type)
893 {
894   if (TYPE_LENGTH (new_encl_type) <= TYPE_LENGTH (value_enclosing_type (val))) 
895     {
896       val->enclosing_type = new_encl_type;
897       return val;
898     }
899   else
900     {
901       struct value *new_val;
902       struct value *prev;
903       
904       new_val = (struct value *) xrealloc (val, sizeof (struct value) + TYPE_LENGTH (new_encl_type));
905
906       new_val->enclosing_type = new_encl_type;
907  
908       /* We have to make sure this ends up in the same place in the value
909          chain as the original copy, so it's clean-up behavior is the same. 
910          If the value has been released, this is a waste of time, but there
911          is no way to tell that in advance, so... */
912       
913       if (val != all_values) 
914         {
915           for (prev = all_values; prev != NULL; prev = prev->next)
916             {
917               if (prev->next == val) 
918                 {
919                   prev->next = new_val;
920                   break;
921                 }
922             }
923         }
924       
925       return new_val;
926     }
927 }
928
929 /* Given a value ARG1 (offset by OFFSET bytes)
930    of a struct or union type ARG_TYPE,
931    extract and return the value of one of its (non-static) fields.
932    FIELDNO says which field. */
933
934 struct value *
935 value_primitive_field (struct value *arg1, int offset,
936                        int fieldno, struct type *arg_type)
937 {
938   struct value *v;
939   struct type *type;
940
941   CHECK_TYPEDEF (arg_type);
942   type = TYPE_FIELD_TYPE (arg_type, fieldno);
943
944   /* Handle packed fields */
945
946   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
947     {
948       v = value_from_longest (type,
949                               unpack_field_as_long (arg_type,
950                                                     VALUE_CONTENTS (arg1)
951                                                     + offset,
952                                                     fieldno));
953       v->bitpos = TYPE_FIELD_BITPOS (arg_type, fieldno) % 8;
954       v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
955       v->offset = value_offset (arg1) + offset
956         + TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
957     }
958   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
959     {
960       /* This field is actually a base subobject, so preserve the
961          entire object's contents for later references to virtual
962          bases, etc.  */
963       v = allocate_value (value_enclosing_type (arg1));
964       v->type = type;
965       if (VALUE_LAZY (arg1))
966         VALUE_LAZY (v) = 1;
967       else
968         memcpy (value_contents_all_raw (v), value_contents_all_raw (arg1),
969                 TYPE_LENGTH (value_enclosing_type (arg1)));
970       v->offset = value_offset (arg1);
971       VALUE_EMBEDDED_OFFSET (v)
972         = offset +
973         VALUE_EMBEDDED_OFFSET (arg1) +
974         TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
975     }
976   else
977     {
978       /* Plain old data member */
979       offset += TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
980       v = allocate_value (type);
981       if (VALUE_LAZY (arg1))
982         VALUE_LAZY (v) = 1;
983       else
984         memcpy (value_contents_raw (v),
985                 value_contents_raw (arg1) + offset,
986                 TYPE_LENGTH (type));
987       v->offset = (value_offset (arg1) + offset
988                    + VALUE_EMBEDDED_OFFSET (arg1));
989     }
990   VALUE_LVAL (v) = VALUE_LVAL (arg1);
991   if (VALUE_LVAL (arg1) == lval_internalvar)
992     VALUE_LVAL (v) = lval_internalvar_component;
993   VALUE_ADDRESS (v) = VALUE_ADDRESS (arg1);
994   VALUE_REGNUM (v) = VALUE_REGNUM (arg1);
995   VALUE_FRAME_ID (v) = VALUE_FRAME_ID (arg1);
996 /*  VALUE_OFFSET (v) = VALUE_OFFSET (arg1) + offset
997    + TYPE_FIELD_BITPOS (arg_type, fieldno) / 8; */
998   return v;
999 }
1000
1001 /* Given a value ARG1 of a struct or union type,
1002    extract and return the value of one of its (non-static) fields.
1003    FIELDNO says which field. */
1004
1005 struct value *
1006 value_field (struct value *arg1, int fieldno)
1007 {
1008   return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
1009 }
1010
1011 /* Return a non-virtual function as a value.
1012    F is the list of member functions which contains the desired method.
1013    J is an index into F which provides the desired method.
1014
1015    We only use the symbol for its address, so be happy with either a
1016    full symbol or a minimal symbol.
1017  */
1018
1019 struct value *
1020 value_fn_field (struct value **arg1p, struct fn_field *f, int j, struct type *type,
1021                 int offset)
1022 {
1023   struct value *v;
1024   struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
1025   char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
1026   struct symbol *sym;
1027   struct minimal_symbol *msym;
1028
1029   sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0, NULL);
1030   if (sym != NULL)
1031     {
1032       msym = NULL;
1033     }
1034   else
1035     {
1036       gdb_assert (sym == NULL);
1037       msym = lookup_minimal_symbol (physname, NULL, NULL);
1038       if (msym == NULL)
1039         return NULL;
1040     }
1041
1042   v = allocate_value (ftype);
1043   if (sym)
1044     {
1045       VALUE_ADDRESS (v) = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
1046     }
1047   else
1048     {
1049       VALUE_ADDRESS (v) = SYMBOL_VALUE_ADDRESS (msym);
1050     }
1051
1052   if (arg1p)
1053     {
1054       if (type != value_type (*arg1p))
1055         *arg1p = value_ind (value_cast (lookup_pointer_type (type),
1056                                         value_addr (*arg1p)));
1057
1058       /* Move the `this' pointer according to the offset.
1059          VALUE_OFFSET (*arg1p) += offset;
1060        */
1061     }
1062
1063   return v;
1064 }
1065
1066 \f
1067 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous object at
1068    VALADDR.
1069
1070    Extracting bits depends on endianness of the machine.  Compute the
1071    number of least significant bits to discard.  For big endian machines,
1072    we compute the total number of bits in the anonymous object, subtract
1073    off the bit count from the MSB of the object to the MSB of the
1074    bitfield, then the size of the bitfield, which leaves the LSB discard
1075    count.  For little endian machines, the discard count is simply the
1076    number of bits from the LSB of the anonymous object to the LSB of the
1077    bitfield.
1078
1079    If the field is signed, we also do sign extension. */
1080
1081 LONGEST
1082 unpack_field_as_long (struct type *type, const char *valaddr, int fieldno)
1083 {
1084   ULONGEST val;
1085   ULONGEST valmask;
1086   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
1087   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
1088   int lsbcount;
1089   struct type *field_type;
1090
1091   val = extract_unsigned_integer (valaddr + bitpos / 8, sizeof (val));
1092   field_type = TYPE_FIELD_TYPE (type, fieldno);
1093   CHECK_TYPEDEF (field_type);
1094
1095   /* Extract bits.  See comment above. */
1096
1097   if (BITS_BIG_ENDIAN)
1098     lsbcount = (sizeof val * 8 - bitpos % 8 - bitsize);
1099   else
1100     lsbcount = (bitpos % 8);
1101   val >>= lsbcount;
1102
1103   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
1104      If the field is signed, and is negative, then sign extend. */
1105
1106   if ((bitsize > 0) && (bitsize < 8 * (int) sizeof (val)))
1107     {
1108       valmask = (((ULONGEST) 1) << bitsize) - 1;
1109       val &= valmask;
1110       if (!TYPE_UNSIGNED (field_type))
1111         {
1112           if (val & (valmask ^ (valmask >> 1)))
1113             {
1114               val |= ~valmask;
1115             }
1116         }
1117     }
1118   return (val);
1119 }
1120
1121 /* Modify the value of a bitfield.  ADDR points to a block of memory in
1122    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
1123    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
1124    indicate which bits (in target bit order) comprise the bitfield.  
1125    Requires 0 < BITSIZE <= lbits, 0 <= BITPOS+BITSIZE <= lbits, and
1126    0 <= BITPOS, where lbits is the size of a LONGEST in bits.  */
1127
1128 void
1129 modify_field (char *addr, LONGEST fieldval, int bitpos, int bitsize)
1130 {
1131   ULONGEST oword;
1132   ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
1133
1134   /* If a negative fieldval fits in the field in question, chop
1135      off the sign extension bits.  */
1136   if ((~fieldval & ~(mask >> 1)) == 0)
1137     fieldval &= mask;
1138
1139   /* Warn if value is too big to fit in the field in question.  */
1140   if (0 != (fieldval & ~mask))
1141     {
1142       /* FIXME: would like to include fieldval in the message, but
1143          we don't have a sprintf_longest.  */
1144       warning ("Value does not fit in %d bits.", bitsize);
1145
1146       /* Truncate it, otherwise adjoining fields may be corrupted.  */
1147       fieldval &= mask;
1148     }
1149
1150   oword = extract_unsigned_integer (addr, sizeof oword);
1151
1152   /* Shifting for bit field depends on endianness of the target machine.  */
1153   if (BITS_BIG_ENDIAN)
1154     bitpos = sizeof (oword) * 8 - bitpos - bitsize;
1155
1156   oword &= ~(mask << bitpos);
1157   oword |= fieldval << bitpos;
1158
1159   store_unsigned_integer (addr, sizeof oword, oword);
1160 }
1161 \f
1162 /* Convert C numbers into newly allocated values */
1163
1164 struct value *
1165 value_from_longest (struct type *type, LONGEST num)
1166 {
1167   struct value *val = allocate_value (type);
1168   enum type_code code;
1169   int len;
1170 retry:
1171   code = TYPE_CODE (type);
1172   len = TYPE_LENGTH (type);
1173
1174   switch (code)
1175     {
1176     case TYPE_CODE_TYPEDEF:
1177       type = check_typedef (type);
1178       goto retry;
1179     case TYPE_CODE_INT:
1180     case TYPE_CODE_CHAR:
1181     case TYPE_CODE_ENUM:
1182     case TYPE_CODE_BOOL:
1183     case TYPE_CODE_RANGE:
1184       store_signed_integer (value_contents_raw (val), len, num);
1185       break;
1186
1187     case TYPE_CODE_REF:
1188     case TYPE_CODE_PTR:
1189       store_typed_address (value_contents_raw (val), type, (CORE_ADDR) num);
1190       break;
1191
1192     default:
1193       error ("Unexpected type (%d) encountered for integer constant.", code);
1194     }
1195   return val;
1196 }
1197
1198
1199 /* Create a value representing a pointer of type TYPE to the address
1200    ADDR.  */
1201 struct value *
1202 value_from_pointer (struct type *type, CORE_ADDR addr)
1203 {
1204   struct value *val = allocate_value (type);
1205   store_typed_address (value_contents_raw (val), type, addr);
1206   return val;
1207 }
1208
1209
1210 /* Create a value for a string constant to be stored locally
1211    (not in the inferior's memory space, but in GDB memory).
1212    This is analogous to value_from_longest, which also does not
1213    use inferior memory.  String shall NOT contain embedded nulls.  */
1214
1215 struct value *
1216 value_from_string (char *ptr)
1217 {
1218   struct value *val;
1219   int len = strlen (ptr);
1220   int lowbound = current_language->string_lower_bound;
1221   struct type *string_char_type;
1222   struct type *rangetype;
1223   struct type *stringtype;
1224
1225   rangetype = create_range_type ((struct type *) NULL,
1226                                  builtin_type_int,
1227                                  lowbound, len + lowbound - 1);
1228   string_char_type = language_string_char_type (current_language,
1229                                                 current_gdbarch);
1230   stringtype = create_array_type ((struct type *) NULL,
1231                                   string_char_type,
1232                                   rangetype);
1233   val = allocate_value (stringtype);
1234   memcpy (value_contents_raw (val), ptr, len);
1235   return val;
1236 }
1237
1238 struct value *
1239 value_from_double (struct type *type, DOUBLEST num)
1240 {
1241   struct value *val = allocate_value (type);
1242   struct type *base_type = check_typedef (type);
1243   enum type_code code = TYPE_CODE (base_type);
1244   int len = TYPE_LENGTH (base_type);
1245
1246   if (code == TYPE_CODE_FLT)
1247     {
1248       store_typed_floating (value_contents_raw (val), base_type, num);
1249     }
1250   else
1251     error ("Unexpected type encountered for floating constant.");
1252
1253   return val;
1254 }
1255
1256 struct value *
1257 coerce_ref (struct value *arg)
1258 {
1259   struct type *value_type_arg_tmp = check_typedef (value_type (arg));
1260   if (TYPE_CODE (value_type_arg_tmp) == TYPE_CODE_REF)
1261     arg = value_at_lazy (TYPE_TARGET_TYPE (value_type_arg_tmp),
1262                          unpack_pointer (value_type (arg),              
1263                                          VALUE_CONTENTS (arg)));
1264   return arg;
1265 }
1266
1267 struct value *
1268 coerce_array (struct value *arg)
1269 {
1270   arg = coerce_ref (arg);
1271   if (current_language->c_style_arrays
1272       && TYPE_CODE (value_type (arg)) == TYPE_CODE_ARRAY)
1273     arg = value_coerce_array (arg);
1274   if (TYPE_CODE (value_type (arg)) == TYPE_CODE_FUNC)
1275     arg = value_coerce_function (arg);
1276   return arg;
1277 }
1278
1279 struct value *
1280 coerce_number (struct value *arg)
1281 {
1282   arg = coerce_array (arg);
1283   arg = coerce_enum (arg);
1284   return arg;
1285 }
1286
1287 struct value *
1288 coerce_enum (struct value *arg)
1289 {
1290   if (TYPE_CODE (check_typedef (value_type (arg))) == TYPE_CODE_ENUM)
1291     arg = value_cast (builtin_type_unsigned_int, arg);
1292   return arg;
1293 }
1294 \f
1295
1296 /* Should we use DEPRECATED_EXTRACT_STRUCT_VALUE_ADDRESS instead of
1297    EXTRACT_RETURN_VALUE?  GCC_P is true if compiled with gcc and TYPE
1298    is the type (which is known to be struct, union or array).
1299
1300    On most machines, the struct convention is used unless we are
1301    using gcc and the type is of a special size.  */
1302 /* As of about 31 Mar 93, GCC was changed to be compatible with the
1303    native compiler.  GCC 2.3.3 was the last release that did it the
1304    old way.  Since gcc2_compiled was not changed, we have no
1305    way to correctly win in all cases, so we just do the right thing
1306    for gcc1 and for gcc2 after this change.  Thus it loses for gcc
1307    2.0-2.3.3.  This is somewhat unfortunate, but changing gcc2_compiled
1308    would cause more chaos than dealing with some struct returns being
1309    handled wrong.  */
1310 /* NOTE: cagney/2004-06-13: Deleted check for "gcc_p".  GCC 1.x is
1311    dead.  */
1312
1313 int
1314 generic_use_struct_convention (int gcc_p, struct type *value_type)
1315 {
1316   return !(TYPE_LENGTH (value_type) == 1
1317            || TYPE_LENGTH (value_type) == 2
1318            || TYPE_LENGTH (value_type) == 4
1319            || TYPE_LENGTH (value_type) == 8);
1320 }
1321
1322 /* Return true if the function returning the specified type is using
1323    the convention of returning structures in memory (passing in the
1324    address as a hidden first parameter).  GCC_P is nonzero if compiled
1325    with GCC.  */
1326
1327 int
1328 using_struct_return (struct type *value_type, int gcc_p)
1329 {
1330   enum type_code code = TYPE_CODE (value_type);
1331
1332   if (code == TYPE_CODE_ERROR)
1333     error ("Function return type unknown.");
1334
1335   if (code == TYPE_CODE_VOID)
1336     /* A void return value is never in memory.  See also corresponding
1337        code in "print_return_value".  */
1338     return 0;
1339
1340   /* Probe the architecture for the return-value convention.  */
1341   return (gdbarch_return_value (current_gdbarch, value_type,
1342                                 NULL, NULL, NULL)
1343           != RETURN_VALUE_REGISTER_CONVENTION);
1344 }
1345
1346 void
1347 _initialize_values (void)
1348 {
1349   add_cmd ("convenience", no_class, show_convenience,
1350            "Debugger convenience (\"$foo\") variables.\n\
1351 These variables are created when you assign them values;\n\
1352 thus, \"print $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\n\
1353 A few convenience variables are given values automatically:\n\
1354 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
1355 \"$__\" holds the contents of the last address examined with \"x\".",
1356            &showlist);
1357
1358   add_cmd ("values", no_class, show_values,
1359            "Elements of value history around item number IDX (or last ten).",
1360            &showlist);
1361 }