Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / gdb / gdb / values.c
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
2    Copyright 1986, 87, 89, 91, 93, 94, 95, 96, 97, 1998
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "gdb_string.h"
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "value.h"
26 #include "gdbcore.h"
27 #include "frame.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "target.h"
31 #include "language.h"
32 #include "scm-lang.h"
33 #include "demangle.h"
34
35 /* Prototypes for exported functions. */
36
37 void _initialize_values PARAMS ((void));
38
39 /* Prototypes for local functions. */
40
41 static value_ptr value_headof PARAMS ((value_ptr, struct type *,
42                                        struct type *));
43
44 static void show_values PARAMS ((char *, int));
45
46 static void show_convenience PARAMS ((char *, int));
47
48 static int vb_match PARAMS ((struct type *, int, struct type *));
49
50 /* The value-history records all the values printed
51    by print commands during this session.  Each chunk
52    records 60 consecutive values.  The first chunk on
53    the chain records the most recent values.
54    The total number of values is in value_history_count.  */
55
56 #define VALUE_HISTORY_CHUNK 60
57
58 struct value_history_chunk
59 {
60   struct value_history_chunk *next;
61   value_ptr values[VALUE_HISTORY_CHUNK];
62 };
63
64 /* Chain of chunks now in use.  */
65
66 static struct value_history_chunk *value_history_chain;
67
68 static int value_history_count; /* Abs number of last entry stored */
69 \f
70 /* List of all value objects currently allocated
71    (except for those released by calls to release_value)
72    This is so they can be freed after each command.  */
73
74 static value_ptr all_values;
75
76 /* Allocate a  value  that has the correct length for type TYPE.  */
77
78 value_ptr
79 allocate_value (type)
80      struct type *type;
81 {
82   register value_ptr val;
83   struct type *atype = check_typedef (type);
84
85   val = (struct value *) xmalloc (sizeof (struct value) + TYPE_LENGTH (atype));
86   VALUE_NEXT (val) = all_values;
87   all_values = val;
88   VALUE_TYPE (val) = type;
89   VALUE_ENCLOSING_TYPE (val) = type;
90   VALUE_LVAL (val) = not_lval;
91   VALUE_ADDRESS (val) = 0;
92   VALUE_FRAME (val) = 0;
93   VALUE_OFFSET (val) = 0;
94   VALUE_BITPOS (val) = 0;
95   VALUE_BITSIZE (val) = 0;
96   VALUE_REGNO (val) = -1;
97   VALUE_LAZY (val) = 0;
98   VALUE_OPTIMIZED_OUT (val) = 0;
99   VALUE_BFD_SECTION (val) = NULL;
100   VALUE_EMBEDDED_OFFSET (val) = 0;
101   VALUE_POINTED_TO_OFFSET (val) = 0;
102   val->modifiable = 1;
103   return val;
104 }
105
106 /* Allocate a  value  that has the correct length
107    for COUNT repetitions type TYPE.  */
108
109 value_ptr
110 allocate_repeat_value (type, count)
111      struct type *type;
112      int count;
113 {
114   int low_bound = current_language->string_lower_bound; /* ??? */
115   /* FIXME-type-allocation: need a way to free this type when we are
116      done with it.  */
117   struct type *range_type
118     = create_range_type ((struct type *) NULL, builtin_type_int,
119                          low_bound, count + low_bound - 1);
120   /* FIXME-type-allocation: need a way to free this type when we are
121      done with it.  */
122   return allocate_value (create_array_type ((struct type *) NULL,
123                                             type, range_type));
124 }
125
126 /* Return a mark in the value chain.  All values allocated after the
127    mark is obtained (except for those released) are subject to being freed
128    if a subsequent value_free_to_mark is passed the mark.  */
129 value_ptr
130 value_mark ()
131 {
132   return all_values;
133 }
134
135 /* Free all values allocated since MARK was obtained by value_mark
136    (except for those released).  */
137 void
138 value_free_to_mark (mark)
139      value_ptr mark;
140 {
141   value_ptr val, next;
142
143   for (val = all_values; val && val != mark; val = next)
144     {
145       next = VALUE_NEXT (val);
146       value_free (val);
147     }
148   all_values = val;
149 }
150
151 /* Free all the values that have been allocated (except for those released).
152    Called after each command, successful or not.  */
153
154 void
155 free_all_values ()
156 {
157   register value_ptr val, next;
158
159   for (val = all_values; val; val = next)
160     {
161       next = VALUE_NEXT (val);
162       value_free (val);
163     }
164
165   all_values = 0;
166 }
167
168 /* Remove VAL from the chain all_values
169    so it will not be freed automatically.  */
170
171 void
172 release_value (val)
173      register value_ptr val;
174 {
175   register value_ptr v;
176
177   if (all_values == val)
178     {
179       all_values = val->next;
180       return;
181     }
182
183   for (v = all_values; v; v = v->next)
184     {
185       if (v->next == val)
186         {
187           v->next = val->next;
188           break;
189         }
190     }
191 }
192
193 /* Release all values up to mark  */
194 value_ptr
195 value_release_to_mark (mark)
196      value_ptr mark;
197 {
198   value_ptr val, next;
199
200   for (val = next = all_values; next; next = VALUE_NEXT (next))
201     if (VALUE_NEXT (next) == mark)
202       {
203         all_values = VALUE_NEXT (next);
204         VALUE_NEXT (next) = 0;
205         return val;
206       }
207   all_values = 0;
208   return val;
209 }
210
211 /* Return a copy of the value ARG.
212    It contains the same contents, for same memory address,
213    but it's a different block of storage.  */
214
215 value_ptr
216 value_copy (arg)
217      value_ptr arg;
218 {
219   register struct type *encl_type = VALUE_ENCLOSING_TYPE (arg);
220   register value_ptr val = allocate_value (encl_type);
221   VALUE_TYPE (val) = VALUE_TYPE (arg);
222   VALUE_LVAL (val) = VALUE_LVAL (arg);
223   VALUE_ADDRESS (val) = VALUE_ADDRESS (arg);
224   VALUE_OFFSET (val) = VALUE_OFFSET (arg);
225   VALUE_BITPOS (val) = VALUE_BITPOS (arg);
226   VALUE_BITSIZE (val) = VALUE_BITSIZE (arg);
227   VALUE_FRAME (val) = VALUE_FRAME (arg);
228   VALUE_REGNO (val) = VALUE_REGNO (arg);
229   VALUE_LAZY (val) = VALUE_LAZY (arg);
230   VALUE_OPTIMIZED_OUT (val) = VALUE_OPTIMIZED_OUT (arg);
231   VALUE_EMBEDDED_OFFSET (val) = VALUE_EMBEDDED_OFFSET (arg);
232   VALUE_POINTED_TO_OFFSET (val) = VALUE_POINTED_TO_OFFSET (arg);
233   VALUE_BFD_SECTION (val) = VALUE_BFD_SECTION (arg);
234   val->modifiable = arg->modifiable;
235   if (!VALUE_LAZY (val))
236     {
237       memcpy (VALUE_CONTENTS_ALL_RAW (val), VALUE_CONTENTS_ALL_RAW (arg),
238               TYPE_LENGTH (VALUE_ENCLOSING_TYPE (arg)));
239
240     }
241   return val;
242 }
243 \f
244 /* Access to the value history.  */
245
246 /* Record a new value in the value history.
247    Returns the absolute history index of the entry.
248    Result of -1 indicates the value was not saved; otherwise it is the
249    value history index of this new item.  */
250
251 int
252 record_latest_value (val)
253      value_ptr val;
254 {
255   int i;
256
257   /* We don't want this value to have anything to do with the inferior anymore.
258      In particular, "set $1 = 50" should not affect the variable from which
259      the value was taken, and fast watchpoints should be able to assume that
260      a value on the value history never changes.  */
261   if (VALUE_LAZY (val))
262     value_fetch_lazy (val);
263   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
264      from.  This is a bit dubious, because then *&$1 does not just return $1
265      but the current contents of that location.  c'est la vie...  */
266   val->modifiable = 0;
267   release_value (val);
268
269   /* Here we treat value_history_count as origin-zero
270      and applying to the value being stored now.  */
271
272   i = value_history_count % VALUE_HISTORY_CHUNK;
273   if (i == 0)
274     {
275       register struct value_history_chunk *new
276         = (struct value_history_chunk *)
277           xmalloc (sizeof (struct value_history_chunk));
278       memset (new->values, 0, sizeof new->values);
279       new->next = value_history_chain;
280       value_history_chain = new;
281     }
282
283   value_history_chain->values[i] = val;
284
285   /* Now we regard value_history_count as origin-one
286      and applying to the value just stored.  */
287
288   return ++value_history_count;
289 }
290
291 /* Return a copy of the value in the history with sequence number NUM.  */
292
293 value_ptr
294 access_value_history (num)
295      int num;
296 {
297   register struct value_history_chunk *chunk;
298   register int i;
299   register int absnum = num;
300
301   if (absnum <= 0)
302     absnum += value_history_count;
303
304   if (absnum <= 0)
305     {
306       if (num == 0)
307         error ("The history is empty.");
308       else if (num == 1)
309         error ("There is only one value in the history.");
310       else
311         error ("History does not go back to $$%d.", -num);
312     }
313   if (absnum > value_history_count)
314     error ("History has not yet reached $%d.", absnum);
315
316   absnum--;
317
318   /* Now absnum is always absolute and origin zero.  */
319
320   chunk = value_history_chain;
321   for (i = (value_history_count - 1) / VALUE_HISTORY_CHUNK - absnum / VALUE_HISTORY_CHUNK;
322        i > 0; i--)
323     chunk = chunk->next;
324
325   return value_copy (chunk->values[absnum % VALUE_HISTORY_CHUNK]);
326 }
327
328 /* Clear the value history entirely.
329    Must be done when new symbol tables are loaded,
330    because the type pointers become invalid.  */
331
332 void
333 clear_value_history ()
334 {
335   register struct value_history_chunk *next;
336   register int i;
337   register value_ptr val;
338
339   while (value_history_chain)
340     {
341       for (i = 0; i < VALUE_HISTORY_CHUNK; i++)
342         if ((val = value_history_chain->values[i]) != NULL)
343           free ((PTR)val);
344       next = value_history_chain->next;
345       free ((PTR)value_history_chain);
346       value_history_chain = next;
347     }
348   value_history_count = 0;
349 }
350
351 static void
352 show_values (num_exp, from_tty)
353      char *num_exp;
354      int from_tty;
355 {
356   register int i;
357   register value_ptr val;
358   static int num = 1;
359
360   if (num_exp)
361     {
362         /* "info history +" should print from the stored position.
363            "info history <exp>" should print around value number <exp>.  */
364       if (num_exp[0] != '+' || num_exp[1] != '\0')
365         num = parse_and_eval_address (num_exp) - 5;
366     }
367   else
368     {
369       /* "info history" means print the last 10 values.  */
370       num = value_history_count - 9;
371     }
372
373   if (num <= 0)
374     num = 1;
375
376   for (i = num; i < num + 10 && i <= value_history_count; i++)
377     {
378       val = access_value_history (i);
379       printf_filtered ("$%d = ", i);
380       value_print (val, gdb_stdout, 0, Val_pretty_default);
381       printf_filtered ("\n");
382     }
383
384   /* The next "info history +" should start after what we just printed.  */
385   num += 10;
386
387   /* Hitting just return after this command should do the same thing as
388      "info history +".  If num_exp is null, this is unnecessary, since
389      "info history +" is not useful after "info history".  */
390   if (from_tty && num_exp)
391     {
392       num_exp[0] = '+';
393       num_exp[1] = '\0';
394     }
395 }
396 \f
397 /* Internal variables.  These are variables within the debugger
398    that hold values assigned by debugger commands.
399    The user refers to them with a '$' prefix
400    that does not appear in the variable names stored internally.  */
401
402 static struct internalvar *internalvars;
403
404 /* Look up an internal variable with name NAME.  NAME should not
405    normally include a dollar sign.
406
407    If the specified internal variable does not exist,
408    one is created, with a void value.  */
409
410 struct internalvar *
411 lookup_internalvar (name)
412      char *name;
413 {
414   register struct internalvar *var;
415
416   for (var = internalvars; var; var = var->next)
417     if (STREQ (var->name, name))
418       return var;
419
420   var = (struct internalvar *) xmalloc (sizeof (struct internalvar));
421   var->name = concat (name, NULL);
422   var->value = allocate_value (builtin_type_void);
423   release_value (var->value);
424   var->next = internalvars;
425   internalvars = var;
426   return var;
427 }
428
429 value_ptr
430 value_of_internalvar (var)
431      struct internalvar *var;
432 {
433   register value_ptr val;
434
435 #ifdef IS_TRAPPED_INTERNALVAR
436   if (IS_TRAPPED_INTERNALVAR (var->name))
437     return VALUE_OF_TRAPPED_INTERNALVAR (var);
438 #endif 
439
440   val = value_copy (var->value);
441   if (VALUE_LAZY (val))
442     value_fetch_lazy (val);
443   VALUE_LVAL (val) = lval_internalvar;
444   VALUE_INTERNALVAR (val) = var;
445   return val;
446 }
447
448 void
449 set_internalvar_component (var, offset, bitpos, bitsize, newval)
450      struct internalvar *var;
451      int offset, bitpos, bitsize;
452      value_ptr newval;
453 {
454   register char *addr = VALUE_CONTENTS (var->value) + offset;
455
456 #ifdef IS_TRAPPED_INTERNALVAR
457   if (IS_TRAPPED_INTERNALVAR (var->name))
458     SET_TRAPPED_INTERNALVAR (var, newval, bitpos, bitsize, offset);
459 #endif
460
461   if (bitsize)
462     modify_field (addr, value_as_long (newval),
463                   bitpos, bitsize);
464   else
465     memcpy (addr, VALUE_CONTENTS (newval), TYPE_LENGTH (VALUE_TYPE (newval)));
466 }
467
468 void
469 set_internalvar (var, val)
470      struct internalvar *var;
471      value_ptr val;
472 {
473   value_ptr newval;
474
475 #ifdef IS_TRAPPED_INTERNALVAR
476   if (IS_TRAPPED_INTERNALVAR (var->name))
477     SET_TRAPPED_INTERNALVAR (var, val, 0, 0, 0);
478 #endif
479
480   newval = value_copy (val);
481   newval->modifiable = 1;
482
483   /* Force the value to be fetched from the target now, to avoid problems
484      later when this internalvar is referenced and the target is gone or
485      has changed.  */
486   if (VALUE_LAZY (newval))
487     value_fetch_lazy (newval);
488
489   /* Begin code which must not call error().  If var->value points to
490      something free'd, an error() obviously leaves a dangling pointer.
491      But we also get a danling pointer if var->value points to
492      something in the value chain (i.e., before release_value is
493      called), because after the error free_all_values will get called before
494      long.  */
495   free ((PTR)var->value);
496   var->value = newval;
497   release_value (newval);
498   /* End code which must not call error().  */
499 }
500
501 char *
502 internalvar_name (var)
503      struct internalvar *var;
504 {
505   return var->name;
506 }
507
508 /* Free all internalvars.  Done when new symtabs are loaded,
509    because that makes the values invalid.  */
510
511 void
512 clear_internalvars ()
513 {
514   register struct internalvar *var;
515
516   while (internalvars)
517     {
518       var = internalvars;
519       internalvars = var->next;
520       free ((PTR)var->name);
521       free ((PTR)var->value);
522       free ((PTR)var);
523     }
524 }
525
526 static void
527 show_convenience (ignore, from_tty)
528      char *ignore;
529      int from_tty;
530 {
531   register struct internalvar *var;
532   int varseen = 0;
533
534   for (var = internalvars; var; var = var->next)
535     {
536 #ifdef IS_TRAPPED_INTERNALVAR
537       if (IS_TRAPPED_INTERNALVAR (var->name))
538         continue;
539 #endif
540       if (!varseen)
541         {
542           varseen = 1;
543         }
544       printf_filtered ("$%s = ", var->name);
545       value_print (var->value, gdb_stdout, 0, Val_pretty_default);
546       printf_filtered ("\n");
547     }
548   if (!varseen)
549     printf_unfiltered ("No debugger convenience variables now defined.\n\
550 Convenience variables have names starting with \"$\";\n\
551 use \"set\" as in \"set $foo = 5\" to define them.\n");
552 }
553 \f
554 /* Extract a value as a C number (either long or double).
555    Knows how to convert fixed values to double, or
556    floating values to long.
557    Does not deallocate the value.  */
558
559 LONGEST
560 value_as_long (val)
561      register value_ptr val;
562 {
563   /* This coerces arrays and functions, which is necessary (e.g.
564      in disassemble_command).  It also dereferences references, which
565      I suspect is the most logical thing to do.  */
566   COERCE_ARRAY (val);
567   return unpack_long (VALUE_TYPE (val), VALUE_CONTENTS (val));
568 }
569
570 DOUBLEST
571 value_as_double (val)
572      register value_ptr val;
573 {
574   DOUBLEST foo;
575   int inv;
576   
577   foo = unpack_double (VALUE_TYPE (val), VALUE_CONTENTS (val), &inv);
578   if (inv)
579     error ("Invalid floating value found in program.");
580   return foo;
581 }
582 /* Extract a value as a C pointer.
583    Does not deallocate the value.  */
584 CORE_ADDR
585 value_as_pointer (val)
586      value_ptr val;
587 {
588   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
589      whether we want this to be true eventually.  */
590 #if 0
591   /* ADDR_BITS_REMOVE is wrong if we are being called for a
592      non-address (e.g. argument to "signal", "info break", etc.), or
593      for pointers to char, in which the low bits *are* significant.  */
594   return ADDR_BITS_REMOVE(value_as_long (val));
595 #else
596   return value_as_long (val);
597 #endif
598 }
599 \f
600 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
601    as a long, or as a double, assuming the raw data is described
602    by type TYPE.  Knows how to convert different sizes of values
603    and can convert between fixed and floating point.  We don't assume
604    any alignment for the raw data.  Return value is in host byte order.
605
606    If you want functions and arrays to be coerced to pointers, and
607    references to be dereferenced, call value_as_long() instead.
608
609    C++: It is assumed that the front-end has taken care of
610    all matters concerning pointers to members.  A pointer
611    to member which reaches here is considered to be equivalent
612    to an INT (or some size).  After all, it is only an offset.  */
613
614 LONGEST
615 unpack_long (type, valaddr)
616      struct type *type;
617      char *valaddr;
618 {
619   register enum type_code code = TYPE_CODE (type);
620   register int len = TYPE_LENGTH (type);
621   register int nosign = TYPE_UNSIGNED (type);
622
623   if (current_language->la_language == language_scm
624       && is_scmvalue_type (type))
625     return scm_unpack (type, valaddr, TYPE_CODE_INT);
626
627   switch (code)
628     {
629     case TYPE_CODE_TYPEDEF:
630       return unpack_long (check_typedef (type), valaddr);
631     case TYPE_CODE_ENUM:
632     case TYPE_CODE_BOOL:
633     case TYPE_CODE_INT:
634     case TYPE_CODE_CHAR:
635     case TYPE_CODE_RANGE:
636       if (nosign)
637         return extract_unsigned_integer (valaddr, len);
638       else
639         return extract_signed_integer (valaddr, len);
640
641     case TYPE_CODE_FLT:
642       return extract_floating (valaddr, len);
643
644     case TYPE_CODE_PTR:
645     case TYPE_CODE_REF:
646       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
647          whether we want this to be true eventually.  */
648 #ifdef GDB_TARGET_IS_D10V
649       if (len == 2)
650           return D10V_MAKE_DADDR(extract_address (valaddr, len));
651 #endif
652       return extract_address (valaddr, len);
653
654     case TYPE_CODE_MEMBER:
655       error ("not implemented: member types in unpack_long");
656
657     default:
658       error ("Value can't be converted to integer.");
659     }
660   return 0; /* Placate lint.  */
661 }
662
663 /* Return a double value from the specified type and address.
664    INVP points to an int which is set to 0 for valid value,
665    1 for invalid value (bad float format).  In either case,
666    the returned double is OK to use.  Argument is in target
667    format, result is in host format.  */
668
669 DOUBLEST
670 unpack_double (type, valaddr, invp)
671      struct type *type;
672      char *valaddr;
673      int *invp;
674 {
675   enum type_code code;
676   int len;
677   int nosign;
678
679   *invp = 0;                    /* Assume valid.   */
680   CHECK_TYPEDEF (type);
681   code = TYPE_CODE (type);
682   len = TYPE_LENGTH (type);
683   nosign = TYPE_UNSIGNED (type);
684   if (code == TYPE_CODE_FLT)
685     {
686 #ifdef INVALID_FLOAT
687       if (INVALID_FLOAT (valaddr, len))
688         {
689           *invp = 1;
690           return 1.234567891011121314;
691         }
692 #endif
693       return extract_floating (valaddr, len);
694     }
695   else if (nosign)
696     {
697       /* Unsigned -- be sure we compensate for signed LONGEST.  */
698 #if !defined (_MSC_VER) || (_MSC_VER > 900)
699       return (ULONGEST) unpack_long (type, valaddr);
700 #else
701       /* FIXME!!! msvc22 doesn't support unsigned __int64 -> double */
702       return (LONGEST) unpack_long (type, valaddr);
703 #endif /* _MSC_VER */
704     }
705   else
706     {
707       /* Signed -- we are OK with unpack_long.  */
708       return unpack_long (type, valaddr);
709     }
710 }
711
712 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
713    as a CORE_ADDR, assuming the raw data is described by type TYPE.
714    We don't assume any alignment for the raw data.  Return value is in
715    host byte order.
716
717    If you want functions and arrays to be coerced to pointers, and
718    references to be dereferenced, call value_as_pointer() instead.
719
720    C++: It is assumed that the front-end has taken care of
721    all matters concerning pointers to members.  A pointer
722    to member which reaches here is considered to be equivalent
723    to an INT (or some size).  After all, it is only an offset.  */
724
725 CORE_ADDR
726 unpack_pointer (type, valaddr)
727      struct type *type;
728      char *valaddr;
729 {
730   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
731      whether we want this to be true eventually.  */
732   return unpack_long (type, valaddr);
733 }
734 \f
735 /* Get the value of the FIELDN'th field (which must be static) of TYPE. */
736
737 value_ptr
738 value_static_field (type, fieldno)
739      struct type *type;
740      int fieldno;
741 {
742   CORE_ADDR addr;
743   asection *sect;
744   if (TYPE_FIELD_STATIC_HAS_ADDR (type, fieldno))
745     {
746       addr = TYPE_FIELD_STATIC_PHYSADDR (type, fieldno);
747       sect = NULL;
748     }
749   else
750     {
751       char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
752       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_NAMESPACE, 0, NULL);
753       if (sym == NULL)
754         {
755           /* With some compilers, e.g. HP aCC, static data members are reported
756              as non-debuggable symbols */ 
757           struct minimal_symbol * msym = lookup_minimal_symbol (phys_name, NULL, NULL);
758           if (!msym)
759             return NULL;
760           else
761             {     
762               addr = SYMBOL_VALUE_ADDRESS (msym);
763               sect = SYMBOL_BFD_SECTION (msym);
764             }
765         }
766       else
767         {
768           addr = SYMBOL_VALUE_ADDRESS (sym);
769           sect = SYMBOL_BFD_SECTION (sym);
770         }
771       SET_FIELD_PHYSADDR (TYPE_FIELD (type, fieldno), addr);
772     }
773   return value_at (TYPE_FIELD_TYPE (type, fieldno), addr, sect);
774 }
775
776 /* Given a value ARG1 (offset by OFFSET bytes)
777    of a struct or union type ARG_TYPE,
778    extract and return the value of one of its (non-static) fields.
779    FIELDNO says which field. */
780
781 value_ptr
782 value_primitive_field (arg1, offset, fieldno, arg_type)
783      register value_ptr arg1;
784      int offset;
785      register int fieldno;
786      register struct type *arg_type;
787 {
788   register value_ptr v;
789   register struct type *type;
790
791   CHECK_TYPEDEF (arg_type);
792   type = TYPE_FIELD_TYPE (arg_type, fieldno);
793
794   /* Handle packed fields */
795
796   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
797     {
798       v = value_from_longest (type,
799                               unpack_field_as_long (arg_type,
800                                                     VALUE_CONTENTS (arg1)
801                                                       + offset,
802                                                     fieldno));
803       VALUE_BITPOS (v) = TYPE_FIELD_BITPOS (arg_type, fieldno) % 8;
804       VALUE_BITSIZE (v) = TYPE_FIELD_BITSIZE (arg_type, fieldno);
805     }
806   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
807     {
808       /* This field is actually a base subobject, so preserve the
809          entire object's contents for later references to virtual
810          bases, etc.  */
811       v = allocate_value (VALUE_ENCLOSING_TYPE (arg1));
812       VALUE_TYPE (v) = arg_type;
813       if (VALUE_LAZY (arg1))
814         VALUE_LAZY (v) = 1;
815       else
816         memcpy (VALUE_CONTENTS_ALL_RAW (v), VALUE_CONTENTS_ALL_RAW (arg1),
817                 TYPE_LENGTH (VALUE_ENCLOSING_TYPE (arg1)));
818       VALUE_OFFSET (v) = VALUE_OFFSET (arg1);
819       VALUE_EMBEDDED_OFFSET (v)
820         = offset + 
821           VALUE_EMBEDDED_OFFSET (arg1) + 
822           TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
823     }
824   else
825     {
826       /* Plain old data member */
827       offset += TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
828       v = allocate_value (type);
829       if (VALUE_LAZY (arg1))
830         VALUE_LAZY (v) = 1;
831       else
832         memcpy (VALUE_CONTENTS_RAW (v),
833                 VALUE_CONTENTS_RAW (arg1) + offset,
834                 TYPE_LENGTH (type));
835       VALUE_OFFSET (v) = VALUE_OFFSET (arg1) + offset;
836     }
837   VALUE_LVAL (v) = VALUE_LVAL (arg1);
838   if (VALUE_LVAL (arg1) == lval_internalvar)
839     VALUE_LVAL (v) = lval_internalvar_component;
840   VALUE_ADDRESS (v) = VALUE_ADDRESS (arg1);
841 /*  VALUE_OFFSET (v) = VALUE_OFFSET (arg1) + offset
842                      + TYPE_FIELD_BITPOS (arg_type, fieldno) / 8; */
843   return v;
844 }
845
846 /* Given a value ARG1 of a struct or union type,
847    extract and return the value of one of its (non-static) fields.
848    FIELDNO says which field. */
849
850 value_ptr
851 value_field (arg1, fieldno)
852      register value_ptr arg1;
853      register int fieldno;
854 {
855   return value_primitive_field (arg1, 0, fieldno, VALUE_TYPE (arg1));
856 }
857
858 /* Return a non-virtual function as a value.
859    F is the list of member functions which contains the desired method.
860    J is an index into F which provides the desired method. */
861
862 value_ptr
863 value_fn_field (arg1p, f, j, type, offset)
864      value_ptr *arg1p;
865      struct fn_field *f;
866      int j;
867      struct type *type;
868      int offset;
869 {
870   register value_ptr v;
871   register struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
872   struct symbol *sym;
873
874   sym = lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
875                        0, VAR_NAMESPACE, 0, NULL);
876   if (! sym) 
877         return NULL;
878 /*
879         error ("Internal error: could not find physical method named %s",
880                     TYPE_FN_FIELD_PHYSNAME (f, j));
881 */
882   
883   v = allocate_value (ftype);
884   VALUE_ADDRESS (v) = BLOCK_START (SYMBOL_BLOCK_VALUE (sym));
885   VALUE_TYPE (v) = ftype;
886
887   if (arg1p)
888    {
889     if (type != VALUE_TYPE (*arg1p))
890       *arg1p = value_ind (value_cast (lookup_pointer_type (type),
891                                       value_addr (*arg1p)));
892
893     /* Move the `this' pointer according to the offset. 
894     VALUE_OFFSET (*arg1p) += offset;
895     */
896     }
897
898   return v;
899 }
900
901 /* Return a virtual function as a value.
902    ARG1 is the object which provides the virtual function
903    table pointer.  *ARG1P is side-effected in calling this function.
904    F is the list of member functions which contains the desired virtual
905    function.
906    J is an index into F which provides the desired virtual function.
907
908    TYPE is the type in which F is located.  */
909 value_ptr
910 value_virtual_fn_field (arg1p, f, j, type, offset)
911      value_ptr *arg1p;
912      struct fn_field *f;
913      int j;
914      struct type *type;
915      int offset;
916 {
917   value_ptr arg1 = *arg1p;
918   struct type *type1 = check_typedef (VALUE_TYPE (arg1));
919
920   if (TYPE_HAS_VTABLE (type))
921     {
922       /* Deal with HP/Taligent runtime model for virtual functions */
923       value_ptr vp;
924       value_ptr argp;        /* arg1 cast to base */
925       CORE_ADDR vfunc_addr;  /* address of virtual method */
926       CORE_ADDR coreptr;     /* pointer to target address */ 
927       int class_index;       /* which class segment pointer to use */
928       struct type * ftype = TYPE_FN_FIELD_TYPE (f, j);   /* method type */
929
930       argp = value_cast (type, *arg1p);
931
932       if (VALUE_ADDRESS (argp) == 0)
933         error ("Address of object is null; object may not have been created.");
934       
935       /* pai: FIXME -- 32x64 possible problem? */
936       /* First word (4 bytes) in object layout is the vtable pointer */
937       coreptr = * (CORE_ADDR *) (VALUE_CONTENTS (argp)); /* pai: (temp)  */
938                                  /* + offset + VALUE_EMBEDDED_OFFSET (argp)); */ 
939
940       if (!coreptr)
941         error ("Virtual table pointer is null for object; object may not have been created.");
942       
943       /* pai/1997-05-09
944        * FIXME: The code here currently handles only
945        * the non-RRBC case of the Taligent/HP runtime spec; when RRBC
946        * is introduced, the condition for the "if" below will have to
947        * be changed to be a test for the RRBC case.  */
948        
949       if (1)
950         {
951           /* Non-RRBC case; the virtual function pointers are stored at fixed
952            * offsets in the virtual table. */
953
954           /* Retrieve the offset in the virtual table from the debug
955            * info.  The offset of the vfunc's entry is in words from
956            * the beginning of the vtable; but first we have to adjust
957            * by HP_ACC_VFUNC_START to account for other entries */
958           
959           /* pai: FIXME: 32x64 problem here, a word may be 8 bytes in
960            * which case the multiplier should be 8 and values should be long */
961           vp = value_at (builtin_type_int,
962                          coreptr + 4 * (TYPE_FN_FIELD_VOFFSET (f, j) + HP_ACC_VFUNC_START), NULL);
963           
964           coreptr = * (CORE_ADDR *) (VALUE_CONTENTS (vp));
965           /* coreptr now contains the address of the virtual function */
966           /* (Actually, it contains the pointer to the plabel for the function. */
967         }
968       else
969         {
970           /* RRBC case; the virtual function pointers are found by double
971            * indirection through the class segment tables. */
972           
973           /* Choose class segment depending on type we were passed */ 
974           class_index = class_index_in_primary_list (type);
975       
976           /* Find class segment pointer.  These are in the vtable slots after
977            * some other entries, so adjust by HP_ACC_VFUNC_START for that. */
978           /* pai: FIXME 32x64 problem here, if words are 8 bytes long
979            * the multiplier below has to be 8 and value should be long. */
980           vp = value_at (builtin_type_int,
981                          coreptr + 4 * (HP_ACC_VFUNC_START + class_index), NULL);
982           /* Indirect once more, offset by function index */
983           /* pai: FIXME 32x64 problem here, again multiplier could be 8 and value long */
984           coreptr = * (CORE_ADDR *) (VALUE_CONTENTS (vp) + 4 * TYPE_FN_FIELD_VOFFSET (f, j));
985           vp = value_at (builtin_type_int, coreptr, NULL);
986           coreptr = * (CORE_ADDR *) (VALUE_CONTENTS (vp));
987           
988           /* coreptr now contains the address of the virtual function */
989           /* (Actually, it contains the pointer to the plabel for the function.) */
990           
991         }
992
993       if (!coreptr)
994         error ("Address of virtual function is null; error in virtual table?");
995
996       /* Wrap this addr in a value and return pointer */ 
997       vp = allocate_value (ftype);
998       VALUE_TYPE (vp) = ftype;
999       VALUE_ADDRESS (vp) = coreptr;
1000       
1001       /* pai: (temp) do we need the value_ind stuff in value_fn_field? */
1002       return vp;
1003     }
1004   else  
1005     { /* Not using HP/Taligent runtime conventions; so try to
1006        * use g++ conventions for virtual table */
1007       
1008       struct type *entry_type;
1009       /* First, get the virtual function table pointer.  That comes
1010          with a strange type, so cast it to type `pointer to long' (which
1011          should serve just fine as a function type).  Then, index into
1012          the table, and convert final value to appropriate function type.  */
1013       value_ptr entry, vfn, vtbl;
1014       value_ptr vi = value_from_longest (builtin_type_int, 
1015                                          (LONGEST) TYPE_FN_FIELD_VOFFSET (f, j));
1016       struct type *fcontext = TYPE_FN_FIELD_FCONTEXT (f, j);
1017       struct type *context;
1018       if (fcontext == NULL)
1019        /* We don't have an fcontext (e.g. the program was compiled with
1020           g++ version 1).  Try to get the vtbl from the TYPE_VPTR_BASETYPE.
1021           This won't work right for multiple inheritance, but at least we
1022           should do as well as GDB 3.x did.  */
1023         fcontext = TYPE_VPTR_BASETYPE (type);
1024       context = lookup_pointer_type (fcontext);
1025       /* Now context is a pointer to the basetype containing the vtbl.  */
1026       if (TYPE_TARGET_TYPE (context) != type1)
1027         {
1028           value_ptr tmp = value_cast (context, value_addr (arg1));
1029           VALUE_POINTED_TO_OFFSET (tmp) = 0;
1030           arg1 = value_ind (tmp);
1031           type1 = check_typedef (VALUE_TYPE (arg1));
1032         }
1033
1034       context = type1;
1035       /* Now context is the basetype containing the vtbl.  */
1036
1037       /* This type may have been defined before its virtual function table
1038          was.  If so, fill in the virtual function table entry for the
1039          type now.  */
1040       if (TYPE_VPTR_FIELDNO (context) < 0)
1041         fill_in_vptr_fieldno (context);
1042
1043       /* The virtual function table is now an array of structures
1044          which have the form { int16 offset, delta; void *pfn; }.  */
1045       vtbl = value_primitive_field (arg1, 0, TYPE_VPTR_FIELDNO (context),
1046                                     TYPE_VPTR_BASETYPE (context));
1047       
1048       /* With older versions of g++, the vtbl field pointed to an array
1049          of structures.  Nowadays it points directly to the structure. */
1050       if (TYPE_CODE (VALUE_TYPE (vtbl)) == TYPE_CODE_PTR
1051           && TYPE_CODE (TYPE_TARGET_TYPE (VALUE_TYPE (vtbl))) == TYPE_CODE_ARRAY)
1052         {
1053           /* Handle the case where the vtbl field points to an
1054              array of structures. */
1055           vtbl = value_ind (vtbl);
1056
1057           /* Index into the virtual function table.  This is hard-coded because
1058              looking up a field is not cheap, and it may be important to save
1059              time, e.g. if the user has set a conditional breakpoint calling
1060              a virtual function.  */
1061           entry = value_subscript (vtbl, vi);
1062         }
1063       else
1064         {
1065           /* Handle the case where the vtbl field points directly to a structure. */
1066           vtbl = value_add (vtbl, vi);
1067           entry = value_ind (vtbl);
1068         }
1069
1070       entry_type = check_typedef (VALUE_TYPE (entry));
1071
1072       if (TYPE_CODE (entry_type) == TYPE_CODE_STRUCT)
1073         {
1074           /* Move the `this' pointer according to the virtual function table. */
1075           VALUE_OFFSET (arg1) += value_as_long (value_field (entry, 0));
1076
1077           if (! VALUE_LAZY (arg1))
1078             {
1079               VALUE_LAZY (arg1) = 1;
1080               value_fetch_lazy (arg1);
1081             }
1082
1083           vfn = value_field (entry, 2);
1084         }
1085       else if (TYPE_CODE (entry_type) == TYPE_CODE_PTR)
1086         vfn = entry;
1087       else
1088         error ("I'm confused:  virtual function table has bad type");
1089       /* Reinstantiate the function pointer with the correct type.  */
1090       VALUE_TYPE (vfn) = lookup_pointer_type (TYPE_FN_FIELD_TYPE (f, j));
1091
1092       *arg1p = arg1;
1093       return vfn;
1094     }
1095 }
1096
1097 /* ARG is a pointer to an object we know to be at least
1098    a DTYPE.  BTYPE is the most derived basetype that has
1099    already been searched (and need not be searched again).
1100    After looking at the vtables between BTYPE and DTYPE,
1101    return the most derived type we find.  The caller must
1102    be satisfied when the return value == DTYPE.
1103
1104    FIXME-tiemann: should work with dossier entries as well.  */
1105
1106 static value_ptr
1107 value_headof (in_arg, btype, dtype)
1108      value_ptr in_arg;
1109      struct type *btype, *dtype;
1110 {
1111   /* First collect the vtables we must look at for this object.  */
1112   /* FIXME-tiemann: right now, just look at top-most vtable.  */
1113   value_ptr arg, vtbl, entry, best_entry = 0;
1114   int i, nelems;
1115   int offset, best_offset = 0;
1116   struct symbol *sym;
1117   CORE_ADDR pc_for_sym;
1118   char *demangled_name;
1119   struct minimal_symbol *msymbol;
1120
1121   btype = TYPE_VPTR_BASETYPE (dtype);
1122   CHECK_TYPEDEF (btype);
1123   arg = in_arg;
1124   if (btype != dtype)
1125     arg = value_cast (lookup_pointer_type (btype), arg);
1126   vtbl = value_ind (value_field (value_ind (arg), TYPE_VPTR_FIELDNO (btype)));
1127
1128   /* Check that VTBL looks like it points to a virtual function table.  */
1129   msymbol = lookup_minimal_symbol_by_pc (VALUE_ADDRESS (vtbl));
1130   if (msymbol == NULL
1131       || (demangled_name = SYMBOL_NAME (msymbol)) == NULL
1132       || !VTBL_PREFIX_P (demangled_name))
1133     {
1134       /* If we expected to find a vtable, but did not, let the user
1135          know that we aren't happy, but don't throw an error.
1136          FIXME: there has to be a better way to do this.  */
1137       struct type *error_type = (struct type *)xmalloc (sizeof (struct type));
1138       memcpy (error_type, VALUE_TYPE (in_arg), sizeof (struct type));
1139       TYPE_NAME (error_type) = savestring ("suspicious *", sizeof ("suspicious *"));
1140       VALUE_TYPE (in_arg) = error_type;
1141       return in_arg;
1142     }
1143
1144   /* Now search through the virtual function table.  */
1145   entry = value_ind (vtbl);
1146   nelems = longest_to_int (value_as_long (value_field (entry, 2)));
1147   for (i = 1; i <= nelems; i++)
1148     {
1149       entry = value_subscript (vtbl, value_from_longest (builtin_type_int, 
1150                                                       (LONGEST) i));
1151       /* This won't work if we're using thunks. */
1152       if (TYPE_CODE (check_typedef (VALUE_TYPE (entry))) != TYPE_CODE_STRUCT)
1153         break;
1154       offset = longest_to_int (value_as_long (value_field (entry, 0)));
1155       /* If we use '<=' we can handle single inheritance
1156        * where all offsets are zero - just use the first entry found. */
1157       if (offset <= best_offset)
1158         {
1159           best_offset = offset;
1160           best_entry = entry;
1161         }
1162     }
1163   /* Move the pointer according to BEST_ENTRY's offset, and figure
1164      out what type we should return as the new pointer.  */
1165   if (best_entry == 0)
1166     {
1167       /* An alternative method (which should no longer be necessary).
1168        * But we leave it in for future use, when we will hopefully
1169        * have optimizes the vtable to use thunks instead of offsets. */
1170       /* Use the name of vtable itself to extract a base type. */
1171       demangled_name += 4;  /* Skip _vt$ prefix. */
1172     }
1173   else
1174     {
1175       pc_for_sym = value_as_pointer (value_field (best_entry, 2));
1176       sym = find_pc_function (pc_for_sym);
1177       demangled_name = cplus_demangle (SYMBOL_NAME (sym), DMGL_ANSI);
1178       *(strchr (demangled_name, ':')) = '\0';
1179     }
1180   sym = lookup_symbol (demangled_name, 0, VAR_NAMESPACE, 0, 0);
1181   if (sym == NULL)
1182     error ("could not find type declaration for `%s'", demangled_name);
1183   if (best_entry)
1184     {
1185       free (demangled_name);
1186       arg = value_add (value_cast (builtin_type_int, arg),
1187                        value_field (best_entry, 0));
1188     }
1189   else arg = in_arg;
1190   VALUE_TYPE (arg) = lookup_pointer_type (SYMBOL_TYPE (sym));
1191   return arg;
1192 }
1193
1194 /* ARG is a pointer object of type TYPE.  If TYPE has virtual
1195    function tables, probe ARG's tables (including the vtables
1196    of its baseclasses) to figure out the most derived type that ARG
1197    could actually be a pointer to.  */
1198
1199 value_ptr
1200 value_from_vtable_info (arg, type)
1201      value_ptr arg;
1202      struct type *type;
1203 {
1204   /* Take care of preliminaries.  */
1205   if (TYPE_VPTR_FIELDNO (type) < 0)
1206     fill_in_vptr_fieldno (type);
1207   if (TYPE_VPTR_FIELDNO (type) < 0)
1208     return 0;
1209
1210   return value_headof (arg, 0, type);
1211 }
1212
1213 /* Return true if the INDEXth field of TYPE is a virtual baseclass
1214    pointer which is for the base class whose type is BASECLASS.  */
1215
1216 static int
1217 vb_match (type, index, basetype)
1218      struct type *type;
1219      int index;
1220      struct type *basetype;
1221 {
1222   struct type *fieldtype;
1223   char *name = TYPE_FIELD_NAME (type, index);
1224   char *field_class_name = NULL;
1225
1226   if (*name != '_')
1227     return 0;
1228   /* gcc 2.4 uses _vb$.  */
1229   if (name[1] == 'v' && name[2] == 'b' && is_cplus_marker (name[3]))
1230     field_class_name = name + 4;
1231   /* gcc 2.5 will use __vb_.  */
1232   if (name[1] == '_' && name[2] == 'v' && name[3] == 'b' && name[4] == '_')
1233     field_class_name = name + 5;
1234
1235   if (field_class_name == NULL)
1236     /* This field is not a virtual base class pointer.  */
1237     return 0;
1238
1239   /* It's a virtual baseclass pointer, now we just need to find out whether
1240      it is for this baseclass.  */
1241   fieldtype = TYPE_FIELD_TYPE (type, index);
1242   if (fieldtype == NULL
1243       || TYPE_CODE (fieldtype) != TYPE_CODE_PTR)
1244     /* "Can't happen".  */
1245     return 0;
1246
1247   /* What we check for is that either the types are equal (needed for
1248      nameless types) or have the same name.  This is ugly, and a more
1249      elegant solution should be devised (which would probably just push
1250      the ugliness into symbol reading unless we change the stabs format).  */
1251   if (TYPE_TARGET_TYPE (fieldtype) == basetype)
1252     return 1;
1253
1254   if (TYPE_NAME (basetype) != NULL
1255       && TYPE_NAME (TYPE_TARGET_TYPE (fieldtype)) != NULL
1256       && STREQ (TYPE_NAME (basetype),
1257                 TYPE_NAME (TYPE_TARGET_TYPE (fieldtype))))
1258     return 1;
1259   return 0;
1260 }
1261
1262 /* Compute the offset of the baseclass which is
1263    the INDEXth baseclass of class TYPE,
1264    for value at VALADDR (in host) at ADDRESS (in target).
1265    The result is the offset of the baseclass value relative
1266    to (the address of)(ARG) + OFFSET.
1267
1268    -1 is returned on error. */
1269
1270 int
1271 baseclass_offset (type, index, valaddr, address)
1272      struct type *type;
1273      int index;
1274      char *valaddr;
1275      CORE_ADDR address;
1276 {
1277   struct type *basetype = TYPE_BASECLASS (type, index);
1278
1279   if (BASETYPE_VIA_VIRTUAL (type, index))
1280     {
1281       /* Must hunt for the pointer to this virtual baseclass.  */
1282       register int i, len = TYPE_NFIELDS (type);
1283       register int n_baseclasses = TYPE_N_BASECLASSES (type);
1284
1285       /* First look for the virtual baseclass pointer
1286          in the fields.  */
1287       for (i = n_baseclasses; i < len; i++)
1288         {
1289           if (vb_match (type, i, basetype))
1290             {
1291               CORE_ADDR addr
1292                 = unpack_pointer (TYPE_FIELD_TYPE (type, i),
1293                                   valaddr + (TYPE_FIELD_BITPOS (type, i) / 8));
1294
1295               return addr - (LONGEST) address;
1296             }
1297         }
1298       /* Not in the fields, so try looking through the baseclasses.  */
1299       for (i = index+1; i < n_baseclasses; i++)
1300         {
1301           int boffset =
1302               baseclass_offset (type, i, valaddr, address);
1303           if (boffset)
1304             return boffset;
1305         }
1306       /* Not found.  */
1307       return -1;
1308     }
1309
1310   /* Baseclass is easily computed.  */
1311   return TYPE_BASECLASS_BITPOS (type, index) / 8;
1312 }
1313 \f
1314 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous object at
1315    VALADDR.
1316
1317    Extracting bits depends on endianness of the machine.  Compute the
1318    number of least significant bits to discard.  For big endian machines,
1319    we compute the total number of bits in the anonymous object, subtract
1320    off the bit count from the MSB of the object to the MSB of the
1321    bitfield, then the size of the bitfield, which leaves the LSB discard
1322    count.  For little endian machines, the discard count is simply the
1323    number of bits from the LSB of the anonymous object to the LSB of the
1324    bitfield.
1325
1326    If the field is signed, we also do sign extension. */
1327
1328 LONGEST
1329 unpack_field_as_long (type, valaddr, fieldno)
1330      struct type *type;
1331      char *valaddr;
1332      int fieldno;
1333 {
1334   ULONGEST val;
1335   ULONGEST valmask;
1336   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
1337   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
1338   int lsbcount;
1339   struct type *field_type;
1340
1341   val = extract_unsigned_integer (valaddr + bitpos / 8, sizeof (val));
1342   field_type = TYPE_FIELD_TYPE (type, fieldno);
1343   CHECK_TYPEDEF (field_type);
1344
1345   /* Extract bits.  See comment above. */
1346
1347   if (BITS_BIG_ENDIAN)
1348     lsbcount = (sizeof val * 8 - bitpos % 8 - bitsize);
1349   else
1350     lsbcount = (bitpos % 8);
1351   val >>= lsbcount;
1352
1353   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
1354      If the field is signed, and is negative, then sign extend. */
1355
1356   if ((bitsize > 0) && (bitsize < 8 * (int) sizeof (val)))
1357     {
1358       valmask = (((ULONGEST) 1) << bitsize) - 1;
1359       val &= valmask;
1360       if (!TYPE_UNSIGNED (field_type))
1361         {
1362           if (val & (valmask ^ (valmask >> 1)))
1363             {
1364               val |= ~valmask;
1365             }
1366         }
1367     }
1368   return (val);
1369 }
1370
1371 /* Modify the value of a bitfield.  ADDR points to a block of memory in
1372    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
1373    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
1374    indicate which bits (in target bit order) comprise the bitfield.  */
1375
1376 void
1377 modify_field (addr, fieldval, bitpos, bitsize)
1378      char *addr;
1379      LONGEST fieldval;
1380      int bitpos, bitsize;
1381 {
1382   LONGEST oword;
1383
1384   /* If a negative fieldval fits in the field in question, chop
1385      off the sign extension bits.  */
1386   if (bitsize < (8 * (int) sizeof (fieldval))
1387       && (~fieldval & ~((1 << (bitsize - 1)) - 1)) == 0)
1388     fieldval = fieldval & ((1 << bitsize) - 1);
1389
1390   /* Warn if value is too big to fit in the field in question.  */
1391   if (bitsize < (8 * (int) sizeof (fieldval))
1392       && 0 != (fieldval & ~((1<<bitsize)-1)))
1393     {
1394       /* FIXME: would like to include fieldval in the message, but
1395          we don't have a sprintf_longest.  */
1396       warning ("Value does not fit in %d bits.", bitsize);
1397
1398       /* Truncate it, otherwise adjoining fields may be corrupted.  */
1399       fieldval = fieldval & ((1 << bitsize) - 1);
1400     }
1401
1402   oword = extract_signed_integer (addr, sizeof oword);
1403
1404   /* Shifting for bit field depends on endianness of the target machine.  */
1405   if (BITS_BIG_ENDIAN)
1406     bitpos = sizeof (oword) * 8 - bitpos - bitsize;
1407
1408   /* Mask out old value, while avoiding shifts >= size of oword */
1409   if (bitsize < 8 * (int) sizeof (oword))
1410     oword &= ~(((((ULONGEST)1) << bitsize) - 1) << bitpos);
1411   else
1412     oword &= ~((~(ULONGEST)0) << bitpos);
1413   oword |= fieldval << bitpos;
1414
1415   store_signed_integer (addr, sizeof oword, oword);
1416 }
1417 \f
1418 /* Convert C numbers into newly allocated values */
1419
1420 value_ptr
1421 value_from_longest (type, num)
1422      struct type *type;
1423      register LONGEST num;
1424 {
1425   register value_ptr val = allocate_value (type);
1426   register enum type_code code;
1427   register int len;
1428  retry:
1429   code = TYPE_CODE (type);
1430   len = TYPE_LENGTH (type);
1431
1432   switch (code)
1433     {
1434     case TYPE_CODE_TYPEDEF:
1435       type = check_typedef (type);
1436       goto retry;
1437     case TYPE_CODE_INT:
1438     case TYPE_CODE_CHAR:
1439     case TYPE_CODE_ENUM:
1440     case TYPE_CODE_BOOL:
1441     case TYPE_CODE_RANGE:
1442       store_signed_integer (VALUE_CONTENTS_RAW (val), len, num);
1443       break;
1444       
1445     case TYPE_CODE_REF:
1446     case TYPE_CODE_PTR:
1447       /* This assumes that all pointers of a given length
1448          have the same form.  */
1449       store_address (VALUE_CONTENTS_RAW (val), len, (CORE_ADDR) num);
1450       break;
1451       
1452     default:
1453       error ("Unexpected type (%d) encountered for integer constant.", code);
1454     }
1455   return val;
1456 }
1457
1458 value_ptr
1459 value_from_double (type, num)
1460      struct type *type;
1461      DOUBLEST num;
1462 {
1463   register value_ptr val = allocate_value (type);
1464   struct type *base_type = check_typedef (type);
1465   register enum type_code code = TYPE_CODE (base_type);
1466   register int len = TYPE_LENGTH (base_type);
1467
1468   if (code == TYPE_CODE_FLT)
1469     {
1470       store_floating (VALUE_CONTENTS_RAW (val), len, num);
1471     }
1472   else
1473     error ("Unexpected type encountered for floating constant.");
1474
1475   return val;
1476 }
1477 \f
1478 /* Deal with the value that is "about to be returned".  */
1479
1480 /* Return the value that a function returning now
1481    would be returning to its caller, assuming its type is VALTYPE.
1482    RETBUF is where we look for what ought to be the contents
1483    of the registers (in raw form).  This is because it is often
1484    desirable to restore old values to those registers
1485    after saving the contents of interest, and then call
1486    this function using the saved values.
1487    struct_return is non-zero when the function in question is
1488    using the structure return conventions on the machine in question;
1489    0 when it is using the value returning conventions (this often
1490    means returning pointer to where structure is vs. returning value). */
1491
1492 value_ptr
1493 value_being_returned (valtype, retbuf, struct_return)
1494      register struct type *valtype;
1495      char retbuf[REGISTER_BYTES];
1496      int struct_return;
1497      /*ARGSUSED*/
1498 {
1499   register value_ptr val;
1500   CORE_ADDR addr;
1501
1502 #if defined (EXTRACT_STRUCT_VALUE_ADDRESS)
1503   /* If this is not defined, just use EXTRACT_RETURN_VALUE instead.  */
1504   if (struct_return) {
1505     addr = EXTRACT_STRUCT_VALUE_ADDRESS (retbuf);
1506     if (!addr)
1507       error ("Function return value unknown");
1508     return value_at (valtype, addr, NULL);
1509   }
1510 #endif
1511
1512   val = allocate_value (valtype);
1513   CHECK_TYPEDEF (valtype);
1514   EXTRACT_RETURN_VALUE (valtype, retbuf, VALUE_CONTENTS_RAW (val));
1515
1516   return val;
1517 }
1518
1519 /* Should we use EXTRACT_STRUCT_VALUE_ADDRESS instead of
1520    EXTRACT_RETURN_VALUE?  GCC_P is true if compiled with gcc
1521    and TYPE is the type (which is known to be struct, union or array).
1522
1523    On most machines, the struct convention is used unless we are
1524    using gcc and the type is of a special size.  */
1525 /* As of about 31 Mar 93, GCC was changed to be compatible with the
1526    native compiler.  GCC 2.3.3 was the last release that did it the
1527    old way.  Since gcc2_compiled was not changed, we have no
1528    way to correctly win in all cases, so we just do the right thing
1529    for gcc1 and for gcc2 after this change.  Thus it loses for gcc
1530    2.0-2.3.3.  This is somewhat unfortunate, but changing gcc2_compiled
1531    would cause more chaos than dealing with some struct returns being
1532    handled wrong.  */
1533
1534 int
1535 generic_use_struct_convention (gcc_p, value_type)
1536      int gcc_p;
1537      struct type *value_type;
1538 {     
1539   return !((gcc_p == 1)
1540             && (TYPE_LENGTH (value_type) == 1
1541                 || TYPE_LENGTH (value_type) == 2
1542                 || TYPE_LENGTH (value_type) == 4
1543                 || TYPE_LENGTH (value_type) == 8));
1544 }
1545
1546 #ifndef USE_STRUCT_CONVENTION
1547 #define USE_STRUCT_CONVENTION(gcc_p,type) generic_use_struct_convention (gcc_p, type)
1548 #endif
1549
1550 /* Some fundamental types (such as long double) are returned on the stack for
1551    certain architectures.  This macro should return true for any type besides
1552    struct, union or array that gets returned on the stack.  */
1553
1554 #ifndef RETURN_VALUE_ON_STACK
1555 #define RETURN_VALUE_ON_STACK(TYPE) 0
1556 #endif
1557
1558 /* Return true if the function specified is using the structure returning
1559    convention on this machine to return arguments, or 0 if it is using
1560    the value returning convention.  FUNCTION is the value representing
1561    the function, FUNCADDR is the address of the function, and VALUE_TYPE
1562    is the type returned by the function.  GCC_P is nonzero if compiled
1563    with GCC.  */
1564
1565 int
1566 using_struct_return (function, funcaddr, value_type, gcc_p)
1567      value_ptr function;
1568      CORE_ADDR funcaddr;
1569      struct type *value_type;
1570      int gcc_p;
1571      /*ARGSUSED*/
1572 {
1573   register enum type_code code = TYPE_CODE (value_type);
1574
1575   if (code == TYPE_CODE_ERROR)
1576     error ("Function return type unknown.");
1577
1578   if (code == TYPE_CODE_STRUCT
1579       || code == TYPE_CODE_UNION
1580       || code == TYPE_CODE_ARRAY
1581       || RETURN_VALUE_ON_STACK (value_type))
1582     return USE_STRUCT_CONVENTION (gcc_p, value_type);
1583
1584   return 0;
1585 }
1586
1587 /* Store VAL so it will be returned if a function returns now.
1588    Does not verify that VAL's type matches what the current
1589    function wants to return.  */
1590
1591 void
1592 set_return_value (val)
1593      value_ptr val;
1594 {
1595   struct type *type = check_typedef (VALUE_TYPE (val));
1596   register enum type_code code = TYPE_CODE (type);
1597
1598   if (code == TYPE_CODE_ERROR)
1599     error ("Function return type unknown.");
1600
1601   if (   code == TYPE_CODE_STRUCT
1602       || code == TYPE_CODE_UNION)       /* FIXME, implement struct return.  */
1603     error ("GDB does not support specifying a struct or union return value.");
1604
1605   STORE_RETURN_VALUE (type, VALUE_CONTENTS (val));
1606 }
1607 \f
1608 void
1609 _initialize_values ()
1610 {
1611   add_cmd ("convenience", no_class, show_convenience,
1612             "Debugger convenience (\"$foo\") variables.\n\
1613 These variables are created when you assign them values;\n\
1614 thus, \"print $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\n\
1615 A few convenience variables are given values automatically:\n\
1616 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
1617 \"$__\" holds the contents of the last address examined with \"x\".",
1618            &showlist);
1619
1620   add_cmd ("values", no_class, show_values,
1621            "Elements of value history around item number IDX (or last ten).",
1622            &showlist);
1623 }