OSDN Git Service

2007-10-25 Wu Zhou <woodzltc@cn.ibm.com>
[pf3gnuchains/pf3gnuchains3x.git] / gdb / value.c
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
2
3    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007
5    Free 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 3 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, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "gdb_string.h"
24 #include "symtab.h"
25 #include "gdbtypes.h"
26 #include "value.h"
27 #include "gdbcore.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "target.h"
31 #include "language.h"
32 #include "demangle.h"
33 #include "doublest.h"
34 #include "gdb_assert.h"
35 #include "regcache.h"
36 #include "block.h"
37 #include "dfp.h"
38
39 /* Prototypes for exported functions. */
40
41 void _initialize_values (void);
42
43 struct value
44 {
45   /* Type of value; either not an lval, or one of the various
46      different possible kinds of lval.  */
47   enum lval_type lval;
48
49   /* Is it modifiable?  Only relevant if lval != not_lval.  */
50   int modifiable;
51
52   /* Location of value (if lval).  */
53   union
54   {
55     /* If lval == lval_memory, this is the address in the inferior.
56        If lval == lval_register, this is the byte offset into the
57        registers structure.  */
58     CORE_ADDR address;
59
60     /* Pointer to internal variable.  */
61     struct internalvar *internalvar;
62   } location;
63
64   /* Describes offset of a value within lval of a structure in bytes.
65      If lval == lval_memory, this is an offset to the address.  If
66      lval == lval_register, this is a further offset from
67      location.address within the registers structure.  Note also the
68      member embedded_offset below.  */
69   int offset;
70
71   /* Only used for bitfields; number of bits contained in them.  */
72   int bitsize;
73
74   /* Only used for bitfields; position of start of field.  For
75      BITS_BIG_ENDIAN=0 targets, it is the position of the LSB.  For
76      BITS_BIG_ENDIAN=1 targets, it is the position of the MSB. */
77   int bitpos;
78
79   /* Frame register value is relative to.  This will be described in
80      the lval enum above as "lval_register".  */
81   struct frame_id frame_id;
82
83   /* Type of the value.  */
84   struct type *type;
85
86   /* If a value represents a C++ object, then the `type' field gives
87      the object's compile-time type.  If the object actually belongs
88      to some class derived from `type', perhaps with other base
89      classes and additional members, then `type' is just a subobject
90      of the real thing, and the full object is probably larger than
91      `type' would suggest.
92
93      If `type' is a dynamic class (i.e. one with a vtable), then GDB
94      can actually determine the object's run-time type by looking at
95      the run-time type information in the vtable.  When this
96      information is available, we may elect to read in the entire
97      object, for several reasons:
98
99      - When printing the value, the user would probably rather see the
100      full object, not just the limited portion apparent from the
101      compile-time type.
102
103      - If `type' has virtual base classes, then even printing `type'
104      alone may require reaching outside the `type' portion of the
105      object to wherever the virtual base class has been stored.
106
107      When we store the entire object, `enclosing_type' is the run-time
108      type -- the complete object -- and `embedded_offset' is the
109      offset of `type' within that larger type, in bytes.  The
110      value_contents() macro takes `embedded_offset' into account, so
111      most GDB code continues to see the `type' portion of the value,
112      just as the inferior would.
113
114      If `type' is a pointer to an object, then `enclosing_type' is a
115      pointer to the object's run-time type, and `pointed_to_offset' is
116      the offset in bytes from the full object to the pointed-to object
117      -- that is, the value `embedded_offset' would have if we followed
118      the pointer and fetched the complete object.  (I don't really see
119      the point.  Why not just determine the run-time type when you
120      indirect, and avoid the special case?  The contents don't matter
121      until you indirect anyway.)
122
123      If we're not doing anything fancy, `enclosing_type' is equal to
124      `type', and `embedded_offset' is zero, so everything works
125      normally.  */
126   struct type *enclosing_type;
127   int embedded_offset;
128   int pointed_to_offset;
129
130   /* Values are stored in a chain, so that they can be deleted easily
131      over calls to the inferior.  Values assigned to internal
132      variables or put into the value history are taken off this
133      list.  */
134   struct value *next;
135
136   /* Register number if the value is from a register.  */
137   short regnum;
138
139   /* If zero, contents of this value are in the contents field.  If
140      nonzero, contents are in inferior memory at address in the
141      location.address field plus the offset field (and the lval field
142      should be lval_memory).
143
144      WARNING: This field is used by the code which handles watchpoints
145      (see breakpoint.c) to decide whether a particular value can be
146      watched by hardware watchpoints.  If the lazy flag is set for
147      some member of a value chain, it is assumed that this member of
148      the chain doesn't need to be watched as part of watching the
149      value itself.  This is how GDB avoids watching the entire struct
150      or array when the user wants to watch a single struct member or
151      array element.  If you ever change the way lazy flag is set and
152      reset, be sure to consider this use as well!  */
153   char lazy;
154
155   /* If nonzero, this is the value of a variable which does not
156      actually exist in the program.  */
157   char optimized_out;
158
159   /* If value is a variable, is it initialized or not.  */
160   int initialized;
161
162   /* Actual contents of the value.  For use of this value; setting it
163      uses the stuff above.  Not valid if lazy is nonzero.  Target
164      byte-order.  We force it to be aligned properly for any possible
165      value.  Note that a value therefore extends beyond what is
166      declared here.  */
167   union
168   {
169     gdb_byte contents[1];
170     DOUBLEST force_doublest_align;
171     LONGEST force_longest_align;
172     CORE_ADDR force_core_addr_align;
173     void *force_pointer_align;
174   } aligner;
175   /* Do not add any new members here -- contents above will trash
176      them.  */
177 };
178
179 /* Prototypes for local functions. */
180
181 static void show_values (char *, int);
182
183 static void show_convenience (char *, int);
184
185
186 /* The value-history records all the values printed
187    by print commands during this session.  Each chunk
188    records 60 consecutive values.  The first chunk on
189    the chain records the most recent values.
190    The total number of values is in value_history_count.  */
191
192 #define VALUE_HISTORY_CHUNK 60
193
194 struct value_history_chunk
195   {
196     struct value_history_chunk *next;
197     struct value *values[VALUE_HISTORY_CHUNK];
198   };
199
200 /* Chain of chunks now in use.  */
201
202 static struct value_history_chunk *value_history_chain;
203
204 static int value_history_count; /* Abs number of last entry stored */
205 \f
206 /* List of all value objects currently allocated
207    (except for those released by calls to release_value)
208    This is so they can be freed after each command.  */
209
210 static struct value *all_values;
211
212 /* Allocate a  value  that has the correct length for type TYPE.  */
213
214 struct value *
215 allocate_value (struct type *type)
216 {
217   struct value *val;
218   struct type *atype = check_typedef (type);
219
220   val = (struct value *) xzalloc (sizeof (struct value) + TYPE_LENGTH (atype));
221   val->next = all_values;
222   all_values = val;
223   val->type = type;
224   val->enclosing_type = type;
225   VALUE_LVAL (val) = not_lval;
226   VALUE_ADDRESS (val) = 0;
227   VALUE_FRAME_ID (val) = null_frame_id;
228   val->offset = 0;
229   val->bitpos = 0;
230   val->bitsize = 0;
231   VALUE_REGNUM (val) = -1;
232   val->lazy = 0;
233   val->optimized_out = 0;
234   val->embedded_offset = 0;
235   val->pointed_to_offset = 0;
236   val->modifiable = 1;
237   val->initialized = 1;  /* Default to initialized.  */
238   return val;
239 }
240
241 /* Allocate a  value  that has the correct length
242    for COUNT repetitions type TYPE.  */
243
244 struct value *
245 allocate_repeat_value (struct type *type, int count)
246 {
247   int low_bound = current_language->string_lower_bound;         /* ??? */
248   /* FIXME-type-allocation: need a way to free this type when we are
249      done with it.  */
250   struct type *range_type
251   = create_range_type ((struct type *) NULL, builtin_type_int,
252                        low_bound, count + low_bound - 1);
253   /* FIXME-type-allocation: need a way to free this type when we are
254      done with it.  */
255   return allocate_value (create_array_type ((struct type *) NULL,
256                                             type, range_type));
257 }
258
259 /* Accessor methods.  */
260
261 struct value *
262 value_next (struct value *value)
263 {
264   return value->next;
265 }
266
267 struct type *
268 value_type (struct value *value)
269 {
270   return value->type;
271 }
272 void
273 deprecated_set_value_type (struct value *value, struct type *type)
274 {
275   value->type = type;
276 }
277
278 int
279 value_offset (struct value *value)
280 {
281   return value->offset;
282 }
283 void
284 set_value_offset (struct value *value, int offset)
285 {
286   value->offset = offset;
287 }
288
289 int
290 value_bitpos (struct value *value)
291 {
292   return value->bitpos;
293 }
294 void
295 set_value_bitpos (struct value *value, int bit)
296 {
297   value->bitpos = bit;
298 }
299
300 int
301 value_bitsize (struct value *value)
302 {
303   return value->bitsize;
304 }
305 void
306 set_value_bitsize (struct value *value, int bit)
307 {
308   value->bitsize = bit;
309 }
310
311 gdb_byte *
312 value_contents_raw (struct value *value)
313 {
314   return value->aligner.contents + value->embedded_offset;
315 }
316
317 gdb_byte *
318 value_contents_all_raw (struct value *value)
319 {
320   return value->aligner.contents;
321 }
322
323 struct type *
324 value_enclosing_type (struct value *value)
325 {
326   return value->enclosing_type;
327 }
328
329 const gdb_byte *
330 value_contents_all (struct value *value)
331 {
332   if (value->lazy)
333     value_fetch_lazy (value);
334   return value->aligner.contents;
335 }
336
337 int
338 value_lazy (struct value *value)
339 {
340   return value->lazy;
341 }
342
343 void
344 set_value_lazy (struct value *value, int val)
345 {
346   value->lazy = val;
347 }
348
349 const gdb_byte *
350 value_contents (struct value *value)
351 {
352   return value_contents_writeable (value);
353 }
354
355 gdb_byte *
356 value_contents_writeable (struct value *value)
357 {
358   if (value->lazy)
359     value_fetch_lazy (value);
360   return value_contents_raw (value);
361 }
362
363 /* Return non-zero if VAL1 and VAL2 have the same contents.  Note that
364    this function is different from value_equal; in C the operator ==
365    can return 0 even if the two values being compared are equal.  */
366
367 int
368 value_contents_equal (struct value *val1, struct value *val2)
369 {
370   struct type *type1;
371   struct type *type2;
372   int len;
373
374   type1 = check_typedef (value_type (val1));
375   type2 = check_typedef (value_type (val2));
376   len = TYPE_LENGTH (type1);
377   if (len != TYPE_LENGTH (type2))
378     return 0;
379
380   return (memcmp (value_contents (val1), value_contents (val2), len) == 0);
381 }
382
383 int
384 value_optimized_out (struct value *value)
385 {
386   return value->optimized_out;
387 }
388
389 void
390 set_value_optimized_out (struct value *value, int val)
391 {
392   value->optimized_out = val;
393 }
394
395 int
396 value_embedded_offset (struct value *value)
397 {
398   return value->embedded_offset;
399 }
400
401 void
402 set_value_embedded_offset (struct value *value, int val)
403 {
404   value->embedded_offset = val;
405 }
406
407 int
408 value_pointed_to_offset (struct value *value)
409 {
410   return value->pointed_to_offset;
411 }
412
413 void
414 set_value_pointed_to_offset (struct value *value, int val)
415 {
416   value->pointed_to_offset = val;
417 }
418
419 enum lval_type *
420 deprecated_value_lval_hack (struct value *value)
421 {
422   return &value->lval;
423 }
424
425 CORE_ADDR *
426 deprecated_value_address_hack (struct value *value)
427 {
428   return &value->location.address;
429 }
430
431 struct internalvar **
432 deprecated_value_internalvar_hack (struct value *value)
433 {
434   return &value->location.internalvar;
435 }
436
437 struct frame_id *
438 deprecated_value_frame_id_hack (struct value *value)
439 {
440   return &value->frame_id;
441 }
442
443 short *
444 deprecated_value_regnum_hack (struct value *value)
445 {
446   return &value->regnum;
447 }
448
449 int
450 deprecated_value_modifiable (struct value *value)
451 {
452   return value->modifiable;
453 }
454 void
455 deprecated_set_value_modifiable (struct value *value, int modifiable)
456 {
457   value->modifiable = modifiable;
458 }
459 \f
460 /* Return a mark in the value chain.  All values allocated after the
461    mark is obtained (except for those released) are subject to being freed
462    if a subsequent value_free_to_mark is passed the mark.  */
463 struct value *
464 value_mark (void)
465 {
466   return all_values;
467 }
468
469 /* Free all values allocated since MARK was obtained by value_mark
470    (except for those released).  */
471 void
472 value_free_to_mark (struct value *mark)
473 {
474   struct value *val;
475   struct value *next;
476
477   for (val = all_values; val && val != mark; val = next)
478     {
479       next = val->next;
480       value_free (val);
481     }
482   all_values = val;
483 }
484
485 /* Free all the values that have been allocated (except for those released).
486    Called after each command, successful or not.  */
487
488 void
489 free_all_values (void)
490 {
491   struct value *val;
492   struct value *next;
493
494   for (val = all_values; val; val = next)
495     {
496       next = val->next;
497       value_free (val);
498     }
499
500   all_values = 0;
501 }
502
503 /* Remove VAL from the chain all_values
504    so it will not be freed automatically.  */
505
506 void
507 release_value (struct value *val)
508 {
509   struct value *v;
510
511   if (all_values == val)
512     {
513       all_values = val->next;
514       return;
515     }
516
517   for (v = all_values; v; v = v->next)
518     {
519       if (v->next == val)
520         {
521           v->next = val->next;
522           break;
523         }
524     }
525 }
526
527 /* Release all values up to mark  */
528 struct value *
529 value_release_to_mark (struct value *mark)
530 {
531   struct value *val;
532   struct value *next;
533
534   for (val = next = all_values; next; next = next->next)
535     if (next->next == mark)
536       {
537         all_values = next->next;
538         next->next = NULL;
539         return val;
540       }
541   all_values = 0;
542   return val;
543 }
544
545 /* Return a copy of the value ARG.
546    It contains the same contents, for same memory address,
547    but it's a different block of storage.  */
548
549 struct value *
550 value_copy (struct value *arg)
551 {
552   struct type *encl_type = value_enclosing_type (arg);
553   struct value *val = allocate_value (encl_type);
554   val->type = arg->type;
555   VALUE_LVAL (val) = VALUE_LVAL (arg);
556   val->location = arg->location;
557   val->offset = arg->offset;
558   val->bitpos = arg->bitpos;
559   val->bitsize = arg->bitsize;
560   VALUE_FRAME_ID (val) = VALUE_FRAME_ID (arg);
561   VALUE_REGNUM (val) = VALUE_REGNUM (arg);
562   val->lazy = arg->lazy;
563   val->optimized_out = arg->optimized_out;
564   val->embedded_offset = value_embedded_offset (arg);
565   val->pointed_to_offset = arg->pointed_to_offset;
566   val->modifiable = arg->modifiable;
567   if (!value_lazy (val))
568     {
569       memcpy (value_contents_all_raw (val), value_contents_all_raw (arg),
570               TYPE_LENGTH (value_enclosing_type (arg)));
571
572     }
573   return val;
574 }
575 \f
576 /* Access to the value history.  */
577
578 /* Record a new value in the value history.
579    Returns the absolute history index of the entry.
580    Result of -1 indicates the value was not saved; otherwise it is the
581    value history index of this new item.  */
582
583 int
584 record_latest_value (struct value *val)
585 {
586   int i;
587
588   /* We don't want this value to have anything to do with the inferior anymore.
589      In particular, "set $1 = 50" should not affect the variable from which
590      the value was taken, and fast watchpoints should be able to assume that
591      a value on the value history never changes.  */
592   if (value_lazy (val))
593     value_fetch_lazy (val);
594   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
595      from.  This is a bit dubious, because then *&$1 does not just return $1
596      but the current contents of that location.  c'est la vie...  */
597   val->modifiable = 0;
598   release_value (val);
599
600   /* Here we treat value_history_count as origin-zero
601      and applying to the value being stored now.  */
602
603   i = value_history_count % VALUE_HISTORY_CHUNK;
604   if (i == 0)
605     {
606       struct value_history_chunk *new
607       = (struct value_history_chunk *)
608       xmalloc (sizeof (struct value_history_chunk));
609       memset (new->values, 0, sizeof new->values);
610       new->next = value_history_chain;
611       value_history_chain = new;
612     }
613
614   value_history_chain->values[i] = val;
615
616   /* Now we regard value_history_count as origin-one
617      and applying to the value just stored.  */
618
619   return ++value_history_count;
620 }
621
622 /* Return a copy of the value in the history with sequence number NUM.  */
623
624 struct value *
625 access_value_history (int num)
626 {
627   struct value_history_chunk *chunk;
628   int i;
629   int absnum = num;
630
631   if (absnum <= 0)
632     absnum += value_history_count;
633
634   if (absnum <= 0)
635     {
636       if (num == 0)
637         error (_("The history is empty."));
638       else if (num == 1)
639         error (_("There is only one value in the history."));
640       else
641         error (_("History does not go back to $$%d."), -num);
642     }
643   if (absnum > value_history_count)
644     error (_("History has not yet reached $%d."), absnum);
645
646   absnum--;
647
648   /* Now absnum is always absolute and origin zero.  */
649
650   chunk = value_history_chain;
651   for (i = (value_history_count - 1) / VALUE_HISTORY_CHUNK - absnum / VALUE_HISTORY_CHUNK;
652        i > 0; i--)
653     chunk = chunk->next;
654
655   return value_copy (chunk->values[absnum % VALUE_HISTORY_CHUNK]);
656 }
657
658 static void
659 show_values (char *num_exp, int from_tty)
660 {
661   int i;
662   struct value *val;
663   static int num = 1;
664
665   if (num_exp)
666     {
667       /* "info history +" should print from the stored position.
668          "info history <exp>" should print around value number <exp>.  */
669       if (num_exp[0] != '+' || num_exp[1] != '\0')
670         num = parse_and_eval_long (num_exp) - 5;
671     }
672   else
673     {
674       /* "info history" means print the last 10 values.  */
675       num = value_history_count - 9;
676     }
677
678   if (num <= 0)
679     num = 1;
680
681   for (i = num; i < num + 10 && i <= value_history_count; i++)
682     {
683       val = access_value_history (i);
684       printf_filtered (("$%d = "), i);
685       value_print (val, gdb_stdout, 0, Val_pretty_default);
686       printf_filtered (("\n"));
687     }
688
689   /* The next "info history +" should start after what we just printed.  */
690   num += 10;
691
692   /* Hitting just return after this command should do the same thing as
693      "info history +".  If num_exp is null, this is unnecessary, since
694      "info history +" is not useful after "info history".  */
695   if (from_tty && num_exp)
696     {
697       num_exp[0] = '+';
698       num_exp[1] = '\0';
699     }
700 }
701 \f
702 /* Internal variables.  These are variables within the debugger
703    that hold values assigned by debugger commands.
704    The user refers to them with a '$' prefix
705    that does not appear in the variable names stored internally.  */
706
707 static struct internalvar *internalvars;
708
709 /* If the variable does not already exist create it and give it the value given.
710    If no value is given then the default is zero.  */
711 static void
712 init_if_undefined_command (char* args, int from_tty)
713 {
714   struct internalvar* intvar;
715
716   /* Parse the expression - this is taken from set_command().  */
717   struct expression *expr = parse_expression (args);
718   register struct cleanup *old_chain =
719     make_cleanup (free_current_contents, &expr);
720
721   /* Validate the expression.
722      Was the expression an assignment?
723      Or even an expression at all?  */
724   if (expr->nelts == 0 || expr->elts[0].opcode != BINOP_ASSIGN)
725     error (_("Init-if-undefined requires an assignment expression."));
726
727   /* Extract the variable from the parsed expression.
728      In the case of an assign the lvalue will be in elts[1] and elts[2].  */
729   if (expr->elts[1].opcode != OP_INTERNALVAR)
730     error (_("The first parameter to init-if-undefined should be a GDB variable."));
731   intvar = expr->elts[2].internalvar;
732
733   /* Only evaluate the expression if the lvalue is void.
734      This may still fail if the expresssion is invalid.  */
735   if (TYPE_CODE (value_type (intvar->value)) == TYPE_CODE_VOID)
736     evaluate_expression (expr);
737
738   do_cleanups (old_chain);
739 }
740
741
742 /* Look up an internal variable with name NAME.  NAME should not
743    normally include a dollar sign.
744
745    If the specified internal variable does not exist,
746    the return value is NULL.  */
747
748 struct internalvar *
749 lookup_only_internalvar (char *name)
750 {
751   struct internalvar *var;
752
753   for (var = internalvars; var; var = var->next)
754     if (strcmp (var->name, name) == 0)
755       return var;
756
757   return NULL;
758 }
759
760
761 /* Create an internal variable with name NAME and with a void value.
762    NAME should not normally include a dollar sign.  */
763
764 struct internalvar *
765 create_internalvar (char *name)
766 {
767   struct internalvar *var;
768   var = (struct internalvar *) xmalloc (sizeof (struct internalvar));
769   var->name = concat (name, (char *)NULL);
770   var->value = allocate_value (builtin_type_void);
771   var->endian = gdbarch_byte_order (current_gdbarch);
772   release_value (var->value);
773   var->next = internalvars;
774   internalvars = var;
775   return var;
776 }
777
778
779 /* Look up an internal variable with name NAME.  NAME should not
780    normally include a dollar sign.
781
782    If the specified internal variable does not exist,
783    one is created, with a void value.  */
784
785 struct internalvar *
786 lookup_internalvar (char *name)
787 {
788   struct internalvar *var;
789
790   var = lookup_only_internalvar (name);
791   if (var)
792     return var;
793
794   return create_internalvar (name);
795 }
796
797 struct value *
798 value_of_internalvar (struct internalvar *var)
799 {
800   struct value *val;
801   int i, j;
802   gdb_byte temp;
803
804   val = value_copy (var->value);
805   if (value_lazy (val))
806     value_fetch_lazy (val);
807   VALUE_LVAL (val) = lval_internalvar;
808   VALUE_INTERNALVAR (val) = var;
809
810   /* Values are always stored in the target's byte order.  When connected to a
811      target this will most likely always be correct, so there's normally no
812      need to worry about it.
813
814      However, internal variables can be set up before the target endian is
815      known and so may become out of date.  Fix it up before anybody sees.
816
817      Internal variables usually hold simple scalar values, and we can
818      correct those.  More complex values (e.g. structures and floating
819      point types) are left alone, because they would be too complicated
820      to correct.  */
821
822   if (var->endian != gdbarch_byte_order (current_gdbarch))
823     {
824       gdb_byte *array = value_contents_raw (val);
825       struct type *type = check_typedef (value_enclosing_type (val));
826       switch (TYPE_CODE (type))
827         {
828         case TYPE_CODE_INT:
829         case TYPE_CODE_PTR:
830           /* Reverse the bytes.  */
831           for (i = 0, j = TYPE_LENGTH (type) - 1; i < j; i++, j--)
832             {
833               temp = array[j];
834               array[j] = array[i];
835               array[i] = temp;
836             }
837           break;
838         }
839     }
840
841   return val;
842 }
843
844 void
845 set_internalvar_component (struct internalvar *var, int offset, int bitpos,
846                            int bitsize, struct value *newval)
847 {
848   gdb_byte *addr = value_contents_writeable (var->value) + offset;
849
850   if (bitsize)
851     modify_field (addr, value_as_long (newval),
852                   bitpos, bitsize);
853   else
854     memcpy (addr, value_contents (newval), TYPE_LENGTH (value_type (newval)));
855 }
856
857 void
858 set_internalvar (struct internalvar *var, struct value *val)
859 {
860   struct value *newval;
861
862   newval = value_copy (val);
863   newval->modifiable = 1;
864
865   /* Force the value to be fetched from the target now, to avoid problems
866      later when this internalvar is referenced and the target is gone or
867      has changed.  */
868   if (value_lazy (newval))
869     value_fetch_lazy (newval);
870
871   /* Begin code which must not call error().  If var->value points to
872      something free'd, an error() obviously leaves a dangling pointer.
873      But we also get a danling pointer if var->value points to
874      something in the value chain (i.e., before release_value is
875      called), because after the error free_all_values will get called before
876      long.  */
877   xfree (var->value);
878   var->value = newval;
879   var->endian = gdbarch_byte_order (current_gdbarch);
880   release_value (newval);
881   /* End code which must not call error().  */
882 }
883
884 char *
885 internalvar_name (struct internalvar *var)
886 {
887   return var->name;
888 }
889
890 /* Update VALUE before discarding OBJFILE.  COPIED_TYPES is used to
891    prevent cycles / duplicates.  */
892
893 static void
894 preserve_one_value (struct value *value, struct objfile *objfile,
895                     htab_t copied_types)
896 {
897   if (TYPE_OBJFILE (value->type) == objfile)
898     value->type = copy_type_recursive (objfile, value->type, copied_types);
899
900   if (TYPE_OBJFILE (value->enclosing_type) == objfile)
901     value->enclosing_type = copy_type_recursive (objfile,
902                                                  value->enclosing_type,
903                                                  copied_types);
904 }
905
906 /* Update the internal variables and value history when OBJFILE is
907    discarded; we must copy the types out of the objfile.  New global types
908    will be created for every convenience variable which currently points to
909    this objfile's types, and the convenience variables will be adjusted to
910    use the new global types.  */
911
912 void
913 preserve_values (struct objfile *objfile)
914 {
915   htab_t copied_types;
916   struct value_history_chunk *cur;
917   struct internalvar *var;
918   int i;
919
920   /* Create the hash table.  We allocate on the objfile's obstack, since
921      it is soon to be deleted.  */
922   copied_types = create_copied_types_hash (objfile);
923
924   for (cur = value_history_chain; cur; cur = cur->next)
925     for (i = 0; i < VALUE_HISTORY_CHUNK; i++)
926       if (cur->values[i])
927         preserve_one_value (cur->values[i], objfile, copied_types);
928
929   for (var = internalvars; var; var = var->next)
930     preserve_one_value (var->value, objfile, copied_types);
931
932   htab_delete (copied_types);
933 }
934
935 static void
936 show_convenience (char *ignore, int from_tty)
937 {
938   struct internalvar *var;
939   int varseen = 0;
940
941   for (var = internalvars; var; var = var->next)
942     {
943       if (!varseen)
944         {
945           varseen = 1;
946         }
947       printf_filtered (("$%s = "), var->name);
948       value_print (value_of_internalvar (var), gdb_stdout,
949                    0, Val_pretty_default);
950       printf_filtered (("\n"));
951     }
952   if (!varseen)
953     printf_unfiltered (_("\
954 No debugger convenience variables now defined.\n\
955 Convenience variables have names starting with \"$\";\n\
956 use \"set\" as in \"set $foo = 5\" to define them.\n"));
957 }
958 \f
959 /* Extract a value as a C number (either long or double).
960    Knows how to convert fixed values to double, or
961    floating values to long.
962    Does not deallocate the value.  */
963
964 LONGEST
965 value_as_long (struct value *val)
966 {
967   /* This coerces arrays and functions, which is necessary (e.g.
968      in disassemble_command).  It also dereferences references, which
969      I suspect is the most logical thing to do.  */
970   val = coerce_array (val);
971   return unpack_long (value_type (val), value_contents (val));
972 }
973
974 DOUBLEST
975 value_as_double (struct value *val)
976 {
977   DOUBLEST foo;
978   int inv;
979
980   foo = unpack_double (value_type (val), value_contents (val), &inv);
981   if (inv)
982     error (_("Invalid floating value found in program."));
983   return foo;
984 }
985 /* Extract a value as a C pointer. Does not deallocate the value.  
986    Note that val's type may not actually be a pointer; value_as_long
987    handles all the cases.  */
988 CORE_ADDR
989 value_as_address (struct value *val)
990 {
991   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
992      whether we want this to be true eventually.  */
993 #if 0
994   /* gdbarch_addr_bits_remove is wrong if we are being called for a
995      non-address (e.g. argument to "signal", "info break", etc.), or
996      for pointers to char, in which the low bits *are* significant.  */
997   return gdbarch_addr_bits_remove (current_gdbarch, value_as_long (val));
998 #else
999
1000   /* There are several targets (IA-64, PowerPC, and others) which
1001      don't represent pointers to functions as simply the address of
1002      the function's entry point.  For example, on the IA-64, a
1003      function pointer points to a two-word descriptor, generated by
1004      the linker, which contains the function's entry point, and the
1005      value the IA-64 "global pointer" register should have --- to
1006      support position-independent code.  The linker generates
1007      descriptors only for those functions whose addresses are taken.
1008
1009      On such targets, it's difficult for GDB to convert an arbitrary
1010      function address into a function pointer; it has to either find
1011      an existing descriptor for that function, or call malloc and
1012      build its own.  On some targets, it is impossible for GDB to
1013      build a descriptor at all: the descriptor must contain a jump
1014      instruction; data memory cannot be executed; and code memory
1015      cannot be modified.
1016
1017      Upon entry to this function, if VAL is a value of type `function'
1018      (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
1019      VALUE_ADDRESS (val) is the address of the function.  This is what
1020      you'll get if you evaluate an expression like `main'.  The call
1021      to COERCE_ARRAY below actually does all the usual unary
1022      conversions, which includes converting values of type `function'
1023      to `pointer to function'.  This is the challenging conversion
1024      discussed above.  Then, `unpack_long' will convert that pointer
1025      back into an address.
1026
1027      So, suppose the user types `disassemble foo' on an architecture
1028      with a strange function pointer representation, on which GDB
1029      cannot build its own descriptors, and suppose further that `foo'
1030      has no linker-built descriptor.  The address->pointer conversion
1031      will signal an error and prevent the command from running, even
1032      though the next step would have been to convert the pointer
1033      directly back into the same address.
1034
1035      The following shortcut avoids this whole mess.  If VAL is a
1036      function, just return its address directly.  */
1037   if (TYPE_CODE (value_type (val)) == TYPE_CODE_FUNC
1038       || TYPE_CODE (value_type (val)) == TYPE_CODE_METHOD)
1039     return VALUE_ADDRESS (val);
1040
1041   val = coerce_array (val);
1042
1043   /* Some architectures (e.g. Harvard), map instruction and data
1044      addresses onto a single large unified address space.  For
1045      instance: An architecture may consider a large integer in the
1046      range 0x10000000 .. 0x1000ffff to already represent a data
1047      addresses (hence not need a pointer to address conversion) while
1048      a small integer would still need to be converted integer to
1049      pointer to address.  Just assume such architectures handle all
1050      integer conversions in a single function.  */
1051
1052   /* JimB writes:
1053
1054      I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
1055      must admonish GDB hackers to make sure its behavior matches the
1056      compiler's, whenever possible.
1057
1058      In general, I think GDB should evaluate expressions the same way
1059      the compiler does.  When the user copies an expression out of
1060      their source code and hands it to a `print' command, they should
1061      get the same value the compiler would have computed.  Any
1062      deviation from this rule can cause major confusion and annoyance,
1063      and needs to be justified carefully.  In other words, GDB doesn't
1064      really have the freedom to do these conversions in clever and
1065      useful ways.
1066
1067      AndrewC pointed out that users aren't complaining about how GDB
1068      casts integers to pointers; they are complaining that they can't
1069      take an address from a disassembly listing and give it to `x/i'.
1070      This is certainly important.
1071
1072      Adding an architecture method like integer_to_address() certainly
1073      makes it possible for GDB to "get it right" in all circumstances
1074      --- the target has complete control over how things get done, so
1075      people can Do The Right Thing for their target without breaking
1076      anyone else.  The standard doesn't specify how integers get
1077      converted to pointers; usually, the ABI doesn't either, but
1078      ABI-specific code is a more reasonable place to handle it.  */
1079
1080   if (TYPE_CODE (value_type (val)) != TYPE_CODE_PTR
1081       && TYPE_CODE (value_type (val)) != TYPE_CODE_REF
1082       && gdbarch_integer_to_address_p (current_gdbarch))
1083     return gdbarch_integer_to_address (current_gdbarch, value_type (val),
1084                                        value_contents (val));
1085
1086   return unpack_long (value_type (val), value_contents (val));
1087 #endif
1088 }
1089 \f
1090 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
1091    as a long, or as a double, assuming the raw data is described
1092    by type TYPE.  Knows how to convert different sizes of values
1093    and can convert between fixed and floating point.  We don't assume
1094    any alignment for the raw data.  Return value is in host byte order.
1095
1096    If you want functions and arrays to be coerced to pointers, and
1097    references to be dereferenced, call value_as_long() instead.
1098
1099    C++: It is assumed that the front-end has taken care of
1100    all matters concerning pointers to members.  A pointer
1101    to member which reaches here is considered to be equivalent
1102    to an INT (or some size).  After all, it is only an offset.  */
1103
1104 LONGEST
1105 unpack_long (struct type *type, const gdb_byte *valaddr)
1106 {
1107   enum type_code code = TYPE_CODE (type);
1108   int len = TYPE_LENGTH (type);
1109   int nosign = TYPE_UNSIGNED (type);
1110
1111   switch (code)
1112     {
1113     case TYPE_CODE_TYPEDEF:
1114       return unpack_long (check_typedef (type), valaddr);
1115     case TYPE_CODE_ENUM:
1116     case TYPE_CODE_FLAGS:
1117     case TYPE_CODE_BOOL:
1118     case TYPE_CODE_INT:
1119     case TYPE_CODE_CHAR:
1120     case TYPE_CODE_RANGE:
1121     case TYPE_CODE_MEMBERPTR:
1122       if (nosign)
1123         return extract_unsigned_integer (valaddr, len);
1124       else
1125         return extract_signed_integer (valaddr, len);
1126
1127     case TYPE_CODE_FLT:
1128       return extract_typed_floating (valaddr, type);
1129
1130     case TYPE_CODE_PTR:
1131     case TYPE_CODE_REF:
1132       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
1133          whether we want this to be true eventually.  */
1134       return extract_typed_address (valaddr, type);
1135
1136     default:
1137       error (_("Value can't be converted to integer."));
1138     }
1139   return 0;                     /* Placate lint.  */
1140 }
1141
1142 /* Return a double value from the specified type and address.
1143    INVP points to an int which is set to 0 for valid value,
1144    1 for invalid value (bad float format).  In either case,
1145    the returned double is OK to use.  Argument is in target
1146    format, result is in host format.  */
1147
1148 DOUBLEST
1149 unpack_double (struct type *type, const gdb_byte *valaddr, int *invp)
1150 {
1151   enum type_code code;
1152   int len;
1153   int nosign;
1154
1155   *invp = 0;                    /* Assume valid.   */
1156   CHECK_TYPEDEF (type);
1157   code = TYPE_CODE (type);
1158   len = TYPE_LENGTH (type);
1159   nosign = TYPE_UNSIGNED (type);
1160   if (code == TYPE_CODE_FLT)
1161     {
1162       /* NOTE: cagney/2002-02-19: There was a test here to see if the
1163          floating-point value was valid (using the macro
1164          INVALID_FLOAT).  That test/macro have been removed.
1165
1166          It turns out that only the VAX defined this macro and then
1167          only in a non-portable way.  Fixing the portability problem
1168          wouldn't help since the VAX floating-point code is also badly
1169          bit-rotten.  The target needs to add definitions for the
1170          methods gdbarch_float_format and gdbarch_double_format - these
1171          exactly describe the target floating-point format.  The
1172          problem here is that the corresponding floatformat_vax_f and
1173          floatformat_vax_d values these methods should be set to are
1174          also not defined either.  Oops!
1175
1176          Hopefully someone will add both the missing floatformat
1177          definitions and the new cases for floatformat_is_valid ().  */
1178
1179       if (!floatformat_is_valid (floatformat_from_type (type), valaddr))
1180         {
1181           *invp = 1;
1182           return 0.0;
1183         }
1184
1185       return extract_typed_floating (valaddr, type);
1186     }
1187   else if (nosign)
1188     {
1189       /* Unsigned -- be sure we compensate for signed LONGEST.  */
1190       return (ULONGEST) unpack_long (type, valaddr);
1191     }
1192   else
1193     {
1194       /* Signed -- we are OK with unpack_long.  */
1195       return unpack_long (type, valaddr);
1196     }
1197 }
1198
1199 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
1200    as a CORE_ADDR, assuming the raw data is described by type TYPE.
1201    We don't assume any alignment for the raw data.  Return value is in
1202    host byte order.
1203
1204    If you want functions and arrays to be coerced to pointers, and
1205    references to be dereferenced, call value_as_address() instead.
1206
1207    C++: It is assumed that the front-end has taken care of
1208    all matters concerning pointers to members.  A pointer
1209    to member which reaches here is considered to be equivalent
1210    to an INT (or some size).  After all, it is only an offset.  */
1211
1212 CORE_ADDR
1213 unpack_pointer (struct type *type, const gdb_byte *valaddr)
1214 {
1215   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
1216      whether we want this to be true eventually.  */
1217   return unpack_long (type, valaddr);
1218 }
1219
1220 \f
1221 /* Get the value of the FIELDN'th field (which must be static) of
1222    TYPE.  Return NULL if the field doesn't exist or has been
1223    optimized out. */
1224
1225 struct value *
1226 value_static_field (struct type *type, int fieldno)
1227 {
1228   struct value *retval;
1229
1230   if (TYPE_FIELD_STATIC_HAS_ADDR (type, fieldno))
1231     {
1232       retval = value_at (TYPE_FIELD_TYPE (type, fieldno),
1233                          TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
1234     }
1235   else
1236     {
1237       char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
1238       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0, NULL);
1239       if (sym == NULL)
1240         {
1241           /* With some compilers, e.g. HP aCC, static data members are reported
1242              as non-debuggable symbols */
1243           struct minimal_symbol *msym = lookup_minimal_symbol (phys_name, NULL, NULL);
1244           if (!msym)
1245             return NULL;
1246           else
1247             {
1248               retval = value_at (TYPE_FIELD_TYPE (type, fieldno),
1249                                  SYMBOL_VALUE_ADDRESS (msym));
1250             }
1251         }
1252       else
1253         {
1254           /* SYM should never have a SYMBOL_CLASS which will require
1255              read_var_value to use the FRAME parameter.  */
1256           if (symbol_read_needs_frame (sym))
1257             warning (_("static field's value depends on the current "
1258                      "frame - bad debug info?"));
1259           retval = read_var_value (sym, NULL);
1260         }
1261       if (retval && VALUE_LVAL (retval) == lval_memory)
1262         SET_FIELD_PHYSADDR (TYPE_FIELD (type, fieldno),
1263                             VALUE_ADDRESS (retval));
1264     }
1265   return retval;
1266 }
1267
1268 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.  
1269    You have to be careful here, since the size of the data area for the value 
1270    is set by the length of the enclosing type.  So if NEW_ENCL_TYPE is bigger 
1271    than the old enclosing type, you have to allocate more space for the data.  
1272    The return value is a pointer to the new version of this value structure. */
1273
1274 struct value *
1275 value_change_enclosing_type (struct value *val, struct type *new_encl_type)
1276 {
1277   if (TYPE_LENGTH (new_encl_type) <= TYPE_LENGTH (value_enclosing_type (val))) 
1278     {
1279       val->enclosing_type = new_encl_type;
1280       return val;
1281     }
1282   else
1283     {
1284       struct value *new_val;
1285       struct value *prev;
1286       
1287       new_val = (struct value *) xrealloc (val, sizeof (struct value) + TYPE_LENGTH (new_encl_type));
1288
1289       new_val->enclosing_type = new_encl_type;
1290  
1291       /* We have to make sure this ends up in the same place in the value
1292          chain as the original copy, so it's clean-up behavior is the same. 
1293          If the value has been released, this is a waste of time, but there
1294          is no way to tell that in advance, so... */
1295       
1296       if (val != all_values) 
1297         {
1298           for (prev = all_values; prev != NULL; prev = prev->next)
1299             {
1300               if (prev->next == val) 
1301                 {
1302                   prev->next = new_val;
1303                   break;
1304                 }
1305             }
1306         }
1307       
1308       return new_val;
1309     }
1310 }
1311
1312 /* Given a value ARG1 (offset by OFFSET bytes)
1313    of a struct or union type ARG_TYPE,
1314    extract and return the value of one of its (non-static) fields.
1315    FIELDNO says which field. */
1316
1317 struct value *
1318 value_primitive_field (struct value *arg1, int offset,
1319                        int fieldno, struct type *arg_type)
1320 {
1321   struct value *v;
1322   struct type *type;
1323
1324   CHECK_TYPEDEF (arg_type);
1325   type = TYPE_FIELD_TYPE (arg_type, fieldno);
1326
1327   /* Handle packed fields */
1328
1329   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
1330     {
1331       v = value_from_longest (type,
1332                               unpack_field_as_long (arg_type,
1333                                                     value_contents (arg1)
1334                                                     + offset,
1335                                                     fieldno));
1336       v->bitpos = TYPE_FIELD_BITPOS (arg_type, fieldno) % 8;
1337       v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
1338       v->offset = value_offset (arg1) + offset
1339         + TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
1340     }
1341   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
1342     {
1343       /* This field is actually a base subobject, so preserve the
1344          entire object's contents for later references to virtual
1345          bases, etc.  */
1346       v = allocate_value (value_enclosing_type (arg1));
1347       v->type = type;
1348       if (value_lazy (arg1))
1349         set_value_lazy (v, 1);
1350       else
1351         memcpy (value_contents_all_raw (v), value_contents_all_raw (arg1),
1352                 TYPE_LENGTH (value_enclosing_type (arg1)));
1353       v->offset = value_offset (arg1);
1354       v->embedded_offset = (offset + value_embedded_offset (arg1)
1355                             + TYPE_FIELD_BITPOS (arg_type, fieldno) / 8);
1356     }
1357   else
1358     {
1359       /* Plain old data member */
1360       offset += TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
1361       v = allocate_value (type);
1362       if (value_lazy (arg1))
1363         set_value_lazy (v, 1);
1364       else
1365         memcpy (value_contents_raw (v),
1366                 value_contents_raw (arg1) + offset,
1367                 TYPE_LENGTH (type));
1368       v->offset = (value_offset (arg1) + offset
1369                    + value_embedded_offset (arg1));
1370     }
1371   VALUE_LVAL (v) = VALUE_LVAL (arg1);
1372   if (VALUE_LVAL (arg1) == lval_internalvar)
1373     VALUE_LVAL (v) = lval_internalvar_component;
1374   v->location = arg1->location;
1375   VALUE_REGNUM (v) = VALUE_REGNUM (arg1);
1376   VALUE_FRAME_ID (v) = VALUE_FRAME_ID (arg1);
1377   return v;
1378 }
1379
1380 /* Given a value ARG1 of a struct or union type,
1381    extract and return the value of one of its (non-static) fields.
1382    FIELDNO says which field. */
1383
1384 struct value *
1385 value_field (struct value *arg1, int fieldno)
1386 {
1387   return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
1388 }
1389
1390 /* Return a non-virtual function as a value.
1391    F is the list of member functions which contains the desired method.
1392    J is an index into F which provides the desired method.
1393
1394    We only use the symbol for its address, so be happy with either a
1395    full symbol or a minimal symbol.
1396  */
1397
1398 struct value *
1399 value_fn_field (struct value **arg1p, struct fn_field *f, int j, struct type *type,
1400                 int offset)
1401 {
1402   struct value *v;
1403   struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
1404   char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
1405   struct symbol *sym;
1406   struct minimal_symbol *msym;
1407
1408   sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0, NULL);
1409   if (sym != NULL)
1410     {
1411       msym = NULL;
1412     }
1413   else
1414     {
1415       gdb_assert (sym == NULL);
1416       msym = lookup_minimal_symbol (physname, NULL, NULL);
1417       if (msym == NULL)
1418         return NULL;
1419     }
1420
1421   v = allocate_value (ftype);
1422   if (sym)
1423     {
1424       VALUE_ADDRESS (v) = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
1425     }
1426   else
1427     {
1428       VALUE_ADDRESS (v) = SYMBOL_VALUE_ADDRESS (msym);
1429     }
1430
1431   if (arg1p)
1432     {
1433       if (type != value_type (*arg1p))
1434         *arg1p = value_ind (value_cast (lookup_pointer_type (type),
1435                                         value_addr (*arg1p)));
1436
1437       /* Move the `this' pointer according to the offset.
1438          VALUE_OFFSET (*arg1p) += offset;
1439        */
1440     }
1441
1442   return v;
1443 }
1444
1445 \f
1446 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous object at
1447    VALADDR.
1448
1449    Extracting bits depends on endianness of the machine.  Compute the
1450    number of least significant bits to discard.  For big endian machines,
1451    we compute the total number of bits in the anonymous object, subtract
1452    off the bit count from the MSB of the object to the MSB of the
1453    bitfield, then the size of the bitfield, which leaves the LSB discard
1454    count.  For little endian machines, the discard count is simply the
1455    number of bits from the LSB of the anonymous object to the LSB of the
1456    bitfield.
1457
1458    If the field is signed, we also do sign extension. */
1459
1460 LONGEST
1461 unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
1462 {
1463   ULONGEST val;
1464   ULONGEST valmask;
1465   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
1466   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
1467   int lsbcount;
1468   struct type *field_type;
1469
1470   val = extract_unsigned_integer (valaddr + bitpos / 8, sizeof (val));
1471   field_type = TYPE_FIELD_TYPE (type, fieldno);
1472   CHECK_TYPEDEF (field_type);
1473
1474   /* Extract bits.  See comment above. */
1475
1476   if (BITS_BIG_ENDIAN)
1477     lsbcount = (sizeof val * 8 - bitpos % 8 - bitsize);
1478   else
1479     lsbcount = (bitpos % 8);
1480   val >>= lsbcount;
1481
1482   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
1483      If the field is signed, and is negative, then sign extend. */
1484
1485   if ((bitsize > 0) && (bitsize < 8 * (int) sizeof (val)))
1486     {
1487       valmask = (((ULONGEST) 1) << bitsize) - 1;
1488       val &= valmask;
1489       if (!TYPE_UNSIGNED (field_type))
1490         {
1491           if (val & (valmask ^ (valmask >> 1)))
1492             {
1493               val |= ~valmask;
1494             }
1495         }
1496     }
1497   return (val);
1498 }
1499
1500 /* Modify the value of a bitfield.  ADDR points to a block of memory in
1501    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
1502    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
1503    indicate which bits (in target bit order) comprise the bitfield.  
1504    Requires 0 < BITSIZE <= lbits, 0 <= BITPOS+BITSIZE <= lbits, and
1505    0 <= BITPOS, where lbits is the size of a LONGEST in bits.  */
1506
1507 void
1508 modify_field (gdb_byte *addr, LONGEST fieldval, int bitpos, int bitsize)
1509 {
1510   ULONGEST oword;
1511   ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
1512
1513   /* If a negative fieldval fits in the field in question, chop
1514      off the sign extension bits.  */
1515   if ((~fieldval & ~(mask >> 1)) == 0)
1516     fieldval &= mask;
1517
1518   /* Warn if value is too big to fit in the field in question.  */
1519   if (0 != (fieldval & ~mask))
1520     {
1521       /* FIXME: would like to include fieldval in the message, but
1522          we don't have a sprintf_longest.  */
1523       warning (_("Value does not fit in %d bits."), bitsize);
1524
1525       /* Truncate it, otherwise adjoining fields may be corrupted.  */
1526       fieldval &= mask;
1527     }
1528
1529   oword = extract_unsigned_integer (addr, sizeof oword);
1530
1531   /* Shifting for bit field depends on endianness of the target machine.  */
1532   if (BITS_BIG_ENDIAN)
1533     bitpos = sizeof (oword) * 8 - bitpos - bitsize;
1534
1535   oword &= ~(mask << bitpos);
1536   oword |= fieldval << bitpos;
1537
1538   store_unsigned_integer (addr, sizeof oword, oword);
1539 }
1540 \f
1541 /* Pack NUM into BUF using a target format of TYPE.  */
1542
1543 void
1544 pack_long (gdb_byte *buf, struct type *type, LONGEST num)
1545 {
1546   int len;
1547
1548   type = check_typedef (type);
1549   len = TYPE_LENGTH (type);
1550
1551   switch (TYPE_CODE (type))
1552     {
1553     case TYPE_CODE_INT:
1554     case TYPE_CODE_CHAR:
1555     case TYPE_CODE_ENUM:
1556     case TYPE_CODE_FLAGS:
1557     case TYPE_CODE_BOOL:
1558     case TYPE_CODE_RANGE:
1559     case TYPE_CODE_MEMBERPTR:
1560       store_signed_integer (buf, len, num);
1561       break;
1562
1563     case TYPE_CODE_REF:
1564     case TYPE_CODE_PTR:
1565       store_typed_address (buf, type, (CORE_ADDR) num);
1566       break;
1567
1568     default:
1569       error (_("Unexpected type (%d) encountered for integer constant."),
1570              TYPE_CODE (type));
1571     }
1572 }
1573
1574
1575 /* Convert C numbers into newly allocated values.  */
1576
1577 struct value *
1578 value_from_longest (struct type *type, LONGEST num)
1579 {
1580   struct value *val = allocate_value (type);
1581
1582   pack_long (value_contents_raw (val), type, num);
1583
1584   return val;
1585 }
1586
1587
1588 /* Create a value representing a pointer of type TYPE to the address
1589    ADDR.  */
1590 struct value *
1591 value_from_pointer (struct type *type, CORE_ADDR addr)
1592 {
1593   struct value *val = allocate_value (type);
1594   store_typed_address (value_contents_raw (val), type, addr);
1595   return val;
1596 }
1597
1598
1599 /* Create a value for a string constant to be stored locally
1600    (not in the inferior's memory space, but in GDB memory).
1601    This is analogous to value_from_longest, which also does not
1602    use inferior memory.  String shall NOT contain embedded nulls.  */
1603
1604 struct value *
1605 value_from_string (char *ptr)
1606 {
1607   struct value *val;
1608   int len = strlen (ptr);
1609   int lowbound = current_language->string_lower_bound;
1610   struct type *string_char_type;
1611   struct type *rangetype;
1612   struct type *stringtype;
1613
1614   rangetype = create_range_type ((struct type *) NULL,
1615                                  builtin_type_int,
1616                                  lowbound, len + lowbound - 1);
1617   string_char_type = language_string_char_type (current_language,
1618                                                 current_gdbarch);
1619   stringtype = create_array_type ((struct type *) NULL,
1620                                   string_char_type,
1621                                   rangetype);
1622   val = allocate_value (stringtype);
1623   memcpy (value_contents_raw (val), ptr, len);
1624   return val;
1625 }
1626
1627 struct value *
1628 value_from_double (struct type *type, DOUBLEST num)
1629 {
1630   struct value *val = allocate_value (type);
1631   struct type *base_type = check_typedef (type);
1632   enum type_code code = TYPE_CODE (base_type);
1633   int len = TYPE_LENGTH (base_type);
1634
1635   if (code == TYPE_CODE_FLT)
1636     {
1637       store_typed_floating (value_contents_raw (val), base_type, num);
1638     }
1639   else
1640     error (_("Unexpected type encountered for floating constant."));
1641
1642   return val;
1643 }
1644
1645 struct value *
1646 value_from_decfloat (struct type *expect_type, struct type *type,
1647                       gdb_byte decbytes[16])
1648 {
1649   struct value *val = allocate_value (type);
1650   int len = TYPE_LENGTH (type);
1651
1652   if (expect_type)
1653     {
1654       int expect_len = TYPE_LENGTH (expect_type);
1655       char decstr[128];
1656       int real_len;
1657
1658       decimal_to_string (decbytes, len, decstr);
1659       decimal_from_string (decbytes, expect_len, decstr);
1660     }
1661
1662   memcpy (value_contents_raw (val), decbytes, len);
1663   return val;
1664 }
1665
1666 struct value *
1667 coerce_ref (struct value *arg)
1668 {
1669   struct type *value_type_arg_tmp = check_typedef (value_type (arg));
1670   if (TYPE_CODE (value_type_arg_tmp) == TYPE_CODE_REF)
1671     arg = value_at_lazy (TYPE_TARGET_TYPE (value_type_arg_tmp),
1672                          unpack_pointer (value_type (arg),              
1673                                          value_contents (arg)));
1674   return arg;
1675 }
1676
1677 struct value *
1678 coerce_array (struct value *arg)
1679 {
1680   arg = coerce_ref (arg);
1681   if (current_language->c_style_arrays
1682       && TYPE_CODE (value_type (arg)) == TYPE_CODE_ARRAY)
1683     arg = value_coerce_array (arg);
1684   if (TYPE_CODE (value_type (arg)) == TYPE_CODE_FUNC)
1685     arg = value_coerce_function (arg);
1686   return arg;
1687 }
1688
1689 struct value *
1690 coerce_number (struct value *arg)
1691 {
1692   arg = coerce_array (arg);
1693   arg = coerce_enum (arg);
1694   return arg;
1695 }
1696
1697 struct value *
1698 coerce_enum (struct value *arg)
1699 {
1700   if (TYPE_CODE (check_typedef (value_type (arg))) == TYPE_CODE_ENUM)
1701     arg = value_cast (builtin_type_unsigned_int, arg);
1702   return arg;
1703 }
1704 \f
1705
1706 /* Return true if the function returning the specified type is using
1707    the convention of returning structures in memory (passing in the
1708    address as a hidden first parameter).  */
1709
1710 int
1711 using_struct_return (struct type *value_type)
1712 {
1713   enum type_code code = TYPE_CODE (value_type);
1714
1715   if (code == TYPE_CODE_ERROR)
1716     error (_("Function return type unknown."));
1717
1718   if (code == TYPE_CODE_VOID)
1719     /* A void return value is never in memory.  See also corresponding
1720        code in "print_return_value".  */
1721     return 0;
1722
1723   /* Probe the architecture for the return-value convention.  */
1724   return (gdbarch_return_value (current_gdbarch, value_type,
1725                                 NULL, NULL, NULL)
1726           != RETURN_VALUE_REGISTER_CONVENTION);
1727 }
1728
1729 /* Set the initialized field in a value struct.  */
1730
1731 void
1732 set_value_initialized (struct value *val, int status)
1733 {
1734   val->initialized = status;
1735 }
1736
1737 /* Return the initialized field in a value struct.  */
1738
1739 int
1740 value_initialized (struct value *val)
1741 {
1742   return val->initialized;
1743 }
1744
1745 void
1746 _initialize_values (void)
1747 {
1748   add_cmd ("convenience", no_class, show_convenience, _("\
1749 Debugger convenience (\"$foo\") variables.\n\
1750 These variables are created when you assign them values;\n\
1751 thus, \"print $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\
1752 \n\
1753 A few convenience variables are given values automatically:\n\
1754 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
1755 \"$__\" holds the contents of the last address examined with \"x\"."),
1756            &showlist);
1757
1758   add_cmd ("values", no_class, show_values,
1759            _("Elements of value history around item number IDX (or last ten)."),
1760            &showlist);
1761
1762   add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
1763 Initialize a convenience variable if necessary.\n\
1764 init-if-undefined VARIABLE = EXPRESSION\n\
1765 Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
1766 exist or does not contain a value.  The EXPRESSION is not evaluated if the\n\
1767 VARIABLE is already initialized."));
1768 }