GDB (API)
/home/stan/gdb/src/gdb/ada-lang.c
Go to the documentation of this file.
00001 /* Ada language support routines for GDB, the GNU debugger.
00002 
00003    Copyright (C) 1992-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 
00021 #include "defs.h"
00022 #include <stdio.h>
00023 #include "gdb_string.h"
00024 #include <ctype.h>
00025 #include <stdarg.h>
00026 #include "demangle.h"
00027 #include "gdb_regex.h"
00028 #include "frame.h"
00029 #include "symtab.h"
00030 #include "gdbtypes.h"
00031 #include "gdbcmd.h"
00032 #include "expression.h"
00033 #include "parser-defs.h"
00034 #include "language.h"
00035 #include "c-lang.h"
00036 #include "inferior.h"
00037 #include "symfile.h"
00038 #include "objfiles.h"
00039 #include "breakpoint.h"
00040 #include "gdbcore.h"
00041 #include "hashtab.h"
00042 #include "gdb_obstack.h"
00043 #include "ada-lang.h"
00044 #include "completer.h"
00045 #include "gdb_stat.h"
00046 #ifdef UI_OUT
00047 #include "ui-out.h"
00048 #endif
00049 #include "block.h"
00050 #include "infcall.h"
00051 #include "dictionary.h"
00052 #include "exceptions.h"
00053 #include "annotate.h"
00054 #include "valprint.h"
00055 #include "source.h"
00056 #include "observer.h"
00057 #include "vec.h"
00058 #include "stack.h"
00059 #include "gdb_vecs.h"
00060 #include "typeprint.h"
00061 
00062 #include "psymtab.h"
00063 #include "value.h"
00064 #include "mi/mi-common.h"
00065 #include "arch-utils.h"
00066 #include "exceptions.h"
00067 #include "cli/cli-utils.h"
00068 
00069 /* Define whether or not the C operator '/' truncates towards zero for
00070    differently signed operands (truncation direction is undefined in C).
00071    Copied from valarith.c.  */
00072 
00073 #ifndef TRUNCATION_TOWARDS_ZERO
00074 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
00075 #endif
00076 
00077 static struct type *desc_base_type (struct type *);
00078 
00079 static struct type *desc_bounds_type (struct type *);
00080 
00081 static struct value *desc_bounds (struct value *);
00082 
00083 static int fat_pntr_bounds_bitpos (struct type *);
00084 
00085 static int fat_pntr_bounds_bitsize (struct type *);
00086 
00087 static struct type *desc_data_target_type (struct type *);
00088 
00089 static struct value *desc_data (struct value *);
00090 
00091 static int fat_pntr_data_bitpos (struct type *);
00092 
00093 static int fat_pntr_data_bitsize (struct type *);
00094 
00095 static struct value *desc_one_bound (struct value *, int, int);
00096 
00097 static int desc_bound_bitpos (struct type *, int, int);
00098 
00099 static int desc_bound_bitsize (struct type *, int, int);
00100 
00101 static struct type *desc_index_type (struct type *, int);
00102 
00103 static int desc_arity (struct type *);
00104 
00105 static int ada_type_match (struct type *, struct type *, int);
00106 
00107 static int ada_args_match (struct symbol *, struct value **, int);
00108 
00109 static int full_match (const char *, const char *);
00110 
00111 static struct value *make_array_descriptor (struct type *, struct value *);
00112 
00113 static void ada_add_block_symbols (struct obstack *,
00114                                    struct block *, const char *,
00115                                    domain_enum, struct objfile *, int);
00116 
00117 static int is_nonfunction (struct ada_symbol_info *, int);
00118 
00119 static void add_defn_to_vec (struct obstack *, struct symbol *,
00120                              struct block *);
00121 
00122 static int num_defns_collected (struct obstack *);
00123 
00124 static struct ada_symbol_info *defns_collected (struct obstack *, int);
00125 
00126 static struct value *resolve_subexp (struct expression **, int *, int,
00127                                      struct type *);
00128 
00129 static void replace_operator_with_call (struct expression **, int, int, int,
00130                                         struct symbol *, const struct block *);
00131 
00132 static int possible_user_operator_p (enum exp_opcode, struct value **);
00133 
00134 static char *ada_op_name (enum exp_opcode);
00135 
00136 static const char *ada_decoded_op_name (enum exp_opcode);
00137 
00138 static int numeric_type_p (struct type *);
00139 
00140 static int integer_type_p (struct type *);
00141 
00142 static int scalar_type_p (struct type *);
00143 
00144 static int discrete_type_p (struct type *);
00145 
00146 static enum ada_renaming_category parse_old_style_renaming (struct type *,
00147                                                             const char **,
00148                                                             int *,
00149                                                             const char **);
00150 
00151 static struct symbol *find_old_style_renaming_symbol (const char *,
00152                                                       const struct block *);
00153 
00154 static struct type *ada_lookup_struct_elt_type (struct type *, char *,
00155                                                 int, int, int *);
00156 
00157 static struct value *evaluate_subexp_type (struct expression *, int *);
00158 
00159 static struct type *ada_find_parallel_type_with_name (struct type *,
00160                                                       const char *);
00161 
00162 static int is_dynamic_field (struct type *, int);
00163 
00164 static struct type *to_fixed_variant_branch_type (struct type *,
00165                                                   const gdb_byte *,
00166                                                   CORE_ADDR, struct value *);
00167 
00168 static struct type *to_fixed_array_type (struct type *, struct value *, int);
00169 
00170 static struct type *to_fixed_range_type (struct type *, struct value *);
00171 
00172 static struct type *to_static_fixed_type (struct type *);
00173 static struct type *static_unwrap_type (struct type *type);
00174 
00175 static struct value *unwrap_value (struct value *);
00176 
00177 static struct type *constrained_packed_array_type (struct type *, long *);
00178 
00179 static struct type *decode_constrained_packed_array_type (struct type *);
00180 
00181 static long decode_packed_array_bitsize (struct type *);
00182 
00183 static struct value *decode_constrained_packed_array (struct value *);
00184 
00185 static int ada_is_packed_array_type  (struct type *);
00186 
00187 static int ada_is_unconstrained_packed_array_type (struct type *);
00188 
00189 static struct value *value_subscript_packed (struct value *, int,
00190                                              struct value **);
00191 
00192 static void move_bits (gdb_byte *, int, const gdb_byte *, int, int, int);
00193 
00194 static struct value *coerce_unspec_val_to_type (struct value *,
00195                                                 struct type *);
00196 
00197 static struct value *get_var_value (char *, char *);
00198 
00199 static int lesseq_defined_than (struct symbol *, struct symbol *);
00200 
00201 static int equiv_types (struct type *, struct type *);
00202 
00203 static int is_name_suffix (const char *);
00204 
00205 static int advance_wild_match (const char **, const char *, int);
00206 
00207 static int wild_match (const char *, const char *);
00208 
00209 static struct value *ada_coerce_ref (struct value *);
00210 
00211 static LONGEST pos_atr (struct value *);
00212 
00213 static struct value *value_pos_atr (struct type *, struct value *);
00214 
00215 static struct value *value_val_atr (struct type *, struct value *);
00216 
00217 static struct symbol *standard_lookup (const char *, const struct block *,
00218                                        domain_enum);
00219 
00220 static struct value *ada_search_struct_field (char *, struct value *, int,
00221                                               struct type *);
00222 
00223 static struct value *ada_value_primitive_field (struct value *, int, int,
00224                                                 struct type *);
00225 
00226 static int find_struct_field (const char *, struct type *, int,
00227                               struct type **, int *, int *, int *, int *);
00228 
00229 static struct value *ada_to_fixed_value_create (struct type *, CORE_ADDR,
00230                                                 struct value *);
00231 
00232 static int ada_resolve_function (struct ada_symbol_info *, int,
00233                                  struct value **, int, const char *,
00234                                  struct type *);
00235 
00236 static int ada_is_direct_array_type (struct type *);
00237 
00238 static void ada_language_arch_info (struct gdbarch *,
00239                                     struct language_arch_info *);
00240 
00241 static void check_size (const struct type *);
00242 
00243 static struct value *ada_index_struct_field (int, struct value *, int,
00244                                              struct type *);
00245 
00246 static struct value *assign_aggregate (struct value *, struct value *, 
00247                                        struct expression *,
00248                                        int *, enum noside);
00249 
00250 static void aggregate_assign_from_choices (struct value *, struct value *, 
00251                                            struct expression *,
00252                                            int *, LONGEST *, int *,
00253                                            int, LONGEST, LONGEST);
00254 
00255 static void aggregate_assign_positional (struct value *, struct value *,
00256                                          struct expression *,
00257                                          int *, LONGEST *, int *, int,
00258                                          LONGEST, LONGEST);
00259 
00260 
00261 static void aggregate_assign_others (struct value *, struct value *,
00262                                      struct expression *,
00263                                      int *, LONGEST *, int, LONGEST, LONGEST);
00264 
00265 
00266 static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);
00267 
00268 
00269 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
00270                                           int *, enum noside);
00271 
00272 static void ada_forward_operator_length (struct expression *, int, int *,
00273                                          int *);
00274 
00275 static struct type *ada_find_any_type (const char *name);
00276 
00277 
00278 
00279 /* Maximum-sized dynamic type.  */
00280 static unsigned int varsize_limit;
00281 
00282 /* FIXME: brobecker/2003-09-17: No longer a const because it is
00283    returned by a function that does not return a const char *.  */
00284 static char *ada_completer_word_break_characters =
00285 #ifdef VMS
00286   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
00287 #else
00288   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
00289 #endif
00290 
00291 /* The name of the symbol to use to get the name of the main subprogram.  */
00292 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
00293   = "__gnat_ada_main_program_name";
00294 
00295 /* Limit on the number of warnings to raise per expression evaluation.  */
00296 static int warning_limit = 2;
00297 
00298 /* Number of warning messages issued; reset to 0 by cleanups after
00299    expression evaluation.  */
00300 static int warnings_issued = 0;
00301 
00302 static const char *known_runtime_file_name_patterns[] = {
00303   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
00304 };
00305 
00306 static const char *known_auxiliary_function_name_patterns[] = {
00307   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
00308 };
00309 
00310 /* Space for allocating results of ada_lookup_symbol_list.  */
00311 static struct obstack symbol_list_obstack;
00312 
00313                         /* Inferior-specific data.  */
00314 
00315 /* Per-inferior data for this module.  */
00316 
00317 struct ada_inferior_data
00318 {
00319   /* The ada__tags__type_specific_data type, which is used when decoding
00320      tagged types.  With older versions of GNAT, this type was directly
00321      accessible through a component ("tsd") in the object tag.  But this
00322      is no longer the case, so we cache it for each inferior.  */
00323   struct type *tsd_type;
00324 
00325   /* The exception_support_info data.  This data is used to determine
00326      how to implement support for Ada exception catchpoints in a given
00327      inferior.  */
00328   const struct exception_support_info *exception_info;
00329 };
00330 
00331 /* Our key to this module's inferior data.  */
00332 static const struct inferior_data *ada_inferior_data;
00333 
00334 /* A cleanup routine for our inferior data.  */
00335 static void
00336 ada_inferior_data_cleanup (struct inferior *inf, void *arg)
00337 {
00338   struct ada_inferior_data *data;
00339 
00340   data = inferior_data (inf, ada_inferior_data);
00341   if (data != NULL)
00342     xfree (data);
00343 }
00344 
00345 /* Return our inferior data for the given inferior (INF).
00346 
00347    This function always returns a valid pointer to an allocated
00348    ada_inferior_data structure.  If INF's inferior data has not
00349    been previously set, this functions creates a new one with all
00350    fields set to zero, sets INF's inferior to it, and then returns
00351    a pointer to that newly allocated ada_inferior_data.  */
00352 
00353 static struct ada_inferior_data *
00354 get_ada_inferior_data (struct inferior *inf)
00355 {
00356   struct ada_inferior_data *data;
00357 
00358   data = inferior_data (inf, ada_inferior_data);
00359   if (data == NULL)
00360     {
00361       data = XZALLOC (struct ada_inferior_data);
00362       set_inferior_data (inf, ada_inferior_data, data);
00363     }
00364 
00365   return data;
00366 }
00367 
00368 /* Perform all necessary cleanups regarding our module's inferior data
00369    that is required after the inferior INF just exited.  */
00370 
00371 static void
00372 ada_inferior_exit (struct inferior *inf)
00373 {
00374   ada_inferior_data_cleanup (inf, NULL);
00375   set_inferior_data (inf, ada_inferior_data, NULL);
00376 }
00377 
00378                         /* Utilities */
00379 
00380 /* If TYPE is a TYPE_CODE_TYPEDEF type, return the target type after
00381    all typedef layers have been peeled.  Otherwise, return TYPE.
00382 
00383    Normally, we really expect a typedef type to only have 1 typedef layer.
00384    In other words, we really expect the target type of a typedef type to be
00385    a non-typedef type.  This is particularly true for Ada units, because
00386    the language does not have a typedef vs not-typedef distinction.
00387    In that respect, the Ada compiler has been trying to eliminate as many
00388    typedef definitions in the debugging information, since they generally
00389    do not bring any extra information (we still use typedef under certain
00390    circumstances related mostly to the GNAT encoding).
00391 
00392    Unfortunately, we have seen situations where the debugging information
00393    generated by the compiler leads to such multiple typedef layers.  For
00394    instance, consider the following example with stabs:
00395 
00396      .stabs  "pck__float_array___XUP:Tt(0,46)=s16P_ARRAY:(0,47)=[...]"[...]
00397      .stabs  "pck__float_array___XUP:t(0,36)=(0,46)",128,0,6,0
00398 
00399    This is an error in the debugging information which causes type
00400    pck__float_array___XUP to be defined twice, and the second time,
00401    it is defined as a typedef of a typedef.
00402 
00403    This is on the fringe of legality as far as debugging information is
00404    concerned, and certainly unexpected.  But it is easy to handle these
00405    situations correctly, so we can afford to be lenient in this case.  */
00406 
00407 static struct type *
00408 ada_typedef_target_type (struct type *type)
00409 {
00410   while (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
00411     type = TYPE_TARGET_TYPE (type);
00412   return type;
00413 }
00414 
00415 /* Given DECODED_NAME a string holding a symbol name in its
00416    decoded form (ie using the Ada dotted notation), returns
00417    its unqualified name.  */
00418 
00419 static const char *
00420 ada_unqualified_name (const char *decoded_name)
00421 {
00422   const char *result = strrchr (decoded_name, '.');
00423 
00424   if (result != NULL)
00425     result++;                   /* Skip the dot...  */
00426   else
00427     result = decoded_name;
00428 
00429   return result;
00430 }
00431 
00432 /* Return a string starting with '<', followed by STR, and '>'.
00433    The result is good until the next call.  */
00434 
00435 static char *
00436 add_angle_brackets (const char *str)
00437 {
00438   static char *result = NULL;
00439 
00440   xfree (result);
00441   result = xstrprintf ("<%s>", str);
00442   return result;
00443 }
00444 
00445 static char *
00446 ada_get_gdb_completer_word_break_characters (void)
00447 {
00448   return ada_completer_word_break_characters;
00449 }
00450 
00451 /* Print an array element index using the Ada syntax.  */
00452 
00453 static void
00454 ada_print_array_index (struct value *index_value, struct ui_file *stream,
00455                        const struct value_print_options *options)
00456 {
00457   LA_VALUE_PRINT (index_value, stream, options);
00458   fprintf_filtered (stream, " => ");
00459 }
00460 
00461 /* Assuming VECT points to an array of *SIZE objects of size
00462    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
00463    updating *SIZE as necessary and returning the (new) array.  */
00464 
00465 void *
00466 grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
00467 {
00468   if (*size < min_size)
00469     {
00470       *size *= 2;
00471       if (*size < min_size)
00472         *size = min_size;
00473       vect = xrealloc (vect, *size * element_size);
00474     }
00475   return vect;
00476 }
00477 
00478 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
00479    suffix of FIELD_NAME beginning "___".  */
00480 
00481 static int
00482 field_name_match (const char *field_name, const char *target)
00483 {
00484   int len = strlen (target);
00485 
00486   return
00487     (strncmp (field_name, target, len) == 0
00488      && (field_name[len] == '\0'
00489          || (strncmp (field_name + len, "___", 3) == 0
00490              && strcmp (field_name + strlen (field_name) - 6,
00491                         "___XVN") != 0)));
00492 }
00493 
00494 
00495 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
00496    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
00497    and return its index.  This function also handles fields whose name
00498    have ___ suffixes because the compiler sometimes alters their name
00499    by adding such a suffix to represent fields with certain constraints.
00500    If the field could not be found, return a negative number if
00501    MAYBE_MISSING is set.  Otherwise raise an error.  */
00502 
00503 int
00504 ada_get_field_index (const struct type *type, const char *field_name,
00505                      int maybe_missing)
00506 {
00507   int fieldno;
00508   struct type *struct_type = check_typedef ((struct type *) type);
00509 
00510   for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
00511     if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
00512       return fieldno;
00513 
00514   if (!maybe_missing)
00515     error (_("Unable to find field %s in struct %s.  Aborting"),
00516            field_name, TYPE_NAME (struct_type));
00517 
00518   return -1;
00519 }
00520 
00521 /* The length of the prefix of NAME prior to any "___" suffix.  */
00522 
00523 int
00524 ada_name_prefix_len (const char *name)
00525 {
00526   if (name == NULL)
00527     return 0;
00528   else
00529     {
00530       const char *p = strstr (name, "___");
00531 
00532       if (p == NULL)
00533         return strlen (name);
00534       else
00535         return p - name;
00536     }
00537 }
00538 
00539 /* Return non-zero if SUFFIX is a suffix of STR.
00540    Return zero if STR is null.  */
00541 
00542 static int
00543 is_suffix (const char *str, const char *suffix)
00544 {
00545   int len1, len2;
00546 
00547   if (str == NULL)
00548     return 0;
00549   len1 = strlen (str);
00550   len2 = strlen (suffix);
00551   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
00552 }
00553 
00554 /* The contents of value VAL, treated as a value of type TYPE.  The
00555    result is an lval in memory if VAL is.  */
00556 
00557 static struct value *
00558 coerce_unspec_val_to_type (struct value *val, struct type *type)
00559 {
00560   type = ada_check_typedef (type);
00561   if (value_type (val) == type)
00562     return val;
00563   else
00564     {
00565       struct value *result;
00566 
00567       /* Make sure that the object size is not unreasonable before
00568          trying to allocate some memory for it.  */
00569       check_size (type);
00570 
00571       if (value_lazy (val)
00572           || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
00573         result = allocate_value_lazy (type);
00574       else
00575         {
00576           result = allocate_value (type);
00577           memcpy (value_contents_raw (result), value_contents (val),
00578                   TYPE_LENGTH (type));
00579         }
00580       set_value_component_location (result, val);
00581       set_value_bitsize (result, value_bitsize (val));
00582       set_value_bitpos (result, value_bitpos (val));
00583       set_value_address (result, value_address (val));
00584       set_value_optimized_out (result, value_optimized_out_const (val));
00585       return result;
00586     }
00587 }
00588 
00589 static const gdb_byte *
00590 cond_offset_host (const gdb_byte *valaddr, long offset)
00591 {
00592   if (valaddr == NULL)
00593     return NULL;
00594   else
00595     return valaddr + offset;
00596 }
00597 
00598 static CORE_ADDR
00599 cond_offset_target (CORE_ADDR address, long offset)
00600 {
00601   if (address == 0)
00602     return 0;
00603   else
00604     return address + offset;
00605 }
00606 
00607 /* Issue a warning (as for the definition of warning in utils.c, but
00608    with exactly one argument rather than ...), unless the limit on the
00609    number of warnings has passed during the evaluation of the current
00610    expression.  */
00611 
00612 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
00613    provided by "complaint".  */
00614 static void lim_warning (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
00615 
00616 static void
00617 lim_warning (const char *format, ...)
00618 {
00619   va_list args;
00620 
00621   va_start (args, format);
00622   warnings_issued += 1;
00623   if (warnings_issued <= warning_limit)
00624     vwarning (format, args);
00625 
00626   va_end (args);
00627 }
00628 
00629 /* Issue an error if the size of an object of type T is unreasonable,
00630    i.e. if it would be a bad idea to allocate a value of this type in
00631    GDB.  */
00632 
00633 static void
00634 check_size (const struct type *type)
00635 {
00636   if (TYPE_LENGTH (type) > varsize_limit)
00637     error (_("object size is larger than varsize-limit"));
00638 }
00639 
00640 /* Maximum value of a SIZE-byte signed integer type.  */
00641 static LONGEST
00642 max_of_size (int size)
00643 {
00644   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
00645 
00646   return top_bit | (top_bit - 1);
00647 }
00648 
00649 /* Minimum value of a SIZE-byte signed integer type.  */
00650 static LONGEST
00651 min_of_size (int size)
00652 {
00653   return -max_of_size (size) - 1;
00654 }
00655 
00656 /* Maximum value of a SIZE-byte unsigned integer type.  */
00657 static ULONGEST
00658 umax_of_size (int size)
00659 {
00660   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
00661 
00662   return top_bit | (top_bit - 1);
00663 }
00664 
00665 /* Maximum value of integral type T, as a signed quantity.  */
00666 static LONGEST
00667 max_of_type (struct type *t)
00668 {
00669   if (TYPE_UNSIGNED (t))
00670     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
00671   else
00672     return max_of_size (TYPE_LENGTH (t));
00673 }
00674 
00675 /* Minimum value of integral type T, as a signed quantity.  */
00676 static LONGEST
00677 min_of_type (struct type *t)
00678 {
00679   if (TYPE_UNSIGNED (t)) 
00680     return 0;
00681   else
00682     return min_of_size (TYPE_LENGTH (t));
00683 }
00684 
00685 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
00686 LONGEST
00687 ada_discrete_type_high_bound (struct type *type)
00688 {
00689   switch (TYPE_CODE (type))
00690     {
00691     case TYPE_CODE_RANGE:
00692       return TYPE_HIGH_BOUND (type);
00693     case TYPE_CODE_ENUM:
00694       return TYPE_FIELD_ENUMVAL (type, TYPE_NFIELDS (type) - 1);
00695     case TYPE_CODE_BOOL:
00696       return 1;
00697     case TYPE_CODE_CHAR:
00698     case TYPE_CODE_INT:
00699       return max_of_type (type);
00700     default:
00701       error (_("Unexpected type in ada_discrete_type_high_bound."));
00702     }
00703 }
00704 
00705 /* The smallest value in the domain of TYPE, a discrete type, as an integer.  */
00706 LONGEST
00707 ada_discrete_type_low_bound (struct type *type)
00708 {
00709   switch (TYPE_CODE (type))
00710     {
00711     case TYPE_CODE_RANGE:
00712       return TYPE_LOW_BOUND (type);
00713     case TYPE_CODE_ENUM:
00714       return TYPE_FIELD_ENUMVAL (type, 0);
00715     case TYPE_CODE_BOOL:
00716       return 0;
00717     case TYPE_CODE_CHAR:
00718     case TYPE_CODE_INT:
00719       return min_of_type (type);
00720     default:
00721       error (_("Unexpected type in ada_discrete_type_low_bound."));
00722     }
00723 }
00724 
00725 /* The identity on non-range types.  For range types, the underlying
00726    non-range scalar type.  */
00727 
00728 static struct type *
00729 get_base_type (struct type *type)
00730 {
00731   while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
00732     {
00733       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
00734         return type;
00735       type = TYPE_TARGET_TYPE (type);
00736     }
00737   return type;
00738 }
00739 
00740 /* Return a decoded version of the given VALUE.  This means returning
00741    a value whose type is obtained by applying all the GNAT-specific
00742    encondings, making the resulting type a static but standard description
00743    of the initial type.  */
00744 
00745 struct value *
00746 ada_get_decoded_value (struct value *value)
00747 {
00748   struct type *type = ada_check_typedef (value_type (value));
00749 
00750   if (ada_is_array_descriptor_type (type)
00751       || (ada_is_constrained_packed_array_type (type)
00752           && TYPE_CODE (type) != TYPE_CODE_PTR))
00753     {
00754       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)  /* array access type.  */
00755         value = ada_coerce_to_simple_array_ptr (value);
00756       else
00757         value = ada_coerce_to_simple_array (value);
00758     }
00759   else
00760     value = ada_to_fixed_value (value);
00761 
00762   return value;
00763 }
00764 
00765 /* Same as ada_get_decoded_value, but with the given TYPE.
00766    Because there is no associated actual value for this type,
00767    the resulting type might be a best-effort approximation in
00768    the case of dynamic types.  */
00769 
00770 struct type *
00771 ada_get_decoded_type (struct type *type)
00772 {
00773   type = to_static_fixed_type (type);
00774   if (ada_is_constrained_packed_array_type (type))
00775     type = ada_coerce_to_simple_array_type (type);
00776   return type;
00777 }
00778 
00779 
00780 
00781                                 /* Language Selection */
00782 
00783 /* If the main program is in Ada, return language_ada, otherwise return LANG
00784    (the main program is in Ada iif the adainit symbol is found).  */
00785 
00786 enum language
00787 ada_update_initial_language (enum language lang)
00788 {
00789   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
00790                              (struct objfile *) NULL) != NULL)
00791     return language_ada;
00792 
00793   return lang;
00794 }
00795 
00796 /* If the main procedure is written in Ada, then return its name.
00797    The result is good until the next call.  Return NULL if the main
00798    procedure doesn't appear to be in Ada.  */
00799 
00800 char *
00801 ada_main_name (void)
00802 {
00803   struct minimal_symbol *msym;
00804   static char *main_program_name = NULL;
00805 
00806   /* For Ada, the name of the main procedure is stored in a specific
00807      string constant, generated by the binder.  Look for that symbol,
00808      extract its address, and then read that string.  If we didn't find
00809      that string, then most probably the main procedure is not written
00810      in Ada.  */
00811   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
00812 
00813   if (msym != NULL)
00814     {
00815       CORE_ADDR main_program_name_addr;
00816       int err_code;
00817 
00818       main_program_name_addr = SYMBOL_VALUE_ADDRESS (msym);
00819       if (main_program_name_addr == 0)
00820         error (_("Invalid address for Ada main program name."));
00821 
00822       xfree (main_program_name);
00823       target_read_string (main_program_name_addr, &main_program_name,
00824                           1024, &err_code);
00825 
00826       if (err_code != 0)
00827         return NULL;
00828       return main_program_name;
00829     }
00830 
00831   /* The main procedure doesn't seem to be in Ada.  */
00832   return NULL;
00833 }
00834 
00835                                 /* Symbols */
00836 
00837 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
00838    of NULLs.  */
00839 
00840 const struct ada_opname_map ada_opname_table[] = {
00841   {"Oadd", "\"+\"", BINOP_ADD},
00842   {"Osubtract", "\"-\"", BINOP_SUB},
00843   {"Omultiply", "\"*\"", BINOP_MUL},
00844   {"Odivide", "\"/\"", BINOP_DIV},
00845   {"Omod", "\"mod\"", BINOP_MOD},
00846   {"Orem", "\"rem\"", BINOP_REM},
00847   {"Oexpon", "\"**\"", BINOP_EXP},
00848   {"Olt", "\"<\"", BINOP_LESS},
00849   {"Ole", "\"<=\"", BINOP_LEQ},
00850   {"Ogt", "\">\"", BINOP_GTR},
00851   {"Oge", "\">=\"", BINOP_GEQ},
00852   {"Oeq", "\"=\"", BINOP_EQUAL},
00853   {"One", "\"/=\"", BINOP_NOTEQUAL},
00854   {"Oand", "\"and\"", BINOP_BITWISE_AND},
00855   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
00856   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
00857   {"Oconcat", "\"&\"", BINOP_CONCAT},
00858   {"Oabs", "\"abs\"", UNOP_ABS},
00859   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
00860   {"Oadd", "\"+\"", UNOP_PLUS},
00861   {"Osubtract", "\"-\"", UNOP_NEG},
00862   {NULL, NULL}
00863 };
00864 
00865 /* The "encoded" form of DECODED, according to GNAT conventions.
00866    The result is valid until the next call to ada_encode.  */
00867 
00868 char *
00869 ada_encode (const char *decoded)
00870 {
00871   static char *encoding_buffer = NULL;
00872   static size_t encoding_buffer_size = 0;
00873   const char *p;
00874   int k;
00875 
00876   if (decoded == NULL)
00877     return NULL;
00878 
00879   GROW_VECT (encoding_buffer, encoding_buffer_size,
00880              2 * strlen (decoded) + 10);
00881 
00882   k = 0;
00883   for (p = decoded; *p != '\0'; p += 1)
00884     {
00885       if (*p == '.')
00886         {
00887           encoding_buffer[k] = encoding_buffer[k + 1] = '_';
00888           k += 2;
00889         }
00890       else if (*p == '"')
00891         {
00892           const struct ada_opname_map *mapping;
00893 
00894           for (mapping = ada_opname_table;
00895                mapping->encoded != NULL
00896                && strncmp (mapping->decoded, p,
00897                            strlen (mapping->decoded)) != 0; mapping += 1)
00898             ;
00899           if (mapping->encoded == NULL)
00900             error (_("invalid Ada operator name: %s"), p);
00901           strcpy (encoding_buffer + k, mapping->encoded);
00902           k += strlen (mapping->encoded);
00903           break;
00904         }
00905       else
00906         {
00907           encoding_buffer[k] = *p;
00908           k += 1;
00909         }
00910     }
00911 
00912   encoding_buffer[k] = '\0';
00913   return encoding_buffer;
00914 }
00915 
00916 /* Return NAME folded to lower case, or, if surrounded by single
00917    quotes, unfolded, but with the quotes stripped away.  Result good
00918    to next call.  */
00919 
00920 char *
00921 ada_fold_name (const char *name)
00922 {
00923   static char *fold_buffer = NULL;
00924   static size_t fold_buffer_size = 0;
00925 
00926   int len = strlen (name);
00927   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
00928 
00929   if (name[0] == '\'')
00930     {
00931       strncpy (fold_buffer, name + 1, len - 2);
00932       fold_buffer[len - 2] = '\000';
00933     }
00934   else
00935     {
00936       int i;
00937 
00938       for (i = 0; i <= len; i += 1)
00939         fold_buffer[i] = tolower (name[i]);
00940     }
00941 
00942   return fold_buffer;
00943 }
00944 
00945 /* Return nonzero if C is either a digit or a lowercase alphabet character.  */
00946 
00947 static int
00948 is_lower_alphanum (const char c)
00949 {
00950   return (isdigit (c) || (isalpha (c) && islower (c)));
00951 }
00952 
00953 /* ENCODED is the linkage name of a symbol and LEN contains its length.
00954    This function saves in LEN the length of that same symbol name but
00955    without either of these suffixes:
00956      . .{DIGIT}+
00957      . ${DIGIT}+
00958      . ___{DIGIT}+
00959      . __{DIGIT}+.
00960 
00961    These are suffixes introduced by the compiler for entities such as
00962    nested subprogram for instance, in order to avoid name clashes.
00963    They do not serve any purpose for the debugger.  */
00964 
00965 static void
00966 ada_remove_trailing_digits (const char *encoded, int *len)
00967 {
00968   if (*len > 1 && isdigit (encoded[*len - 1]))
00969     {
00970       int i = *len - 2;
00971 
00972       while (i > 0 && isdigit (encoded[i]))
00973         i--;
00974       if (i >= 0 && encoded[i] == '.')
00975         *len = i;
00976       else if (i >= 0 && encoded[i] == '$')
00977         *len = i;
00978       else if (i >= 2 && strncmp (encoded + i - 2, "___", 3) == 0)
00979         *len = i - 2;
00980       else if (i >= 1 && strncmp (encoded + i - 1, "__", 2) == 0)
00981         *len = i - 1;
00982     }
00983 }
00984 
00985 /* Remove the suffix introduced by the compiler for protected object
00986    subprograms.  */
00987 
00988 static void
00989 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
00990 {
00991   /* Remove trailing N.  */
00992 
00993   /* Protected entry subprograms are broken into two
00994      separate subprograms: The first one is unprotected, and has
00995      a 'N' suffix; the second is the protected version, and has
00996      the 'P' suffix.  The second calls the first one after handling
00997      the protection.  Since the P subprograms are internally generated,
00998      we leave these names undecoded, giving the user a clue that this
00999      entity is internal.  */
01000 
01001   if (*len > 1
01002       && encoded[*len - 1] == 'N'
01003       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
01004     *len = *len - 1;
01005 }
01006 
01007 /* Remove trailing X[bn]* suffixes (indicating names in package bodies).  */
01008 
01009 static void
01010 ada_remove_Xbn_suffix (const char *encoded, int *len)
01011 {
01012   int i = *len - 1;
01013 
01014   while (i > 0 && (encoded[i] == 'b' || encoded[i] == 'n'))
01015     i--;
01016 
01017   if (encoded[i] != 'X')
01018     return;
01019 
01020   if (i == 0)
01021     return;
01022 
01023   if (isalnum (encoded[i-1]))
01024     *len = i;
01025 }
01026 
01027 /* If ENCODED follows the GNAT entity encoding conventions, then return
01028    the decoded form of ENCODED.  Otherwise, return "<%s>" where "%s" is
01029    replaced by ENCODED.
01030 
01031    The resulting string is valid until the next call of ada_decode.
01032    If the string is unchanged by decoding, the original string pointer
01033    is returned.  */
01034 
01035 const char *
01036 ada_decode (const char *encoded)
01037 {
01038   int i, j;
01039   int len0;
01040   const char *p;
01041   char *decoded;
01042   int at_start_name;
01043   static char *decoding_buffer = NULL;
01044   static size_t decoding_buffer_size = 0;
01045 
01046   /* The name of the Ada main procedure starts with "_ada_".
01047      This prefix is not part of the decoded name, so skip this part
01048      if we see this prefix.  */
01049   if (strncmp (encoded, "_ada_", 5) == 0)
01050     encoded += 5;
01051 
01052   /* If the name starts with '_', then it is not a properly encoded
01053      name, so do not attempt to decode it.  Similarly, if the name
01054      starts with '<', the name should not be decoded.  */
01055   if (encoded[0] == '_' || encoded[0] == '<')
01056     goto Suppress;
01057 
01058   len0 = strlen (encoded);
01059 
01060   ada_remove_trailing_digits (encoded, &len0);
01061   ada_remove_po_subprogram_suffix (encoded, &len0);
01062 
01063   /* Remove the ___X.* suffix if present.  Do not forget to verify that
01064      the suffix is located before the current "end" of ENCODED.  We want
01065      to avoid re-matching parts of ENCODED that have previously been
01066      marked as discarded (by decrementing LEN0).  */
01067   p = strstr (encoded, "___");
01068   if (p != NULL && p - encoded < len0 - 3)
01069     {
01070       if (p[3] == 'X')
01071         len0 = p - encoded;
01072       else
01073         goto Suppress;
01074     }
01075 
01076   /* Remove any trailing TKB suffix.  It tells us that this symbol
01077      is for the body of a task, but that information does not actually
01078      appear in the decoded name.  */
01079 
01080   if (len0 > 3 && strncmp (encoded + len0 - 3, "TKB", 3) == 0)
01081     len0 -= 3;
01082 
01083   /* Remove any trailing TB suffix.  The TB suffix is slightly different
01084      from the TKB suffix because it is used for non-anonymous task
01085      bodies.  */
01086 
01087   if (len0 > 2 && strncmp (encoded + len0 - 2, "TB", 2) == 0)
01088     len0 -= 2;
01089 
01090   /* Remove trailing "B" suffixes.  */
01091   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */
01092 
01093   if (len0 > 1 && strncmp (encoded + len0 - 1, "B", 1) == 0)
01094     len0 -= 1;
01095 
01096   /* Make decoded big enough for possible expansion by operator name.  */
01097 
01098   GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
01099   decoded = decoding_buffer;
01100 
01101   /* Remove trailing __{digit}+ or trailing ${digit}+.  */
01102 
01103   if (len0 > 1 && isdigit (encoded[len0 - 1]))
01104     {
01105       i = len0 - 2;
01106       while ((i >= 0 && isdigit (encoded[i]))
01107              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
01108         i -= 1;
01109       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
01110         len0 = i - 1;
01111       else if (encoded[i] == '$')
01112         len0 = i;
01113     }
01114 
01115   /* The first few characters that are not alphabetic are not part
01116      of any encoding we use, so we can copy them over verbatim.  */
01117 
01118   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
01119     decoded[j] = encoded[i];
01120 
01121   at_start_name = 1;
01122   while (i < len0)
01123     {
01124       /* Is this a symbol function?  */
01125       if (at_start_name && encoded[i] == 'O')
01126         {
01127           int k;
01128 
01129           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
01130             {
01131               int op_len = strlen (ada_opname_table[k].encoded);
01132               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
01133                             op_len - 1) == 0)
01134                   && !isalnum (encoded[i + op_len]))
01135                 {
01136                   strcpy (decoded + j, ada_opname_table[k].decoded);
01137                   at_start_name = 0;
01138                   i += op_len;
01139                   j += strlen (ada_opname_table[k].decoded);
01140                   break;
01141                 }
01142             }
01143           if (ada_opname_table[k].encoded != NULL)
01144             continue;
01145         }
01146       at_start_name = 0;
01147 
01148       /* Replace "TK__" with "__", which will eventually be translated
01149          into "." (just below).  */
01150 
01151       if (i < len0 - 4 && strncmp (encoded + i, "TK__", 4) == 0)
01152         i += 2;
01153 
01154       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
01155          be translated into "." (just below).  These are internal names
01156          generated for anonymous blocks inside which our symbol is nested.  */
01157 
01158       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
01159           && encoded [i+2] == 'B' && encoded [i+3] == '_'
01160           && isdigit (encoded [i+4]))
01161         {
01162           int k = i + 5;
01163           
01164           while (k < len0 && isdigit (encoded[k]))
01165             k++;  /* Skip any extra digit.  */
01166 
01167           /* Double-check that the "__B_{DIGITS}+" sequence we found
01168              is indeed followed by "__".  */
01169           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
01170             i = k;
01171         }
01172 
01173       /* Remove _E{DIGITS}+[sb] */
01174 
01175       /* Just as for protected object subprograms, there are 2 categories
01176          of subprograms created by the compiler for each entry.  The first
01177          one implements the actual entry code, and has a suffix following
01178          the convention above; the second one implements the barrier and
01179          uses the same convention as above, except that the 'E' is replaced
01180          by a 'B'.
01181 
01182          Just as above, we do not decode the name of barrier functions
01183          to give the user a clue that the code he is debugging has been
01184          internally generated.  */
01185 
01186       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
01187           && isdigit (encoded[i+2]))
01188         {
01189           int k = i + 3;
01190 
01191           while (k < len0 && isdigit (encoded[k]))
01192             k++;
01193 
01194           if (k < len0
01195               && (encoded[k] == 'b' || encoded[k] == 's'))
01196             {
01197               k++;
01198               /* Just as an extra precaution, make sure that if this
01199                  suffix is followed by anything else, it is a '_'.
01200                  Otherwise, we matched this sequence by accident.  */
01201               if (k == len0
01202                   || (k < len0 && encoded[k] == '_'))
01203                 i = k;
01204             }
01205         }
01206 
01207       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
01208          the GNAT front-end in protected object subprograms.  */
01209 
01210       if (i < len0 + 3
01211           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
01212         {
01213           /* Backtrack a bit up until we reach either the begining of
01214              the encoded name, or "__".  Make sure that we only find
01215              digits or lowercase characters.  */
01216           const char *ptr = encoded + i - 1;
01217 
01218           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
01219             ptr--;
01220           if (ptr < encoded
01221               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
01222             i++;
01223         }
01224 
01225       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
01226         {
01227           /* This is a X[bn]* sequence not separated from the previous
01228              part of the name with a non-alpha-numeric character (in other
01229              words, immediately following an alpha-numeric character), then
01230              verify that it is placed at the end of the encoded name.  If
01231              not, then the encoding is not valid and we should abort the
01232              decoding.  Otherwise, just skip it, it is used in body-nested
01233              package names.  */
01234           do
01235             i += 1;
01236           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
01237           if (i < len0)
01238             goto Suppress;
01239         }
01240       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
01241         {
01242          /* Replace '__' by '.'.  */
01243           decoded[j] = '.';
01244           at_start_name = 1;
01245           i += 2;
01246           j += 1;
01247         }
01248       else
01249         {
01250           /* It's a character part of the decoded name, so just copy it
01251              over.  */
01252           decoded[j] = encoded[i];
01253           i += 1;
01254           j += 1;
01255         }
01256     }
01257   decoded[j] = '\000';
01258 
01259   /* Decoded names should never contain any uppercase character.
01260      Double-check this, and abort the decoding if we find one.  */
01261 
01262   for (i = 0; decoded[i] != '\0'; i += 1)
01263     if (isupper (decoded[i]) || decoded[i] == ' ')
01264       goto Suppress;
01265 
01266   if (strcmp (decoded, encoded) == 0)
01267     return encoded;
01268   else
01269     return decoded;
01270 
01271 Suppress:
01272   GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
01273   decoded = decoding_buffer;
01274   if (encoded[0] == '<')
01275     strcpy (decoded, encoded);
01276   else
01277     xsnprintf (decoded, decoding_buffer_size, "<%s>", encoded);
01278   return decoded;
01279 
01280 }
01281 
01282 /* Table for keeping permanent unique copies of decoded names.  Once
01283    allocated, names in this table are never released.  While this is a
01284    storage leak, it should not be significant unless there are massive
01285    changes in the set of decoded names in successive versions of a 
01286    symbol table loaded during a single session.  */
01287 static struct htab *decoded_names_store;
01288 
01289 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
01290    in the language-specific part of GSYMBOL, if it has not been
01291    previously computed.  Tries to save the decoded name in the same
01292    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
01293    in any case, the decoded symbol has a lifetime at least that of
01294    GSYMBOL).
01295    The GSYMBOL parameter is "mutable" in the C++ sense: logically
01296    const, but nevertheless modified to a semantically equivalent form
01297    when a decoded name is cached in it.  */
01298 
01299 const char *
01300 ada_decode_symbol (const struct general_symbol_info *arg)
01301 {
01302   struct general_symbol_info *gsymbol = (struct general_symbol_info *) arg;
01303   const char **resultp =
01304     &gsymbol->language_specific.mangled_lang.demangled_name;
01305 
01306   if (!gsymbol->ada_mangled)
01307     {
01308       const char *decoded = ada_decode (gsymbol->name);
01309       struct obstack *obstack = gsymbol->language_specific.obstack;
01310 
01311       gsymbol->ada_mangled = 1;
01312 
01313       if (obstack != NULL)
01314         *resultp = obstack_copy0 (obstack, decoded, strlen (decoded));
01315       else
01316         {
01317           /* Sometimes, we can't find a corresponding objfile, in
01318              which case, we put the result on the heap.  Since we only
01319              decode when needed, we hope this usually does not cause a
01320              significant memory leak (FIXME).  */
01321 
01322           char **slot = (char **) htab_find_slot (decoded_names_store,
01323                                                   decoded, INSERT);
01324 
01325           if (*slot == NULL)
01326             *slot = xstrdup (decoded);
01327           *resultp = *slot;
01328         }
01329     }
01330 
01331   return *resultp;
01332 }
01333 
01334 static char *
01335 ada_la_decode (const char *encoded, int options)
01336 {
01337   return xstrdup (ada_decode (encoded));
01338 }
01339 
01340 /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
01341    suffixes that encode debugging information or leading _ada_ on
01342    SYM_NAME (see is_name_suffix commentary for the debugging
01343    information that is ignored).  If WILD, then NAME need only match a
01344    suffix of SYM_NAME minus the same suffixes.  Also returns 0 if
01345    either argument is NULL.  */
01346 
01347 static int
01348 match_name (const char *sym_name, const char *name, int wild)
01349 {
01350   if (sym_name == NULL || name == NULL)
01351     return 0;
01352   else if (wild)
01353     return wild_match (sym_name, name) == 0;
01354   else
01355     {
01356       int len_name = strlen (name);
01357 
01358       return (strncmp (sym_name, name, len_name) == 0
01359               && is_name_suffix (sym_name + len_name))
01360         || (strncmp (sym_name, "_ada_", 5) == 0
01361             && strncmp (sym_name + 5, name, len_name) == 0
01362             && is_name_suffix (sym_name + len_name + 5));
01363     }
01364 }
01365 
01366 
01367                                 /* Arrays */
01368 
01369 /* Assuming that INDEX_DESC_TYPE is an ___XA structure, a structure
01370    generated by the GNAT compiler to describe the index type used
01371    for each dimension of an array, check whether it follows the latest
01372    known encoding.  If not, fix it up to conform to the latest encoding.
01373    Otherwise, do nothing.  This function also does nothing if
01374    INDEX_DESC_TYPE is NULL.
01375 
01376    The GNAT encoding used to describle the array index type evolved a bit.
01377    Initially, the information would be provided through the name of each
01378    field of the structure type only, while the type of these fields was
01379    described as unspecified and irrelevant.  The debugger was then expected
01380    to perform a global type lookup using the name of that field in order
01381    to get access to the full index type description.  Because these global
01382    lookups can be very expensive, the encoding was later enhanced to make
01383    the global lookup unnecessary by defining the field type as being
01384    the full index type description.
01385 
01386    The purpose of this routine is to allow us to support older versions
01387    of the compiler by detecting the use of the older encoding, and by
01388    fixing up the INDEX_DESC_TYPE to follow the new one (at this point,
01389    we essentially replace each field's meaningless type by the associated
01390    index subtype).  */
01391 
01392 void
01393 ada_fixup_array_indexes_type (struct type *index_desc_type)
01394 {
01395   int i;
01396 
01397   if (index_desc_type == NULL)
01398     return;
01399   gdb_assert (TYPE_NFIELDS (index_desc_type) > 0);
01400 
01401   /* Check if INDEX_DESC_TYPE follows the older encoding (it is sufficient
01402      to check one field only, no need to check them all).  If not, return
01403      now.
01404 
01405      If our INDEX_DESC_TYPE was generated using the older encoding,
01406      the field type should be a meaningless integer type whose name
01407      is not equal to the field name.  */
01408   if (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)) != NULL
01409       && strcmp (TYPE_NAME (TYPE_FIELD_TYPE (index_desc_type, 0)),
01410                  TYPE_FIELD_NAME (index_desc_type, 0)) == 0)
01411     return;
01412 
01413   /* Fixup each field of INDEX_DESC_TYPE.  */
01414   for (i = 0; i < TYPE_NFIELDS (index_desc_type); i++)
01415    {
01416      const char *name = TYPE_FIELD_NAME (index_desc_type, i);
01417      struct type *raw_type = ada_check_typedef (ada_find_any_type (name));
01418 
01419      if (raw_type)
01420        TYPE_FIELD_TYPE (index_desc_type, i) = raw_type;
01421    }
01422 }
01423 
01424 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors.  */
01425 
01426 static char *bound_name[] = {
01427   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
01428   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
01429 };
01430 
01431 /* Maximum number of array dimensions we are prepared to handle.  */
01432 
01433 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
01434 
01435 
01436 /* The desc_* routines return primitive portions of array descriptors
01437    (fat pointers).  */
01438 
01439 /* The descriptor or array type, if any, indicated by TYPE; removes
01440    level of indirection, if needed.  */
01441 
01442 static struct type *
01443 desc_base_type (struct type *type)
01444 {
01445   if (type == NULL)
01446     return NULL;
01447   type = ada_check_typedef (type);
01448   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
01449     type = ada_typedef_target_type (type);
01450 
01451   if (type != NULL
01452       && (TYPE_CODE (type) == TYPE_CODE_PTR
01453           || TYPE_CODE (type) == TYPE_CODE_REF))
01454     return ada_check_typedef (TYPE_TARGET_TYPE (type));
01455   else
01456     return type;
01457 }
01458 
01459 /* True iff TYPE indicates a "thin" array pointer type.  */
01460 
01461 static int
01462 is_thin_pntr (struct type *type)
01463 {
01464   return
01465     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
01466     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
01467 }
01468 
01469 /* The descriptor type for thin pointer type TYPE.  */
01470 
01471 static struct type *
01472 thin_descriptor_type (struct type *type)
01473 {
01474   struct type *base_type = desc_base_type (type);
01475 
01476   if (base_type == NULL)
01477     return NULL;
01478   if (is_suffix (ada_type_name (base_type), "___XVE"))
01479     return base_type;
01480   else
01481     {
01482       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
01483 
01484       if (alt_type == NULL)
01485         return base_type;
01486       else
01487         return alt_type;
01488     }
01489 }
01490 
01491 /* A pointer to the array data for thin-pointer value VAL.  */
01492 
01493 static struct value *
01494 thin_data_pntr (struct value *val)
01495 {
01496   struct type *type = ada_check_typedef (value_type (val));
01497   struct type *data_type = desc_data_target_type (thin_descriptor_type (type));
01498 
01499   data_type = lookup_pointer_type (data_type);
01500 
01501   if (TYPE_CODE (type) == TYPE_CODE_PTR)
01502     return value_cast (data_type, value_copy (val));
01503   else
01504     return value_from_longest (data_type, value_address (val));
01505 }
01506 
01507 /* True iff TYPE indicates a "thick" array pointer type.  */
01508 
01509 static int
01510 is_thick_pntr (struct type *type)
01511 {
01512   type = desc_base_type (type);
01513   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
01514           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
01515 }
01516 
01517 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
01518    pointer to one, the type of its bounds data; otherwise, NULL.  */
01519 
01520 static struct type *
01521 desc_bounds_type (struct type *type)
01522 {
01523   struct type *r;
01524 
01525   type = desc_base_type (type);
01526 
01527   if (type == NULL)
01528     return NULL;
01529   else if (is_thin_pntr (type))
01530     {
01531       type = thin_descriptor_type (type);
01532       if (type == NULL)
01533         return NULL;
01534       r = lookup_struct_elt_type (type, "BOUNDS", 1);
01535       if (r != NULL)
01536         return ada_check_typedef (r);
01537     }
01538   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
01539     {
01540       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
01541       if (r != NULL)
01542         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
01543     }
01544   return NULL;
01545 }
01546 
01547 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
01548    one, a pointer to its bounds data.   Otherwise NULL.  */
01549 
01550 static struct value *
01551 desc_bounds (struct value *arr)
01552 {
01553   struct type *type = ada_check_typedef (value_type (arr));
01554 
01555   if (is_thin_pntr (type))
01556     {
01557       struct type *bounds_type =
01558         desc_bounds_type (thin_descriptor_type (type));
01559       LONGEST addr;
01560 
01561       if (bounds_type == NULL)
01562         error (_("Bad GNAT array descriptor"));
01563 
01564       /* NOTE: The following calculation is not really kosher, but
01565          since desc_type is an XVE-encoded type (and shouldn't be),
01566          the correct calculation is a real pain.  FIXME (and fix GCC).  */
01567       if (TYPE_CODE (type) == TYPE_CODE_PTR)
01568         addr = value_as_long (arr);
01569       else
01570         addr = value_address (arr);
01571 
01572       return
01573         value_from_longest (lookup_pointer_type (bounds_type),
01574                             addr - TYPE_LENGTH (bounds_type));
01575     }
01576 
01577   else if (is_thick_pntr (type))
01578     {
01579       struct value *p_bounds = value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
01580                                                _("Bad GNAT array descriptor"));
01581       struct type *p_bounds_type = value_type (p_bounds);
01582 
01583       if (p_bounds_type
01584           && TYPE_CODE (p_bounds_type) == TYPE_CODE_PTR)
01585         {
01586           struct type *target_type = TYPE_TARGET_TYPE (p_bounds_type);
01587 
01588           if (TYPE_STUB (target_type))
01589             p_bounds = value_cast (lookup_pointer_type
01590                                    (ada_check_typedef (target_type)),
01591                                    p_bounds);
01592         }
01593       else
01594         error (_("Bad GNAT array descriptor"));
01595 
01596       return p_bounds;
01597     }
01598   else
01599     return NULL;
01600 }
01601 
01602 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
01603    position of the field containing the address of the bounds data.  */
01604 
01605 static int
01606 fat_pntr_bounds_bitpos (struct type *type)
01607 {
01608   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
01609 }
01610 
01611 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
01612    size of the field containing the address of the bounds data.  */
01613 
01614 static int
01615 fat_pntr_bounds_bitsize (struct type *type)
01616 {
01617   type = desc_base_type (type);
01618 
01619   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
01620     return TYPE_FIELD_BITSIZE (type, 1);
01621   else
01622     return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
01623 }
01624 
01625 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
01626    pointer to one, the type of its array data (a array-with-no-bounds type);
01627    otherwise, NULL.  Use ada_type_of_array to get an array type with bounds
01628    data.  */
01629 
01630 static struct type *
01631 desc_data_target_type (struct type *type)
01632 {
01633   type = desc_base_type (type);
01634 
01635   /* NOTE: The following is bogus; see comment in desc_bounds.  */
01636   if (is_thin_pntr (type))
01637     return desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1));
01638   else if (is_thick_pntr (type))
01639     {
01640       struct type *data_type = lookup_struct_elt_type (type, "P_ARRAY", 1);
01641 
01642       if (data_type
01643           && TYPE_CODE (ada_check_typedef (data_type)) == TYPE_CODE_PTR)
01644         return ada_check_typedef (TYPE_TARGET_TYPE (data_type));
01645     }
01646 
01647   return NULL;
01648 }
01649 
01650 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
01651    its array data.  */
01652 
01653 static struct value *
01654 desc_data (struct value *arr)
01655 {
01656   struct type *type = value_type (arr);
01657 
01658   if (is_thin_pntr (type))
01659     return thin_data_pntr (arr);
01660   else if (is_thick_pntr (type))
01661     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
01662                              _("Bad GNAT array descriptor"));
01663   else
01664     return NULL;
01665 }
01666 
01667 
01668 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
01669    position of the field containing the address of the data.  */
01670 
01671 static int
01672 fat_pntr_data_bitpos (struct type *type)
01673 {
01674   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
01675 }
01676 
01677 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
01678    size of the field containing the address of the data.  */
01679 
01680 static int
01681 fat_pntr_data_bitsize (struct type *type)
01682 {
01683   type = desc_base_type (type);
01684 
01685   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
01686     return TYPE_FIELD_BITSIZE (type, 0);
01687   else
01688     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
01689 }
01690 
01691 /* If BOUNDS is an array-bounds structure (or pointer to one), return
01692    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
01693    bound, if WHICH is 1.  The first bound is I=1.  */
01694 
01695 static struct value *
01696 desc_one_bound (struct value *bounds, int i, int which)
01697 {
01698   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
01699                            _("Bad GNAT array descriptor bounds"));
01700 }
01701 
01702 /* If BOUNDS is an array-bounds structure type, return the bit position
01703    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
01704    bound, if WHICH is 1.  The first bound is I=1.  */
01705 
01706 static int
01707 desc_bound_bitpos (struct type *type, int i, int which)
01708 {
01709   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
01710 }
01711 
01712 /* If BOUNDS is an array-bounds structure type, return the bit field size
01713    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
01714    bound, if WHICH is 1.  The first bound is I=1.  */
01715 
01716 static int
01717 desc_bound_bitsize (struct type *type, int i, int which)
01718 {
01719   type = desc_base_type (type);
01720 
01721   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
01722     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
01723   else
01724     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
01725 }
01726 
01727 /* If TYPE is the type of an array-bounds structure, the type of its
01728    Ith bound (numbering from 1).  Otherwise, NULL.  */
01729 
01730 static struct type *
01731 desc_index_type (struct type *type, int i)
01732 {
01733   type = desc_base_type (type);
01734 
01735   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
01736     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
01737   else
01738     return NULL;
01739 }
01740 
01741 /* The number of index positions in the array-bounds type TYPE.
01742    Return 0 if TYPE is NULL.  */
01743 
01744 static int
01745 desc_arity (struct type *type)
01746 {
01747   type = desc_base_type (type);
01748 
01749   if (type != NULL)
01750     return TYPE_NFIELDS (type) / 2;
01751   return 0;
01752 }
01753 
01754 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
01755    an array descriptor type (representing an unconstrained array
01756    type).  */
01757 
01758 static int
01759 ada_is_direct_array_type (struct type *type)
01760 {
01761   if (type == NULL)
01762     return 0;
01763   type = ada_check_typedef (type);
01764   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
01765           || ada_is_array_descriptor_type (type));
01766 }
01767 
01768 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
01769  * to one.  */
01770 
01771 static int
01772 ada_is_array_type (struct type *type)
01773 {
01774   while (type != NULL 
01775          && (TYPE_CODE (type) == TYPE_CODE_PTR 
01776              || TYPE_CODE (type) == TYPE_CODE_REF))
01777     type = TYPE_TARGET_TYPE (type);
01778   return ada_is_direct_array_type (type);
01779 }
01780 
01781 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
01782 
01783 int
01784 ada_is_simple_array_type (struct type *type)
01785 {
01786   if (type == NULL)
01787     return 0;
01788   type = ada_check_typedef (type);
01789   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
01790           || (TYPE_CODE (type) == TYPE_CODE_PTR
01791               && TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type)))
01792                  == TYPE_CODE_ARRAY));
01793 }
01794 
01795 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
01796 
01797 int
01798 ada_is_array_descriptor_type (struct type *type)
01799 {
01800   struct type *data_type = desc_data_target_type (type);
01801 
01802   if (type == NULL)
01803     return 0;
01804   type = ada_check_typedef (type);
01805   return (data_type != NULL
01806           && TYPE_CODE (data_type) == TYPE_CODE_ARRAY
01807           && desc_arity (desc_bounds_type (type)) > 0);
01808 }
01809 
01810 /* Non-zero iff type is a partially mal-formed GNAT array
01811    descriptor.  FIXME: This is to compensate for some problems with
01812    debugging output from GNAT.  Re-examine periodically to see if it
01813    is still needed.  */
01814 
01815 int
01816 ada_is_bogus_array_descriptor (struct type *type)
01817 {
01818   return
01819     type != NULL
01820     && TYPE_CODE (type) == TYPE_CODE_STRUCT
01821     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
01822         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
01823     && !ada_is_array_descriptor_type (type);
01824 }
01825 
01826 
01827 /* If ARR has a record type in the form of a standard GNAT array descriptor,
01828    (fat pointer) returns the type of the array data described---specifically,
01829    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
01830    in from the descriptor; otherwise, they are left unspecified.  If
01831    the ARR denotes a null array descriptor and BOUNDS is non-zero,
01832    returns NULL.  The result is simply the type of ARR if ARR is not
01833    a descriptor.  */
01834 struct type *
01835 ada_type_of_array (struct value *arr, int bounds)
01836 {
01837   if (ada_is_constrained_packed_array_type (value_type (arr)))
01838     return decode_constrained_packed_array_type (value_type (arr));
01839 
01840   if (!ada_is_array_descriptor_type (value_type (arr)))
01841     return value_type (arr);
01842 
01843   if (!bounds)
01844     {
01845       struct type *array_type =
01846         ada_check_typedef (desc_data_target_type (value_type (arr)));
01847 
01848       if (ada_is_unconstrained_packed_array_type (value_type (arr)))
01849         TYPE_FIELD_BITSIZE (array_type, 0) =
01850           decode_packed_array_bitsize (value_type (arr));
01851       
01852       return array_type;
01853     }
01854   else
01855     {
01856       struct type *elt_type;
01857       int arity;
01858       struct value *descriptor;
01859 
01860       elt_type = ada_array_element_type (value_type (arr), -1);
01861       arity = ada_array_arity (value_type (arr));
01862 
01863       if (elt_type == NULL || arity == 0)
01864         return ada_check_typedef (value_type (arr));
01865 
01866       descriptor = desc_bounds (arr);
01867       if (value_as_long (descriptor) == 0)
01868         return NULL;
01869       while (arity > 0)
01870         {
01871           struct type *range_type = alloc_type_copy (value_type (arr));
01872           struct type *array_type = alloc_type_copy (value_type (arr));
01873           struct value *low = desc_one_bound (descriptor, arity, 0);
01874           struct value *high = desc_one_bound (descriptor, arity, 1);
01875 
01876           arity -= 1;
01877           create_range_type (range_type, value_type (low),
01878                              longest_to_int (value_as_long (low)),
01879                              longest_to_int (value_as_long (high)));
01880           elt_type = create_array_type (array_type, elt_type, range_type);
01881 
01882           if (ada_is_unconstrained_packed_array_type (value_type (arr)))
01883             {
01884               /* We need to store the element packed bitsize, as well as
01885                  recompute the array size, because it was previously
01886                  computed based on the unpacked element size.  */
01887               LONGEST lo = value_as_long (low);
01888               LONGEST hi = value_as_long (high);
01889 
01890               TYPE_FIELD_BITSIZE (elt_type, 0) =
01891                 decode_packed_array_bitsize (value_type (arr));
01892               /* If the array has no element, then the size is already
01893                  zero, and does not need to be recomputed.  */
01894               if (lo < hi)
01895                 {
01896                   int array_bitsize =
01897                         (hi - lo + 1) * TYPE_FIELD_BITSIZE (elt_type, 0);
01898 
01899                   TYPE_LENGTH (array_type) = (array_bitsize + 7) / 8;
01900                 }
01901             }
01902         }
01903 
01904       return lookup_pointer_type (elt_type);
01905     }
01906 }
01907 
01908 /* If ARR does not represent an array, returns ARR unchanged.
01909    Otherwise, returns either a standard GDB array with bounds set
01910    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
01911    GDB array.  Returns NULL if ARR is a null fat pointer.  */
01912 
01913 struct value *
01914 ada_coerce_to_simple_array_ptr (struct value *arr)
01915 {
01916   if (ada_is_array_descriptor_type (value_type (arr)))
01917     {
01918       struct type *arrType = ada_type_of_array (arr, 1);
01919 
01920       if (arrType == NULL)
01921         return NULL;
01922       return value_cast (arrType, value_copy (desc_data (arr)));
01923     }
01924   else if (ada_is_constrained_packed_array_type (value_type (arr)))
01925     return decode_constrained_packed_array (arr);
01926   else
01927     return arr;
01928 }
01929 
01930 /* If ARR does not represent an array, returns ARR unchanged.
01931    Otherwise, returns a standard GDB array describing ARR (which may
01932    be ARR itself if it already is in the proper form).  */
01933 
01934 struct value *
01935 ada_coerce_to_simple_array (struct value *arr)
01936 {
01937   if (ada_is_array_descriptor_type (value_type (arr)))
01938     {
01939       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
01940 
01941       if (arrVal == NULL)
01942         error (_("Bounds unavailable for null array pointer."));
01943       check_size (TYPE_TARGET_TYPE (value_type (arrVal)));
01944       return value_ind (arrVal);
01945     }
01946   else if (ada_is_constrained_packed_array_type (value_type (arr)))
01947     return decode_constrained_packed_array (arr);
01948   else
01949     return arr;
01950 }
01951 
01952 /* If TYPE represents a GNAT array type, return it translated to an
01953    ordinary GDB array type (possibly with BITSIZE fields indicating
01954    packing).  For other types, is the identity.  */
01955 
01956 struct type *
01957 ada_coerce_to_simple_array_type (struct type *type)
01958 {
01959   if (ada_is_constrained_packed_array_type (type))
01960     return decode_constrained_packed_array_type (type);
01961 
01962   if (ada_is_array_descriptor_type (type))
01963     return ada_check_typedef (desc_data_target_type (type));
01964 
01965   return type;
01966 }
01967 
01968 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
01969 
01970 static int
01971 ada_is_packed_array_type  (struct type *type)
01972 {
01973   if (type == NULL)
01974     return 0;
01975   type = desc_base_type (type);
01976   type = ada_check_typedef (type);
01977   return
01978     ada_type_name (type) != NULL
01979     && strstr (ada_type_name (type), "___XP") != NULL;
01980 }
01981 
01982 /* Non-zero iff TYPE represents a standard GNAT constrained
01983    packed-array type.  */
01984 
01985 int
01986 ada_is_constrained_packed_array_type (struct type *type)
01987 {
01988   return ada_is_packed_array_type (type)
01989     && !ada_is_array_descriptor_type (type);
01990 }
01991 
01992 /* Non-zero iff TYPE represents an array descriptor for a
01993    unconstrained packed-array type.  */
01994 
01995 static int
01996 ada_is_unconstrained_packed_array_type (struct type *type)
01997 {
01998   return ada_is_packed_array_type (type)
01999     && ada_is_array_descriptor_type (type);
02000 }
02001 
02002 /* Given that TYPE encodes a packed array type (constrained or unconstrained),
02003    return the size of its elements in bits.  */
02004 
02005 static long
02006 decode_packed_array_bitsize (struct type *type)
02007 {
02008   const char *raw_name;
02009   const char *tail;
02010   long bits;
02011 
02012   /* Access to arrays implemented as fat pointers are encoded as a typedef
02013      of the fat pointer type.  We need the name of the fat pointer type
02014      to do the decoding, so strip the typedef layer.  */
02015   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
02016     type = ada_typedef_target_type (type);
02017 
02018   raw_name = ada_type_name (ada_check_typedef (type));
02019   if (!raw_name)
02020     raw_name = ada_type_name (desc_base_type (type));
02021 
02022   if (!raw_name)
02023     return 0;
02024 
02025   tail = strstr (raw_name, "___XP");
02026   gdb_assert (tail != NULL);
02027 
02028   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
02029     {
02030       lim_warning
02031         (_("could not understand bit size information on packed array"));
02032       return 0;
02033     }
02034 
02035   return bits;
02036 }
02037 
02038 /* Given that TYPE is a standard GDB array type with all bounds filled
02039    in, and that the element size of its ultimate scalar constituents
02040    (that is, either its elements, or, if it is an array of arrays, its
02041    elements' elements, etc.) is *ELT_BITS, return an identical type,
02042    but with the bit sizes of its elements (and those of any
02043    constituent arrays) recorded in the BITSIZE components of its
02044    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
02045    in bits.  */
02046 
02047 static struct type *
02048 constrained_packed_array_type (struct type *type, long *elt_bits)
02049 {
02050   struct type *new_elt_type;
02051   struct type *new_type;
02052   struct type *index_type_desc;
02053   struct type *index_type;
02054   LONGEST low_bound, high_bound;
02055 
02056   type = ada_check_typedef (type);
02057   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
02058     return type;
02059 
02060   index_type_desc = ada_find_parallel_type (type, "___XA");
02061   if (index_type_desc)
02062     index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, 0),
02063                                       NULL);
02064   else
02065     index_type = TYPE_INDEX_TYPE (type);
02066 
02067   new_type = alloc_type_copy (type);
02068   new_elt_type =
02069     constrained_packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
02070                                    elt_bits);
02071   create_array_type (new_type, new_elt_type, index_type);
02072   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
02073   TYPE_NAME (new_type) = ada_type_name (type);
02074 
02075   if (get_discrete_bounds (index_type, &low_bound, &high_bound) < 0)
02076     low_bound = high_bound = 0;
02077   if (high_bound < low_bound)
02078     *elt_bits = TYPE_LENGTH (new_type) = 0;
02079   else
02080     {
02081       *elt_bits *= (high_bound - low_bound + 1);
02082       TYPE_LENGTH (new_type) =
02083         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
02084     }
02085 
02086   TYPE_FIXED_INSTANCE (new_type) = 1;
02087   return new_type;
02088 }
02089 
02090 /* The array type encoded by TYPE, where
02091    ada_is_constrained_packed_array_type (TYPE).  */
02092 
02093 static struct type *
02094 decode_constrained_packed_array_type (struct type *type)
02095 {
02096   const char *raw_name = ada_type_name (ada_check_typedef (type));
02097   char *name;
02098   const char *tail;
02099   struct type *shadow_type;
02100   long bits;
02101 
02102   if (!raw_name)
02103     raw_name = ada_type_name (desc_base_type (type));
02104 
02105   if (!raw_name)
02106     return NULL;
02107 
02108   name = (char *) alloca (strlen (raw_name) + 1);
02109   tail = strstr (raw_name, "___XP");
02110   type = desc_base_type (type);
02111 
02112   memcpy (name, raw_name, tail - raw_name);
02113   name[tail - raw_name] = '\000';
02114 
02115   shadow_type = ada_find_parallel_type_with_name (type, name);
02116 
02117   if (shadow_type == NULL)
02118     {
02119       lim_warning (_("could not find bounds information on packed array"));
02120       return NULL;
02121     }
02122   CHECK_TYPEDEF (shadow_type);
02123 
02124   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
02125     {
02126       lim_warning (_("could not understand bounds "
02127                      "information on packed array"));
02128       return NULL;
02129     }
02130 
02131   bits = decode_packed_array_bitsize (type);
02132   return constrained_packed_array_type (shadow_type, &bits);
02133 }
02134 
02135 /* Given that ARR is a struct value *indicating a GNAT constrained packed
02136    array, returns a simple array that denotes that array.  Its type is a
02137    standard GDB array type except that the BITSIZEs of the array
02138    target types are set to the number of bits in each element, and the
02139    type length is set appropriately.  */
02140 
02141 static struct value *
02142 decode_constrained_packed_array (struct value *arr)
02143 {
02144   struct type *type;
02145 
02146   arr = ada_coerce_ref (arr);
02147 
02148   /* If our value is a pointer, then dererence it.  Make sure that
02149      this operation does not cause the target type to be fixed, as
02150      this would indirectly cause this array to be decoded.  The rest
02151      of the routine assumes that the array hasn't been decoded yet,
02152      so we use the basic "value_ind" routine to perform the dereferencing,
02153      as opposed to using "ada_value_ind".  */
02154   if (TYPE_CODE (ada_check_typedef (value_type (arr))) == TYPE_CODE_PTR)
02155     arr = value_ind (arr);
02156 
02157   type = decode_constrained_packed_array_type (value_type (arr));
02158   if (type == NULL)
02159     {
02160       error (_("can't unpack array"));
02161       return NULL;
02162     }
02163 
02164   if (gdbarch_bits_big_endian (get_type_arch (value_type (arr)))
02165       && ada_is_modular_type (value_type (arr)))
02166     {
02167        /* This is a (right-justified) modular type representing a packed
02168          array with no wrapper.  In order to interpret the value through
02169          the (left-justified) packed array type we just built, we must
02170          first left-justify it.  */
02171       int bit_size, bit_pos;
02172       ULONGEST mod;
02173 
02174       mod = ada_modulus (value_type (arr)) - 1;
02175       bit_size = 0;
02176       while (mod > 0)
02177         {
02178           bit_size += 1;
02179           mod >>= 1;
02180         }
02181       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
02182       arr = ada_value_primitive_packed_val (arr, NULL,
02183                                             bit_pos / HOST_CHAR_BIT,
02184                                             bit_pos % HOST_CHAR_BIT,
02185                                             bit_size,
02186                                             type);
02187     }
02188 
02189   return coerce_unspec_val_to_type (arr, type);
02190 }
02191 
02192 
02193 /* The value of the element of packed array ARR at the ARITY indices
02194    given in IND.   ARR must be a simple array.  */
02195 
02196 static struct value *
02197 value_subscript_packed (struct value *arr, int arity, struct value **ind)
02198 {
02199   int i;
02200   int bits, elt_off, bit_off;
02201   long elt_total_bit_offset;
02202   struct type *elt_type;
02203   struct value *v;
02204 
02205   bits = 0;
02206   elt_total_bit_offset = 0;
02207   elt_type = ada_check_typedef (value_type (arr));
02208   for (i = 0; i < arity; i += 1)
02209     {
02210       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
02211           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
02212         error
02213           (_("attempt to do packed indexing of "
02214              "something other than a packed array"));
02215       else
02216         {
02217           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
02218           LONGEST lowerbound, upperbound;
02219           LONGEST idx;
02220 
02221           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
02222             {
02223               lim_warning (_("don't know bounds of array"));
02224               lowerbound = upperbound = 0;
02225             }
02226 
02227           idx = pos_atr (ind[i]);
02228           if (idx < lowerbound || idx > upperbound)
02229             lim_warning (_("packed array index %ld out of bounds"),
02230                          (long) idx);
02231           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
02232           elt_total_bit_offset += (idx - lowerbound) * bits;
02233           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
02234         }
02235     }
02236   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
02237   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
02238 
02239   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
02240                                       bits, elt_type);
02241   return v;
02242 }
02243 
02244 /* Non-zero iff TYPE includes negative integer values.  */
02245 
02246 static int
02247 has_negatives (struct type *type)
02248 {
02249   switch (TYPE_CODE (type))
02250     {
02251     default:
02252       return 0;
02253     case TYPE_CODE_INT:
02254       return !TYPE_UNSIGNED (type);
02255     case TYPE_CODE_RANGE:
02256       return TYPE_LOW_BOUND (type) < 0;
02257     }
02258 }
02259 
02260 
02261 /* Create a new value of type TYPE from the contents of OBJ starting
02262    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
02263    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
02264    assigning through the result will set the field fetched from.
02265    VALADDR is ignored unless OBJ is NULL, in which case,
02266    VALADDR+OFFSET must address the start of storage containing the 
02267    packed value.  The value returned  in this case is never an lval.
02268    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
02269 
02270 struct value *
02271 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
02272                                 long offset, int bit_offset, int bit_size,
02273                                 struct type *type)
02274 {
02275   struct value *v;
02276   int src,                      /* Index into the source area */
02277     targ,                       /* Index into the target area */
02278     srcBitsLeft,                /* Number of source bits left to move */
02279     nsrc, ntarg,                /* Number of source and target bytes */
02280     unusedLS,                   /* Number of bits in next significant
02281                                    byte of source that are unused */
02282     accumSize;                  /* Number of meaningful bits in accum */
02283   unsigned char *bytes;         /* First byte containing data to unpack */
02284   unsigned char *unpacked;
02285   unsigned long accum;          /* Staging area for bits being transferred */
02286   unsigned char sign;
02287   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
02288   /* Transmit bytes from least to most significant; delta is the direction
02289      the indices move.  */
02290   int delta = gdbarch_bits_big_endian (get_type_arch (type)) ? -1 : 1;
02291 
02292   type = ada_check_typedef (type);
02293 
02294   if (obj == NULL)
02295     {
02296       v = allocate_value (type);
02297       bytes = (unsigned char *) (valaddr + offset);
02298     }
02299   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
02300     {
02301       v = value_at (type, value_address (obj));
02302       bytes = (unsigned char *) alloca (len);
02303       read_memory (value_address (v) + offset, bytes, len);
02304     }
02305   else
02306     {
02307       v = allocate_value (type);
02308       bytes = (unsigned char *) value_contents (obj) + offset;
02309     }
02310 
02311   if (obj != NULL)
02312     {
02313       long new_offset = offset;
02314 
02315       set_value_component_location (v, obj);
02316       set_value_bitpos (v, bit_offset + value_bitpos (obj));
02317       set_value_bitsize (v, bit_size);
02318       if (value_bitpos (v) >= HOST_CHAR_BIT)
02319         {
02320           ++new_offset;
02321           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
02322         }
02323       set_value_offset (v, new_offset);
02324 
02325       /* Also set the parent value.  This is needed when trying to
02326          assign a new value (in inferior memory).  */
02327       set_value_parent (v, obj);
02328     }
02329   else
02330     set_value_bitsize (v, bit_size);
02331   unpacked = (unsigned char *) value_contents (v);
02332 
02333   srcBitsLeft = bit_size;
02334   nsrc = len;
02335   ntarg = TYPE_LENGTH (type);
02336   sign = 0;
02337   if (bit_size == 0)
02338     {
02339       memset (unpacked, 0, TYPE_LENGTH (type));
02340       return v;
02341     }
02342   else if (gdbarch_bits_big_endian (get_type_arch (type)))
02343     {
02344       src = len - 1;
02345       if (has_negatives (type)
02346           && ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
02347         sign = ~0;
02348 
02349       unusedLS =
02350         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
02351         % HOST_CHAR_BIT;
02352 
02353       switch (TYPE_CODE (type))
02354         {
02355         case TYPE_CODE_ARRAY:
02356         case TYPE_CODE_UNION:
02357         case TYPE_CODE_STRUCT:
02358           /* Non-scalar values must be aligned at a byte boundary...  */
02359           accumSize =
02360             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
02361           /* ... And are placed at the beginning (most-significant) bytes
02362              of the target.  */
02363           targ = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
02364           ntarg = targ + 1;
02365           break;
02366         default:
02367           accumSize = 0;
02368           targ = TYPE_LENGTH (type) - 1;
02369           break;
02370         }
02371     }
02372   else
02373     {
02374       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
02375 
02376       src = targ = 0;
02377       unusedLS = bit_offset;
02378       accumSize = 0;
02379 
02380       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
02381         sign = ~0;
02382     }
02383 
02384   accum = 0;
02385   while (nsrc > 0)
02386     {
02387       /* Mask for removing bits of the next source byte that are not
02388          part of the value.  */
02389       unsigned int unusedMSMask =
02390         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
02391         1;
02392       /* Sign-extend bits for this byte.  */
02393       unsigned int signMask = sign & ~unusedMSMask;
02394 
02395       accum |=
02396         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
02397       accumSize += HOST_CHAR_BIT - unusedLS;
02398       if (accumSize >= HOST_CHAR_BIT)
02399         {
02400           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
02401           accumSize -= HOST_CHAR_BIT;
02402           accum >>= HOST_CHAR_BIT;
02403           ntarg -= 1;
02404           targ += delta;
02405         }
02406       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
02407       unusedLS = 0;
02408       nsrc -= 1;
02409       src += delta;
02410     }
02411   while (ntarg > 0)
02412     {
02413       accum |= sign << accumSize;
02414       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
02415       accumSize -= HOST_CHAR_BIT;
02416       accum >>= HOST_CHAR_BIT;
02417       ntarg -= 1;
02418       targ += delta;
02419     }
02420 
02421   return v;
02422 }
02423 
02424 /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
02425    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
02426    not overlap.  */
02427 static void
02428 move_bits (gdb_byte *target, int targ_offset, const gdb_byte *source,
02429            int src_offset, int n, int bits_big_endian_p)
02430 {
02431   unsigned int accum, mask;
02432   int accum_bits, chunk_size;
02433 
02434   target += targ_offset / HOST_CHAR_BIT;
02435   targ_offset %= HOST_CHAR_BIT;
02436   source += src_offset / HOST_CHAR_BIT;
02437   src_offset %= HOST_CHAR_BIT;
02438   if (bits_big_endian_p)
02439     {
02440       accum = (unsigned char) *source;
02441       source += 1;
02442       accum_bits = HOST_CHAR_BIT - src_offset;
02443 
02444       while (n > 0)
02445         {
02446           int unused_right;
02447 
02448           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
02449           accum_bits += HOST_CHAR_BIT;
02450           source += 1;
02451           chunk_size = HOST_CHAR_BIT - targ_offset;
02452           if (chunk_size > n)
02453             chunk_size = n;
02454           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
02455           mask = ((1 << chunk_size) - 1) << unused_right;
02456           *target =
02457             (*target & ~mask)
02458             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
02459           n -= chunk_size;
02460           accum_bits -= chunk_size;
02461           target += 1;
02462           targ_offset = 0;
02463         }
02464     }
02465   else
02466     {
02467       accum = (unsigned char) *source >> src_offset;
02468       source += 1;
02469       accum_bits = HOST_CHAR_BIT - src_offset;
02470 
02471       while (n > 0)
02472         {
02473           accum = accum + ((unsigned char) *source << accum_bits);
02474           accum_bits += HOST_CHAR_BIT;
02475           source += 1;
02476           chunk_size = HOST_CHAR_BIT - targ_offset;
02477           if (chunk_size > n)
02478             chunk_size = n;
02479           mask = ((1 << chunk_size) - 1) << targ_offset;
02480           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
02481           n -= chunk_size;
02482           accum_bits -= chunk_size;
02483           accum >>= chunk_size;
02484           target += 1;
02485           targ_offset = 0;
02486         }
02487     }
02488 }
02489 
02490 /* Store the contents of FROMVAL into the location of TOVAL.
02491    Return a new value with the location of TOVAL and contents of
02492    FROMVAL.   Handles assignment into packed fields that have
02493    floating-point or non-scalar types.  */
02494 
02495 static struct value *
02496 ada_value_assign (struct value *toval, struct value *fromval)
02497 {
02498   struct type *type = value_type (toval);
02499   int bits = value_bitsize (toval);
02500 
02501   toval = ada_coerce_ref (toval);
02502   fromval = ada_coerce_ref (fromval);
02503 
02504   if (ada_is_direct_array_type (value_type (toval)))
02505     toval = ada_coerce_to_simple_array (toval);
02506   if (ada_is_direct_array_type (value_type (fromval)))
02507     fromval = ada_coerce_to_simple_array (fromval);
02508 
02509   if (!deprecated_value_modifiable (toval))
02510     error (_("Left operand of assignment is not a modifiable lvalue."));
02511 
02512   if (VALUE_LVAL (toval) == lval_memory
02513       && bits > 0
02514       && (TYPE_CODE (type) == TYPE_CODE_FLT
02515           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
02516     {
02517       int len = (value_bitpos (toval)
02518                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
02519       int from_size;
02520       gdb_byte *buffer = alloca (len);
02521       struct value *val;
02522       CORE_ADDR to_addr = value_address (toval);
02523 
02524       if (TYPE_CODE (type) == TYPE_CODE_FLT)
02525         fromval = value_cast (type, fromval);
02526 
02527       read_memory (to_addr, buffer, len);
02528       from_size = value_bitsize (fromval);
02529       if (from_size == 0)
02530         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
02531       if (gdbarch_bits_big_endian (get_type_arch (type)))
02532         move_bits (buffer, value_bitpos (toval),
02533                    value_contents (fromval), from_size - bits, bits, 1);
02534       else
02535         move_bits (buffer, value_bitpos (toval),
02536                    value_contents (fromval), 0, bits, 0);
02537       write_memory_with_notification (to_addr, buffer, len);
02538 
02539       val = value_copy (toval);
02540       memcpy (value_contents_raw (val), value_contents (fromval),
02541               TYPE_LENGTH (type));
02542       deprecated_set_value_type (val, type);
02543 
02544       return val;
02545     }
02546 
02547   return value_assign (toval, fromval);
02548 }
02549 
02550 
02551 /* Given that COMPONENT is a memory lvalue that is part of the lvalue 
02552  * CONTAINER, assign the contents of VAL to COMPONENTS's place in 
02553  * CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not 
02554  * COMPONENT, and not the inferior's memory.  The current contents 
02555  * of COMPONENT are ignored.  */
02556 static void
02557 value_assign_to_component (struct value *container, struct value *component,
02558                            struct value *val)
02559 {
02560   LONGEST offset_in_container =
02561     (LONGEST)  (value_address (component) - value_address (container));
02562   int bit_offset_in_container = 
02563     value_bitpos (component) - value_bitpos (container);
02564   int bits;
02565   
02566   val = value_cast (value_type (component), val);
02567 
02568   if (value_bitsize (component) == 0)
02569     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
02570   else
02571     bits = value_bitsize (component);
02572 
02573   if (gdbarch_bits_big_endian (get_type_arch (value_type (container))))
02574     move_bits (value_contents_writeable (container) + offset_in_container, 
02575                value_bitpos (container) + bit_offset_in_container,
02576                value_contents (val),
02577                TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits,
02578                bits, 1);
02579   else
02580     move_bits (value_contents_writeable (container) + offset_in_container, 
02581                value_bitpos (container) + bit_offset_in_container,
02582                value_contents (val), 0, bits, 0);
02583 }              
02584                         
02585 /* The value of the element of array ARR at the ARITY indices given in IND.
02586    ARR may be either a simple array, GNAT array descriptor, or pointer
02587    thereto.  */
02588 
02589 struct value *
02590 ada_value_subscript (struct value *arr, int arity, struct value **ind)
02591 {
02592   int k;
02593   struct value *elt;
02594   struct type *elt_type;
02595 
02596   elt = ada_coerce_to_simple_array (arr);
02597 
02598   elt_type = ada_check_typedef (value_type (elt));
02599   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
02600       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
02601     return value_subscript_packed (elt, arity, ind);
02602 
02603   for (k = 0; k < arity; k += 1)
02604     {
02605       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
02606         error (_("too many subscripts (%d expected)"), k);
02607       elt = value_subscript (elt, pos_atr (ind[k]));
02608     }
02609   return elt;
02610 }
02611 
02612 /* Assuming ARR is a pointer to a standard GDB array of type TYPE, the
02613    value of the element of *ARR at the ARITY indices given in
02614    IND.  Does not read the entire array into memory.  */
02615 
02616 static struct value *
02617 ada_value_ptr_subscript (struct value *arr, struct type *type, int arity,
02618                          struct value **ind)
02619 {
02620   int k;
02621 
02622   for (k = 0; k < arity; k += 1)
02623     {
02624       LONGEST lwb, upb;
02625 
02626       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
02627         error (_("too many subscripts (%d expected)"), k);
02628       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
02629                         value_copy (arr));
02630       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
02631       arr = value_ptradd (arr, pos_atr (ind[k]) - lwb);
02632       type = TYPE_TARGET_TYPE (type);
02633     }
02634 
02635   return value_ind (arr);
02636 }
02637 
02638 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
02639    actual type of ARRAY_PTR is ignored), returns the Ada slice of HIGH-LOW+1
02640    elements starting at index LOW.  The lower bound of this array is LOW, as
02641    per Ada rules.  */
02642 static struct value *
02643 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
02644                           int low, int high)
02645 {
02646   struct type *type0 = ada_check_typedef (type);
02647   CORE_ADDR base = value_as_address (array_ptr)
02648     + ((low - ada_discrete_type_low_bound (TYPE_INDEX_TYPE (type0)))
02649        * TYPE_LENGTH (TYPE_TARGET_TYPE (type0)));
02650   struct type *index_type =
02651     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type0)),
02652                        low, high);
02653   struct type *slice_type =
02654     create_array_type (NULL, TYPE_TARGET_TYPE (type0), index_type);
02655 
02656   return value_at_lazy (slice_type, base);
02657 }
02658 
02659 
02660 static struct value *
02661 ada_value_slice (struct value *array, int low, int high)
02662 {
02663   struct type *type = ada_check_typedef (value_type (array));
02664   struct type *index_type =
02665     create_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
02666   struct type *slice_type =
02667     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
02668 
02669   return value_cast (slice_type, value_slice (array, low, high - low + 1));
02670 }
02671 
02672 /* If type is a record type in the form of a standard GNAT array
02673    descriptor, returns the number of dimensions for type.  If arr is a
02674    simple array, returns the number of "array of"s that prefix its
02675    type designation.  Otherwise, returns 0.  */
02676 
02677 int
02678 ada_array_arity (struct type *type)
02679 {
02680   int arity;
02681 
02682   if (type == NULL)
02683     return 0;
02684 
02685   type = desc_base_type (type);
02686 
02687   arity = 0;
02688   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
02689     return desc_arity (desc_bounds_type (type));
02690   else
02691     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
02692       {
02693         arity += 1;
02694         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
02695       }
02696 
02697   return arity;
02698 }
02699 
02700 /* If TYPE is a record type in the form of a standard GNAT array
02701    descriptor or a simple array type, returns the element type for
02702    TYPE after indexing by NINDICES indices, or by all indices if
02703    NINDICES is -1.  Otherwise, returns NULL.  */
02704 
02705 struct type *
02706 ada_array_element_type (struct type *type, int nindices)
02707 {
02708   type = desc_base_type (type);
02709 
02710   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
02711     {
02712       int k;
02713       struct type *p_array_type;
02714 
02715       p_array_type = desc_data_target_type (type);
02716 
02717       k = ada_array_arity (type);
02718       if (k == 0)
02719         return NULL;
02720 
02721       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
02722       if (nindices >= 0 && k > nindices)
02723         k = nindices;
02724       while (k > 0 && p_array_type != NULL)
02725         {
02726           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
02727           k -= 1;
02728         }
02729       return p_array_type;
02730     }
02731   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
02732     {
02733       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
02734         {
02735           type = TYPE_TARGET_TYPE (type);
02736           nindices -= 1;
02737         }
02738       return type;
02739     }
02740 
02741   return NULL;
02742 }
02743 
02744 /* The type of nth index in arrays of given type (n numbering from 1).
02745    Does not examine memory.  Throws an error if N is invalid or TYPE
02746    is not an array type.  NAME is the name of the Ada attribute being
02747    evaluated ('range, 'first, 'last, or 'length); it is used in building
02748    the error message.  */
02749 
02750 static struct type *
02751 ada_index_type (struct type *type, int n, const char *name)
02752 {
02753   struct type *result_type;
02754 
02755   type = desc_base_type (type);
02756 
02757   if (n < 0 || n > ada_array_arity (type))
02758     error (_("invalid dimension number to '%s"), name);
02759 
02760   if (ada_is_simple_array_type (type))
02761     {
02762       int i;
02763 
02764       for (i = 1; i < n; i += 1)
02765         type = TYPE_TARGET_TYPE (type);
02766       result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
02767       /* FIXME: The stabs type r(0,0);bound;bound in an array type
02768          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
02769          perhaps stabsread.c would make more sense.  */
02770       if (result_type && TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
02771         result_type = NULL;
02772     }
02773   else
02774     {
02775       result_type = desc_index_type (desc_bounds_type (type), n);
02776       if (result_type == NULL)
02777         error (_("attempt to take bound of something that is not an array"));
02778     }
02779 
02780   return result_type;
02781 }
02782 
02783 /* Given that arr is an array type, returns the lower bound of the
02784    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
02785    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
02786    array-descriptor type.  It works for other arrays with bounds supplied
02787    by run-time quantities other than discriminants.  */
02788 
02789 static LONGEST
02790 ada_array_bound_from_type (struct type * arr_type, int n, int which)
02791 {
02792   struct type *type, *elt_type, *index_type_desc, *index_type;
02793   int i;
02794 
02795   gdb_assert (which == 0 || which == 1);
02796 
02797   if (ada_is_constrained_packed_array_type (arr_type))
02798     arr_type = decode_constrained_packed_array_type (arr_type);
02799 
02800   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
02801     return (LONGEST) - which;
02802 
02803   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
02804     type = TYPE_TARGET_TYPE (arr_type);
02805   else
02806     type = arr_type;
02807 
02808   elt_type = type;
02809   for (i = n; i > 1; i--)
02810     elt_type = TYPE_TARGET_TYPE (type);
02811 
02812   index_type_desc = ada_find_parallel_type (type, "___XA");
02813   ada_fixup_array_indexes_type (index_type_desc);
02814   if (index_type_desc != NULL)
02815     index_type = to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, n - 1),
02816                                       NULL);
02817   else
02818     index_type = TYPE_INDEX_TYPE (elt_type);
02819 
02820   return
02821     (LONGEST) (which == 0
02822                ? ada_discrete_type_low_bound (index_type)
02823                : ada_discrete_type_high_bound (index_type));
02824 }
02825 
02826 /* Given that arr is an array value, returns the lower bound of the
02827    nth index (numbering from 1) if WHICH is 0, and the upper bound if
02828    WHICH is 1.  This routine will also work for arrays with bounds
02829    supplied by run-time quantities other than discriminants.  */
02830 
02831 static LONGEST
02832 ada_array_bound (struct value *arr, int n, int which)
02833 {
02834   struct type *arr_type = value_type (arr);
02835 
02836   if (ada_is_constrained_packed_array_type (arr_type))
02837     return ada_array_bound (decode_constrained_packed_array (arr), n, which);
02838   else if (ada_is_simple_array_type (arr_type))
02839     return ada_array_bound_from_type (arr_type, n, which);
02840   else
02841     return value_as_long (desc_one_bound (desc_bounds (arr), n, which));
02842 }
02843 
02844 /* Given that arr is an array value, returns the length of the
02845    nth index.  This routine will also work for arrays with bounds
02846    supplied by run-time quantities other than discriminants.
02847    Does not work for arrays indexed by enumeration types with representation
02848    clauses at the moment.  */
02849 
02850 static LONGEST
02851 ada_array_length (struct value *arr, int n)
02852 {
02853   struct type *arr_type = ada_check_typedef (value_type (arr));
02854 
02855   if (ada_is_constrained_packed_array_type (arr_type))
02856     return ada_array_length (decode_constrained_packed_array (arr), n);
02857 
02858   if (ada_is_simple_array_type (arr_type))
02859     return (ada_array_bound_from_type (arr_type, n, 1)
02860             - ada_array_bound_from_type (arr_type, n, 0) + 1);
02861   else
02862     return (value_as_long (desc_one_bound (desc_bounds (arr), n, 1))
02863             - value_as_long (desc_one_bound (desc_bounds (arr), n, 0)) + 1);
02864 }
02865 
02866 /* An empty array whose type is that of ARR_TYPE (an array type),
02867    with bounds LOW to LOW-1.  */
02868 
02869 static struct value *
02870 empty_array (struct type *arr_type, int low)
02871 {
02872   struct type *arr_type0 = ada_check_typedef (arr_type);
02873   struct type *index_type =
02874     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type0)),
02875                        low, low - 1);
02876   struct type *elt_type = ada_array_element_type (arr_type0, 1);
02877 
02878   return allocate_value (create_array_type (NULL, elt_type, index_type));
02879 }
02880 
02881 
02882                                 /* Name resolution */
02883 
02884 /* The "decoded" name for the user-definable Ada operator corresponding
02885    to OP.  */
02886 
02887 static const char *
02888 ada_decoded_op_name (enum exp_opcode op)
02889 {
02890   int i;
02891 
02892   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
02893     {
02894       if (ada_opname_table[i].op == op)
02895         return ada_opname_table[i].decoded;
02896     }
02897   error (_("Could not find operator name for opcode"));
02898 }
02899 
02900 
02901 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
02902    references (marked by OP_VAR_VALUE nodes in which the symbol has an
02903    undefined namespace) and converts operators that are
02904    user-defined into appropriate function calls.  If CONTEXT_TYPE is
02905    non-null, it provides a preferred result type [at the moment, only
02906    type void has any effect---causing procedures to be preferred over
02907    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
02908    return type is preferred.  May change (expand) *EXP.  */
02909 
02910 static void
02911 resolve (struct expression **expp, int void_context_p)
02912 {
02913   struct type *context_type = NULL;
02914   int pc = 0;
02915 
02916   if (void_context_p)
02917     context_type = builtin_type ((*expp)->gdbarch)->builtin_void;
02918 
02919   resolve_subexp (expp, &pc, 1, context_type);
02920 }
02921 
02922 /* Resolve the operator of the subexpression beginning at
02923    position *POS of *EXPP.  "Resolving" consists of replacing
02924    the symbols that have undefined namespaces in OP_VAR_VALUE nodes
02925    with their resolutions, replacing built-in operators with
02926    function calls to user-defined operators, where appropriate, and,
02927    when DEPROCEDURE_P is non-zero, converting function-valued variables
02928    into parameterless calls.  May expand *EXPP.  The CONTEXT_TYPE functions
02929    are as in ada_resolve, above.  */
02930 
02931 static struct value *
02932 resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
02933                 struct type *context_type)
02934 {
02935   int pc = *pos;
02936   int i;
02937   struct expression *exp;       /* Convenience: == *expp.  */
02938   enum exp_opcode op = (*expp)->elts[pc].opcode;
02939   struct value **argvec;        /* Vector of operand types (alloca'ed).  */
02940   int nargs;                    /* Number of operands.  */
02941   int oplen;
02942 
02943   argvec = NULL;
02944   nargs = 0;
02945   exp = *expp;
02946 
02947   /* Pass one: resolve operands, saving their types and updating *pos,
02948      if needed.  */
02949   switch (op)
02950     {
02951     case OP_FUNCALL:
02952       if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
02953           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
02954         *pos += 7;
02955       else
02956         {
02957           *pos += 3;
02958           resolve_subexp (expp, pos, 0, NULL);
02959         }
02960       nargs = longest_to_int (exp->elts[pc + 1].longconst);
02961       break;
02962 
02963     case UNOP_ADDR:
02964       *pos += 1;
02965       resolve_subexp (expp, pos, 0, NULL);
02966       break;
02967 
02968     case UNOP_QUAL:
02969       *pos += 3;
02970       resolve_subexp (expp, pos, 1, check_typedef (exp->elts[pc + 1].type));
02971       break;
02972 
02973     case OP_ATR_MODULUS:
02974     case OP_ATR_SIZE:
02975     case OP_ATR_TAG:
02976     case OP_ATR_FIRST:
02977     case OP_ATR_LAST:
02978     case OP_ATR_LENGTH:
02979     case OP_ATR_POS:
02980     case OP_ATR_VAL:
02981     case OP_ATR_MIN:
02982     case OP_ATR_MAX:
02983     case TERNOP_IN_RANGE:
02984     case BINOP_IN_BOUNDS:
02985     case UNOP_IN_RANGE:
02986     case OP_AGGREGATE:
02987     case OP_OTHERS:
02988     case OP_CHOICES:
02989     case OP_POSITIONAL:
02990     case OP_DISCRETE_RANGE:
02991     case OP_NAME:
02992       ada_forward_operator_length (exp, pc, &oplen, &nargs);
02993       *pos += oplen;
02994       break;
02995 
02996     case BINOP_ASSIGN:
02997       {
02998         struct value *arg1;
02999 
03000         *pos += 1;
03001         arg1 = resolve_subexp (expp, pos, 0, NULL);
03002         if (arg1 == NULL)
03003           resolve_subexp (expp, pos, 1, NULL);
03004         else
03005           resolve_subexp (expp, pos, 1, value_type (arg1));
03006         break;
03007       }
03008 
03009     case UNOP_CAST:
03010       *pos += 3;
03011       nargs = 1;
03012       break;
03013 
03014     case BINOP_ADD:
03015     case BINOP_SUB:
03016     case BINOP_MUL:
03017     case BINOP_DIV:
03018     case BINOP_REM:
03019     case BINOP_MOD:
03020     case BINOP_EXP:
03021     case BINOP_CONCAT:
03022     case BINOP_LOGICAL_AND:
03023     case BINOP_LOGICAL_OR:
03024     case BINOP_BITWISE_AND:
03025     case BINOP_BITWISE_IOR:
03026     case BINOP_BITWISE_XOR:
03027 
03028     case BINOP_EQUAL:
03029     case BINOP_NOTEQUAL:
03030     case BINOP_LESS:
03031     case BINOP_GTR:
03032     case BINOP_LEQ:
03033     case BINOP_GEQ:
03034 
03035     case BINOP_REPEAT:
03036     case BINOP_SUBSCRIPT:
03037     case BINOP_COMMA:
03038       *pos += 1;
03039       nargs = 2;
03040       break;
03041 
03042     case UNOP_NEG:
03043     case UNOP_PLUS:
03044     case UNOP_LOGICAL_NOT:
03045     case UNOP_ABS:
03046     case UNOP_IND:
03047       *pos += 1;
03048       nargs = 1;
03049       break;
03050 
03051     case OP_LONG:
03052     case OP_DOUBLE:
03053     case OP_VAR_VALUE:
03054       *pos += 4;
03055       break;
03056 
03057     case OP_TYPE:
03058     case OP_BOOL:
03059     case OP_LAST:
03060     case OP_INTERNALVAR:
03061       *pos += 3;
03062       break;
03063 
03064     case UNOP_MEMVAL:
03065       *pos += 3;
03066       nargs = 1;
03067       break;
03068 
03069     case OP_REGISTER:
03070       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
03071       break;
03072 
03073     case STRUCTOP_STRUCT:
03074       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
03075       nargs = 1;
03076       break;
03077 
03078     case TERNOP_SLICE:
03079       *pos += 1;
03080       nargs = 3;
03081       break;
03082 
03083     case OP_STRING:
03084       break;
03085 
03086     default:
03087       error (_("Unexpected operator during name resolution"));
03088     }
03089 
03090   argvec = (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
03091   for (i = 0; i < nargs; i += 1)
03092     argvec[i] = resolve_subexp (expp, pos, 1, NULL);
03093   argvec[i] = NULL;
03094   exp = *expp;
03095 
03096   /* Pass two: perform any resolution on principal operator.  */
03097   switch (op)
03098     {
03099     default:
03100       break;
03101 
03102     case OP_VAR_VALUE:
03103       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
03104         {
03105           struct ada_symbol_info *candidates;
03106           int n_candidates;
03107 
03108           n_candidates =
03109             ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
03110                                     (exp->elts[pc + 2].symbol),
03111                                     exp->elts[pc + 1].block, VAR_DOMAIN,
03112                                     &candidates);
03113 
03114           if (n_candidates > 1)
03115             {
03116               /* Types tend to get re-introduced locally, so if there
03117                  are any local symbols that are not types, first filter
03118                  out all types.  */
03119               int j;
03120               for (j = 0; j < n_candidates; j += 1)
03121                 switch (SYMBOL_CLASS (candidates[j].sym))
03122                   {
03123                   case LOC_REGISTER:
03124                   case LOC_ARG:
03125                   case LOC_REF_ARG:
03126                   case LOC_REGPARM_ADDR:
03127                   case LOC_LOCAL:
03128                   case LOC_COMPUTED:
03129                     goto FoundNonType;
03130                   default:
03131                     break;
03132                   }
03133             FoundNonType:
03134               if (j < n_candidates)
03135                 {
03136                   j = 0;
03137                   while (j < n_candidates)
03138                     {
03139                       if (SYMBOL_CLASS (candidates[j].sym) == LOC_TYPEDEF)
03140                         {
03141                           candidates[j] = candidates[n_candidates - 1];
03142                           n_candidates -= 1;
03143                         }
03144                       else
03145                         j += 1;
03146                     }
03147                 }
03148             }
03149 
03150           if (n_candidates == 0)
03151             error (_("No definition found for %s"),
03152                    SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
03153           else if (n_candidates == 1)
03154             i = 0;
03155           else if (deprocedure_p
03156                    && !is_nonfunction (candidates, n_candidates))
03157             {
03158               i = ada_resolve_function
03159                 (candidates, n_candidates, NULL, 0,
03160                  SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
03161                  context_type);
03162               if (i < 0)
03163                 error (_("Could not find a match for %s"),
03164                        SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
03165             }
03166           else
03167             {
03168               printf_filtered (_("Multiple matches for %s\n"),
03169                                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
03170               user_select_syms (candidates, n_candidates, 1);
03171               i = 0;
03172             }
03173 
03174           exp->elts[pc + 1].block = candidates[i].block;
03175           exp->elts[pc + 2].symbol = candidates[i].sym;
03176           if (innermost_block == NULL
03177               || contained_in (candidates[i].block, innermost_block))
03178             innermost_block = candidates[i].block;
03179         }
03180 
03181       if (deprocedure_p
03182           && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
03183               == TYPE_CODE_FUNC))
03184         {
03185           replace_operator_with_call (expp, pc, 0, 0,
03186                                       exp->elts[pc + 2].symbol,
03187                                       exp->elts[pc + 1].block);
03188           exp = *expp;
03189         }
03190       break;
03191 
03192     case OP_FUNCALL:
03193       {
03194         if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
03195             && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
03196           {
03197             struct ada_symbol_info *candidates;
03198             int n_candidates;
03199 
03200             n_candidates =
03201               ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
03202                                       (exp->elts[pc + 5].symbol),
03203                                       exp->elts[pc + 4].block, VAR_DOMAIN,
03204                                       &candidates);
03205             if (n_candidates == 1)
03206               i = 0;
03207             else
03208               {
03209                 i = ada_resolve_function
03210                   (candidates, n_candidates,
03211                    argvec, nargs,
03212                    SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
03213                    context_type);
03214                 if (i < 0)
03215                   error (_("Could not find a match for %s"),
03216                          SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
03217               }
03218 
03219             exp->elts[pc + 4].block = candidates[i].block;
03220             exp->elts[pc + 5].symbol = candidates[i].sym;
03221             if (innermost_block == NULL
03222                 || contained_in (candidates[i].block, innermost_block))
03223               innermost_block = candidates[i].block;
03224           }
03225       }
03226       break;
03227     case BINOP_ADD:
03228     case BINOP_SUB:
03229     case BINOP_MUL:
03230     case BINOP_DIV:
03231     case BINOP_REM:
03232     case BINOP_MOD:
03233     case BINOP_CONCAT:
03234     case BINOP_BITWISE_AND:
03235     case BINOP_BITWISE_IOR:
03236     case BINOP_BITWISE_XOR:
03237     case BINOP_EQUAL:
03238     case BINOP_NOTEQUAL:
03239     case BINOP_LESS:
03240     case BINOP_GTR:
03241     case BINOP_LEQ:
03242     case BINOP_GEQ:
03243     case BINOP_EXP:
03244     case UNOP_NEG:
03245     case UNOP_PLUS:
03246     case UNOP_LOGICAL_NOT:
03247     case UNOP_ABS:
03248       if (possible_user_operator_p (op, argvec))
03249         {
03250           struct ada_symbol_info *candidates;
03251           int n_candidates;
03252 
03253           n_candidates =
03254             ada_lookup_symbol_list (ada_encode (ada_decoded_op_name (op)),
03255                                     (struct block *) NULL, VAR_DOMAIN,
03256                                     &candidates);
03257           i = ada_resolve_function (candidates, n_candidates, argvec, nargs,
03258                                     ada_decoded_op_name (op), NULL);
03259           if (i < 0)
03260             break;
03261 
03262           replace_operator_with_call (expp, pc, nargs, 1,
03263                                       candidates[i].sym, candidates[i].block);
03264           exp = *expp;
03265         }
03266       break;
03267 
03268     case OP_TYPE:
03269     case OP_REGISTER:
03270       return NULL;
03271     }
03272 
03273   *pos = pc;
03274   return evaluate_subexp_type (exp, pos);
03275 }
03276 
03277 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
03278    MAY_DEREF is non-zero, the formal may be a pointer and the actual
03279    a non-pointer.  */
03280 /* The term "match" here is rather loose.  The match is heuristic and
03281    liberal.  */
03282 
03283 static int
03284 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
03285 {
03286   ftype = ada_check_typedef (ftype);
03287   atype = ada_check_typedef (atype);
03288 
03289   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
03290     ftype = TYPE_TARGET_TYPE (ftype);
03291   if (TYPE_CODE (atype) == TYPE_CODE_REF)
03292     atype = TYPE_TARGET_TYPE (atype);
03293 
03294   switch (TYPE_CODE (ftype))
03295     {
03296     default:
03297       return TYPE_CODE (ftype) == TYPE_CODE (atype);
03298     case TYPE_CODE_PTR:
03299       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
03300         return ada_type_match (TYPE_TARGET_TYPE (ftype),
03301                                TYPE_TARGET_TYPE (atype), 0);
03302       else
03303         return (may_deref
03304                 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
03305     case TYPE_CODE_INT:
03306     case TYPE_CODE_ENUM:
03307     case TYPE_CODE_RANGE:
03308       switch (TYPE_CODE (atype))
03309         {
03310         case TYPE_CODE_INT:
03311         case TYPE_CODE_ENUM:
03312         case TYPE_CODE_RANGE:
03313           return 1;
03314         default:
03315           return 0;
03316         }
03317 
03318     case TYPE_CODE_ARRAY:
03319       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
03320               || ada_is_array_descriptor_type (atype));
03321 
03322     case TYPE_CODE_STRUCT:
03323       if (ada_is_array_descriptor_type (ftype))
03324         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
03325                 || ada_is_array_descriptor_type (atype));
03326       else
03327         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
03328                 && !ada_is_array_descriptor_type (atype));
03329 
03330     case TYPE_CODE_UNION:
03331     case TYPE_CODE_FLT:
03332       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
03333     }
03334 }
03335 
03336 /* Return non-zero if the formals of FUNC "sufficiently match" the
03337    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
03338    may also be an enumeral, in which case it is treated as a 0-
03339    argument function.  */
03340 
03341 static int
03342 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
03343 {
03344   int i;
03345   struct type *func_type = SYMBOL_TYPE (func);
03346 
03347   if (SYMBOL_CLASS (func) == LOC_CONST
03348       && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
03349     return (n_actuals == 0);
03350   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
03351     return 0;
03352 
03353   if (TYPE_NFIELDS (func_type) != n_actuals)
03354     return 0;
03355 
03356   for (i = 0; i < n_actuals; i += 1)
03357     {
03358       if (actuals[i] == NULL)
03359         return 0;
03360       else
03361         {
03362           struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type,
03363                                                                    i));
03364           struct type *atype = ada_check_typedef (value_type (actuals[i]));
03365 
03366           if (!ada_type_match (ftype, atype, 1))
03367             return 0;
03368         }
03369     }
03370   return 1;
03371 }
03372 
03373 /* False iff function type FUNC_TYPE definitely does not produce a value
03374    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
03375    FUNC_TYPE is not a valid function type with a non-null return type
03376    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
03377 
03378 static int
03379 return_match (struct type *func_type, struct type *context_type)
03380 {
03381   struct type *return_type;
03382 
03383   if (func_type == NULL)
03384     return 1;
03385 
03386   if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
03387     return_type = get_base_type (TYPE_TARGET_TYPE (func_type));
03388   else
03389     return_type = get_base_type (func_type);
03390   if (return_type == NULL)
03391     return 1;
03392 
03393   context_type = get_base_type (context_type);
03394 
03395   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
03396     return context_type == NULL || return_type == context_type;
03397   else if (context_type == NULL)
03398     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
03399   else
03400     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
03401 }
03402 
03403 
03404 /* Returns the index in SYMS[0..NSYMS-1] that contains  the symbol for the
03405    function (if any) that matches the types of the NARGS arguments in
03406    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
03407    that returns that type, then eliminate matches that don't.  If
03408    CONTEXT_TYPE is void and there is at least one match that does not
03409    return void, eliminate all matches that do.
03410 
03411    Asks the user if there is more than one match remaining.  Returns -1
03412    if there is no such symbol or none is selected.  NAME is used
03413    solely for messages.  May re-arrange and modify SYMS in
03414    the process; the index returned is for the modified vector.  */
03415 
03416 static int
03417 ada_resolve_function (struct ada_symbol_info syms[],
03418                       int nsyms, struct value **args, int nargs,
03419                       const char *name, struct type *context_type)
03420 {
03421   int fallback;
03422   int k;
03423   int m;                        /* Number of hits */
03424 
03425   m = 0;
03426   /* In the first pass of the loop, we only accept functions matching
03427      context_type.  If none are found, we add a second pass of the loop
03428      where every function is accepted.  */
03429   for (fallback = 0; m == 0 && fallback < 2; fallback++)
03430     {
03431       for (k = 0; k < nsyms; k += 1)
03432         {
03433           struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].sym));
03434 
03435           if (ada_args_match (syms[k].sym, args, nargs)
03436               && (fallback || return_match (type, context_type)))
03437             {
03438               syms[m] = syms[k];
03439               m += 1;
03440             }
03441         }
03442     }
03443 
03444   if (m == 0)
03445     return -1;
03446   else if (m > 1)
03447     {
03448       printf_filtered (_("Multiple matches for %s\n"), name);
03449       user_select_syms (syms, m, 1);
03450       return 0;
03451     }
03452   return 0;
03453 }
03454 
03455 /* Returns true (non-zero) iff decoded name N0 should appear before N1
03456    in a listing of choices during disambiguation (see sort_choices, below).
03457    The idea is that overloadings of a subprogram name from the
03458    same package should sort in their source order.  We settle for ordering
03459    such symbols by their trailing number (__N  or $N).  */
03460 
03461 static int
03462 encoded_ordered_before (const char *N0, const char *N1)
03463 {
03464   if (N1 == NULL)
03465     return 0;
03466   else if (N0 == NULL)
03467     return 1;
03468   else
03469     {
03470       int k0, k1;
03471 
03472       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
03473         ;
03474       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
03475         ;
03476       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
03477           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
03478         {
03479           int n0, n1;
03480 
03481           n0 = k0;
03482           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
03483             n0 -= 1;
03484           n1 = k1;
03485           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
03486             n1 -= 1;
03487           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
03488             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
03489         }
03490       return (strcmp (N0, N1) < 0);
03491     }
03492 }
03493 
03494 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
03495    encoded names.  */
03496 
03497 static void
03498 sort_choices (struct ada_symbol_info syms[], int nsyms)
03499 {
03500   int i;
03501 
03502   for (i = 1; i < nsyms; i += 1)
03503     {
03504       struct ada_symbol_info sym = syms[i];
03505       int j;
03506 
03507       for (j = i - 1; j >= 0; j -= 1)
03508         {
03509           if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].sym),
03510                                       SYMBOL_LINKAGE_NAME (sym.sym)))
03511             break;
03512           syms[j + 1] = syms[j];
03513         }
03514       syms[j + 1] = sym;
03515     }
03516 }
03517 
03518 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0 
03519    by asking the user (if necessary), returning the number selected, 
03520    and setting the first elements of SYMS items.  Error if no symbols
03521    selected.  */
03522 
03523 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
03524    to be re-integrated one of these days.  */
03525 
03526 int
03527 user_select_syms (struct ada_symbol_info *syms, int nsyms, int max_results)
03528 {
03529   int i;
03530   int *chosen = (int *) alloca (sizeof (int) * nsyms);
03531   int n_chosen;
03532   int first_choice = (max_results == 1) ? 1 : 2;
03533   const char *select_mode = multiple_symbols_select_mode ();
03534 
03535   if (max_results < 1)
03536     error (_("Request to select 0 symbols!"));
03537   if (nsyms <= 1)
03538     return nsyms;
03539 
03540   if (select_mode == multiple_symbols_cancel)
03541     error (_("\
03542 canceled because the command is ambiguous\n\
03543 See set/show multiple-symbol."));
03544   
03545   /* If select_mode is "all", then return all possible symbols.
03546      Only do that if more than one symbol can be selected, of course.
03547      Otherwise, display the menu as usual.  */
03548   if (select_mode == multiple_symbols_all && max_results > 1)
03549     return nsyms;
03550 
03551   printf_unfiltered (_("[0] cancel\n"));
03552   if (max_results > 1)
03553     printf_unfiltered (_("[1] all\n"));
03554 
03555   sort_choices (syms, nsyms);
03556 
03557   for (i = 0; i < nsyms; i += 1)
03558     {
03559       if (syms[i].sym == NULL)
03560         continue;
03561 
03562       if (SYMBOL_CLASS (syms[i].sym) == LOC_BLOCK)
03563         {
03564           struct symtab_and_line sal =
03565             find_function_start_sal (syms[i].sym, 1);
03566 
03567           if (sal.symtab == NULL)
03568             printf_unfiltered (_("[%d] %s at <no source file available>:%d\n"),
03569                                i + first_choice,
03570                                SYMBOL_PRINT_NAME (syms[i].sym),
03571                                sal.line);
03572           else
03573             printf_unfiltered (_("[%d] %s at %s:%d\n"), i + first_choice,
03574                                SYMBOL_PRINT_NAME (syms[i].sym),
03575                                symtab_to_filename_for_display (sal.symtab),
03576                                sal.line);
03577           continue;
03578         }
03579       else
03580         {
03581           int is_enumeral =
03582             (SYMBOL_CLASS (syms[i].sym) == LOC_CONST
03583              && SYMBOL_TYPE (syms[i].sym) != NULL
03584              && TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) == TYPE_CODE_ENUM);
03585           struct symtab *symtab = SYMBOL_SYMTAB (syms[i].sym);
03586 
03587           if (SYMBOL_LINE (syms[i].sym) != 0 && symtab != NULL)
03588             printf_unfiltered (_("[%d] %s at %s:%d\n"),
03589                                i + first_choice,
03590                                SYMBOL_PRINT_NAME (syms[i].sym),
03591                                symtab_to_filename_for_display (symtab),
03592                                SYMBOL_LINE (syms[i].sym));
03593           else if (is_enumeral
03594                    && TYPE_NAME (SYMBOL_TYPE (syms[i].sym)) != NULL)
03595             {
03596               printf_unfiltered (("[%d] "), i + first_choice);
03597               ada_print_type (SYMBOL_TYPE (syms[i].sym), NULL,
03598                               gdb_stdout, -1, 0, &type_print_raw_options);
03599               printf_unfiltered (_("'(%s) (enumeral)\n"),
03600                                  SYMBOL_PRINT_NAME (syms[i].sym));
03601             }
03602           else if (symtab != NULL)
03603             printf_unfiltered (is_enumeral
03604                                ? _("[%d] %s in %s (enumeral)\n")
03605                                : _("[%d] %s at %s:?\n"),
03606                                i + first_choice,
03607                                SYMBOL_PRINT_NAME (syms[i].sym),
03608                                symtab_to_filename_for_display (symtab));
03609           else
03610             printf_unfiltered (is_enumeral
03611                                ? _("[%d] %s (enumeral)\n")
03612                                : _("[%d] %s at ?\n"),
03613                                i + first_choice,
03614                                SYMBOL_PRINT_NAME (syms[i].sym));
03615         }
03616     }
03617 
03618   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
03619                              "overload-choice");
03620 
03621   for (i = 0; i < n_chosen; i += 1)
03622     syms[i] = syms[chosen[i]];
03623 
03624   return n_chosen;
03625 }
03626 
03627 /* Read and validate a set of numeric choices from the user in the
03628    range 0 .. N_CHOICES-1.  Place the results in increasing
03629    order in CHOICES[0 .. N-1], and return N.
03630 
03631    The user types choices as a sequence of numbers on one line
03632    separated by blanks, encoding them as follows:
03633 
03634      + A choice of 0 means to cancel the selection, throwing an error.
03635      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
03636      + The user chooses k by typing k+IS_ALL_CHOICE+1.
03637 
03638    The user is not allowed to choose more than MAX_RESULTS values.
03639 
03640    ANNOTATION_SUFFIX, if present, is used to annotate the input
03641    prompts (for use with the -f switch).  */
03642 
03643 int
03644 get_selections (int *choices, int n_choices, int max_results,
03645                 int is_all_choice, char *annotation_suffix)
03646 {
03647   char *args;
03648   char *prompt;
03649   int n_chosen;
03650   int first_choice = is_all_choice ? 2 : 1;
03651 
03652   prompt = getenv ("PS2");
03653   if (prompt == NULL)
03654     prompt = "> ";
03655 
03656   args = command_line_input (prompt, 0, annotation_suffix);
03657 
03658   if (args == NULL)
03659     error_no_arg (_("one or more choice numbers"));
03660 
03661   n_chosen = 0;
03662 
03663   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
03664      order, as given in args.  Choices are validated.  */
03665   while (1)
03666     {
03667       char *args2;
03668       int choice, j;
03669 
03670       args = skip_spaces (args);
03671       if (*args == '\0' && n_chosen == 0)
03672         error_no_arg (_("one or more choice numbers"));
03673       else if (*args == '\0')
03674         break;
03675 
03676       choice = strtol (args, &args2, 10);
03677       if (args == args2 || choice < 0
03678           || choice > n_choices + first_choice - 1)
03679         error (_("Argument must be choice number"));
03680       args = args2;
03681 
03682       if (choice == 0)
03683         error (_("cancelled"));
03684 
03685       if (choice < first_choice)
03686         {
03687           n_chosen = n_choices;
03688           for (j = 0; j < n_choices; j += 1)
03689             choices[j] = j;
03690           break;
03691         }
03692       choice -= first_choice;
03693 
03694       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
03695         {
03696         }
03697 
03698       if (j < 0 || choice != choices[j])
03699         {
03700           int k;
03701 
03702           for (k = n_chosen - 1; k > j; k -= 1)
03703             choices[k + 1] = choices[k];
03704           choices[j + 1] = choice;
03705           n_chosen += 1;
03706         }
03707     }
03708 
03709   if (n_chosen > max_results)
03710     error (_("Select no more than %d of the above"), max_results);
03711 
03712   return n_chosen;
03713 }
03714 
03715 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
03716    on the function identified by SYM and BLOCK, and taking NARGS
03717    arguments.  Update *EXPP as needed to hold more space.  */
03718 
03719 static void
03720 replace_operator_with_call (struct expression **expp, int pc, int nargs,
03721                             int oplen, struct symbol *sym,
03722                             const struct block *block)
03723 {
03724   /* A new expression, with 6 more elements (3 for funcall, 4 for function
03725      symbol, -oplen for operator being replaced).  */
03726   struct expression *newexp = (struct expression *)
03727     xzalloc (sizeof (struct expression)
03728              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
03729   struct expression *exp = *expp;
03730 
03731   newexp->nelts = exp->nelts + 7 - oplen;
03732   newexp->language_defn = exp->language_defn;
03733   newexp->gdbarch = exp->gdbarch;
03734   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
03735   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
03736           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
03737 
03738   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
03739   newexp->elts[pc + 1].longconst = (LONGEST) nargs;
03740 
03741   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
03742   newexp->elts[pc + 4].block = block;
03743   newexp->elts[pc + 5].symbol = sym;
03744 
03745   *expp = newexp;
03746   xfree (exp);
03747 }
03748 
03749 /* Type-class predicates */
03750 
03751 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
03752    or FLOAT).  */
03753 
03754 static int
03755 numeric_type_p (struct type *type)
03756 {
03757   if (type == NULL)
03758     return 0;
03759   else
03760     {
03761       switch (TYPE_CODE (type))
03762         {
03763         case TYPE_CODE_INT:
03764         case TYPE_CODE_FLT:
03765           return 1;
03766         case TYPE_CODE_RANGE:
03767           return (type == TYPE_TARGET_TYPE (type)
03768                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
03769         default:
03770           return 0;
03771         }
03772     }
03773 }
03774 
03775 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
03776 
03777 static int
03778 integer_type_p (struct type *type)
03779 {
03780   if (type == NULL)
03781     return 0;
03782   else
03783     {
03784       switch (TYPE_CODE (type))
03785         {
03786         case TYPE_CODE_INT:
03787           return 1;
03788         case TYPE_CODE_RANGE:
03789           return (type == TYPE_TARGET_TYPE (type)
03790                   || integer_type_p (TYPE_TARGET_TYPE (type)));
03791         default:
03792           return 0;
03793         }
03794     }
03795 }
03796 
03797 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
03798 
03799 static int
03800 scalar_type_p (struct type *type)
03801 {
03802   if (type == NULL)
03803     return 0;
03804   else
03805     {
03806       switch (TYPE_CODE (type))
03807         {
03808         case TYPE_CODE_INT:
03809         case TYPE_CODE_RANGE:
03810         case TYPE_CODE_ENUM:
03811         case TYPE_CODE_FLT:
03812           return 1;
03813         default:
03814           return 0;
03815         }
03816     }
03817 }
03818 
03819 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
03820 
03821 static int
03822 discrete_type_p (struct type *type)
03823 {
03824   if (type == NULL)
03825     return 0;
03826   else
03827     {
03828       switch (TYPE_CODE (type))
03829         {
03830         case TYPE_CODE_INT:
03831         case TYPE_CODE_RANGE:
03832         case TYPE_CODE_ENUM:
03833         case TYPE_CODE_BOOL:
03834           return 1;
03835         default:
03836           return 0;
03837         }
03838     }
03839 }
03840 
03841 /* Returns non-zero if OP with operands in the vector ARGS could be
03842    a user-defined function.  Errs on the side of pre-defined operators
03843    (i.e., result 0).  */
03844 
03845 static int
03846 possible_user_operator_p (enum exp_opcode op, struct value *args[])
03847 {
03848   struct type *type0 =
03849     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
03850   struct type *type1 =
03851     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
03852 
03853   if (type0 == NULL)
03854     return 0;
03855 
03856   switch (op)
03857     {
03858     default:
03859       return 0;
03860 
03861     case BINOP_ADD:
03862     case BINOP_SUB:
03863     case BINOP_MUL:
03864     case BINOP_DIV:
03865       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
03866 
03867     case BINOP_REM:
03868     case BINOP_MOD:
03869     case BINOP_BITWISE_AND:
03870     case BINOP_BITWISE_IOR:
03871     case BINOP_BITWISE_XOR:
03872       return (!(integer_type_p (type0) && integer_type_p (type1)));
03873 
03874     case BINOP_EQUAL:
03875     case BINOP_NOTEQUAL:
03876     case BINOP_LESS:
03877     case BINOP_GTR:
03878     case BINOP_LEQ:
03879     case BINOP_GEQ:
03880       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
03881 
03882     case BINOP_CONCAT:
03883       return !ada_is_array_type (type0) || !ada_is_array_type (type1);
03884 
03885     case BINOP_EXP:
03886       return (!(numeric_type_p (type0) && integer_type_p (type1)));
03887 
03888     case UNOP_NEG:
03889     case UNOP_PLUS:
03890     case UNOP_LOGICAL_NOT:
03891     case UNOP_ABS:
03892       return (!numeric_type_p (type0));
03893 
03894     }
03895 }
03896 
03897                                 /* Renaming */
03898 
03899 /* NOTES: 
03900 
03901    1. In the following, we assume that a renaming type's name may
03902       have an ___XD suffix.  It would be nice if this went away at some
03903       point.
03904    2. We handle both the (old) purely type-based representation of 
03905       renamings and the (new) variable-based encoding.  At some point,
03906       it is devoutly to be hoped that the former goes away 
03907       (FIXME: hilfinger-2007-07-09).
03908    3. Subprogram renamings are not implemented, although the XRS
03909       suffix is recognized (FIXME: hilfinger-2007-07-09).  */
03910 
03911 /* If SYM encodes a renaming, 
03912 
03913        <renaming> renames <renamed entity>,
03914 
03915    sets *LEN to the length of the renamed entity's name,
03916    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
03917    the string describing the subcomponent selected from the renamed
03918    entity.  Returns ADA_NOT_RENAMING if SYM does not encode a renaming
03919    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
03920    are undefined).  Otherwise, returns a value indicating the category
03921    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
03922    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
03923    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
03924    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
03925    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
03926    may be NULL, in which case they are not assigned.
03927 
03928    [Currently, however, GCC does not generate subprogram renamings.]  */
03929 
03930 enum ada_renaming_category
03931 ada_parse_renaming (struct symbol *sym,
03932                     const char **renamed_entity, int *len, 
03933                     const char **renaming_expr)
03934 {
03935   enum ada_renaming_category kind;
03936   const char *info;
03937   const char *suffix;
03938 
03939   if (sym == NULL)
03940     return ADA_NOT_RENAMING;
03941   switch (SYMBOL_CLASS (sym)) 
03942     {
03943     default:
03944       return ADA_NOT_RENAMING;
03945     case LOC_TYPEDEF:
03946       return parse_old_style_renaming (SYMBOL_TYPE (sym), 
03947                                        renamed_entity, len, renaming_expr);
03948     case LOC_LOCAL:
03949     case LOC_STATIC:
03950     case LOC_COMPUTED:
03951     case LOC_OPTIMIZED_OUT:
03952       info = strstr (SYMBOL_LINKAGE_NAME (sym), "___XR");
03953       if (info == NULL)
03954         return ADA_NOT_RENAMING;
03955       switch (info[5])
03956         {
03957         case '_':
03958           kind = ADA_OBJECT_RENAMING;
03959           info += 6;
03960           break;
03961         case 'E':
03962           kind = ADA_EXCEPTION_RENAMING;
03963           info += 7;
03964           break;
03965         case 'P':
03966           kind = ADA_PACKAGE_RENAMING;
03967           info += 7;
03968           break;
03969         case 'S':
03970           kind = ADA_SUBPROGRAM_RENAMING;
03971           info += 7;
03972           break;
03973         default:
03974           return ADA_NOT_RENAMING;
03975         }
03976     }
03977 
03978   if (renamed_entity != NULL)
03979     *renamed_entity = info;
03980   suffix = strstr (info, "___XE");
03981   if (suffix == NULL || suffix == info)
03982     return ADA_NOT_RENAMING;
03983   if (len != NULL)
03984     *len = strlen (info) - strlen (suffix);
03985   suffix += 5;
03986   if (renaming_expr != NULL)
03987     *renaming_expr = suffix;
03988   return kind;
03989 }
03990 
03991 /* Assuming TYPE encodes a renaming according to the old encoding in
03992    exp_dbug.ads, returns details of that renaming in *RENAMED_ENTITY,
03993    *LEN, and *RENAMING_EXPR, as for ada_parse_renaming, above.  Returns
03994    ADA_NOT_RENAMING otherwise.  */
03995 static enum ada_renaming_category
03996 parse_old_style_renaming (struct type *type,
03997                           const char **renamed_entity, int *len, 
03998                           const char **renaming_expr)
03999 {
04000   enum ada_renaming_category kind;
04001   const char *name;
04002   const char *info;
04003   const char *suffix;
04004 
04005   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM 
04006       || TYPE_NFIELDS (type) != 1)
04007     return ADA_NOT_RENAMING;
04008 
04009   name = type_name_no_tag (type);
04010   if (name == NULL)
04011     return ADA_NOT_RENAMING;
04012   
04013   name = strstr (name, "___XR");
04014   if (name == NULL)
04015     return ADA_NOT_RENAMING;
04016   switch (name[5])
04017     {
04018     case '\0':
04019     case '_':
04020       kind = ADA_OBJECT_RENAMING;
04021       break;
04022     case 'E':
04023       kind = ADA_EXCEPTION_RENAMING;
04024       break;
04025     case 'P':
04026       kind = ADA_PACKAGE_RENAMING;
04027       break;
04028     case 'S':
04029       kind = ADA_SUBPROGRAM_RENAMING;
04030       break;
04031     default:
04032       return ADA_NOT_RENAMING;
04033     }
04034 
04035   info = TYPE_FIELD_NAME (type, 0);
04036   if (info == NULL)
04037     return ADA_NOT_RENAMING;
04038   if (renamed_entity != NULL)
04039     *renamed_entity = info;
04040   suffix = strstr (info, "___XE");
04041   if (renaming_expr != NULL)
04042     *renaming_expr = suffix + 5;
04043   if (suffix == NULL || suffix == info)
04044     return ADA_NOT_RENAMING;
04045   if (len != NULL)
04046     *len = suffix - info;
04047   return kind;
04048 }
04049 
04050 /* Compute the value of the given RENAMING_SYM, which is expected to
04051    be a symbol encoding a renaming expression.  BLOCK is the block
04052    used to evaluate the renaming.  */
04053 
04054 static struct value *
04055 ada_read_renaming_var_value (struct symbol *renaming_sym,
04056                              struct block *block)
04057 {
04058   const char *sym_name;
04059   struct expression *expr;
04060   struct value *value;
04061   struct cleanup *old_chain = NULL;
04062 
04063   sym_name = SYMBOL_LINKAGE_NAME (renaming_sym);
04064   expr = parse_exp_1 (&sym_name, 0, block, 0);
04065   old_chain = make_cleanup (free_current_contents, &expr);
04066   value = evaluate_expression (expr);
04067 
04068   do_cleanups (old_chain);
04069   return value;
04070 }
04071 
04072 
04073                                 /* Evaluation: Function Calls */
04074 
04075 /* Return an lvalue containing the value VAL.  This is the identity on
04076    lvalues, and otherwise has the side-effect of allocating memory
04077    in the inferior where a copy of the value contents is copied.  */
04078 
04079 static struct value *
04080 ensure_lval (struct value *val)
04081 {
04082   if (VALUE_LVAL (val) == not_lval
04083       || VALUE_LVAL (val) == lval_internalvar)
04084     {
04085       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
04086       const CORE_ADDR addr =
04087         value_as_long (value_allocate_space_in_inferior (len));
04088 
04089       set_value_address (val, addr);
04090       VALUE_LVAL (val) = lval_memory;
04091       write_memory (addr, value_contents (val), len);
04092     }
04093 
04094   return val;
04095 }
04096 
04097 /* Return the value ACTUAL, converted to be an appropriate value for a
04098    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
04099    allocating any necessary descriptors (fat pointers), or copies of
04100    values not residing in memory, updating it as needed.  */
04101 
04102 struct value *
04103 ada_convert_actual (struct value *actual, struct type *formal_type0)
04104 {
04105   struct type *actual_type = ada_check_typedef (value_type (actual));
04106   struct type *formal_type = ada_check_typedef (formal_type0);
04107   struct type *formal_target =
04108     TYPE_CODE (formal_type) == TYPE_CODE_PTR
04109     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
04110   struct type *actual_target =
04111     TYPE_CODE (actual_type) == TYPE_CODE_PTR
04112     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
04113 
04114   if (ada_is_array_descriptor_type (formal_target)
04115       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
04116     return make_array_descriptor (formal_type, actual);
04117   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
04118            || TYPE_CODE (formal_type) == TYPE_CODE_REF)
04119     {
04120       struct value *result;
04121 
04122       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
04123           && ada_is_array_descriptor_type (actual_target))
04124         result = desc_data (actual);
04125       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
04126         {
04127           if (VALUE_LVAL (actual) != lval_memory)
04128             {
04129               struct value *val;
04130 
04131               actual_type = ada_check_typedef (value_type (actual));
04132               val = allocate_value (actual_type);
04133               memcpy ((char *) value_contents_raw (val),
04134                       (char *) value_contents (actual),
04135                       TYPE_LENGTH (actual_type));
04136               actual = ensure_lval (val);
04137             }
04138           result = value_addr (actual);
04139         }
04140       else
04141         return actual;
04142       return value_cast_pointers (formal_type, result, 0);
04143     }
04144   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
04145     return ada_value_ind (actual);
04146 
04147   return actual;
04148 }
04149 
04150 /* Convert VALUE (which must be an address) to a CORE_ADDR that is a pointer of
04151    type TYPE.  This is usually an inefficient no-op except on some targets
04152    (such as AVR) where the representation of a pointer and an address
04153    differs.  */
04154 
04155 static CORE_ADDR
04156 value_pointer (struct value *value, struct type *type)
04157 {
04158   struct gdbarch *gdbarch = get_type_arch (type);
04159   unsigned len = TYPE_LENGTH (type);
04160   gdb_byte *buf = alloca (len);
04161   CORE_ADDR addr;
04162 
04163   addr = value_address (value);
04164   gdbarch_address_to_pointer (gdbarch, type, buf, addr);
04165   addr = extract_unsigned_integer (buf, len, gdbarch_byte_order (gdbarch));
04166   return addr;
04167 }
04168 
04169 
04170 /* Push a descriptor of type TYPE for array value ARR on the stack at
04171    *SP, updating *SP to reflect the new descriptor.  Return either
04172    an lvalue representing the new descriptor, or (if TYPE is a pointer-
04173    to-descriptor type rather than a descriptor type), a struct value *
04174    representing a pointer to this descriptor.  */
04175 
04176 static struct value *
04177 make_array_descriptor (struct type *type, struct value *arr)
04178 {
04179   struct type *bounds_type = desc_bounds_type (type);
04180   struct type *desc_type = desc_base_type (type);
04181   struct value *descriptor = allocate_value (desc_type);
04182   struct value *bounds = allocate_value (bounds_type);
04183   int i;
04184 
04185   for (i = ada_array_arity (ada_check_typedef (value_type (arr)));
04186        i > 0; i -= 1)
04187     {
04188       modify_field (value_type (bounds), value_contents_writeable (bounds),
04189                     ada_array_bound (arr, i, 0),
04190                     desc_bound_bitpos (bounds_type, i, 0),
04191                     desc_bound_bitsize (bounds_type, i, 0));
04192       modify_field (value_type (bounds), value_contents_writeable (bounds),
04193                     ada_array_bound (arr, i, 1),
04194                     desc_bound_bitpos (bounds_type, i, 1),
04195                     desc_bound_bitsize (bounds_type, i, 1));
04196     }
04197 
04198   bounds = ensure_lval (bounds);
04199 
04200   modify_field (value_type (descriptor),
04201                 value_contents_writeable (descriptor),
04202                 value_pointer (ensure_lval (arr),
04203                                TYPE_FIELD_TYPE (desc_type, 0)),
04204                 fat_pntr_data_bitpos (desc_type),
04205                 fat_pntr_data_bitsize (desc_type));
04206 
04207   modify_field (value_type (descriptor),
04208                 value_contents_writeable (descriptor),
04209                 value_pointer (bounds,
04210                                TYPE_FIELD_TYPE (desc_type, 1)),
04211                 fat_pntr_bounds_bitpos (desc_type),
04212                 fat_pntr_bounds_bitsize (desc_type));
04213 
04214   descriptor = ensure_lval (descriptor);
04215 
04216   if (TYPE_CODE (type) == TYPE_CODE_PTR)
04217     return value_addr (descriptor);
04218   else
04219     return descriptor;
04220 }
04221 
04222 /* Dummy definitions for an experimental caching module that is not
04223  * used in the public sources.  */
04224 
04225 static int
04226 lookup_cached_symbol (const char *name, domain_enum namespace,
04227                       struct symbol **sym, struct block **block)
04228 {
04229   return 0;
04230 }
04231 
04232 static void
04233 cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
04234               const struct block *block)
04235 {
04236 }
04237 
04238                                 /* Symbol Lookup */
04239 
04240 /* Return nonzero if wild matching should be used when searching for
04241    all symbols matching LOOKUP_NAME.
04242 
04243    LOOKUP_NAME is expected to be a symbol name after transformation
04244    for Ada lookups (see ada_name_for_lookup).  */
04245 
04246 static int
04247 should_use_wild_match (const char *lookup_name)
04248 {
04249   return (strstr (lookup_name, "__") == NULL);
04250 }
04251 
04252 /* Return the result of a standard (literal, C-like) lookup of NAME in
04253    given DOMAIN, visible from lexical block BLOCK.  */
04254 
04255 static struct symbol *
04256 standard_lookup (const char *name, const struct block *block,
04257                  domain_enum domain)
04258 {
04259   /* Initialize it just to avoid a GCC false warning.  */
04260   struct symbol *sym = NULL;
04261 
04262   if (lookup_cached_symbol (name, domain, &sym, NULL))
04263     return sym;
04264   sym = lookup_symbol_in_language (name, block, domain, language_c, 0);
04265   cache_symbol (name, domain, sym, block_found);
04266   return sym;
04267 }
04268 
04269 
04270 /* Non-zero iff there is at least one non-function/non-enumeral symbol
04271    in the symbol fields of SYMS[0..N-1].  We treat enumerals as functions, 
04272    since they contend in overloading in the same way.  */
04273 static int
04274 is_nonfunction (struct ada_symbol_info syms[], int n)
04275 {
04276   int i;
04277 
04278   for (i = 0; i < n; i += 1)
04279     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_FUNC
04280         && (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM
04281             || SYMBOL_CLASS (syms[i].sym) != LOC_CONST))
04282       return 1;
04283 
04284   return 0;
04285 }
04286 
04287 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
04288    struct types.  Otherwise, they may not.  */
04289 
04290 static int
04291 equiv_types (struct type *type0, struct type *type1)
04292 {
04293   if (type0 == type1)
04294     return 1;
04295   if (type0 == NULL || type1 == NULL
04296       || TYPE_CODE (type0) != TYPE_CODE (type1))
04297     return 0;
04298   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
04299        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
04300       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
04301       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
04302     return 1;
04303 
04304   return 0;
04305 }
04306 
04307 /* True iff SYM0 represents the same entity as SYM1, or one that is
04308    no more defined than that of SYM1.  */
04309 
04310 static int
04311 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
04312 {
04313   if (sym0 == sym1)
04314     return 1;
04315   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
04316       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
04317     return 0;
04318 
04319   switch (SYMBOL_CLASS (sym0))
04320     {
04321     case LOC_UNDEF:
04322       return 1;
04323     case LOC_TYPEDEF:
04324       {
04325         struct type *type0 = SYMBOL_TYPE (sym0);
04326         struct type *type1 = SYMBOL_TYPE (sym1);
04327         const char *name0 = SYMBOL_LINKAGE_NAME (sym0);
04328         const char *name1 = SYMBOL_LINKAGE_NAME (sym1);
04329         int len0 = strlen (name0);
04330 
04331         return
04332           TYPE_CODE (type0) == TYPE_CODE (type1)
04333           && (equiv_types (type0, type1)
04334               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
04335                   && strncmp (name1 + len0, "___XV", 5) == 0));
04336       }
04337     case LOC_CONST:
04338       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
04339         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
04340     default:
04341       return 0;
04342     }
04343 }
04344 
04345 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct ada_symbol_info
04346    records in OBSTACKP.  Do nothing if SYM is a duplicate.  */
04347 
04348 static void
04349 add_defn_to_vec (struct obstack *obstackp,
04350                  struct symbol *sym,
04351                  struct block *block)
04352 {
04353   int i;
04354   struct ada_symbol_info *prevDefns = defns_collected (obstackp, 0);
04355 
04356   /* Do not try to complete stub types, as the debugger is probably
04357      already scanning all symbols matching a certain name at the
04358      time when this function is called.  Trying to replace the stub
04359      type by its associated full type will cause us to restart a scan
04360      which may lead to an infinite recursion.  Instead, the client
04361      collecting the matching symbols will end up collecting several
04362      matches, with at least one of them complete.  It can then filter
04363      out the stub ones if needed.  */
04364 
04365   for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
04366     {
04367       if (lesseq_defined_than (sym, prevDefns[i].sym))
04368         return;
04369       else if (lesseq_defined_than (prevDefns[i].sym, sym))
04370         {
04371           prevDefns[i].sym = sym;
04372           prevDefns[i].block = block;
04373           return;
04374         }
04375     }
04376 
04377   {
04378     struct ada_symbol_info info;
04379 
04380     info.sym = sym;
04381     info.block = block;
04382     obstack_grow (obstackp, &info, sizeof (struct ada_symbol_info));
04383   }
04384 }
04385 
04386 /* Number of ada_symbol_info structures currently collected in 
04387    current vector in *OBSTACKP.  */
04388 
04389 static int
04390 num_defns_collected (struct obstack *obstackp)
04391 {
04392   return obstack_object_size (obstackp) / sizeof (struct ada_symbol_info);
04393 }
04394 
04395 /* Vector of ada_symbol_info structures currently collected in current 
04396    vector in *OBSTACKP.  If FINISH, close off the vector and return
04397    its final address.  */
04398 
04399 static struct ada_symbol_info *
04400 defns_collected (struct obstack *obstackp, int finish)
04401 {
04402   if (finish)
04403     return obstack_finish (obstackp);
04404   else
04405     return (struct ada_symbol_info *) obstack_base (obstackp);
04406 }
04407 
04408 /* Return a bound minimal symbol matching NAME according to Ada
04409    decoding rules.  Returns an invalid symbol if there is no such
04410    minimal symbol.  Names prefixed with "standard__" are handled
04411    specially: "standard__" is first stripped off, and only static and
04412    global symbols are searched.  */
04413 
04414 struct bound_minimal_symbol
04415 ada_lookup_simple_minsym (const char *name)
04416 {
04417   struct bound_minimal_symbol result;
04418   struct objfile *objfile;
04419   struct minimal_symbol *msymbol;
04420   const int wild_match_p = should_use_wild_match (name);
04421 
04422   memset (&result, 0, sizeof (result));
04423 
04424   /* Special case: If the user specifies a symbol name inside package
04425      Standard, do a non-wild matching of the symbol name without
04426      the "standard__" prefix.  This was primarily introduced in order
04427      to allow the user to specifically access the standard exceptions
04428      using, for instance, Standard.Constraint_Error when Constraint_Error
04429      is ambiguous (due to the user defining its own Constraint_Error
04430      entity inside its program).  */
04431   if (strncmp (name, "standard__", sizeof ("standard__") - 1) == 0)
04432     name += sizeof ("standard__") - 1;
04433 
04434   ALL_MSYMBOLS (objfile, msymbol)
04435   {
04436     if (match_name (SYMBOL_LINKAGE_NAME (msymbol), name, wild_match_p)
04437         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
04438       {
04439         result.minsym = msymbol;
04440         result.objfile = objfile;
04441         break;
04442       }
04443   }
04444 
04445   return result;
04446 }
04447 
04448 /* For all subprograms that statically enclose the subprogram of the
04449    selected frame, add symbols matching identifier NAME in DOMAIN
04450    and their blocks to the list of data in OBSTACKP, as for
04451    ada_add_block_symbols (q.v.).   If WILD_MATCH_P, treat as NAME
04452    with a wildcard prefix.  */
04453 
04454 static void
04455 add_symbols_from_enclosing_procs (struct obstack *obstackp,
04456                                   const char *name, domain_enum namespace,
04457                                   int wild_match_p)
04458 {
04459 }
04460 
04461 /* True if TYPE is definitely an artificial type supplied to a symbol
04462    for which no debugging information was given in the symbol file.  */
04463 
04464 static int
04465 is_nondebugging_type (struct type *type)
04466 {
04467   const char *name = ada_type_name (type);
04468 
04469   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
04470 }
04471 
04472 /* Return nonzero if TYPE1 and TYPE2 are two enumeration types
04473    that are deemed "identical" for practical purposes.
04474 
04475    This function assumes that TYPE1 and TYPE2 are both TYPE_CODE_ENUM
04476    types and that their number of enumerals is identical (in other
04477    words, TYPE_NFIELDS (type1) == TYPE_NFIELDS (type2)).  */
04478 
04479 static int
04480 ada_identical_enum_types_p (struct type *type1, struct type *type2)
04481 {
04482   int i;
04483 
04484   /* The heuristic we use here is fairly conservative.  We consider
04485      that 2 enumerate types are identical if they have the same
04486      number of enumerals and that all enumerals have the same
04487      underlying value and name.  */
04488 
04489   /* All enums in the type should have an identical underlying value.  */
04490   for (i = 0; i < TYPE_NFIELDS (type1); i++)
04491     if (TYPE_FIELD_ENUMVAL (type1, i) != TYPE_FIELD_ENUMVAL (type2, i))
04492       return 0;
04493 
04494   /* All enumerals should also have the same name (modulo any numerical
04495      suffix).  */
04496   for (i = 0; i < TYPE_NFIELDS (type1); i++)
04497     {
04498       const char *name_1 = TYPE_FIELD_NAME (type1, i);
04499       const char *name_2 = TYPE_FIELD_NAME (type2, i);
04500       int len_1 = strlen (name_1);
04501       int len_2 = strlen (name_2);
04502 
04503       ada_remove_trailing_digits (TYPE_FIELD_NAME (type1, i), &len_1);
04504       ada_remove_trailing_digits (TYPE_FIELD_NAME (type2, i), &len_2);
04505       if (len_1 != len_2
04506           || strncmp (TYPE_FIELD_NAME (type1, i),
04507                       TYPE_FIELD_NAME (type2, i),
04508                       len_1) != 0)
04509         return 0;
04510     }
04511 
04512   return 1;
04513 }
04514 
04515 /* Return nonzero if all the symbols in SYMS are all enumeral symbols
04516    that are deemed "identical" for practical purposes.  Sometimes,
04517    enumerals are not strictly identical, but their types are so similar
04518    that they can be considered identical.
04519 
04520    For instance, consider the following code:
04521 
04522       type Color is (Black, Red, Green, Blue, White);
04523       type RGB_Color is new Color range Red .. Blue;
04524 
04525    Type RGB_Color is a subrange of an implicit type which is a copy
04526    of type Color. If we call that implicit type RGB_ColorB ("B" is
04527    for "Base Type"), then type RGB_ColorB is a copy of type Color.
04528    As a result, when an expression references any of the enumeral
04529    by name (Eg. "print green"), the expression is technically
04530    ambiguous and the user should be asked to disambiguate. But
04531    doing so would only hinder the user, since it wouldn't matter
04532    what choice he makes, the outcome would always be the same.
04533    So, for practical purposes, we consider them as the same.  */
04534 
04535 static int
04536 symbols_are_identical_enums (struct ada_symbol_info *syms, int nsyms)
04537 {
04538   int i;
04539 
04540   /* Before performing a thorough comparison check of each type,
04541      we perform a series of inexpensive checks.  We expect that these
04542      checks will quickly fail in the vast majority of cases, and thus
04543      help prevent the unnecessary use of a more expensive comparison.
04544      Said comparison also expects us to make some of these checks
04545      (see ada_identical_enum_types_p).  */
04546 
04547   /* Quick check: All symbols should have an enum type.  */
04548   for (i = 0; i < nsyms; i++)
04549     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM)
04550       return 0;
04551 
04552   /* Quick check: They should all have the same value.  */
04553   for (i = 1; i < nsyms; i++)
04554     if (SYMBOL_VALUE (syms[i].sym) != SYMBOL_VALUE (syms[0].sym))
04555       return 0;
04556 
04557   /* Quick check: They should all have the same number of enumerals.  */
04558   for (i = 1; i < nsyms; i++)
04559     if (TYPE_NFIELDS (SYMBOL_TYPE (syms[i].sym))
04560         != TYPE_NFIELDS (SYMBOL_TYPE (syms[0].sym)))
04561       return 0;
04562 
04563   /* All the sanity checks passed, so we might have a set of
04564      identical enumeration types.  Perform a more complete
04565      comparison of the type of each symbol.  */
04566   for (i = 1; i < nsyms; i++)
04567     if (!ada_identical_enum_types_p (SYMBOL_TYPE (syms[i].sym),
04568                                      SYMBOL_TYPE (syms[0].sym)))
04569       return 0;
04570 
04571   return 1;
04572 }
04573 
04574 /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely
04575    duplicate other symbols in the list (The only case I know of where
04576    this happens is when object files containing stabs-in-ecoff are
04577    linked with files containing ordinary ecoff debugging symbols (or no
04578    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.
04579    Returns the number of items in the modified list.  */
04580 
04581 static int
04582 remove_extra_symbols (struct ada_symbol_info *syms, int nsyms)
04583 {
04584   int i, j;
04585 
04586   /* We should never be called with less than 2 symbols, as there
04587      cannot be any extra symbol in that case.  But it's easy to
04588      handle, since we have nothing to do in that case.  */
04589   if (nsyms < 2)
04590     return nsyms;
04591 
04592   i = 0;
04593   while (i < nsyms)
04594     {
04595       int remove_p = 0;
04596 
04597       /* If two symbols have the same name and one of them is a stub type,
04598          the get rid of the stub.  */
04599 
04600       if (TYPE_STUB (SYMBOL_TYPE (syms[i].sym))
04601           && SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL)
04602         {
04603           for (j = 0; j < nsyms; j++)
04604             {
04605               if (j != i
04606                   && !TYPE_STUB (SYMBOL_TYPE (syms[j].sym))
04607                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
04608                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
04609                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0)
04610                 remove_p = 1;
04611             }
04612         }
04613 
04614       /* Two symbols with the same name, same class and same address
04615          should be identical.  */
04616 
04617       else if (SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL
04618           && SYMBOL_CLASS (syms[i].sym) == LOC_STATIC
04619           && is_nondebugging_type (SYMBOL_TYPE (syms[i].sym)))
04620         {
04621           for (j = 0; j < nsyms; j += 1)
04622             {
04623               if (i != j
04624                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
04625                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
04626                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0
04627                   && SYMBOL_CLASS (syms[i].sym) == SYMBOL_CLASS (syms[j].sym)
04628                   && SYMBOL_VALUE_ADDRESS (syms[i].sym)
04629                   == SYMBOL_VALUE_ADDRESS (syms[j].sym))
04630                 remove_p = 1;
04631             }
04632         }
04633       
04634       if (remove_p)
04635         {
04636           for (j = i + 1; j < nsyms; j += 1)
04637             syms[j - 1] = syms[j];
04638           nsyms -= 1;
04639         }
04640 
04641       i += 1;
04642     }
04643 
04644   /* If all the remaining symbols are identical enumerals, then
04645      just keep the first one and discard the rest.
04646 
04647      Unlike what we did previously, we do not discard any entry
04648      unless they are ALL identical.  This is because the symbol
04649      comparison is not a strict comparison, but rather a practical
04650      comparison.  If all symbols are considered identical, then
04651      we can just go ahead and use the first one and discard the rest.
04652      But if we cannot reduce the list to a single element, we have
04653      to ask the user to disambiguate anyways.  And if we have to
04654      present a multiple-choice menu, it's less confusing if the list
04655      isn't missing some choices that were identical and yet distinct.  */
04656   if (symbols_are_identical_enums (syms, nsyms))
04657     nsyms = 1;
04658 
04659   return nsyms;
04660 }
04661 
04662 /* Given a type that corresponds to a renaming entity, use the type name
04663    to extract the scope (package name or function name, fully qualified,
04664    and following the GNAT encoding convention) where this renaming has been
04665    defined.  The string returned needs to be deallocated after use.  */
04666 
04667 static char *
04668 xget_renaming_scope (struct type *renaming_type)
04669 {
04670   /* The renaming types adhere to the following convention:
04671      <scope>__<rename>___<XR extension>.
04672      So, to extract the scope, we search for the "___XR" extension,
04673      and then backtrack until we find the first "__".  */
04674 
04675   const char *name = type_name_no_tag (renaming_type);
04676   char *suffix = strstr (name, "___XR");
04677   char *last;
04678   int scope_len;
04679   char *scope;
04680 
04681   /* Now, backtrack a bit until we find the first "__".  Start looking
04682      at suffix - 3, as the <rename> part is at least one character long.  */
04683 
04684   for (last = suffix - 3; last > name; last--)
04685     if (last[0] == '_' && last[1] == '_')
04686       break;
04687 
04688   /* Make a copy of scope and return it.  */
04689 
04690   scope_len = last - name;
04691   scope = (char *) xmalloc ((scope_len + 1) * sizeof (char));
04692 
04693   strncpy (scope, name, scope_len);
04694   scope[scope_len] = '\0';
04695 
04696   return scope;
04697 }
04698 
04699 /* Return nonzero if NAME corresponds to a package name.  */
04700 
04701 static int
04702 is_package_name (const char *name)
04703 {
04704   /* Here, We take advantage of the fact that no symbols are generated
04705      for packages, while symbols are generated for each function.
04706      So the condition for NAME represent a package becomes equivalent
04707      to NAME not existing in our list of symbols.  There is only one
04708      small complication with library-level functions (see below).  */
04709 
04710   char *fun_name;
04711 
04712   /* If it is a function that has not been defined at library level,
04713      then we should be able to look it up in the symbols.  */
04714   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
04715     return 0;
04716 
04717   /* Library-level function names start with "_ada_".  See if function
04718      "_ada_" followed by NAME can be found.  */
04719 
04720   /* Do a quick check that NAME does not contain "__", since library-level
04721      functions names cannot contain "__" in them.  */
04722   if (strstr (name, "__") != NULL)
04723     return 0;
04724 
04725   fun_name = xstrprintf ("_ada_%s", name);
04726 
04727   return (standard_lookup (fun_name, NULL, VAR_DOMAIN) == NULL);
04728 }
04729 
04730 /* Return nonzero if SYM corresponds to a renaming entity that is
04731    not visible from FUNCTION_NAME.  */
04732 
04733 static int
04734 old_renaming_is_invisible (const struct symbol *sym, const char *function_name)
04735 {
04736   char *scope;
04737   struct cleanup *old_chain;
04738 
04739   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
04740     return 0;
04741 
04742   scope = xget_renaming_scope (SYMBOL_TYPE (sym));
04743   old_chain = make_cleanup (xfree, scope);
04744 
04745   /* If the rename has been defined in a package, then it is visible.  */
04746   if (is_package_name (scope))
04747     {
04748       do_cleanups (old_chain);
04749       return 0;
04750     }
04751 
04752   /* Check that the rename is in the current function scope by checking
04753      that its name starts with SCOPE.  */
04754 
04755   /* If the function name starts with "_ada_", it means that it is
04756      a library-level function.  Strip this prefix before doing the
04757      comparison, as the encoding for the renaming does not contain
04758      this prefix.  */
04759   if (strncmp (function_name, "_ada_", 5) == 0)
04760     function_name += 5;
04761 
04762   {
04763     int is_invisible = strncmp (function_name, scope, strlen (scope)) != 0;
04764 
04765     do_cleanups (old_chain);
04766     return is_invisible;
04767   }
04768 }
04769 
04770 /* Remove entries from SYMS that corresponds to a renaming entity that
04771    is not visible from the function associated with CURRENT_BLOCK or
04772    that is superfluous due to the presence of more specific renaming
04773    information.  Places surviving symbols in the initial entries of
04774    SYMS and returns the number of surviving symbols.
04775    
04776    Rationale:
04777    First, in cases where an object renaming is implemented as a
04778    reference variable, GNAT may produce both the actual reference
04779    variable and the renaming encoding.  In this case, we discard the
04780    latter.
04781 
04782    Second, GNAT emits a type following a specified encoding for each renaming
04783    entity.  Unfortunately, STABS currently does not support the definition
04784    of types that are local to a given lexical block, so all renamings types
04785    are emitted at library level.  As a consequence, if an application
04786    contains two renaming entities using the same name, and a user tries to
04787    print the value of one of these entities, the result of the ada symbol
04788    lookup will also contain the wrong renaming type.
04789 
04790    This function partially covers for this limitation by attempting to
04791    remove from the SYMS list renaming symbols that should be visible
04792    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
04793    method with the current information available.  The implementation
04794    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
04795    
04796       - When the user tries to print a rename in a function while there
04797         is another rename entity defined in a package:  Normally, the
04798         rename in the function has precedence over the rename in the
04799         package, so the latter should be removed from the list.  This is
04800         currently not the case.
04801         
04802       - This function will incorrectly remove valid renames if
04803         the CURRENT_BLOCK corresponds to a function which symbol name
04804         has been changed by an "Export" pragma.  As a consequence,
04805         the user will be unable to print such rename entities.  */
04806 
04807 static int
04808 remove_irrelevant_renamings (struct ada_symbol_info *syms,
04809                              int nsyms, const struct block *current_block)
04810 {
04811   struct symbol *current_function;
04812   const char *current_function_name;
04813   int i;
04814   int is_new_style_renaming;
04815 
04816   /* If there is both a renaming foo___XR... encoded as a variable and
04817      a simple variable foo in the same block, discard the latter.
04818      First, zero out such symbols, then compress.  */
04819   is_new_style_renaming = 0;
04820   for (i = 0; i < nsyms; i += 1)
04821     {
04822       struct symbol *sym = syms[i].sym;
04823       const struct block *block = syms[i].block;
04824       const char *name;
04825       const char *suffix;
04826 
04827       if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
04828         continue;
04829       name = SYMBOL_LINKAGE_NAME (sym);
04830       suffix = strstr (name, "___XR");
04831 
04832       if (suffix != NULL)
04833         {
04834           int name_len = suffix - name;
04835           int j;
04836 
04837           is_new_style_renaming = 1;
04838           for (j = 0; j < nsyms; j += 1)
04839             if (i != j && syms[j].sym != NULL
04840                 && strncmp (name, SYMBOL_LINKAGE_NAME (syms[j].sym),
04841                             name_len) == 0
04842                 && block == syms[j].block)
04843               syms[j].sym = NULL;
04844         }
04845     }
04846   if (is_new_style_renaming)
04847     {
04848       int j, k;
04849 
04850       for (j = k = 0; j < nsyms; j += 1)
04851         if (syms[j].sym != NULL)
04852             {
04853               syms[k] = syms[j];
04854               k += 1;
04855             }
04856       return k;
04857     }
04858 
04859   /* Extract the function name associated to CURRENT_BLOCK.
04860      Abort if unable to do so.  */
04861 
04862   if (current_block == NULL)
04863     return nsyms;
04864 
04865   current_function = block_linkage_function (current_block);
04866   if (current_function == NULL)
04867     return nsyms;
04868 
04869   current_function_name = SYMBOL_LINKAGE_NAME (current_function);
04870   if (current_function_name == NULL)
04871     return nsyms;
04872 
04873   /* Check each of the symbols, and remove it from the list if it is
04874      a type corresponding to a renaming that is out of the scope of
04875      the current block.  */
04876 
04877   i = 0;
04878   while (i < nsyms)
04879     {
04880       if (ada_parse_renaming (syms[i].sym, NULL, NULL, NULL)
04881           == ADA_OBJECT_RENAMING
04882           && old_renaming_is_invisible (syms[i].sym, current_function_name))
04883         {
04884           int j;
04885 
04886           for (j = i + 1; j < nsyms; j += 1)
04887             syms[j - 1] = syms[j];
04888           nsyms -= 1;
04889         }
04890       else
04891         i += 1;
04892     }
04893 
04894   return nsyms;
04895 }
04896 
04897 /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
04898    whose name and domain match NAME and DOMAIN respectively.
04899    If no match was found, then extend the search to "enclosing"
04900    routines (in other words, if we're inside a nested function,
04901    search the symbols defined inside the enclosing functions).
04902    If WILD_MATCH_P is nonzero, perform the naming matching in
04903    "wild" mode (see function "wild_match" for more info).
04904 
04905    Note: This function assumes that OBSTACKP has 0 (zero) element in it.  */
04906 
04907 static void
04908 ada_add_local_symbols (struct obstack *obstackp, const char *name,
04909                        struct block *block, domain_enum domain,
04910                        int wild_match_p)
04911 {
04912   int block_depth = 0;
04913 
04914   while (block != NULL)
04915     {
04916       block_depth += 1;
04917       ada_add_block_symbols (obstackp, block, name, domain, NULL,
04918                              wild_match_p);
04919 
04920       /* If we found a non-function match, assume that's the one.  */
04921       if (is_nonfunction (defns_collected (obstackp, 0),
04922                           num_defns_collected (obstackp)))
04923         return;
04924 
04925       block = BLOCK_SUPERBLOCK (block);
04926     }
04927 
04928   /* If no luck so far, try to find NAME as a local symbol in some lexically
04929      enclosing subprogram.  */
04930   if (num_defns_collected (obstackp) == 0 && block_depth > 2)
04931     add_symbols_from_enclosing_procs (obstackp, name, domain, wild_match_p);
04932 }
04933 
04934 /* An object of this type is used as the user_data argument when
04935    calling the map_matching_symbols method.  */
04936 
04937 struct match_data
04938 {
04939   struct objfile *objfile;
04940   struct obstack *obstackp;
04941   struct symbol *arg_sym;
04942   int found_sym;
04943 };
04944 
04945 /* A callback for add_matching_symbols that adds SYM, found in BLOCK,
04946    to a list of symbols.  DATA0 is a pointer to a struct match_data *
04947    containing the obstack that collects the symbol list, the file that SYM
04948    must come from, a flag indicating whether a non-argument symbol has
04949    been found in the current block, and the last argument symbol
04950    passed in SYM within the current block (if any).  When SYM is null,
04951    marking the end of a block, the argument symbol is added if no
04952    other has been found.  */
04953 
04954 static int
04955 aux_add_nonlocal_symbols (struct block *block, struct symbol *sym, void *data0)
04956 {
04957   struct match_data *data = (struct match_data *) data0;
04958   
04959   if (sym == NULL)
04960     {
04961       if (!data->found_sym && data->arg_sym != NULL) 
04962         add_defn_to_vec (data->obstackp,
04963                          fixup_symbol_section (data->arg_sym, data->objfile),
04964                          block);
04965       data->found_sym = 0;
04966       data->arg_sym = NULL;
04967     }
04968   else 
04969     {
04970       if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
04971         return 0;
04972       else if (SYMBOL_IS_ARGUMENT (sym))
04973         data->arg_sym = sym;
04974       else
04975         {
04976           data->found_sym = 1;
04977           add_defn_to_vec (data->obstackp,
04978                            fixup_symbol_section (sym, data->objfile),
04979                            block);
04980         }
04981     }
04982   return 0;
04983 }
04984 
04985 /* Implements compare_names, but only applying the comparision using
04986    the given CASING.  */
04987 
04988 static int
04989 compare_names_with_case (const char *string1, const char *string2,
04990                          enum case_sensitivity casing)
04991 {
04992   while (*string1 != '\0' && *string2 != '\0')
04993     {
04994       char c1, c2;
04995 
04996       if (isspace (*string1) || isspace (*string2))
04997         return strcmp_iw_ordered (string1, string2);
04998 
04999       if (casing == case_sensitive_off)
05000         {
05001           c1 = tolower (*string1);
05002           c2 = tolower (*string2);
05003         }
05004       else
05005         {
05006           c1 = *string1;
05007           c2 = *string2;
05008         }
05009       if (c1 != c2)
05010         break;
05011 
05012       string1 += 1;
05013       string2 += 1;
05014     }
05015 
05016   switch (*string1)
05017     {
05018     case '(':
05019       return strcmp_iw_ordered (string1, string2);
05020     case '_':
05021       if (*string2 == '\0')
05022         {
05023           if (is_name_suffix (string1))
05024             return 0;
05025           else
05026             return 1;
05027         }
05028       /* FALLTHROUGH */
05029     default:
05030       if (*string2 == '(')
05031         return strcmp_iw_ordered (string1, string2);
05032       else
05033         {
05034           if (casing == case_sensitive_off)
05035             return tolower (*string1) - tolower (*string2);
05036           else
05037             return *string1 - *string2;
05038         }
05039     }
05040 }
05041 
05042 /* Compare STRING1 to STRING2, with results as for strcmp.
05043    Compatible with strcmp_iw_ordered in that...
05044 
05045        strcmp_iw_ordered (STRING1, STRING2) <= 0
05046 
05047    ... implies...
05048 
05049        compare_names (STRING1, STRING2) <= 0
05050 
05051    (they may differ as to what symbols compare equal).  */
05052 
05053 static int
05054 compare_names (const char *string1, const char *string2)
05055 {
05056   int result;
05057 
05058   /* Similar to what strcmp_iw_ordered does, we need to perform
05059      a case-insensitive comparison first, and only resort to
05060      a second, case-sensitive, comparison if the first one was
05061      not sufficient to differentiate the two strings.  */
05062 
05063   result = compare_names_with_case (string1, string2, case_sensitive_off);
05064   if (result == 0)
05065     result = compare_names_with_case (string1, string2, case_sensitive_on);
05066 
05067   return result;
05068 }
05069 
05070 /* Add to OBSTACKP all non-local symbols whose name and domain match
05071    NAME and DOMAIN respectively.  The search is performed on GLOBAL_BLOCK
05072    symbols if GLOBAL is non-zero, or on STATIC_BLOCK symbols otherwise.  */
05073 
05074 static void
05075 add_nonlocal_symbols (struct obstack *obstackp, const char *name,
05076                       domain_enum domain, int global,
05077                       int is_wild_match)
05078 {
05079   struct objfile *objfile;
05080   struct match_data data;
05081 
05082   memset (&data, 0, sizeof data);
05083   data.obstackp = obstackp;
05084 
05085   ALL_OBJFILES (objfile)
05086     {
05087       data.objfile = objfile;
05088 
05089       if (is_wild_match)
05090         objfile->sf->qf->map_matching_symbols (objfile, name, domain, global,
05091                                                aux_add_nonlocal_symbols, &data,
05092                                                wild_match, NULL);
05093       else
05094         objfile->sf->qf->map_matching_symbols (objfile, name, domain, global,
05095                                                aux_add_nonlocal_symbols, &data,
05096                                                full_match, compare_names);
05097     }
05098 
05099   if (num_defns_collected (obstackp) == 0 && global && !is_wild_match)
05100     {
05101       ALL_OBJFILES (objfile)
05102         {
05103           char *name1 = alloca (strlen (name) + sizeof ("_ada_"));
05104           strcpy (name1, "_ada_");
05105           strcpy (name1 + sizeof ("_ada_") - 1, name);
05106           data.objfile = objfile;
05107           objfile->sf->qf->map_matching_symbols (objfile, name1, domain,
05108                                                  global,
05109                                                  aux_add_nonlocal_symbols,
05110                                                  &data,
05111                                                  full_match, compare_names);
05112         }
05113     }           
05114 }
05115 
05116 /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and, if full_search is
05117    non-zero, enclosing scope and in global scopes, returning the number of
05118    matches.
05119    Sets *RESULTS to point to a vector of (SYM,BLOCK) tuples,
05120    indicating the symbols found and the blocks and symbol tables (if
05121    any) in which they were found.  This vector is transient---good only to
05122    the next call of ada_lookup_symbol_list.
05123 
05124    When full_search is non-zero, any non-function/non-enumeral
05125    symbol match within the nest of blocks whose innermost member is BLOCK0,
05126    is the one match returned (no other matches in that or
05127    enclosing blocks is returned).  If there are any matches in or
05128    surrounding BLOCK0, then these alone are returned.
05129 
05130    Names prefixed with "standard__" are handled specially: "standard__"
05131    is first stripped off, and only static and global symbols are searched.  */
05132 
05133 static int
05134 ada_lookup_symbol_list_worker (const char *name0, const struct block *block0,
05135                                domain_enum namespace,
05136                                struct ada_symbol_info **results,
05137                                int full_search)
05138 {
05139   struct symbol *sym;
05140   struct block *block;
05141   const char *name;
05142   const int wild_match_p = should_use_wild_match (name0);
05143   int cacheIfUnique;
05144   int ndefns;
05145 
05146   obstack_free (&symbol_list_obstack, NULL);
05147   obstack_init (&symbol_list_obstack);
05148 
05149   cacheIfUnique = 0;
05150 
05151   /* Search specified block and its superiors.  */
05152 
05153   name = name0;
05154   block = (struct block *) block0;      /* FIXME: No cast ought to be
05155                                            needed, but adding const will
05156                                            have a cascade effect.  */
05157 
05158   /* Special case: If the user specifies a symbol name inside package
05159      Standard, do a non-wild matching of the symbol name without
05160      the "standard__" prefix.  This was primarily introduced in order
05161      to allow the user to specifically access the standard exceptions
05162      using, for instance, Standard.Constraint_Error when Constraint_Error
05163      is ambiguous (due to the user defining its own Constraint_Error
05164      entity inside its program).  */
05165   if (strncmp (name0, "standard__", sizeof ("standard__") - 1) == 0)
05166     {
05167       block = NULL;
05168       name = name0 + sizeof ("standard__") - 1;
05169     }
05170 
05171   /* Check the non-global symbols.  If we have ANY match, then we're done.  */
05172 
05173   if (block != NULL)
05174     {
05175       if (full_search)
05176         {
05177           ada_add_local_symbols (&symbol_list_obstack, name, block,
05178                                  namespace, wild_match_p);
05179         }
05180       else
05181         {
05182           /* In the !full_search case we're are being called by
05183              ada_iterate_over_symbols, and we don't want to search
05184              superblocks.  */
05185           ada_add_block_symbols (&symbol_list_obstack, block, name,
05186                                  namespace, NULL, wild_match_p);
05187         }
05188       if (num_defns_collected (&symbol_list_obstack) > 0 || !full_search)
05189         goto done;
05190     }
05191 
05192   /* No non-global symbols found.  Check our cache to see if we have
05193      already performed this search before.  If we have, then return
05194      the same result.  */
05195 
05196   cacheIfUnique = 1;
05197   if (lookup_cached_symbol (name0, namespace, &sym, &block))
05198     {
05199       if (sym != NULL)
05200         add_defn_to_vec (&symbol_list_obstack, sym, block);
05201       goto done;
05202     }
05203 
05204   /* Search symbols from all global blocks.  */
05205  
05206   add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 1,
05207                         wild_match_p);
05208 
05209   /* Now add symbols from all per-file blocks if we've gotten no hits
05210      (not strictly correct, but perhaps better than an error).  */
05211 
05212   if (num_defns_collected (&symbol_list_obstack) == 0)
05213     add_nonlocal_symbols (&symbol_list_obstack, name, namespace, 0,
05214                           wild_match_p);
05215 
05216 done:
05217   ndefns = num_defns_collected (&symbol_list_obstack);
05218   *results = defns_collected (&symbol_list_obstack, 1);
05219 
05220   ndefns = remove_extra_symbols (*results, ndefns);
05221 
05222   if (ndefns == 0 && full_search)
05223     cache_symbol (name0, namespace, NULL, NULL);
05224 
05225   if (ndefns == 1 && full_search && cacheIfUnique)
05226     cache_symbol (name0, namespace, (*results)[0].sym, (*results)[0].block);
05227 
05228   ndefns = remove_irrelevant_renamings (*results, ndefns, block0);
05229 
05230   return ndefns;
05231 }
05232 
05233 /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and enclosing scope and
05234    in global scopes, returning the number of matches, and setting *RESULTS
05235    to a vector of (SYM,BLOCK) tuples.
05236    See ada_lookup_symbol_list_worker for further details.  */
05237 
05238 int
05239 ada_lookup_symbol_list (const char *name0, const struct block *block0,
05240                         domain_enum domain, struct ada_symbol_info **results)
05241 {
05242   return ada_lookup_symbol_list_worker (name0, block0, domain, results, 1);
05243 }
05244 
05245 /* Implementation of the la_iterate_over_symbols method.  */
05246 
05247 static void
05248 ada_iterate_over_symbols (const struct block *block,
05249                           const char *name, domain_enum domain,
05250                           symbol_found_callback_ftype *callback,
05251                           void *data)
05252 {
05253   int ndefs, i;
05254   struct ada_symbol_info *results;
05255 
05256   ndefs = ada_lookup_symbol_list_worker (name, block, domain, &results, 0);
05257   for (i = 0; i < ndefs; ++i)
05258     {
05259       if (! (*callback) (results[i].sym, data))
05260         break;
05261     }
05262 }
05263 
05264 /* If NAME is the name of an entity, return a string that should
05265    be used to look that entity up in Ada units.  This string should
05266    be deallocated after use using xfree.
05267 
05268    NAME can have any form that the "break" or "print" commands might
05269    recognize.  In other words, it does not have to be the "natural"
05270    name, or the "encoded" name.  */
05271 
05272 char *
05273 ada_name_for_lookup (const char *name)
05274 {
05275   char *canon;
05276   int nlen = strlen (name);
05277 
05278   if (name[0] == '<' && name[nlen - 1] == '>')
05279     {
05280       canon = xmalloc (nlen - 1);
05281       memcpy (canon, name + 1, nlen - 2);
05282       canon[nlen - 2] = '\0';
05283     }
05284   else
05285     canon = xstrdup (ada_encode (ada_fold_name (name)));
05286   return canon;
05287 }
05288 
05289 /* The result is as for ada_lookup_symbol_list with FULL_SEARCH set
05290    to 1, but choosing the first symbol found if there are multiple
05291    choices.
05292 
05293    The result is stored in *INFO, which must be non-NULL.
05294    If no match is found, INFO->SYM is set to NULL.  */
05295 
05296 void
05297 ada_lookup_encoded_symbol (const char *name, const struct block *block,
05298                            domain_enum namespace,
05299                            struct ada_symbol_info *info)
05300 {
05301   struct ada_symbol_info *candidates;
05302   int n_candidates;
05303 
05304   gdb_assert (info != NULL);
05305   memset (info, 0, sizeof (struct ada_symbol_info));
05306 
05307   n_candidates = ada_lookup_symbol_list (name, block, namespace, &candidates);
05308   if (n_candidates == 0)
05309     return;
05310 
05311   *info = candidates[0];
05312   info->sym = fixup_symbol_section (info->sym, NULL);
05313 }
05314 
05315 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
05316    scope and in global scopes, or NULL if none.  NAME is folded and
05317    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
05318    choosing the first symbol if there are multiple choices.
05319    If IS_A_FIELD_OF_THIS is not NULL, it is set to zero.  */
05320 
05321 struct symbol *
05322 ada_lookup_symbol (const char *name, const struct block *block0,
05323                    domain_enum namespace, int *is_a_field_of_this)
05324 {
05325   struct ada_symbol_info info;
05326 
05327   if (is_a_field_of_this != NULL)
05328     *is_a_field_of_this = 0;
05329 
05330   ada_lookup_encoded_symbol (ada_encode (ada_fold_name (name)),
05331                              block0, namespace, &info);
05332   return info.sym;
05333 }
05334 
05335 static struct symbol *
05336 ada_lookup_symbol_nonlocal (const char *name,
05337                             const struct block *block,
05338                             const domain_enum domain)
05339 {
05340   return ada_lookup_symbol (name, block_static_block (block), domain, NULL);
05341 }
05342 
05343 
05344 /* True iff STR is a possible encoded suffix of a normal Ada name
05345    that is to be ignored for matching purposes.  Suffixes of parallel
05346    names (e.g., XVE) are not included here.  Currently, the possible suffixes
05347    are given by any of the regular expressions:
05348 
05349    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
05350    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
05351    TKB              [subprogram suffix for task bodies]
05352    _E[0-9]+[bs]$    [protected object entry suffixes]
05353    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
05354 
05355    Also, any leading "__[0-9]+" sequence is skipped before the suffix
05356    match is performed.  This sequence is used to differentiate homonyms,
05357    is an optional part of a valid name suffix.  */
05358 
05359 static int
05360 is_name_suffix (const char *str)
05361 {
05362   int k;
05363   const char *matching;
05364   const int len = strlen (str);
05365 
05366   /* Skip optional leading __[0-9]+.  */
05367 
05368   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
05369     {
05370       str += 3;
05371       while (isdigit (str[0]))
05372         str += 1;
05373     }
05374   
05375   /* [.$][0-9]+ */
05376 
05377   if (str[0] == '.' || str[0] == '$')
05378     {
05379       matching = str + 1;
05380       while (isdigit (matching[0]))
05381         matching += 1;
05382       if (matching[0] == '\0')
05383         return 1;
05384     }
05385 
05386   /* ___[0-9]+ */
05387 
05388   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
05389     {
05390       matching = str + 3;
05391       while (isdigit (matching[0]))
05392         matching += 1;
05393       if (matching[0] == '\0')
05394         return 1;
05395     }
05396 
05397   /* "TKB" suffixes are used for subprograms implementing task bodies.  */
05398 
05399   if (strcmp (str, "TKB") == 0)
05400     return 1;
05401 
05402 #if 0
05403   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
05404      with a N at the end.  Unfortunately, the compiler uses the same
05405      convention for other internal types it creates.  So treating
05406      all entity names that end with an "N" as a name suffix causes
05407      some regressions.  For instance, consider the case of an enumerated
05408      type.  To support the 'Image attribute, it creates an array whose
05409      name ends with N.
05410      Having a single character like this as a suffix carrying some
05411      information is a bit risky.  Perhaps we should change the encoding
05412      to be something like "_N" instead.  In the meantime, do not do
05413      the following check.  */
05414   /* Protected Object Subprograms */
05415   if (len == 1 && str [0] == 'N')
05416     return 1;
05417 #endif
05418 
05419   /* _E[0-9]+[bs]$ */
05420   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
05421     {
05422       matching = str + 3;
05423       while (isdigit (matching[0]))
05424         matching += 1;
05425       if ((matching[0] == 'b' || matching[0] == 's')
05426           && matching [1] == '\0')
05427         return 1;
05428     }
05429 
05430   /* ??? We should not modify STR directly, as we are doing below.  This
05431      is fine in this case, but may become problematic later if we find
05432      that this alternative did not work, and want to try matching
05433      another one from the begining of STR.  Since we modified it, we
05434      won't be able to find the begining of the string anymore!  */
05435   if (str[0] == 'X')
05436     {
05437       str += 1;
05438       while (str[0] != '_' && str[0] != '\0')
05439         {
05440           if (str[0] != 'n' && str[0] != 'b')
05441             return 0;
05442           str += 1;
05443         }
05444     }
05445 
05446   if (str[0] == '\000')
05447     return 1;
05448 
05449   if (str[0] == '_')
05450     {
05451       if (str[1] != '_' || str[2] == '\000')
05452         return 0;
05453       if (str[2] == '_')
05454         {
05455           if (strcmp (str + 3, "JM") == 0)
05456             return 1;
05457           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
05458              the LJM suffix in favor of the JM one.  But we will
05459              still accept LJM as a valid suffix for a reasonable
05460              amount of time, just to allow ourselves to debug programs
05461              compiled using an older version of GNAT.  */
05462           if (strcmp (str + 3, "LJM") == 0)
05463             return 1;
05464           if (str[3] != 'X')
05465             return 0;
05466           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
05467               || str[4] == 'U' || str[4] == 'P')
05468             return 1;
05469           if (str[4] == 'R' && str[5] != 'T')
05470             return 1;
05471           return 0;
05472         }
05473       if (!isdigit (str[2]))
05474         return 0;
05475       for (k = 3; str[k] != '\0'; k += 1)
05476         if (!isdigit (str[k]) && str[k] != '_')
05477           return 0;
05478       return 1;
05479     }
05480   if (str[0] == '$' && isdigit (str[1]))
05481     {
05482       for (k = 2; str[k] != '\0'; k += 1)
05483         if (!isdigit (str[k]) && str[k] != '_')
05484           return 0;
05485       return 1;
05486     }
05487   return 0;
05488 }
05489 
05490 /* Return non-zero if the string starting at NAME and ending before
05491    NAME_END contains no capital letters.  */
05492 
05493 static int
05494 is_valid_name_for_wild_match (const char *name0)
05495 {
05496   const char *decoded_name = ada_decode (name0);
05497   int i;
05498 
05499   /* If the decoded name starts with an angle bracket, it means that
05500      NAME0 does not follow the GNAT encoding format.  It should then
05501      not be allowed as a possible wild match.  */
05502   if (decoded_name[0] == '<')
05503     return 0;
05504 
05505   for (i=0; decoded_name[i] != '\0'; i++)
05506     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
05507       return 0;
05508 
05509   return 1;
05510 }
05511 
05512 /* Advance *NAMEP to next occurrence of TARGET0 in the string NAME0
05513    that could start a simple name.  Assumes that *NAMEP points into
05514    the string beginning at NAME0.  */
05515 
05516 static int
05517 advance_wild_match (const char **namep, const char *name0, int target0)
05518 {
05519   const char *name = *namep;
05520 
05521   while (1)
05522     {
05523       int t0, t1;
05524 
05525       t0 = *name;
05526       if (t0 == '_')
05527         {
05528           t1 = name[1];
05529           if ((t1 >= 'a' && t1 <= 'z') || (t1 >= '0' && t1 <= '9'))
05530             {
05531               name += 1;
05532               if (name == name0 + 5 && strncmp (name0, "_ada", 4) == 0)
05533                 break;
05534               else
05535                 name += 1;
05536             }
05537           else if (t1 == '_' && ((name[2] >= 'a' && name[2] <= 'z')
05538                                  || name[2] == target0))
05539             {
05540               name += 2;
05541               break;
05542             }
05543           else
05544             return 0;
05545         }
05546       else if ((t0 >= 'a' && t0 <= 'z') || (t0 >= '0' && t0 <= '9'))
05547         name += 1;
05548       else
05549         return 0;
05550     }
05551 
05552   *namep = name;
05553   return 1;
05554 }
05555 
05556 /* Return 0 iff NAME encodes a name of the form prefix.PATN.  Ignores any
05557    informational suffixes of NAME (i.e., for which is_name_suffix is
05558    true).  Assumes that PATN is a lower-cased Ada simple name.  */
05559 
05560 static int
05561 wild_match (const char *name, const char *patn)
05562 {
05563   const char *p;
05564   const char *name0 = name;
05565 
05566   while (1)
05567     {
05568       const char *match = name;
05569 
05570       if (*name == *patn)
05571         {
05572           for (name += 1, p = patn + 1; *p != '\0'; name += 1, p += 1)
05573             if (*p != *name)
05574               break;
05575           if (*p == '\0' && is_name_suffix (name))
05576             return match != name0 && !is_valid_name_for_wild_match (name0);
05577 
05578           if (name[-1] == '_')
05579             name -= 1;
05580         }
05581       if (!advance_wild_match (&name, name0, *patn))
05582         return 1;
05583     }
05584 }
05585 
05586 /* Returns 0 iff symbol name SYM_NAME matches SEARCH_NAME, apart from
05587    informational suffix.  */
05588 
05589 static int
05590 full_match (const char *sym_name, const char *search_name)
05591 {
05592   return !match_name (sym_name, search_name, 0);
05593 }
05594 
05595 
05596 /* Add symbols from BLOCK matching identifier NAME in DOMAIN to
05597    vector *defn_symbols, updating the list of symbols in OBSTACKP 
05598    (if necessary).  If WILD, treat as NAME with a wildcard prefix.
05599    OBJFILE is the section containing BLOCK.  */
05600 
05601 static void
05602 ada_add_block_symbols (struct obstack *obstackp,
05603                        struct block *block, const char *name,
05604                        domain_enum domain, struct objfile *objfile,
05605                        int wild)
05606 {
05607   struct block_iterator iter;
05608   int name_len = strlen (name);
05609   /* A matching argument symbol, if any.  */
05610   struct symbol *arg_sym;
05611   /* Set true when we find a matching non-argument symbol.  */
05612   int found_sym;
05613   struct symbol *sym;
05614 
05615   arg_sym = NULL;
05616   found_sym = 0;
05617   if (wild)
05618     {
05619       for (sym = block_iter_match_first (block, name, wild_match, &iter);
05620            sym != NULL; sym = block_iter_match_next (name, wild_match, &iter))
05621       {
05622         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
05623                                    SYMBOL_DOMAIN (sym), domain)
05624             && wild_match (SYMBOL_LINKAGE_NAME (sym), name) == 0)
05625           {
05626             if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
05627               continue;
05628             else if (SYMBOL_IS_ARGUMENT (sym))
05629               arg_sym = sym;
05630             else
05631               {
05632                 found_sym = 1;
05633                 add_defn_to_vec (obstackp,
05634                                  fixup_symbol_section (sym, objfile),
05635                                  block);
05636               }
05637           }
05638       }
05639     }
05640   else
05641     {
05642      for (sym = block_iter_match_first (block, name, full_match, &iter);
05643           sym != NULL; sym = block_iter_match_next (name, full_match, &iter))
05644       {
05645         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
05646                                    SYMBOL_DOMAIN (sym), domain))
05647           {
05648             if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
05649               {
05650                 if (SYMBOL_IS_ARGUMENT (sym))
05651                   arg_sym = sym;
05652                 else
05653                   {
05654                     found_sym = 1;
05655                     add_defn_to_vec (obstackp,
05656                                      fixup_symbol_section (sym, objfile),
05657                                      block);
05658                   }
05659               }
05660           }
05661       }
05662     }
05663 
05664   if (!found_sym && arg_sym != NULL)
05665     {
05666       add_defn_to_vec (obstackp,
05667                        fixup_symbol_section (arg_sym, objfile),
05668                        block);
05669     }
05670 
05671   if (!wild)
05672     {
05673       arg_sym = NULL;
05674       found_sym = 0;
05675 
05676       ALL_BLOCK_SYMBOLS (block, iter, sym)
05677       {
05678         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
05679                                    SYMBOL_DOMAIN (sym), domain))
05680           {
05681             int cmp;
05682 
05683             cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
05684             if (cmp == 0)
05685               {
05686                 cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (sym), 5);
05687                 if (cmp == 0)
05688                   cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
05689                                  name_len);
05690               }
05691 
05692             if (cmp == 0
05693                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
05694               {
05695                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
05696                   {
05697                     if (SYMBOL_IS_ARGUMENT (sym))
05698                       arg_sym = sym;
05699                     else
05700                       {
05701                         found_sym = 1;
05702                         add_defn_to_vec (obstackp,
05703                                          fixup_symbol_section (sym, objfile),
05704                                          block);
05705                       }
05706                   }
05707               }
05708           }
05709       }
05710 
05711       /* NOTE: This really shouldn't be needed for _ada_ symbols.
05712          They aren't parameters, right?  */
05713       if (!found_sym && arg_sym != NULL)
05714         {
05715           add_defn_to_vec (obstackp,
05716                            fixup_symbol_section (arg_sym, objfile),
05717                            block);
05718         }
05719     }
05720 }
05721 
05722 
05723                                 /* Symbol Completion */
05724 
05725 /* If SYM_NAME is a completion candidate for TEXT, return this symbol
05726    name in a form that's appropriate for the completion.  The result
05727    does not need to be deallocated, but is only good until the next call.
05728 
05729    TEXT_LEN is equal to the length of TEXT.
05730    Perform a wild match if WILD_MATCH_P is set.
05731    ENCODED_P should be set if TEXT represents the start of a symbol name
05732    in its encoded form.  */
05733 
05734 static const char *
05735 symbol_completion_match (const char *sym_name,
05736                          const char *text, int text_len,
05737                          int wild_match_p, int encoded_p)
05738 {
05739   const int verbatim_match = (text[0] == '<');
05740   int match = 0;
05741 
05742   if (verbatim_match)
05743     {
05744       /* Strip the leading angle bracket.  */
05745       text = text + 1;
05746       text_len--;
05747     }
05748 
05749   /* First, test against the fully qualified name of the symbol.  */
05750 
05751   if (strncmp (sym_name, text, text_len) == 0)
05752     match = 1;
05753 
05754   if (match && !encoded_p)
05755     {
05756       /* One needed check before declaring a positive match is to verify
05757          that iff we are doing a verbatim match, the decoded version
05758          of the symbol name starts with '<'.  Otherwise, this symbol name
05759          is not a suitable completion.  */
05760       const char *sym_name_copy = sym_name;
05761       int has_angle_bracket;
05762 
05763       sym_name = ada_decode (sym_name);
05764       has_angle_bracket = (sym_name[0] == '<');
05765       match = (has_angle_bracket == verbatim_match);
05766       sym_name = sym_name_copy;
05767     }
05768 
05769   if (match && !verbatim_match)
05770     {
05771       /* When doing non-verbatim match, another check that needs to
05772          be done is to verify that the potentially matching symbol name
05773          does not include capital letters, because the ada-mode would
05774          not be able to understand these symbol names without the
05775          angle bracket notation.  */
05776       const char *tmp;
05777 
05778       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
05779       if (*tmp != '\0')
05780         match = 0;
05781     }
05782 
05783   /* Second: Try wild matching...  */
05784 
05785   if (!match && wild_match_p)
05786     {
05787       /* Since we are doing wild matching, this means that TEXT
05788          may represent an unqualified symbol name.  We therefore must
05789          also compare TEXT against the unqualified name of the symbol.  */
05790       sym_name = ada_unqualified_name (ada_decode (sym_name));
05791 
05792       if (strncmp (sym_name, text, text_len) == 0)
05793         match = 1;
05794     }
05795 
05796   /* Finally: If we found a mach, prepare the result to return.  */
05797 
05798   if (!match)
05799     return NULL;
05800 
05801   if (verbatim_match)
05802     sym_name = add_angle_brackets (sym_name);
05803 
05804   if (!encoded_p)
05805     sym_name = ada_decode (sym_name);
05806 
05807   return sym_name;
05808 }
05809 
05810 /* A companion function to ada_make_symbol_completion_list().
05811    Check if SYM_NAME represents a symbol which name would be suitable
05812    to complete TEXT (TEXT_LEN is the length of TEXT), in which case
05813    it is appended at the end of the given string vector SV.
05814 
05815    ORIG_TEXT is the string original string from the user command
05816    that needs to be completed.  WORD is the entire command on which
05817    completion should be performed.  These two parameters are used to
05818    determine which part of the symbol name should be added to the
05819    completion vector.
05820    if WILD_MATCH_P is set, then wild matching is performed.
05821    ENCODED_P should be set if TEXT represents a symbol name in its
05822    encoded formed (in which case the completion should also be
05823    encoded).  */
05824 
05825 static void
05826 symbol_completion_add (VEC(char_ptr) **sv,
05827                        const char *sym_name,
05828                        const char *text, int text_len,
05829                        const char *orig_text, const char *word,
05830                        int wild_match_p, int encoded_p)
05831 {
05832   const char *match = symbol_completion_match (sym_name, text, text_len,
05833                                                wild_match_p, encoded_p);
05834   char *completion;
05835 
05836   if (match == NULL)
05837     return;
05838 
05839   /* We found a match, so add the appropriate completion to the given
05840      string vector.  */
05841 
05842   if (word == orig_text)
05843     {
05844       completion = xmalloc (strlen (match) + 5);
05845       strcpy (completion, match);
05846     }
05847   else if (word > orig_text)
05848     {
05849       /* Return some portion of sym_name.  */
05850       completion = xmalloc (strlen (match) + 5);
05851       strcpy (completion, match + (word - orig_text));
05852     }
05853   else
05854     {
05855       /* Return some of ORIG_TEXT plus sym_name.  */
05856       completion = xmalloc (strlen (match) + (orig_text - word) + 5);
05857       strncpy (completion, word, orig_text - word);
05858       completion[orig_text - word] = '\0';
05859       strcat (completion, match);
05860     }
05861 
05862   VEC_safe_push (char_ptr, *sv, completion);
05863 }
05864 
05865 /* An object of this type is passed as the user_data argument to the
05866    expand_partial_symbol_names method.  */
05867 struct add_partial_datum
05868 {
05869   VEC(char_ptr) **completions;
05870   const char *text;
05871   int text_len;
05872   const char *text0;
05873   const char *word;
05874   int wild_match;
05875   int encoded;
05876 };
05877 
05878 /* A callback for expand_partial_symbol_names.  */
05879 static int
05880 ada_expand_partial_symbol_name (const char *name, void *user_data)
05881 {
05882   struct add_partial_datum *data = user_data;
05883   
05884   return symbol_completion_match (name, data->text, data->text_len,
05885                                   data->wild_match, data->encoded) != NULL;
05886 }
05887 
05888 /* Return a list of possible symbol names completing TEXT0.  WORD is
05889    the entire command on which completion is made.  */
05890 
05891 static VEC (char_ptr) *
05892 ada_make_symbol_completion_list (const char *text0, const char *word,
05893                                  enum type_code code)
05894 {
05895   char *text;
05896   int text_len;
05897   int wild_match_p;
05898   int encoded_p;
05899   VEC(char_ptr) *completions = VEC_alloc (char_ptr, 128);
05900   struct symbol *sym;
05901   struct symtab *s;
05902   struct minimal_symbol *msymbol;
05903   struct objfile *objfile;
05904   struct block *b, *surrounding_static_block = 0;
05905   int i;
05906   struct block_iterator iter;
05907   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
05908 
05909   gdb_assert (code == TYPE_CODE_UNDEF);
05910 
05911   if (text0[0] == '<')
05912     {
05913       text = xstrdup (text0);
05914       make_cleanup (xfree, text);
05915       text_len = strlen (text);
05916       wild_match_p = 0;
05917       encoded_p = 1;
05918     }
05919   else
05920     {
05921       text = xstrdup (ada_encode (text0));
05922       make_cleanup (xfree, text);
05923       text_len = strlen (text);
05924       for (i = 0; i < text_len; i++)
05925         text[i] = tolower (text[i]);
05926 
05927       encoded_p = (strstr (text0, "__") != NULL);
05928       /* If the name contains a ".", then the user is entering a fully
05929          qualified entity name, and the match must not be done in wild
05930          mode.  Similarly, if the user wants to complete what looks like
05931          an encoded name, the match must not be done in wild mode.  */
05932       wild_match_p = (strchr (text0, '.') == NULL && !encoded_p);
05933     }
05934 
05935   /* First, look at the partial symtab symbols.  */
05936   {
05937     struct add_partial_datum data;
05938 
05939     data.completions = &completions;
05940     data.text = text;
05941     data.text_len = text_len;
05942     data.text0 = text0;
05943     data.word = word;
05944     data.wild_match = wild_match_p;
05945     data.encoded = encoded_p;
05946     expand_partial_symbol_names (ada_expand_partial_symbol_name, &data);
05947   }
05948 
05949   /* At this point scan through the misc symbol vectors and add each
05950      symbol you find to the list.  Eventually we want to ignore
05951      anything that isn't a text symbol (everything else will be
05952      handled by the psymtab code above).  */
05953 
05954   ALL_MSYMBOLS (objfile, msymbol)
05955   {
05956     QUIT;
05957     symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (msymbol),
05958                            text, text_len, text0, word, wild_match_p,
05959                            encoded_p);
05960   }
05961 
05962   /* Search upwards from currently selected frame (so that we can
05963      complete on local vars.  */
05964 
05965   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
05966     {
05967       if (!BLOCK_SUPERBLOCK (b))
05968         surrounding_static_block = b;   /* For elmin of dups */
05969 
05970       ALL_BLOCK_SYMBOLS (b, iter, sym)
05971       {
05972         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
05973                                text, text_len, text0, word,
05974                                wild_match_p, encoded_p);
05975       }
05976     }
05977 
05978   /* Go through the symtabs and check the externs and statics for
05979      symbols which match.  */
05980 
05981   ALL_SYMTABS (objfile, s)
05982   {
05983     QUIT;
05984     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
05985     ALL_BLOCK_SYMBOLS (b, iter, sym)
05986     {
05987       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
05988                              text, text_len, text0, word,
05989                              wild_match_p, encoded_p);
05990     }
05991   }
05992 
05993   ALL_SYMTABS (objfile, s)
05994   {
05995     QUIT;
05996     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
05997     /* Don't do this block twice.  */
05998     if (b == surrounding_static_block)
05999       continue;
06000     ALL_BLOCK_SYMBOLS (b, iter, sym)
06001     {
06002       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
06003                              text, text_len, text0, word,
06004                              wild_match_p, encoded_p);
06005     }
06006   }
06007 
06008   do_cleanups (old_chain);
06009   return completions;
06010 }
06011 
06012                                 /* Field Access */
06013 
06014 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
06015    for tagged types.  */
06016 
06017 static int
06018 ada_is_dispatch_table_ptr_type (struct type *type)
06019 {
06020   const char *name;
06021 
06022   if (TYPE_CODE (type) != TYPE_CODE_PTR)
06023     return 0;
06024 
06025   name = TYPE_NAME (TYPE_TARGET_TYPE (type));
06026   if (name == NULL)
06027     return 0;
06028 
06029   return (strcmp (name, "ada__tags__dispatch_table") == 0);
06030 }
06031 
06032 /* Return non-zero if TYPE is an interface tag.  */
06033 
06034 static int
06035 ada_is_interface_tag (struct type *type)
06036 {
06037   const char *name = TYPE_NAME (type);
06038 
06039   if (name == NULL)
06040     return 0;
06041 
06042   return (strcmp (name, "ada__tags__interface_tag") == 0);
06043 }
06044 
06045 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
06046    to be invisible to users.  */
06047 
06048 int
06049 ada_is_ignored_field (struct type *type, int field_num)
06050 {
06051   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
06052     return 1;
06053 
06054   /* Check the name of that field.  */
06055   {
06056     const char *name = TYPE_FIELD_NAME (type, field_num);
06057 
06058     /* Anonymous field names should not be printed.
06059        brobecker/2007-02-20: I don't think this can actually happen
06060        but we don't want to print the value of annonymous fields anyway.  */
06061     if (name == NULL)
06062       return 1;
06063 
06064     /* Normally, fields whose name start with an underscore ("_")
06065        are fields that have been internally generated by the compiler,
06066        and thus should not be printed.  The "_parent" field is special,
06067        however: This is a field internally generated by the compiler
06068        for tagged types, and it contains the components inherited from
06069        the parent type.  This field should not be printed as is, but
06070        should not be ignored either.  */
06071     if (name[0] == '_' && strncmp (name, "_parent", 7) != 0)
06072       return 1;
06073   }
06074 
06075   /* If this is the dispatch table of a tagged type or an interface tag,
06076      then ignore.  */
06077   if (ada_is_tagged_type (type, 1)
06078       && (ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num))
06079           || ada_is_interface_tag (TYPE_FIELD_TYPE (type, field_num))))
06080     return 1;
06081 
06082   /* Not a special field, so it should not be ignored.  */
06083   return 0;
06084 }
06085 
06086 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
06087    pointer or reference type whose ultimate target has a tag field.  */
06088 
06089 int
06090 ada_is_tagged_type (struct type *type, int refok)
06091 {
06092   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1, NULL) != NULL);
06093 }
06094 
06095 /* True iff TYPE represents the type of X'Tag */
06096 
06097 int
06098 ada_is_tag_type (struct type *type)
06099 {
06100   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
06101     return 0;
06102   else
06103     {
06104       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
06105 
06106       return (name != NULL
06107               && strcmp (name, "ada__tags__dispatch_table") == 0);
06108     }
06109 }
06110 
06111 /* The type of the tag on VAL.  */
06112 
06113 struct type *
06114 ada_tag_type (struct value *val)
06115 {
06116   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0, NULL);
06117 }
06118 
06119 /* Return 1 if TAG follows the old scheme for Ada tags (used for Ada 95,
06120    retired at Ada 05).  */
06121 
06122 static int
06123 is_ada95_tag (struct value *tag)
06124 {
06125   return ada_value_struct_elt (tag, "tsd", 1) != NULL;
06126 }
06127 
06128 /* The value of the tag on VAL.  */
06129 
06130 struct value *
06131 ada_value_tag (struct value *val)
06132 {
06133   return ada_value_struct_elt (val, "_tag", 0);
06134 }
06135 
06136 /* The value of the tag on the object of type TYPE whose contents are
06137    saved at VALADDR, if it is non-null, or is at memory address
06138    ADDRESS.  */
06139 
06140 static struct value *
06141 value_tag_from_contents_and_address (struct type *type,
06142                                      const gdb_byte *valaddr,
06143                                      CORE_ADDR address)
06144 {
06145   int tag_byte_offset;
06146   struct type *tag_type;
06147 
06148   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
06149                          NULL, NULL, NULL))
06150     {
06151       const gdb_byte *valaddr1 = ((valaddr == NULL)
06152                                   ? NULL
06153                                   : valaddr + tag_byte_offset);
06154       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
06155 
06156       return value_from_contents_and_address (tag_type, valaddr1, address1);
06157     }
06158   return NULL;
06159 }
06160 
06161 static struct type *
06162 type_from_tag (struct value *tag)
06163 {
06164   const char *type_name = ada_tag_name (tag);
06165 
06166   if (type_name != NULL)
06167     return ada_find_any_type (ada_encode (type_name));
06168   return NULL;
06169 }
06170 
06171 /* Given a value OBJ of a tagged type, return a value of this
06172    type at the base address of the object.  The base address, as
06173    defined in Ada.Tags, it is the address of the primary tag of
06174    the object, and therefore where the field values of its full
06175    view can be fetched.  */
06176 
06177 struct value *
06178 ada_tag_value_at_base_address (struct value *obj)
06179 {
06180   volatile struct gdb_exception e;
06181   struct value *val;
06182   LONGEST offset_to_top = 0;
06183   struct type *ptr_type, *obj_type;
06184   struct value *tag;
06185   CORE_ADDR base_address;
06186 
06187   obj_type = value_type (obj);
06188 
06189   /* It is the responsability of the caller to deref pointers.  */
06190 
06191   if (TYPE_CODE (obj_type) == TYPE_CODE_PTR
06192       || TYPE_CODE (obj_type) == TYPE_CODE_REF)
06193     return obj;
06194 
06195   tag = ada_value_tag (obj);
06196   if (!tag)
06197     return obj;
06198 
06199   /* Base addresses only appeared with Ada 05 and multiple inheritance.  */
06200 
06201   if (is_ada95_tag (tag))
06202     return obj;
06203 
06204   ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
06205   ptr_type = lookup_pointer_type (ptr_type);
06206   val = value_cast (ptr_type, tag);
06207   if (!val)
06208     return obj;
06209 
06210   /* It is perfectly possible that an exception be raised while
06211      trying to determine the base address, just like for the tag;
06212      see ada_tag_name for more details.  We do not print the error
06213      message for the same reason.  */
06214 
06215   TRY_CATCH (e, RETURN_MASK_ERROR)
06216     {
06217       offset_to_top = value_as_long (value_ind (value_ptradd (val, -2)));
06218     }
06219 
06220   if (e.reason < 0)
06221     return obj;
06222 
06223   /* If offset is null, nothing to do.  */
06224 
06225   if (offset_to_top == 0)
06226     return obj;
06227 
06228   /* -1 is a special case in Ada.Tags; however, what should be done
06229      is not quite clear from the documentation.  So do nothing for
06230      now.  */
06231 
06232   if (offset_to_top == -1)
06233     return obj;
06234 
06235   base_address = value_address (obj) - offset_to_top;
06236   tag = value_tag_from_contents_and_address (obj_type, NULL, base_address);
06237 
06238   /* Make sure that we have a proper tag at the new address.
06239      Otherwise, offset_to_top is bogus (which can happen when
06240      the object is not initialized yet).  */
06241 
06242   if (!tag)
06243     return obj;
06244 
06245   obj_type = type_from_tag (tag);
06246 
06247   if (!obj_type)
06248     return obj;
06249 
06250   return value_from_contents_and_address (obj_type, NULL, base_address);
06251 }
06252 
06253 /* Return the "ada__tags__type_specific_data" type.  */
06254 
06255 static struct type *
06256 ada_get_tsd_type (struct inferior *inf)
06257 {
06258   struct ada_inferior_data *data = get_ada_inferior_data (inf);
06259 
06260   if (data->tsd_type == 0)
06261     data->tsd_type = ada_find_any_type ("ada__tags__type_specific_data");
06262   return data->tsd_type;
06263 }
06264 
06265 /* Return the TSD (type-specific data) associated to the given TAG.
06266    TAG is assumed to be the tag of a tagged-type entity.
06267 
06268    May return NULL if we are unable to get the TSD.  */
06269 
06270 static struct value *
06271 ada_get_tsd_from_tag (struct value *tag)
06272 {
06273   struct value *val;
06274   struct type *type;
06275 
06276   /* First option: The TSD is simply stored as a field of our TAG.
06277      Only older versions of GNAT would use this format, but we have
06278      to test it first, because there are no visible markers for
06279      the current approach except the absence of that field.  */
06280 
06281   val = ada_value_struct_elt (tag, "tsd", 1);
06282   if (val)
06283     return val;
06284 
06285   /* Try the second representation for the dispatch table (in which
06286      there is no explicit 'tsd' field in the referent of the tag pointer,
06287      and instead the tsd pointer is stored just before the dispatch
06288      table.  */
06289 
06290   type = ada_get_tsd_type (current_inferior());
06291   if (type == NULL)
06292     return NULL;
06293   type = lookup_pointer_type (lookup_pointer_type (type));
06294   val = value_cast (type, tag);
06295   if (val == NULL)
06296     return NULL;
06297   return value_ind (value_ptradd (val, -1));
06298 }
06299 
06300 /* Given the TSD of a tag (type-specific data), return a string
06301    containing the name of the associated type.
06302 
06303    The returned value is good until the next call.  May return NULL
06304    if we are unable to determine the tag name.  */
06305 
06306 static char *
06307 ada_tag_name_from_tsd (struct value *tsd)
06308 {
06309   static char name[1024];
06310   char *p;
06311   struct value *val;
06312 
06313   val = ada_value_struct_elt (tsd, "expanded_name", 1);
06314   if (val == NULL)
06315     return NULL;
06316   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
06317   for (p = name; *p != '\0'; p += 1)
06318     if (isalpha (*p))
06319       *p = tolower (*p);
06320   return name;
06321 }
06322 
06323 /* The type name of the dynamic type denoted by the 'tag value TAG, as
06324    a C string.
06325 
06326    Return NULL if the TAG is not an Ada tag, or if we were unable to
06327    determine the name of that tag.  The result is good until the next
06328    call.  */
06329 
06330 const char *
06331 ada_tag_name (struct value *tag)
06332 {
06333   volatile struct gdb_exception e;
06334   char *name = NULL;
06335 
06336   if (!ada_is_tag_type (value_type (tag)))
06337     return NULL;
06338 
06339   /* It is perfectly possible that an exception be raised while trying
06340      to determine the TAG's name, even under normal circumstances:
06341      The associated variable may be uninitialized or corrupted, for
06342      instance. We do not let any exception propagate past this point.
06343      instead we return NULL.
06344 
06345      We also do not print the error message either (which often is very
06346      low-level (Eg: "Cannot read memory at 0x[...]"), but instead let
06347      the caller print a more meaningful message if necessary.  */
06348   TRY_CATCH (e, RETURN_MASK_ERROR)
06349     {
06350       struct value *tsd = ada_get_tsd_from_tag (tag);
06351 
06352       if (tsd != NULL)
06353         name = ada_tag_name_from_tsd (tsd);
06354     }
06355 
06356   return name;
06357 }
06358 
06359 /* The parent type of TYPE, or NULL if none.  */
06360 
06361 struct type *
06362 ada_parent_type (struct type *type)
06363 {
06364   int i;
06365 
06366   type = ada_check_typedef (type);
06367 
06368   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
06369     return NULL;
06370 
06371   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
06372     if (ada_is_parent_field (type, i))
06373       {
06374         struct type *parent_type = TYPE_FIELD_TYPE (type, i);
06375 
06376         /* If the _parent field is a pointer, then dereference it.  */
06377         if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
06378           parent_type = TYPE_TARGET_TYPE (parent_type);
06379         /* If there is a parallel XVS type, get the actual base type.  */
06380         parent_type = ada_get_base_type (parent_type);
06381 
06382         return ada_check_typedef (parent_type);
06383       }
06384 
06385   return NULL;
06386 }
06387 
06388 /* True iff field number FIELD_NUM of structure type TYPE contains the
06389    parent-type (inherited) fields of a derived type.  Assumes TYPE is
06390    a structure type with at least FIELD_NUM+1 fields.  */
06391 
06392 int
06393 ada_is_parent_field (struct type *type, int field_num)
06394 {
06395   const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
06396 
06397   return (name != NULL
06398           && (strncmp (name, "PARENT", 6) == 0
06399               || strncmp (name, "_parent", 7) == 0));
06400 }
06401 
06402 /* True iff field number FIELD_NUM of structure type TYPE is a
06403    transparent wrapper field (which should be silently traversed when doing
06404    field selection and flattened when printing).  Assumes TYPE is a
06405    structure type with at least FIELD_NUM+1 fields.  Such fields are always
06406    structures.  */
06407 
06408 int
06409 ada_is_wrapper_field (struct type *type, int field_num)
06410 {
06411   const char *name = TYPE_FIELD_NAME (type, field_num);
06412 
06413   return (name != NULL
06414           && (strncmp (name, "PARENT", 6) == 0
06415               || strcmp (name, "REP") == 0
06416               || strncmp (name, "_parent", 7) == 0
06417               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
06418 }
06419 
06420 /* True iff field number FIELD_NUM of structure or union type TYPE
06421    is a variant wrapper.  Assumes TYPE is a structure type with at least
06422    FIELD_NUM+1 fields.  */
06423 
06424 int
06425 ada_is_variant_part (struct type *type, int field_num)
06426 {
06427   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
06428 
06429   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
06430           || (is_dynamic_field (type, field_num)
06431               && (TYPE_CODE (TYPE_TARGET_TYPE (field_type)) 
06432                   == TYPE_CODE_UNION)));
06433 }
06434 
06435 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
06436    whose discriminants are contained in the record type OUTER_TYPE,
06437    returns the type of the controlling discriminant for the variant.
06438    May return NULL if the type could not be found.  */
06439 
06440 struct type *
06441 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
06442 {
06443   char *name = ada_variant_discrim_name (var_type);
06444 
06445   return ada_lookup_struct_elt_type (outer_type, name, 1, 1, NULL);
06446 }
06447 
06448 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
06449    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
06450    represents a 'when others' clause; otherwise 0.  */
06451 
06452 int
06453 ada_is_others_clause (struct type *type, int field_num)
06454 {
06455   const char *name = TYPE_FIELD_NAME (type, field_num);
06456 
06457   return (name != NULL && name[0] == 'O');
06458 }
06459 
06460 /* Assuming that TYPE0 is the type of the variant part of a record,
06461    returns the name of the discriminant controlling the variant.
06462    The value is valid until the next call to ada_variant_discrim_name.  */
06463 
06464 char *
06465 ada_variant_discrim_name (struct type *type0)
06466 {
06467   static char *result = NULL;
06468   static size_t result_len = 0;
06469   struct type *type;
06470   const char *name;
06471   const char *discrim_end;
06472   const char *discrim_start;
06473 
06474   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
06475     type = TYPE_TARGET_TYPE (type0);
06476   else
06477     type = type0;
06478 
06479   name = ada_type_name (type);
06480 
06481   if (name == NULL || name[0] == '\000')
06482     return "";
06483 
06484   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
06485        discrim_end -= 1)
06486     {
06487       if (strncmp (discrim_end, "___XVN", 6) == 0)
06488         break;
06489     }
06490   if (discrim_end == name)
06491     return "";
06492 
06493   for (discrim_start = discrim_end; discrim_start != name + 3;
06494        discrim_start -= 1)
06495     {
06496       if (discrim_start == name + 1)
06497         return "";
06498       if ((discrim_start > name + 3
06499            && strncmp (discrim_start - 3, "___", 3) == 0)
06500           || discrim_start[-1] == '.')
06501         break;
06502     }
06503 
06504   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
06505   strncpy (result, discrim_start, discrim_end - discrim_start);
06506   result[discrim_end - discrim_start] = '\0';
06507   return result;
06508 }
06509 
06510 /* Scan STR for a subtype-encoded number, beginning at position K.
06511    Put the position of the character just past the number scanned in
06512    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
06513    Return 1 if there was a valid number at the given position, and 0
06514    otherwise.  A "subtype-encoded" number consists of the absolute value
06515    in decimal, followed by the letter 'm' to indicate a negative number.
06516    Assumes 0m does not occur.  */
06517 
06518 int
06519 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
06520 {
06521   ULONGEST RU;
06522 
06523   if (!isdigit (str[k]))
06524     return 0;
06525 
06526   /* Do it the hard way so as not to make any assumption about
06527      the relationship of unsigned long (%lu scan format code) and
06528      LONGEST.  */
06529   RU = 0;
06530   while (isdigit (str[k]))
06531     {
06532       RU = RU * 10 + (str[k] - '0');
06533       k += 1;
06534     }
06535 
06536   if (str[k] == 'm')
06537     {
06538       if (R != NULL)
06539         *R = (-(LONGEST) (RU - 1)) - 1;
06540       k += 1;
06541     }
06542   else if (R != NULL)
06543     *R = (LONGEST) RU;
06544 
06545   /* NOTE on the above: Technically, C does not say what the results of
06546      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
06547      number representable as a LONGEST (although either would probably work
06548      in most implementations).  When RU>0, the locution in the then branch
06549      above is always equivalent to the negative of RU.  */
06550 
06551   if (new_k != NULL)
06552     *new_k = k;
06553   return 1;
06554 }
06555 
06556 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
06557    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
06558    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
06559 
06560 int
06561 ada_in_variant (LONGEST val, struct type *type, int field_num)
06562 {
06563   const char *name = TYPE_FIELD_NAME (type, field_num);
06564   int p;
06565 
06566   p = 0;
06567   while (1)
06568     {
06569       switch (name[p])
06570         {
06571         case '\0':
06572           return 0;
06573         case 'S':
06574           {
06575             LONGEST W;
06576 
06577             if (!ada_scan_number (name, p + 1, &W, &p))
06578               return 0;
06579             if (val == W)
06580               return 1;
06581             break;
06582           }
06583         case 'R':
06584           {
06585             LONGEST L, U;
06586 
06587             if (!ada_scan_number (name, p + 1, &L, &p)
06588                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
06589               return 0;
06590             if (val >= L && val <= U)
06591               return 1;
06592             break;
06593           }
06594         case 'O':
06595           return 1;
06596         default:
06597           return 0;
06598         }
06599     }
06600 }
06601 
06602 /* FIXME: Lots of redundancy below.  Try to consolidate.  */
06603 
06604 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
06605    ARG_TYPE, extract and return the value of one of its (non-static)
06606    fields.  FIELDNO says which field.   Differs from value_primitive_field
06607    only in that it can handle packed values of arbitrary type.  */
06608 
06609 static struct value *
06610 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
06611                            struct type *arg_type)
06612 {
06613   struct type *type;
06614 
06615   arg_type = ada_check_typedef (arg_type);
06616   type = TYPE_FIELD_TYPE (arg_type, fieldno);
06617 
06618   /* Handle packed fields.  */
06619 
06620   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
06621     {
06622       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
06623       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
06624 
06625       return ada_value_primitive_packed_val (arg1, value_contents (arg1),
06626                                              offset + bit_pos / 8,
06627                                              bit_pos % 8, bit_size, type);
06628     }
06629   else
06630     return value_primitive_field (arg1, offset, fieldno, arg_type);
06631 }
06632 
06633 /* Find field with name NAME in object of type TYPE.  If found, 
06634    set the following for each argument that is non-null:
06635     - *FIELD_TYPE_P to the field's type; 
06636     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within 
06637       an object of that type;
06638     - *BIT_OFFSET_P to the bit offset modulo byte size of the field; 
06639     - *BIT_SIZE_P to its size in bits if the field is packed, and 
06640       0 otherwise;
06641    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
06642    fields up to but not including the desired field, or by the total
06643    number of fields if not found.   A NULL value of NAME never
06644    matches; the function just counts visible fields in this case.
06645    
06646    Returns 1 if found, 0 otherwise.  */
06647 
06648 static int
06649 find_struct_field (const char *name, struct type *type, int offset,
06650                    struct type **field_type_p,
06651                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
06652                    int *index_p)
06653 {
06654   int i;
06655 
06656   type = ada_check_typedef (type);
06657 
06658   if (field_type_p != NULL)
06659     *field_type_p = NULL;
06660   if (byte_offset_p != NULL)
06661     *byte_offset_p = 0;
06662   if (bit_offset_p != NULL)
06663     *bit_offset_p = 0;
06664   if (bit_size_p != NULL)
06665     *bit_size_p = 0;
06666 
06667   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
06668     {
06669       int bit_pos = TYPE_FIELD_BITPOS (type, i);
06670       int fld_offset = offset + bit_pos / 8;
06671       const char *t_field_name = TYPE_FIELD_NAME (type, i);
06672 
06673       if (t_field_name == NULL)
06674         continue;
06675 
06676       else if (name != NULL && field_name_match (t_field_name, name))
06677         {
06678           int bit_size = TYPE_FIELD_BITSIZE (type, i);
06679 
06680           if (field_type_p != NULL)
06681             *field_type_p = TYPE_FIELD_TYPE (type, i);
06682           if (byte_offset_p != NULL)
06683             *byte_offset_p = fld_offset;
06684           if (bit_offset_p != NULL)
06685             *bit_offset_p = bit_pos % 8;
06686           if (bit_size_p != NULL)
06687             *bit_size_p = bit_size;
06688           return 1;
06689         }
06690       else if (ada_is_wrapper_field (type, i))
06691         {
06692           if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
06693                                  field_type_p, byte_offset_p, bit_offset_p,
06694                                  bit_size_p, index_p))
06695             return 1;
06696         }
06697       else if (ada_is_variant_part (type, i))
06698         {
06699           /* PNH: Wait.  Do we ever execute this section, or is ARG always of 
06700              fixed type?? */
06701           int j;
06702           struct type *field_type
06703             = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
06704 
06705           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
06706             {
06707               if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
06708                                      fld_offset
06709                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
06710                                      field_type_p, byte_offset_p,
06711                                      bit_offset_p, bit_size_p, index_p))
06712                 return 1;
06713             }
06714         }
06715       else if (index_p != NULL)
06716         *index_p += 1;
06717     }
06718   return 0;
06719 }
06720 
06721 /* Number of user-visible fields in record type TYPE.  */
06722 
06723 static int
06724 num_visible_fields (struct type *type)
06725 {
06726   int n;
06727 
06728   n = 0;
06729   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
06730   return n;
06731 }
06732 
06733 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
06734    and search in it assuming it has (class) type TYPE.
06735    If found, return value, else return NULL.
06736 
06737    Searches recursively through wrapper fields (e.g., '_parent').  */
06738 
06739 static struct value *
06740 ada_search_struct_field (char *name, struct value *arg, int offset,
06741                          struct type *type)
06742 {
06743   int i;
06744 
06745   type = ada_check_typedef (type);
06746   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
06747     {
06748       const char *t_field_name = TYPE_FIELD_NAME (type, i);
06749 
06750       if (t_field_name == NULL)
06751         continue;
06752 
06753       else if (field_name_match (t_field_name, name))
06754         return ada_value_primitive_field (arg, offset, i, type);
06755 
06756       else if (ada_is_wrapper_field (type, i))
06757         {
06758           struct value *v =     /* Do not let indent join lines here.  */
06759             ada_search_struct_field (name, arg,
06760                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
06761                                      TYPE_FIELD_TYPE (type, i));
06762 
06763           if (v != NULL)
06764             return v;
06765         }
06766 
06767       else if (ada_is_variant_part (type, i))
06768         {
06769           /* PNH: Do we ever get here?  See find_struct_field.  */
06770           int j;
06771           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
06772                                                                         i));
06773           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
06774 
06775           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
06776             {
06777               struct value *v = ada_search_struct_field /* Force line
06778                                                            break.  */
06779                 (name, arg,
06780                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
06781                  TYPE_FIELD_TYPE (field_type, j));
06782 
06783               if (v != NULL)
06784                 return v;
06785             }
06786         }
06787     }
06788   return NULL;
06789 }
06790 
06791 static struct value *ada_index_struct_field_1 (int *, struct value *,
06792                                                int, struct type *);
06793 
06794 
06795 /* Return field #INDEX in ARG, where the index is that returned by
06796  * find_struct_field through its INDEX_P argument.  Adjust the address
06797  * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
06798  * If found, return value, else return NULL.  */
06799 
06800 static struct value *
06801 ada_index_struct_field (int index, struct value *arg, int offset,
06802                         struct type *type)
06803 {
06804   return ada_index_struct_field_1 (&index, arg, offset, type);
06805 }
06806 
06807 
06808 /* Auxiliary function for ada_index_struct_field.  Like
06809  * ada_index_struct_field, but takes index from *INDEX_P and modifies
06810  * *INDEX_P.  */
06811 
06812 static struct value *
06813 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
06814                           struct type *type)
06815 {
06816   int i;
06817   type = ada_check_typedef (type);
06818 
06819   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
06820     {
06821       if (TYPE_FIELD_NAME (type, i) == NULL)
06822         continue;
06823       else if (ada_is_wrapper_field (type, i))
06824         {
06825           struct value *v =     /* Do not let indent join lines here.  */
06826             ada_index_struct_field_1 (index_p, arg,
06827                                       offset + TYPE_FIELD_BITPOS (type, i) / 8,
06828                                       TYPE_FIELD_TYPE (type, i));
06829 
06830           if (v != NULL)
06831             return v;
06832         }
06833 
06834       else if (ada_is_variant_part (type, i))
06835         {
06836           /* PNH: Do we ever get here?  See ada_search_struct_field,
06837              find_struct_field.  */
06838           error (_("Cannot assign this kind of variant record"));
06839         }
06840       else if (*index_p == 0)
06841         return ada_value_primitive_field (arg, offset, i, type);
06842       else
06843         *index_p -= 1;
06844     }
06845   return NULL;
06846 }
06847 
06848 /* Given ARG, a value of type (pointer or reference to a)*
06849    structure/union, extract the component named NAME from the ultimate
06850    target structure/union and return it as a value with its
06851    appropriate type.
06852 
06853    The routine searches for NAME among all members of the structure itself
06854    and (recursively) among all members of any wrapper members
06855    (e.g., '_parent').
06856 
06857    If NO_ERR, then simply return NULL in case of error, rather than 
06858    calling error.  */
06859 
06860 struct value *
06861 ada_value_struct_elt (struct value *arg, char *name, int no_err)
06862 {
06863   struct type *t, *t1;
06864   struct value *v;
06865 
06866   v = NULL;
06867   t1 = t = ada_check_typedef (value_type (arg));
06868   if (TYPE_CODE (t) == TYPE_CODE_REF)
06869     {
06870       t1 = TYPE_TARGET_TYPE (t);
06871       if (t1 == NULL)
06872         goto BadValue;
06873       t1 = ada_check_typedef (t1);
06874       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
06875         {
06876           arg = coerce_ref (arg);
06877           t = t1;
06878         }
06879     }
06880 
06881   while (TYPE_CODE (t) == TYPE_CODE_PTR)
06882     {
06883       t1 = TYPE_TARGET_TYPE (t);
06884       if (t1 == NULL)
06885         goto BadValue;
06886       t1 = ada_check_typedef (t1);
06887       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
06888         {
06889           arg = value_ind (arg);
06890           t = t1;
06891         }
06892       else
06893         break;
06894     }
06895 
06896   if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
06897     goto BadValue;
06898 
06899   if (t1 == t)
06900     v = ada_search_struct_field (name, arg, 0, t);
06901   else
06902     {
06903       int bit_offset, bit_size, byte_offset;
06904       struct type *field_type;
06905       CORE_ADDR address;
06906 
06907       if (TYPE_CODE (t) == TYPE_CODE_PTR)
06908         address = value_address (ada_value_ind (arg));
06909       else
06910         address = value_address (ada_coerce_ref (arg));
06911 
06912       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL, address, NULL, 1);
06913       if (find_struct_field (name, t1, 0,
06914                              &field_type, &byte_offset, &bit_offset,
06915                              &bit_size, NULL))
06916         {
06917           if (bit_size != 0)
06918             {
06919               if (TYPE_CODE (t) == TYPE_CODE_REF)
06920                 arg = ada_coerce_ref (arg);
06921               else
06922                 arg = ada_value_ind (arg);
06923               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
06924                                                   bit_offset, bit_size,
06925                                                   field_type);
06926             }
06927           else
06928             v = value_at_lazy (field_type, address + byte_offset);
06929         }
06930     }
06931 
06932   if (v != NULL || no_err)
06933     return v;
06934   else
06935     error (_("There is no member named %s."), name);
06936 
06937  BadValue:
06938   if (no_err)
06939     return NULL;
06940   else
06941     error (_("Attempt to extract a component of "
06942              "a value that is not a record."));
06943 }
06944 
06945 /* Given a type TYPE, look up the type of the component of type named NAME.
06946    If DISPP is non-null, add its byte displacement from the beginning of a
06947    structure (pointed to by a value) of type TYPE to *DISPP (does not
06948    work for packed fields).
06949 
06950    Matches any field whose name has NAME as a prefix, possibly
06951    followed by "___".
06952 
06953    TYPE can be either a struct or union.  If REFOK, TYPE may also 
06954    be a (pointer or reference)+ to a struct or union, and the
06955    ultimate target type will be searched.
06956 
06957    Looks recursively into variant clauses and parent types.
06958 
06959    If NOERR is nonzero, return NULL if NAME is not suitably defined or
06960    TYPE is not a type of the right kind.  */
06961 
06962 static struct type *
06963 ada_lookup_struct_elt_type (struct type *type, char *name, int refok,
06964                             int noerr, int *dispp)
06965 {
06966   int i;
06967 
06968   if (name == NULL)
06969     goto BadName;
06970 
06971   if (refok && type != NULL)
06972     while (1)
06973       {
06974         type = ada_check_typedef (type);
06975         if (TYPE_CODE (type) != TYPE_CODE_PTR
06976             && TYPE_CODE (type) != TYPE_CODE_REF)
06977           break;
06978         type = TYPE_TARGET_TYPE (type);
06979       }
06980 
06981   if (type == NULL
06982       || (TYPE_CODE (type) != TYPE_CODE_STRUCT
06983           && TYPE_CODE (type) != TYPE_CODE_UNION))
06984     {
06985       if (noerr)
06986         return NULL;
06987       else
06988         {
06989           target_terminal_ours ();
06990           gdb_flush (gdb_stdout);
06991           if (type == NULL)
06992             error (_("Type (null) is not a structure or union type"));
06993           else
06994             {
06995               /* XXX: type_sprint */
06996               fprintf_unfiltered (gdb_stderr, _("Type "));
06997               type_print (type, "", gdb_stderr, -1);
06998               error (_(" is not a structure or union type"));
06999             }
07000         }
07001     }
07002 
07003   type = to_static_fixed_type (type);
07004 
07005   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
07006     {
07007       const char *t_field_name = TYPE_FIELD_NAME (type, i);
07008       struct type *t;
07009       int disp;
07010 
07011       if (t_field_name == NULL)
07012         continue;
07013 
07014       else if (field_name_match (t_field_name, name))
07015         {
07016           if (dispp != NULL)
07017             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
07018           return ada_check_typedef (TYPE_FIELD_TYPE (type, i));
07019         }
07020 
07021       else if (ada_is_wrapper_field (type, i))
07022         {
07023           disp = 0;
07024           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
07025                                           0, 1, &disp);
07026           if (t != NULL)
07027             {
07028               if (dispp != NULL)
07029                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
07030               return t;
07031             }
07032         }
07033 
07034       else if (ada_is_variant_part (type, i))
07035         {
07036           int j;
07037           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type,
07038                                                                         i));
07039 
07040           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
07041             {
07042               /* FIXME pnh 2008/01/26: We check for a field that is
07043                  NOT wrapped in a struct, since the compiler sometimes
07044                  generates these for unchecked variant types.  Revisit
07045                  if the compiler changes this practice.  */
07046               const char *v_field_name = TYPE_FIELD_NAME (field_type, j);
07047               disp = 0;
07048               if (v_field_name != NULL 
07049                   && field_name_match (v_field_name, name))
07050                 t = ada_check_typedef (TYPE_FIELD_TYPE (field_type, j));
07051               else
07052                 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type,
07053                                                                  j),
07054                                                 name, 0, 1, &disp);
07055 
07056               if (t != NULL)
07057                 {
07058                   if (dispp != NULL)
07059                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
07060                   return t;
07061                 }
07062             }
07063         }
07064 
07065     }
07066 
07067 BadName:
07068   if (!noerr)
07069     {
07070       target_terminal_ours ();
07071       gdb_flush (gdb_stdout);
07072       if (name == NULL)
07073         {
07074           /* XXX: type_sprint */
07075           fprintf_unfiltered (gdb_stderr, _("Type "));
07076           type_print (type, "", gdb_stderr, -1);
07077           error (_(" has no component named <null>"));
07078         }
07079       else
07080         {
07081           /* XXX: type_sprint */
07082           fprintf_unfiltered (gdb_stderr, _("Type "));
07083           type_print (type, "", gdb_stderr, -1);
07084           error (_(" has no component named %s"), name);
07085         }
07086     }
07087 
07088   return NULL;
07089 }
07090 
07091 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
07092    within a value of type OUTER_TYPE, return true iff VAR_TYPE
07093    represents an unchecked union (that is, the variant part of a
07094    record that is named in an Unchecked_Union pragma).  */
07095 
07096 static int
07097 is_unchecked_variant (struct type *var_type, struct type *outer_type)
07098 {
07099   char *discrim_name = ada_variant_discrim_name (var_type);
07100 
07101   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1, NULL) 
07102           == NULL);
07103 }
07104 
07105 
07106 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
07107    within a value of type OUTER_TYPE that is stored in GDB at
07108    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
07109    numbering from 0) is applicable.  Returns -1 if none are.  */
07110 
07111 int
07112 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
07113                            const gdb_byte *outer_valaddr)
07114 {
07115   int others_clause;
07116   int i;
07117   char *discrim_name = ada_variant_discrim_name (var_type);
07118   struct value *outer;
07119   struct value *discrim;
07120   LONGEST discrim_val;
07121 
07122   outer = value_from_contents_and_address (outer_type, outer_valaddr, 0);
07123   discrim = ada_value_struct_elt (outer, discrim_name, 1);
07124   if (discrim == NULL)
07125     return -1;
07126   discrim_val = value_as_long (discrim);
07127 
07128   others_clause = -1;
07129   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
07130     {
07131       if (ada_is_others_clause (var_type, i))
07132         others_clause = i;
07133       else if (ada_in_variant (discrim_val, var_type, i))
07134         return i;
07135     }
07136 
07137   return others_clause;
07138 }
07139 
07140 
07141 
07142                                 /* Dynamic-Sized Records */
07143 
07144 /* Strategy: The type ostensibly attached to a value with dynamic size
07145    (i.e., a size that is not statically recorded in the debugging
07146    data) does not accurately reflect the size or layout of the value.
07147    Our strategy is to convert these values to values with accurate,
07148    conventional types that are constructed on the fly.  */
07149 
07150 /* There is a subtle and tricky problem here.  In general, we cannot
07151    determine the size of dynamic records without its data.  However,
07152    the 'struct value' data structure, which GDB uses to represent
07153    quantities in the inferior process (the target), requires the size
07154    of the type at the time of its allocation in order to reserve space
07155    for GDB's internal copy of the data.  That's why the
07156    'to_fixed_xxx_type' routines take (target) addresses as parameters,
07157    rather than struct value*s.
07158 
07159    However, GDB's internal history variables ($1, $2, etc.) are
07160    struct value*s containing internal copies of the data that are not, in
07161    general, the same as the data at their corresponding addresses in
07162    the target.  Fortunately, the types we give to these values are all
07163    conventional, fixed-size types (as per the strategy described
07164    above), so that we don't usually have to perform the
07165    'to_fixed_xxx_type' conversions to look at their values.
07166    Unfortunately, there is one exception: if one of the internal
07167    history variables is an array whose elements are unconstrained
07168    records, then we will need to create distinct fixed types for each
07169    element selected.  */
07170 
07171 /* The upshot of all of this is that many routines take a (type, host
07172    address, target address) triple as arguments to represent a value.
07173    The host address, if non-null, is supposed to contain an internal
07174    copy of the relevant data; otherwise, the program is to consult the
07175    target at the target address.  */
07176 
07177 /* Assuming that VAL0 represents a pointer value, the result of
07178    dereferencing it.  Differs from value_ind in its treatment of
07179    dynamic-sized types.  */
07180 
07181 struct value *
07182 ada_value_ind (struct value *val0)
07183 {
07184   struct value *val = value_ind (val0);
07185 
07186   if (ada_is_tagged_type (value_type (val), 0))
07187     val = ada_tag_value_at_base_address (val);
07188 
07189   return ada_to_fixed_value (val);
07190 }
07191 
07192 /* The value resulting from dereferencing any "reference to"
07193    qualifiers on VAL0.  */
07194 
07195 static struct value *
07196 ada_coerce_ref (struct value *val0)
07197 {
07198   if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
07199     {
07200       struct value *val = val0;
07201 
07202       val = coerce_ref (val);
07203 
07204       if (ada_is_tagged_type (value_type (val), 0))
07205         val = ada_tag_value_at_base_address (val);
07206 
07207       return ada_to_fixed_value (val);
07208     }
07209   else
07210     return val0;
07211 }
07212 
07213 /* Return OFF rounded upward if necessary to a multiple of
07214    ALIGNMENT (a power of 2).  */
07215 
07216 static unsigned int
07217 align_value (unsigned int off, unsigned int alignment)
07218 {
07219   return (off + alignment - 1) & ~(alignment - 1);
07220 }
07221 
07222 /* Return the bit alignment required for field #F of template type TYPE.  */
07223 
07224 static unsigned int
07225 field_alignment (struct type *type, int f)
07226 {
07227   const char *name = TYPE_FIELD_NAME (type, f);
07228   int len;
07229   int align_offset;
07230 
07231   /* The field name should never be null, unless the debugging information
07232      is somehow malformed.  In this case, we assume the field does not
07233      require any alignment.  */
07234   if (name == NULL)
07235     return 1;
07236 
07237   len = strlen (name);
07238 
07239   if (!isdigit (name[len - 1]))
07240     return 1;
07241 
07242   if (isdigit (name[len - 2]))
07243     align_offset = len - 2;
07244   else
07245     align_offset = len - 1;
07246 
07247   if (align_offset < 7 || strncmp ("___XV", name + align_offset - 6, 5) != 0)
07248     return TARGET_CHAR_BIT;
07249 
07250   return atoi (name + align_offset) * TARGET_CHAR_BIT;
07251 }
07252 
07253 /* Find a typedef or tag symbol named NAME.  Ignores ambiguity.  */
07254 
07255 static struct symbol *
07256 ada_find_any_type_symbol (const char *name)
07257 {
07258   struct symbol *sym;
07259 
07260   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
07261   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
07262     return sym;
07263 
07264   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
07265   return sym;
07266 }
07267 
07268 /* Find a type named NAME.  Ignores ambiguity.  This routine will look
07269    solely for types defined by debug info, it will not search the GDB
07270    primitive types.  */
07271 
07272 static struct type *
07273 ada_find_any_type (const char *name)
07274 {
07275   struct symbol *sym = ada_find_any_type_symbol (name);
07276 
07277   if (sym != NULL)
07278     return SYMBOL_TYPE (sym);
07279 
07280   return NULL;
07281 }
07282 
07283 /* Given NAME_SYM and an associated BLOCK, find a "renaming" symbol
07284    associated with NAME_SYM's name.  NAME_SYM may itself be a renaming
07285    symbol, in which case it is returned.  Otherwise, this looks for
07286    symbols whose name is that of NAME_SYM suffixed with  "___XR".
07287    Return symbol if found, and NULL otherwise.  */
07288 
07289 struct symbol *
07290 ada_find_renaming_symbol (struct symbol *name_sym, const struct block *block)
07291 {
07292   const char *name = SYMBOL_LINKAGE_NAME (name_sym);
07293   struct symbol *sym;
07294 
07295   if (strstr (name, "___XR") != NULL)
07296      return name_sym;
07297 
07298   sym = find_old_style_renaming_symbol (name, block);
07299 
07300   if (sym != NULL)
07301     return sym;
07302 
07303   /* Not right yet.  FIXME pnh 7/20/2007.  */
07304   sym = ada_find_any_type_symbol (name);
07305   if (sym != NULL && strstr (SYMBOL_LINKAGE_NAME (sym), "___XR") != NULL)
07306     return sym;
07307   else
07308     return NULL;
07309 }
07310 
07311 static struct symbol *
07312 find_old_style_renaming_symbol (const char *name, const struct block *block)
07313 {
07314   const struct symbol *function_sym = block_linkage_function (block);
07315   char *rename;
07316 
07317   if (function_sym != NULL)
07318     {
07319       /* If the symbol is defined inside a function, NAME is not fully
07320          qualified.  This means we need to prepend the function name
07321          as well as adding the ``___XR'' suffix to build the name of
07322          the associated renaming symbol.  */
07323       const char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
07324       /* Function names sometimes contain suffixes used
07325          for instance to qualify nested subprograms.  When building
07326          the XR type name, we need to make sure that this suffix is
07327          not included.  So do not include any suffix in the function
07328          name length below.  */
07329       int function_name_len = ada_name_prefix_len (function_name);
07330       const int rename_len = function_name_len + 2      /*  "__" */
07331         + strlen (name) + 6 /* "___XR\0" */ ;
07332 
07333       /* Strip the suffix if necessary.  */
07334       ada_remove_trailing_digits (function_name, &function_name_len);
07335       ada_remove_po_subprogram_suffix (function_name, &function_name_len);
07336       ada_remove_Xbn_suffix (function_name, &function_name_len);
07337 
07338       /* Library-level functions are a special case, as GNAT adds
07339          a ``_ada_'' prefix to the function name to avoid namespace
07340          pollution.  However, the renaming symbols themselves do not
07341          have this prefix, so we need to skip this prefix if present.  */
07342       if (function_name_len > 5 /* "_ada_" */
07343           && strstr (function_name, "_ada_") == function_name)
07344         {
07345           function_name += 5;
07346           function_name_len -= 5;
07347         }
07348 
07349       rename = (char *) alloca (rename_len * sizeof (char));
07350       strncpy (rename, function_name, function_name_len);
07351       xsnprintf (rename + function_name_len, rename_len - function_name_len,
07352                  "__%s___XR", name);
07353     }
07354   else
07355     {
07356       const int rename_len = strlen (name) + 6;
07357 
07358       rename = (char *) alloca (rename_len * sizeof (char));
07359       xsnprintf (rename, rename_len * sizeof (char), "%s___XR", name);
07360     }
07361 
07362   return ada_find_any_type_symbol (rename);
07363 }
07364 
07365 /* Because of GNAT encoding conventions, several GDB symbols may match a
07366    given type name.  If the type denoted by TYPE0 is to be preferred to
07367    that of TYPE1 for purposes of type printing, return non-zero;
07368    otherwise return 0.  */
07369 
07370 int
07371 ada_prefer_type (struct type *type0, struct type *type1)
07372 {
07373   if (type1 == NULL)
07374     return 1;
07375   else if (type0 == NULL)
07376     return 0;
07377   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
07378     return 1;
07379   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
07380     return 0;
07381   else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
07382     return 1;
07383   else if (ada_is_constrained_packed_array_type (type0))
07384     return 1;
07385   else if (ada_is_array_descriptor_type (type0)
07386            && !ada_is_array_descriptor_type (type1))
07387     return 1;
07388   else
07389     {
07390       const char *type0_name = type_name_no_tag (type0);
07391       const char *type1_name = type_name_no_tag (type1);
07392 
07393       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
07394           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
07395         return 1;
07396     }
07397   return 0;
07398 }
07399 
07400 /* The name of TYPE, which is either its TYPE_NAME, or, if that is
07401    null, its TYPE_TAG_NAME.  Null if TYPE is null.  */
07402 
07403 const char *
07404 ada_type_name (struct type *type)
07405 {
07406   if (type == NULL)
07407     return NULL;
07408   else if (TYPE_NAME (type) != NULL)
07409     return TYPE_NAME (type);
07410   else
07411     return TYPE_TAG_NAME (type);
07412 }
07413 
07414 /* Search the list of "descriptive" types associated to TYPE for a type
07415    whose name is NAME.  */
07416 
07417 static struct type *
07418 find_parallel_type_by_descriptive_type (struct type *type, const char *name)
07419 {
07420   struct type *result;
07421 
07422   /* If there no descriptive-type info, then there is no parallel type
07423      to be found.  */
07424   if (!HAVE_GNAT_AUX_INFO (type))
07425     return NULL;
07426 
07427   result = TYPE_DESCRIPTIVE_TYPE (type);
07428   while (result != NULL)
07429     {
07430       const char *result_name = ada_type_name (result);
07431 
07432       if (result_name == NULL)
07433         {
07434           warning (_("unexpected null name on descriptive type"));
07435           return NULL;
07436         }
07437 
07438       /* If the names match, stop.  */
07439       if (strcmp (result_name, name) == 0)
07440         break;
07441 
07442       /* Otherwise, look at the next item on the list, if any.  */
07443       if (HAVE_GNAT_AUX_INFO (result))
07444         result = TYPE_DESCRIPTIVE_TYPE (result);
07445       else
07446         result = NULL;
07447     }
07448 
07449   /* If we didn't find a match, see whether this is a packed array.  With
07450      older compilers, the descriptive type information is either absent or
07451      irrelevant when it comes to packed arrays so the above lookup fails.
07452      Fall back to using a parallel lookup by name in this case.  */
07453   if (result == NULL && ada_is_constrained_packed_array_type (type))
07454     return ada_find_any_type (name);
07455 
07456   return result;
07457 }
07458 
07459 /* Find a parallel type to TYPE with the specified NAME, using the
07460    descriptive type taken from the debugging information, if available,
07461    and otherwise using the (slower) name-based method.  */
07462 
07463 static struct type *
07464 ada_find_parallel_type_with_name (struct type *type, const char *name)
07465 {
07466   struct type *result = NULL;
07467 
07468   if (HAVE_GNAT_AUX_INFO (type))
07469     result = find_parallel_type_by_descriptive_type (type, name);
07470   else
07471     result = ada_find_any_type (name);
07472 
07473   return result;
07474 }
07475 
07476 /* Same as above, but specify the name of the parallel type by appending
07477    SUFFIX to the name of TYPE.  */
07478 
07479 struct type *
07480 ada_find_parallel_type (struct type *type, const char *suffix)
07481 {
07482   char *name;
07483   const char *typename = ada_type_name (type);
07484   int len;
07485 
07486   if (typename == NULL)
07487     return NULL;
07488 
07489   len = strlen (typename);
07490 
07491   name = (char *) alloca (len + strlen (suffix) + 1);
07492 
07493   strcpy (name, typename);
07494   strcpy (name + len, suffix);
07495 
07496   return ada_find_parallel_type_with_name (type, name);
07497 }
07498 
07499 /* If TYPE is a variable-size record type, return the corresponding template
07500    type describing its fields.  Otherwise, return NULL.  */
07501 
07502 static struct type *
07503 dynamic_template_type (struct type *type)
07504 {
07505   type = ada_check_typedef (type);
07506 
07507   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
07508       || ada_type_name (type) == NULL)
07509     return NULL;
07510   else
07511     {
07512       int len = strlen (ada_type_name (type));
07513 
07514       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
07515         return type;
07516       else
07517         return ada_find_parallel_type (type, "___XVE");
07518     }
07519 }
07520 
07521 /* Assuming that TEMPL_TYPE is a union or struct type, returns
07522    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
07523 
07524 static int
07525 is_dynamic_field (struct type *templ_type, int field_num)
07526 {
07527   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
07528 
07529   return name != NULL
07530     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
07531     && strstr (name, "___XVL") != NULL;
07532 }
07533 
07534 /* The index of the variant field of TYPE, or -1 if TYPE does not
07535    represent a variant record type.  */
07536 
07537 static int
07538 variant_field_index (struct type *type)
07539 {
07540   int f;
07541 
07542   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
07543     return -1;
07544 
07545   for (f = 0; f < TYPE_NFIELDS (type); f += 1)
07546     {
07547       if (ada_is_variant_part (type, f))
07548         return f;
07549     }
07550   return -1;
07551 }
07552 
07553 /* A record type with no fields.  */
07554 
07555 static struct type *
07556 empty_record (struct type *template)
07557 {
07558   struct type *type = alloc_type_copy (template);
07559 
07560   TYPE_CODE (type) = TYPE_CODE_STRUCT;
07561   TYPE_NFIELDS (type) = 0;
07562   TYPE_FIELDS (type) = NULL;
07563   INIT_CPLUS_SPECIFIC (type);
07564   TYPE_NAME (type) = "<empty>";
07565   TYPE_TAG_NAME (type) = NULL;
07566   TYPE_LENGTH (type) = 0;
07567   return type;
07568 }
07569 
07570 /* An ordinary record type (with fixed-length fields) that describes
07571    the value of type TYPE at VALADDR or ADDRESS (see comments at
07572    the beginning of this section) VAL according to GNAT conventions.
07573    DVAL0 should describe the (portion of a) record that contains any
07574    necessary discriminants.  It should be NULL if value_type (VAL) is
07575    an outer-level type (i.e., as opposed to a branch of a variant.)  A
07576    variant field (unless unchecked) is replaced by a particular branch
07577    of the variant.
07578 
07579    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
07580    length are not statically known are discarded.  As a consequence,
07581    VALADDR, ADDRESS and DVAL0 are ignored.
07582 
07583    NOTE: Limitations: For now, we assume that dynamic fields and
07584    variants occupy whole numbers of bytes.  However, they need not be
07585    byte-aligned.  */
07586 
07587 struct type *
07588 ada_template_to_fixed_record_type_1 (struct type *type,
07589                                      const gdb_byte *valaddr,
07590                                      CORE_ADDR address, struct value *dval0,
07591                                      int keep_dynamic_fields)
07592 {
07593   struct value *mark = value_mark ();
07594   struct value *dval;
07595   struct type *rtype;
07596   int nfields, bit_len;
07597   int variant_field;
07598   long off;
07599   int fld_bit_len;
07600   int f;
07601 
07602   /* Compute the number of fields in this record type that are going
07603      to be processed: unless keep_dynamic_fields, this includes only
07604      fields whose position and length are static will be processed.  */
07605   if (keep_dynamic_fields)
07606     nfields = TYPE_NFIELDS (type);
07607   else
07608     {
07609       nfields = 0;
07610       while (nfields < TYPE_NFIELDS (type)
07611              && !ada_is_variant_part (type, nfields)
07612              && !is_dynamic_field (type, nfields))
07613         nfields++;
07614     }
07615 
07616   rtype = alloc_type_copy (type);
07617   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
07618   INIT_CPLUS_SPECIFIC (rtype);
07619   TYPE_NFIELDS (rtype) = nfields;
07620   TYPE_FIELDS (rtype) = (struct field *)
07621     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
07622   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
07623   TYPE_NAME (rtype) = ada_type_name (type);
07624   TYPE_TAG_NAME (rtype) = NULL;
07625   TYPE_FIXED_INSTANCE (rtype) = 1;
07626 
07627   off = 0;
07628   bit_len = 0;
07629   variant_field = -1;
07630 
07631   for (f = 0; f < nfields; f += 1)
07632     {
07633       off = align_value (off, field_alignment (type, f))
07634         + TYPE_FIELD_BITPOS (type, f);
07635       SET_FIELD_BITPOS (TYPE_FIELD (rtype, f), off);
07636       TYPE_FIELD_BITSIZE (rtype, f) = 0;
07637 
07638       if (ada_is_variant_part (type, f))
07639         {
07640           variant_field = f;
07641           fld_bit_len = 0;
07642         }
07643       else if (is_dynamic_field (type, f))
07644         {
07645           const gdb_byte *field_valaddr = valaddr;
07646           CORE_ADDR field_address = address;
07647           struct type *field_type =
07648             TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f));
07649 
07650           if (dval0 == NULL)
07651             {
07652               /* rtype's length is computed based on the run-time
07653                  value of discriminants.  If the discriminants are not
07654                  initialized, the type size may be completely bogus and
07655                  GDB may fail to allocate a value for it.  So check the
07656                  size first before creating the value.  */
07657               check_size (rtype);
07658               dval = value_from_contents_and_address (rtype, valaddr, address);
07659             }
07660           else
07661             dval = dval0;
07662 
07663           /* If the type referenced by this field is an aligner type, we need
07664              to unwrap that aligner type, because its size might not be set.
07665              Keeping the aligner type would cause us to compute the wrong
07666              size for this field, impacting the offset of the all the fields
07667              that follow this one.  */
07668           if (ada_is_aligner_type (field_type))
07669             {
07670               long field_offset = TYPE_FIELD_BITPOS (field_type, f);
07671 
07672               field_valaddr = cond_offset_host (field_valaddr, field_offset);
07673               field_address = cond_offset_target (field_address, field_offset);
07674               field_type = ada_aligned_type (field_type);
07675             }
07676 
07677           field_valaddr = cond_offset_host (field_valaddr,
07678                                             off / TARGET_CHAR_BIT);
07679           field_address = cond_offset_target (field_address,
07680                                               off / TARGET_CHAR_BIT);
07681 
07682           /* Get the fixed type of the field.  Note that, in this case,
07683              we do not want to get the real type out of the tag: if
07684              the current field is the parent part of a tagged record,
07685              we will get the tag of the object.  Clearly wrong: the real
07686              type of the parent is not the real type of the child.  We
07687              would end up in an infinite loop.  */
07688           field_type = ada_get_base_type (field_type);
07689           field_type = ada_to_fixed_type (field_type, field_valaddr,
07690                                           field_address, dval, 0);
07691           /* If the field size is already larger than the maximum
07692              object size, then the record itself will necessarily
07693              be larger than the maximum object size.  We need to make
07694              this check now, because the size might be so ridiculously
07695              large (due to an uninitialized variable in the inferior)
07696              that it would cause an overflow when adding it to the
07697              record size.  */
07698           check_size (field_type);
07699 
07700           TYPE_FIELD_TYPE (rtype, f) = field_type;
07701           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
07702           /* The multiplication can potentially overflow.  But because
07703              the field length has been size-checked just above, and
07704              assuming that the maximum size is a reasonable value,
07705              an overflow should not happen in practice.  So rather than
07706              adding overflow recovery code to this already complex code,
07707              we just assume that it's not going to happen.  */
07708           fld_bit_len =
07709             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
07710         }
07711       else
07712         {
07713           /* Note: If this field's type is a typedef, it is important
07714              to preserve the typedef layer.
07715 
07716              Otherwise, we might be transforming a typedef to a fat
07717              pointer (encoding a pointer to an unconstrained array),
07718              into a basic fat pointer (encoding an unconstrained
07719              array).  As both types are implemented using the same
07720              structure, the typedef is the only clue which allows us
07721              to distinguish between the two options.  Stripping it
07722              would prevent us from printing this field appropriately.  */
07723           TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
07724           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
07725           if (TYPE_FIELD_BITSIZE (type, f) > 0)
07726             fld_bit_len =
07727               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
07728           else
07729             {
07730               struct type *field_type = TYPE_FIELD_TYPE (type, f);
07731 
07732               /* We need to be careful of typedefs when computing
07733                  the length of our field.  If this is a typedef,
07734                  get the length of the target type, not the length
07735                  of the typedef.  */
07736               if (TYPE_CODE (field_type) == TYPE_CODE_TYPEDEF)
07737                 field_type = ada_typedef_target_type (field_type);
07738 
07739               fld_bit_len =
07740                 TYPE_LENGTH (ada_check_typedef (field_type)) * TARGET_CHAR_BIT;
07741             }
07742         }
07743       if (off + fld_bit_len > bit_len)
07744         bit_len = off + fld_bit_len;
07745       off += fld_bit_len;
07746       TYPE_LENGTH (rtype) =
07747         align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
07748     }
07749 
07750   /* We handle the variant part, if any, at the end because of certain
07751      odd cases in which it is re-ordered so as NOT to be the last field of
07752      the record.  This can happen in the presence of representation
07753      clauses.  */
07754   if (variant_field >= 0)
07755     {
07756       struct type *branch_type;
07757 
07758       off = TYPE_FIELD_BITPOS (rtype, variant_field);
07759 
07760       if (dval0 == NULL)
07761         dval = value_from_contents_and_address (rtype, valaddr, address);
07762       else
07763         dval = dval0;
07764 
07765       branch_type =
07766         to_fixed_variant_branch_type
07767         (TYPE_FIELD_TYPE (type, variant_field),
07768          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
07769          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
07770       if (branch_type == NULL)
07771         {
07772           for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
07773             TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
07774           TYPE_NFIELDS (rtype) -= 1;
07775         }
07776       else
07777         {
07778           TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
07779           TYPE_FIELD_NAME (rtype, variant_field) = "S";
07780           fld_bit_len =
07781             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
07782             TARGET_CHAR_BIT;
07783           if (off + fld_bit_len > bit_len)
07784             bit_len = off + fld_bit_len;
07785           TYPE_LENGTH (rtype) =
07786             align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
07787         }
07788     }
07789 
07790   /* According to exp_dbug.ads, the size of TYPE for variable-size records
07791      should contain the alignment of that record, which should be a strictly
07792      positive value.  If null or negative, then something is wrong, most
07793      probably in the debug info.  In that case, we don't round up the size
07794      of the resulting type.  If this record is not part of another structure,
07795      the current RTYPE length might be good enough for our purposes.  */
07796   if (TYPE_LENGTH (type) <= 0)
07797     {
07798       if (TYPE_NAME (rtype))
07799         warning (_("Invalid type size for `%s' detected: %d."),
07800                  TYPE_NAME (rtype), TYPE_LENGTH (type));
07801       else
07802         warning (_("Invalid type size for <unnamed> detected: %d."),
07803                  TYPE_LENGTH (type));
07804     }
07805   else
07806     {
07807       TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
07808                                          TYPE_LENGTH (type));
07809     }
07810 
07811   value_free_to_mark (mark);
07812   if (TYPE_LENGTH (rtype) > varsize_limit)
07813     error (_("record type with dynamic size is larger than varsize-limit"));
07814   return rtype;
07815 }
07816 
07817 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
07818    of 1.  */
07819 
07820 static struct type *
07821 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
07822                                CORE_ADDR address, struct value *dval0)
07823 {
07824   return ada_template_to_fixed_record_type_1 (type, valaddr,
07825                                               address, dval0, 1);
07826 }
07827 
07828 /* An ordinary record type in which ___XVL-convention fields and
07829    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
07830    static approximations, containing all possible fields.  Uses
07831    no runtime values.  Useless for use in values, but that's OK,
07832    since the results are used only for type determinations.   Works on both
07833    structs and unions.  Representation note: to save space, we memorize
07834    the result of this function in the TYPE_TARGET_TYPE of the
07835    template type.  */
07836 
07837 static struct type *
07838 template_to_static_fixed_type (struct type *type0)
07839 {
07840   struct type *type;
07841   int nfields;
07842   int f;
07843 
07844   if (TYPE_TARGET_TYPE (type0) != NULL)
07845     return TYPE_TARGET_TYPE (type0);
07846 
07847   nfields = TYPE_NFIELDS (type0);
07848   type = type0;
07849 
07850   for (f = 0; f < nfields; f += 1)
07851     {
07852       struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type0, f));
07853       struct type *new_type;
07854 
07855       if (is_dynamic_field (type0, f))
07856         new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
07857       else
07858         new_type = static_unwrap_type (field_type);
07859       if (type == type0 && new_type != field_type)
07860         {
07861           TYPE_TARGET_TYPE (type0) = type = alloc_type_copy (type0);
07862           TYPE_CODE (type) = TYPE_CODE (type0);
07863           INIT_CPLUS_SPECIFIC (type);
07864           TYPE_NFIELDS (type) = nfields;
07865           TYPE_FIELDS (type) = (struct field *)
07866             TYPE_ALLOC (type, nfields * sizeof (struct field));
07867           memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
07868                   sizeof (struct field) * nfields);
07869           TYPE_NAME (type) = ada_type_name (type0);
07870           TYPE_TAG_NAME (type) = NULL;
07871           TYPE_FIXED_INSTANCE (type) = 1;
07872           TYPE_LENGTH (type) = 0;
07873         }
07874       TYPE_FIELD_TYPE (type, f) = new_type;
07875       TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
07876     }
07877   return type;
07878 }
07879 
07880 /* Given an object of type TYPE whose contents are at VALADDR and
07881    whose address in memory is ADDRESS, returns a revision of TYPE,
07882    which should be a non-dynamic-sized record, in which the variant
07883    part, if any, is replaced with the appropriate branch.  Looks
07884    for discriminant values in DVAL0, which can be NULL if the record
07885    contains the necessary discriminant values.  */
07886 
07887 static struct type *
07888 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
07889                                    CORE_ADDR address, struct value *dval0)
07890 {
07891   struct value *mark = value_mark ();
07892   struct value *dval;
07893   struct type *rtype;
07894   struct type *branch_type;
07895   int nfields = TYPE_NFIELDS (type);
07896   int variant_field = variant_field_index (type);
07897 
07898   if (variant_field == -1)
07899     return type;
07900 
07901   if (dval0 == NULL)
07902     dval = value_from_contents_and_address (type, valaddr, address);
07903   else
07904     dval = dval0;
07905 
07906   rtype = alloc_type_copy (type);
07907   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
07908   INIT_CPLUS_SPECIFIC (rtype);
07909   TYPE_NFIELDS (rtype) = nfields;
07910   TYPE_FIELDS (rtype) =
07911     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
07912   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
07913           sizeof (struct field) * nfields);
07914   TYPE_NAME (rtype) = ada_type_name (type);
07915   TYPE_TAG_NAME (rtype) = NULL;
07916   TYPE_FIXED_INSTANCE (rtype) = 1;
07917   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
07918 
07919   branch_type = to_fixed_variant_branch_type
07920     (TYPE_FIELD_TYPE (type, variant_field),
07921      cond_offset_host (valaddr,
07922                        TYPE_FIELD_BITPOS (type, variant_field)
07923                        / TARGET_CHAR_BIT),
07924      cond_offset_target (address,
07925                          TYPE_FIELD_BITPOS (type, variant_field)
07926                          / TARGET_CHAR_BIT), dval);
07927   if (branch_type == NULL)
07928     {
07929       int f;
07930 
07931       for (f = variant_field + 1; f < nfields; f += 1)
07932         TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
07933       TYPE_NFIELDS (rtype) -= 1;
07934     }
07935   else
07936     {
07937       TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
07938       TYPE_FIELD_NAME (rtype, variant_field) = "S";
07939       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
07940       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
07941     }
07942   TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
07943 
07944   value_free_to_mark (mark);
07945   return rtype;
07946 }
07947 
07948 /* An ordinary record type (with fixed-length fields) that describes
07949    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
07950    beginning of this section].   Any necessary discriminants' values
07951    should be in DVAL, a record value; it may be NULL if the object
07952    at ADDR itself contains any necessary discriminant values.
07953    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
07954    values from the record are needed.  Except in the case that DVAL,
07955    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
07956    unchecked) is replaced by a particular branch of the variant.
07957 
07958    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
07959    is questionable and may be removed.  It can arise during the
07960    processing of an unconstrained-array-of-record type where all the
07961    variant branches have exactly the same size.  This is because in
07962    such cases, the compiler does not bother to use the XVS convention
07963    when encoding the record.  I am currently dubious of this
07964    shortcut and suspect the compiler should be altered.  FIXME.  */
07965 
07966 static struct type *
07967 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
07968                       CORE_ADDR address, struct value *dval)
07969 {
07970   struct type *templ_type;
07971 
07972   if (TYPE_FIXED_INSTANCE (type0))
07973     return type0;
07974 
07975   templ_type = dynamic_template_type (type0);
07976 
07977   if (templ_type != NULL)
07978     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
07979   else if (variant_field_index (type0) >= 0)
07980     {
07981       if (dval == NULL && valaddr == NULL && address == 0)
07982         return type0;
07983       return to_record_with_fixed_variant_part (type0, valaddr, address,
07984                                                 dval);
07985     }
07986   else
07987     {
07988       TYPE_FIXED_INSTANCE (type0) = 1;
07989       return type0;
07990     }
07991 
07992 }
07993 
07994 /* An ordinary record type (with fixed-length fields) that describes
07995    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
07996    union type.  Any necessary discriminants' values should be in DVAL,
07997    a record value.  That is, this routine selects the appropriate
07998    branch of the union at ADDR according to the discriminant value
07999    indicated in the union's type name.  Returns VAR_TYPE0 itself if
08000    it represents a variant subject to a pragma Unchecked_Union.  */
08001 
08002 static struct type *
08003 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
08004                               CORE_ADDR address, struct value *dval)
08005 {
08006   int which;
08007   struct type *templ_type;
08008   struct type *var_type;
08009 
08010   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
08011     var_type = TYPE_TARGET_TYPE (var_type0);
08012   else
08013     var_type = var_type0;
08014 
08015   templ_type = ada_find_parallel_type (var_type, "___XVU");
08016 
08017   if (templ_type != NULL)
08018     var_type = templ_type;
08019 
08020   if (is_unchecked_variant (var_type, value_type (dval)))
08021       return var_type0;
08022   which =
08023     ada_which_variant_applies (var_type,
08024                                value_type (dval), value_contents (dval));
08025 
08026   if (which < 0)
08027     return empty_record (var_type);
08028   else if (is_dynamic_field (var_type, which))
08029     return to_fixed_record_type
08030       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
08031        valaddr, address, dval);
08032   else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
08033     return
08034       to_fixed_record_type
08035       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
08036   else
08037     return TYPE_FIELD_TYPE (var_type, which);
08038 }
08039 
08040 /* Assuming that TYPE0 is an array type describing the type of a value
08041    at ADDR, and that DVAL describes a record containing any
08042    discriminants used in TYPE0, returns a type for the value that
08043    contains no dynamic components (that is, no components whose sizes
08044    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
08045    true, gives an error message if the resulting type's size is over
08046    varsize_limit.  */
08047 
08048 static struct type *
08049 to_fixed_array_type (struct type *type0, struct value *dval,
08050                      int ignore_too_big)
08051 {
08052   struct type *index_type_desc;
08053   struct type *result;
08054   int constrained_packed_array_p;
08055 
08056   type0 = ada_check_typedef (type0);
08057   if (TYPE_FIXED_INSTANCE (type0))
08058     return type0;
08059 
08060   constrained_packed_array_p = ada_is_constrained_packed_array_type (type0);
08061   if (constrained_packed_array_p)
08062     type0 = decode_constrained_packed_array_type (type0);
08063 
08064   index_type_desc = ada_find_parallel_type (type0, "___XA");
08065   ada_fixup_array_indexes_type (index_type_desc);
08066   if (index_type_desc == NULL)
08067     {
08068       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
08069 
08070       /* NOTE: elt_type---the fixed version of elt_type0---should never
08071          depend on the contents of the array in properly constructed
08072          debugging data.  */
08073       /* Create a fixed version of the array element type.
08074          We're not providing the address of an element here,
08075          and thus the actual object value cannot be inspected to do
08076          the conversion.  This should not be a problem, since arrays of
08077          unconstrained objects are not allowed.  In particular, all
08078          the elements of an array of a tagged type should all be of
08079          the same type specified in the debugging info.  No need to
08080          consult the object tag.  */
08081       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
08082 
08083       /* Make sure we always create a new array type when dealing with
08084          packed array types, since we're going to fix-up the array
08085          type length and element bitsize a little further down.  */
08086       if (elt_type0 == elt_type && !constrained_packed_array_p)
08087         result = type0;
08088       else
08089         result = create_array_type (alloc_type_copy (type0),
08090                                     elt_type, TYPE_INDEX_TYPE (type0));
08091     }
08092   else
08093     {
08094       int i;
08095       struct type *elt_type0;
08096 
08097       elt_type0 = type0;
08098       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
08099         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
08100 
08101       /* NOTE: result---the fixed version of elt_type0---should never
08102          depend on the contents of the array in properly constructed
08103          debugging data.  */
08104       /* Create a fixed version of the array element type.
08105          We're not providing the address of an element here,
08106          and thus the actual object value cannot be inspected to do
08107          the conversion.  This should not be a problem, since arrays of
08108          unconstrained objects are not allowed.  In particular, all
08109          the elements of an array of a tagged type should all be of
08110          the same type specified in the debugging info.  No need to
08111          consult the object tag.  */
08112       result =
08113         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
08114 
08115       elt_type0 = type0;
08116       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
08117         {
08118           struct type *range_type =
08119             to_fixed_range_type (TYPE_FIELD_TYPE (index_type_desc, i), dval);
08120 
08121           result = create_array_type (alloc_type_copy (elt_type0),
08122                                       result, range_type);
08123           elt_type0 = TYPE_TARGET_TYPE (elt_type0);
08124         }
08125       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
08126         error (_("array type with dynamic size is larger than varsize-limit"));
08127     }
08128 
08129   /* We want to preserve the type name.  This can be useful when
08130      trying to get the type name of a value that has already been
08131      printed (for instance, if the user did "print VAR; whatis $".  */
08132   TYPE_NAME (result) = TYPE_NAME (type0);
08133 
08134   if (constrained_packed_array_p)
08135     {
08136       /* So far, the resulting type has been created as if the original
08137          type was a regular (non-packed) array type.  As a result, the
08138          bitsize of the array elements needs to be set again, and the array
08139          length needs to be recomputed based on that bitsize.  */
08140       int len = TYPE_LENGTH (result) / TYPE_LENGTH (TYPE_TARGET_TYPE (result));
08141       int elt_bitsize = TYPE_FIELD_BITSIZE (type0, 0);
08142 
08143       TYPE_FIELD_BITSIZE (result, 0) = TYPE_FIELD_BITSIZE (type0, 0);
08144       TYPE_LENGTH (result) = len * elt_bitsize / HOST_CHAR_BIT;
08145       if (TYPE_LENGTH (result) * HOST_CHAR_BIT < len * elt_bitsize)
08146         TYPE_LENGTH (result)++;
08147     }
08148 
08149   TYPE_FIXED_INSTANCE (result) = 1;
08150   return result;
08151 }
08152 
08153 
08154 /* A standard type (containing no dynamically sized components)
08155    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
08156    DVAL describes a record containing any discriminants used in TYPE0,
08157    and may be NULL if there are none, or if the object of type TYPE at
08158    ADDRESS or in VALADDR contains these discriminants.
08159    
08160    If CHECK_TAG is not null, in the case of tagged types, this function
08161    attempts to locate the object's tag and use it to compute the actual
08162    type.  However, when ADDRESS is null, we cannot use it to determine the
08163    location of the tag, and therefore compute the tagged type's actual type.
08164    So we return the tagged type without consulting the tag.  */
08165    
08166 static struct type *
08167 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
08168                    CORE_ADDR address, struct value *dval, int check_tag)
08169 {
08170   type = ada_check_typedef (type);
08171   switch (TYPE_CODE (type))
08172     {
08173     default:
08174       return type;
08175     case TYPE_CODE_STRUCT:
08176       {
08177         struct type *static_type = to_static_fixed_type (type);
08178         struct type *fixed_record_type =
08179           to_fixed_record_type (type, valaddr, address, NULL);
08180 
08181         /* If STATIC_TYPE is a tagged type and we know the object's address,
08182            then we can determine its tag, and compute the object's actual
08183            type from there.  Note that we have to use the fixed record
08184            type (the parent part of the record may have dynamic fields
08185            and the way the location of _tag is expressed may depend on
08186            them).  */
08187 
08188         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
08189           {
08190             struct value *tag =
08191               value_tag_from_contents_and_address
08192               (fixed_record_type,
08193                valaddr,
08194                address);
08195             struct type *real_type = type_from_tag (tag);
08196             struct value *obj =
08197               value_from_contents_and_address (fixed_record_type,
08198                                                valaddr,
08199                                                address);
08200             if (real_type != NULL)
08201               return to_fixed_record_type
08202                 (real_type, NULL,
08203                  value_address (ada_tag_value_at_base_address (obj)), NULL);
08204           }
08205 
08206         /* Check to see if there is a parallel ___XVZ variable.
08207            If there is, then it provides the actual size of our type.  */
08208         else if (ada_type_name (fixed_record_type) != NULL)
08209           {
08210             const char *name = ada_type_name (fixed_record_type);
08211             char *xvz_name = alloca (strlen (name) + 7 /* "___XVZ\0" */);
08212             int xvz_found = 0;
08213             LONGEST size;
08214 
08215             xsnprintf (xvz_name, strlen (name) + 7, "%s___XVZ", name);
08216             size = get_int_var_value (xvz_name, &xvz_found);
08217             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
08218               {
08219                 fixed_record_type = copy_type (fixed_record_type);
08220                 TYPE_LENGTH (fixed_record_type) = size;
08221 
08222                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
08223                    observed this when the debugging info is STABS, and
08224                    apparently it is something that is hard to fix.
08225 
08226                    In practice, we don't need the actual type definition
08227                    at all, because the presence of the XVZ variable allows us
08228                    to assume that there must be a XVS type as well, which we
08229                    should be able to use later, when we need the actual type
08230                    definition.
08231 
08232                    In the meantime, pretend that the "fixed" type we are
08233                    returning is NOT a stub, because this can cause trouble
08234                    when using this type to create new types targeting it.
08235                    Indeed, the associated creation routines often check
08236                    whether the target type is a stub and will try to replace
08237                    it, thus using a type with the wrong size.  This, in turn,
08238                    might cause the new type to have the wrong size too.
08239                    Consider the case of an array, for instance, where the size
08240                    of the array is computed from the number of elements in
08241                    our array multiplied by the size of its element.  */
08242                 TYPE_STUB (fixed_record_type) = 0;
08243               }
08244           }
08245         return fixed_record_type;
08246       }
08247     case TYPE_CODE_ARRAY:
08248       return to_fixed_array_type (type, dval, 1);
08249     case TYPE_CODE_UNION:
08250       if (dval == NULL)
08251         return type;
08252       else
08253         return to_fixed_variant_branch_type (type, valaddr, address, dval);
08254     }
08255 }
08256 
08257 /* The same as ada_to_fixed_type_1, except that it preserves the type
08258    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
08259 
08260    The typedef layer needs be preserved in order to differentiate between
08261    arrays and array pointers when both types are implemented using the same
08262    fat pointer.  In the array pointer case, the pointer is encoded as
08263    a typedef of the pointer type.  For instance, considering:
08264 
08265           type String_Access is access String;
08266           S1 : String_Access := null;
08267 
08268    To the debugger, S1 is defined as a typedef of type String.  But
08269    to the user, it is a pointer.  So if the user tries to print S1,
08270    we should not dereference the array, but print the array address
08271    instead.
08272 
08273    If we didn't preserve the typedef layer, we would lose the fact that
08274    the type is to be presented as a pointer (needs de-reference before
08275    being printed).  And we would also use the source-level type name.  */
08276 
08277 struct type *
08278 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
08279                    CORE_ADDR address, struct value *dval, int check_tag)
08280 
08281 {
08282   struct type *fixed_type =
08283     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
08284 
08285   /*  If TYPE is a typedef and its target type is the same as the FIXED_TYPE,
08286       then preserve the typedef layer.
08287 
08288       Implementation note: We can only check the main-type portion of
08289       the TYPE and FIXED_TYPE, because eliminating the typedef layer
08290       from TYPE now returns a type that has the same instance flags
08291       as TYPE.  For instance, if TYPE is a "typedef const", and its
08292       target type is a "struct", then the typedef elimination will return
08293       a "const" version of the target type.  See check_typedef for more
08294       details about how the typedef layer elimination is done.
08295 
08296       brobecker/2010-11-19: It seems to me that the only case where it is
08297       useful to preserve the typedef layer is when dealing with fat pointers.
08298       Perhaps, we could add a check for that and preserve the typedef layer
08299       only in that situation.  But this seems unecessary so far, probably
08300       because we call check_typedef/ada_check_typedef pretty much everywhere.
08301       */
08302   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
08303       && (TYPE_MAIN_TYPE (ada_typedef_target_type (type))
08304           == TYPE_MAIN_TYPE (fixed_type)))
08305     return type;
08306 
08307   return fixed_type;
08308 }
08309 
08310 /* A standard (static-sized) type corresponding as well as possible to
08311    TYPE0, but based on no runtime data.  */
08312 
08313 static struct type *
08314 to_static_fixed_type (struct type *type0)
08315 {
08316   struct type *type;
08317 
08318   if (type0 == NULL)
08319     return NULL;
08320 
08321   if (TYPE_FIXED_INSTANCE (type0))
08322     return type0;
08323 
08324   type0 = ada_check_typedef (type0);
08325 
08326   switch (TYPE_CODE (type0))
08327     {
08328     default:
08329       return type0;
08330     case TYPE_CODE_STRUCT:
08331       type = dynamic_template_type (type0);
08332       if (type != NULL)
08333         return template_to_static_fixed_type (type);
08334       else
08335         return template_to_static_fixed_type (type0);
08336     case TYPE_CODE_UNION:
08337       type = ada_find_parallel_type (type0, "___XVU");
08338       if (type != NULL)
08339         return template_to_static_fixed_type (type);
08340       else
08341         return template_to_static_fixed_type (type0);
08342     }
08343 }
08344 
08345 /* A static approximation of TYPE with all type wrappers removed.  */
08346 
08347 static struct type *
08348 static_unwrap_type (struct type *type)
08349 {
08350   if (ada_is_aligner_type (type))
08351     {
08352       struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
08353       if (ada_type_name (type1) == NULL)
08354         TYPE_NAME (type1) = ada_type_name (type);
08355 
08356       return static_unwrap_type (type1);
08357     }
08358   else
08359     {
08360       struct type *raw_real_type = ada_get_base_type (type);
08361 
08362       if (raw_real_type == type)
08363         return type;
08364       else
08365         return to_static_fixed_type (raw_real_type);
08366     }
08367 }
08368 
08369 /* In some cases, incomplete and private types require
08370    cross-references that are not resolved as records (for example,
08371       type Foo;
08372       type FooP is access Foo;
08373       V: FooP;
08374       type Foo is array ...;
08375    ).  In these cases, since there is no mechanism for producing
08376    cross-references to such types, we instead substitute for FooP a
08377    stub enumeration type that is nowhere resolved, and whose tag is
08378    the name of the actual type.  Call these types "non-record stubs".  */
08379 
08380 /* A type equivalent to TYPE that is not a non-record stub, if one
08381    exists, otherwise TYPE.  */
08382 
08383 struct type *
08384 ada_check_typedef (struct type *type)
08385 {
08386   if (type == NULL)
08387     return NULL;
08388 
08389   /* If our type is a typedef type of a fat pointer, then we're done.
08390      We don't want to strip the TYPE_CODE_TYPDEF layer, because this is
08391      what allows us to distinguish between fat pointers that represent
08392      array types, and fat pointers that represent array access types
08393      (in both cases, the compiler implements them as fat pointers).  */
08394   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
08395       && is_thick_pntr (ada_typedef_target_type (type)))
08396     return type;
08397 
08398   CHECK_TYPEDEF (type);
08399   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
08400       || !TYPE_STUB (type)
08401       || TYPE_TAG_NAME (type) == NULL)
08402     return type;
08403   else
08404     {
08405       const char *name = TYPE_TAG_NAME (type);
08406       struct type *type1 = ada_find_any_type (name);
08407 
08408       if (type1 == NULL)
08409         return type;
08410 
08411       /* TYPE1 might itself be a TYPE_CODE_TYPEDEF (this can happen with
08412          stubs pointing to arrays, as we don't create symbols for array
08413          types, only for the typedef-to-array types).  If that's the case,
08414          strip the typedef layer.  */
08415       if (TYPE_CODE (type1) == TYPE_CODE_TYPEDEF)
08416         type1 = ada_check_typedef (type1);
08417 
08418       return type1;
08419     }
08420 }
08421 
08422 /* A value representing the data at VALADDR/ADDRESS as described by
08423    type TYPE0, but with a standard (static-sized) type that correctly
08424    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
08425    type, then return VAL0 [this feature is simply to avoid redundant
08426    creation of struct values].  */
08427 
08428 static struct value *
08429 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
08430                            struct value *val0)
08431 {
08432   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
08433 
08434   if (type == type0 && val0 != NULL)
08435     return val0;
08436   else
08437     return value_from_contents_and_address (type, 0, address);
08438 }
08439 
08440 /* A value representing VAL, but with a standard (static-sized) type
08441    that correctly describes it.  Does not necessarily create a new
08442    value.  */
08443 
08444 struct value *
08445 ada_to_fixed_value (struct value *val)
08446 {
08447   val = unwrap_value (val);
08448   val = ada_to_fixed_value_create (value_type (val),
08449                                       value_address (val),
08450                                       val);
08451   return val;
08452 }
08453 
08454 
08455 /* Attributes */
08456 
08457 /* Table mapping attribute numbers to names.
08458    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
08459 
08460 static const char *attribute_names[] = {
08461   "<?>",
08462 
08463   "first",
08464   "last",
08465   "length",
08466   "image",
08467   "max",
08468   "min",
08469   "modulus",
08470   "pos",
08471   "size",
08472   "tag",
08473   "val",
08474   0
08475 };
08476 
08477 const char *
08478 ada_attribute_name (enum exp_opcode n)
08479 {
08480   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
08481     return attribute_names[n - OP_ATR_FIRST + 1];
08482   else
08483     return attribute_names[0];
08484 }
08485 
08486 /* Evaluate the 'POS attribute applied to ARG.  */
08487 
08488 static LONGEST
08489 pos_atr (struct value *arg)
08490 {
08491   struct value *val = coerce_ref (arg);
08492   struct type *type = value_type (val);
08493 
08494   if (!discrete_type_p (type))
08495     error (_("'POS only defined on discrete types"));
08496 
08497   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
08498     {
08499       int i;
08500       LONGEST v = value_as_long (val);
08501 
08502       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
08503         {
08504           if (v == TYPE_FIELD_ENUMVAL (type, i))
08505             return i;
08506         }
08507       error (_("enumeration value is invalid: can't find 'POS"));
08508     }
08509   else
08510     return value_as_long (val);
08511 }
08512 
08513 static struct value *
08514 value_pos_atr (struct type *type, struct value *arg)
08515 {
08516   return value_from_longest (type, pos_atr (arg));
08517 }
08518 
08519 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
08520 
08521 static struct value *
08522 value_val_atr (struct type *type, struct value *arg)
08523 {
08524   if (!discrete_type_p (type))
08525     error (_("'VAL only defined on discrete types"));
08526   if (!integer_type_p (value_type (arg)))
08527     error (_("'VAL requires integral argument"));
08528 
08529   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
08530     {
08531       long pos = value_as_long (arg);
08532 
08533       if (pos < 0 || pos >= TYPE_NFIELDS (type))
08534         error (_("argument to 'VAL out of range"));
08535       return value_from_longest (type, TYPE_FIELD_ENUMVAL (type, pos));
08536     }
08537   else
08538     return value_from_longest (type, value_as_long (arg));
08539 }
08540 
08541 
08542                                 /* Evaluation */
08543 
08544 /* True if TYPE appears to be an Ada character type.
08545    [At the moment, this is true only for Character and Wide_Character;
08546    It is a heuristic test that could stand improvement].  */
08547 
08548 int
08549 ada_is_character_type (struct type *type)
08550 {
08551   const char *name;
08552 
08553   /* If the type code says it's a character, then assume it really is,
08554      and don't check any further.  */
08555   if (TYPE_CODE (type) == TYPE_CODE_CHAR)
08556     return 1;
08557   
08558   /* Otherwise, assume it's a character type iff it is a discrete type
08559      with a known character type name.  */
08560   name = ada_type_name (type);
08561   return (name != NULL
08562           && (TYPE_CODE (type) == TYPE_CODE_INT
08563               || TYPE_CODE (type) == TYPE_CODE_RANGE)
08564           && (strcmp (name, "character") == 0
08565               || strcmp (name, "wide_character") == 0
08566               || strcmp (name, "wide_wide_character") == 0
08567               || strcmp (name, "unsigned char") == 0));
08568 }
08569 
08570 /* True if TYPE appears to be an Ada string type.  */
08571 
08572 int
08573 ada_is_string_type (struct type *type)
08574 {
08575   type = ada_check_typedef (type);
08576   if (type != NULL
08577       && TYPE_CODE (type) != TYPE_CODE_PTR
08578       && (ada_is_simple_array_type (type)
08579           || ada_is_array_descriptor_type (type))
08580       && ada_array_arity (type) == 1)
08581     {
08582       struct type *elttype = ada_array_element_type (type, 1);
08583 
08584       return ada_is_character_type (elttype);
08585     }
08586   else
08587     return 0;
08588 }
08589 
08590 /* The compiler sometimes provides a parallel XVS type for a given
08591    PAD type.  Normally, it is safe to follow the PAD type directly,
08592    but older versions of the compiler have a bug that causes the offset
08593    of its "F" field to be wrong.  Following that field in that case
08594    would lead to incorrect results, but this can be worked around
08595    by ignoring the PAD type and using the associated XVS type instead.
08596 
08597    Set to True if the debugger should trust the contents of PAD types.
08598    Otherwise, ignore the PAD type if there is a parallel XVS type.  */
08599 static int trust_pad_over_xvs = 1;
08600 
08601 /* True if TYPE is a struct type introduced by the compiler to force the
08602    alignment of a value.  Such types have a single field with a
08603    distinctive name.  */
08604 
08605 int
08606 ada_is_aligner_type (struct type *type)
08607 {
08608   type = ada_check_typedef (type);
08609 
08610   if (!trust_pad_over_xvs && ada_find_parallel_type (type, "___XVS") != NULL)
08611     return 0;
08612 
08613   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
08614           && TYPE_NFIELDS (type) == 1
08615           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
08616 }
08617 
08618 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
08619    the parallel type.  */
08620 
08621 struct type *
08622 ada_get_base_type (struct type *raw_type)
08623 {
08624   struct type *real_type_namer;
08625   struct type *raw_real_type;
08626 
08627   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
08628     return raw_type;
08629 
08630   if (ada_is_aligner_type (raw_type))
08631     /* The encoding specifies that we should always use the aligner type.
08632        So, even if this aligner type has an associated XVS type, we should
08633        simply ignore it.
08634 
08635        According to the compiler gurus, an XVS type parallel to an aligner
08636        type may exist because of a stabs limitation.  In stabs, aligner
08637        types are empty because the field has a variable-sized type, and
08638        thus cannot actually be used as an aligner type.  As a result,
08639        we need the associated parallel XVS type to decode the type.
08640        Since the policy in the compiler is to not change the internal
08641        representation based on the debugging info format, we sometimes
08642        end up having a redundant XVS type parallel to the aligner type.  */
08643     return raw_type;
08644 
08645   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
08646   if (real_type_namer == NULL
08647       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
08648       || TYPE_NFIELDS (real_type_namer) != 1)
08649     return raw_type;
08650 
08651   if (TYPE_CODE (TYPE_FIELD_TYPE (real_type_namer, 0)) != TYPE_CODE_REF)
08652     {
08653       /* This is an older encoding form where the base type needs to be
08654          looked up by name.  We prefer the newer enconding because it is
08655          more efficient.  */
08656       raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
08657       if (raw_real_type == NULL)
08658         return raw_type;
08659       else
08660         return raw_real_type;
08661     }
08662 
08663   /* The field in our XVS type is a reference to the base type.  */
08664   return TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (real_type_namer, 0));
08665 }
08666 
08667 /* The type of value designated by TYPE, with all aligners removed.  */
08668 
08669 struct type *
08670 ada_aligned_type (struct type *type)
08671 {
08672   if (ada_is_aligner_type (type))
08673     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
08674   else
08675     return ada_get_base_type (type);
08676 }
08677 
08678 
08679 /* The address of the aligned value in an object at address VALADDR
08680    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
08681 
08682 const gdb_byte *
08683 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
08684 {
08685   if (ada_is_aligner_type (type))
08686     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
08687                                    valaddr +
08688                                    TYPE_FIELD_BITPOS (type,
08689                                                       0) / TARGET_CHAR_BIT);
08690   else
08691     return valaddr;
08692 }
08693 
08694 
08695 
08696 /* The printed representation of an enumeration literal with encoded
08697    name NAME.  The value is good to the next call of ada_enum_name.  */
08698 const char *
08699 ada_enum_name (const char *name)
08700 {
08701   static char *result;
08702   static size_t result_len = 0;
08703   char *tmp;
08704 
08705   /* First, unqualify the enumeration name:
08706      1. Search for the last '.' character.  If we find one, then skip
08707      all the preceding characters, the unqualified name starts
08708      right after that dot.
08709      2. Otherwise, we may be debugging on a target where the compiler
08710      translates dots into "__".  Search forward for double underscores,
08711      but stop searching when we hit an overloading suffix, which is
08712      of the form "__" followed by digits.  */
08713 
08714   tmp = strrchr (name, '.');
08715   if (tmp != NULL)
08716     name = tmp + 1;
08717   else
08718     {
08719       while ((tmp = strstr (name, "__")) != NULL)
08720         {
08721           if (isdigit (tmp[2]))
08722             break;
08723           else
08724             name = tmp + 2;
08725         }
08726     }
08727 
08728   if (name[0] == 'Q')
08729     {
08730       int v;
08731 
08732       if (name[1] == 'U' || name[1] == 'W')
08733         {
08734           if (sscanf (name + 2, "%x", &v) != 1)
08735             return name;
08736         }
08737       else
08738         return name;
08739 
08740       GROW_VECT (result, result_len, 16);
08741       if (isascii (v) && isprint (v))
08742         xsnprintf (result, result_len, "'%c'", v);
08743       else if (name[1] == 'U')
08744         xsnprintf (result, result_len, "[\"%02x\"]", v);
08745       else
08746         xsnprintf (result, result_len, "[\"%04x\"]", v);
08747 
08748       return result;
08749     }
08750   else
08751     {
08752       tmp = strstr (name, "__");
08753       if (tmp == NULL)
08754         tmp = strstr (name, "$");
08755       if (tmp != NULL)
08756         {
08757           GROW_VECT (result, result_len, tmp - name + 1);
08758           strncpy (result, name, tmp - name);
08759           result[tmp - name] = '\0';
08760           return result;
08761         }
08762 
08763       return name;
08764     }
08765 }
08766 
08767 /* Evaluate the subexpression of EXP starting at *POS as for
08768    evaluate_type, updating *POS to point just past the evaluated
08769    expression.  */
08770 
08771 static struct value *
08772 evaluate_subexp_type (struct expression *exp, int *pos)
08773 {
08774   return evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
08775 }
08776 
08777 /* If VAL is wrapped in an aligner or subtype wrapper, return the
08778    value it wraps.  */
08779 
08780 static struct value *
08781 unwrap_value (struct value *val)
08782 {
08783   struct type *type = ada_check_typedef (value_type (val));
08784 
08785   if (ada_is_aligner_type (type))
08786     {
08787       struct value *v = ada_value_struct_elt (val, "F", 0);
08788       struct type *val_type = ada_check_typedef (value_type (v));
08789 
08790       if (ada_type_name (val_type) == NULL)
08791         TYPE_NAME (val_type) = ada_type_name (type);
08792 
08793       return unwrap_value (v);
08794     }
08795   else
08796     {
08797       struct type *raw_real_type =
08798         ada_check_typedef (ada_get_base_type (type));
08799 
08800       /* If there is no parallel XVS or XVE type, then the value is
08801          already unwrapped.  Return it without further modification.  */
08802       if ((type == raw_real_type)
08803           && ada_find_parallel_type (type, "___XVE") == NULL)
08804         return val;
08805 
08806       return
08807         coerce_unspec_val_to_type
08808         (val, ada_to_fixed_type (raw_real_type, 0,
08809                                  value_address (val),
08810                                  NULL, 1));
08811     }
08812 }
08813 
08814 static struct value *
08815 cast_to_fixed (struct type *type, struct value *arg)
08816 {
08817   LONGEST val;
08818 
08819   if (type == value_type (arg))
08820     return arg;
08821   else if (ada_is_fixed_point_type (value_type (arg)))
08822     val = ada_float_to_fixed (type,
08823                               ada_fixed_to_float (value_type (arg),
08824                                                   value_as_long (arg)));
08825   else
08826     {
08827       DOUBLEST argd = value_as_double (arg);
08828 
08829       val = ada_float_to_fixed (type, argd);
08830     }
08831 
08832   return value_from_longest (type, val);
08833 }
08834 
08835 static struct value *
08836 cast_from_fixed (struct type *type, struct value *arg)
08837 {
08838   DOUBLEST val = ada_fixed_to_float (value_type (arg),
08839                                      value_as_long (arg));
08840 
08841   return value_from_double (type, val);
08842 }
08843 
08844 /* Given two array types T1 and T2, return nonzero iff both arrays
08845    contain the same number of elements.  */
08846 
08847 static int
08848 ada_same_array_size_p (struct type *t1, struct type *t2)
08849 {
08850   LONGEST lo1, hi1, lo2, hi2;
08851 
08852   /* Get the array bounds in order to verify that the size of
08853      the two arrays match.  */
08854   if (!get_array_bounds (t1, &lo1, &hi1)
08855       || !get_array_bounds (t2, &lo2, &hi2))
08856     error (_("unable to determine array bounds"));
08857 
08858   /* To make things easier for size comparison, normalize a bit
08859      the case of empty arrays by making sure that the difference
08860      between upper bound and lower bound is always -1.  */
08861   if (lo1 > hi1)
08862     hi1 = lo1 - 1;
08863   if (lo2 > hi2)
08864     hi2 = lo2 - 1;
08865 
08866   return (hi1 - lo1 == hi2 - lo2);
08867 }
08868 
08869 /* Assuming that VAL is an array of integrals, and TYPE represents
08870    an array with the same number of elements, but with wider integral
08871    elements, return an array "casted" to TYPE.  In practice, this
08872    means that the returned array is built by casting each element
08873    of the original array into TYPE's (wider) element type.  */
08874 
08875 static struct value *
08876 ada_promote_array_of_integrals (struct type *type, struct value *val)
08877 {
08878   struct type *elt_type = TYPE_TARGET_TYPE (type);
08879   LONGEST lo, hi;
08880   struct value *res;
08881   LONGEST i;
08882 
08883   /* Verify that both val and type are arrays of scalars, and
08884      that the size of val's elements is smaller than the size
08885      of type's element.  */
08886   gdb_assert (TYPE_CODE (type) == TYPE_CODE_ARRAY);
08887   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (type)));
08888   gdb_assert (TYPE_CODE (value_type (val)) == TYPE_CODE_ARRAY);
08889   gdb_assert (is_integral_type (TYPE_TARGET_TYPE (value_type (val))));
08890   gdb_assert (TYPE_LENGTH (TYPE_TARGET_TYPE (type))
08891               > TYPE_LENGTH (TYPE_TARGET_TYPE (value_type (val))));
08892 
08893   if (!get_array_bounds (type, &lo, &hi))
08894     error (_("unable to determine array bounds"));
08895 
08896   res = allocate_value (type);
08897 
08898   /* Promote each array element.  */
08899   for (i = 0; i < hi - lo + 1; i++)
08900     {
08901       struct value *elt = value_cast (elt_type, value_subscript (val, lo + i));
08902 
08903       memcpy (value_contents_writeable (res) + (i * TYPE_LENGTH (elt_type)),
08904               value_contents_all (elt), TYPE_LENGTH (elt_type));
08905     }
08906 
08907   return res;
08908 }
08909 
08910 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
08911    return the converted value.  */
08912 
08913 static struct value *
08914 coerce_for_assign (struct type *type, struct value *val)
08915 {
08916   struct type *type2 = value_type (val);
08917 
08918   if (type == type2)
08919     return val;
08920 
08921   type2 = ada_check_typedef (type2);
08922   type = ada_check_typedef (type);
08923 
08924   if (TYPE_CODE (type2) == TYPE_CODE_PTR
08925       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
08926     {
08927       val = ada_value_ind (val);
08928       type2 = value_type (val);
08929     }
08930 
08931   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
08932       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
08933     {
08934       if (!ada_same_array_size_p (type, type2))
08935         error (_("cannot assign arrays of different length"));
08936 
08937       if (is_integral_type (TYPE_TARGET_TYPE (type))
08938           && is_integral_type (TYPE_TARGET_TYPE (type2))
08939           && TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
08940                < TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
08941         {
08942           /* Allow implicit promotion of the array elements to
08943              a wider type.  */
08944           return ada_promote_array_of_integrals (type, val);
08945         }
08946 
08947       if (TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
08948           != TYPE_LENGTH (TYPE_TARGET_TYPE (type)))
08949         error (_("Incompatible types in assignment"));
08950       deprecated_set_value_type (val, type);
08951     }
08952   return val;
08953 }
08954 
08955 static struct value *
08956 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
08957 {
08958   struct value *val;
08959   struct type *type1, *type2;
08960   LONGEST v, v1, v2;
08961 
08962   arg1 = coerce_ref (arg1);
08963   arg2 = coerce_ref (arg2);
08964   type1 = get_base_type (ada_check_typedef (value_type (arg1)));
08965   type2 = get_base_type (ada_check_typedef (value_type (arg2)));
08966 
08967   if (TYPE_CODE (type1) != TYPE_CODE_INT
08968       || TYPE_CODE (type2) != TYPE_CODE_INT)
08969     return value_binop (arg1, arg2, op);
08970 
08971   switch (op)
08972     {
08973     case BINOP_MOD:
08974     case BINOP_DIV:
08975     case BINOP_REM:
08976       break;
08977     default:
08978       return value_binop (arg1, arg2, op);
08979     }
08980 
08981   v2 = value_as_long (arg2);
08982   if (v2 == 0)
08983     error (_("second operand of %s must not be zero."), op_string (op));
08984 
08985   if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
08986     return value_binop (arg1, arg2, op);
08987 
08988   v1 = value_as_long (arg1);
08989   switch (op)
08990     {
08991     case BINOP_DIV:
08992       v = v1 / v2;
08993       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
08994         v += v > 0 ? -1 : 1;
08995       break;
08996     case BINOP_REM:
08997       v = v1 % v2;
08998       if (v * v1 < 0)
08999         v -= v2;
09000       break;
09001     default:
09002       /* Should not reach this point.  */
09003       v = 0;
09004     }
09005 
09006   val = allocate_value (type1);
09007   store_unsigned_integer (value_contents_raw (val),
09008                           TYPE_LENGTH (value_type (val)),
09009                           gdbarch_byte_order (get_type_arch (type1)), v);
09010   return val;
09011 }
09012 
09013 static int
09014 ada_value_equal (struct value *arg1, struct value *arg2)
09015 {
09016   if (ada_is_direct_array_type (value_type (arg1))
09017       || ada_is_direct_array_type (value_type (arg2)))
09018     {
09019       /* Automatically dereference any array reference before
09020          we attempt to perform the comparison.  */
09021       arg1 = ada_coerce_ref (arg1);
09022       arg2 = ada_coerce_ref (arg2);
09023       
09024       arg1 = ada_coerce_to_simple_array (arg1);
09025       arg2 = ada_coerce_to_simple_array (arg2);
09026       if (TYPE_CODE (value_type (arg1)) != TYPE_CODE_ARRAY
09027           || TYPE_CODE (value_type (arg2)) != TYPE_CODE_ARRAY)
09028         error (_("Attempt to compare array with non-array"));
09029       /* FIXME: The following works only for types whose
09030          representations use all bits (no padding or undefined bits)
09031          and do not have user-defined equality.  */
09032       return
09033         TYPE_LENGTH (value_type (arg1)) == TYPE_LENGTH (value_type (arg2))
09034         && memcmp (value_contents (arg1), value_contents (arg2),
09035                    TYPE_LENGTH (value_type (arg1))) == 0;
09036     }
09037   return value_equal (arg1, arg2);
09038 }
09039 
09040 /* Total number of component associations in the aggregate starting at
09041    index PC in EXP.  Assumes that index PC is the start of an
09042    OP_AGGREGATE.  */
09043 
09044 static int
09045 num_component_specs (struct expression *exp, int pc)
09046 {
09047   int n, m, i;
09048 
09049   m = exp->elts[pc + 1].longconst;
09050   pc += 3;
09051   n = 0;
09052   for (i = 0; i < m; i += 1)
09053     {
09054       switch (exp->elts[pc].opcode) 
09055         {
09056         default:
09057           n += 1;
09058           break;
09059         case OP_CHOICES:
09060           n += exp->elts[pc + 1].longconst;
09061           break;
09062         }
09063       ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
09064     }
09065   return n;
09066 }
09067 
09068 /* Assign the result of evaluating EXP starting at *POS to the INDEXth 
09069    component of LHS (a simple array or a record), updating *POS past
09070    the expression, assuming that LHS is contained in CONTAINER.  Does
09071    not modify the inferior's memory, nor does it modify LHS (unless
09072    LHS == CONTAINER).  */
09073 
09074 static void
09075 assign_component (struct value *container, struct value *lhs, LONGEST index,
09076                   struct expression *exp, int *pos)
09077 {
09078   struct value *mark = value_mark ();
09079   struct value *elt;
09080 
09081   if (TYPE_CODE (value_type (lhs)) == TYPE_CODE_ARRAY)
09082     {
09083       struct type *index_type = builtin_type (exp->gdbarch)->builtin_int;
09084       struct value *index_val = value_from_longest (index_type, index);
09085 
09086       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
09087     }
09088   else
09089     {
09090       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
09091       elt = ada_to_fixed_value (elt);
09092     }
09093 
09094   if (exp->elts[*pos].opcode == OP_AGGREGATE)
09095     assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
09096   else
09097     value_assign_to_component (container, elt, 
09098                                ada_evaluate_subexp (NULL, exp, pos, 
09099                                                     EVAL_NORMAL));
09100 
09101   value_free_to_mark (mark);
09102 }
09103 
09104 /* Assuming that LHS represents an lvalue having a record or array
09105    type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
09106    of that aggregate's value to LHS, advancing *POS past the
09107    aggregate.  NOSIDE is as for evaluate_subexp.  CONTAINER is an
09108    lvalue containing LHS (possibly LHS itself).  Does not modify
09109    the inferior's memory, nor does it modify the contents of 
09110    LHS (unless == CONTAINER).  Returns the modified CONTAINER.  */
09111 
09112 static struct value *
09113 assign_aggregate (struct value *container, 
09114                   struct value *lhs, struct expression *exp, 
09115                   int *pos, enum noside noside)
09116 {
09117   struct type *lhs_type;
09118   int n = exp->elts[*pos+1].longconst;
09119   LONGEST low_index, high_index;
09120   int num_specs;
09121   LONGEST *indices;
09122   int max_indices, num_indices;
09123   int i;
09124 
09125   *pos += 3;
09126   if (noside != EVAL_NORMAL)
09127     {
09128       for (i = 0; i < n; i += 1)
09129         ada_evaluate_subexp (NULL, exp, pos, noside);
09130       return container;
09131     }
09132 
09133   container = ada_coerce_ref (container);
09134   if (ada_is_direct_array_type (value_type (container)))
09135     container = ada_coerce_to_simple_array (container);
09136   lhs = ada_coerce_ref (lhs);
09137   if (!deprecated_value_modifiable (lhs))
09138     error (_("Left operand of assignment is not a modifiable lvalue."));
09139 
09140   lhs_type = value_type (lhs);
09141   if (ada_is_direct_array_type (lhs_type))
09142     {
09143       lhs = ada_coerce_to_simple_array (lhs);
09144       lhs_type = value_type (lhs);
09145       low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
09146       high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
09147     }
09148   else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
09149     {
09150       low_index = 0;
09151       high_index = num_visible_fields (lhs_type) - 1;
09152     }
09153   else
09154     error (_("Left-hand side must be array or record."));
09155 
09156   num_specs = num_component_specs (exp, *pos - 3);
09157   max_indices = 4 * num_specs + 4;
09158   indices = alloca (max_indices * sizeof (indices[0]));
09159   indices[0] = indices[1] = low_index - 1;
09160   indices[2] = indices[3] = high_index + 1;
09161   num_indices = 4;
09162 
09163   for (i = 0; i < n; i += 1)
09164     {
09165       switch (exp->elts[*pos].opcode)
09166         {
09167           case OP_CHOICES:
09168             aggregate_assign_from_choices (container, lhs, exp, pos, indices, 
09169                                            &num_indices, max_indices,
09170                                            low_index, high_index);
09171             break;
09172           case OP_POSITIONAL:
09173             aggregate_assign_positional (container, lhs, exp, pos, indices,
09174                                          &num_indices, max_indices,
09175                                          low_index, high_index);
09176             break;
09177           case OP_OTHERS:
09178             if (i != n-1)
09179               error (_("Misplaced 'others' clause"));
09180             aggregate_assign_others (container, lhs, exp, pos, indices, 
09181                                      num_indices, low_index, high_index);
09182             break;
09183           default:
09184             error (_("Internal error: bad aggregate clause"));
09185         }
09186     }
09187 
09188   return container;
09189 }
09190               
09191 /* Assign into the component of LHS indexed by the OP_POSITIONAL
09192    construct at *POS, updating *POS past the construct, given that
09193    the positions are relative to lower bound LOW, where HIGH is the 
09194    upper bound.  Record the position in INDICES[0 .. MAX_INDICES-1]
09195    updating *NUM_INDICES as needed.  CONTAINER is as for
09196    assign_aggregate.  */
09197 static void
09198 aggregate_assign_positional (struct value *container,
09199                              struct value *lhs, struct expression *exp,
09200                              int *pos, LONGEST *indices, int *num_indices,
09201                              int max_indices, LONGEST low, LONGEST high) 
09202 {
09203   LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
09204   
09205   if (ind - 1 == high)
09206     warning (_("Extra components in aggregate ignored."));
09207   if (ind <= high)
09208     {
09209       add_component_interval (ind, ind, indices, num_indices, max_indices);
09210       *pos += 3;
09211       assign_component (container, lhs, ind, exp, pos);
09212     }
09213   else
09214     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
09215 }
09216 
09217 /* Assign into the components of LHS indexed by the OP_CHOICES
09218    construct at *POS, updating *POS past the construct, given that
09219    the allowable indices are LOW..HIGH.  Record the indices assigned
09220    to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
09221    needed.  CONTAINER is as for assign_aggregate.  */
09222 static void
09223 aggregate_assign_from_choices (struct value *container,
09224                                struct value *lhs, struct expression *exp,
09225                                int *pos, LONGEST *indices, int *num_indices,
09226                                int max_indices, LONGEST low, LONGEST high) 
09227 {
09228   int j;
09229   int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
09230   int choice_pos, expr_pc;
09231   int is_array = ada_is_direct_array_type (value_type (lhs));
09232 
09233   choice_pos = *pos += 3;
09234 
09235   for (j = 0; j < n_choices; j += 1)
09236     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
09237   expr_pc = *pos;
09238   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
09239   
09240   for (j = 0; j < n_choices; j += 1)
09241     {
09242       LONGEST lower, upper;
09243       enum exp_opcode op = exp->elts[choice_pos].opcode;
09244 
09245       if (op == OP_DISCRETE_RANGE)
09246         {
09247           choice_pos += 1;
09248           lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
09249                                                       EVAL_NORMAL));
09250           upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos, 
09251                                                       EVAL_NORMAL));
09252         }
09253       else if (is_array)
09254         {
09255           lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos, 
09256                                                       EVAL_NORMAL));
09257           upper = lower;
09258         }
09259       else
09260         {
09261           int ind;
09262           const char *name;
09263 
09264           switch (op)
09265             {
09266             case OP_NAME:
09267               name = &exp->elts[choice_pos + 2].string;
09268               break;
09269             case OP_VAR_VALUE:
09270               name = SYMBOL_NATURAL_NAME (exp->elts[choice_pos + 2].symbol);
09271               break;
09272             default:
09273               error (_("Invalid record component association."));
09274             }
09275           ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
09276           ind = 0;
09277           if (! find_struct_field (name, value_type (lhs), 0, 
09278                                    NULL, NULL, NULL, NULL, &ind))
09279             error (_("Unknown component name: %s."), name);
09280           lower = upper = ind;
09281         }
09282 
09283       if (lower <= upper && (lower < low || upper > high))
09284         error (_("Index in component association out of bounds."));
09285 
09286       add_component_interval (lower, upper, indices, num_indices,
09287                               max_indices);
09288       while (lower <= upper)
09289         {
09290           int pos1;
09291 
09292           pos1 = expr_pc;
09293           assign_component (container, lhs, lower, exp, &pos1);
09294           lower += 1;
09295         }
09296     }
09297 }
09298 
09299 /* Assign the value of the expression in the OP_OTHERS construct in
09300    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
09301    have not been previously assigned.  The index intervals already assigned
09302    are in INDICES[0 .. NUM_INDICES-1].  Updates *POS to after the 
09303    OP_OTHERS clause.  CONTAINER is as for assign_aggregate.  */
09304 static void
09305 aggregate_assign_others (struct value *container,
09306                          struct value *lhs, struct expression *exp,
09307                          int *pos, LONGEST *indices, int num_indices,
09308                          LONGEST low, LONGEST high) 
09309 {
09310   int i;
09311   int expr_pc = *pos + 1;
09312   
09313   for (i = 0; i < num_indices - 2; i += 2)
09314     {
09315       LONGEST ind;
09316 
09317       for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
09318         {
09319           int localpos;
09320 
09321           localpos = expr_pc;
09322           assign_component (container, lhs, ind, exp, &localpos);
09323         }
09324     }
09325   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
09326 }
09327 
09328 /* Add the interval [LOW .. HIGH] to the sorted set of intervals 
09329    [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
09330    modifying *SIZE as needed.  It is an error if *SIZE exceeds
09331    MAX_SIZE.  The resulting intervals do not overlap.  */
09332 static void
09333 add_component_interval (LONGEST low, LONGEST high, 
09334                         LONGEST* indices, int *size, int max_size)
09335 {
09336   int i, j;
09337 
09338   for (i = 0; i < *size; i += 2) {
09339     if (high >= indices[i] && low <= indices[i + 1])
09340       {
09341         int kh;
09342 
09343         for (kh = i + 2; kh < *size; kh += 2)
09344           if (high < indices[kh])
09345             break;
09346         if (low < indices[i])
09347           indices[i] = low;
09348         indices[i + 1] = indices[kh - 1];
09349         if (high > indices[i + 1])
09350           indices[i + 1] = high;
09351         memcpy (indices + i + 2, indices + kh, *size - kh);
09352         *size -= kh - i - 2;
09353         return;
09354       }
09355     else if (high < indices[i])
09356       break;
09357   }
09358         
09359   if (*size == max_size)
09360     error (_("Internal error: miscounted aggregate components."));
09361   *size += 2;
09362   for (j = *size-1; j >= i+2; j -= 1)
09363     indices[j] = indices[j - 2];
09364   indices[i] = low;
09365   indices[i + 1] = high;
09366 }
09367 
09368 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
09369    is different.  */
09370 
09371 static struct value *
09372 ada_value_cast (struct type *type, struct value *arg2, enum noside noside)
09373 {
09374   if (type == ada_check_typedef (value_type (arg2)))
09375     return arg2;
09376 
09377   if (ada_is_fixed_point_type (type))
09378     return (cast_to_fixed (type, arg2));
09379 
09380   if (ada_is_fixed_point_type (value_type (arg2)))
09381     return cast_from_fixed (type, arg2);
09382 
09383   return value_cast (type, arg2);
09384 }
09385 
09386 /*  Evaluating Ada expressions, and printing their result.
09387     ------------------------------------------------------
09388 
09389     1. Introduction:
09390     ----------------
09391 
09392     We usually evaluate an Ada expression in order to print its value.
09393     We also evaluate an expression in order to print its type, which
09394     happens during the EVAL_AVOID_SIDE_EFFECTS phase of the evaluation,
09395     but we'll focus mostly on the EVAL_NORMAL phase.  In practice, the
09396     EVAL_AVOID_SIDE_EFFECTS phase allows us to simplify certain aspects of
09397     the evaluation compared to the EVAL_NORMAL, but is otherwise very
09398     similar.
09399 
09400     Evaluating expressions is a little more complicated for Ada entities
09401     than it is for entities in languages such as C.  The main reason for
09402     this is that Ada provides types whose definition might be dynamic.
09403     One example of such types is variant records.  Or another example
09404     would be an array whose bounds can only be known at run time.
09405 
09406     The following description is a general guide as to what should be
09407     done (and what should NOT be done) in order to evaluate an expression
09408     involving such types, and when.  This does not cover how the semantic
09409     information is encoded by GNAT as this is covered separatly.  For the
09410     document used as the reference for the GNAT encoding, see exp_dbug.ads
09411     in the GNAT sources.
09412 
09413     Ideally, we should embed each part of this description next to its
09414     associated code.  Unfortunately, the amount of code is so vast right
09415     now that it's hard to see whether the code handling a particular
09416     situation might be duplicated or not.  One day, when the code is
09417     cleaned up, this guide might become redundant with the comments
09418     inserted in the code, and we might want to remove it.
09419 
09420     2. ``Fixing'' an Entity, the Simple Case:
09421     -----------------------------------------
09422 
09423     When evaluating Ada expressions, the tricky issue is that they may
09424     reference entities whose type contents and size are not statically
09425     known.  Consider for instance a variant record:
09426 
09427        type Rec (Empty : Boolean := True) is record
09428           case Empty is
09429              when True => null;
09430              when False => Value : Integer;
09431           end case;
09432        end record;
09433        Yes : Rec := (Empty => False, Value => 1);
09434        No  : Rec := (empty => True);
09435 
09436     The size and contents of that record depends on the value of the
09437     descriminant (Rec.Empty).  At this point, neither the debugging
09438     information nor the associated type structure in GDB are able to
09439     express such dynamic types.  So what the debugger does is to create
09440     "fixed" versions of the type that applies to the specific object.
09441     We also informally refer to this opperation as "fixing" an object,
09442     which means creating its associated fixed type.
09443 
09444     Example: when printing the value of variable "Yes" above, its fixed
09445     type would look like this:
09446 
09447        type Rec is record
09448           Empty : Boolean;
09449           Value : Integer;
09450        end record;
09451 
09452     On the other hand, if we printed the value of "No", its fixed type
09453     would become:
09454 
09455        type Rec is record
09456           Empty : Boolean;
09457        end record;
09458 
09459     Things become a little more complicated when trying to fix an entity
09460     with a dynamic type that directly contains another dynamic type,
09461     such as an array of variant records, for instance.  There are
09462     two possible cases: Arrays, and records.
09463 
09464     3. ``Fixing'' Arrays:
09465     ---------------------
09466 
09467     The type structure in GDB describes an array in terms of its bounds,
09468     and the type of its elements.  By design, all elements in the array
09469     have the same type and we cannot represent an array of variant elements
09470     using the current type structure in GDB.  When fixing an array,
09471     we cannot fix the array element, as we would potentially need one
09472     fixed type per element of the array.  As a result, the best we can do
09473     when fixing an array is to produce an array whose bounds and size
09474     are correct (allowing us to read it from memory), but without having
09475     touched its element type.  Fixing each element will be done later,
09476     when (if) necessary.
09477 
09478     Arrays are a little simpler to handle than records, because the same
09479     amount of memory is allocated for each element of the array, even if
09480     the amount of space actually used by each element differs from element
09481     to element.  Consider for instance the following array of type Rec:
09482 
09483        type Rec_Array is array (1 .. 2) of Rec;
09484 
09485     The actual amount of memory occupied by each element might be different
09486     from element to element, depending on the value of their discriminant.
09487     But the amount of space reserved for each element in the array remains
09488     fixed regardless.  So we simply need to compute that size using
09489     the debugging information available, from which we can then determine
09490     the array size (we multiply the number of elements of the array by
09491     the size of each element).
09492 
09493     The simplest case is when we have an array of a constrained element
09494     type. For instance, consider the following type declarations:
09495 
09496         type Bounded_String (Max_Size : Integer) is
09497            Length : Integer;
09498            Buffer : String (1 .. Max_Size);
09499         end record;
09500         type Bounded_String_Array is array (1 ..2) of Bounded_String (80);
09501 
09502     In this case, the compiler describes the array as an array of
09503     variable-size elements (identified by its XVS suffix) for which
09504     the size can be read in the parallel XVZ variable.
09505 
09506     In the case of an array of an unconstrained element type, the compiler
09507     wraps the array element inside a private PAD type.  This type should not
09508     be shown to the user, and must be "unwrap"'ed before printing.  Note
09509     that we also use the adjective "aligner" in our code to designate
09510     these wrapper types.
09511 
09512     In some cases, the size allocated for each element is statically
09513     known.  In that case, the PAD type already has the correct size,
09514     and the array element should remain unfixed.
09515 
09516     But there are cases when this size is not statically known.
09517     For instance, assuming that "Five" is an integer variable:
09518 
09519         type Dynamic is array (1 .. Five) of Integer;
09520         type Wrapper (Has_Length : Boolean := False) is record
09521            Data : Dynamic;
09522            case Has_Length is
09523               when True => Length : Integer;
09524               when False => null;
09525            end case;
09526         end record;
09527         type Wrapper_Array is array (1 .. 2) of Wrapper;
09528 
09529         Hello : Wrapper_Array := (others => (Has_Length => True,
09530                                              Data => (others => 17),
09531                                              Length => 1));
09532 
09533 
09534     The debugging info would describe variable Hello as being an
09535     array of a PAD type.  The size of that PAD type is not statically
09536     known, but can be determined using a parallel XVZ variable.
09537     In that case, a copy of the PAD type with the correct size should
09538     be used for the fixed array.
09539 
09540     3. ``Fixing'' record type objects:
09541     ----------------------------------
09542 
09543     Things are slightly different from arrays in the case of dynamic
09544     record types.  In this case, in order to compute the associated
09545     fixed type, we need to determine the size and offset of each of
09546     its components.  This, in turn, requires us to compute the fixed
09547     type of each of these components.
09548 
09549     Consider for instance the example:
09550 
09551         type Bounded_String (Max_Size : Natural) is record
09552            Str : String (1 .. Max_Size);
09553            Length : Natural;
09554         end record;
09555         My_String : Bounded_String (Max_Size => 10);
09556 
09557     In that case, the position of field "Length" depends on the size
09558     of field Str, which itself depends on the value of the Max_Size
09559     discriminant.  In order to fix the type of variable My_String,
09560     we need to fix the type of field Str.  Therefore, fixing a variant
09561     record requires us to fix each of its components.
09562 
09563     However, if a component does not have a dynamic size, the component
09564     should not be fixed.  In particular, fields that use a PAD type
09565     should not fixed.  Here is an example where this might happen
09566     (assuming type Rec above):
09567 
09568        type Container (Big : Boolean) is record
09569           First : Rec;
09570           After : Integer;
09571           case Big is
09572              when True => Another : Integer;
09573              when False => null;
09574           end case;
09575        end record;
09576        My_Container : Container := (Big => False,
09577                                     First => (Empty => True),
09578                                     After => 42);
09579 
09580     In that example, the compiler creates a PAD type for component First,
09581     whose size is constant, and then positions the component After just
09582     right after it.  The offset of component After is therefore constant
09583     in this case.
09584 
09585     The debugger computes the position of each field based on an algorithm
09586     that uses, among other things, the actual position and size of the field
09587     preceding it.  Let's now imagine that the user is trying to print
09588     the value of My_Container.  If the type fixing was recursive, we would
09589     end up computing the offset of field After based on the size of the
09590     fixed version of field First.  And since in our example First has
09591     only one actual field, the size of the fixed type is actually smaller
09592     than the amount of space allocated to that field, and thus we would
09593     compute the wrong offset of field After.
09594 
09595     To make things more complicated, we need to watch out for dynamic
09596     components of variant records (identified by the ___XVL suffix in
09597     the component name).  Even if the target type is a PAD type, the size
09598     of that type might not be statically known.  So the PAD type needs
09599     to be unwrapped and the resulting type needs to be fixed.  Otherwise,
09600     we might end up with the wrong size for our component.  This can be
09601     observed with the following type declarations:
09602 
09603         type Octal is new Integer range 0 .. 7;
09604         type Octal_Array is array (Positive range <>) of Octal;
09605         pragma Pack (Octal_Array);
09606 
09607         type Octal_Buffer (Size : Positive) is record
09608            Buffer : Octal_Array (1 .. Size);
09609            Length : Integer;
09610         end record;
09611 
09612     In that case, Buffer is a PAD type whose size is unset and needs
09613     to be computed by fixing the unwrapped type.
09614 
09615     4. When to ``Fix'' un-``Fixed'' sub-elements of an entity:
09616     ----------------------------------------------------------
09617 
09618     Lastly, when should the sub-elements of an entity that remained unfixed
09619     thus far, be actually fixed?
09620 
09621     The answer is: Only when referencing that element.  For instance
09622     when selecting one component of a record, this specific component
09623     should be fixed at that point in time.  Or when printing the value
09624     of a record, each component should be fixed before its value gets
09625     printed.  Similarly for arrays, the element of the array should be
09626     fixed when printing each element of the array, or when extracting
09627     one element out of that array.  On the other hand, fixing should
09628     not be performed on the elements when taking a slice of an array!
09629 
09630     Note that one of the side-effects of miscomputing the offset and
09631     size of each field is that we end up also miscomputing the size
09632     of the containing type.  This can have adverse results when computing
09633     the value of an entity.  GDB fetches the value of an entity based
09634     on the size of its type, and thus a wrong size causes GDB to fetch
09635     the wrong amount of memory.  In the case where the computed size is
09636     too small, GDB fetches too little data to print the value of our
09637     entiry.  Results in this case as unpredicatble, as we usually read
09638     past the buffer containing the data =:-o.  */
09639 
09640 /* Implement the evaluate_exp routine in the exp_descriptor structure
09641    for the Ada language.  */
09642 
09643 static struct value *
09644 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
09645                      int *pos, enum noside noside)
09646 {
09647   enum exp_opcode op;
09648   int tem;
09649   int pc;
09650   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
09651   struct type *type;
09652   int nargs, oplen;
09653   struct value **argvec;
09654 
09655   pc = *pos;
09656   *pos += 1;
09657   op = exp->elts[pc].opcode;
09658 
09659   switch (op)
09660     {
09661     default:
09662       *pos -= 1;
09663       arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
09664 
09665       if (noside == EVAL_NORMAL)
09666         arg1 = unwrap_value (arg1);
09667 
09668       /* If evaluating an OP_DOUBLE and an EXPECT_TYPE was provided,
09669          then we need to perform the conversion manually, because
09670          evaluate_subexp_standard doesn't do it.  This conversion is
09671          necessary in Ada because the different kinds of float/fixed
09672          types in Ada have different representations.
09673 
09674          Similarly, we need to perform the conversion from OP_LONG
09675          ourselves.  */
09676       if ((op == OP_DOUBLE || op == OP_LONG) && expect_type != NULL)
09677         arg1 = ada_value_cast (expect_type, arg1, noside);
09678 
09679       return arg1;
09680 
09681     case OP_STRING:
09682       {
09683         struct value *result;
09684 
09685         *pos -= 1;
09686         result = evaluate_subexp_standard (expect_type, exp, pos, noside);
09687         /* The result type will have code OP_STRING, bashed there from 
09688            OP_ARRAY.  Bash it back.  */
09689         if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
09690           TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
09691         return result;
09692       }
09693 
09694     case UNOP_CAST:
09695       (*pos) += 2;
09696       type = exp->elts[pc + 1].type;
09697       arg1 = evaluate_subexp (type, exp, pos, noside);
09698       if (noside == EVAL_SKIP)
09699         goto nosideret;
09700       arg1 = ada_value_cast (type, arg1, noside);
09701       return arg1;
09702 
09703     case UNOP_QUAL:
09704       (*pos) += 2;
09705       type = exp->elts[pc + 1].type;
09706       return ada_evaluate_subexp (type, exp, pos, noside);
09707 
09708     case BINOP_ASSIGN:
09709       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09710       if (exp->elts[*pos].opcode == OP_AGGREGATE)
09711         {
09712           arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
09713           if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
09714             return arg1;
09715           return ada_value_assign (arg1, arg1);
09716         }
09717       /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
09718          except if the lhs of our assignment is a convenience variable.
09719          In the case of assigning to a convenience variable, the lhs
09720          should be exactly the result of the evaluation of the rhs.  */
09721       type = value_type (arg1);
09722       if (VALUE_LVAL (arg1) == lval_internalvar)
09723          type = NULL;
09724       arg2 = evaluate_subexp (type, exp, pos, noside);
09725       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
09726         return arg1;
09727       if (ada_is_fixed_point_type (value_type (arg1)))
09728         arg2 = cast_to_fixed (value_type (arg1), arg2);
09729       else if (ada_is_fixed_point_type (value_type (arg2)))
09730         error
09731           (_("Fixed-point values must be assigned to fixed-point variables"));
09732       else
09733         arg2 = coerce_for_assign (value_type (arg1), arg2);
09734       return ada_value_assign (arg1, arg2);
09735 
09736     case BINOP_ADD:
09737       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
09738       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
09739       if (noside == EVAL_SKIP)
09740         goto nosideret;
09741       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
09742         return (value_from_longest
09743                  (value_type (arg1),
09744                   value_as_long (arg1) + value_as_long (arg2)));
09745       if ((ada_is_fixed_point_type (value_type (arg1))
09746            || ada_is_fixed_point_type (value_type (arg2)))
09747           && value_type (arg1) != value_type (arg2))
09748         error (_("Operands of fixed-point addition must have the same type"));
09749       /* Do the addition, and cast the result to the type of the first
09750          argument.  We cannot cast the result to a reference type, so if
09751          ARG1 is a reference type, find its underlying type.  */
09752       type = value_type (arg1);
09753       while (TYPE_CODE (type) == TYPE_CODE_REF)
09754         type = TYPE_TARGET_TYPE (type);
09755       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
09756       return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));
09757 
09758     case BINOP_SUB:
09759       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
09760       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
09761       if (noside == EVAL_SKIP)
09762         goto nosideret;
09763       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
09764         return (value_from_longest
09765                  (value_type (arg1),
09766                   value_as_long (arg1) - value_as_long (arg2)));
09767       if ((ada_is_fixed_point_type (value_type (arg1))
09768            || ada_is_fixed_point_type (value_type (arg2)))
09769           && value_type (arg1) != value_type (arg2))
09770         error (_("Operands of fixed-point subtraction "
09771                  "must have the same type"));
09772       /* Do the substraction, and cast the result to the type of the first
09773          argument.  We cannot cast the result to a reference type, so if
09774          ARG1 is a reference type, find its underlying type.  */
09775       type = value_type (arg1);
09776       while (TYPE_CODE (type) == TYPE_CODE_REF)
09777         type = TYPE_TARGET_TYPE (type);
09778       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
09779       return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));
09780 
09781     case BINOP_MUL:
09782     case BINOP_DIV:
09783     case BINOP_REM:
09784     case BINOP_MOD:
09785       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09786       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09787       if (noside == EVAL_SKIP)
09788         goto nosideret;
09789       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
09790         {
09791           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
09792           return value_zero (value_type (arg1), not_lval);
09793         }
09794       else
09795         {
09796           type = builtin_type (exp->gdbarch)->builtin_double;
09797           if (ada_is_fixed_point_type (value_type (arg1)))
09798             arg1 = cast_from_fixed (type, arg1);
09799           if (ada_is_fixed_point_type (value_type (arg2)))
09800             arg2 = cast_from_fixed (type, arg2);
09801           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
09802           return ada_value_binop (arg1, arg2, op);
09803         }
09804 
09805     case BINOP_EQUAL:
09806     case BINOP_NOTEQUAL:
09807       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09808       arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
09809       if (noside == EVAL_SKIP)
09810         goto nosideret;
09811       if (noside == EVAL_AVOID_SIDE_EFFECTS)
09812         tem = 0;
09813       else
09814         {
09815           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
09816           tem = ada_value_equal (arg1, arg2);
09817         }
09818       if (op == BINOP_NOTEQUAL)
09819         tem = !tem;
09820       type = language_bool_type (exp->language_defn, exp->gdbarch);
09821       return value_from_longest (type, (LONGEST) tem);
09822 
09823     case UNOP_NEG:
09824       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09825       if (noside == EVAL_SKIP)
09826         goto nosideret;
09827       else if (ada_is_fixed_point_type (value_type (arg1)))
09828         return value_cast (value_type (arg1), value_neg (arg1));
09829       else
09830         {
09831           unop_promote (exp->language_defn, exp->gdbarch, &arg1);
09832           return value_neg (arg1);
09833         }
09834 
09835     case BINOP_LOGICAL_AND:
09836     case BINOP_LOGICAL_OR:
09837     case UNOP_LOGICAL_NOT:
09838       {
09839         struct value *val;
09840 
09841         *pos -= 1;
09842         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
09843         type = language_bool_type (exp->language_defn, exp->gdbarch);
09844         return value_cast (type, val);
09845       }
09846 
09847     case BINOP_BITWISE_AND:
09848     case BINOP_BITWISE_IOR:
09849     case BINOP_BITWISE_XOR:
09850       {
09851         struct value *val;
09852 
09853         arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
09854         *pos = pc;
09855         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
09856 
09857         return value_cast (value_type (arg1), val);
09858       }
09859 
09860     case OP_VAR_VALUE:
09861       *pos -= 1;
09862 
09863       if (noside == EVAL_SKIP)
09864         {
09865           *pos += 4;
09866           goto nosideret;
09867         }
09868       else if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
09869         /* Only encountered when an unresolved symbol occurs in a
09870            context other than a function call, in which case, it is
09871            invalid.  */
09872         error (_("Unexpected unresolved symbol, %s, during evaluation"),
09873                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
09874       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
09875         {
09876           type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
09877           /* Check to see if this is a tagged type.  We also need to handle
09878              the case where the type is a reference to a tagged type, but
09879              we have to be careful to exclude pointers to tagged types.
09880              The latter should be shown as usual (as a pointer), whereas
09881              a reference should mostly be transparent to the user.  */
09882           if (ada_is_tagged_type (type, 0)
09883               || (TYPE_CODE(type) == TYPE_CODE_REF
09884                   && ada_is_tagged_type (TYPE_TARGET_TYPE (type), 0)))
09885           {
09886             /* Tagged types are a little special in the fact that the real
09887                type is dynamic and can only be determined by inspecting the
09888                object's tag.  This means that we need to get the object's
09889                value first (EVAL_NORMAL) and then extract the actual object
09890                type from its tag.
09891 
09892                Note that we cannot skip the final step where we extract
09893                the object type from its tag, because the EVAL_NORMAL phase
09894                results in dynamic components being resolved into fixed ones.
09895                This can cause problems when trying to print the type
09896                description of tagged types whose parent has a dynamic size:
09897                We use the type name of the "_parent" component in order
09898                to print the name of the ancestor type in the type description.
09899                If that component had a dynamic size, the resolution into
09900                a fixed type would result in the loss of that type name,
09901                thus preventing us from printing the name of the ancestor
09902                type in the type description.  */
09903             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);
09904 
09905             if (TYPE_CODE (type) != TYPE_CODE_REF)
09906               {
09907                 struct type *actual_type;
09908 
09909                 actual_type = type_from_tag (ada_value_tag (arg1));
09910                 if (actual_type == NULL)
09911                   /* If, for some reason, we were unable to determine
09912                      the actual type from the tag, then use the static
09913                      approximation that we just computed as a fallback.
09914                      This can happen if the debugging information is
09915                      incomplete, for instance.  */
09916                   actual_type = type;
09917                 return value_zero (actual_type, not_lval);
09918               }
09919             else
09920               {
09921                 /* In the case of a ref, ada_coerce_ref takes care
09922                    of determining the actual type.  But the evaluation
09923                    should return a ref as it should be valid to ask
09924                    for its address; so rebuild a ref after coerce.  */
09925                 arg1 = ada_coerce_ref (arg1);
09926                 return value_ref (arg1);
09927               }
09928           }
09929 
09930           *pos += 4;
09931           return value_zero
09932             (to_static_fixed_type
09933              (static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol))),
09934              not_lval);
09935         }
09936       else
09937         {
09938           arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
09939           return ada_to_fixed_value (arg1);
09940         }
09941 
09942     case OP_FUNCALL:
09943       (*pos) += 2;
09944 
09945       /* Allocate arg vector, including space for the function to be
09946          called in argvec[0] and a terminating NULL.  */
09947       nargs = longest_to_int (exp->elts[pc + 1].longconst);
09948       argvec =
09949         (struct value **) alloca (sizeof (struct value *) * (nargs + 2));
09950 
09951       if (exp->elts[*pos].opcode == OP_VAR_VALUE
09952           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
09953         error (_("Unexpected unresolved symbol, %s, during evaluation"),
09954                SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
09955       else
09956         {
09957           for (tem = 0; tem <= nargs; tem += 1)
09958             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
09959           argvec[tem] = 0;
09960 
09961           if (noside == EVAL_SKIP)
09962             goto nosideret;
09963         }
09964 
09965       if (ada_is_constrained_packed_array_type
09966           (desc_base_type (value_type (argvec[0]))))
09967         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
09968       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
09969                && TYPE_FIELD_BITSIZE (value_type (argvec[0]), 0) != 0)
09970         /* This is a packed array that has already been fixed, and
09971            therefore already coerced to a simple array.  Nothing further
09972            to do.  */
09973         ;
09974       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF
09975                || (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
09976                    && VALUE_LVAL (argvec[0]) == lval_memory))
09977         argvec[0] = value_addr (argvec[0]);
09978 
09979       type = ada_check_typedef (value_type (argvec[0]));
09980 
09981       /* Ada allows us to implicitly dereference arrays when subscripting
09982          them.  So, if this is an array typedef (encoding use for array
09983          access types encoded as fat pointers), strip it now.  */
09984       if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF)
09985         type = ada_typedef_target_type (type);
09986 
09987       if (TYPE_CODE (type) == TYPE_CODE_PTR)
09988         {
09989           switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
09990             {
09991             case TYPE_CODE_FUNC:
09992               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
09993               break;
09994             case TYPE_CODE_ARRAY:
09995               break;
09996             case TYPE_CODE_STRUCT:
09997               if (noside != EVAL_AVOID_SIDE_EFFECTS)
09998                 argvec[0] = ada_value_ind (argvec[0]);
09999               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
10000               break;
10001             default:
10002               error (_("cannot subscript or call something of type `%s'"),
10003                      ada_type_name (value_type (argvec[0])));
10004               break;
10005             }
10006         }
10007 
10008       switch (TYPE_CODE (type))
10009         {
10010         case TYPE_CODE_FUNC:
10011           if (noside == EVAL_AVOID_SIDE_EFFECTS)
10012             {
10013               struct type *rtype = TYPE_TARGET_TYPE (type);
10014 
10015               if (TYPE_GNU_IFUNC (type))
10016                 return allocate_value (TYPE_TARGET_TYPE (rtype));
10017               return allocate_value (rtype);
10018             }
10019           return call_function_by_hand (argvec[0], nargs, argvec + 1);
10020         case TYPE_CODE_INTERNAL_FUNCTION:
10021           if (noside == EVAL_AVOID_SIDE_EFFECTS)
10022             /* We don't know anything about what the internal
10023                function might return, but we have to return
10024                something.  */
10025             return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10026                                not_lval);
10027           else
10028             return call_internal_function (exp->gdbarch, exp->language_defn,
10029                                            argvec[0], nargs, argvec + 1);
10030 
10031         case TYPE_CODE_STRUCT:
10032           {
10033             int arity;
10034 
10035             arity = ada_array_arity (type);
10036             type = ada_array_element_type (type, nargs);
10037             if (type == NULL)
10038               error (_("cannot subscript or call a record"));
10039             if (arity != nargs)
10040               error (_("wrong number of subscripts; expecting %d"), arity);
10041             if (noside == EVAL_AVOID_SIDE_EFFECTS)
10042               return value_zero (ada_aligned_type (type), lval_memory);
10043             return
10044               unwrap_value (ada_value_subscript
10045                             (argvec[0], nargs, argvec + 1));
10046           }
10047         case TYPE_CODE_ARRAY:
10048           if (noside == EVAL_AVOID_SIDE_EFFECTS)
10049             {
10050               type = ada_array_element_type (type, nargs);
10051               if (type == NULL)
10052                 error (_("element type of array unknown"));
10053               else
10054                 return value_zero (ada_aligned_type (type), lval_memory);
10055             }
10056           return
10057             unwrap_value (ada_value_subscript
10058                           (ada_coerce_to_simple_array (argvec[0]),
10059                            nargs, argvec + 1));
10060         case TYPE_CODE_PTR:     /* Pointer to array */
10061           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
10062           if (noside == EVAL_AVOID_SIDE_EFFECTS)
10063             {
10064               type = ada_array_element_type (type, nargs);
10065               if (type == NULL)
10066                 error (_("element type of array unknown"));
10067               else
10068                 return value_zero (ada_aligned_type (type), lval_memory);
10069             }
10070           return
10071             unwrap_value (ada_value_ptr_subscript (argvec[0], type,
10072                                                    nargs, argvec + 1));
10073 
10074         default:
10075           error (_("Attempt to index or call something other than an "
10076                    "array or function"));
10077         }
10078 
10079     case TERNOP_SLICE:
10080       {
10081         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10082         struct value *low_bound_val =
10083           evaluate_subexp (NULL_TYPE, exp, pos, noside);
10084         struct value *high_bound_val =
10085           evaluate_subexp (NULL_TYPE, exp, pos, noside);
10086         LONGEST low_bound;
10087         LONGEST high_bound;
10088 
10089         low_bound_val = coerce_ref (low_bound_val);
10090         high_bound_val = coerce_ref (high_bound_val);
10091         low_bound = pos_atr (low_bound_val);
10092         high_bound = pos_atr (high_bound_val);
10093 
10094         if (noside == EVAL_SKIP)
10095           goto nosideret;
10096 
10097         /* If this is a reference to an aligner type, then remove all
10098            the aligners.  */
10099         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
10100             && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
10101           TYPE_TARGET_TYPE (value_type (array)) =
10102             ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
10103 
10104         if (ada_is_constrained_packed_array_type (value_type (array)))
10105           error (_("cannot slice a packed array"));
10106 
10107         /* If this is a reference to an array or an array lvalue,
10108            convert to a pointer.  */
10109         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
10110             || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
10111                 && VALUE_LVAL (array) == lval_memory))
10112           array = value_addr (array);
10113 
10114         if (noside == EVAL_AVOID_SIDE_EFFECTS
10115             && ada_is_array_descriptor_type (ada_check_typedef
10116                                              (value_type (array))))
10117           return empty_array (ada_type_of_array (array, 0), low_bound);
10118 
10119         array = ada_coerce_to_simple_array_ptr (array);
10120 
10121         /* If we have more than one level of pointer indirection,
10122            dereference the value until we get only one level.  */
10123         while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
10124                && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
10125                      == TYPE_CODE_PTR))
10126           array = value_ind (array);
10127 
10128         /* Make sure we really do have an array type before going further,
10129            to avoid a SEGV when trying to get the index type or the target
10130            type later down the road if the debug info generated by
10131            the compiler is incorrect or incomplete.  */
10132         if (!ada_is_simple_array_type (value_type (array)))
10133           error (_("cannot take slice of non-array"));
10134 
10135         if (TYPE_CODE (ada_check_typedef (value_type (array)))
10136             == TYPE_CODE_PTR)
10137           {
10138             struct type *type0 = ada_check_typedef (value_type (array));
10139 
10140             if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
10141               return empty_array (TYPE_TARGET_TYPE (type0), low_bound);
10142             else
10143               {
10144                 struct type *arr_type0 =
10145                   to_fixed_array_type (TYPE_TARGET_TYPE (type0), NULL, 1);
10146 
10147                 return ada_value_slice_from_ptr (array, arr_type0,
10148                                                  longest_to_int (low_bound),
10149                                                  longest_to_int (high_bound));
10150               }
10151           }
10152         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10153           return array;
10154         else if (high_bound < low_bound)
10155           return empty_array (value_type (array), low_bound);
10156         else
10157           return ada_value_slice (array, longest_to_int (low_bound),
10158                                   longest_to_int (high_bound));
10159       }
10160 
10161     case UNOP_IN_RANGE:
10162       (*pos) += 2;
10163       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10164       type = check_typedef (exp->elts[pc + 1].type);
10165 
10166       if (noside == EVAL_SKIP)
10167         goto nosideret;
10168 
10169       switch (TYPE_CODE (type))
10170         {
10171         default:
10172           lim_warning (_("Membership test incompletely implemented; "
10173                          "always returns true"));
10174           type = language_bool_type (exp->language_defn, exp->gdbarch);
10175           return value_from_longest (type, (LONGEST) 1);
10176 
10177         case TYPE_CODE_RANGE:
10178           arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
10179           arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
10180           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10181           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10182           type = language_bool_type (exp->language_defn, exp->gdbarch);
10183           return
10184             value_from_longest (type,
10185                                 (value_less (arg1, arg3)
10186                                  || value_equal (arg1, arg3))
10187                                 && (value_less (arg2, arg1)
10188                                     || value_equal (arg2, arg1)));
10189         }
10190 
10191     case BINOP_IN_BOUNDS:
10192       (*pos) += 2;
10193       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10194       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10195 
10196       if (noside == EVAL_SKIP)
10197         goto nosideret;
10198 
10199       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10200         {
10201           type = language_bool_type (exp->language_defn, exp->gdbarch);
10202           return value_zero (type, not_lval);
10203         }
10204 
10205       tem = longest_to_int (exp->elts[pc + 1].longconst);
10206 
10207       type = ada_index_type (value_type (arg2), tem, "range");
10208       if (!type)
10209         type = value_type (arg1);
10210 
10211       arg3 = value_from_longest (type, ada_array_bound (arg2, tem, 1));
10212       arg2 = value_from_longest (type, ada_array_bound (arg2, tem, 0));
10213 
10214       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10215       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10216       type = language_bool_type (exp->language_defn, exp->gdbarch);
10217       return
10218         value_from_longest (type,
10219                             (value_less (arg1, arg3)
10220                              || value_equal (arg1, arg3))
10221                             && (value_less (arg2, arg1)
10222                                 || value_equal (arg2, arg1)));
10223 
10224     case TERNOP_IN_RANGE:
10225       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10226       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10227       arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10228 
10229       if (noside == EVAL_SKIP)
10230         goto nosideret;
10231 
10232       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10233       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
10234       type = language_bool_type (exp->language_defn, exp->gdbarch);
10235       return
10236         value_from_longest (type,
10237                             (value_less (arg1, arg3)
10238                              || value_equal (arg1, arg3))
10239                             && (value_less (arg2, arg1)
10240                                 || value_equal (arg2, arg1)));
10241 
10242     case OP_ATR_FIRST:
10243     case OP_ATR_LAST:
10244     case OP_ATR_LENGTH:
10245       {
10246         struct type *type_arg;
10247 
10248         if (exp->elts[*pos].opcode == OP_TYPE)
10249           {
10250             evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10251             arg1 = NULL;
10252             type_arg = check_typedef (exp->elts[pc + 2].type);
10253           }
10254         else
10255           {
10256             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10257             type_arg = NULL;
10258           }
10259 
10260         if (exp->elts[*pos].opcode != OP_LONG)
10261           error (_("Invalid operand to '%s"), ada_attribute_name (op));
10262         tem = longest_to_int (exp->elts[*pos + 2].longconst);
10263         *pos += 4;
10264 
10265         if (noside == EVAL_SKIP)
10266           goto nosideret;
10267 
10268         if (type_arg == NULL)
10269           {
10270             arg1 = ada_coerce_ref (arg1);
10271 
10272             if (ada_is_constrained_packed_array_type (value_type (arg1)))
10273               arg1 = ada_coerce_to_simple_array (arg1);
10274 
10275             type = ada_index_type (value_type (arg1), tem,
10276                                    ada_attribute_name (op));
10277             if (type == NULL)
10278               type = builtin_type (exp->gdbarch)->builtin_int;
10279 
10280             if (noside == EVAL_AVOID_SIDE_EFFECTS)
10281               return allocate_value (type);
10282 
10283             switch (op)
10284               {
10285               default:          /* Should never happen.  */
10286                 error (_("unexpected attribute encountered"));
10287               case OP_ATR_FIRST:
10288                 return value_from_longest
10289                         (type, ada_array_bound (arg1, tem, 0));
10290               case OP_ATR_LAST:
10291                 return value_from_longest
10292                         (type, ada_array_bound (arg1, tem, 1));
10293               case OP_ATR_LENGTH:
10294                 return value_from_longest
10295                         (type, ada_array_length (arg1, tem));
10296               }
10297           }
10298         else if (discrete_type_p (type_arg))
10299           {
10300             struct type *range_type;
10301             const char *name = ada_type_name (type_arg);
10302 
10303             range_type = NULL;
10304             if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
10305               range_type = to_fixed_range_type (type_arg, NULL);
10306             if (range_type == NULL)
10307               range_type = type_arg;
10308             switch (op)
10309               {
10310               default:
10311                 error (_("unexpected attribute encountered"));
10312               case OP_ATR_FIRST:
10313                 return value_from_longest 
10314                   (range_type, ada_discrete_type_low_bound (range_type));
10315               case OP_ATR_LAST:
10316                 return value_from_longest
10317                   (range_type, ada_discrete_type_high_bound (range_type));
10318               case OP_ATR_LENGTH:
10319                 error (_("the 'length attribute applies only to array types"));
10320               }
10321           }
10322         else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
10323           error (_("unimplemented type attribute"));
10324         else
10325           {
10326             LONGEST low, high;
10327 
10328             if (ada_is_constrained_packed_array_type (type_arg))
10329               type_arg = decode_constrained_packed_array_type (type_arg);
10330 
10331             type = ada_index_type (type_arg, tem, ada_attribute_name (op));
10332             if (type == NULL)
10333               type = builtin_type (exp->gdbarch)->builtin_int;
10334 
10335             if (noside == EVAL_AVOID_SIDE_EFFECTS)
10336               return allocate_value (type);
10337 
10338             switch (op)
10339               {
10340               default:
10341                 error (_("unexpected attribute encountered"));
10342               case OP_ATR_FIRST:
10343                 low = ada_array_bound_from_type (type_arg, tem, 0);
10344                 return value_from_longest (type, low);
10345               case OP_ATR_LAST:
10346                 high = ada_array_bound_from_type (type_arg, tem, 1);
10347                 return value_from_longest (type, high);
10348               case OP_ATR_LENGTH:
10349                 low = ada_array_bound_from_type (type_arg, tem, 0);
10350                 high = ada_array_bound_from_type (type_arg, tem, 1);
10351                 return value_from_longest (type, high - low + 1);
10352               }
10353           }
10354       }
10355 
10356     case OP_ATR_TAG:
10357       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10358       if (noside == EVAL_SKIP)
10359         goto nosideret;
10360 
10361       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10362         return value_zero (ada_tag_type (arg1), not_lval);
10363 
10364       return ada_value_tag (arg1);
10365 
10366     case OP_ATR_MIN:
10367     case OP_ATR_MAX:
10368       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10369       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10370       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10371       if (noside == EVAL_SKIP)
10372         goto nosideret;
10373       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10374         return value_zero (value_type (arg1), not_lval);
10375       else
10376         {
10377           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10378           return value_binop (arg1, arg2,
10379                               op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
10380         }
10381 
10382     case OP_ATR_MODULUS:
10383       {
10384         struct type *type_arg = check_typedef (exp->elts[pc + 2].type);
10385 
10386         evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10387         if (noside == EVAL_SKIP)
10388           goto nosideret;
10389 
10390         if (!ada_is_modular_type (type_arg))
10391           error (_("'modulus must be applied to modular type"));
10392 
10393         return value_from_longest (TYPE_TARGET_TYPE (type_arg),
10394                                    ada_modulus (type_arg));
10395       }
10396 
10397 
10398     case OP_ATR_POS:
10399       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10400       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10401       if (noside == EVAL_SKIP)
10402         goto nosideret;
10403       type = builtin_type (exp->gdbarch)->builtin_int;
10404       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10405         return value_zero (type, not_lval);
10406       else
10407         return value_pos_atr (type, arg1);
10408 
10409     case OP_ATR_SIZE:
10410       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10411       type = value_type (arg1);
10412 
10413       /* If the argument is a reference, then dereference its type, since
10414          the user is really asking for the size of the actual object,
10415          not the size of the pointer.  */
10416       if (TYPE_CODE (type) == TYPE_CODE_REF)
10417         type = TYPE_TARGET_TYPE (type);
10418 
10419       if (noside == EVAL_SKIP)
10420         goto nosideret;
10421       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10422         return value_zero (builtin_type (exp->gdbarch)->builtin_int, not_lval);
10423       else
10424         return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
10425                                    TARGET_CHAR_BIT * TYPE_LENGTH (type));
10426 
10427     case OP_ATR_VAL:
10428       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
10429       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10430       type = exp->elts[pc + 2].type;
10431       if (noside == EVAL_SKIP)
10432         goto nosideret;
10433       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10434         return value_zero (type, not_lval);
10435       else
10436         return value_val_atr (type, arg1);
10437 
10438     case BINOP_EXP:
10439       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10440       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10441       if (noside == EVAL_SKIP)
10442         goto nosideret;
10443       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10444         return value_zero (value_type (arg1), not_lval);
10445       else
10446         {
10447           /* For integer exponentiation operations,
10448              only promote the first argument.  */
10449           if (is_integral_type (value_type (arg2)))
10450             unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10451           else
10452             binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
10453 
10454           return value_binop (arg1, arg2, op);
10455         }
10456 
10457     case UNOP_PLUS:
10458       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10459       if (noside == EVAL_SKIP)
10460         goto nosideret;
10461       else
10462         return arg1;
10463 
10464     case UNOP_ABS:
10465       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10466       if (noside == EVAL_SKIP)
10467         goto nosideret;
10468       unop_promote (exp->language_defn, exp->gdbarch, &arg1);
10469       if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
10470         return value_neg (arg1);
10471       else
10472         return arg1;
10473 
10474     case UNOP_IND:
10475       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10476       if (noside == EVAL_SKIP)
10477         goto nosideret;
10478       type = ada_check_typedef (value_type (arg1));
10479       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10480         {
10481           if (ada_is_array_descriptor_type (type))
10482             /* GDB allows dereferencing GNAT array descriptors.  */
10483             {
10484               struct type *arrType = ada_type_of_array (arg1, 0);
10485 
10486               if (arrType == NULL)
10487                 error (_("Attempt to dereference null array pointer."));
10488               return value_at_lazy (arrType, 0);
10489             }
10490           else if (TYPE_CODE (type) == TYPE_CODE_PTR
10491                    || TYPE_CODE (type) == TYPE_CODE_REF
10492                    /* In C you can dereference an array to get the 1st elt.  */
10493                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
10494             {
10495               type = to_static_fixed_type
10496                 (ada_aligned_type
10497                  (ada_check_typedef (TYPE_TARGET_TYPE (type))));
10498               check_size (type);
10499               return value_zero (type, lval_memory);
10500             }
10501           else if (TYPE_CODE (type) == TYPE_CODE_INT)
10502             {
10503               /* GDB allows dereferencing an int.  */
10504               if (expect_type == NULL)
10505                 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
10506                                    lval_memory);
10507               else
10508                 {
10509                   expect_type = 
10510                     to_static_fixed_type (ada_aligned_type (expect_type));
10511                   return value_zero (expect_type, lval_memory);
10512                 }
10513             }
10514           else
10515             error (_("Attempt to take contents of a non-pointer value."));
10516         }
10517       arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for??  */
10518       type = ada_check_typedef (value_type (arg1));
10519 
10520       if (TYPE_CODE (type) == TYPE_CODE_INT)
10521           /* GDB allows dereferencing an int.  If we were given
10522              the expect_type, then use that as the target type.
10523              Otherwise, assume that the target type is an int.  */
10524         {
10525           if (expect_type != NULL)
10526             return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
10527                                               arg1));
10528           else
10529             return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
10530                                   (CORE_ADDR) value_as_address (arg1));
10531         }
10532 
10533       if (ada_is_array_descriptor_type (type))
10534         /* GDB allows dereferencing GNAT array descriptors.  */
10535         return ada_coerce_to_simple_array (arg1);
10536       else
10537         return ada_value_ind (arg1);
10538 
10539     case STRUCTOP_STRUCT:
10540       tem = longest_to_int (exp->elts[pc + 1].longconst);
10541       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
10542       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
10543       if (noside == EVAL_SKIP)
10544         goto nosideret;
10545       if (noside == EVAL_AVOID_SIDE_EFFECTS)
10546         {
10547           struct type *type1 = value_type (arg1);
10548 
10549           if (ada_is_tagged_type (type1, 1))
10550             {
10551               type = ada_lookup_struct_elt_type (type1,
10552                                                  &exp->elts[pc + 2].string,
10553                                                  1, 1, NULL);
10554               if (type == NULL)
10555                 /* In this case, we assume that the field COULD exist
10556                    in some extension of the type.  Return an object of 
10557                    "type" void, which will match any formal 
10558                    (see ada_type_match).  */
10559                 return value_zero (builtin_type (exp->gdbarch)->builtin_void,
10560                                    lval_memory);
10561             }
10562           else
10563             type =
10564               ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
10565                                           0, NULL);
10566 
10567           return value_zero (ada_aligned_type (type), lval_memory);
10568         }
10569       else
10570         arg1 = ada_value_struct_elt (arg1, &exp->elts[pc + 2].string, 0);
10571         arg1 = unwrap_value (arg1);
10572         return ada_to_fixed_value (arg1);
10573 
10574     case OP_TYPE:
10575       /* The value is not supposed to be used.  This is here to make it
10576          easier to accommodate expressions that contain types.  */
10577       (*pos) += 2;
10578       if (noside == EVAL_SKIP)
10579         goto nosideret;
10580       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
10581         return allocate_value (exp->elts[pc + 1].type);
10582       else
10583         error (_("Attempt to use a type name as an expression"));
10584 
10585     case OP_AGGREGATE:
10586     case OP_CHOICES:
10587     case OP_OTHERS:
10588     case OP_DISCRETE_RANGE:
10589     case OP_POSITIONAL:
10590     case OP_NAME:
10591       if (noside == EVAL_NORMAL)
10592         switch (op) 
10593           {
10594           case OP_NAME:
10595             error (_("Undefined name, ambiguous name, or renaming used in "
10596                      "component association: %s."), &exp->elts[pc+2].string);
10597           case OP_AGGREGATE:
10598             error (_("Aggregates only allowed on the right of an assignment"));
10599           default:
10600             internal_error (__FILE__, __LINE__,
10601                             _("aggregate apparently mangled"));
10602           }
10603 
10604       ada_forward_operator_length (exp, pc, &oplen, &nargs);
10605       *pos += oplen - 1;
10606       for (tem = 0; tem < nargs; tem += 1) 
10607         ada_evaluate_subexp (NULL, exp, pos, noside);
10608       goto nosideret;
10609     }
10610 
10611 nosideret:
10612   return value_from_longest (builtin_type (exp->gdbarch)->builtin_int, 1);
10613 }
10614 
10615 
10616                                 /* Fixed point */
10617 
10618 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
10619    type name that encodes the 'small and 'delta information.
10620    Otherwise, return NULL.  */
10621 
10622 static const char *
10623 fixed_type_info (struct type *type)
10624 {
10625   const char *name = ada_type_name (type);
10626   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
10627 
10628   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
10629     {
10630       const char *tail = strstr (name, "___XF_");
10631 
10632       if (tail == NULL)
10633         return NULL;
10634       else
10635         return tail + 5;
10636     }
10637   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
10638     return fixed_type_info (TYPE_TARGET_TYPE (type));
10639   else
10640     return NULL;
10641 }
10642 
10643 /* Returns non-zero iff TYPE represents an Ada fixed-point type.  */
10644 
10645 int
10646 ada_is_fixed_point_type (struct type *type)
10647 {
10648   return fixed_type_info (type) != NULL;
10649 }
10650 
10651 /* Return non-zero iff TYPE represents a System.Address type.  */
10652 
10653 int
10654 ada_is_system_address_type (struct type *type)
10655 {
10656   return (TYPE_NAME (type)
10657           && strcmp (TYPE_NAME (type), "system__address") == 0);
10658 }
10659 
10660 /* Assuming that TYPE is the representation of an Ada fixed-point
10661    type, return its delta, or -1 if the type is malformed and the
10662    delta cannot be determined.  */
10663 
10664 DOUBLEST
10665 ada_delta (struct type *type)
10666 {
10667   const char *encoding = fixed_type_info (type);
10668   DOUBLEST num, den;
10669 
10670   /* Strictly speaking, num and den are encoded as integer.  However,
10671      they may not fit into a long, and they will have to be converted
10672      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
10673   if (sscanf (encoding, "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
10674               &num, &den) < 2)
10675     return -1.0;
10676   else
10677     return num / den;
10678 }
10679 
10680 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
10681    factor ('SMALL value) associated with the type.  */
10682 
10683 static DOUBLEST
10684 scaling_factor (struct type *type)
10685 {
10686   const char *encoding = fixed_type_info (type);
10687   DOUBLEST num0, den0, num1, den1;
10688   int n;
10689 
10690   /* Strictly speaking, num's and den's are encoded as integer.  However,
10691      they may not fit into a long, and they will have to be converted
10692      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
10693   n = sscanf (encoding,
10694               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT
10695               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
10696               &num0, &den0, &num1, &den1);
10697 
10698   if (n < 2)
10699     return 1.0;
10700   else if (n == 4)
10701     return num1 / den1;
10702   else
10703     return num0 / den0;
10704 }
10705 
10706 
10707 /* Assuming that X is the representation of a value of fixed-point
10708    type TYPE, return its floating-point equivalent.  */
10709 
10710 DOUBLEST
10711 ada_fixed_to_float (struct type *type, LONGEST x)
10712 {
10713   return (DOUBLEST) x *scaling_factor (type);
10714 }
10715 
10716 /* The representation of a fixed-point value of type TYPE
10717    corresponding to the value X.  */
10718 
10719 LONGEST
10720 ada_float_to_fixed (struct type *type, DOUBLEST x)
10721 {
10722   return (LONGEST) (x / scaling_factor (type) + 0.5);
10723 }
10724 
10725 
10726 
10727                                 /* Range types */
10728 
10729 /* Scan STR beginning at position K for a discriminant name, and
10730    return the value of that discriminant field of DVAL in *PX.  If
10731    PNEW_K is not null, put the position of the character beyond the
10732    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
10733    not alter *PX and *PNEW_K if unsuccessful.  */
10734 
10735 static int
10736 scan_discrim_bound (char *str, int k, struct value *dval, LONGEST * px,
10737                     int *pnew_k)
10738 {
10739   static char *bound_buffer = NULL;
10740   static size_t bound_buffer_len = 0;
10741   char *bound;
10742   char *pend;
10743   struct value *bound_val;
10744 
10745   if (dval == NULL || str == NULL || str[k] == '\0')
10746     return 0;
10747 
10748   pend = strstr (str + k, "__");
10749   if (pend == NULL)
10750     {
10751       bound = str + k;
10752       k += strlen (bound);
10753     }
10754   else
10755     {
10756       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
10757       bound = bound_buffer;
10758       strncpy (bound_buffer, str + k, pend - (str + k));
10759       bound[pend - (str + k)] = '\0';
10760       k = pend - str;
10761     }
10762 
10763   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
10764   if (bound_val == NULL)
10765     return 0;
10766 
10767   *px = value_as_long (bound_val);
10768   if (pnew_k != NULL)
10769     *pnew_k = k;
10770   return 1;
10771 }
10772 
10773 /* Value of variable named NAME in the current environment.  If
10774    no such variable found, then if ERR_MSG is null, returns 0, and
10775    otherwise causes an error with message ERR_MSG.  */
10776 
10777 static struct value *
10778 get_var_value (char *name, char *err_msg)
10779 {
10780   struct ada_symbol_info *syms;
10781   int nsyms;
10782 
10783   nsyms = ada_lookup_symbol_list (name, get_selected_block (0), VAR_DOMAIN,
10784                                   &syms);
10785 
10786   if (nsyms != 1)
10787     {
10788       if (err_msg == NULL)
10789         return 0;
10790       else
10791         error (("%s"), err_msg);
10792     }
10793 
10794   return value_of_variable (syms[0].sym, syms[0].block);
10795 }
10796 
10797 /* Value of integer variable named NAME in the current environment.  If
10798    no such variable found, returns 0, and sets *FLAG to 0.  If
10799    successful, sets *FLAG to 1.  */
10800 
10801 LONGEST
10802 get_int_var_value (char *name, int *flag)
10803 {
10804   struct value *var_val = get_var_value (name, 0);
10805 
10806   if (var_val == 0)
10807     {
10808       if (flag != NULL)
10809         *flag = 0;
10810       return 0;
10811     }
10812   else
10813     {
10814       if (flag != NULL)
10815         *flag = 1;
10816       return value_as_long (var_val);
10817     }
10818 }
10819 
10820 
10821 /* Return a range type whose base type is that of the range type named
10822    NAME in the current environment, and whose bounds are calculated
10823    from NAME according to the GNAT range encoding conventions.
10824    Extract discriminant values, if needed, from DVAL.  ORIG_TYPE is the
10825    corresponding range type from debug information; fall back to using it
10826    if symbol lookup fails.  If a new type must be created, allocate it
10827    like ORIG_TYPE was.  The bounds information, in general, is encoded
10828    in NAME, the base type given in the named range type.  */
10829 
10830 static struct type *
10831 to_fixed_range_type (struct type *raw_type, struct value *dval)
10832 {
10833   const char *name;
10834   struct type *base_type;
10835   char *subtype_info;
10836 
10837   gdb_assert (raw_type != NULL);
10838   gdb_assert (TYPE_NAME (raw_type) != NULL);
10839 
10840   if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
10841     base_type = TYPE_TARGET_TYPE (raw_type);
10842   else
10843     base_type = raw_type;
10844 
10845   name = TYPE_NAME (raw_type);
10846   subtype_info = strstr (name, "___XD");
10847   if (subtype_info == NULL)
10848     {
10849       LONGEST L = ada_discrete_type_low_bound (raw_type);
10850       LONGEST U = ada_discrete_type_high_bound (raw_type);
10851 
10852       if (L < INT_MIN || U > INT_MAX)
10853         return raw_type;
10854       else
10855         return create_range_type (alloc_type_copy (raw_type), raw_type,
10856                                   ada_discrete_type_low_bound (raw_type),
10857                                   ada_discrete_type_high_bound (raw_type));
10858     }
10859   else
10860     {
10861       static char *name_buf = NULL;
10862       static size_t name_len = 0;
10863       int prefix_len = subtype_info - name;
10864       LONGEST L, U;
10865       struct type *type;
10866       char *bounds_str;
10867       int n;
10868 
10869       GROW_VECT (name_buf, name_len, prefix_len + 5);
10870       strncpy (name_buf, name, prefix_len);
10871       name_buf[prefix_len] = '\0';
10872 
10873       subtype_info += 5;
10874       bounds_str = strchr (subtype_info, '_');
10875       n = 1;
10876 
10877       if (*subtype_info == 'L')
10878         {
10879           if (!ada_scan_number (bounds_str, n, &L, &n)
10880               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
10881             return raw_type;
10882           if (bounds_str[n] == '_')
10883             n += 2;
10884           else if (bounds_str[n] == '.')     /* FIXME? SGI Workshop kludge.  */
10885             n += 1;
10886           subtype_info += 1;
10887         }
10888       else
10889         {
10890           int ok;
10891 
10892           strcpy (name_buf + prefix_len, "___L");
10893           L = get_int_var_value (name_buf, &ok);
10894           if (!ok)
10895             {
10896               lim_warning (_("Unknown lower bound, using 1."));
10897               L = 1;
10898             }
10899         }
10900 
10901       if (*subtype_info == 'U')
10902         {
10903           if (!ada_scan_number (bounds_str, n, &U, &n)
10904               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
10905             return raw_type;
10906         }
10907       else
10908         {
10909           int ok;
10910 
10911           strcpy (name_buf + prefix_len, "___U");
10912           U = get_int_var_value (name_buf, &ok);
10913           if (!ok)
10914             {
10915               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
10916               U = L;
10917             }
10918         }
10919 
10920       type = create_range_type (alloc_type_copy (raw_type), base_type, L, U);
10921       TYPE_NAME (type) = name;
10922       return type;
10923     }
10924 }
10925 
10926 /* True iff NAME is the name of a range type.  */
10927 
10928 int
10929 ada_is_range_type_name (const char *name)
10930 {
10931   return (name != NULL && strstr (name, "___XD"));
10932 }
10933 
10934 
10935                                 /* Modular types */
10936 
10937 /* True iff TYPE is an Ada modular type.  */
10938 
10939 int
10940 ada_is_modular_type (struct type *type)
10941 {
10942   struct type *subranged_type = get_base_type (type);
10943 
10944   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
10945           && TYPE_CODE (subranged_type) == TYPE_CODE_INT
10946           && TYPE_UNSIGNED (subranged_type));
10947 }
10948 
10949 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
10950 
10951 ULONGEST
10952 ada_modulus (struct type *type)
10953 {
10954   return (ULONGEST) TYPE_HIGH_BOUND (type) + 1;
10955 }
10956 
10957 
10958 /* Ada exception catchpoint support:
10959    ---------------------------------
10960 
10961    We support 3 kinds of exception catchpoints:
10962      . catchpoints on Ada exceptions
10963      . catchpoints on unhandled Ada exceptions
10964      . catchpoints on failed assertions
10965 
10966    Exceptions raised during failed assertions, or unhandled exceptions
10967    could perfectly be caught with the general catchpoint on Ada exceptions.
10968    However, we can easily differentiate these two special cases, and having
10969    the option to distinguish these two cases from the rest can be useful
10970    to zero-in on certain situations.
10971 
10972    Exception catchpoints are a specialized form of breakpoint,
10973    since they rely on inserting breakpoints inside known routines
10974    of the GNAT runtime.  The implementation therefore uses a standard
10975    breakpoint structure of the BP_BREAKPOINT type, but with its own set
10976    of breakpoint_ops.
10977 
10978    Support in the runtime for exception catchpoints have been changed
10979    a few times already, and these changes affect the implementation
10980    of these catchpoints.  In order to be able to support several
10981    variants of the runtime, we use a sniffer that will determine
10982    the runtime variant used by the program being debugged.  */
10983 
10984 /* Ada's standard exceptions.  */
10985 
10986 static char *standard_exc[] = {
10987   "constraint_error",
10988   "program_error",
10989   "storage_error",
10990   "tasking_error"
10991 };
10992 
10993 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
10994 
10995 /* A structure that describes how to support exception catchpoints
10996    for a given executable.  */
10997 
10998 struct exception_support_info
10999 {
11000    /* The name of the symbol to break on in order to insert
11001       a catchpoint on exceptions.  */
11002    const char *catch_exception_sym;
11003 
11004    /* The name of the symbol to break on in order to insert
11005       a catchpoint on unhandled exceptions.  */
11006    const char *catch_exception_unhandled_sym;
11007 
11008    /* The name of the symbol to break on in order to insert
11009       a catchpoint on failed assertions.  */
11010    const char *catch_assert_sym;
11011 
11012    /* Assuming that the inferior just triggered an unhandled exception
11013       catchpoint, this function is responsible for returning the address
11014       in inferior memory where the name of that exception is stored.
11015       Return zero if the address could not be computed.  */
11016    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
11017 };
11018 
11019 static CORE_ADDR ada_unhandled_exception_name_addr (void);
11020 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
11021 
11022 /* The following exception support info structure describes how to
11023    implement exception catchpoints with the latest version of the
11024    Ada runtime (as of 2007-03-06).  */
11025 
11026 static const struct exception_support_info default_exception_support_info =
11027 {
11028   "__gnat_debug_raise_exception", /* catch_exception_sym */
11029   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11030   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
11031   ada_unhandled_exception_name_addr
11032 };
11033 
11034 /* The following exception support info structure describes how to
11035    implement exception catchpoints with a slightly older version
11036    of the Ada runtime.  */
11037 
11038 static const struct exception_support_info exception_support_info_fallback =
11039 {
11040   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
11041   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
11042   "system__assertions__raise_assert_failure",  /* catch_assert_sym */
11043   ada_unhandled_exception_name_addr_from_raise
11044 };
11045 
11046 /* Return nonzero if we can detect the exception support routines
11047    described in EINFO.
11048 
11049    This function errors out if an abnormal situation is detected
11050    (for instance, if we find the exception support routines, but
11051    that support is found to be incomplete).  */
11052 
11053 static int
11054 ada_has_this_exception_support (const struct exception_support_info *einfo)
11055 {
11056   struct symbol *sym;
11057 
11058   /* The symbol we're looking up is provided by a unit in the GNAT runtime
11059      that should be compiled with debugging information.  As a result, we
11060      expect to find that symbol in the symtabs.  */
11061 
11062   sym = standard_lookup (einfo->catch_exception_sym, NULL, VAR_DOMAIN);
11063   if (sym == NULL)
11064     {
11065       /* Perhaps we did not find our symbol because the Ada runtime was
11066          compiled without debugging info, or simply stripped of it.
11067          It happens on some GNU/Linux distributions for instance, where
11068          users have to install a separate debug package in order to get
11069          the runtime's debugging info.  In that situation, let the user
11070          know why we cannot insert an Ada exception catchpoint.
11071 
11072          Note: Just for the purpose of inserting our Ada exception
11073          catchpoint, we could rely purely on the associated minimal symbol.
11074          But we would be operating in degraded mode anyway, since we are
11075          still lacking the debugging info needed later on to extract
11076          the name of the exception being raised (this name is printed in
11077          the catchpoint message, and is also used when trying to catch
11078          a specific exception).  We do not handle this case for now.  */
11079       struct minimal_symbol *msym
11080         = lookup_minimal_symbol (einfo->catch_exception_sym, NULL, NULL);
11081 
11082       if (msym && MSYMBOL_TYPE (msym) != mst_solib_trampoline)
11083         error (_("Your Ada runtime appears to be missing some debugging "
11084                  "information.\nCannot insert Ada exception catchpoint "
11085                  "in this configuration."));
11086 
11087       return 0;
11088     }
11089 
11090   /* Make sure that the symbol we found corresponds to a function.  */
11091 
11092   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
11093     error (_("Symbol \"%s\" is not a function (class = %d)"),
11094            SYMBOL_LINKAGE_NAME (sym), SYMBOL_CLASS (sym));
11095 
11096   return 1;
11097 }
11098 
11099 /* Inspect the Ada runtime and determine which exception info structure
11100    should be used to provide support for exception catchpoints.
11101 
11102    This function will always set the per-inferior exception_info,
11103    or raise an error.  */
11104 
11105 static void
11106 ada_exception_support_info_sniffer (void)
11107 {
11108   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11109 
11110   /* If the exception info is already known, then no need to recompute it.  */
11111   if (data->exception_info != NULL)
11112     return;
11113 
11114   /* Check the latest (default) exception support info.  */
11115   if (ada_has_this_exception_support (&default_exception_support_info))
11116     {
11117       data->exception_info = &default_exception_support_info;
11118       return;
11119     }
11120 
11121   /* Try our fallback exception suport info.  */
11122   if (ada_has_this_exception_support (&exception_support_info_fallback))
11123     {
11124       data->exception_info = &exception_support_info_fallback;
11125       return;
11126     }
11127 
11128   /* Sometimes, it is normal for us to not be able to find the routine
11129      we are looking for.  This happens when the program is linked with
11130      the shared version of the GNAT runtime, and the program has not been
11131      started yet.  Inform the user of these two possible causes if
11132      applicable.  */
11133 
11134   if (ada_update_initial_language (language_unknown) != language_ada)
11135     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));
11136 
11137   /* If the symbol does not exist, then check that the program is
11138      already started, to make sure that shared libraries have been
11139      loaded.  If it is not started, this may mean that the symbol is
11140      in a shared library.  */
11141 
11142   if (ptid_get_pid (inferior_ptid) == 0)
11143     error (_("Unable to insert catchpoint. Try to start the program first."));
11144 
11145   /* At this point, we know that we are debugging an Ada program and
11146      that the inferior has been started, but we still are not able to
11147      find the run-time symbols.  That can mean that we are in
11148      configurable run time mode, or that a-except as been optimized
11149      out by the linker...  In any case, at this point it is not worth
11150      supporting this feature.  */
11151 
11152   error (_("Cannot insert Ada exception catchpoints in this configuration."));
11153 }
11154 
11155 /* True iff FRAME is very likely to be that of a function that is
11156    part of the runtime system.  This is all very heuristic, but is
11157    intended to be used as advice as to what frames are uninteresting
11158    to most users.  */
11159 
11160 static int
11161 is_known_support_routine (struct frame_info *frame)
11162 {
11163   struct symtab_and_line sal;
11164   char *func_name;
11165   enum language func_lang;
11166   int i;
11167   const char *fullname;
11168 
11169   /* If this code does not have any debugging information (no symtab),
11170      This cannot be any user code.  */
11171 
11172   find_frame_sal (frame, &sal);
11173   if (sal.symtab == NULL)
11174     return 1;
11175 
11176   /* If there is a symtab, but the associated source file cannot be
11177      located, then assume this is not user code:  Selecting a frame
11178      for which we cannot display the code would not be very helpful
11179      for the user.  This should also take care of case such as VxWorks
11180      where the kernel has some debugging info provided for a few units.  */
11181 
11182   fullname = symtab_to_fullname (sal.symtab);
11183   if (access (fullname, R_OK) != 0)
11184     return 1;
11185 
11186   /* Check the unit filename againt the Ada runtime file naming.
11187      We also check the name of the objfile against the name of some
11188      known system libraries that sometimes come with debugging info
11189      too.  */
11190 
11191   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
11192     {
11193       re_comp (known_runtime_file_name_patterns[i]);
11194       if (re_exec (lbasename (sal.symtab->filename)))
11195         return 1;
11196       if (sal.symtab->objfile != NULL
11197           && re_exec (objfile_name (sal.symtab->objfile)))
11198         return 1;
11199     }
11200 
11201   /* Check whether the function is a GNAT-generated entity.  */
11202 
11203   find_frame_funname (frame, &func_name, &func_lang, NULL);
11204   if (func_name == NULL)
11205     return 1;
11206 
11207   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
11208     {
11209       re_comp (known_auxiliary_function_name_patterns[i]);
11210       if (re_exec (func_name))
11211         {
11212           xfree (func_name);
11213           return 1;
11214         }
11215     }
11216 
11217   xfree (func_name);
11218   return 0;
11219 }
11220 
11221 /* Find the first frame that contains debugging information and that is not
11222    part of the Ada run-time, starting from FI and moving upward.  */
11223 
11224 void
11225 ada_find_printable_frame (struct frame_info *fi)
11226 {
11227   for (; fi != NULL; fi = get_prev_frame (fi))
11228     {
11229       if (!is_known_support_routine (fi))
11230         {
11231           select_frame (fi);
11232           break;
11233         }
11234     }
11235 
11236 }
11237 
11238 /* Assuming that the inferior just triggered an unhandled exception
11239    catchpoint, return the address in inferior memory where the name
11240    of the exception is stored.
11241    
11242    Return zero if the address could not be computed.  */
11243 
11244 static CORE_ADDR
11245 ada_unhandled_exception_name_addr (void)
11246 {
11247   return parse_and_eval_address ("e.full_name");
11248 }
11249 
11250 /* Same as ada_unhandled_exception_name_addr, except that this function
11251    should be used when the inferior uses an older version of the runtime,
11252    where the exception name needs to be extracted from a specific frame
11253    several frames up in the callstack.  */
11254 
11255 static CORE_ADDR
11256 ada_unhandled_exception_name_addr_from_raise (void)
11257 {
11258   int frame_level;
11259   struct frame_info *fi;
11260   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11261   struct cleanup *old_chain;
11262 
11263   /* To determine the name of this exception, we need to select
11264      the frame corresponding to RAISE_SYM_NAME.  This frame is
11265      at least 3 levels up, so we simply skip the first 3 frames
11266      without checking the name of their associated function.  */
11267   fi = get_current_frame ();
11268   for (frame_level = 0; frame_level < 3; frame_level += 1)
11269     if (fi != NULL)
11270       fi = get_prev_frame (fi); 
11271 
11272   old_chain = make_cleanup (null_cleanup, NULL);
11273   while (fi != NULL)
11274     {
11275       char *func_name;
11276       enum language func_lang;
11277 
11278       find_frame_funname (fi, &func_name, &func_lang, NULL);
11279       if (func_name != NULL)
11280         {
11281           make_cleanup (xfree, func_name);
11282 
11283           if (strcmp (func_name,
11284                       data->exception_info->catch_exception_sym) == 0)
11285             break; /* We found the frame we were looking for...  */
11286           fi = get_prev_frame (fi);
11287         }
11288     }
11289   do_cleanups (old_chain);
11290 
11291   if (fi == NULL)
11292     return 0;
11293 
11294   select_frame (fi);
11295   return parse_and_eval_address ("id.full_name");
11296 }
11297 
11298 /* Assuming the inferior just triggered an Ada exception catchpoint
11299    (of any type), return the address in inferior memory where the name
11300    of the exception is stored, if applicable.
11301 
11302    Return zero if the address could not be computed, or if not relevant.  */
11303 
11304 static CORE_ADDR
11305 ada_exception_name_addr_1 (enum ada_exception_catchpoint_kind ex,
11306                            struct breakpoint *b)
11307 {
11308   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
11309 
11310   switch (ex)
11311     {
11312       case ada_catch_exception:
11313         return (parse_and_eval_address ("e.full_name"));
11314         break;
11315 
11316       case ada_catch_exception_unhandled:
11317         return data->exception_info->unhandled_exception_name_addr ();
11318         break;
11319       
11320       case ada_catch_assert:
11321         return 0;  /* Exception name is not relevant in this case.  */
11322         break;
11323 
11324       default:
11325         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11326         break;
11327     }
11328 
11329   return 0; /* Should never be reached.  */
11330 }
11331 
11332 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
11333    any error that ada_exception_name_addr_1 might cause to be thrown.
11334    When an error is intercepted, a warning with the error message is printed,
11335    and zero is returned.  */
11336 
11337 static CORE_ADDR
11338 ada_exception_name_addr (enum ada_exception_catchpoint_kind ex,
11339                          struct breakpoint *b)
11340 {
11341   volatile struct gdb_exception e;
11342   CORE_ADDR result = 0;
11343 
11344   TRY_CATCH (e, RETURN_MASK_ERROR)
11345     {
11346       result = ada_exception_name_addr_1 (ex, b);
11347     }
11348 
11349   if (e.reason < 0)
11350     {
11351       warning (_("failed to get exception name: %s"), e.message);
11352       return 0;
11353     }
11354 
11355   return result;
11356 }
11357 
11358 static char *ada_exception_catchpoint_cond_string (const char *excep_string);
11359 
11360 /* Ada catchpoints.
11361 
11362    In the case of catchpoints on Ada exceptions, the catchpoint will
11363    stop the target on every exception the program throws.  When a user
11364    specifies the name of a specific exception, we translate this
11365    request into a condition expression (in text form), and then parse
11366    it into an expression stored in each of the catchpoint's locations.
11367    We then use this condition to check whether the exception that was
11368    raised is the one the user is interested in.  If not, then the
11369    target is resumed again.  We store the name of the requested
11370    exception, in order to be able to re-set the condition expression
11371    when symbols change.  */
11372 
11373 /* An instance of this type is used to represent an Ada catchpoint
11374    breakpoint location.  It includes a "struct bp_location" as a kind
11375    of base class; users downcast to "struct bp_location *" when
11376    needed.  */
11377 
11378 struct ada_catchpoint_location
11379 {
11380   /* The base class.  */
11381   struct bp_location base;
11382 
11383   /* The condition that checks whether the exception that was raised
11384      is the specific exception the user specified on catchpoint
11385      creation.  */
11386   struct expression *excep_cond_expr;
11387 };
11388 
11389 /* Implement the DTOR method in the bp_location_ops structure for all
11390    Ada exception catchpoint kinds.  */
11391 
11392 static void
11393 ada_catchpoint_location_dtor (struct bp_location *bl)
11394 {
11395   struct ada_catchpoint_location *al = (struct ada_catchpoint_location *) bl;
11396 
11397   xfree (al->excep_cond_expr);
11398 }
11399 
11400 /* The vtable to be used in Ada catchpoint locations.  */
11401 
11402 static const struct bp_location_ops ada_catchpoint_location_ops =
11403 {
11404   ada_catchpoint_location_dtor
11405 };
11406 
11407 /* An instance of this type is used to represent an Ada catchpoint.
11408    It includes a "struct breakpoint" as a kind of base class; users
11409    downcast to "struct breakpoint *" when needed.  */
11410 
11411 struct ada_catchpoint
11412 {
11413   /* The base class.  */
11414   struct breakpoint base;
11415 
11416   /* The name of the specific exception the user specified.  */
11417   char *excep_string;
11418 };
11419 
11420 /* Parse the exception condition string in the context of each of the
11421    catchpoint's locations, and store them for later evaluation.  */
11422 
11423 static void
11424 create_excep_cond_exprs (struct ada_catchpoint *c)
11425 {
11426   struct cleanup *old_chain;
11427   struct bp_location *bl;
11428   char *cond_string;
11429 
11430   /* Nothing to do if there's no specific exception to catch.  */
11431   if (c->excep_string == NULL)
11432     return;
11433 
11434   /* Same if there are no locations... */
11435   if (c->base.loc == NULL)
11436     return;
11437 
11438   /* Compute the condition expression in text form, from the specific
11439      expection we want to catch.  */
11440   cond_string = ada_exception_catchpoint_cond_string (c->excep_string);
11441   old_chain = make_cleanup (xfree, cond_string);
11442 
11443   /* Iterate over all the catchpoint's locations, and parse an
11444      expression for each.  */
11445   for (bl = c->base.loc; bl != NULL; bl = bl->next)
11446     {
11447       struct ada_catchpoint_location *ada_loc
11448         = (struct ada_catchpoint_location *) bl;
11449       struct expression *exp = NULL;
11450 
11451       if (!bl->shlib_disabled)
11452         {
11453           volatile struct gdb_exception e;
11454           const char *s;
11455 
11456           s = cond_string;
11457           TRY_CATCH (e, RETURN_MASK_ERROR)
11458             {
11459               exp = parse_exp_1 (&s, bl->address,
11460                                  block_for_pc (bl->address), 0);
11461             }
11462           if (e.reason < 0)
11463             warning (_("failed to reevaluate internal exception condition "
11464                        "for catchpoint %d: %s"),
11465                      c->base.number, e.message);
11466         }
11467 
11468       ada_loc->excep_cond_expr = exp;
11469     }
11470 
11471   do_cleanups (old_chain);
11472 }
11473 
11474 /* Implement the DTOR method in the breakpoint_ops structure for all
11475    exception catchpoint kinds.  */
11476 
11477 static void
11478 dtor_exception (enum ada_exception_catchpoint_kind ex, struct breakpoint *b)
11479 {
11480   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11481 
11482   xfree (c->excep_string);
11483 
11484   bkpt_breakpoint_ops.dtor (b);
11485 }
11486 
11487 /* Implement the ALLOCATE_LOCATION method in the breakpoint_ops
11488    structure for all exception catchpoint kinds.  */
11489 
11490 static struct bp_location *
11491 allocate_location_exception (enum ada_exception_catchpoint_kind ex,
11492                              struct breakpoint *self)
11493 {
11494   struct ada_catchpoint_location *loc;
11495 
11496   loc = XNEW (struct ada_catchpoint_location);
11497   init_bp_location (&loc->base, &ada_catchpoint_location_ops, self);
11498   loc->excep_cond_expr = NULL;
11499   return &loc->base;
11500 }
11501 
11502 /* Implement the RE_SET method in the breakpoint_ops structure for all
11503    exception catchpoint kinds.  */
11504 
11505 static void
11506 re_set_exception (enum ada_exception_catchpoint_kind ex, struct breakpoint *b)
11507 {
11508   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11509 
11510   /* Call the base class's method.  This updates the catchpoint's
11511      locations.  */
11512   bkpt_breakpoint_ops.re_set (b);
11513 
11514   /* Reparse the exception conditional expressions.  One for each
11515      location.  */
11516   create_excep_cond_exprs (c);
11517 }
11518 
11519 /* Returns true if we should stop for this breakpoint hit.  If the
11520    user specified a specific exception, we only want to cause a stop
11521    if the program thrown that exception.  */
11522 
11523 static int
11524 should_stop_exception (const struct bp_location *bl)
11525 {
11526   struct ada_catchpoint *c = (struct ada_catchpoint *) bl->owner;
11527   const struct ada_catchpoint_location *ada_loc
11528     = (const struct ada_catchpoint_location *) bl;
11529   volatile struct gdb_exception ex;
11530   int stop;
11531 
11532   /* With no specific exception, should always stop.  */
11533   if (c->excep_string == NULL)
11534     return 1;
11535 
11536   if (ada_loc->excep_cond_expr == NULL)
11537     {
11538       /* We will have a NULL expression if back when we were creating
11539          the expressions, this location's had failed to parse.  */
11540       return 1;
11541     }
11542 
11543   stop = 1;
11544   TRY_CATCH (ex, RETURN_MASK_ALL)
11545     {
11546       struct value *mark;
11547 
11548       mark = value_mark ();
11549       stop = value_true (evaluate_expression (ada_loc->excep_cond_expr));
11550       value_free_to_mark (mark);
11551     }
11552   if (ex.reason < 0)
11553     exception_fprintf (gdb_stderr, ex,
11554                        _("Error in testing exception condition:\n"));
11555   return stop;
11556 }
11557 
11558 /* Implement the CHECK_STATUS method in the breakpoint_ops structure
11559    for all exception catchpoint kinds.  */
11560 
11561 static void
11562 check_status_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
11563 {
11564   bs->stop = should_stop_exception (bs->bp_location_at);
11565 }
11566 
11567 /* Implement the PRINT_IT method in the breakpoint_ops structure
11568    for all exception catchpoint kinds.  */
11569 
11570 static enum print_stop_action
11571 print_it_exception (enum ada_exception_catchpoint_kind ex, bpstat bs)
11572 {
11573   struct ui_out *uiout = current_uiout;
11574   struct breakpoint *b = bs->breakpoint_at;
11575 
11576   annotate_catchpoint (b->number);
11577 
11578   if (ui_out_is_mi_like_p (uiout))
11579     {
11580       ui_out_field_string (uiout, "reason",
11581                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11582       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11583     }
11584 
11585   ui_out_text (uiout,
11586                b->disposition == disp_del ? "\nTemporary catchpoint "
11587                                           : "\nCatchpoint ");
11588   ui_out_field_int (uiout, "bkptno", b->number);
11589   ui_out_text (uiout, ", ");
11590 
11591   switch (ex)
11592     {
11593       case ada_catch_exception:
11594       case ada_catch_exception_unhandled:
11595         {
11596           const CORE_ADDR addr = ada_exception_name_addr (ex, b);
11597           char exception_name[256];
11598 
11599           if (addr != 0)
11600             {
11601               read_memory (addr, (gdb_byte *) exception_name,
11602                            sizeof (exception_name) - 1);
11603               exception_name [sizeof (exception_name) - 1] = '\0';
11604             }
11605           else
11606             {
11607               /* For some reason, we were unable to read the exception
11608                  name.  This could happen if the Runtime was compiled
11609                  without debugging info, for instance.  In that case,
11610                  just replace the exception name by the generic string
11611                  "exception" - it will read as "an exception" in the
11612                  notification we are about to print.  */
11613               memcpy (exception_name, "exception", sizeof ("exception"));
11614             }
11615           /* In the case of unhandled exception breakpoints, we print
11616              the exception name as "unhandled EXCEPTION_NAME", to make
11617              it clearer to the user which kind of catchpoint just got
11618              hit.  We used ui_out_text to make sure that this extra
11619              info does not pollute the exception name in the MI case.  */
11620           if (ex == ada_catch_exception_unhandled)
11621             ui_out_text (uiout, "unhandled ");
11622           ui_out_field_string (uiout, "exception-name", exception_name);
11623         }
11624         break;
11625       case ada_catch_assert:
11626         /* In this case, the name of the exception is not really
11627            important.  Just print "failed assertion" to make it clearer
11628            that his program just hit an assertion-failure catchpoint.
11629            We used ui_out_text because this info does not belong in
11630            the MI output.  */
11631         ui_out_text (uiout, "failed assertion");
11632         break;
11633     }
11634   ui_out_text (uiout, " at ");
11635   ada_find_printable_frame (get_current_frame ());
11636 
11637   return PRINT_SRC_AND_LOC;
11638 }
11639 
11640 /* Implement the PRINT_ONE method in the breakpoint_ops structure
11641    for all exception catchpoint kinds.  */
11642 
11643 static void
11644 print_one_exception (enum ada_exception_catchpoint_kind ex,
11645                      struct breakpoint *b, struct bp_location **last_loc)
11646 { 
11647   struct ui_out *uiout = current_uiout;
11648   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11649   struct value_print_options opts;
11650 
11651   get_user_print_options (&opts);
11652   if (opts.addressprint)
11653     {
11654       annotate_field (4);
11655       ui_out_field_core_addr (uiout, "addr", b->loc->gdbarch, b->loc->address);
11656     }
11657 
11658   annotate_field (5);
11659   *last_loc = b->loc;
11660   switch (ex)
11661     {
11662       case ada_catch_exception:
11663         if (c->excep_string != NULL)
11664           {
11665             char *msg = xstrprintf (_("`%s' Ada exception"), c->excep_string);
11666 
11667             ui_out_field_string (uiout, "what", msg);
11668             xfree (msg);
11669           }
11670         else
11671           ui_out_field_string (uiout, "what", "all Ada exceptions");
11672         
11673         break;
11674 
11675       case ada_catch_exception_unhandled:
11676         ui_out_field_string (uiout, "what", "unhandled Ada exceptions");
11677         break;
11678       
11679       case ada_catch_assert:
11680         ui_out_field_string (uiout, "what", "failed Ada assertions");
11681         break;
11682 
11683       default:
11684         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11685         break;
11686     }
11687 }
11688 
11689 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
11690    for all exception catchpoint kinds.  */
11691 
11692 static void
11693 print_mention_exception (enum ada_exception_catchpoint_kind ex,
11694                          struct breakpoint *b)
11695 {
11696   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11697   struct ui_out *uiout = current_uiout;
11698 
11699   ui_out_text (uiout, b->disposition == disp_del ? _("Temporary catchpoint ")
11700                                                  : _("Catchpoint "));
11701   ui_out_field_int (uiout, "bkptno", b->number);
11702   ui_out_text (uiout, ": ");
11703 
11704   switch (ex)
11705     {
11706       case ada_catch_exception:
11707         if (c->excep_string != NULL)
11708           {
11709             char *info = xstrprintf (_("`%s' Ada exception"), c->excep_string);
11710             struct cleanup *old_chain = make_cleanup (xfree, info);
11711 
11712             ui_out_text (uiout, info);
11713             do_cleanups (old_chain);
11714           }
11715         else
11716           ui_out_text (uiout, _("all Ada exceptions"));
11717         break;
11718 
11719       case ada_catch_exception_unhandled:
11720         ui_out_text (uiout, _("unhandled Ada exceptions"));
11721         break;
11722       
11723       case ada_catch_assert:
11724         ui_out_text (uiout, _("failed Ada assertions"));
11725         break;
11726 
11727       default:
11728         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11729         break;
11730     }
11731 }
11732 
11733 /* Implement the PRINT_RECREATE method in the breakpoint_ops structure
11734    for all exception catchpoint kinds.  */
11735 
11736 static void
11737 print_recreate_exception (enum ada_exception_catchpoint_kind ex,
11738                           struct breakpoint *b, struct ui_file *fp)
11739 {
11740   struct ada_catchpoint *c = (struct ada_catchpoint *) b;
11741 
11742   switch (ex)
11743     {
11744       case ada_catch_exception:
11745         fprintf_filtered (fp, "catch exception");
11746         if (c->excep_string != NULL)
11747           fprintf_filtered (fp, " %s", c->excep_string);
11748         break;
11749 
11750       case ada_catch_exception_unhandled:
11751         fprintf_filtered (fp, "catch exception unhandled");
11752         break;
11753 
11754       case ada_catch_assert:
11755         fprintf_filtered (fp, "catch assert");
11756         break;
11757 
11758       default:
11759         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
11760     }
11761   print_recreate_thread (b, fp);
11762 }
11763 
11764 /* Virtual table for "catch exception" breakpoints.  */
11765 
11766 static void
11767 dtor_catch_exception (struct breakpoint *b)
11768 {
11769   dtor_exception (ada_catch_exception, b);
11770 }
11771 
11772 static struct bp_location *
11773 allocate_location_catch_exception (struct breakpoint *self)
11774 {
11775   return allocate_location_exception (ada_catch_exception, self);
11776 }
11777 
11778 static void
11779 re_set_catch_exception (struct breakpoint *b)
11780 {
11781   re_set_exception (ada_catch_exception, b);
11782 }
11783 
11784 static void
11785 check_status_catch_exception (bpstat bs)
11786 {
11787   check_status_exception (ada_catch_exception, bs);
11788 }
11789 
11790 static enum print_stop_action
11791 print_it_catch_exception (bpstat bs)
11792 {
11793   return print_it_exception (ada_catch_exception, bs);
11794 }
11795 
11796 static void
11797 print_one_catch_exception (struct breakpoint *b, struct bp_location **last_loc)
11798 {
11799   print_one_exception (ada_catch_exception, b, last_loc);
11800 }
11801 
11802 static void
11803 print_mention_catch_exception (struct breakpoint *b)
11804 {
11805   print_mention_exception (ada_catch_exception, b);
11806 }
11807 
11808 static void
11809 print_recreate_catch_exception (struct breakpoint *b, struct ui_file *fp)
11810 {
11811   print_recreate_exception (ada_catch_exception, b, fp);
11812 }
11813 
11814 static struct breakpoint_ops catch_exception_breakpoint_ops;
11815 
11816 /* Virtual table for "catch exception unhandled" breakpoints.  */
11817 
11818 static void
11819 dtor_catch_exception_unhandled (struct breakpoint *b)
11820 {
11821   dtor_exception (ada_catch_exception_unhandled, b);
11822 }
11823 
11824 static struct bp_location *
11825 allocate_location_catch_exception_unhandled (struct breakpoint *self)
11826 {
11827   return allocate_location_exception (ada_catch_exception_unhandled, self);
11828 }
11829 
11830 static void
11831 re_set_catch_exception_unhandled (struct breakpoint *b)
11832 {
11833   re_set_exception (ada_catch_exception_unhandled, b);
11834 }
11835 
11836 static void
11837 check_status_catch_exception_unhandled (bpstat bs)
11838 {
11839   check_status_exception (ada_catch_exception_unhandled, bs);
11840 }
11841 
11842 static enum print_stop_action
11843 print_it_catch_exception_unhandled (bpstat bs)
11844 {
11845   return print_it_exception (ada_catch_exception_unhandled, bs);
11846 }
11847 
11848 static void
11849 print_one_catch_exception_unhandled (struct breakpoint *b,
11850                                      struct bp_location **last_loc)
11851 {
11852   print_one_exception (ada_catch_exception_unhandled, b, last_loc);
11853 }
11854 
11855 static void
11856 print_mention_catch_exception_unhandled (struct breakpoint *b)
11857 {
11858   print_mention_exception (ada_catch_exception_unhandled, b);
11859 }
11860 
11861 static void
11862 print_recreate_catch_exception_unhandled (struct breakpoint *b,
11863                                           struct ui_file *fp)
11864 {
11865   print_recreate_exception (ada_catch_exception_unhandled, b, fp);
11866 }
11867 
11868 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops;
11869 
11870 /* Virtual table for "catch assert" breakpoints.  */
11871 
11872 static void
11873 dtor_catch_assert (struct breakpoint *b)
11874 {
11875   dtor_exception (ada_catch_assert, b);
11876 }
11877 
11878 static struct bp_location *
11879 allocate_location_catch_assert (struct breakpoint *self)
11880 {
11881   return allocate_location_exception (ada_catch_assert, self);
11882 }
11883 
11884 static void
11885 re_set_catch_assert (struct breakpoint *b)
11886 {
11887   re_set_exception (ada_catch_assert, b);
11888 }
11889 
11890 static void
11891 check_status_catch_assert (bpstat bs)
11892 {
11893   check_status_exception (ada_catch_assert, bs);
11894 }
11895 
11896 static enum print_stop_action
11897 print_it_catch_assert (bpstat bs)
11898 {
11899   return print_it_exception (ada_catch_assert, bs);
11900 }
11901 
11902 static void
11903 print_one_catch_assert (struct breakpoint *b, struct bp_location **last_loc)
11904 {
11905   print_one_exception (ada_catch_assert, b, last_loc);
11906 }
11907 
11908 static void
11909 print_mention_catch_assert (struct breakpoint *b)
11910 {
11911   print_mention_exception (ada_catch_assert, b);
11912 }
11913 
11914 static void
11915 print_recreate_catch_assert (struct breakpoint *b, struct ui_file *fp)
11916 {
11917   print_recreate_exception (ada_catch_assert, b, fp);
11918 }
11919 
11920 static struct breakpoint_ops catch_assert_breakpoint_ops;
11921 
11922 /* Return a newly allocated copy of the first space-separated token
11923    in ARGSP, and then adjust ARGSP to point immediately after that
11924    token.
11925 
11926    Return NULL if ARGPS does not contain any more tokens.  */
11927 
11928 static char *
11929 ada_get_next_arg (char **argsp)
11930 {
11931   char *args = *argsp;
11932   char *end;
11933   char *result;
11934 
11935   args = skip_spaces (args);
11936   if (args[0] == '\0')
11937     return NULL; /* No more arguments.  */
11938   
11939   /* Find the end of the current argument.  */
11940 
11941   end = skip_to_space (args);
11942 
11943   /* Adjust ARGSP to point to the start of the next argument.  */
11944 
11945   *argsp = end;
11946 
11947   /* Make a copy of the current argument and return it.  */
11948 
11949   result = xmalloc (end - args + 1);
11950   strncpy (result, args, end - args);
11951   result[end - args] = '\0';
11952   
11953   return result;
11954 }
11955 
11956 /* Split the arguments specified in a "catch exception" command.  
11957    Set EX to the appropriate catchpoint type.
11958    Set EXCEP_STRING to the name of the specific exception if
11959    specified by the user.
11960    If a condition is found at the end of the arguments, the condition
11961    expression is stored in COND_STRING (memory must be deallocated
11962    after use).  Otherwise COND_STRING is set to NULL.  */
11963 
11964 static void
11965 catch_ada_exception_command_split (char *args,
11966                                    enum ada_exception_catchpoint_kind *ex,
11967                                    char **excep_string,
11968                                    char **cond_string)
11969 {
11970   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
11971   char *exception_name;
11972   char *cond = NULL;
11973 
11974   exception_name = ada_get_next_arg (&args);
11975   if (exception_name != NULL && strcmp (exception_name, "if") == 0)
11976     {
11977       /* This is not an exception name; this is the start of a condition
11978          expression for a catchpoint on all exceptions.  So, "un-get"
11979          this token, and set exception_name to NULL.  */
11980       xfree (exception_name);
11981       exception_name = NULL;
11982       args -= 2;
11983     }
11984   make_cleanup (xfree, exception_name);
11985 
11986   /* Check to see if we have a condition.  */
11987 
11988   args = skip_spaces (args);
11989   if (strncmp (args, "if", 2) == 0
11990       && (isspace (args[2]) || args[2] == '\0'))
11991     {
11992       args += 2;
11993       args = skip_spaces (args);
11994 
11995       if (args[0] == '\0')
11996         error (_("Condition missing after `if' keyword"));
11997       cond = xstrdup (args);
11998       make_cleanup (xfree, cond);
11999 
12000       args += strlen (args);
12001     }
12002 
12003   /* Check that we do not have any more arguments.  Anything else
12004      is unexpected.  */
12005 
12006   if (args[0] != '\0')
12007     error (_("Junk at end of expression"));
12008 
12009   discard_cleanups (old_chain);
12010 
12011   if (exception_name == NULL)
12012     {
12013       /* Catch all exceptions.  */
12014       *ex = ada_catch_exception;
12015       *excep_string = NULL;
12016     }
12017   else if (strcmp (exception_name, "unhandled") == 0)
12018     {
12019       /* Catch unhandled exceptions.  */
12020       *ex = ada_catch_exception_unhandled;
12021       *excep_string = NULL;
12022     }
12023   else
12024     {
12025       /* Catch a specific exception.  */
12026       *ex = ada_catch_exception;
12027       *excep_string = exception_name;
12028     }
12029   *cond_string = cond;
12030 }
12031 
12032 /* Return the name of the symbol on which we should break in order to
12033    implement a catchpoint of the EX kind.  */
12034 
12035 static const char *
12036 ada_exception_sym_name (enum ada_exception_catchpoint_kind ex)
12037 {
12038   struct ada_inferior_data *data = get_ada_inferior_data (current_inferior ());
12039 
12040   gdb_assert (data->exception_info != NULL);
12041 
12042   switch (ex)
12043     {
12044       case ada_catch_exception:
12045         return (data->exception_info->catch_exception_sym);
12046         break;
12047       case ada_catch_exception_unhandled:
12048         return (data->exception_info->catch_exception_unhandled_sym);
12049         break;
12050       case ada_catch_assert:
12051         return (data->exception_info->catch_assert_sym);
12052         break;
12053       default:
12054         internal_error (__FILE__, __LINE__,
12055                         _("unexpected catchpoint kind (%d)"), ex);
12056     }
12057 }
12058 
12059 /* Return the breakpoint ops "virtual table" used for catchpoints
12060    of the EX kind.  */
12061 
12062 static const struct breakpoint_ops *
12063 ada_exception_breakpoint_ops (enum ada_exception_catchpoint_kind ex)
12064 {
12065   switch (ex)
12066     {
12067       case ada_catch_exception:
12068         return (&catch_exception_breakpoint_ops);
12069         break;
12070       case ada_catch_exception_unhandled:
12071         return (&catch_exception_unhandled_breakpoint_ops);
12072         break;
12073       case ada_catch_assert:
12074         return (&catch_assert_breakpoint_ops);
12075         break;
12076       default:
12077         internal_error (__FILE__, __LINE__,
12078                         _("unexpected catchpoint kind (%d)"), ex);
12079     }
12080 }
12081 
12082 /* Return the condition that will be used to match the current exception
12083    being raised with the exception that the user wants to catch.  This
12084    assumes that this condition is used when the inferior just triggered
12085    an exception catchpoint.
12086    
12087    The string returned is a newly allocated string that needs to be
12088    deallocated later.  */
12089 
12090 static char *
12091 ada_exception_catchpoint_cond_string (const char *excep_string)
12092 {
12093   int i;
12094 
12095   /* The standard exceptions are a special case.  They are defined in
12096      runtime units that have been compiled without debugging info; if
12097      EXCEP_STRING is the not-fully-qualified name of a standard
12098      exception (e.g. "constraint_error") then, during the evaluation
12099      of the condition expression, the symbol lookup on this name would
12100      *not* return this standard exception.  The catchpoint condition
12101      may then be set only on user-defined exceptions which have the
12102      same not-fully-qualified name (e.g. my_package.constraint_error).
12103 
12104      To avoid this unexcepted behavior, these standard exceptions are
12105      systematically prefixed by "standard".  This means that "catch
12106      exception constraint_error" is rewritten into "catch exception
12107      standard.constraint_error".
12108 
12109      If an exception named contraint_error is defined in another package of
12110      the inferior program, then the only way to specify this exception as a
12111      breakpoint condition is to use its fully-qualified named:
12112      e.g. my_package.constraint_error.  */
12113 
12114   for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
12115     {
12116       if (strcmp (standard_exc [i], excep_string) == 0)
12117         {
12118           return xstrprintf ("long_integer (e) = long_integer (&standard.%s)",
12119                              excep_string);
12120         }
12121     }
12122   return xstrprintf ("long_integer (e) = long_integer (&%s)", excep_string);
12123 }
12124 
12125 /* Return the symtab_and_line that should be used to insert an exception
12126    catchpoint of the TYPE kind.
12127 
12128    EXCEP_STRING should contain the name of a specific exception that
12129    the catchpoint should catch, or NULL otherwise.
12130 
12131    ADDR_STRING returns the name of the function where the real
12132    breakpoint that implements the catchpoints is set, depending on the
12133    type of catchpoint we need to create.  */
12134 
12135 static struct symtab_and_line
12136 ada_exception_sal (enum ada_exception_catchpoint_kind ex, char *excep_string,
12137                    char **addr_string, const struct breakpoint_ops **ops)
12138 {
12139   const char *sym_name;
12140   struct symbol *sym;
12141 
12142   /* First, find out which exception support info to use.  */
12143   ada_exception_support_info_sniffer ();
12144 
12145   /* Then lookup the function on which we will break in order to catch
12146      the Ada exceptions requested by the user.  */
12147   sym_name = ada_exception_sym_name (ex);
12148   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
12149 
12150   /* We can assume that SYM is not NULL at this stage.  If the symbol
12151      did not exist, ada_exception_support_info_sniffer would have
12152      raised an exception.
12153 
12154      Also, ada_exception_support_info_sniffer should have already
12155      verified that SYM is a function symbol.  */
12156   gdb_assert (sym != NULL);
12157   gdb_assert (SYMBOL_CLASS (sym) == LOC_BLOCK);
12158 
12159   /* Set ADDR_STRING.  */
12160   *addr_string = xstrdup (sym_name);
12161 
12162   /* Set OPS.  */
12163   *ops = ada_exception_breakpoint_ops (ex);
12164 
12165   return find_function_start_sal (sym, 1);
12166 }
12167 
12168 /* Create an Ada exception catchpoint.
12169 
12170    EX_KIND is the kind of exception catchpoint to be created.
12171 
12172    EXCEPT_STRING, if not NULL, indicates the name of the exception
12173    to which this catchpoint applies.  If NULL, this catchpoint is
12174    expected to trigger for all exceptions.
12175 
12176    COND_STRING, if not NULL, is the catchpoint condition.
12177 
12178    TEMPFLAG, if nonzero, means that the underlying breakpoint
12179    should be temporary.
12180 
12181    FROM_TTY is the usual argument passed to all commands implementations.  */
12182 
12183 void
12184 create_ada_exception_catchpoint (struct gdbarch *gdbarch,
12185                                  enum ada_exception_catchpoint_kind ex_kind,
12186                                  char *excep_string,
12187                                  char *cond_string,
12188                                  int tempflag,
12189                                  int disabled,
12190                                  int from_tty)
12191 {
12192   struct ada_catchpoint *c;
12193   char *addr_string = NULL;
12194   const struct breakpoint_ops *ops = NULL;
12195   struct symtab_and_line sal
12196     = ada_exception_sal (ex_kind, excep_string, &addr_string, &ops);
12197 
12198   c = XNEW (struct ada_catchpoint);
12199   init_ada_exception_breakpoint (&c->base, gdbarch, sal, addr_string,
12200                                  ops, tempflag, disabled, from_tty);
12201   c->excep_string = excep_string;
12202   create_excep_cond_exprs (c);
12203   if (cond_string != NULL)
12204     set_breakpoint_condition (&c->base, cond_string, from_tty);
12205   install_breakpoint (0, &c->base, 1);
12206 }
12207 
12208 /* Implement the "catch exception" command.  */
12209 
12210 static void
12211 catch_ada_exception_command (char *arg, int from_tty,
12212                              struct cmd_list_element *command)
12213 {
12214   struct gdbarch *gdbarch = get_current_arch ();
12215   int tempflag;
12216   enum ada_exception_catchpoint_kind ex_kind;
12217   char *excep_string = NULL;
12218   char *cond_string = NULL;
12219 
12220   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12221 
12222   if (!arg)
12223     arg = "";
12224   catch_ada_exception_command_split (arg, &ex_kind, &excep_string,
12225                                      &cond_string);
12226   create_ada_exception_catchpoint (gdbarch, ex_kind,
12227                                    excep_string, cond_string,
12228                                    tempflag, 1 /* enabled */,
12229                                    from_tty);
12230 }
12231 
12232 /* Split the arguments specified in a "catch assert" command.
12233 
12234    ARGS contains the command's arguments (or the empty string if
12235    no arguments were passed).
12236 
12237    If ARGS contains a condition, set COND_STRING to that condition
12238    (the memory needs to be deallocated after use).  */
12239 
12240 static void
12241 catch_ada_assert_command_split (char *args, char **cond_string)
12242 {
12243   args = skip_spaces (args);
12244 
12245   /* Check whether a condition was provided.  */
12246   if (strncmp (args, "if", 2) == 0
12247       && (isspace (args[2]) || args[2] == '\0'))
12248     {
12249       args += 2;
12250       args = skip_spaces (args);
12251       if (args[0] == '\0')
12252         error (_("condition missing after `if' keyword"));
12253       *cond_string = xstrdup (args);
12254     }
12255 
12256   /* Otherwise, there should be no other argument at the end of
12257      the command.  */
12258   else if (args[0] != '\0')
12259     error (_("Junk at end of arguments."));
12260 }
12261 
12262 /* Implement the "catch assert" command.  */
12263 
12264 static void
12265 catch_assert_command (char *arg, int from_tty,
12266                       struct cmd_list_element *command)
12267 {
12268   struct gdbarch *gdbarch = get_current_arch ();
12269   int tempflag;
12270   char *cond_string = NULL;
12271 
12272   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12273 
12274   if (!arg)
12275     arg = "";
12276   catch_ada_assert_command_split (arg, &cond_string);
12277   create_ada_exception_catchpoint (gdbarch, ada_catch_assert,
12278                                    NULL, cond_string,
12279                                    tempflag, 1 /* enabled */,
12280                                    from_tty);
12281 }
12282                                 /* Operators */
12283 /* Information about operators given special treatment in functions
12284    below.  */
12285 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>).  */
12286 
12287 #define ADA_OPERATORS \
12288     OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
12289     OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
12290     OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
12291     OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
12292     OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
12293     OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
12294     OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
12295     OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
12296     OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
12297     OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
12298     OP_DEFN (OP_ATR_POS, 1, 2, 0) \
12299     OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
12300     OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
12301     OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
12302     OP_DEFN (UNOP_QUAL, 3, 1, 0) \
12303     OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
12304     OP_DEFN (OP_OTHERS, 1, 1, 0) \
12305     OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
12306     OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
12307 
12308 static void
12309 ada_operator_length (const struct expression *exp, int pc, int *oplenp,
12310                      int *argsp)
12311 {
12312   switch (exp->elts[pc - 1].opcode)
12313     {
12314     default:
12315       operator_length_standard (exp, pc, oplenp, argsp);
12316       break;
12317 
12318 #define OP_DEFN(op, len, args, binop) \
12319     case op: *oplenp = len; *argsp = args; break;
12320       ADA_OPERATORS;
12321 #undef OP_DEFN
12322 
12323     case OP_AGGREGATE:
12324       *oplenp = 3;
12325       *argsp = longest_to_int (exp->elts[pc - 2].longconst);
12326       break;
12327 
12328     case OP_CHOICES:
12329       *oplenp = 3;
12330       *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
12331       break;
12332     }
12333 }
12334 
12335 /* Implementation of the exp_descriptor method operator_check.  */
12336 
12337 static int
12338 ada_operator_check (struct expression *exp, int pos,
12339                     int (*objfile_func) (struct objfile *objfile, void *data),
12340                     void *data)
12341 {
12342   const union exp_element *const elts = exp->elts;
12343   struct type *type = NULL;
12344 
12345   switch (elts[pos].opcode)
12346     {
12347       case UNOP_IN_RANGE:
12348       case UNOP_QUAL:
12349         type = elts[pos + 1].type;
12350         break;
12351 
12352       default:
12353         return operator_check_standard (exp, pos, objfile_func, data);
12354     }
12355 
12356   /* Invoke callbacks for TYPE and OBJFILE if they were set as non-NULL.  */
12357 
12358   if (type && TYPE_OBJFILE (type)
12359       && (*objfile_func) (TYPE_OBJFILE (type), data))
12360     return 1;
12361 
12362   return 0;
12363 }
12364 
12365 static char *
12366 ada_op_name (enum exp_opcode opcode)
12367 {
12368   switch (opcode)
12369     {
12370     default:
12371       return op_name_standard (opcode);
12372 
12373 #define OP_DEFN(op, len, args, binop) case op: return #op;
12374       ADA_OPERATORS;
12375 #undef OP_DEFN
12376 
12377     case OP_AGGREGATE:
12378       return "OP_AGGREGATE";
12379     case OP_CHOICES:
12380       return "OP_CHOICES";
12381     case OP_NAME:
12382       return "OP_NAME";
12383     }
12384 }
12385 
12386 /* As for operator_length, but assumes PC is pointing at the first
12387    element of the operator, and gives meaningful results only for the 
12388    Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise.  */
12389 
12390 static void
12391 ada_forward_operator_length (struct expression *exp, int pc,
12392                              int *oplenp, int *argsp)
12393 {
12394   switch (exp->elts[pc].opcode)
12395     {
12396     default:
12397       *oplenp = *argsp = 0;
12398       break;
12399 
12400 #define OP_DEFN(op, len, args, binop) \
12401     case op: *oplenp = len; *argsp = args; break;
12402       ADA_OPERATORS;
12403 #undef OP_DEFN
12404 
12405     case OP_AGGREGATE:
12406       *oplenp = 3;
12407       *argsp = longest_to_int (exp->elts[pc + 1].longconst);
12408       break;
12409 
12410     case OP_CHOICES:
12411       *oplenp = 3;
12412       *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
12413       break;
12414 
12415     case OP_STRING:
12416     case OP_NAME:
12417       {
12418         int len = longest_to_int (exp->elts[pc + 1].longconst);
12419 
12420         *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
12421         *argsp = 0;
12422         break;
12423       }
12424     }
12425 }
12426 
12427 static int
12428 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
12429 {
12430   enum exp_opcode op = exp->elts[elt].opcode;
12431   int oplen, nargs;
12432   int pc = elt;
12433   int i;
12434 
12435   ada_forward_operator_length (exp, elt, &oplen, &nargs);
12436 
12437   switch (op)
12438     {
12439       /* Ada attributes ('Foo).  */
12440     case OP_ATR_FIRST:
12441     case OP_ATR_LAST:
12442     case OP_ATR_LENGTH:
12443     case OP_ATR_IMAGE:
12444     case OP_ATR_MAX:
12445     case OP_ATR_MIN:
12446     case OP_ATR_MODULUS:
12447     case OP_ATR_POS:
12448     case OP_ATR_SIZE:
12449     case OP_ATR_TAG:
12450     case OP_ATR_VAL:
12451       break;
12452 
12453     case UNOP_IN_RANGE:
12454     case UNOP_QUAL:
12455       /* XXX: gdb_sprint_host_address, type_sprint */
12456       fprintf_filtered (stream, _("Type @"));
12457       gdb_print_host_address (exp->elts[pc + 1].type, stream);
12458       fprintf_filtered (stream, " (");
12459       type_print (exp->elts[pc + 1].type, NULL, stream, 0);
12460       fprintf_filtered (stream, ")");
12461       break;
12462     case BINOP_IN_BOUNDS:
12463       fprintf_filtered (stream, " (%d)",
12464                         longest_to_int (exp->elts[pc + 2].longconst));
12465       break;
12466     case TERNOP_IN_RANGE:
12467       break;
12468 
12469     case OP_AGGREGATE:
12470     case OP_OTHERS:
12471     case OP_DISCRETE_RANGE:
12472     case OP_POSITIONAL:
12473     case OP_CHOICES:
12474       break;
12475 
12476     case OP_NAME:
12477     case OP_STRING:
12478       {
12479         char *name = &exp->elts[elt + 2].string;
12480         int len = longest_to_int (exp->elts[elt + 1].longconst);
12481 
12482         fprintf_filtered (stream, "Text: `%.*s'", len, name);
12483         break;
12484       }
12485 
12486     default:
12487       return dump_subexp_body_standard (exp, stream, elt);
12488     }
12489 
12490   elt += oplen;
12491   for (i = 0; i < nargs; i += 1)
12492     elt = dump_subexp (exp, stream, elt);
12493 
12494   return elt;
12495 }
12496 
12497 /* The Ada extension of print_subexp (q.v.).  */
12498 
12499 static void
12500 ada_print_subexp (struct expression *exp, int *pos,
12501                   struct ui_file *stream, enum precedence prec)
12502 {
12503   int oplen, nargs, i;
12504   int pc = *pos;
12505   enum exp_opcode op = exp->elts[pc].opcode;
12506 
12507   ada_forward_operator_length (exp, pc, &oplen, &nargs);
12508 
12509   *pos += oplen;
12510   switch (op)
12511     {
12512     default:
12513       *pos -= oplen;
12514       print_subexp_standard (exp, pos, stream, prec);
12515       return;
12516 
12517     case OP_VAR_VALUE:
12518       fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
12519       return;
12520 
12521     case BINOP_IN_BOUNDS:
12522       /* XXX: sprint_subexp */
12523       print_subexp (exp, pos, stream, PREC_SUFFIX);
12524       fputs_filtered (" in ", stream);
12525       print_subexp (exp, pos, stream, PREC_SUFFIX);
12526       fputs_filtered ("'range", stream);
12527       if (exp->elts[pc + 1].longconst > 1)
12528         fprintf_filtered (stream, "(%ld)",
12529                           (long) exp->elts[pc + 1].longconst);
12530       return;
12531 
12532     case TERNOP_IN_RANGE:
12533       if (prec >= PREC_EQUAL)
12534         fputs_filtered ("(", stream);
12535       /* XXX: sprint_subexp */
12536       print_subexp (exp, pos, stream, PREC_SUFFIX);
12537       fputs_filtered (" in ", stream);
12538       print_subexp (exp, pos, stream, PREC_EQUAL);
12539       fputs_filtered (" .. ", stream);
12540       print_subexp (exp, pos, stream, PREC_EQUAL);
12541       if (prec >= PREC_EQUAL)
12542         fputs_filtered (")", stream);
12543       return;
12544 
12545     case OP_ATR_FIRST:
12546     case OP_ATR_LAST:
12547     case OP_ATR_LENGTH:
12548     case OP_ATR_IMAGE:
12549     case OP_ATR_MAX:
12550     case OP_ATR_MIN:
12551     case OP_ATR_MODULUS:
12552     case OP_ATR_POS:
12553     case OP_ATR_SIZE:
12554     case OP_ATR_TAG:
12555     case OP_ATR_VAL:
12556       if (exp->elts[*pos].opcode == OP_TYPE)
12557         {
12558           if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
12559             LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0,
12560                            &type_print_raw_options);
12561           *pos += 3;
12562         }
12563       else
12564         print_subexp (exp, pos, stream, PREC_SUFFIX);
12565       fprintf_filtered (stream, "'%s", ada_attribute_name (op));
12566       if (nargs > 1)
12567         {
12568           int tem;
12569 
12570           for (tem = 1; tem < nargs; tem += 1)
12571             {
12572               fputs_filtered ((tem == 1) ? " (" : ", ", stream);
12573               print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
12574             }
12575           fputs_filtered (")", stream);
12576         }
12577       return;
12578 
12579     case UNOP_QUAL:
12580       type_print (exp->elts[pc + 1].type, "", stream, 0);
12581       fputs_filtered ("'(", stream);
12582       print_subexp (exp, pos, stream, PREC_PREFIX);
12583       fputs_filtered (")", stream);
12584       return;
12585 
12586     case UNOP_IN_RANGE:
12587       /* XXX: sprint_subexp */
12588       print_subexp (exp, pos, stream, PREC_SUFFIX);
12589       fputs_filtered (" in ", stream);
12590       LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0,
12591                      &type_print_raw_options);
12592       return;
12593 
12594     case OP_DISCRETE_RANGE:
12595       print_subexp (exp, pos, stream, PREC_SUFFIX);
12596       fputs_filtered ("..", stream);
12597       print_subexp (exp, pos, stream, PREC_SUFFIX);
12598       return;
12599 
12600     case OP_OTHERS:
12601       fputs_filtered ("others => ", stream);
12602       print_subexp (exp, pos, stream, PREC_SUFFIX);
12603       return;
12604 
12605     case OP_CHOICES:
12606       for (i = 0; i < nargs-1; i += 1)
12607         {
12608           if (i > 0)
12609             fputs_filtered ("|", stream);
12610           print_subexp (exp, pos, stream, PREC_SUFFIX);
12611         }
12612       fputs_filtered (" => ", stream);
12613       print_subexp (exp, pos, stream, PREC_SUFFIX);
12614       return;
12615       
12616     case OP_POSITIONAL:
12617       print_subexp (exp, pos, stream, PREC_SUFFIX);
12618       return;
12619 
12620     case OP_AGGREGATE:
12621       fputs_filtered ("(", stream);
12622       for (i = 0; i < nargs; i += 1)
12623         {
12624           if (i > 0)
12625             fputs_filtered (", ", stream);
12626           print_subexp (exp, pos, stream, PREC_SUFFIX);
12627         }
12628       fputs_filtered (")", stream);
12629       return;
12630     }
12631 }
12632 
12633 /* Table mapping opcodes into strings for printing operators
12634    and precedences of the operators.  */
12635 
12636 static const struct op_print ada_op_print_tab[] = {
12637   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
12638   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
12639   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
12640   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
12641   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
12642   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
12643   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
12644   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
12645   {"<=", BINOP_LEQ, PREC_ORDER, 0},
12646   {">=", BINOP_GEQ, PREC_ORDER, 0},
12647   {">", BINOP_GTR, PREC_ORDER, 0},
12648   {"<", BINOP_LESS, PREC_ORDER, 0},
12649   {">>", BINOP_RSH, PREC_SHIFT, 0},
12650   {"<<", BINOP_LSH, PREC_SHIFT, 0},
12651   {"+", BINOP_ADD, PREC_ADD, 0},
12652   {"-", BINOP_SUB, PREC_ADD, 0},
12653   {"&", BINOP_CONCAT, PREC_ADD, 0},
12654   {"*", BINOP_MUL, PREC_MUL, 0},
12655   {"/", BINOP_DIV, PREC_MUL, 0},
12656   {"rem", BINOP_REM, PREC_MUL, 0},
12657   {"mod", BINOP_MOD, PREC_MUL, 0},
12658   {"**", BINOP_EXP, PREC_REPEAT, 0},
12659   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
12660   {"-", UNOP_NEG, PREC_PREFIX, 0},
12661   {"+", UNOP_PLUS, PREC_PREFIX, 0},
12662   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
12663   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
12664   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
12665   {".all", UNOP_IND, PREC_SUFFIX, 1},
12666   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
12667   {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
12668   {NULL, 0, 0, 0}
12669 };
12670 
12671 enum ada_primitive_types {
12672   ada_primitive_type_int,
12673   ada_primitive_type_long,
12674   ada_primitive_type_short,
12675   ada_primitive_type_char,
12676   ada_primitive_type_float,
12677   ada_primitive_type_double,
12678   ada_primitive_type_void,
12679   ada_primitive_type_long_long,
12680   ada_primitive_type_long_double,
12681   ada_primitive_type_natural,
12682   ada_primitive_type_positive,
12683   ada_primitive_type_system_address,
12684   nr_ada_primitive_types
12685 };
12686 
12687 static void
12688 ada_language_arch_info (struct gdbarch *gdbarch,
12689                         struct language_arch_info *lai)
12690 {
12691   const struct builtin_type *builtin = builtin_type (gdbarch);
12692 
12693   lai->primitive_type_vector
12694     = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
12695                               struct type *);
12696 
12697   lai->primitive_type_vector [ada_primitive_type_int]
12698     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12699                          0, "integer");
12700   lai->primitive_type_vector [ada_primitive_type_long]
12701     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
12702                          0, "long_integer");
12703   lai->primitive_type_vector [ada_primitive_type_short]
12704     = arch_integer_type (gdbarch, gdbarch_short_bit (gdbarch),
12705                          0, "short_integer");
12706   lai->string_char_type
12707     = lai->primitive_type_vector [ada_primitive_type_char]
12708     = arch_integer_type (gdbarch, TARGET_CHAR_BIT, 0, "character");
12709   lai->primitive_type_vector [ada_primitive_type_float]
12710     = arch_float_type (gdbarch, gdbarch_float_bit (gdbarch),
12711                        "float", NULL);
12712   lai->primitive_type_vector [ada_primitive_type_double]
12713     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
12714                        "long_float", NULL);
12715   lai->primitive_type_vector [ada_primitive_type_long_long]
12716     = arch_integer_type (gdbarch, gdbarch_long_long_bit (gdbarch),
12717                          0, "long_long_integer");
12718   lai->primitive_type_vector [ada_primitive_type_long_double]
12719     = arch_float_type (gdbarch, gdbarch_double_bit (gdbarch),
12720                        "long_long_float", NULL);
12721   lai->primitive_type_vector [ada_primitive_type_natural]
12722     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12723                          0, "natural");
12724   lai->primitive_type_vector [ada_primitive_type_positive]
12725     = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
12726                          0, "positive");
12727   lai->primitive_type_vector [ada_primitive_type_void]
12728     = builtin->builtin_void;
12729 
12730   lai->primitive_type_vector [ada_primitive_type_system_address]
12731     = lookup_pointer_type (arch_type (gdbarch, TYPE_CODE_VOID, 1, "void"));
12732   TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
12733     = "system__address";
12734 
12735   lai->bool_type_symbol = NULL;
12736   lai->bool_type_default = builtin->builtin_bool;
12737 }
12738 
12739                                 /* Language vector */
12740 
12741 /* Not really used, but needed in the ada_language_defn.  */
12742 
12743 static void
12744 emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
12745 {
12746   ada_emit_char (c, type, stream, quoter, 1);
12747 }
12748 
12749 static int
12750 parse (void)
12751 {
12752   warnings_issued = 0;
12753   return ada_parse ();
12754 }
12755 
12756 static const struct exp_descriptor ada_exp_descriptor = {
12757   ada_print_subexp,
12758   ada_operator_length,
12759   ada_operator_check,
12760   ada_op_name,
12761   ada_dump_subexp_body,
12762   ada_evaluate_subexp
12763 };
12764 
12765 /* Implement the "la_get_symbol_name_cmp" language_defn method
12766    for Ada.  */
12767 
12768 static symbol_name_cmp_ftype
12769 ada_get_symbol_name_cmp (const char *lookup_name)
12770 {
12771   if (should_use_wild_match (lookup_name))
12772     return wild_match;
12773   else
12774     return compare_names;
12775 }
12776 
12777 /* Implement the "la_read_var_value" language_defn method for Ada.  */
12778 
12779 static struct value *
12780 ada_read_var_value (struct symbol *var, struct frame_info *frame)
12781 {
12782   struct block *frame_block = NULL;
12783   struct symbol *renaming_sym = NULL;
12784 
12785   /* The only case where default_read_var_value is not sufficient
12786      is when VAR is a renaming...  */
12787   if (frame)
12788     frame_block = get_frame_block (frame, NULL);
12789   if (frame_block)
12790     renaming_sym = ada_find_renaming_symbol (var, frame_block);
12791   if (renaming_sym != NULL)
12792     return ada_read_renaming_var_value (renaming_sym, frame_block);
12793 
12794   /* This is a typical case where we expect the default_read_var_value
12795      function to work.  */
12796   return default_read_var_value (var, frame);
12797 }
12798 
12799 const struct language_defn ada_language_defn = {
12800   "ada",                        /* Language name */
12801   language_ada,
12802   range_check_off,
12803   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
12804                                    that's not quite what this means.  */
12805   array_row_major,
12806   macro_expansion_no,
12807   &ada_exp_descriptor,
12808   parse,
12809   ada_error,
12810   resolve,
12811   ada_printchar,                /* Print a character constant */
12812   ada_printstr,                 /* Function to print string constant */
12813   emit_char,                    /* Function to print single char (not used) */
12814   ada_print_type,               /* Print a type using appropriate syntax */
12815   ada_print_typedef,            /* Print a typedef using appropriate syntax */
12816   ada_val_print,                /* Print a value using appropriate syntax */
12817   ada_value_print,              /* Print a top-level value */
12818   ada_read_var_value,           /* la_read_var_value */
12819   NULL,                         /* Language specific skip_trampoline */
12820   NULL,                         /* name_of_this */
12821   ada_lookup_symbol_nonlocal,   /* Looking up non-local symbols.  */
12822   basic_lookup_transparent_type,        /* lookup_transparent_type */
12823   ada_la_decode,                /* Language specific symbol demangler */
12824   NULL,                         /* Language specific
12825                                    class_name_from_physname */
12826   ada_op_print_tab,             /* expression operators for printing */
12827   0,                            /* c-style arrays */
12828   1,                            /* String lower bound */
12829   ada_get_gdb_completer_word_break_characters,
12830   ada_make_symbol_completion_list,
12831   ada_language_arch_info,
12832   ada_print_array_index,
12833   default_pass_by_reference,
12834   c_get_string,
12835   ada_get_symbol_name_cmp,      /* la_get_symbol_name_cmp */
12836   ada_iterate_over_symbols,
12837   LANG_MAGIC
12838 };
12839 
12840 /* Provide a prototype to silence -Wmissing-prototypes.  */
12841 extern initialize_file_ftype _initialize_ada_language;
12842 
12843 /* Command-list for the "set/show ada" prefix command.  */
12844 static struct cmd_list_element *set_ada_list;
12845 static struct cmd_list_element *show_ada_list;
12846 
12847 /* Implement the "set ada" prefix command.  */
12848 
12849 static void
12850 set_ada_command (char *arg, int from_tty)
12851 {
12852   printf_unfiltered (_(\
12853 "\"set ada\" must be followed by the name of a setting.\n"));
12854   help_list (set_ada_list, "set ada ", -1, gdb_stdout);
12855 }
12856 
12857 /* Implement the "show ada" prefix command.  */
12858 
12859 static void
12860 show_ada_command (char *args, int from_tty)
12861 {
12862   cmd_show_list (show_ada_list, from_tty, "");
12863 }
12864 
12865 static void
12866 initialize_ada_catchpoint_ops (void)
12867 {
12868   struct breakpoint_ops *ops;
12869 
12870   initialize_breakpoint_ops ();
12871 
12872   ops = &catch_exception_breakpoint_ops;
12873   *ops = bkpt_breakpoint_ops;
12874   ops->dtor = dtor_catch_exception;
12875   ops->allocate_location = allocate_location_catch_exception;
12876   ops->re_set = re_set_catch_exception;
12877   ops->check_status = check_status_catch_exception;
12878   ops->print_it = print_it_catch_exception;
12879   ops->print_one = print_one_catch_exception;
12880   ops->print_mention = print_mention_catch_exception;
12881   ops->print_recreate = print_recreate_catch_exception;
12882 
12883   ops = &catch_exception_unhandled_breakpoint_ops;
12884   *ops = bkpt_breakpoint_ops;
12885   ops->dtor = dtor_catch_exception_unhandled;
12886   ops->allocate_location = allocate_location_catch_exception_unhandled;
12887   ops->re_set = re_set_catch_exception_unhandled;
12888   ops->check_status = check_status_catch_exception_unhandled;
12889   ops->print_it = print_it_catch_exception_unhandled;
12890   ops->print_one = print_one_catch_exception_unhandled;
12891   ops->print_mention = print_mention_catch_exception_unhandled;
12892   ops->print_recreate = print_recreate_catch_exception_unhandled;
12893 
12894   ops = &catch_assert_breakpoint_ops;
12895   *ops = bkpt_breakpoint_ops;
12896   ops->dtor = dtor_catch_assert;
12897   ops->allocate_location = allocate_location_catch_assert;
12898   ops->re_set = re_set_catch_assert;
12899   ops->check_status = check_status_catch_assert;
12900   ops->print_it = print_it_catch_assert;
12901   ops->print_one = print_one_catch_assert;
12902   ops->print_mention = print_mention_catch_assert;
12903   ops->print_recreate = print_recreate_catch_assert;
12904 }
12905 
12906 void
12907 _initialize_ada_language (void)
12908 {
12909   add_language (&ada_language_defn);
12910 
12911   initialize_ada_catchpoint_ops ();
12912 
12913   add_prefix_cmd ("ada", no_class, set_ada_command,
12914                   _("Prefix command for changing Ada-specfic settings"),
12915                   &set_ada_list, "set ada ", 0, &setlist);
12916 
12917   add_prefix_cmd ("ada", no_class, show_ada_command,
12918                   _("Generic command for showing Ada-specific settings."),
12919                   &show_ada_list, "show ada ", 0, &showlist);
12920 
12921   add_setshow_boolean_cmd ("trust-PAD-over-XVS", class_obscure,
12922                            &trust_pad_over_xvs, _("\
12923 Enable or disable an optimization trusting PAD types over XVS types"), _("\
12924 Show whether an optimization trusting PAD types over XVS types is activated"),
12925                            _("\
12926 This is related to the encoding used by the GNAT compiler.  The debugger\n\
12927 should normally trust the contents of PAD types, but certain older versions\n\
12928 of GNAT have a bug that sometimes causes the information in the PAD type\n\
12929 to be incorrect.  Turning this setting \"off\" allows the debugger to\n\
12930 work around this bug.  It is always safe to turn this option \"off\", but\n\
12931 this incurs a slight performance penalty, so it is recommended to NOT change\n\
12932 this option to \"off\" unless necessary."),
12933                             NULL, NULL, &set_ada_list, &show_ada_list);
12934 
12935   add_catch_command ("exception", _("\
12936 Catch Ada exceptions, when raised.\n\
12937 With an argument, catch only exceptions with the given name."),
12938                      catch_ada_exception_command,
12939                      NULL,
12940                      CATCH_PERMANENT,
12941                      CATCH_TEMPORARY);
12942   add_catch_command ("assert", _("\
12943 Catch failed Ada assertions, when raised.\n\
12944 With an argument, catch only exceptions with the given name."),
12945                      catch_assert_command,
12946                      NULL,
12947                      CATCH_PERMANENT,
12948                      CATCH_TEMPORARY);
12949 
12950   varsize_limit = 65536;
12951 
12952   obstack_init (&symbol_list_obstack);
12953 
12954   decoded_names_store = htab_create_alloc
12955     (256, htab_hash_string, (int (*)(const void *, const void *)) streq,
12956      NULL, xcalloc, xfree);
12957 
12958   /* Setup per-inferior data.  */
12959   observer_attach_inferior_exit (ada_inferior_exit);
12960   ada_inferior_data
12961     = register_inferior_data_with_cleanup (NULL, ada_inferior_data_cleanup);
12962 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines