OSDN Git Service

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