Change defn of LOCAL_LABEL_PREFIX to ""
[external/binutils.git] / gdb / valops.c
1 /* Perform non-arithmetic operations on values, for GDB.
2    Copyright 1986, 87, 89, 91, 92, 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,
20    Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "value.h"
26 #include "frame.h"
27 #include "inferior.h"
28 #include "gdbcore.h"
29 #include "target.h"
30 #include "demangle.h"
31 #include "language.h"
32 #include "gdbcmd.h"
33
34 #include <errno.h>
35 #include "gdb_string.h"
36
37 /* Flag indicating HP compilers were used; needed to correctly handle some
38    value operations with HP aCC code/runtime. */
39 extern int hp_som_som_object_present;
40
41 extern int overload_debug;
42 /* Local functions.  */
43
44 static int typecmp (int staticp, struct type *t1[], value_ptr t2[]);
45
46 static CORE_ADDR find_function_addr (value_ptr, struct type **);
47 static value_ptr value_arg_coerce (value_ptr, struct type *, int);
48
49
50 static CORE_ADDR value_push (CORE_ADDR, value_ptr);
51
52 static value_ptr search_struct_field (char *, value_ptr, int,
53                                       struct type *, int);
54
55 static value_ptr search_struct_method (char *, value_ptr *,
56                                        value_ptr *,
57                                        int, int *, struct type *);
58
59 static int check_field_in (struct type *, const char *);
60
61 static CORE_ADDR allocate_space_in_inferior (int);
62
63 static value_ptr cast_into_complex (struct type *, value_ptr);
64
65 static struct fn_field *find_method_list (value_ptr * argp, char *method,
66                                           int offset, int *static_memfuncp,
67                                           struct type *type, int *num_fns,
68                                           struct type **basetype,
69                                           int *boffset);
70
71 void _initialize_valops (void);
72
73 /* Flag for whether we want to abandon failed expression evals by default.  */
74
75 #if 0
76 static int auto_abandon = 0;
77 #endif
78
79 int overload_resolution = 0;
80
81 /* This boolean tells what gdb should do if a signal is received while in
82    a function called from gdb (call dummy).  If set, gdb unwinds the stack
83    and restore the context to what as it was before the call.
84    The default is to stop in the frame where the signal was received. */
85
86 int unwind_on_signal_p = 0;
87 \f
88
89
90 /* Find the address of function name NAME in the inferior.  */
91
92 value_ptr
93 find_function_in_inferior (char *name)
94 {
95   register struct symbol *sym;
96   sym = lookup_symbol (name, 0, VAR_NAMESPACE, 0, NULL);
97   if (sym != NULL)
98     {
99       if (SYMBOL_CLASS (sym) != LOC_BLOCK)
100         {
101           error ("\"%s\" exists in this program but is not a function.",
102                  name);
103         }
104       return value_of_variable (sym, NULL);
105     }
106   else
107     {
108       struct minimal_symbol *msymbol = lookup_minimal_symbol (name, NULL, NULL);
109       if (msymbol != NULL)
110         {
111           struct type *type;
112           CORE_ADDR maddr;
113           type = lookup_pointer_type (builtin_type_char);
114           type = lookup_function_type (type);
115           type = lookup_pointer_type (type);
116           maddr = SYMBOL_VALUE_ADDRESS (msymbol);
117           return value_from_pointer (type, maddr);
118         }
119       else
120         {
121           if (!target_has_execution)
122             error ("evaluation of this expression requires the target program to be active");
123           else
124             error ("evaluation of this expression requires the program to have a function \"%s\".", name);
125         }
126     }
127 }
128
129 /* Allocate NBYTES of space in the inferior using the inferior's malloc
130    and return a value that is a pointer to the allocated space. */
131
132 value_ptr
133 value_allocate_space_in_inferior (int len)
134 {
135   value_ptr blocklen;
136   register value_ptr val = find_function_in_inferior ("malloc");
137
138   blocklen = value_from_longest (builtin_type_int, (LONGEST) len);
139   val = call_function_by_hand (val, 1, &blocklen);
140   if (value_logical_not (val))
141     {
142       if (!target_has_execution)
143         error ("No memory available to program now: you need to start the target first");
144       else
145         error ("No memory available to program: call to malloc failed");
146     }
147   return val;
148 }
149
150 static CORE_ADDR
151 allocate_space_in_inferior (int len)
152 {
153   return value_as_long (value_allocate_space_in_inferior (len));
154 }
155
156 /* Cast value ARG2 to type TYPE and return as a value.
157    More general than a C cast: accepts any two types of the same length,
158    and if ARG2 is an lvalue it can be cast into anything at all.  */
159 /* In C++, casts may change pointer or object representations.  */
160
161 value_ptr
162 value_cast (struct type *type, register value_ptr arg2)
163 {
164   register enum type_code code1;
165   register enum type_code code2;
166   register int scalar;
167   struct type *type2;
168
169   int convert_to_boolean = 0;
170
171   if (VALUE_TYPE (arg2) == type)
172     return arg2;
173
174   CHECK_TYPEDEF (type);
175   code1 = TYPE_CODE (type);
176   COERCE_REF (arg2);
177   type2 = check_typedef (VALUE_TYPE (arg2));
178
179   /* A cast to an undetermined-length array_type, such as (TYPE [])OBJECT,
180      is treated like a cast to (TYPE [N])OBJECT,
181      where N is sizeof(OBJECT)/sizeof(TYPE). */
182   if (code1 == TYPE_CODE_ARRAY)
183     {
184       struct type *element_type = TYPE_TARGET_TYPE (type);
185       unsigned element_length = TYPE_LENGTH (check_typedef (element_type));
186       if (element_length > 0
187         && TYPE_ARRAY_UPPER_BOUND_TYPE (type) == BOUND_CANNOT_BE_DETERMINED)
188         {
189           struct type *range_type = TYPE_INDEX_TYPE (type);
190           int val_length = TYPE_LENGTH (type2);
191           LONGEST low_bound, high_bound, new_length;
192           if (get_discrete_bounds (range_type, &low_bound, &high_bound) < 0)
193             low_bound = 0, high_bound = 0;
194           new_length = val_length / element_length;
195           if (val_length % element_length != 0)
196             warning ("array element type size does not divide object size in cast");
197           /* FIXME-type-allocation: need a way to free this type when we are
198              done with it.  */
199           range_type = create_range_type ((struct type *) NULL,
200                                           TYPE_TARGET_TYPE (range_type),
201                                           low_bound,
202                                           new_length + low_bound - 1);
203           VALUE_TYPE (arg2) = create_array_type ((struct type *) NULL,
204                                                  element_type, range_type);
205           return arg2;
206         }
207     }
208
209   if (current_language->c_style_arrays
210       && TYPE_CODE (type2) == TYPE_CODE_ARRAY)
211     arg2 = value_coerce_array (arg2);
212
213   if (TYPE_CODE (type2) == TYPE_CODE_FUNC)
214     arg2 = value_coerce_function (arg2);
215
216   type2 = check_typedef (VALUE_TYPE (arg2));
217   COERCE_VARYING_ARRAY (arg2, type2);
218   code2 = TYPE_CODE (type2);
219
220   if (code1 == TYPE_CODE_COMPLEX)
221     return cast_into_complex (type, arg2);
222   if (code1 == TYPE_CODE_BOOL)
223     {
224       code1 = TYPE_CODE_INT;
225       convert_to_boolean = 1;
226     }
227   if (code1 == TYPE_CODE_CHAR)
228     code1 = TYPE_CODE_INT;
229   if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
230     code2 = TYPE_CODE_INT;
231
232   scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
233             || code2 == TYPE_CODE_ENUM || code2 == TYPE_CODE_RANGE);
234
235   if (code1 == TYPE_CODE_STRUCT
236       && code2 == TYPE_CODE_STRUCT
237       && TYPE_NAME (type) != 0)
238     {
239       /* Look in the type of the source to see if it contains the
240          type of the target as a superclass.  If so, we'll need to
241          offset the object in addition to changing its type.  */
242       value_ptr v = search_struct_field (type_name_no_tag (type),
243                                          arg2, 0, type2, 1);
244       if (v)
245         {
246           VALUE_TYPE (v) = type;
247           return v;
248         }
249     }
250   if (code1 == TYPE_CODE_FLT && scalar)
251     return value_from_double (type, value_as_double (arg2));
252   else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
253             || code1 == TYPE_CODE_RANGE)
254            && (scalar || code2 == TYPE_CODE_PTR))
255     {
256       LONGEST longest;
257
258       if (hp_som_som_object_present &&  /* if target compiled by HP aCC */
259           (code2 == TYPE_CODE_PTR))
260         {
261           unsigned int *ptr;
262           value_ptr retvalp;
263
264           switch (TYPE_CODE (TYPE_TARGET_TYPE (type2)))
265             {
266               /* With HP aCC, pointers to data members have a bias */
267             case TYPE_CODE_MEMBER:
268               retvalp = value_from_longest (type, value_as_long (arg2));
269               /* force evaluation */
270               ptr = (unsigned int *) VALUE_CONTENTS (retvalp);
271               *ptr &= ~0x20000000;      /* zap 29th bit to remove bias */
272               return retvalp;
273
274               /* While pointers to methods don't really point to a function */
275             case TYPE_CODE_METHOD:
276               error ("Pointers to methods not supported with HP aCC");
277
278             default:
279               break;            /* fall out and go to normal handling */
280             }
281         }
282       longest = value_as_long (arg2);
283       return value_from_longest (type, convert_to_boolean ?
284                                  (LONGEST) (longest ? 1 : 0) : longest);
285     }
286   else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT  ||
287                                       code2 == TYPE_CODE_ENUM ||
288                                       code2 == TYPE_CODE_RANGE))
289     {
290       int ptr_bit = HOST_CHAR_BIT * TYPE_LENGTH (type);
291       LONGEST longest = value_as_long (arg2);
292       if (ptr_bit < sizeof (LONGEST) * HOST_CHAR_BIT)
293         {
294           if (longest >= ((LONGEST) 1 << ptr_bit)
295               || longest <= -((LONGEST) 1 << ptr_bit))
296             warning ("value truncated");
297         }
298       return value_from_longest (type, longest);
299     }
300   else if (TYPE_LENGTH (type) == TYPE_LENGTH (type2))
301     {
302       if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
303         {
304           struct type *t1 = check_typedef (TYPE_TARGET_TYPE (type));
305           struct type *t2 = check_typedef (TYPE_TARGET_TYPE (type2));
306           if (TYPE_CODE (t1) == TYPE_CODE_STRUCT
307               && TYPE_CODE (t2) == TYPE_CODE_STRUCT
308               && !value_logical_not (arg2))
309             {
310               value_ptr v;
311
312               /* Look in the type of the source to see if it contains the
313                  type of the target as a superclass.  If so, we'll need to
314                  offset the pointer rather than just change its type.  */
315               if (TYPE_NAME (t1) != NULL)
316                 {
317                   v = search_struct_field (type_name_no_tag (t1),
318                                            value_ind (arg2), 0, t2, 1);
319                   if (v)
320                     {
321                       v = value_addr (v);
322                       VALUE_TYPE (v) = type;
323                       return v;
324                     }
325                 }
326
327               /* Look in the type of the target to see if it contains the
328                  type of the source as a superclass.  If so, we'll need to
329                  offset the pointer rather than just change its type.
330                  FIXME: This fails silently with virtual inheritance.  */
331               if (TYPE_NAME (t2) != NULL)
332                 {
333                   v = search_struct_field (type_name_no_tag (t2),
334                                        value_zero (t1, not_lval), 0, t1, 1);
335                   if (v)
336                     {
337                       value_ptr v2 = value_ind (arg2);
338                       VALUE_ADDRESS (v2) -= VALUE_ADDRESS (v)
339                         + VALUE_OFFSET (v);
340
341                       /* JYG: adjust the new pointer value and
342                          embedded offset. */
343                       v2->aligner.contents[0] -=  VALUE_EMBEDDED_OFFSET (v);
344                       VALUE_EMBEDDED_OFFSET (v2) = 0;
345
346                       v2 = value_addr (v2);
347                       VALUE_TYPE (v2) = type;
348                       return v2;
349                     }
350                 }
351             }
352           /* No superclass found, just fall through to change ptr type.  */
353         }
354       VALUE_TYPE (arg2) = type;
355       VALUE_ENCLOSING_TYPE (arg2) = type;       /* pai: chk_val */
356       VALUE_POINTED_TO_OFFSET (arg2) = 0;       /* pai: chk_val */
357       return arg2;
358     }
359   else if (chill_varying_type (type))
360     {
361       struct type *range1, *range2, *eltype1, *eltype2;
362       value_ptr val;
363       int count1, count2;
364       LONGEST low_bound, high_bound;
365       char *valaddr, *valaddr_data;
366       /* For lint warning about eltype2 possibly uninitialized: */
367       eltype2 = NULL;
368       if (code2 == TYPE_CODE_BITSTRING)
369         error ("not implemented: converting bitstring to varying type");
370       if ((code2 != TYPE_CODE_ARRAY && code2 != TYPE_CODE_STRING)
371           || (eltype1 = check_typedef (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, 1))),
372               eltype2 = check_typedef (TYPE_TARGET_TYPE (type2)),
373               (TYPE_LENGTH (eltype1) != TYPE_LENGTH (eltype2)
374       /* || TYPE_CODE (eltype1) != TYPE_CODE (eltype2) */ )))
375         error ("Invalid conversion to varying type");
376       range1 = TYPE_FIELD_TYPE (TYPE_FIELD_TYPE (type, 1), 0);
377       range2 = TYPE_FIELD_TYPE (type2, 0);
378       if (get_discrete_bounds (range1, &low_bound, &high_bound) < 0)
379         count1 = -1;
380       else
381         count1 = high_bound - low_bound + 1;
382       if (get_discrete_bounds (range2, &low_bound, &high_bound) < 0)
383         count1 = -1, count2 = 0;        /* To force error before */
384       else
385         count2 = high_bound - low_bound + 1;
386       if (count2 > count1)
387         error ("target varying type is too small");
388       val = allocate_value (type);
389       valaddr = VALUE_CONTENTS_RAW (val);
390       valaddr_data = valaddr + TYPE_FIELD_BITPOS (type, 1) / 8;
391       /* Set val's __var_length field to count2. */
392       store_signed_integer (valaddr, TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0)),
393                             count2);
394       /* Set the __var_data field to count2 elements copied from arg2. */
395       memcpy (valaddr_data, VALUE_CONTENTS (arg2),
396               count2 * TYPE_LENGTH (eltype2));
397       /* Zero the rest of the __var_data field of val. */
398       memset (valaddr_data + count2 * TYPE_LENGTH (eltype2), '\0',
399               (count1 - count2) * TYPE_LENGTH (eltype2));
400       return val;
401     }
402   else if (VALUE_LVAL (arg2) == lval_memory)
403     {
404       return value_at_lazy (type, VALUE_ADDRESS (arg2) + VALUE_OFFSET (arg2),
405                             VALUE_BFD_SECTION (arg2));
406     }
407   else if (code1 == TYPE_CODE_VOID)
408     {
409       return value_zero (builtin_type_void, not_lval);
410     }
411   else
412     {
413       error ("Invalid cast.");
414       return 0;
415     }
416 }
417
418 /* Create a value of type TYPE that is zero, and return it.  */
419
420 value_ptr
421 value_zero (struct type *type, enum lval_type lv)
422 {
423   register value_ptr val = allocate_value (type);
424
425   memset (VALUE_CONTENTS (val), 0, TYPE_LENGTH (check_typedef (type)));
426   VALUE_LVAL (val) = lv;
427
428   return val;
429 }
430
431 /* Return a value with type TYPE located at ADDR.
432
433    Call value_at only if the data needs to be fetched immediately;
434    if we can be 'lazy' and defer the fetch, perhaps indefinately, call
435    value_at_lazy instead.  value_at_lazy simply records the address of
436    the data and sets the lazy-evaluation-required flag.  The lazy flag
437    is tested in the VALUE_CONTENTS macro, which is used if and when
438    the contents are actually required.
439
440    Note: value_at does *NOT* handle embedded offsets; perform such
441    adjustments before or after calling it. */
442
443 value_ptr
444 value_at (struct type *type, CORE_ADDR addr, asection *sect)
445 {
446   register value_ptr val;
447
448   if (TYPE_CODE (check_typedef (type)) == TYPE_CODE_VOID)
449     error ("Attempt to dereference a generic pointer.");
450
451   val = allocate_value (type);
452
453   if (GDB_TARGET_IS_D10V
454       && TYPE_CODE (type) == TYPE_CODE_PTR
455       && TYPE_TARGET_TYPE (type)
456       && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC))
457     {
458       /* pointer to function */
459       unsigned long num;
460       unsigned short snum;
461       snum = read_memory_unsigned_integer (addr, 2);
462       num = D10V_MAKE_IADDR (snum);
463       store_address (VALUE_CONTENTS_RAW (val), 4, num);
464     }
465   else if (GDB_TARGET_IS_D10V
466            && TYPE_CODE (type) == TYPE_CODE_PTR)
467     {
468       /* pointer to data */
469       unsigned long num;
470       unsigned short snum;
471       snum = read_memory_unsigned_integer (addr, 2);
472       num = D10V_MAKE_DADDR (snum);
473       store_address (VALUE_CONTENTS_RAW (val), 4, num);
474     }
475   else
476     read_memory (addr, VALUE_CONTENTS_ALL_RAW (val), TYPE_LENGTH (type));
477
478   VALUE_LVAL (val) = lval_memory;
479   VALUE_ADDRESS (val) = addr;
480   VALUE_BFD_SECTION (val) = sect;
481
482   return val;
483 }
484
485 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).  */
486
487 value_ptr
488 value_at_lazy (struct type *type, CORE_ADDR addr, asection *sect)
489 {
490   register value_ptr val;
491
492   if (TYPE_CODE (check_typedef (type)) == TYPE_CODE_VOID)
493     error ("Attempt to dereference a generic pointer.");
494
495   val = allocate_value (type);
496
497   VALUE_LVAL (val) = lval_memory;
498   VALUE_ADDRESS (val) = addr;
499   VALUE_LAZY (val) = 1;
500   VALUE_BFD_SECTION (val) = sect;
501
502   return val;
503 }
504
505 /* Called only from the VALUE_CONTENTS and VALUE_CONTENTS_ALL macros,
506    if the current data for a variable needs to be loaded into
507    VALUE_CONTENTS(VAL).  Fetches the data from the user's process, and
508    clears the lazy flag to indicate that the data in the buffer is valid.
509
510    If the value is zero-length, we avoid calling read_memory, which would
511    abort.  We mark the value as fetched anyway -- all 0 bytes of it.
512
513    This function returns a value because it is used in the VALUE_CONTENTS
514    macro as part of an expression, where a void would not work.  The
515    value is ignored.  */
516
517 int
518 value_fetch_lazy (register value_ptr val)
519 {
520   CORE_ADDR addr = VALUE_ADDRESS (val) + VALUE_OFFSET (val);
521   int length = TYPE_LENGTH (VALUE_ENCLOSING_TYPE (val));
522
523   struct type *type = VALUE_TYPE (val);
524   if (GDB_TARGET_IS_D10V
525       && TYPE_CODE (type) == TYPE_CODE_PTR
526       && TYPE_TARGET_TYPE (type)
527       && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC))
528     {
529       /* pointer to function */
530       unsigned long num;
531       unsigned short snum;
532       snum = read_memory_unsigned_integer (addr, 2);
533       num = D10V_MAKE_IADDR (snum);
534       store_address (VALUE_CONTENTS_RAW (val), 4, num);
535     }
536   else if (GDB_TARGET_IS_D10V
537            && TYPE_CODE (type) == TYPE_CODE_PTR)
538     {
539       /* pointer to data */
540       unsigned long num;
541       unsigned short snum;
542       snum = read_memory_unsigned_integer (addr, 2);
543       num = D10V_MAKE_DADDR (snum);
544       store_address (VALUE_CONTENTS_RAW (val), 4, num);
545     }
546   else if (length)
547     read_memory (addr, VALUE_CONTENTS_ALL_RAW (val), length);
548
549   VALUE_LAZY (val) = 0;
550   return 0;
551 }
552
553
554 /* Store the contents of FROMVAL into the location of TOVAL.
555    Return a new value with the location of TOVAL and contents of FROMVAL.  */
556
557 value_ptr
558 value_assign (register value_ptr toval, register value_ptr fromval)
559 {
560   register struct type *type;
561   register value_ptr val;
562   char raw_buffer[MAX_REGISTER_RAW_SIZE];
563   int use_buffer = 0;
564
565   if (!toval->modifiable)
566     error ("Left operand of assignment is not a modifiable lvalue.");
567
568   COERCE_REF (toval);
569
570   type = VALUE_TYPE (toval);
571   if (VALUE_LVAL (toval) != lval_internalvar)
572     fromval = value_cast (type, fromval);
573   else
574     COERCE_ARRAY (fromval);
575   CHECK_TYPEDEF (type);
576
577   /* If TOVAL is a special machine register requiring conversion
578      of program values to a special raw format,
579      convert FROMVAL's contents now, with result in `raw_buffer',
580      and set USE_BUFFER to the number of bytes to write.  */
581
582   if (VALUE_REGNO (toval) >= 0)
583     {
584       int regno = VALUE_REGNO (toval);
585       if (REGISTER_CONVERTIBLE (regno))
586         {
587           struct type *fromtype = check_typedef (VALUE_TYPE (fromval));
588           REGISTER_CONVERT_TO_RAW (fromtype, regno,
589                                    VALUE_CONTENTS (fromval), raw_buffer);
590           use_buffer = REGISTER_RAW_SIZE (regno);
591         }
592     }
593
594   switch (VALUE_LVAL (toval))
595     {
596     case lval_internalvar:
597       set_internalvar (VALUE_INTERNALVAR (toval), fromval);
598       val = value_copy (VALUE_INTERNALVAR (toval)->value);
599       VALUE_ENCLOSING_TYPE (val) = VALUE_ENCLOSING_TYPE (fromval);
600       VALUE_EMBEDDED_OFFSET (val) = VALUE_EMBEDDED_OFFSET (fromval);
601       VALUE_POINTED_TO_OFFSET (val) = VALUE_POINTED_TO_OFFSET (fromval);
602       return val;
603
604     case lval_internalvar_component:
605       set_internalvar_component (VALUE_INTERNALVAR (toval),
606                                  VALUE_OFFSET (toval),
607                                  VALUE_BITPOS (toval),
608                                  VALUE_BITSIZE (toval),
609                                  fromval);
610       break;
611
612     case lval_memory:
613       {
614         char *dest_buffer;
615         CORE_ADDR changed_addr;
616         int changed_len;
617
618         if (VALUE_BITSIZE (toval))
619           {
620             char buffer[sizeof (LONGEST)];
621             /* We assume that the argument to read_memory is in units of
622                host chars.  FIXME:  Is that correct?  */
623             changed_len = (VALUE_BITPOS (toval)
624                            + VALUE_BITSIZE (toval)
625                            + HOST_CHAR_BIT - 1)
626               / HOST_CHAR_BIT;
627
628             if (changed_len > (int) sizeof (LONGEST))
629               error ("Can't handle bitfields which don't fit in a %d bit word.",
630                      sizeof (LONGEST) * HOST_CHAR_BIT);
631
632             read_memory (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
633                          buffer, changed_len);
634             modify_field (buffer, value_as_long (fromval),
635                           VALUE_BITPOS (toval), VALUE_BITSIZE (toval));
636             changed_addr = VALUE_ADDRESS (toval) + VALUE_OFFSET (toval);
637             dest_buffer = buffer;
638           }
639         else if (use_buffer)
640           {
641             changed_addr = VALUE_ADDRESS (toval) + VALUE_OFFSET (toval);
642             changed_len = use_buffer;
643             dest_buffer = raw_buffer;
644           }
645         else
646           {
647             changed_addr = VALUE_ADDRESS (toval) + VALUE_OFFSET (toval);
648             changed_len = TYPE_LENGTH (type);
649             dest_buffer = VALUE_CONTENTS (fromval);
650           }
651
652         write_memory (changed_addr, dest_buffer, changed_len);
653         if (memory_changed_hook)
654           memory_changed_hook (changed_addr, changed_len);
655       }
656       break;
657
658     case lval_register:
659       if (VALUE_BITSIZE (toval))
660         {
661           char buffer[sizeof (LONGEST)];
662           int len =
663                 REGISTER_RAW_SIZE (VALUE_REGNO (toval)) - VALUE_OFFSET (toval);
664
665           if (len > (int) sizeof (LONGEST))
666             error ("Can't handle bitfields in registers larger than %d bits.",
667                    sizeof (LONGEST) * HOST_CHAR_BIT);
668
669           if (VALUE_BITPOS (toval) + VALUE_BITSIZE (toval)
670               > len * HOST_CHAR_BIT)
671             /* Getting this right would involve being very careful about
672                byte order.  */
673             error ("Can't assign to bitfields that cross register "
674                    "boundaries.");
675
676           read_register_bytes (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
677                                buffer, len);
678           modify_field (buffer, value_as_long (fromval),
679                         VALUE_BITPOS (toval), VALUE_BITSIZE (toval));
680           write_register_bytes (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
681                                 buffer, len);
682         }
683       else if (use_buffer)
684         write_register_bytes (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
685                               raw_buffer, use_buffer);
686       else
687         {
688           /* Do any conversion necessary when storing this type to more
689              than one register.  */
690 #ifdef REGISTER_CONVERT_FROM_TYPE
691           memcpy (raw_buffer, VALUE_CONTENTS (fromval), TYPE_LENGTH (type));
692           REGISTER_CONVERT_FROM_TYPE (VALUE_REGNO (toval), type, raw_buffer);
693           write_register_bytes (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
694                                 raw_buffer, TYPE_LENGTH (type));
695 #else
696           write_register_bytes (VALUE_ADDRESS (toval) + VALUE_OFFSET (toval),
697                               VALUE_CONTENTS (fromval), TYPE_LENGTH (type));
698 #endif
699         }
700       /* Assigning to the stack pointer, frame pointer, and other
701          (architecture and calling convention specific) registers may
702          cause the frame cache to be out of date.  We just do this
703          on all assignments to registers for simplicity; I doubt the slowdown
704          matters.  */
705       reinit_frame_cache ();
706       break;
707
708     case lval_reg_frame_relative:
709       {
710         /* value is stored in a series of registers in the frame
711            specified by the structure.  Copy that value out, modify
712            it, and copy it back in.  */
713         int amount_to_copy = (VALUE_BITSIZE (toval) ? 1 : TYPE_LENGTH (type));
714         int reg_size = REGISTER_RAW_SIZE (VALUE_FRAME_REGNUM (toval));
715         int byte_offset = VALUE_OFFSET (toval) % reg_size;
716         int reg_offset = VALUE_OFFSET (toval) / reg_size;
717         int amount_copied;
718
719         /* Make the buffer large enough in all cases.  */
720         char *buffer = (char *) alloca (amount_to_copy
721                                         + sizeof (LONGEST)
722                                         + MAX_REGISTER_RAW_SIZE);
723
724         int regno;
725         struct frame_info *frame;
726
727         /* Figure out which frame this is in currently.  */
728         for (frame = get_current_frame ();
729              frame && FRAME_FP (frame) != VALUE_FRAME (toval);
730              frame = get_prev_frame (frame))
731           ;
732
733         if (!frame)
734           error ("Value being assigned to is no longer active.");
735
736         amount_to_copy += (reg_size - amount_to_copy % reg_size);
737
738         /* Copy it out.  */
739         for ((regno = VALUE_FRAME_REGNUM (toval) + reg_offset,
740               amount_copied = 0);
741              amount_copied < amount_to_copy;
742              amount_copied += reg_size, regno++)
743           {
744             get_saved_register (buffer + amount_copied,
745                                 (int *) NULL, (CORE_ADDR *) NULL,
746                                 frame, regno, (enum lval_type *) NULL);
747           }
748
749         /* Modify what needs to be modified.  */
750         if (VALUE_BITSIZE (toval))
751           modify_field (buffer + byte_offset,
752                         value_as_long (fromval),
753                         VALUE_BITPOS (toval), VALUE_BITSIZE (toval));
754         else if (use_buffer)
755           memcpy (buffer + byte_offset, raw_buffer, use_buffer);
756         else
757           memcpy (buffer + byte_offset, VALUE_CONTENTS (fromval),
758                   TYPE_LENGTH (type));
759
760         /* Copy it back.  */
761         for ((regno = VALUE_FRAME_REGNUM (toval) + reg_offset,
762               amount_copied = 0);
763              amount_copied < amount_to_copy;
764              amount_copied += reg_size, regno++)
765           {
766             enum lval_type lval;
767             CORE_ADDR addr;
768             int optim;
769
770             /* Just find out where to put it.  */
771             get_saved_register ((char *) NULL,
772                                 &optim, &addr, frame, regno, &lval);
773
774             if (optim)
775               error ("Attempt to assign to a value that was optimized out.");
776             if (lval == lval_memory)
777               write_memory (addr, buffer + amount_copied, reg_size);
778             else if (lval == lval_register)
779               write_register_bytes (addr, buffer + amount_copied, reg_size);
780             else
781               error ("Attempt to assign to an unmodifiable value.");
782           }
783
784         if (register_changed_hook)
785           register_changed_hook (-1);
786       }
787       break;
788
789
790     default:
791       error ("Left operand of assignment is not an lvalue.");
792     }
793
794   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
795      If the field is signed, and is negative, then sign extend. */
796   if ((VALUE_BITSIZE (toval) > 0)
797       && (VALUE_BITSIZE (toval) < 8 * (int) sizeof (LONGEST)))
798     {
799       LONGEST fieldval = value_as_long (fromval);
800       LONGEST valmask = (((ULONGEST) 1) << VALUE_BITSIZE (toval)) - 1;
801
802       fieldval &= valmask;
803       if (!TYPE_UNSIGNED (type) && (fieldval & (valmask ^ (valmask >> 1))))
804         fieldval |= ~valmask;
805
806       fromval = value_from_longest (type, fieldval);
807     }
808
809   val = value_copy (toval);
810   memcpy (VALUE_CONTENTS_RAW (val), VALUE_CONTENTS (fromval),
811           TYPE_LENGTH (type));
812   VALUE_TYPE (val) = type;
813   VALUE_ENCLOSING_TYPE (val) = VALUE_ENCLOSING_TYPE (fromval);
814   VALUE_EMBEDDED_OFFSET (val) = VALUE_EMBEDDED_OFFSET (fromval);
815   VALUE_POINTED_TO_OFFSET (val) = VALUE_POINTED_TO_OFFSET (fromval);
816
817   return val;
818 }
819
820 /* Extend a value VAL to COUNT repetitions of its type.  */
821
822 value_ptr
823 value_repeat (value_ptr arg1, int count)
824 {
825   register value_ptr val;
826
827   if (VALUE_LVAL (arg1) != lval_memory)
828     error ("Only values in memory can be extended with '@'.");
829   if (count < 1)
830     error ("Invalid number %d of repetitions.", count);
831
832   val = allocate_repeat_value (VALUE_ENCLOSING_TYPE (arg1), count);
833
834   read_memory (VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1),
835                VALUE_CONTENTS_ALL_RAW (val),
836                TYPE_LENGTH (VALUE_ENCLOSING_TYPE (val)));
837   VALUE_LVAL (val) = lval_memory;
838   VALUE_ADDRESS (val) = VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1);
839
840   return val;
841 }
842
843 value_ptr
844 value_of_variable (struct symbol *var, struct block *b)
845 {
846   value_ptr val;
847   struct frame_info *frame = NULL;
848
849   if (!b)
850     frame = NULL;               /* Use selected frame.  */
851   else if (symbol_read_needs_frame (var))
852     {
853       frame = block_innermost_frame (b);
854       if (!frame)
855         {
856           if (BLOCK_FUNCTION (b)
857               && SYMBOL_SOURCE_NAME (BLOCK_FUNCTION (b)))
858             error ("No frame is currently executing in block %s.",
859                    SYMBOL_SOURCE_NAME (BLOCK_FUNCTION (b)));
860           else
861             error ("No frame is currently executing in specified block");
862         }
863     }
864
865   val = read_var_value (var, frame);
866   if (!val)
867     error ("Address of symbol \"%s\" is unknown.", SYMBOL_SOURCE_NAME (var));
868
869   return val;
870 }
871
872 /* Given a value which is an array, return a value which is a pointer to its
873    first element, regardless of whether or not the array has a nonzero lower
874    bound.
875
876    FIXME:  A previous comment here indicated that this routine should be
877    substracting the array's lower bound.  It's not clear to me that this
878    is correct.  Given an array subscripting operation, it would certainly
879    work to do the adjustment here, essentially computing:
880
881    (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
882
883    However I believe a more appropriate and logical place to account for
884    the lower bound is to do so in value_subscript, essentially computing:
885
886    (&array[0] + ((index - lowerbound) * sizeof array[0]))
887
888    As further evidence consider what would happen with operations other
889    than array subscripting, where the caller would get back a value that
890    had an address somewhere before the actual first element of the array,
891    and the information about the lower bound would be lost because of
892    the coercion to pointer type.
893  */
894
895 value_ptr
896 value_coerce_array (value_ptr arg1)
897 {
898   register struct type *type = check_typedef (VALUE_TYPE (arg1));
899
900   if (VALUE_LVAL (arg1) != lval_memory)
901     error ("Attempt to take address of value not located in memory.");
902
903   return value_from_pointer (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
904                              (VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1)));
905 }
906
907 /* Given a value which is a function, return a value which is a pointer
908    to it.  */
909
910 value_ptr
911 value_coerce_function (value_ptr arg1)
912 {
913   value_ptr retval;
914
915   if (VALUE_LVAL (arg1) != lval_memory)
916     error ("Attempt to take address of value not located in memory.");
917
918   retval = value_from_pointer (lookup_pointer_type (VALUE_TYPE (arg1)),
919                                (VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1)));
920   VALUE_BFD_SECTION (retval) = VALUE_BFD_SECTION (arg1);
921   return retval;
922 }
923
924 /* Return a pointer value for the object for which ARG1 is the contents.  */
925
926 value_ptr
927 value_addr (value_ptr arg1)
928 {
929   value_ptr arg2;
930
931   struct type *type = check_typedef (VALUE_TYPE (arg1));
932   if (TYPE_CODE (type) == TYPE_CODE_REF)
933     {
934       /* Copy the value, but change the type from (T&) to (T*).
935          We keep the same location information, which is efficient,
936          and allows &(&X) to get the location containing the reference. */
937       arg2 = value_copy (arg1);
938       VALUE_TYPE (arg2) = lookup_pointer_type (TYPE_TARGET_TYPE (type));
939       return arg2;
940     }
941   if (TYPE_CODE (type) == TYPE_CODE_FUNC)
942     return value_coerce_function (arg1);
943
944   if (VALUE_LVAL (arg1) != lval_memory)
945     error ("Attempt to take address of value not located in memory.");
946
947   /* Get target memory address */
948   arg2 = value_from_pointer (lookup_pointer_type (VALUE_TYPE (arg1)),
949                              (VALUE_ADDRESS (arg1)
950                               + VALUE_OFFSET (arg1)
951                               + VALUE_EMBEDDED_OFFSET (arg1)));
952
953   /* This may be a pointer to a base subobject; so remember the
954      full derived object's type ... */
955   VALUE_ENCLOSING_TYPE (arg2) = lookup_pointer_type (VALUE_ENCLOSING_TYPE (arg1));
956   /* ... and also the relative position of the subobject in the full object */
957   VALUE_POINTED_TO_OFFSET (arg2) = VALUE_EMBEDDED_OFFSET (arg1);
958   VALUE_BFD_SECTION (arg2) = VALUE_BFD_SECTION (arg1);
959   return arg2;
960 }
961
962 /* Given a value of a pointer type, apply the C unary * operator to it.  */
963
964 value_ptr
965 value_ind (value_ptr arg1)
966 {
967   struct type *base_type;
968   value_ptr arg2;
969
970   COERCE_ARRAY (arg1);
971
972   base_type = check_typedef (VALUE_TYPE (arg1));
973
974   if (TYPE_CODE (base_type) == TYPE_CODE_MEMBER)
975     error ("not implemented: member types in value_ind");
976
977   /* Allow * on an integer so we can cast it to whatever we want.
978      This returns an int, which seems like the most C-like thing
979      to do.  "long long" variables are rare enough that
980      BUILTIN_TYPE_LONGEST would seem to be a mistake.  */
981   if (TYPE_CODE (base_type) == TYPE_CODE_INT)
982     return value_at (builtin_type_int,
983                      (CORE_ADDR) value_as_long (arg1),
984                      VALUE_BFD_SECTION (arg1));
985   else if (TYPE_CODE (base_type) == TYPE_CODE_PTR)
986     {
987       struct type *enc_type;
988       /* We may be pointing to something embedded in a larger object */
989       /* Get the real type of the enclosing object */
990       enc_type = check_typedef (VALUE_ENCLOSING_TYPE (arg1));
991       enc_type = TYPE_TARGET_TYPE (enc_type);
992       /* Retrieve the enclosing object pointed to */
993       arg2 = value_at_lazy (enc_type,
994                    value_as_pointer (arg1) - VALUE_POINTED_TO_OFFSET (arg1),
995                             VALUE_BFD_SECTION (arg1));
996       /* Re-adjust type */
997       VALUE_TYPE (arg2) = TYPE_TARGET_TYPE (base_type);
998       /* Add embedding info */
999       VALUE_ENCLOSING_TYPE (arg2) = enc_type;
1000       VALUE_EMBEDDED_OFFSET (arg2) = VALUE_POINTED_TO_OFFSET (arg1);
1001
1002       /* We may be pointing to an object of some derived type */
1003       arg2 = value_full_object (arg2, NULL, 0, 0, 0);
1004       return arg2;
1005     }
1006
1007   error ("Attempt to take contents of a non-pointer value.");
1008   return 0;                     /* For lint -- never reached */
1009 }
1010 \f
1011 /* Pushing small parts of stack frames.  */
1012
1013 /* Push one word (the size of object that a register holds).  */
1014
1015 CORE_ADDR
1016 push_word (CORE_ADDR sp, ULONGEST word)
1017 {
1018   register int len = REGISTER_SIZE;
1019   char buffer[MAX_REGISTER_RAW_SIZE];
1020
1021   store_unsigned_integer (buffer, len, word);
1022   if (INNER_THAN (1, 2))
1023     {
1024       /* stack grows downward */
1025       sp -= len;
1026       write_memory (sp, buffer, len);
1027     }
1028   else
1029     {
1030       /* stack grows upward */
1031       write_memory (sp, buffer, len);
1032       sp += len;
1033     }
1034
1035   return sp;
1036 }
1037
1038 /* Push LEN bytes with data at BUFFER.  */
1039
1040 CORE_ADDR
1041 push_bytes (CORE_ADDR sp, char *buffer, int len)
1042 {
1043   if (INNER_THAN (1, 2))
1044     {
1045       /* stack grows downward */
1046       sp -= len;
1047       write_memory (sp, buffer, len);
1048     }
1049   else
1050     {
1051       /* stack grows upward */
1052       write_memory (sp, buffer, len);
1053       sp += len;
1054     }
1055
1056   return sp;
1057 }
1058
1059 #ifndef PARM_BOUNDARY
1060 #define PARM_BOUNDARY (0)
1061 #endif
1062
1063 /* Push onto the stack the specified value VALUE.  Pad it correctly for
1064    it to be an argument to a function.  */
1065
1066 static CORE_ADDR
1067 value_push (register CORE_ADDR sp, value_ptr arg)
1068 {
1069   register int len = TYPE_LENGTH (VALUE_ENCLOSING_TYPE (arg));
1070   register int container_len = len;
1071   register int offset;
1072
1073   /* How big is the container we're going to put this value in?  */
1074   if (PARM_BOUNDARY)
1075     container_len = ((len + PARM_BOUNDARY / TARGET_CHAR_BIT - 1)
1076                      & ~(PARM_BOUNDARY / TARGET_CHAR_BIT - 1));
1077
1078   /* Are we going to put it at the high or low end of the container?  */
1079   if (TARGET_BYTE_ORDER == BIG_ENDIAN)
1080     offset = container_len - len;
1081   else
1082     offset = 0;
1083
1084   if (INNER_THAN (1, 2))
1085     {
1086       /* stack grows downward */
1087       sp -= container_len;
1088       write_memory (sp + offset, VALUE_CONTENTS_ALL (arg), len);
1089     }
1090   else
1091     {
1092       /* stack grows upward */
1093       write_memory (sp + offset, VALUE_CONTENTS_ALL (arg), len);
1094       sp += container_len;
1095     }
1096
1097   return sp;
1098 }
1099
1100 #ifndef PUSH_ARGUMENTS
1101 #define PUSH_ARGUMENTS default_push_arguments
1102 #endif
1103
1104 CORE_ADDR
1105 default_push_arguments (int nargs, value_ptr *args, CORE_ADDR sp,
1106                         int struct_return, CORE_ADDR struct_addr)
1107 {
1108   /* ASSERT ( !struct_return); */
1109   int i;
1110   for (i = nargs - 1; i >= 0; i--)
1111     sp = value_push (sp, args[i]);
1112   return sp;
1113 }
1114
1115
1116 /* A default function for COERCE_FLOAT_TO_DOUBLE: do the coercion only
1117    when we don't have any type for the argument at hand.  This occurs
1118    when we have no debug info, or when passing varargs.
1119
1120    This is an annoying default: the rule the compiler follows is to do
1121    the standard promotions whenever there is no prototype in scope,
1122    and almost all targets want this behavior.  But there are some old
1123    architectures which want this odd behavior.  If you want to go
1124    through them all and fix them, please do.  Modern gdbarch-style
1125    targets may find it convenient to use standard_coerce_float_to_double.  */
1126 int
1127 default_coerce_float_to_double (struct type *formal, struct type *actual)
1128 {
1129   return formal == NULL;
1130 }
1131
1132
1133 /* Always coerce floats to doubles when there is no prototype in scope.
1134    If your architecture follows the standard type promotion rules for
1135    calling unprototyped functions, your gdbarch init function can pass
1136    this function to set_gdbarch_coerce_float_to_double to use its logic.  */
1137 int
1138 standard_coerce_float_to_double (struct type *formal, struct type *actual)
1139 {
1140   return 1;
1141 }
1142
1143
1144 /* Perform the standard coercions that are specified
1145    for arguments to be passed to C functions.
1146
1147    If PARAM_TYPE is non-NULL, it is the expected parameter type.
1148    IS_PROTOTYPED is non-zero if the function declaration is prototyped.  */
1149
1150 static value_ptr
1151 value_arg_coerce (value_ptr arg, struct type *param_type, int is_prototyped)
1152 {
1153   register struct type *arg_type = check_typedef (VALUE_TYPE (arg));
1154   register struct type *type
1155   = param_type ? check_typedef (param_type) : arg_type;
1156
1157   switch (TYPE_CODE (type))
1158     {
1159     case TYPE_CODE_REF:
1160       if (TYPE_CODE (arg_type) != TYPE_CODE_REF)
1161         {
1162           arg = value_addr (arg);
1163           VALUE_TYPE (arg) = param_type;
1164           return arg;
1165         }
1166       break;
1167     case TYPE_CODE_INT:
1168     case TYPE_CODE_CHAR:
1169     case TYPE_CODE_BOOL:
1170     case TYPE_CODE_ENUM:
1171       /* If we don't have a prototype, coerce to integer type if necessary.  */
1172       if (!is_prototyped)
1173         {
1174           if (TYPE_LENGTH (type) < TYPE_LENGTH (builtin_type_int))
1175             type = builtin_type_int;
1176         }
1177       /* Currently all target ABIs require at least the width of an integer
1178          type for an argument.  We may have to conditionalize the following
1179          type coercion for future targets.  */
1180       if (TYPE_LENGTH (type) < TYPE_LENGTH (builtin_type_int))
1181         type = builtin_type_int;
1182       break;
1183     case TYPE_CODE_FLT:
1184       /* FIXME: We should always convert floats to doubles in the
1185          non-prototyped case.  As many debugging formats include
1186          no information about prototyping, we have to live with
1187          COERCE_FLOAT_TO_DOUBLE for now.  */
1188       if (!is_prototyped && COERCE_FLOAT_TO_DOUBLE (param_type, arg_type))
1189         {
1190           if (TYPE_LENGTH (type) < TYPE_LENGTH (builtin_type_double))
1191             type = builtin_type_double;
1192           else if (TYPE_LENGTH (type) > TYPE_LENGTH (builtin_type_double))
1193             type = builtin_type_long_double;
1194         }
1195       break;
1196     case TYPE_CODE_FUNC:
1197       type = lookup_pointer_type (type);
1198       break;
1199     case TYPE_CODE_ARRAY:
1200       if (current_language->c_style_arrays)
1201         type = lookup_pointer_type (TYPE_TARGET_TYPE (type));
1202       break;
1203     case TYPE_CODE_UNDEF:
1204     case TYPE_CODE_PTR:
1205     case TYPE_CODE_STRUCT:
1206     case TYPE_CODE_UNION:
1207     case TYPE_CODE_VOID:
1208     case TYPE_CODE_SET:
1209     case TYPE_CODE_RANGE:
1210     case TYPE_CODE_STRING:
1211     case TYPE_CODE_BITSTRING:
1212     case TYPE_CODE_ERROR:
1213     case TYPE_CODE_MEMBER:
1214     case TYPE_CODE_METHOD:
1215     case TYPE_CODE_COMPLEX:
1216     default:
1217       break;
1218     }
1219
1220   return value_cast (type, arg);
1221 }
1222
1223 /* Determine a function's address and its return type from its value.
1224    Calls error() if the function is not valid for calling.  */
1225
1226 static CORE_ADDR
1227 find_function_addr (value_ptr function, struct type **retval_type)
1228 {
1229   register struct type *ftype = check_typedef (VALUE_TYPE (function));
1230   register enum type_code code = TYPE_CODE (ftype);
1231   struct type *value_type;
1232   CORE_ADDR funaddr;
1233
1234   /* If it's a member function, just look at the function
1235      part of it.  */
1236
1237   /* Determine address to call.  */
1238   if (code == TYPE_CODE_FUNC || code == TYPE_CODE_METHOD)
1239     {
1240       funaddr = VALUE_ADDRESS (function);
1241       value_type = TYPE_TARGET_TYPE (ftype);
1242     }
1243   else if (code == TYPE_CODE_PTR)
1244     {
1245       funaddr = value_as_pointer (function);
1246       ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
1247       if (TYPE_CODE (ftype) == TYPE_CODE_FUNC
1248           || TYPE_CODE (ftype) == TYPE_CODE_METHOD)
1249         {
1250           funaddr = CONVERT_FROM_FUNC_PTR_ADDR (funaddr);
1251           value_type = TYPE_TARGET_TYPE (ftype);
1252         }
1253       else
1254         value_type = builtin_type_int;
1255     }
1256   else if (code == TYPE_CODE_INT)
1257     {
1258       /* Handle the case of functions lacking debugging info.
1259          Their values are characters since their addresses are char */
1260       if (TYPE_LENGTH (ftype) == 1)
1261         funaddr = value_as_pointer (value_addr (function));
1262       else
1263         /* Handle integer used as address of a function.  */
1264         funaddr = (CORE_ADDR) value_as_long (function);
1265
1266       value_type = builtin_type_int;
1267     }
1268   else
1269     error ("Invalid data type for function to be called.");
1270
1271   *retval_type = value_type;
1272   return funaddr;
1273 }
1274
1275 /* All this stuff with a dummy frame may seem unnecessarily complicated
1276    (why not just save registers in GDB?).  The purpose of pushing a dummy
1277    frame which looks just like a real frame is so that if you call a
1278    function and then hit a breakpoint (get a signal, etc), "backtrace"
1279    will look right.  Whether the backtrace needs to actually show the
1280    stack at the time the inferior function was called is debatable, but
1281    it certainly needs to not display garbage.  So if you are contemplating
1282    making dummy frames be different from normal frames, consider that.  */
1283
1284 /* Perform a function call in the inferior.
1285    ARGS is a vector of values of arguments (NARGS of them).
1286    FUNCTION is a value, the function to be called.
1287    Returns a value representing what the function returned.
1288    May fail to return, if a breakpoint or signal is hit
1289    during the execution of the function.
1290
1291    ARGS is modified to contain coerced values. */
1292
1293 static value_ptr hand_function_call (value_ptr function, int nargs,
1294                                      value_ptr * args);
1295 static value_ptr
1296 hand_function_call (value_ptr function, int nargs, value_ptr *args)
1297 {
1298   register CORE_ADDR sp;
1299   register int i;
1300   int rc;
1301   CORE_ADDR start_sp;
1302   /* CALL_DUMMY is an array of words (REGISTER_SIZE), but each word
1303      is in host byte order.  Before calling FIX_CALL_DUMMY, we byteswap it
1304      and remove any extra bytes which might exist because ULONGEST is
1305      bigger than REGISTER_SIZE.
1306
1307      NOTE: This is pretty wierd, as the call dummy is actually a
1308      sequence of instructions.  But CISC machines will have
1309      to pack the instructions into REGISTER_SIZE units (and
1310      so will RISC machines for which INSTRUCTION_SIZE is not
1311      REGISTER_SIZE).
1312
1313      NOTE: This is pretty stupid.  CALL_DUMMY should be in strict
1314      target byte order. */
1315
1316   static ULONGEST *dummy;
1317   int sizeof_dummy1;
1318   char *dummy1;
1319   CORE_ADDR old_sp;
1320   struct type *value_type;
1321   unsigned char struct_return;
1322   CORE_ADDR struct_addr = 0;
1323   struct inferior_status *inf_status;
1324   struct cleanup *old_chain;
1325   CORE_ADDR funaddr;
1326   int using_gcc;                /* Set to version of gcc in use, or zero if not gcc */
1327   CORE_ADDR real_pc;
1328   struct type *param_type = NULL;
1329   struct type *ftype = check_typedef (SYMBOL_TYPE (function));
1330
1331   dummy = alloca (SIZEOF_CALL_DUMMY_WORDS);
1332   sizeof_dummy1 = REGISTER_SIZE * SIZEOF_CALL_DUMMY_WORDS / sizeof (ULONGEST);
1333   dummy1 = alloca (sizeof_dummy1);
1334   memcpy (dummy, CALL_DUMMY_WORDS, SIZEOF_CALL_DUMMY_WORDS);
1335
1336   if (!target_has_execution)
1337     noprocess ();
1338
1339   inf_status = save_inferior_status (1);
1340   old_chain = make_cleanup_restore_inferior_status (inf_status);
1341
1342   /* PUSH_DUMMY_FRAME is responsible for saving the inferior registers
1343      (and POP_FRAME for restoring them).  (At least on most machines)
1344      they are saved on the stack in the inferior.  */
1345   PUSH_DUMMY_FRAME;
1346
1347   old_sp = sp = read_sp ();
1348
1349   if (INNER_THAN (1, 2))
1350     {
1351       /* Stack grows down */
1352       sp -= sizeof_dummy1;
1353       start_sp = sp;
1354     }
1355   else
1356     {
1357       /* Stack grows up */
1358       start_sp = sp;
1359       sp += sizeof_dummy1;
1360     }
1361
1362   funaddr = find_function_addr (function, &value_type);
1363   CHECK_TYPEDEF (value_type);
1364
1365   {
1366     struct block *b = block_for_pc (funaddr);
1367     /* If compiled without -g, assume GCC 2.  */
1368     using_gcc = (b == NULL ? 2 : BLOCK_GCC_COMPILED (b));
1369   }
1370
1371   /* Are we returning a value using a structure return or a normal
1372      value return? */
1373
1374   struct_return = using_struct_return (function, funaddr, value_type,
1375                                        using_gcc);
1376
1377   /* Create a call sequence customized for this function
1378      and the number of arguments for it.  */
1379   for (i = 0; i < (int) (SIZEOF_CALL_DUMMY_WORDS / sizeof (dummy[0])); i++)
1380     store_unsigned_integer (&dummy1[i * REGISTER_SIZE],
1381                             REGISTER_SIZE,
1382                             (ULONGEST) dummy[i]);
1383
1384 #ifdef GDB_TARGET_IS_HPPA
1385   real_pc = FIX_CALL_DUMMY (dummy1, start_sp, funaddr, nargs, args,
1386                             value_type, using_gcc);
1387 #else
1388   FIX_CALL_DUMMY (dummy1, start_sp, funaddr, nargs, args,
1389                   value_type, using_gcc);
1390   real_pc = start_sp;
1391 #endif
1392
1393   if (CALL_DUMMY_LOCATION == ON_STACK)
1394     {
1395       write_memory (start_sp, (char *) dummy1, sizeof_dummy1);
1396     }
1397
1398   if (CALL_DUMMY_LOCATION == BEFORE_TEXT_END)
1399     {
1400       /* Convex Unix prohibits executing in the stack segment. */
1401       /* Hope there is empty room at the top of the text segment. */
1402       extern CORE_ADDR text_end;
1403       static int checked = 0;
1404       if (!checked)
1405         for (start_sp = text_end - sizeof_dummy1; start_sp < text_end; ++start_sp)
1406           if (read_memory_integer (start_sp, 1) != 0)
1407             error ("text segment full -- no place to put call");
1408       checked = 1;
1409       sp = old_sp;
1410       real_pc = text_end - sizeof_dummy1;
1411       write_memory (real_pc, (char *) dummy1, sizeof_dummy1);
1412     }
1413
1414   if (CALL_DUMMY_LOCATION == AFTER_TEXT_END)
1415     {
1416       extern CORE_ADDR text_end;
1417       int errcode;
1418       sp = old_sp;
1419       real_pc = text_end;
1420       errcode = target_write_memory (real_pc, (char *) dummy1, sizeof_dummy1);
1421       if (errcode != 0)
1422         error ("Cannot write text segment -- call_function failed");
1423     }
1424
1425   if (CALL_DUMMY_LOCATION == AT_ENTRY_POINT)
1426     {
1427       real_pc = funaddr;
1428     }
1429
1430 #ifdef lint
1431   sp = old_sp;                  /* It really is used, for some ifdef's... */
1432 #endif
1433
1434   if (nargs < TYPE_NFIELDS (ftype))
1435     error ("too few arguments in function call");
1436
1437   for (i = nargs - 1; i >= 0; i--)
1438     {
1439       /* If we're off the end of the known arguments, do the standard
1440          promotions.  FIXME: if we had a prototype, this should only
1441          be allowed if ... were present.  */
1442       if (i >= TYPE_NFIELDS (ftype))
1443         args[i] = value_arg_coerce (args[i], NULL, 0);
1444
1445       else
1446         {
1447           int is_prototyped = TYPE_FLAGS (ftype) & TYPE_FLAG_PROTOTYPED;
1448           param_type = TYPE_FIELD_TYPE (ftype, i);
1449
1450           args[i] = value_arg_coerce (args[i], param_type, is_prototyped);
1451         }
1452
1453       /*elz: this code is to handle the case in which the function to be called
1454          has a pointer to function as parameter and the corresponding actual argument
1455          is the address of a function and not a pointer to function variable.
1456          In aCC compiled code, the calls through pointers to functions (in the body
1457          of the function called by hand) are made via $$dyncall_external which
1458          requires some registers setting, this is taken care of if we call
1459          via a function pointer variable, but not via a function address.
1460          In cc this is not a problem. */
1461
1462       if (using_gcc == 0)
1463         if (param_type)
1464           /* if this parameter is a pointer to function */
1465           if (TYPE_CODE (param_type) == TYPE_CODE_PTR)
1466             if (TYPE_CODE (param_type->target_type) == TYPE_CODE_FUNC)
1467               /* elz: FIXME here should go the test about the compiler used
1468                  to compile the target. We want to issue the error
1469                  message only if the compiler used was HP's aCC.
1470                  If we used HP's cc, then there is no problem and no need
1471                  to return at this point */
1472               if (using_gcc == 0)       /* && compiler == aCC */
1473                 /* go see if the actual parameter is a variable of type
1474                    pointer to function or just a function */
1475                 if (args[i]->lval == not_lval)
1476                   {
1477                     char *arg_name;
1478                     if (find_pc_partial_function ((CORE_ADDR) args[i]->aligner.contents[0], &arg_name, NULL, NULL))
1479                       error ("\
1480 You cannot use function <%s> as argument. \n\
1481 You must use a pointer to function type variable. Command ignored.", arg_name);
1482                   }
1483     }
1484
1485   if (REG_STRUCT_HAS_ADDR_P ())
1486     {
1487       /* This is a machine like the sparc, where we may need to pass a
1488          pointer to the structure, not the structure itself.  */
1489       for (i = nargs - 1; i >= 0; i--)
1490         {
1491           struct type *arg_type = check_typedef (VALUE_TYPE (args[i]));
1492           if ((TYPE_CODE (arg_type) == TYPE_CODE_STRUCT
1493                || TYPE_CODE (arg_type) == TYPE_CODE_UNION
1494                || TYPE_CODE (arg_type) == TYPE_CODE_ARRAY
1495                || TYPE_CODE (arg_type) == TYPE_CODE_STRING
1496                || TYPE_CODE (arg_type) == TYPE_CODE_BITSTRING
1497                || TYPE_CODE (arg_type) == TYPE_CODE_SET
1498                || (TYPE_CODE (arg_type) == TYPE_CODE_FLT
1499                    && TYPE_LENGTH (arg_type) > 8)
1500                )
1501               && REG_STRUCT_HAS_ADDR (using_gcc, arg_type))
1502             {
1503               CORE_ADDR addr;
1504               int len;          /*  = TYPE_LENGTH (arg_type); */
1505               int aligned_len;
1506               arg_type = check_typedef (VALUE_ENCLOSING_TYPE (args[i]));
1507               len = TYPE_LENGTH (arg_type);
1508
1509               if (STACK_ALIGN_P ())
1510                 /* MVS 11/22/96: I think at least some of this
1511                    stack_align code is really broken.  Better to let
1512                    PUSH_ARGUMENTS adjust the stack in a target-defined
1513                    manner.  */
1514                 aligned_len = STACK_ALIGN (len);
1515               else
1516                 aligned_len = len;
1517               if (INNER_THAN (1, 2))
1518                 {
1519                   /* stack grows downward */
1520                   sp -= aligned_len;
1521                 }
1522               else
1523                 {
1524                   /* The stack grows up, so the address of the thing
1525                      we push is the stack pointer before we push it.  */
1526                   addr = sp;
1527                 }
1528               /* Push the structure.  */
1529               write_memory (sp, VALUE_CONTENTS_ALL (args[i]), len);
1530               if (INNER_THAN (1, 2))
1531                 {
1532                   /* The stack grows down, so the address of the thing
1533                      we push is the stack pointer after we push it.  */
1534                   addr = sp;
1535                 }
1536               else
1537                 {
1538                   /* stack grows upward */
1539                   sp += aligned_len;
1540                 }
1541               /* The value we're going to pass is the address of the
1542                  thing we just pushed.  */
1543               /*args[i] = value_from_longest (lookup_pointer_type (value_type),
1544                 (LONGEST) addr); */
1545               args[i] = value_from_pointer (lookup_pointer_type (arg_type),
1546                                             addr);
1547             }
1548         }
1549     }
1550
1551
1552   /* Reserve space for the return structure to be written on the
1553      stack, if necessary */
1554
1555   if (struct_return)
1556     {
1557       int len = TYPE_LENGTH (value_type);
1558       if (STACK_ALIGN_P ())
1559         /* MVS 11/22/96: I think at least some of this stack_align
1560            code is really broken.  Better to let PUSH_ARGUMENTS adjust
1561            the stack in a target-defined manner.  */
1562         len = STACK_ALIGN (len);
1563       if (INNER_THAN (1, 2))
1564         {
1565           /* stack grows downward */
1566           sp -= len;
1567           struct_addr = sp;
1568         }
1569       else
1570         {
1571           /* stack grows upward */
1572           struct_addr = sp;
1573           sp += len;
1574         }
1575     }
1576
1577   /* elz: on HPPA no need for this extra alignment, maybe it is needed
1578      on other architectures. This is because all the alignment is
1579      taken care of in the above code (ifdef REG_STRUCT_HAS_ADDR) and
1580      in hppa_push_arguments */
1581   if (EXTRA_STACK_ALIGNMENT_NEEDED)
1582     {
1583       /* MVS 11/22/96: I think at least some of this stack_align code
1584          is really broken.  Better to let PUSH_ARGUMENTS adjust the
1585          stack in a target-defined manner.  */
1586       if (STACK_ALIGN_P () && INNER_THAN (1, 2))
1587         {
1588           /* If stack grows down, we must leave a hole at the top. */
1589           int len = 0;
1590
1591           for (i = nargs - 1; i >= 0; i--)
1592             len += TYPE_LENGTH (VALUE_ENCLOSING_TYPE (args[i]));
1593           if (CALL_DUMMY_STACK_ADJUST_P)
1594             len += CALL_DUMMY_STACK_ADJUST;
1595           sp -= STACK_ALIGN (len) - len;
1596         }
1597     }
1598
1599   sp = PUSH_ARGUMENTS (nargs, args, sp, struct_return, struct_addr);
1600
1601 #ifdef PUSH_RETURN_ADDRESS      /* for targets that use no CALL_DUMMY */
1602   /* There are a number of targets now which actually don't write any
1603      CALL_DUMMY instructions into the target, but instead just save the
1604      machine state, push the arguments, and jump directly to the callee
1605      function.  Since this doesn't actually involve executing a JSR/BSR
1606      instruction, the return address must be set up by hand, either by
1607      pushing onto the stack or copying into a return-address register
1608      as appropriate.  Formerly this has been done in PUSH_ARGUMENTS,
1609      but that's overloading its functionality a bit, so I'm making it
1610      explicit to do it here.  */
1611   sp = PUSH_RETURN_ADDRESS (real_pc, sp);
1612 #endif /* PUSH_RETURN_ADDRESS */
1613
1614   if (STACK_ALIGN_P () && !INNER_THAN (1, 2))
1615     {
1616       /* If stack grows up, we must leave a hole at the bottom, note
1617          that sp already has been advanced for the arguments!  */
1618       if (CALL_DUMMY_STACK_ADJUST_P)
1619         sp += CALL_DUMMY_STACK_ADJUST;
1620       sp = STACK_ALIGN (sp);
1621     }
1622
1623 /* XXX This seems wrong.  For stacks that grow down we shouldn't do
1624    anything here!  */
1625   /* MVS 11/22/96: I think at least some of this stack_align code is
1626      really broken.  Better to let PUSH_ARGUMENTS adjust the stack in
1627      a target-defined manner.  */
1628   if (CALL_DUMMY_STACK_ADJUST_P)
1629     if (INNER_THAN (1, 2))
1630       {
1631         /* stack grows downward */
1632         sp -= CALL_DUMMY_STACK_ADJUST;
1633       }
1634
1635   /* Store the address at which the structure is supposed to be
1636      written.  Note that this (and the code which reserved the space
1637      above) assumes that gcc was used to compile this function.  Since
1638      it doesn't cost us anything but space and if the function is pcc
1639      it will ignore this value, we will make that assumption.
1640
1641      Also note that on some machines (like the sparc) pcc uses a
1642      convention like gcc's.  */
1643
1644   if (struct_return)
1645     STORE_STRUCT_RETURN (struct_addr, sp);
1646
1647   /* Write the stack pointer.  This is here because the statements above
1648      might fool with it.  On SPARC, this write also stores the register
1649      window into the right place in the new stack frame, which otherwise
1650      wouldn't happen.  (See store_inferior_registers in sparc-nat.c.)  */
1651   write_sp (sp);
1652
1653   if (SAVE_DUMMY_FRAME_TOS_P ())
1654     SAVE_DUMMY_FRAME_TOS (sp);
1655
1656   {
1657     char retbuf[REGISTER_BYTES];
1658     char *name;
1659     struct symbol *symbol;
1660
1661     name = NULL;
1662     symbol = find_pc_function (funaddr);
1663     if (symbol)
1664       {
1665         name = SYMBOL_SOURCE_NAME (symbol);
1666       }
1667     else
1668       {
1669         /* Try the minimal symbols.  */
1670         struct minimal_symbol *msymbol = lookup_minimal_symbol_by_pc (funaddr);
1671
1672         if (msymbol)
1673           {
1674             name = SYMBOL_SOURCE_NAME (msymbol);
1675           }
1676       }
1677     if (name == NULL)
1678       {
1679         char format[80];
1680         sprintf (format, "at %s", local_hex_format ());
1681         name = alloca (80);
1682         /* FIXME-32x64: assumes funaddr fits in a long.  */
1683         sprintf (name, format, (unsigned long) funaddr);
1684       }
1685
1686     /* Execute the stack dummy routine, calling FUNCTION.
1687        When it is done, discard the empty frame
1688        after storing the contents of all regs into retbuf.  */
1689     rc = run_stack_dummy (real_pc + CALL_DUMMY_START_OFFSET, retbuf);
1690
1691     if (rc == 1)
1692       {
1693         /* We stopped inside the FUNCTION because of a random signal.
1694            Further execution of the FUNCTION is not allowed. */
1695
1696         if (unwind_on_signal_p)
1697           {
1698             /* The user wants the context restored. */
1699
1700             /* We must get back to the frame we were before the dummy call. */
1701             POP_FRAME;
1702
1703             /* FIXME: Insert a bunch of wrap_here; name can be very long if it's
1704                a C++ name with arguments and stuff.  */
1705             error ("\
1706 The program being debugged was signaled while in a function called from GDB.\n\
1707 GDB has restored the context to what it was before the call.\n\
1708 To change this behavior use \"set unwindonsignal off\"\n\
1709 Evaluation of the expression containing the function (%s) will be abandoned.",
1710                    name);
1711           }
1712         else
1713           {
1714             /* The user wants to stay in the frame where we stopped (default).*/
1715
1716             /* If we did the cleanups, we would print a spurious error
1717                message (Unable to restore previously selected frame),
1718                would write the registers from the inf_status (which is
1719                wrong), and would do other wrong things.  */
1720             discard_cleanups (old_chain);
1721             discard_inferior_status (inf_status);
1722
1723             /* FIXME: Insert a bunch of wrap_here; name can be very long if it's
1724                a C++ name with arguments and stuff.  */
1725             error ("\
1726 The program being debugged was signaled while in a function called from GDB.\n\
1727 GDB remains in the frame where the signal was received.\n\
1728 To change this behavior use \"set unwindonsignal on\"\n\
1729 Evaluation of the expression containing the function (%s) will be abandoned.",
1730                    name);
1731           }
1732       }
1733
1734     if (rc == 2)
1735       {
1736         /* We hit a breakpoint inside the FUNCTION. */
1737
1738         /* If we did the cleanups, we would print a spurious error
1739            message (Unable to restore previously selected frame),
1740            would write the registers from the inf_status (which is
1741            wrong), and would do other wrong things.  */
1742         discard_cleanups (old_chain);
1743         discard_inferior_status (inf_status);
1744
1745         /* The following error message used to say "The expression
1746            which contained the function call has been discarded."  It
1747            is a hard concept to explain in a few words.  Ideally, GDB
1748            would be able to resume evaluation of the expression when
1749            the function finally is done executing.  Perhaps someday
1750            this will be implemented (it would not be easy).  */
1751
1752         /* FIXME: Insert a bunch of wrap_here; name can be very long if it's
1753            a C++ name with arguments and stuff.  */
1754         error ("\
1755 The program being debugged stopped while in a function called from GDB.\n\
1756 When the function (%s) is done executing, GDB will silently\n\
1757 stop (instead of continuing to evaluate the expression containing\n\
1758 the function call).", name);
1759       }
1760
1761     /* If we get here the called FUNCTION run to completion. */
1762     do_cleanups (old_chain);
1763
1764     /* Figure out the value returned by the function.  */
1765 /* elz: I defined this new macro for the hppa architecture only.
1766    this gives us a way to get the value returned by the function from the stack,
1767    at the same address we told the function to put it.
1768    We cannot assume on the pa that r28 still contains the address of the returned
1769    structure. Usually this will be overwritten by the callee.
1770    I don't know about other architectures, so I defined this macro
1771  */
1772
1773 #ifdef VALUE_RETURNED_FROM_STACK
1774     if (struct_return)
1775       return (value_ptr) VALUE_RETURNED_FROM_STACK (value_type, struct_addr);
1776 #endif
1777
1778     return value_being_returned (value_type, retbuf, struct_return);
1779   }
1780 }
1781
1782 value_ptr
1783 call_function_by_hand (value_ptr function, int nargs, value_ptr *args)
1784 {
1785   if (CALL_DUMMY_P)
1786     {
1787       return hand_function_call (function, nargs, args);
1788     }
1789   else
1790     {
1791       error ("Cannot invoke functions on this machine.");
1792     }
1793 }
1794 \f
1795
1796
1797 /* Create a value for an array by allocating space in the inferior, copying
1798    the data into that space, and then setting up an array value.
1799
1800    The array bounds are set from LOWBOUND and HIGHBOUND, and the array is
1801    populated from the values passed in ELEMVEC.
1802
1803    The element type of the array is inherited from the type of the
1804    first element, and all elements must have the same size (though we
1805    don't currently enforce any restriction on their types). */
1806
1807 value_ptr
1808 value_array (int lowbound, int highbound, value_ptr *elemvec)
1809 {
1810   int nelem;
1811   int idx;
1812   unsigned int typelength;
1813   value_ptr val;
1814   struct type *rangetype;
1815   struct type *arraytype;
1816   CORE_ADDR addr;
1817
1818   /* Validate that the bounds are reasonable and that each of the elements
1819      have the same size. */
1820
1821   nelem = highbound - lowbound + 1;
1822   if (nelem <= 0)
1823     {
1824       error ("bad array bounds (%d, %d)", lowbound, highbound);
1825     }
1826   typelength = TYPE_LENGTH (VALUE_ENCLOSING_TYPE (elemvec[0]));
1827   for (idx = 1; idx < nelem; idx++)
1828     {
1829       if (TYPE_LENGTH (VALUE_ENCLOSING_TYPE (elemvec[idx])) != typelength)
1830         {
1831           error ("array elements must all be the same size");
1832         }
1833     }
1834
1835   rangetype = create_range_type ((struct type *) NULL, builtin_type_int,
1836                                  lowbound, highbound);
1837   arraytype = create_array_type ((struct type *) NULL,
1838                               VALUE_ENCLOSING_TYPE (elemvec[0]), rangetype);
1839
1840   if (!current_language->c_style_arrays)
1841     {
1842       val = allocate_value (arraytype);
1843       for (idx = 0; idx < nelem; idx++)
1844         {
1845           memcpy (VALUE_CONTENTS_ALL_RAW (val) + (idx * typelength),
1846                   VALUE_CONTENTS_ALL (elemvec[idx]),
1847                   typelength);
1848         }
1849       VALUE_BFD_SECTION (val) = VALUE_BFD_SECTION (elemvec[0]);
1850       return val;
1851     }
1852
1853   /* Allocate space to store the array in the inferior, and then initialize
1854      it by copying in each element.  FIXME:  Is it worth it to create a
1855      local buffer in which to collect each value and then write all the
1856      bytes in one operation? */
1857
1858   addr = allocate_space_in_inferior (nelem * typelength);
1859   for (idx = 0; idx < nelem; idx++)
1860     {
1861       write_memory (addr + (idx * typelength), VALUE_CONTENTS_ALL (elemvec[idx]),
1862                     typelength);
1863     }
1864
1865   /* Create the array type and set up an array value to be evaluated lazily. */
1866
1867   val = value_at_lazy (arraytype, addr, VALUE_BFD_SECTION (elemvec[0]));
1868   return (val);
1869 }
1870
1871 /* Create a value for a string constant by allocating space in the inferior,
1872    copying the data into that space, and returning the address with type
1873    TYPE_CODE_STRING.  PTR points to the string constant data; LEN is number
1874    of characters.
1875    Note that string types are like array of char types with a lower bound of
1876    zero and an upper bound of LEN - 1.  Also note that the string may contain
1877    embedded null bytes. */
1878
1879 value_ptr
1880 value_string (char *ptr, int len)
1881 {
1882   value_ptr val;
1883   int lowbound = current_language->string_lower_bound;
1884   struct type *rangetype = create_range_type ((struct type *) NULL,
1885                                               builtin_type_int,
1886                                               lowbound, len + lowbound - 1);
1887   struct type *stringtype
1888   = create_string_type ((struct type *) NULL, rangetype);
1889   CORE_ADDR addr;
1890
1891   if (current_language->c_style_arrays == 0)
1892     {
1893       val = allocate_value (stringtype);
1894       memcpy (VALUE_CONTENTS_RAW (val), ptr, len);
1895       return val;
1896     }
1897
1898
1899   /* Allocate space to store the string in the inferior, and then
1900      copy LEN bytes from PTR in gdb to that address in the inferior. */
1901
1902   addr = allocate_space_in_inferior (len);
1903   write_memory (addr, ptr, len);
1904
1905   val = value_at_lazy (stringtype, addr, NULL);
1906   return (val);
1907 }
1908
1909 value_ptr
1910 value_bitstring (char *ptr, int len)
1911 {
1912   value_ptr val;
1913   struct type *domain_type = create_range_type (NULL, builtin_type_int,
1914                                                 0, len - 1);
1915   struct type *type = create_set_type ((struct type *) NULL, domain_type);
1916   TYPE_CODE (type) = TYPE_CODE_BITSTRING;
1917   val = allocate_value (type);
1918   memcpy (VALUE_CONTENTS_RAW (val), ptr, TYPE_LENGTH (type));
1919   return val;
1920 }
1921 \f
1922 /* See if we can pass arguments in T2 to a function which takes arguments
1923    of types T1.  Both t1 and t2 are NULL-terminated vectors.  If some
1924    arguments need coercion of some sort, then the coerced values are written
1925    into T2.  Return value is 0 if the arguments could be matched, or the
1926    position at which they differ if not.
1927
1928    STATICP is nonzero if the T1 argument list came from a
1929    static member function.
1930
1931    For non-static member functions, we ignore the first argument,
1932    which is the type of the instance variable.  This is because we want
1933    to handle calls with objects from derived classes.  This is not
1934    entirely correct: we should actually check to make sure that a
1935    requested operation is type secure, shouldn't we?  FIXME.  */
1936
1937 static int
1938 typecmp (int staticp, struct type *t1[], value_ptr t2[])
1939 {
1940   int i;
1941
1942   if (t2 == 0)
1943     return 1;
1944   if (staticp && t1 == 0)
1945     return t2[1] != 0;
1946   if (t1 == 0)
1947     return 1;
1948   if (TYPE_CODE (t1[0]) == TYPE_CODE_VOID)
1949     return 0;
1950   if (t1[!staticp] == 0)
1951     return 0;
1952   for (i = !staticp; t1[i] && TYPE_CODE (t1[i]) != TYPE_CODE_VOID; i++)
1953     {
1954       struct type *tt1, *tt2;
1955       if (!t2[i])
1956         return i + 1;
1957       tt1 = check_typedef (t1[i]);
1958       tt2 = check_typedef (VALUE_TYPE (t2[i]));
1959       if (TYPE_CODE (tt1) == TYPE_CODE_REF
1960       /* We should be doing hairy argument matching, as below.  */
1961           && (TYPE_CODE (check_typedef (TYPE_TARGET_TYPE (tt1))) == TYPE_CODE (tt2)))
1962         {
1963           if (TYPE_CODE (tt2) == TYPE_CODE_ARRAY)
1964             t2[i] = value_coerce_array (t2[i]);
1965           else
1966             t2[i] = value_addr (t2[i]);
1967           continue;
1968         }
1969
1970       /* djb - 20000715 - Until the new type structure is in the
1971          place, and we can attempt things like implicit conversions,
1972          we need to do this so you can take something like a map<const
1973          char *>, and properly access map["hello"], because the
1974          argument to [] will be a reference to a pointer to a char,
1975          and the argument will be a pointer to a char. */
1976       while ( TYPE_CODE(tt1) == TYPE_CODE_REF ||
1977               TYPE_CODE (tt1) == TYPE_CODE_PTR)
1978         {
1979           tt1 = check_typedef( TYPE_TARGET_TYPE(tt1) );
1980         }
1981       while ( TYPE_CODE(tt2) == TYPE_CODE_ARRAY ||
1982               TYPE_CODE(tt2) == TYPE_CODE_PTR ||
1983               TYPE_CODE(tt2) == TYPE_CODE_REF)
1984         {
1985           tt2 = check_typedef( TYPE_TARGET_TYPE(tt2) );
1986         }
1987       if (TYPE_CODE (tt1) == TYPE_CODE (tt2))
1988         continue;
1989       /* Array to pointer is a `trivial conversion' according to the ARM.  */
1990
1991       /* We should be doing much hairier argument matching (see section 13.2
1992          of the ARM), but as a quick kludge, just check for the same type
1993          code.  */
1994       if (TYPE_CODE (t1[i]) != TYPE_CODE (VALUE_TYPE (t2[i])))
1995         return i + 1;
1996     }
1997   if (!t1[i])
1998     return 0;
1999   return t2[i] ? i + 1 : 0;
2000 }
2001
2002 /* Helper function used by value_struct_elt to recurse through baseclasses.
2003    Look for a field NAME in ARG1. Adjust the address of ARG1 by OFFSET bytes,
2004    and search in it assuming it has (class) type TYPE.
2005    If found, return value, else return NULL.
2006
2007    If LOOKING_FOR_BASECLASS, then instead of looking for struct fields,
2008    look for a baseclass named NAME.  */
2009
2010 static value_ptr
2011 search_struct_field (char *name, register value_ptr arg1, int offset,
2012                      register struct type *type, int looking_for_baseclass)
2013 {
2014   int i;
2015   int nbases = TYPE_N_BASECLASSES (type);
2016
2017   CHECK_TYPEDEF (type);
2018
2019   if (!looking_for_baseclass)
2020     for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
2021       {
2022         char *t_field_name = TYPE_FIELD_NAME (type, i);
2023
2024         if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2025           {
2026             value_ptr v;
2027             if (TYPE_FIELD_STATIC (type, i))
2028               v = value_static_field (type, i);
2029             else
2030               v = value_primitive_field (arg1, offset, i, type);
2031             if (v == 0)
2032               error ("there is no field named %s", name);
2033             return v;
2034           }
2035
2036         if (t_field_name
2037             && (t_field_name[0] == '\0'
2038                 || (TYPE_CODE (type) == TYPE_CODE_UNION
2039                     && (strcmp_iw (t_field_name, "else") == 0))))
2040           {
2041             struct type *field_type = TYPE_FIELD_TYPE (type, i);
2042             if (TYPE_CODE (field_type) == TYPE_CODE_UNION
2043                 || TYPE_CODE (field_type) == TYPE_CODE_STRUCT)
2044               {
2045                 /* Look for a match through the fields of an anonymous union,
2046                    or anonymous struct.  C++ provides anonymous unions.
2047
2048                    In the GNU Chill implementation of variant record types,
2049                    each <alternative field> has an (anonymous) union type,
2050                    each member of the union represents a <variant alternative>.
2051                    Each <variant alternative> is represented as a struct,
2052                    with a member for each <variant field>.  */
2053
2054                 value_ptr v;
2055                 int new_offset = offset;
2056
2057                 /* This is pretty gross.  In G++, the offset in an anonymous
2058                    union is relative to the beginning of the enclosing struct.
2059                    In the GNU Chill implementation of variant records,
2060                    the bitpos is zero in an anonymous union field, so we
2061                    have to add the offset of the union here. */
2062                 if (TYPE_CODE (field_type) == TYPE_CODE_STRUCT
2063                     || (TYPE_NFIELDS (field_type) > 0
2064                         && TYPE_FIELD_BITPOS (field_type, 0) == 0))
2065                   new_offset += TYPE_FIELD_BITPOS (type, i) / 8;
2066
2067                 v = search_struct_field (name, arg1, new_offset, field_type,
2068                                          looking_for_baseclass);
2069                 if (v)
2070                   return v;
2071               }
2072           }
2073       }
2074
2075   for (i = 0; i < nbases; i++)
2076     {
2077       value_ptr v;
2078       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2079       /* If we are looking for baseclasses, this is what we get when we
2080          hit them.  But it could happen that the base part's member name
2081          is not yet filled in.  */
2082       int found_baseclass = (looking_for_baseclass
2083                              && TYPE_BASECLASS_NAME (type, i) != NULL
2084                              && (strcmp_iw (name, TYPE_BASECLASS_NAME (type, i)) == 0));
2085
2086       if (BASETYPE_VIA_VIRTUAL (type, i))
2087         {
2088           int boffset;
2089           value_ptr v2 = allocate_value (basetype);
2090
2091           boffset = baseclass_offset (type, i,
2092                                       VALUE_CONTENTS (arg1) + offset,
2093                                       VALUE_ADDRESS (arg1)
2094                                       + VALUE_OFFSET (arg1) + offset);
2095           if (boffset == -1)
2096             error ("virtual baseclass botch");
2097
2098           /* The virtual base class pointer might have been clobbered by the
2099              user program. Make sure that it still points to a valid memory
2100              location.  */
2101
2102           boffset += offset;
2103           if (boffset < 0 || boffset >= TYPE_LENGTH (type))
2104             {
2105               CORE_ADDR base_addr;
2106
2107               base_addr = VALUE_ADDRESS (arg1) + VALUE_OFFSET (arg1) + boffset;
2108               if (target_read_memory (base_addr, VALUE_CONTENTS_RAW (v2),
2109                                       TYPE_LENGTH (basetype)) != 0)
2110                 error ("virtual baseclass botch");
2111               VALUE_LVAL (v2) = lval_memory;
2112               VALUE_ADDRESS (v2) = base_addr;
2113             }
2114           else
2115             {
2116               VALUE_LVAL (v2) = VALUE_LVAL (arg1);
2117               VALUE_ADDRESS (v2) = VALUE_ADDRESS (arg1);
2118               VALUE_OFFSET (v2) = VALUE_OFFSET (arg1) + boffset;
2119               if (VALUE_LAZY (arg1))
2120                 VALUE_LAZY (v2) = 1;
2121               else
2122                 memcpy (VALUE_CONTENTS_RAW (v2),
2123                         VALUE_CONTENTS_RAW (arg1) + boffset,
2124                         TYPE_LENGTH (basetype));
2125             }
2126
2127           if (found_baseclass)
2128             return v2;
2129           v = search_struct_field (name, v2, 0, TYPE_BASECLASS (type, i),
2130                                    looking_for_baseclass);
2131         }
2132       else if (found_baseclass)
2133         v = value_primitive_field (arg1, offset, i, type);
2134       else
2135         v = search_struct_field (name, arg1,
2136                                offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2137                                  basetype, looking_for_baseclass);
2138       if (v)
2139         return v;
2140     }
2141   return NULL;
2142 }
2143
2144
2145 /* Return the offset (in bytes) of the virtual base of type BASETYPE
2146  * in an object pointed to by VALADDR (on the host), assumed to be of
2147  * type TYPE.  OFFSET is number of bytes beyond start of ARG to start
2148  * looking (in case VALADDR is the contents of an enclosing object).
2149  *
2150  * This routine recurses on the primary base of the derived class because
2151  * the virtual base entries of the primary base appear before the other
2152  * virtual base entries.
2153  *
2154  * If the virtual base is not found, a negative integer is returned.
2155  * The magnitude of the negative integer is the number of entries in
2156  * the virtual table to skip over (entries corresponding to various
2157  * ancestral classes in the chain of primary bases).
2158  *
2159  * Important: This assumes the HP / Taligent C++ runtime
2160  * conventions. Use baseclass_offset() instead to deal with g++
2161  * conventions.  */
2162
2163 void
2164 find_rt_vbase_offset (struct type *type, struct type *basetype, char *valaddr,
2165                       int offset, int *boffset_p, int *skip_p)
2166 {
2167   int boffset;                  /* offset of virtual base */
2168   int index;                    /* displacement to use in virtual table */
2169   int skip;
2170
2171   value_ptr vp;
2172   CORE_ADDR vtbl;               /* the virtual table pointer */
2173   struct type *pbc;             /* the primary base class */
2174
2175   /* Look for the virtual base recursively in the primary base, first.
2176    * This is because the derived class object and its primary base
2177    * subobject share the primary virtual table.  */
2178
2179   boffset = 0;
2180   pbc = TYPE_PRIMARY_BASE (type);
2181   if (pbc)
2182     {
2183       find_rt_vbase_offset (pbc, basetype, valaddr, offset, &boffset, &skip);
2184       if (skip < 0)
2185         {
2186           *boffset_p = boffset;
2187           *skip_p = -1;
2188           return;
2189         }
2190     }
2191   else
2192     skip = 0;
2193
2194
2195   /* Find the index of the virtual base according to HP/Taligent
2196      runtime spec. (Depth-first, left-to-right.)  */
2197   index = virtual_base_index_skip_primaries (basetype, type);
2198
2199   if (index < 0)
2200     {
2201       *skip_p = skip + virtual_base_list_length_skip_primaries (type);
2202       *boffset_p = 0;
2203       return;
2204     }
2205
2206   /* pai: FIXME -- 32x64 possible problem */
2207   /* First word (4 bytes) in object layout is the vtable pointer */
2208   vtbl = *(CORE_ADDR *) (valaddr + offset);
2209
2210   /* Before the constructor is invoked, things are usually zero'd out. */
2211   if (vtbl == 0)
2212     error ("Couldn't find virtual table -- object may not be constructed yet.");
2213
2214
2215   /* Find virtual base's offset -- jump over entries for primary base
2216    * ancestors, then use the index computed above.  But also adjust by
2217    * HP_ACC_VBASE_START for the vtable slots before the start of the
2218    * virtual base entries.  Offset is negative -- virtual base entries
2219    * appear _before_ the address point of the virtual table. */
2220
2221   /* pai: FIXME -- 32x64 problem, if word = 8 bytes, change multiplier
2222      & use long type */
2223
2224   /* epstein : FIXME -- added param for overlay section. May not be correct */
2225   vp = value_at (builtin_type_int, vtbl + 4 * (-skip - index - HP_ACC_VBASE_START), NULL);
2226   boffset = value_as_long (vp);
2227   *skip_p = -1;
2228   *boffset_p = boffset;
2229   return;
2230 }
2231
2232
2233 /* Helper function used by value_struct_elt to recurse through baseclasses.
2234    Look for a field NAME in ARG1. Adjust the address of ARG1 by OFFSET bytes,
2235    and search in it assuming it has (class) type TYPE.
2236    If found, return value, else if name matched and args not return (value)-1,
2237    else return NULL. */
2238
2239 static value_ptr
2240 search_struct_method (char *name, register value_ptr *arg1p,
2241                       register value_ptr *args, int offset,
2242                       int *static_memfuncp, register struct type *type)
2243 {
2244   int i;
2245   value_ptr v;
2246   int name_matched = 0;
2247   char dem_opname[64];
2248
2249   CHECK_TYPEDEF (type);
2250   for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2251     {
2252       char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2253       /* FIXME!  May need to check for ARM demangling here */
2254       if (strncmp (t_field_name, "__", 2) == 0 ||
2255           strncmp (t_field_name, "op", 2) == 0 ||
2256           strncmp (t_field_name, "type", 4) == 0)
2257         {
2258           if (cplus_demangle_opname (t_field_name, dem_opname, DMGL_ANSI))
2259             t_field_name = dem_opname;
2260           else if (cplus_demangle_opname (t_field_name, dem_opname, 0))
2261             t_field_name = dem_opname;
2262         }
2263       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2264         {
2265           int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2266           struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2267           name_matched = 1;
2268
2269           if (j > 0 && args == 0)
2270             error ("cannot resolve overloaded method `%s': no arguments supplied", name);
2271           while (j >= 0)
2272             {
2273               if (TYPE_FN_FIELD_STUB (f, j))
2274                 check_stub_method (type, i, j);
2275               if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2276                             TYPE_FN_FIELD_ARGS (f, j), args))
2277                 {
2278                   if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2279                     return value_virtual_fn_field (arg1p, f, j, type, offset);
2280                   if (TYPE_FN_FIELD_STATIC_P (f, j) && static_memfuncp)
2281                     *static_memfuncp = 1;
2282                   v = value_fn_field (arg1p, f, j, type, offset);
2283                   if (v != NULL)
2284                     return v;       
2285                 }
2286               j--;
2287             }
2288         }
2289     }
2290
2291   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2292     {
2293       int base_offset;
2294
2295       if (BASETYPE_VIA_VIRTUAL (type, i))
2296         {
2297           if (TYPE_HAS_VTABLE (type))
2298             {
2299               /* HP aCC compiled type, search for virtual base offset
2300                  according to HP/Taligent runtime spec.  */
2301               int skip;
2302               find_rt_vbase_offset (type, TYPE_BASECLASS (type, i),
2303                                     VALUE_CONTENTS_ALL (*arg1p),
2304                                     offset + VALUE_EMBEDDED_OFFSET (*arg1p),
2305                                     &base_offset, &skip);
2306               if (skip >= 0)
2307                 error ("Virtual base class offset not found in vtable");
2308             }
2309           else
2310             {
2311               struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2312               char *base_valaddr;
2313
2314               /* The virtual base class pointer might have been clobbered by the
2315                  user program. Make sure that it still points to a valid memory
2316                  location.  */
2317
2318               if (offset < 0 || offset >= TYPE_LENGTH (type))
2319                 {
2320                   base_valaddr = (char *) alloca (TYPE_LENGTH (baseclass));
2321                   if (target_read_memory (VALUE_ADDRESS (*arg1p)
2322                                           + VALUE_OFFSET (*arg1p) + offset,
2323                                           base_valaddr,
2324                                           TYPE_LENGTH (baseclass)) != 0)
2325                     error ("virtual baseclass botch");
2326                 }
2327               else
2328                 base_valaddr = VALUE_CONTENTS (*arg1p) + offset;
2329
2330               base_offset =
2331                 baseclass_offset (type, i, base_valaddr,
2332                                   VALUE_ADDRESS (*arg1p)
2333                                   + VALUE_OFFSET (*arg1p) + offset);
2334               if (base_offset == -1)
2335                 error ("virtual baseclass botch");
2336             }
2337         }
2338       else
2339         {
2340           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2341         }
2342       v = search_struct_method (name, arg1p, args, base_offset + offset,
2343                                 static_memfuncp, TYPE_BASECLASS (type, i));
2344       if (v == (value_ptr) - 1)
2345         {
2346           name_matched = 1;
2347         }
2348       else if (v)
2349         {
2350 /* FIXME-bothner:  Why is this commented out?  Why is it here?  */
2351 /*        *arg1p = arg1_tmp; */
2352           return v;
2353         }
2354     }
2355   if (name_matched)
2356     return (value_ptr) - 1;
2357   else
2358     return NULL;
2359 }
2360
2361 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2362    extract the component named NAME from the ultimate target structure/union
2363    and return it as a value with its appropriate type.
2364    ERR is used in the error message if *ARGP's type is wrong.
2365
2366    C++: ARGS is a list of argument types to aid in the selection of
2367    an appropriate method. Also, handle derived types.
2368
2369    STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2370    where the truthvalue of whether the function that was resolved was
2371    a static member function or not is stored.
2372
2373    ERR is an error message to be printed in case the field is not found.  */
2374
2375 value_ptr
2376 value_struct_elt (register value_ptr *argp, register value_ptr *args,
2377                   char *name, int *static_memfuncp, char *err)
2378 {
2379   register struct type *t;
2380   value_ptr v;
2381
2382   COERCE_ARRAY (*argp);
2383
2384   t = check_typedef (VALUE_TYPE (*argp));
2385
2386   /* Follow pointers until we get to a non-pointer.  */
2387
2388   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_CODE (t) == TYPE_CODE_REF)
2389     {
2390       *argp = value_ind (*argp);
2391       /* Don't coerce fn pointer to fn and then back again!  */
2392       if (TYPE_CODE (VALUE_TYPE (*argp)) != TYPE_CODE_FUNC)
2393         COERCE_ARRAY (*argp);
2394       t = check_typedef (VALUE_TYPE (*argp));
2395     }
2396
2397   if (TYPE_CODE (t) == TYPE_CODE_MEMBER)
2398     error ("not implemented: member type in value_struct_elt");
2399
2400   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2401       && TYPE_CODE (t) != TYPE_CODE_UNION)
2402     error ("Attempt to extract a component of a value that is not a %s.", err);
2403
2404   /* Assume it's not, unless we see that it is.  */
2405   if (static_memfuncp)
2406     *static_memfuncp = 0;
2407
2408   if (!args)
2409     {
2410       /* if there are no arguments ...do this...  */
2411
2412       /* Try as a field first, because if we succeed, there
2413          is less work to be done.  */
2414       v = search_struct_field (name, *argp, 0, t, 0);
2415       if (v)
2416         return v;
2417
2418       /* C++: If it was not found as a data field, then try to
2419          return it as a pointer to a method.  */
2420
2421       if (destructor_name_p (name, t))
2422         error ("Cannot get value of destructor");
2423
2424       v = search_struct_method (name, argp, args, 0, static_memfuncp, t);
2425
2426       if (v == (value_ptr) - 1)
2427         error ("Cannot take address of a method");
2428       else if (v == 0)
2429         {
2430           if (TYPE_NFN_FIELDS (t))
2431             error ("There is no member or method named %s.", name);
2432           else
2433             error ("There is no member named %s.", name);
2434         }
2435       return v;
2436     }
2437
2438   if (destructor_name_p (name, t))
2439     {
2440       if (!args[1])
2441         {
2442           /* Destructors are a special case.  */
2443           int m_index, f_index;
2444
2445           v = NULL;
2446           if (get_destructor_fn_field (t, &m_index, &f_index))
2447             {
2448               v = value_fn_field (NULL, TYPE_FN_FIELDLIST1 (t, m_index),
2449                                   f_index, NULL, 0);
2450             }
2451           if (v == NULL)
2452             error ("could not find destructor function named %s.", name);
2453           else
2454             return v;
2455         }
2456       else
2457         {
2458           error ("destructor should not have any argument");
2459         }
2460     }
2461   else
2462     v = search_struct_method (name, argp, args, 0, static_memfuncp, t);
2463   
2464   if (v == (value_ptr) - 1)
2465     {
2466       error ("One of the arguments you tried to pass to %s could not be converted to what the function wants.", name);
2467     }
2468   else if (v == 0)
2469     {
2470       /* See if user tried to invoke data as function.  If so,
2471          hand it back.  If it's not callable (i.e., a pointer to function),
2472          gdb should give an error.  */
2473       v = search_struct_field (name, *argp, 0, t, 0);
2474     }
2475
2476   if (!v)
2477     error ("Structure has no component named %s.", name);
2478   return v;
2479 }
2480
2481 /* Search through the methods of an object (and its bases)
2482  * to find a specified method. Return the pointer to the
2483  * fn_field list of overloaded instances.
2484  * Helper function for value_find_oload_list.
2485  * ARGP is a pointer to a pointer to a value (the object)
2486  * METHOD is a string containing the method name
2487  * OFFSET is the offset within the value
2488  * STATIC_MEMFUNCP is set if the method is static
2489  * TYPE is the assumed type of the object
2490  * NUM_FNS is the number of overloaded instances
2491  * BASETYPE is set to the actual type of the subobject where the method is found
2492  * BOFFSET is the offset of the base subobject where the method is found */
2493
2494 static struct fn_field *
2495 find_method_list (value_ptr *argp, char *method, int offset,
2496                   int *static_memfuncp, struct type *type, int *num_fns,
2497                   struct type **basetype, int *boffset)
2498 {
2499   int i;
2500   struct fn_field *f;
2501   CHECK_TYPEDEF (type);
2502
2503   *num_fns = 0;
2504
2505   /* First check in object itself */
2506   for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2507     {
2508       /* pai: FIXME What about operators and type conversions? */
2509       char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2510       if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2511         {
2512           *num_fns = TYPE_FN_FIELDLIST_LENGTH (type, i);
2513           *basetype = type;
2514           *boffset = offset;
2515           return TYPE_FN_FIELDLIST1 (type, i);
2516         }
2517     }
2518
2519   /* Not found in object, check in base subobjects */
2520   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2521     {
2522       int base_offset;
2523       if (BASETYPE_VIA_VIRTUAL (type, i))
2524         {
2525           if (TYPE_HAS_VTABLE (type))
2526             {
2527               /* HP aCC compiled type, search for virtual base offset
2528                * according to HP/Taligent runtime spec.  */
2529               int skip;
2530               find_rt_vbase_offset (type, TYPE_BASECLASS (type, i),
2531                                     VALUE_CONTENTS_ALL (*argp),
2532                                     offset + VALUE_EMBEDDED_OFFSET (*argp),
2533                                     &base_offset, &skip);
2534               if (skip >= 0)
2535                 error ("Virtual base class offset not found in vtable");
2536             }
2537           else
2538             {
2539               /* probably g++ runtime model */
2540               base_offset = VALUE_OFFSET (*argp) + offset;
2541               base_offset =
2542                 baseclass_offset (type, i,
2543                                   VALUE_CONTENTS (*argp) + base_offset,
2544                                   VALUE_ADDRESS (*argp) + base_offset);
2545               if (base_offset == -1)
2546                 error ("virtual baseclass botch");
2547             }
2548         }
2549       else
2550         /* non-virtual base, simply use bit position from debug info */
2551         {
2552           base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2553         }
2554       f = find_method_list (argp, method, base_offset + offset,
2555       static_memfuncp, TYPE_BASECLASS (type, i), num_fns, basetype, boffset);
2556       if (f)
2557         return f;
2558     }
2559   return NULL;
2560 }
2561
2562 /* Return the list of overloaded methods of a specified name.
2563  * ARGP is a pointer to a pointer to a value (the object)
2564  * METHOD is the method name
2565  * OFFSET is the offset within the value contents
2566  * STATIC_MEMFUNCP is set if the method is static
2567  * NUM_FNS is the number of overloaded instances
2568  * BASETYPE is set to the type of the base subobject that defines the method
2569  * BOFFSET is the offset of the base subobject which defines the method */
2570
2571 struct fn_field *
2572 value_find_oload_method_list (value_ptr *argp, char *method, int offset,
2573                               int *static_memfuncp, int *num_fns,
2574                               struct type **basetype, int *boffset)
2575 {
2576   struct type *t;
2577
2578   t = check_typedef (VALUE_TYPE (*argp));
2579
2580   /* code snarfed from value_struct_elt */
2581   while (TYPE_CODE (t) == TYPE_CODE_PTR || TYPE_CODE (t) == TYPE_CODE_REF)
2582     {
2583       *argp = value_ind (*argp);
2584       /* Don't coerce fn pointer to fn and then back again!  */
2585       if (TYPE_CODE (VALUE_TYPE (*argp)) != TYPE_CODE_FUNC)
2586         COERCE_ARRAY (*argp);
2587       t = check_typedef (VALUE_TYPE (*argp));
2588     }
2589
2590   if (TYPE_CODE (t) == TYPE_CODE_MEMBER)
2591     error ("Not implemented: member type in value_find_oload_lis");
2592
2593   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2594       && TYPE_CODE (t) != TYPE_CODE_UNION)
2595     error ("Attempt to extract a component of a value that is not a struct or union");
2596
2597   /* Assume it's not static, unless we see that it is.  */
2598   if (static_memfuncp)
2599     *static_memfuncp = 0;
2600
2601   return find_method_list (argp, method, 0, static_memfuncp, t, num_fns, basetype, boffset);
2602
2603 }
2604
2605 /* Given an array of argument types (ARGTYPES) (which includes an
2606    entry for "this" in the case of C++ methods), the number of
2607    arguments NARGS, the NAME of a function whether it's a method or
2608    not (METHOD), and the degree of laxness (LAX) in conforming to
2609    overload resolution rules in ANSI C++, find the best function that
2610    matches on the argument types according to the overload resolution
2611    rules.
2612
2613    In the case of class methods, the parameter OBJ is an object value
2614    in which to search for overloaded methods.
2615
2616    In the case of non-method functions, the parameter FSYM is a symbol
2617    corresponding to one of the overloaded functions.
2618
2619    Return value is an integer: 0 -> good match, 10 -> debugger applied
2620    non-standard coercions, 100 -> incompatible.
2621
2622    If a method is being searched for, VALP will hold the value.
2623    If a non-method is being searched for, SYMP will hold the symbol for it.
2624
2625    If a method is being searched for, and it is a static method,
2626    then STATICP will point to a non-zero value.
2627
2628    Note: This function does *not* check the value of
2629    overload_resolution.  Caller must check it to see whether overload
2630    resolution is permitted.
2631  */
2632
2633 int
2634 find_overload_match (struct type **arg_types, int nargs, char *name, int method,
2635                      int lax, value_ptr obj, struct symbol *fsym,
2636                      value_ptr *valp, struct symbol **symp, int *staticp)
2637 {
2638   int nparms;
2639   struct type **parm_types;
2640   int champ_nparms = 0;
2641
2642   short oload_champ = -1;       /* Index of best overloaded function */
2643   short oload_ambiguous = 0;    /* Current ambiguity state for overload resolution */
2644   /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs */
2645   short oload_ambig_champ = -1; /* 2nd contender for best match */
2646   short oload_non_standard = 0; /* did we have to use non-standard conversions? */
2647   short oload_incompatible = 0; /* are args supplied incompatible with any function? */
2648
2649   struct badness_vector *bv;    /* A measure of how good an overloaded instance is */
2650   struct badness_vector *oload_champ_bv = NULL;         /* The measure for the current best match */
2651
2652   value_ptr temp = obj;
2653   struct fn_field *fns_ptr = NULL;      /* For methods, the list of overloaded methods */
2654   struct symbol **oload_syms = NULL;    /* For non-methods, the list of overloaded function symbols */
2655   int num_fns = 0;              /* Number of overloaded instances being considered */
2656   struct type *basetype = NULL;
2657   int boffset;
2658   register int jj;
2659   register int ix;
2660
2661   char *obj_type_name = NULL;
2662   char *func_name = NULL;
2663
2664   /* Get the list of overloaded methods or functions */
2665   if (method)
2666     {
2667       int i;
2668       int len;
2669       struct type *domain;
2670       obj_type_name = TYPE_NAME (VALUE_TYPE (obj));
2671       /* Hack: evaluate_subexp_standard often passes in a pointer
2672          value rather than the object itself, so try again */
2673       if ((!obj_type_name || !*obj_type_name) &&
2674           (TYPE_CODE (VALUE_TYPE (obj)) == TYPE_CODE_PTR))
2675         obj_type_name = TYPE_NAME (TYPE_TARGET_TYPE (VALUE_TYPE (obj)));
2676
2677       fns_ptr = value_find_oload_method_list (&temp, name, 0,
2678                                               staticp,
2679                                               &num_fns,
2680                                               &basetype, &boffset);
2681       if (!fns_ptr || !num_fns)
2682         error ("Couldn't find method %s%s%s",
2683                obj_type_name,
2684                (obj_type_name && *obj_type_name) ? "::" : "",
2685                name);
2686       domain = TYPE_DOMAIN_TYPE (fns_ptr[0].type);
2687       len = TYPE_NFN_FIELDS (domain);
2688       /* NOTE: dan/2000-03-10: This stuff is for STABS, which won't
2689          give us the info we need directly in the types. We have to
2690          use the method stub conversion to get it. Be aware that this
2691          is by no means perfect, and if you use STABS, please move to
2692          DWARF-2, or something like it, because trying to improve
2693          overloading using STABS is really a waste of time. */
2694       for (i = 0; i < len; i++)
2695         {
2696           int j;
2697           struct fn_field *f = TYPE_FN_FIELDLIST1 (domain, i);
2698           int len2 = TYPE_FN_FIELDLIST_LENGTH (domain, i);
2699
2700           for (j = 0; j < len2; j++)
2701             {
2702               if (TYPE_FN_FIELD_STUB (f, j) && (!strcmp_iw (TYPE_FN_FIELDLIST_NAME (domain,i),name)))
2703                 check_stub_method (domain, i, j);
2704             }
2705         }
2706     }
2707   else
2708     {
2709       int i = -1;
2710       func_name = cplus_demangle (SYMBOL_NAME (fsym), DMGL_NO_OPTS);
2711
2712       /* If the name is NULL this must be a C-style function.
2713          Just return the same symbol. */
2714       if (!func_name)
2715         {
2716           *symp = fsym;
2717           return 0;
2718         }
2719
2720       oload_syms = make_symbol_overload_list (fsym);
2721       while (oload_syms[++i])
2722         num_fns++;
2723       if (!num_fns)
2724         error ("Couldn't find function %s", func_name);
2725     }
2726
2727   oload_champ_bv = NULL;
2728
2729   /* Consider each candidate in turn */
2730   for (ix = 0; ix < num_fns; ix++)
2731     {
2732       if (method)
2733         {
2734           /* For static member functions, we won't have a this pointer, but nothing
2735              else seems to handle them right now, so we just pretend ourselves */
2736           nparms=0;
2737
2738           if (TYPE_FN_FIELD_ARGS(fns_ptr,ix))
2739             {
2740               while (TYPE_CODE(TYPE_FN_FIELD_ARGS(fns_ptr,ix)[nparms]) != TYPE_CODE_VOID)
2741                 nparms++;
2742             }
2743         }
2744       else
2745         {
2746           /* If it's not a method, this is the proper place */
2747           nparms=TYPE_NFIELDS(SYMBOL_TYPE(oload_syms[ix]));
2748         }
2749
2750       /* Prepare array of parameter types */
2751       parm_types = (struct type **) xmalloc (nparms * (sizeof (struct type *)));
2752       for (jj = 0; jj < nparms; jj++)
2753         parm_types[jj] = (method
2754                           ? (TYPE_FN_FIELD_ARGS (fns_ptr, ix)[jj])
2755                           : TYPE_FIELD_TYPE (SYMBOL_TYPE (oload_syms[ix]), jj));
2756
2757       /* Compare parameter types to supplied argument types */
2758       bv = rank_function (parm_types, nparms, arg_types, nargs);
2759
2760       if (!oload_champ_bv)
2761         {
2762           oload_champ_bv = bv;
2763           oload_champ = 0;
2764           champ_nparms = nparms;
2765         }
2766       else
2767         /* See whether current candidate is better or worse than previous best */
2768         switch (compare_badness (bv, oload_champ_bv))
2769           {
2770           case 0:
2771             oload_ambiguous = 1;        /* top two contenders are equally good */
2772             oload_ambig_champ = ix;
2773             break;
2774           case 1:
2775             oload_ambiguous = 2;        /* incomparable top contenders */
2776             oload_ambig_champ = ix;
2777             break;
2778           case 2:
2779             oload_champ_bv = bv;        /* new champion, record details */
2780             oload_ambiguous = 0;
2781             oload_champ = ix;
2782             oload_ambig_champ = -1;
2783             champ_nparms = nparms;
2784             break;
2785           case 3:
2786           default:
2787             break;
2788           }
2789       xfree (parm_types);
2790       if (overload_debug)
2791         {
2792           if (method)
2793             fprintf_filtered (gdb_stderr,"Overloaded method instance %s, # of parms %d\n", fns_ptr[ix].physname, nparms);
2794           else
2795             fprintf_filtered (gdb_stderr,"Overloaded function instance %s # of parms %d\n", SYMBOL_DEMANGLED_NAME (oload_syms[ix]), nparms);
2796           for (jj = 0; jj < nargs; jj++)
2797             fprintf_filtered (gdb_stderr,"...Badness @ %d : %d\n", jj, bv->rank[jj]);
2798           fprintf_filtered (gdb_stderr,"Overload resolution champion is %d, ambiguous? %d\n", oload_champ, oload_ambiguous);
2799         }
2800     }                           /* end loop over all candidates */
2801   /* NOTE: dan/2000-03-10: Seems to be a better idea to just pick one
2802      if they have the exact same goodness. This is because there is no
2803      way to differentiate based on return type, which we need to in
2804      cases like overloads of .begin() <It's both const and non-const> */
2805 #if 0
2806   if (oload_ambiguous)
2807     {
2808       if (method)
2809         error ("Cannot resolve overloaded method %s%s%s to unique instance; disambiguate by specifying function signature",
2810                obj_type_name,
2811                (obj_type_name && *obj_type_name) ? "::" : "",
2812                name);
2813       else
2814         error ("Cannot resolve overloaded function %s to unique instance; disambiguate by specifying function signature",
2815                func_name);
2816     }
2817 #endif
2818
2819   /* Check how bad the best match is */
2820   for (ix = 1; ix <= nargs; ix++)
2821     {
2822       if (oload_champ_bv->rank[ix] >= 100)
2823         oload_incompatible = 1; /* truly mismatched types */
2824
2825       else if (oload_champ_bv->rank[ix] >= 10)
2826         oload_non_standard = 1; /* non-standard type conversions needed */
2827     }
2828   if (oload_incompatible)
2829     {
2830       if (method)
2831         error ("Cannot resolve method %s%s%s to any overloaded instance",
2832                obj_type_name,
2833                (obj_type_name && *obj_type_name) ? "::" : "",
2834                name);
2835       else
2836         error ("Cannot resolve function %s to any overloaded instance",
2837                func_name);
2838     }
2839   else if (oload_non_standard)
2840     {
2841       if (method)
2842         warning ("Using non-standard conversion to match method %s%s%s to supplied arguments",
2843                  obj_type_name,
2844                  (obj_type_name && *obj_type_name) ? "::" : "",
2845                  name);
2846       else
2847         warning ("Using non-standard conversion to match function %s to supplied arguments",
2848                  func_name);
2849     }
2850
2851   if (method)
2852     {
2853       if (TYPE_FN_FIELD_VIRTUAL_P (fns_ptr, oload_champ))
2854         *valp = value_virtual_fn_field (&temp, fns_ptr, oload_champ, basetype, boffset);
2855       else
2856         *valp = value_fn_field (&temp, fns_ptr, oload_champ, basetype, boffset);
2857     }
2858   else
2859     {
2860       *symp = oload_syms[oload_champ];
2861       xfree (func_name);
2862     }
2863
2864   return oload_incompatible ? 100 : (oload_non_standard ? 10 : 0);
2865 }
2866
2867 /* C++: return 1 is NAME is a legitimate name for the destructor
2868    of type TYPE.  If TYPE does not have a destructor, or
2869    if NAME is inappropriate for TYPE, an error is signaled.  */
2870 int
2871 destructor_name_p (const char *name, const struct type *type)
2872 {
2873   /* destructors are a special case.  */
2874
2875   if (name[0] == '~')
2876     {
2877       char *dname = type_name_no_tag (type);
2878       char *cp = strchr (dname, '<');
2879       unsigned int len;
2880
2881       /* Do not compare the template part for template classes.  */
2882       if (cp == NULL)
2883         len = strlen (dname);
2884       else
2885         len = cp - dname;
2886       if (strlen (name + 1) != len || !STREQN (dname, name + 1, len))
2887         error ("name of destructor must equal name of class");
2888       else
2889         return 1;
2890     }
2891   return 0;
2892 }
2893
2894 /* Helper function for check_field: Given TYPE, a structure/union,
2895    return 1 if the component named NAME from the ultimate
2896    target structure/union is defined, otherwise, return 0. */
2897
2898 static int
2899 check_field_in (register struct type *type, const char *name)
2900 {
2901   register int i;
2902
2903   for (i = TYPE_NFIELDS (type) - 1; i >= TYPE_N_BASECLASSES (type); i--)
2904     {
2905       char *t_field_name = TYPE_FIELD_NAME (type, i);
2906       if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2907         return 1;
2908     }
2909
2910   /* C++: If it was not found as a data field, then try to
2911      return it as a pointer to a method.  */
2912
2913   /* Destructors are a special case.  */
2914   if (destructor_name_p (name, type))
2915     {
2916       int m_index, f_index;
2917
2918       return get_destructor_fn_field (type, &m_index, &f_index);
2919     }
2920
2921   for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
2922     {
2923       if (strcmp_iw (TYPE_FN_FIELDLIST_NAME (type, i), name) == 0)
2924         return 1;
2925     }
2926
2927   for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2928     if (check_field_in (TYPE_BASECLASS (type, i), name))
2929       return 1;
2930
2931   return 0;
2932 }
2933
2934
2935 /* C++: Given ARG1, a value of type (pointer to a)* structure/union,
2936    return 1 if the component named NAME from the ultimate
2937    target structure/union is defined, otherwise, return 0.  */
2938
2939 int
2940 check_field (register value_ptr arg1, const char *name)
2941 {
2942   register struct type *t;
2943
2944   COERCE_ARRAY (arg1);
2945
2946   t = VALUE_TYPE (arg1);
2947
2948   /* Follow pointers until we get to a non-pointer.  */
2949
2950   for (;;)
2951     {
2952       CHECK_TYPEDEF (t);
2953       if (TYPE_CODE (t) != TYPE_CODE_PTR && TYPE_CODE (t) != TYPE_CODE_REF)
2954         break;
2955       t = TYPE_TARGET_TYPE (t);
2956     }
2957
2958   if (TYPE_CODE (t) == TYPE_CODE_MEMBER)
2959     error ("not implemented: member type in check_field");
2960
2961   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2962       && TYPE_CODE (t) != TYPE_CODE_UNION)
2963     error ("Internal error: `this' is not an aggregate");
2964
2965   return check_field_in (t, name);
2966 }
2967
2968 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
2969    return the address of this member as a "pointer to member"
2970    type.  If INTYPE is non-null, then it will be the type
2971    of the member we are looking for.  This will help us resolve
2972    "pointers to member functions".  This function is used
2973    to resolve user expressions of the form "DOMAIN::NAME".  */
2974
2975 value_ptr
2976 value_struct_elt_for_reference (struct type *domain, int offset,
2977                                 struct type *curtype, char *name,
2978                                 struct type *intype)
2979 {
2980   register struct type *t = curtype;
2981   register int i;
2982   value_ptr v;
2983
2984   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
2985       && TYPE_CODE (t) != TYPE_CODE_UNION)
2986     error ("Internal error: non-aggregate type to value_struct_elt_for_reference");
2987
2988   for (i = TYPE_NFIELDS (t) - 1; i >= TYPE_N_BASECLASSES (t); i--)
2989     {
2990       char *t_field_name = TYPE_FIELD_NAME (t, i);
2991
2992       if (t_field_name && STREQ (t_field_name, name))
2993         {
2994           if (TYPE_FIELD_STATIC (t, i))
2995             {
2996               v = value_static_field (t, i);
2997               if (v == NULL)
2998                 error ("Internal error: could not find static variable %s",
2999                        name);
3000               return v;
3001             }
3002           if (TYPE_FIELD_PACKED (t, i))
3003             error ("pointers to bitfield members not allowed");
3004
3005           return value_from_longest
3006             (lookup_reference_type (lookup_member_type (TYPE_FIELD_TYPE (t, i),
3007                                                         domain)),
3008              offset + (LONGEST) (TYPE_FIELD_BITPOS (t, i) >> 3));
3009         }
3010     }
3011
3012   /* C++: If it was not found as a data field, then try to
3013      return it as a pointer to a method.  */
3014
3015   /* Destructors are a special case.  */
3016   if (destructor_name_p (name, t))
3017     {
3018       error ("member pointers to destructors not implemented yet");
3019     }
3020
3021   /* Perform all necessary dereferencing.  */
3022   while (intype && TYPE_CODE (intype) == TYPE_CODE_PTR)
3023     intype = TYPE_TARGET_TYPE (intype);
3024
3025   for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3026     {
3027       char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3028       char dem_opname[64];
3029
3030       if (strncmp (t_field_name, "__", 2) == 0 ||
3031           strncmp (t_field_name, "op", 2) == 0 ||
3032           strncmp (t_field_name, "type", 4) == 0)
3033         {
3034           if (cplus_demangle_opname (t_field_name, dem_opname, DMGL_ANSI))
3035             t_field_name = dem_opname;
3036           else if (cplus_demangle_opname (t_field_name, dem_opname, 0))
3037             t_field_name = dem_opname;
3038         }
3039       if (t_field_name && STREQ (t_field_name, name))
3040         {
3041           int j = TYPE_FN_FIELDLIST_LENGTH (t, i);
3042           struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3043
3044           if (intype == 0 && j > 1)
3045             error ("non-unique member `%s' requires type instantiation", name);
3046           if (intype)
3047             {
3048               while (j--)
3049                 if (TYPE_FN_FIELD_TYPE (f, j) == intype)
3050                   break;
3051               if (j < 0)
3052                 error ("no member function matches that type instantiation");
3053             }
3054           else
3055             j = 0;
3056
3057           if (TYPE_FN_FIELD_STUB (f, j))
3058             check_stub_method (t, i, j);
3059           if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3060             {
3061               return value_from_longest
3062                 (lookup_reference_type
3063                  (lookup_member_type (TYPE_FN_FIELD_TYPE (f, j),
3064                                       domain)),
3065                  (LONGEST) METHOD_PTR_FROM_VOFFSET (TYPE_FN_FIELD_VOFFSET (f, j)));
3066             }
3067           else
3068             {
3069               struct symbol *s = lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3070                                                 0, VAR_NAMESPACE, 0, NULL);
3071               if (s == NULL)
3072                 {
3073                   v = 0;
3074                 }
3075               else
3076                 {
3077                   v = read_var_value (s, 0);
3078 #if 0
3079                   VALUE_TYPE (v) = lookup_reference_type
3080                     (lookup_member_type (TYPE_FN_FIELD_TYPE (f, j),
3081                                          domain));
3082 #endif
3083                 }
3084               return v;
3085             }
3086         }
3087     }
3088   for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3089     {
3090       value_ptr v;
3091       int base_offset;
3092
3093       if (BASETYPE_VIA_VIRTUAL (t, i))
3094         base_offset = 0;
3095       else
3096         base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3097       v = value_struct_elt_for_reference (domain,
3098                                           offset + base_offset,
3099                                           TYPE_BASECLASS (t, i),
3100                                           name,
3101                                           intype);
3102       if (v)
3103         return v;
3104     }
3105   return 0;
3106 }
3107
3108
3109 /* Find the real run-time type of a value using RTTI.
3110  * V is a pointer to the value.
3111  * A pointer to the struct type entry of the run-time type
3112  * is returneed.
3113  * FULL is a flag that is set only if the value V includes
3114  * the entire contents of an object of the RTTI type.
3115  * TOP is the offset to the top of the enclosing object of
3116  * the real run-time type.  This offset may be for the embedded
3117  * object, or for the enclosing object of V.
3118  * USING_ENC is the flag that distinguishes the two cases.
3119  * If it is 1, then the offset is for the enclosing object,
3120  * otherwise for the embedded object.
3121  *
3122  */
3123
3124 struct type *
3125 value_rtti_type (value_ptr v, int *full, int *top, int *using_enc)
3126 {
3127   struct type *known_type;
3128   struct type *rtti_type;
3129   CORE_ADDR coreptr;
3130   value_ptr vp;
3131   int using_enclosing = 0;
3132   long top_offset = 0;
3133   char rtti_type_name[256];
3134
3135   if (full)
3136     *full = 0;
3137   if (top)
3138     *top = -1;
3139   if (using_enc)
3140     *using_enc = 0;
3141
3142   /* Get declared type */
3143   known_type = VALUE_TYPE (v);
3144   CHECK_TYPEDEF (known_type);
3145   /* RTTI works only or class objects */
3146   if (TYPE_CODE (known_type) != TYPE_CODE_CLASS)
3147     return NULL;
3148   if (TYPE_HAS_VTABLE(known_type))
3149     {
3150       /* If neither the declared type nor the enclosing type of the
3151        * value structure has a HP ANSI C++ style virtual table,
3152        * we can't do anything. */
3153       if (!TYPE_HAS_VTABLE (known_type))
3154         {
3155           known_type = VALUE_ENCLOSING_TYPE (v);
3156           CHECK_TYPEDEF (known_type);
3157           if ((TYPE_CODE (known_type) != TYPE_CODE_CLASS) ||
3158               !TYPE_HAS_VTABLE (known_type))
3159             return NULL;                /* No RTTI, or not HP-compiled types */
3160           CHECK_TYPEDEF (known_type);
3161           using_enclosing = 1;
3162         }
3163
3164       if (using_enclosing && using_enc)
3165         *using_enc = 1;
3166
3167       /* First get the virtual table address */
3168       coreptr = *(CORE_ADDR *) ((VALUE_CONTENTS_ALL (v))
3169                                 + VALUE_OFFSET (v)
3170                                 + (using_enclosing ? 0 : VALUE_EMBEDDED_OFFSET (v)));
3171       if (coreptr == 0)
3172         return NULL;            /* return silently -- maybe called on gdb-generated value */
3173
3174       /* Fetch the top offset of the object */
3175       /* FIXME possible 32x64 problem with pointer size & arithmetic */
3176       vp = value_at (builtin_type_int,
3177                      coreptr + 4 * HP_ACC_TOP_OFFSET_OFFSET,
3178                      VALUE_BFD_SECTION (v));
3179       top_offset = value_as_long (vp);
3180       if (top)
3181         *top = top_offset;
3182
3183       /* Fetch the typeinfo pointer */
3184       /* FIXME possible 32x64 problem with pointer size & arithmetic */
3185       vp = value_at (builtin_type_int, coreptr + 4 * HP_ACC_TYPEINFO_OFFSET, VALUE_BFD_SECTION (v));
3186       /* Indirect through the typeinfo pointer and retrieve the pointer
3187        * to the string name */
3188       coreptr = *(CORE_ADDR *) (VALUE_CONTENTS (vp));
3189       if (!coreptr)
3190         error ("Retrieved null typeinfo pointer in trying to determine run-time type");
3191       vp = value_at (builtin_type_int, coreptr + 4, VALUE_BFD_SECTION (v));             /* 4 -> offset of name field */
3192       /* FIXME possible 32x64 problem */
3193
3194       coreptr = *(CORE_ADDR *) (VALUE_CONTENTS (vp));
3195
3196       read_memory_string (coreptr, rtti_type_name, 256);
3197
3198       if (strlen (rtti_type_name) == 0)
3199         error ("Retrieved null type name from typeinfo");
3200
3201       /* search for type */
3202       rtti_type = lookup_typename (rtti_type_name, (struct block *) 0, 1);
3203
3204       if (!rtti_type)
3205         error ("Could not find run-time type: invalid type name %s in typeinfo??", rtti_type_name);
3206       CHECK_TYPEDEF (rtti_type);
3207 #if 0
3208       printf ("RTTI type name %s, tag %s, full? %d\n", TYPE_NAME (rtti_type), TYPE_TAG_NAME (rtti_type), full ? *full : -1);
3209 #endif
3210       /* Check whether we have the entire object */
3211       if (full                  /* Non-null pointer passed */
3212           &&
3213           /* Either we checked on the whole object in hand and found the
3214              top offset to be zero */
3215           (((top_offset == 0) &&
3216             using_enclosing &&
3217             TYPE_LENGTH (known_type) == TYPE_LENGTH (rtti_type))
3218            ||
3219            /* Or we checked on the embedded object and top offset was the
3220               same as the embedded offset */
3221            ((top_offset == VALUE_EMBEDDED_OFFSET (v)) &&
3222             !using_enclosing &&
3223             TYPE_LENGTH (VALUE_ENCLOSING_TYPE (v)) == TYPE_LENGTH (rtti_type))))
3224
3225         *full = 1;
3226     }
3227   else
3228     /*
3229       Right now this is G++ RTTI. Plan on this changing in the
3230       future as i get around to setting the vtables properly for G++
3231       compiled stuff. Also, i'll be using the type info functions,
3232       which are always right. Deal with it until then.
3233     */
3234     {
3235       CORE_ADDR vtbl;
3236       struct minimal_symbol *minsym;
3237       struct symbol *sym;
3238       char *demangled_name;
3239       struct type *btype;
3240       /* If the type has no vptr fieldno, try to get it filled in */
3241       if (TYPE_VPTR_FIELDNO(known_type) < 0)
3242         fill_in_vptr_fieldno(known_type);
3243
3244       /* If we still can't find one, give up */
3245       if (TYPE_VPTR_FIELDNO(known_type) < 0)
3246         return NULL;
3247
3248       /* Make sure our basetype and known type match, otherwise, cast
3249          so we can get at the vtable properly.
3250       */
3251       btype = TYPE_VPTR_BASETYPE (known_type);
3252       CHECK_TYPEDEF (btype);
3253       if (btype != known_type )
3254         {
3255           v = value_cast (btype, v);
3256           if (using_enc)
3257             *using_enc=1;
3258         }
3259       /*
3260         We can't use value_ind here, because it would want to use RTTI, and
3261         we'd waste a bunch of time figuring out we already know the type.
3262         Besides, we don't care about the type, just the actual pointer
3263       */
3264       if (VALUE_ADDRESS (value_field (v, TYPE_VPTR_FIELDNO (known_type))) == 0)
3265         return NULL;
3266
3267       /*
3268          If we are enclosed by something that isn't us, adjust the
3269          address properly and set using_enclosing.
3270       */
3271       if (VALUE_ENCLOSING_TYPE(v) != VALUE_TYPE(v))
3272         {
3273           value_ptr tempval;
3274           tempval=value_field(v,TYPE_VPTR_FIELDNO(known_type));
3275           VALUE_ADDRESS(tempval)+=(TYPE_BASECLASS_BITPOS(known_type,TYPE_VPTR_FIELDNO(known_type))/8);
3276           vtbl=value_as_pointer(tempval);
3277           using_enclosing=1;
3278         }
3279       else
3280         {
3281           vtbl=value_as_pointer(value_field(v,TYPE_VPTR_FIELDNO(known_type)));
3282           using_enclosing=0;
3283         }
3284
3285       /* Try to find a symbol that is the vtable */
3286       minsym=lookup_minimal_symbol_by_pc(vtbl);
3287       if (minsym==NULL || (demangled_name=SYMBOL_NAME(minsym))==NULL || !VTBL_PREFIX_P(demangled_name))
3288         return NULL;
3289
3290       /* If we just skip the prefix, we get screwed by namespaces */
3291       demangled_name=cplus_demangle(demangled_name,DMGL_PARAMS|DMGL_ANSI);
3292       *(strchr(demangled_name,' '))=0;
3293
3294       /* Lookup the type for the name */
3295       rtti_type=lookup_typename(demangled_name, (struct block *)0,1);
3296
3297       if (rtti_type==NULL)
3298         return NULL;
3299
3300       if (TYPE_N_BASECLASSES(rtti_type) > 1 &&  full && (*full) != 1)
3301         {
3302           if (top)
3303             *top=TYPE_BASECLASS_BITPOS(rtti_type,TYPE_VPTR_FIELDNO(rtti_type))/8;
3304           if (top && ((*top) >0))
3305             {
3306               if (TYPE_LENGTH(rtti_type) > TYPE_LENGTH(known_type))
3307                 {
3308                   if (full)
3309                     *full=0;
3310                 }
3311               else
3312                 {
3313                   if (full)
3314                     *full=1;
3315                 }
3316             }
3317         }
3318       else
3319         {
3320           if (full)
3321             *full=1;
3322         }
3323       if (using_enc)
3324         *using_enc=using_enclosing;
3325     }
3326   return rtti_type;
3327 }
3328
3329 /* Given a pointer value V, find the real (RTTI) type
3330    of the object it points to.
3331    Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3332    and refer to the values computed for the object pointed to. */
3333
3334 struct type *
3335 value_rtti_target_type (value_ptr v, int *full, int *top, int *using_enc)
3336 {
3337   value_ptr target;
3338
3339   target = value_ind (v);
3340
3341   return value_rtti_type (target, full, top, using_enc);
3342 }
3343
3344 /* Given a value pointed to by ARGP, check its real run-time type, and
3345    if that is different from the enclosing type, create a new value
3346    using the real run-time type as the enclosing type (and of the same
3347    type as ARGP) and return it, with the embedded offset adjusted to
3348    be the correct offset to the enclosed object
3349    RTYPE is the type, and XFULL, XTOP, and XUSING_ENC are the other
3350    parameters, computed by value_rtti_type(). If these are available,
3351    they can be supplied and a second call to value_rtti_type() is avoided.
3352    (Pass RTYPE == NULL if they're not available */
3353
3354 value_ptr
3355 value_full_object (value_ptr argp, struct type *rtype, int xfull, int xtop,
3356                    int xusing_enc)
3357 {
3358   struct type *real_type;
3359   int full = 0;
3360   int top = -1;
3361   int using_enc = 0;
3362   value_ptr new_val;
3363
3364   if (rtype)
3365     {
3366       real_type = rtype;
3367       full = xfull;
3368       top = xtop;
3369       using_enc = xusing_enc;
3370     }
3371   else
3372     real_type = value_rtti_type (argp, &full, &top, &using_enc);
3373
3374   /* If no RTTI data, or if object is already complete, do nothing */
3375   if (!real_type || real_type == VALUE_ENCLOSING_TYPE (argp))
3376     return argp;
3377
3378   /* If we have the full object, but for some reason the enclosing
3379      type is wrong, set it *//* pai: FIXME -- sounds iffy */
3380   if (full)
3381     {
3382       VALUE_ENCLOSING_TYPE (argp) = real_type;
3383       return argp;
3384     }
3385
3386   /* Check if object is in memory */
3387   if (VALUE_LVAL (argp) != lval_memory)
3388     {
3389       warning ("Couldn't retrieve complete object of RTTI type %s; object may be in register(s).", TYPE_NAME (real_type));
3390
3391       return argp;
3392     }
3393
3394   /* All other cases -- retrieve the complete object */
3395   /* Go back by the computed top_offset from the beginning of the object,
3396      adjusting for the embedded offset of argp if that's what value_rtti_type
3397      used for its computation. */
3398   new_val = value_at_lazy (real_type, VALUE_ADDRESS (argp) - top +
3399                            (using_enc ? 0 : VALUE_EMBEDDED_OFFSET (argp)),
3400                            VALUE_BFD_SECTION (argp));
3401   VALUE_TYPE (new_val) = VALUE_TYPE (argp);
3402   VALUE_EMBEDDED_OFFSET (new_val) = using_enc ? top + VALUE_EMBEDDED_OFFSET (argp) : top;
3403   return new_val;
3404 }
3405
3406
3407
3408
3409 /* C++: return the value of the class instance variable, if one exists.
3410    Flag COMPLAIN signals an error if the request is made in an
3411    inappropriate context.  */
3412
3413 value_ptr
3414 value_of_this (int complain)
3415 {
3416   struct symbol *func, *sym;
3417   struct block *b;
3418   int i;
3419   static const char funny_this[] = "this";
3420   value_ptr this;
3421
3422   if (selected_frame == 0)
3423     {
3424       if (complain)
3425         error ("no frame selected");
3426       else
3427         return 0;
3428     }
3429
3430   func = get_frame_function (selected_frame);
3431   if (!func)
3432     {
3433       if (complain)
3434         error ("no `this' in nameless context");
3435       else
3436         return 0;
3437     }
3438
3439   b = SYMBOL_BLOCK_VALUE (func);
3440   i = BLOCK_NSYMS (b);
3441   if (i <= 0)
3442     {
3443       if (complain)
3444         error ("no args, no `this'");
3445       else
3446         return 0;
3447     }
3448
3449   /* Calling lookup_block_symbol is necessary to get the LOC_REGISTER
3450      symbol instead of the LOC_ARG one (if both exist).  */
3451   sym = lookup_block_symbol (b, funny_this, VAR_NAMESPACE);
3452   if (sym == NULL)
3453     {
3454       if (complain)
3455         error ("current stack frame not in method");
3456       else
3457         return NULL;
3458     }
3459
3460   this = read_var_value (sym, selected_frame);
3461   if (this == 0 && complain)
3462     error ("`this' argument at unknown address");
3463   return this;
3464 }
3465
3466 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH elements
3467    long, starting at LOWBOUND.  The result has the same lower bound as
3468    the original ARRAY.  */
3469
3470 value_ptr
3471 value_slice (value_ptr array, int lowbound, int length)
3472 {
3473   struct type *slice_range_type, *slice_type, *range_type;
3474   LONGEST lowerbound, upperbound, offset;
3475   value_ptr slice;
3476   struct type *array_type;
3477   array_type = check_typedef (VALUE_TYPE (array));
3478   COERCE_VARYING_ARRAY (array, array_type);
3479   if (TYPE_CODE (array_type) != TYPE_CODE_ARRAY
3480       && TYPE_CODE (array_type) != TYPE_CODE_STRING
3481       && TYPE_CODE (array_type) != TYPE_CODE_BITSTRING)
3482     error ("cannot take slice of non-array");
3483   range_type = TYPE_INDEX_TYPE (array_type);
3484   if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
3485     error ("slice from bad array or bitstring");
3486   if (lowbound < lowerbound || length < 0
3487       || lowbound + length - 1 > upperbound
3488   /* Chill allows zero-length strings but not arrays. */
3489       || (current_language->la_language == language_chill
3490           && length == 0 && TYPE_CODE (array_type) == TYPE_CODE_ARRAY))
3491     error ("slice out of range");
3492   /* FIXME-type-allocation: need a way to free this type when we are
3493      done with it.  */
3494   slice_range_type = create_range_type ((struct type *) NULL,
3495                                         TYPE_TARGET_TYPE (range_type),
3496                                         lowbound, lowbound + length - 1);
3497   if (TYPE_CODE (array_type) == TYPE_CODE_BITSTRING)
3498     {
3499       int i;
3500       slice_type = create_set_type ((struct type *) NULL, slice_range_type);
3501       TYPE_CODE (slice_type) = TYPE_CODE_BITSTRING;
3502       slice = value_zero (slice_type, not_lval);
3503       for (i = 0; i < length; i++)
3504         {
3505           int element = value_bit_index (array_type,
3506                                          VALUE_CONTENTS (array),
3507                                          lowbound + i);
3508           if (element < 0)
3509             error ("internal error accessing bitstring");
3510           else if (element > 0)
3511             {
3512               int j = i % TARGET_CHAR_BIT;
3513               if (BITS_BIG_ENDIAN)
3514                 j = TARGET_CHAR_BIT - 1 - j;
3515               VALUE_CONTENTS_RAW (slice)[i / TARGET_CHAR_BIT] |= (1 << j);
3516             }
3517         }
3518       /* We should set the address, bitssize, and bitspos, so the clice
3519          can be used on the LHS, but that may require extensions to
3520          value_assign.  For now, just leave as a non_lval.  FIXME.  */
3521     }
3522   else
3523     {
3524       struct type *element_type = TYPE_TARGET_TYPE (array_type);
3525       offset
3526         = (lowbound - lowerbound) * TYPE_LENGTH (check_typedef (element_type));
3527       slice_type = create_array_type ((struct type *) NULL, element_type,
3528                                       slice_range_type);
3529       TYPE_CODE (slice_type) = TYPE_CODE (array_type);
3530       slice = allocate_value (slice_type);
3531       if (VALUE_LAZY (array))
3532         VALUE_LAZY (slice) = 1;
3533       else
3534         memcpy (VALUE_CONTENTS (slice), VALUE_CONTENTS (array) + offset,
3535                 TYPE_LENGTH (slice_type));
3536       if (VALUE_LVAL (array) == lval_internalvar)
3537         VALUE_LVAL (slice) = lval_internalvar_component;
3538       else
3539         VALUE_LVAL (slice) = VALUE_LVAL (array);
3540       VALUE_ADDRESS (slice) = VALUE_ADDRESS (array);
3541       VALUE_OFFSET (slice) = VALUE_OFFSET (array) + offset;
3542     }
3543   return slice;
3544 }
3545
3546 /* Assuming chill_varying_type (VARRAY) is true, return an equivalent
3547    value as a fixed-length array. */
3548
3549 value_ptr
3550 varying_to_slice (value_ptr varray)
3551 {
3552   struct type *vtype = check_typedef (VALUE_TYPE (varray));
3553   LONGEST length = unpack_long (TYPE_FIELD_TYPE (vtype, 0),
3554                                 VALUE_CONTENTS (varray)
3555                                 + TYPE_FIELD_BITPOS (vtype, 0) / 8);
3556   return value_slice (value_primitive_field (varray, 0, 1, vtype), 0, length);
3557 }
3558
3559 /* Create a value for a FORTRAN complex number.  Currently most of
3560    the time values are coerced to COMPLEX*16 (i.e. a complex number
3561    composed of 2 doubles.  This really should be a smarter routine
3562    that figures out precision inteligently as opposed to assuming
3563    doubles. FIXME: fmb */
3564
3565 value_ptr
3566 value_literal_complex (value_ptr arg1, value_ptr arg2, struct type *type)
3567 {
3568   register value_ptr val;
3569   struct type *real_type = TYPE_TARGET_TYPE (type);
3570
3571   val = allocate_value (type);
3572   arg1 = value_cast (real_type, arg1);
3573   arg2 = value_cast (real_type, arg2);
3574
3575   memcpy (VALUE_CONTENTS_RAW (val),
3576           VALUE_CONTENTS (arg1), TYPE_LENGTH (real_type));
3577   memcpy (VALUE_CONTENTS_RAW (val) + TYPE_LENGTH (real_type),
3578           VALUE_CONTENTS (arg2), TYPE_LENGTH (real_type));
3579   return val;
3580 }
3581
3582 /* Cast a value into the appropriate complex data type. */
3583
3584 static value_ptr
3585 cast_into_complex (struct type *type, register value_ptr val)
3586 {
3587   struct type *real_type = TYPE_TARGET_TYPE (type);
3588   if (TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_COMPLEX)
3589     {
3590       struct type *val_real_type = TYPE_TARGET_TYPE (VALUE_TYPE (val));
3591       value_ptr re_val = allocate_value (val_real_type);
3592       value_ptr im_val = allocate_value (val_real_type);
3593
3594       memcpy (VALUE_CONTENTS_RAW (re_val),
3595               VALUE_CONTENTS (val), TYPE_LENGTH (val_real_type));
3596       memcpy (VALUE_CONTENTS_RAW (im_val),
3597               VALUE_CONTENTS (val) + TYPE_LENGTH (val_real_type),
3598               TYPE_LENGTH (val_real_type));
3599
3600       return value_literal_complex (re_val, im_val, type);
3601     }
3602   else if (TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FLT
3603            || TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_INT)
3604     return value_literal_complex (val, value_zero (real_type, not_lval), type);
3605   else
3606     error ("cannot cast non-number to complex");
3607 }
3608
3609 void
3610 _initialize_valops (void)
3611 {
3612 #if 0
3613   add_show_from_set
3614     (add_set_cmd ("abandon", class_support, var_boolean, (char *) &auto_abandon,
3615                   "Set automatic abandonment of expressions upon failure.",
3616                   &setlist),
3617      &showlist);
3618 #endif
3619
3620   add_show_from_set
3621     (add_set_cmd ("overload-resolution", class_support, var_boolean, (char *) &overload_resolution,
3622                   "Set overload resolution in evaluating C++ functions.",
3623                   &setlist),
3624      &showlist);
3625   overload_resolution = 1;
3626
3627   add_show_from_set (
3628   add_set_cmd ("unwindonsignal", no_class, var_boolean,
3629                (char *) &unwind_on_signal_p,
3630 "Set unwinding of stack if a signal is received while in a call dummy.\n\
3631 The unwindonsignal lets the user determine what gdb should do if a signal\n\
3632 is received while in a function called from gdb (call dummy).  If set, gdb\n\
3633 unwinds the stack and restore the context to what as it was before the call.\n\
3634 The default is to stop in the frame where the signal was received.", &setlist),
3635                      &showlist);
3636 }