2011-02-15 Yao Qi <yao@codesourcery.com>
[platform/upstream/binutils.git] / gdb / arm-tdep.c
1 /* Common target dependent code for GDB on ARM systems.
2
3    Copyright (C) 1988, 1989, 1991, 1992, 1993, 1995, 1996, 1998, 1999, 2000,
4    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
5    Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include <ctype.h>              /* XXX for isupper ().  */
23
24 #include "defs.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include "gdb_string.h"
30 #include "dis-asm.h"            /* For register styles.  */
31 #include "regcache.h"
32 #include "reggroups.h"
33 #include "doublest.h"
34 #include "value.h"
35 #include "arch-utils.h"
36 #include "osabi.h"
37 #include "frame-unwind.h"
38 #include "frame-base.h"
39 #include "trad-frame.h"
40 #include "objfiles.h"
41 #include "dwarf2-frame.h"
42 #include "gdbtypes.h"
43 #include "prologue-value.h"
44 #include "target-descriptions.h"
45 #include "user-regs.h"
46 #include "observer.h"
47
48 #include "arm-tdep.h"
49 #include "gdb/sim-arm.h"
50
51 #include "elf-bfd.h"
52 #include "coff/internal.h"
53 #include "elf/arm.h"
54
55 #include "gdb_assert.h"
56 #include "vec.h"
57
58 #include "features/arm-with-m.c"
59
60 static int arm_debug;
61
62 /* Macros for setting and testing a bit in a minimal symbol that marks
63    it as Thumb function.  The MSB of the minimal symbol's "info" field
64    is used for this purpose.
65
66    MSYMBOL_SET_SPECIAL  Actually sets the "special" bit.
67    MSYMBOL_IS_SPECIAL   Tests the "special" bit in a minimal symbol.  */
68
69 #define MSYMBOL_SET_SPECIAL(msym)                               \
70         MSYMBOL_TARGET_FLAG_1 (msym) = 1
71
72 #define MSYMBOL_IS_SPECIAL(msym)                                \
73         MSYMBOL_TARGET_FLAG_1 (msym)
74
75 /* Per-objfile data used for mapping symbols.  */
76 static const struct objfile_data *arm_objfile_data_key;
77
78 struct arm_mapping_symbol
79 {
80   bfd_vma value;
81   char type;
82 };
83 typedef struct arm_mapping_symbol arm_mapping_symbol_s;
84 DEF_VEC_O(arm_mapping_symbol_s);
85
86 struct arm_per_objfile
87 {
88   VEC(arm_mapping_symbol_s) **section_maps;
89 };
90
91 /* The list of available "set arm ..." and "show arm ..." commands.  */
92 static struct cmd_list_element *setarmcmdlist = NULL;
93 static struct cmd_list_element *showarmcmdlist = NULL;
94
95 /* The type of floating-point to use.  Keep this in sync with enum
96    arm_float_model, and the help string in _initialize_arm_tdep.  */
97 static const char *fp_model_strings[] =
98 {
99   "auto",
100   "softfpa",
101   "fpa",
102   "softvfp",
103   "vfp",
104   NULL
105 };
106
107 /* A variable that can be configured by the user.  */
108 static enum arm_float_model arm_fp_model = ARM_FLOAT_AUTO;
109 static const char *current_fp_model = "auto";
110
111 /* The ABI to use.  Keep this in sync with arm_abi_kind.  */
112 static const char *arm_abi_strings[] =
113 {
114   "auto",
115   "APCS",
116   "AAPCS",
117   NULL
118 };
119
120 /* A variable that can be configured by the user.  */
121 static enum arm_abi_kind arm_abi_global = ARM_ABI_AUTO;
122 static const char *arm_abi_string = "auto";
123
124 /* The execution mode to assume.  */
125 static const char *arm_mode_strings[] =
126   {
127     "auto",
128     "arm",
129     "thumb",
130     NULL
131   };
132
133 static const char *arm_fallback_mode_string = "auto";
134 static const char *arm_force_mode_string = "auto";
135
136 /* Number of different reg name sets (options).  */
137 static int num_disassembly_options;
138
139 /* The standard register names, and all the valid aliases for them.  Note
140    that `fp', `sp' and `pc' are not added in this alias list, because they
141    have been added as builtin user registers in
142    std-regs.c:_initialize_frame_reg.  */
143 static const struct
144 {
145   const char *name;
146   int regnum;
147 } arm_register_aliases[] = {
148   /* Basic register numbers.  */
149   { "r0", 0 },
150   { "r1", 1 },
151   { "r2", 2 },
152   { "r3", 3 },
153   { "r4", 4 },
154   { "r5", 5 },
155   { "r6", 6 },
156   { "r7", 7 },
157   { "r8", 8 },
158   { "r9", 9 },
159   { "r10", 10 },
160   { "r11", 11 },
161   { "r12", 12 },
162   { "r13", 13 },
163   { "r14", 14 },
164   { "r15", 15 },
165   /* Synonyms (argument and variable registers).  */
166   { "a1", 0 },
167   { "a2", 1 },
168   { "a3", 2 },
169   { "a4", 3 },
170   { "v1", 4 },
171   { "v2", 5 },
172   { "v3", 6 },
173   { "v4", 7 },
174   { "v5", 8 },
175   { "v6", 9 },
176   { "v7", 10 },
177   { "v8", 11 },
178   /* Other platform-specific names for r9.  */
179   { "sb", 9 },
180   { "tr", 9 },
181   /* Special names.  */
182   { "ip", 12 },
183   { "lr", 14 },
184   /* Names used by GCC (not listed in the ARM EABI).  */
185   { "sl", 10 },
186   /* A special name from the older ATPCS.  */
187   { "wr", 7 },
188 };
189
190 static const char *const arm_register_names[] =
191 {"r0",  "r1",  "r2",  "r3",     /*  0  1  2  3 */
192  "r4",  "r5",  "r6",  "r7",     /*  4  5  6  7 */
193  "r8",  "r9",  "r10", "r11",    /*  8  9 10 11 */
194  "r12", "sp",  "lr",  "pc",     /* 12 13 14 15 */
195  "f0",  "f1",  "f2",  "f3",     /* 16 17 18 19 */
196  "f4",  "f5",  "f6",  "f7",     /* 20 21 22 23 */
197  "fps", "cpsr" };               /* 24 25       */
198
199 /* Valid register name styles.  */
200 static const char **valid_disassembly_styles;
201
202 /* Disassembly style to use. Default to "std" register names.  */
203 static const char *disassembly_style;
204
205 /* This is used to keep the bfd arch_info in sync with the disassembly
206    style.  */
207 static void set_disassembly_style_sfunc(char *, int,
208                                          struct cmd_list_element *);
209 static void set_disassembly_style (void);
210
211 static void convert_from_extended (const struct floatformat *, const void *,
212                                    void *, int);
213 static void convert_to_extended (const struct floatformat *, void *,
214                                  const void *, int);
215
216 static void arm_neon_quad_read (struct gdbarch *gdbarch,
217                                 struct regcache *regcache,
218                                 int regnum, gdb_byte *buf);
219 static void arm_neon_quad_write (struct gdbarch *gdbarch,
220                                  struct regcache *regcache,
221                                  int regnum, const gdb_byte *buf);
222
223 struct arm_prologue_cache
224 {
225   /* The stack pointer at the time this frame was created; i.e. the
226      caller's stack pointer when this function was called.  It is used
227      to identify this frame.  */
228   CORE_ADDR prev_sp;
229
230   /* The frame base for this frame is just prev_sp - frame size.
231      FRAMESIZE is the distance from the frame pointer to the
232      initial stack pointer.  */
233
234   int framesize;
235
236   /* The register used to hold the frame pointer for this frame.  */
237   int framereg;
238
239   /* Saved register offsets.  */
240   struct trad_frame_saved_reg *saved_regs;
241 };
242
243 static CORE_ADDR arm_analyze_prologue (struct gdbarch *gdbarch,
244                                        CORE_ADDR prologue_start,
245                                        CORE_ADDR prologue_end,
246                                        struct arm_prologue_cache *cache);
247
248 /* Architecture version for displaced stepping.  This effects the behaviour of
249    certain instructions, and really should not be hard-wired.  */
250
251 #define DISPLACED_STEPPING_ARCH_VERSION         5
252
253 /* Addresses for calling Thumb functions have the bit 0 set.
254    Here are some macros to test, set, or clear bit 0 of addresses.  */
255 #define IS_THUMB_ADDR(addr)     ((addr) & 1)
256 #define MAKE_THUMB_ADDR(addr)   ((addr) | 1)
257 #define UNMAKE_THUMB_ADDR(addr) ((addr) & ~1)
258
259 /* Set to true if the 32-bit mode is in use.  */
260
261 int arm_apcs_32 = 1;
262
263 /* Return the bit mask in ARM_PS_REGNUM that indicates Thumb mode.  */
264
265 static int
266 arm_psr_thumb_bit (struct gdbarch *gdbarch)
267 {
268   if (gdbarch_tdep (gdbarch)->is_m)
269     return XPSR_T;
270   else
271     return CPSR_T;
272 }
273
274 /* Determine if FRAME is executing in Thumb mode.  */
275
276 int
277 arm_frame_is_thumb (struct frame_info *frame)
278 {
279   CORE_ADDR cpsr;
280   ULONGEST t_bit = arm_psr_thumb_bit (get_frame_arch (frame));
281
282   /* Every ARM frame unwinder can unwind the T bit of the CPSR, either
283      directly (from a signal frame or dummy frame) or by interpreting
284      the saved LR (from a prologue or DWARF frame).  So consult it and
285      trust the unwinders.  */
286   cpsr = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
287
288   return (cpsr & t_bit) != 0;
289 }
290
291 /* Callback for VEC_lower_bound.  */
292
293 static inline int
294 arm_compare_mapping_symbols (const struct arm_mapping_symbol *lhs,
295                              const struct arm_mapping_symbol *rhs)
296 {
297   return lhs->value < rhs->value;
298 }
299
300 /* Search for the mapping symbol covering MEMADDR.  If one is found,
301    return its type.  Otherwise, return 0.  If START is non-NULL,
302    set *START to the location of the mapping symbol.  */
303
304 static char
305 arm_find_mapping_symbol (CORE_ADDR memaddr, CORE_ADDR *start)
306 {
307   struct obj_section *sec;
308
309   /* If there are mapping symbols, consult them.  */
310   sec = find_pc_section (memaddr);
311   if (sec != NULL)
312     {
313       struct arm_per_objfile *data;
314       VEC(arm_mapping_symbol_s) *map;
315       struct arm_mapping_symbol map_key = { memaddr - obj_section_addr (sec),
316                                             0 };
317       unsigned int idx;
318
319       data = objfile_data (sec->objfile, arm_objfile_data_key);
320       if (data != NULL)
321         {
322           map = data->section_maps[sec->the_bfd_section->index];
323           if (!VEC_empty (arm_mapping_symbol_s, map))
324             {
325               struct arm_mapping_symbol *map_sym;
326
327               idx = VEC_lower_bound (arm_mapping_symbol_s, map, &map_key,
328                                      arm_compare_mapping_symbols);
329
330               /* VEC_lower_bound finds the earliest ordered insertion
331                  point.  If the following symbol starts at this exact
332                  address, we use that; otherwise, the preceding
333                  mapping symbol covers this address.  */
334               if (idx < VEC_length (arm_mapping_symbol_s, map))
335                 {
336                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx);
337                   if (map_sym->value == map_key.value)
338                     {
339                       if (start)
340                         *start = map_sym->value + obj_section_addr (sec);
341                       return map_sym->type;
342                     }
343                 }
344
345               if (idx > 0)
346                 {
347                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx - 1);
348                   if (start)
349                     *start = map_sym->value + obj_section_addr (sec);
350                   return map_sym->type;
351                 }
352             }
353         }
354     }
355
356   return 0;
357 }
358
359 static CORE_ADDR arm_get_next_pc_raw (struct frame_info *frame, 
360                                       CORE_ADDR pc, int insert_bkpt);
361
362 /* Determine if the program counter specified in MEMADDR is in a Thumb
363    function.  This function should be called for addresses unrelated to
364    any executing frame; otherwise, prefer arm_frame_is_thumb.  */
365
366 static int
367 arm_pc_is_thumb (struct gdbarch *gdbarch, CORE_ADDR memaddr)
368 {
369   struct obj_section *sec;
370   struct minimal_symbol *sym;
371   char type;
372
373   /* If bit 0 of the address is set, assume this is a Thumb address.  */
374   if (IS_THUMB_ADDR (memaddr))
375     return 1;
376
377   /* If the user wants to override the symbol table, let him.  */
378   if (strcmp (arm_force_mode_string, "arm") == 0)
379     return 0;
380   if (strcmp (arm_force_mode_string, "thumb") == 0)
381     return 1;
382
383   /* ARM v6-M and v7-M are always in Thumb mode.  */
384   if (gdbarch_tdep (gdbarch)->is_m)
385     return 1;
386
387   /* If there are mapping symbols, consult them.  */
388   type = arm_find_mapping_symbol (memaddr, NULL);
389   if (type)
390     return type == 't';
391
392   /* Thumb functions have a "special" bit set in minimal symbols.  */
393   sym = lookup_minimal_symbol_by_pc (memaddr);
394   if (sym)
395     return (MSYMBOL_IS_SPECIAL (sym));
396
397   /* If the user wants to override the fallback mode, let them.  */
398   if (strcmp (arm_fallback_mode_string, "arm") == 0)
399     return 0;
400   if (strcmp (arm_fallback_mode_string, "thumb") == 0)
401     return 1;
402
403   /* If we couldn't find any symbol, but we're talking to a running
404      target, then trust the current value of $cpsr.  This lets
405      "display/i $pc" always show the correct mode (though if there is
406      a symbol table we will not reach here, so it still may not be
407      displayed in the mode it will be executed).  
408    
409      As a further heuristic if we detect that we are doing a single-step we
410      see what state executing the current instruction ends up with us being
411      in.  */
412   if (target_has_registers)
413     {
414       struct frame_info *current_frame = get_current_frame ();
415       CORE_ADDR current_pc = get_frame_pc (current_frame);
416       int is_thumb = arm_frame_is_thumb (current_frame);
417       CORE_ADDR next_pc;
418       if (memaddr == current_pc)
419         return is_thumb;
420       else
421         {
422           struct gdbarch *gdbarch = get_frame_arch (current_frame);
423           next_pc = arm_get_next_pc_raw (current_frame, current_pc, FALSE);
424           if (memaddr == gdbarch_addr_bits_remove (gdbarch, next_pc))
425             return IS_THUMB_ADDR (next_pc);
426           else
427             return is_thumb;
428         }
429     }
430
431   /* Otherwise we're out of luck; we assume ARM.  */
432   return 0;
433 }
434
435 /* Remove useless bits from addresses in a running program.  */
436 static CORE_ADDR
437 arm_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR val)
438 {
439   if (arm_apcs_32)
440     return UNMAKE_THUMB_ADDR (val);
441   else
442     return (val & 0x03fffffc);
443 }
444
445 /* When reading symbols, we need to zap the low bit of the address,
446    which may be set to 1 for Thumb functions.  */
447 static CORE_ADDR
448 arm_smash_text_address (struct gdbarch *gdbarch, CORE_ADDR val)
449 {
450   return val & ~1;
451 }
452
453 /* Return 1 if PC is the start of a compiler helper function which
454    can be safely ignored during prologue skipping.  IS_THUMB is true
455    if the function is known to be a Thumb function due to the way it
456    is being called.  */
457 static int
458 skip_prologue_function (struct gdbarch *gdbarch, CORE_ADDR pc, int is_thumb)
459 {
460   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
461   struct minimal_symbol *msym;
462
463   msym = lookup_minimal_symbol_by_pc (pc);
464   if (msym != NULL
465       && SYMBOL_VALUE_ADDRESS (msym) == pc
466       && SYMBOL_LINKAGE_NAME (msym) != NULL)
467     {
468       const char *name = SYMBOL_LINKAGE_NAME (msym);
469
470       /* The GNU linker's Thumb call stub to foo is named
471          __foo_from_thumb.  */
472       if (strstr (name, "_from_thumb") != NULL)
473         name += 2;
474
475       /* On soft-float targets, __truncdfsf2 is called to convert promoted
476          arguments to their argument types in non-prototyped
477          functions.  */
478       if (strncmp (name, "__truncdfsf2", strlen ("__truncdfsf2")) == 0)
479         return 1;
480       if (strncmp (name, "__aeabi_d2f", strlen ("__aeabi_d2f")) == 0)
481         return 1;
482
483       /* Internal functions related to thread-local storage.  */
484       if (strncmp (name, "__tls_get_addr", strlen ("__tls_get_addr")) == 0)
485         return 1;
486       if (strncmp (name, "__aeabi_read_tp", strlen ("__aeabi_read_tp")) == 0)
487         return 1;
488     }
489   else
490     {
491       /* If we run against a stripped glibc, we may be unable to identify
492          special functions by name.  Check for one important case,
493          __aeabi_read_tp, by comparing the *code* against the default
494          implementation (this is hand-written ARM assembler in glibc).  */
495
496       if (!is_thumb
497           && read_memory_unsigned_integer (pc, 4, byte_order_for_code)
498              == 0xe3e00a0f /* mov r0, #0xffff0fff */
499           && read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code)
500              == 0xe240f01f) /* sub pc, r0, #31 */
501         return 1;
502     }
503
504   return 0;
505 }
506
507 /* Support routines for instruction parsing.  */
508 #define submask(x) ((1L << ((x) + 1)) - 1)
509 #define bit(obj,st) (((obj) >> (st)) & 1)
510 #define bits(obj,st,fn) (((obj) >> (st)) & submask ((fn) - (st)))
511 #define sbits(obj,st,fn) \
512   ((long) (bits(obj,st,fn) | ((long) bit(obj,fn) * ~ submask (fn - st))))
513 #define BranchDest(addr,instr) \
514   ((CORE_ADDR) (((long) (addr)) + 8 + (sbits (instr, 0, 23) << 2)))
515
516 /* Extract the immediate from instruction movw/movt of encoding T.  INSN1 is
517    the first 16-bit of instruction, and INSN2 is the second 16-bit of
518    instruction.  */
519 #define EXTRACT_MOVW_MOVT_IMM_T(insn1, insn2) \
520   ((bits ((insn1), 0, 3) << 12)               \
521    | (bits ((insn1), 10, 10) << 11)           \
522    | (bits ((insn2), 12, 14) << 8)            \
523    | bits ((insn2), 0, 7))
524
525 /* Extract the immediate from instruction movw/movt of encoding A.  INSN is
526    the 32-bit instruction.  */
527 #define EXTRACT_MOVW_MOVT_IMM_A(insn) \
528   ((bits ((insn), 16, 19) << 12) \
529    | bits ((insn), 0, 11))
530
531 /* Decode immediate value; implements ThumbExpandImmediate pseudo-op.  */
532
533 static unsigned int
534 thumb_expand_immediate (unsigned int imm)
535 {
536   unsigned int count = imm >> 7;
537
538   if (count < 8)
539     switch (count / 2)
540       {
541       case 0:
542         return imm & 0xff;
543       case 1:
544         return (imm & 0xff) | ((imm & 0xff) << 16);
545       case 2:
546         return ((imm & 0xff) << 8) | ((imm & 0xff) << 24);
547       case 3:
548         return (imm & 0xff) | ((imm & 0xff) << 8)
549                 | ((imm & 0xff) << 16) | ((imm & 0xff) << 24);
550       }
551
552   return (0x80 | (imm & 0x7f)) << (32 - count);
553 }
554
555 /* Return 1 if the 16-bit Thumb instruction INST might change
556    control flow, 0 otherwise.  */
557
558 static int
559 thumb_instruction_changes_pc (unsigned short inst)
560 {
561   if ((inst & 0xff00) == 0xbd00)        /* pop {rlist, pc} */
562     return 1;
563
564   if ((inst & 0xf000) == 0xd000)        /* conditional branch */
565     return 1;
566
567   if ((inst & 0xf800) == 0xe000)        /* unconditional branch */
568     return 1;
569
570   if ((inst & 0xff00) == 0x4700)        /* bx REG, blx REG */
571     return 1;
572
573   if ((inst & 0xff87) == 0x4687)        /* mov pc, REG */
574     return 1;
575
576   if ((inst & 0xf500) == 0xb100)        /* CBNZ or CBZ.  */
577     return 1;
578
579   return 0;
580 }
581
582 /* Return 1 if the 32-bit Thumb instruction in INST1 and INST2
583    might change control flow, 0 otherwise.  */
584
585 static int
586 thumb2_instruction_changes_pc (unsigned short inst1, unsigned short inst2)
587 {
588   if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
589     {
590       /* Branches and miscellaneous control instructions.  */
591
592       if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
593         {
594           /* B, BL, BLX.  */
595           return 1;
596         }
597       else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
598         {
599           /* SUBS PC, LR, #imm8.  */
600           return 1;
601         }
602       else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
603         {
604           /* Conditional branch.  */
605           return 1;
606         }
607
608       return 0;
609     }
610
611   if ((inst1 & 0xfe50) == 0xe810)
612     {
613       /* Load multiple or RFE.  */
614
615       if (bit (inst1, 7) && !bit (inst1, 8))
616         {
617           /* LDMIA or POP */
618           if (bit (inst2, 15))
619             return 1;
620         }
621       else if (!bit (inst1, 7) && bit (inst1, 8))
622         {
623           /* LDMDB */
624           if (bit (inst2, 15))
625             return 1;
626         }
627       else if (bit (inst1, 7) && bit (inst1, 8))
628         {
629           /* RFEIA */
630           return 1;
631         }
632       else if (!bit (inst1, 7) && !bit (inst1, 8))
633         {
634           /* RFEDB */
635           return 1;
636         }
637
638       return 0;
639     }
640
641   if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
642     {
643       /* MOV PC or MOVS PC.  */
644       return 1;
645     }
646
647   if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
648     {
649       /* LDR PC.  */
650       if (bits (inst1, 0, 3) == 15)
651         return 1;
652       if (bit (inst1, 7))
653         return 1;
654       if (bit (inst2, 11))
655         return 1;
656       if ((inst2 & 0x0fc0) == 0x0000)
657         return 1;       
658
659       return 0;
660     }
661
662   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
663     {
664       /* TBB.  */
665       return 1;
666     }
667
668   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
669     {
670       /* TBH.  */
671       return 1;
672     }
673
674   return 0;
675 }
676
677 /* Analyze a Thumb prologue, looking for a recognizable stack frame
678    and frame pointer.  Scan until we encounter a store that could
679    clobber the stack frame unexpectedly, or an unknown instruction.
680    Return the last address which is definitely safe to skip for an
681    initial breakpoint.  */
682
683 static CORE_ADDR
684 thumb_analyze_prologue (struct gdbarch *gdbarch,
685                         CORE_ADDR start, CORE_ADDR limit,
686                         struct arm_prologue_cache *cache)
687 {
688   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
689   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
690   int i;
691   pv_t regs[16];
692   struct pv_area *stack;
693   struct cleanup *back_to;
694   CORE_ADDR offset;
695   CORE_ADDR unrecognized_pc = 0;
696
697   for (i = 0; i < 16; i++)
698     regs[i] = pv_register (i, 0);
699   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
700   back_to = make_cleanup_free_pv_area (stack);
701
702   while (start < limit)
703     {
704       unsigned short insn;
705
706       insn = read_memory_unsigned_integer (start, 2, byte_order_for_code);
707
708       if ((insn & 0xfe00) == 0xb400)            /* push { rlist } */
709         {
710           int regno;
711           int mask;
712
713           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
714             break;
715
716           /* Bits 0-7 contain a mask for registers R0-R7.  Bit 8 says
717              whether to save LR (R14).  */
718           mask = (insn & 0xff) | ((insn & 0x100) << 6);
719
720           /* Calculate offsets of saved R0-R7 and LR.  */
721           for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
722             if (mask & (1 << regno))
723               {
724                 regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
725                                                        -4);
726                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
727               }
728         }
729       else if ((insn & 0xff00) == 0xb000)       /* add sp, #simm  OR  
730                                                    sub sp, #simm */
731         {
732           offset = (insn & 0x7f) << 2;          /* get scaled offset */
733           if (insn & 0x80)                      /* Check for SUB.  */
734             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
735                                                    -offset);
736           else
737             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
738                                                    offset);
739         }
740       else if ((insn & 0xf800) == 0xa800)       /* add Rd, sp, #imm */
741         regs[bits (insn, 8, 10)] = pv_add_constant (regs[ARM_SP_REGNUM],
742                                                     (insn & 0xff) << 2);
743       else if ((insn & 0xfe00) == 0x1c00        /* add Rd, Rn, #imm */
744                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
745         regs[bits (insn, 0, 2)] = pv_add_constant (regs[bits (insn, 3, 5)],
746                                                    bits (insn, 6, 8));
747       else if ((insn & 0xf800) == 0x3000        /* add Rd, #imm */
748                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
749         regs[bits (insn, 8, 10)] = pv_add_constant (regs[bits (insn, 8, 10)],
750                                                     bits (insn, 0, 7));
751       else if ((insn & 0xfe00) == 0x1800        /* add Rd, Rn, Rm */
752                && pv_is_register (regs[bits (insn, 6, 8)], ARM_SP_REGNUM)
753                && pv_is_constant (regs[bits (insn, 3, 5)]))
754         regs[bits (insn, 0, 2)] = pv_add (regs[bits (insn, 3, 5)],
755                                           regs[bits (insn, 6, 8)]);
756       else if ((insn & 0xff00) == 0x4400        /* add Rd, Rm */
757                && pv_is_constant (regs[bits (insn, 3, 6)]))
758         {
759           int rd = (bit (insn, 7) << 3) + bits (insn, 0, 2);
760           int rm = bits (insn, 3, 6);
761           regs[rd] = pv_add (regs[rd], regs[rm]);
762         }
763       else if ((insn & 0xff00) == 0x4600)       /* mov hi, lo or mov lo, hi */
764         {
765           int dst_reg = (insn & 0x7) + ((insn & 0x80) >> 4);
766           int src_reg = (insn & 0x78) >> 3;
767           regs[dst_reg] = regs[src_reg];
768         }
769       else if ((insn & 0xf800) == 0x9000)       /* str rd, [sp, #off] */
770         {
771           /* Handle stores to the stack.  Normally pushes are used,
772              but with GCC -mtpcs-frame, there may be other stores
773              in the prologue to create the frame.  */
774           int regno = (insn >> 8) & 0x7;
775           pv_t addr;
776
777           offset = (insn & 0xff) << 2;
778           addr = pv_add_constant (regs[ARM_SP_REGNUM], offset);
779
780           if (pv_area_store_would_trash (stack, addr))
781             break;
782
783           pv_area_store (stack, addr, 4, regs[regno]);
784         }
785       else if ((insn & 0xf800) == 0x6000)       /* str rd, [rn, #off] */
786         {
787           int rd = bits (insn, 0, 2);
788           int rn = bits (insn, 3, 5);
789           pv_t addr;
790
791           offset = bits (insn, 6, 10) << 2;
792           addr = pv_add_constant (regs[rn], offset);
793
794           if (pv_area_store_would_trash (stack, addr))
795             break;
796
797           pv_area_store (stack, addr, 4, regs[rd]);
798         }
799       else if (((insn & 0xf800) == 0x7000       /* strb Rd, [Rn, #off] */
800                 || (insn & 0xf800) == 0x8000)   /* strh Rd, [Rn, #off] */
801                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
802         /* Ignore stores of argument registers to the stack.  */
803         ;
804       else if ((insn & 0xf800) == 0xc800        /* ldmia Rn!, { registers } */
805                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
806         /* Ignore block loads from the stack, potentially copying
807            parameters from memory.  */
808         ;
809       else if ((insn & 0xf800) == 0x9800        /* ldr Rd, [Rn, #immed] */
810                || ((insn & 0xf800) == 0x6800    /* ldr Rd, [sp, #immed] */
811                    && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM)))
812         /* Similarly ignore single loads from the stack.  */
813         ;
814       else if ((insn & 0xffc0) == 0x0000        /* lsls Rd, Rm, #0 */
815                || (insn & 0xffc0) == 0x1c00)    /* add Rd, Rn, #0 */
816         /* Skip register copies, i.e. saves to another register
817            instead of the stack.  */
818         ;
819       else if ((insn & 0xf800) == 0x2000)       /* movs Rd, #imm */
820         /* Recognize constant loads; even with small stacks these are necessary
821            on Thumb.  */
822         regs[bits (insn, 8, 10)] = pv_constant (bits (insn, 0, 7));
823       else if ((insn & 0xf800) == 0x4800)       /* ldr Rd, [pc, #imm] */
824         {
825           /* Constant pool loads, for the same reason.  */
826           unsigned int constant;
827           CORE_ADDR loc;
828
829           loc = start + 4 + bits (insn, 0, 7) * 4;
830           constant = read_memory_unsigned_integer (loc, 4, byte_order);
831           regs[bits (insn, 8, 10)] = pv_constant (constant);
832         }
833       else if ((insn & 0xe000) == 0xe000)
834         {
835           unsigned short inst2;
836
837           inst2 = read_memory_unsigned_integer (start + 2, 2,
838                                                 byte_order_for_code);
839
840           if ((insn & 0xf800) == 0xf000 && (inst2 & 0xe800) == 0xe800)
841             {
842               /* BL, BLX.  Allow some special function calls when
843                  skipping the prologue; GCC generates these before
844                  storing arguments to the stack.  */
845               CORE_ADDR nextpc;
846               int j1, j2, imm1, imm2;
847
848               imm1 = sbits (insn, 0, 10);
849               imm2 = bits (inst2, 0, 10);
850               j1 = bit (inst2, 13);
851               j2 = bit (inst2, 11);
852
853               offset = ((imm1 << 12) + (imm2 << 1));
854               offset ^= ((!j2) << 22) | ((!j1) << 23);
855
856               nextpc = start + 4 + offset;
857               /* For BLX make sure to clear the low bits.  */
858               if (bit (inst2, 12) == 0)
859                 nextpc = nextpc & 0xfffffffc;
860
861               if (!skip_prologue_function (gdbarch, nextpc,
862                                            bit (inst2, 12) != 0))
863                 break;
864             }
865
866           else if ((insn & 0xffd0) == 0xe900    /* stmdb Rn{!},
867                                                    { registers } */
868                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
869             {
870               pv_t addr = regs[bits (insn, 0, 3)];
871               int regno;
872
873               if (pv_area_store_would_trash (stack, addr))
874                 break;
875
876               /* Calculate offsets of saved registers.  */
877               for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
878                 if (inst2 & (1 << regno))
879                   {
880                     addr = pv_add_constant (addr, -4);
881                     pv_area_store (stack, addr, 4, regs[regno]);
882                   }
883
884               if (insn & 0x0020)
885                 regs[bits (insn, 0, 3)] = addr;
886             }
887
888           else if ((insn & 0xff50) == 0xe940    /* strd Rt, Rt2,
889                                                    [Rn, #+/-imm]{!} */
890                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
891             {
892               int regno1 = bits (inst2, 12, 15);
893               int regno2 = bits (inst2, 8, 11);
894               pv_t addr = regs[bits (insn, 0, 3)];
895
896               offset = inst2 & 0xff;
897               if (insn & 0x0080)
898                 addr = pv_add_constant (addr, offset);
899               else
900                 addr = pv_add_constant (addr, -offset);
901
902               if (pv_area_store_would_trash (stack, addr))
903                 break;
904
905               pv_area_store (stack, addr, 4, regs[regno1]);
906               pv_area_store (stack, pv_add_constant (addr, 4),
907                              4, regs[regno2]);
908
909               if (insn & 0x0020)
910                 regs[bits (insn, 0, 3)] = addr;
911             }
912
913           else if ((insn & 0xfff0) == 0xf8c0    /* str Rt,[Rn,+/-#imm]{!} */
914                    && (inst2 & 0x0c00) == 0x0c00
915                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
916             {
917               int regno = bits (inst2, 12, 15);
918               pv_t addr = regs[bits (insn, 0, 3)];
919
920               offset = inst2 & 0xff;
921               if (inst2 & 0x0200)
922                 addr = pv_add_constant (addr, offset);
923               else
924                 addr = pv_add_constant (addr, -offset);
925
926               if (pv_area_store_would_trash (stack, addr))
927                 break;
928
929               pv_area_store (stack, addr, 4, regs[regno]);
930
931               if (inst2 & 0x0100)
932                 regs[bits (insn, 0, 3)] = addr;
933             }
934
935           else if ((insn & 0xfff0) == 0xf8c0    /* str.w Rt,[Rn,#imm] */
936                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
937             {
938               int regno = bits (inst2, 12, 15);
939               pv_t addr;
940
941               offset = inst2 & 0xfff;
942               addr = pv_add_constant (regs[bits (insn, 0, 3)], offset);
943
944               if (pv_area_store_would_trash (stack, addr))
945                 break;
946
947               pv_area_store (stack, addr, 4, regs[regno]);
948             }
949
950           else if ((insn & 0xffd0) == 0xf880    /* str{bh}.w Rt,[Rn,#imm] */
951                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
952             /* Ignore stores of argument registers to the stack.  */
953             ;
954
955           else if ((insn & 0xffd0) == 0xf800    /* str{bh} Rt,[Rn,#+/-imm] */
956                    && (inst2 & 0x0d00) == 0x0c00
957                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
958             /* Ignore stores of argument registers to the stack.  */
959             ;
960
961           else if ((insn & 0xffd0) == 0xe890    /* ldmia Rn[!],
962                                                    { registers } */
963                    && (inst2 & 0x8000) == 0x0000
964                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
965             /* Ignore block loads from the stack, potentially copying
966                parameters from memory.  */
967             ;
968
969           else if ((insn & 0xffb0) == 0xe950    /* ldrd Rt, Rt2,
970                                                    [Rn, #+/-imm] */
971                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
972             /* Similarly ignore dual loads from the stack.  */
973             ;
974
975           else if ((insn & 0xfff0) == 0xf850    /* ldr Rt,[Rn,#+/-imm] */
976                    && (inst2 & 0x0d00) == 0x0c00
977                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
978             /* Similarly ignore single loads from the stack.  */
979             ;
980
981           else if ((insn & 0xfff0) == 0xf8d0    /* ldr.w Rt,[Rn,#imm] */
982                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
983             /* Similarly ignore single loads from the stack.  */
984             ;
985
986           else if ((insn & 0xfbf0) == 0xf100    /* add.w Rd, Rn, #imm */
987                    && (inst2 & 0x8000) == 0x0000)
988             {
989               unsigned int imm = ((bits (insn, 10, 10) << 11)
990                                   | (bits (inst2, 12, 14) << 8)
991                                   | bits (inst2, 0, 7));
992
993               regs[bits (inst2, 8, 11)]
994                 = pv_add_constant (regs[bits (insn, 0, 3)],
995                                    thumb_expand_immediate (imm));
996             }
997
998           else if ((insn & 0xfbf0) == 0xf200    /* addw Rd, Rn, #imm */
999                    && (inst2 & 0x8000) == 0x0000)
1000             {
1001               unsigned int imm = ((bits (insn, 10, 10) << 11)
1002                                   | (bits (inst2, 12, 14) << 8)
1003                                   | bits (inst2, 0, 7));
1004
1005               regs[bits (inst2, 8, 11)]
1006                 = pv_add_constant (regs[bits (insn, 0, 3)], imm);
1007             }
1008
1009           else if ((insn & 0xfbf0) == 0xf1a0    /* sub.w Rd, Rn, #imm */
1010                    && (inst2 & 0x8000) == 0x0000)
1011             {
1012               unsigned int imm = ((bits (insn, 10, 10) << 11)
1013                                   | (bits (inst2, 12, 14) << 8)
1014                                   | bits (inst2, 0, 7));
1015
1016               regs[bits (inst2, 8, 11)]
1017                 = pv_add_constant (regs[bits (insn, 0, 3)],
1018                                    - (CORE_ADDR) thumb_expand_immediate (imm));
1019             }
1020
1021           else if ((insn & 0xfbf0) == 0xf2a0    /* subw Rd, Rn, #imm */
1022                    && (inst2 & 0x8000) == 0x0000)
1023             {
1024               unsigned int imm = ((bits (insn, 10, 10) << 11)
1025                                   | (bits (inst2, 12, 14) << 8)
1026                                   | bits (inst2, 0, 7));
1027
1028               regs[bits (inst2, 8, 11)]
1029                 = pv_add_constant (regs[bits (insn, 0, 3)], - (CORE_ADDR) imm);
1030             }
1031
1032           else if ((insn & 0xfbff) == 0xf04f)   /* mov.w Rd, #const */
1033             {
1034               unsigned int imm = ((bits (insn, 10, 10) << 11)
1035                                   | (bits (inst2, 12, 14) << 8)
1036                                   | bits (inst2, 0, 7));
1037
1038               regs[bits (inst2, 8, 11)]
1039                 = pv_constant (thumb_expand_immediate (imm));
1040             }
1041
1042           else if ((insn & 0xfbf0) == 0xf240)   /* movw Rd, #const */
1043             {
1044               unsigned int imm
1045                 = EXTRACT_MOVW_MOVT_IMM_T (insn, inst2);
1046
1047               regs[bits (inst2, 8, 11)] = pv_constant (imm);
1048             }
1049
1050           else if (insn == 0xea5f               /* mov.w Rd,Rm */
1051                    && (inst2 & 0xf0f0) == 0)
1052             {
1053               int dst_reg = (inst2 & 0x0f00) >> 8;
1054               int src_reg = inst2 & 0xf;
1055               regs[dst_reg] = regs[src_reg];
1056             }
1057
1058           else if ((insn & 0xff7f) == 0xf85f)   /* ldr.w Rt,<label> */
1059             {
1060               /* Constant pool loads.  */
1061               unsigned int constant;
1062               CORE_ADDR loc;
1063
1064               offset = bits (insn, 0, 11);
1065               if (insn & 0x0080)
1066                 loc = start + 4 + offset;
1067               else
1068                 loc = start + 4 - offset;
1069
1070               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1071               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1072             }
1073
1074           else if ((insn & 0xff7f) == 0xe95f)   /* ldrd Rt,Rt2,<label> */
1075             {
1076               /* Constant pool loads.  */
1077               unsigned int constant;
1078               CORE_ADDR loc;
1079
1080               offset = bits (insn, 0, 7) << 2;
1081               if (insn & 0x0080)
1082                 loc = start + 4 + offset;
1083               else
1084                 loc = start + 4 - offset;
1085
1086               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1087               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1088
1089               constant = read_memory_unsigned_integer (loc + 4, 4, byte_order);
1090               regs[bits (inst2, 8, 11)] = pv_constant (constant);
1091             }
1092
1093           else if (thumb2_instruction_changes_pc (insn, inst2))
1094             {
1095               /* Don't scan past anything that might change control flow.  */
1096               break;
1097             }
1098           else
1099             {
1100               /* The optimizer might shove anything into the prologue,
1101                  so we just skip what we don't recognize.  */
1102               unrecognized_pc = start;
1103             }
1104
1105           start += 2;
1106         }
1107       else if (thumb_instruction_changes_pc (insn))
1108         {
1109           /* Don't scan past anything that might change control flow.  */
1110           break;
1111         }
1112       else
1113         {
1114           /* The optimizer might shove anything into the prologue,
1115              so we just skip what we don't recognize.  */
1116           unrecognized_pc = start;
1117         }
1118
1119       start += 2;
1120     }
1121
1122   if (arm_debug)
1123     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1124                         paddress (gdbarch, start));
1125
1126   if (unrecognized_pc == 0)
1127     unrecognized_pc = start;
1128
1129   if (cache == NULL)
1130     {
1131       do_cleanups (back_to);
1132       return unrecognized_pc;
1133     }
1134
1135   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1136     {
1137       /* Frame pointer is fp.  Frame size is constant.  */
1138       cache->framereg = ARM_FP_REGNUM;
1139       cache->framesize = -regs[ARM_FP_REGNUM].k;
1140     }
1141   else if (pv_is_register (regs[THUMB_FP_REGNUM], ARM_SP_REGNUM))
1142     {
1143       /* Frame pointer is r7.  Frame size is constant.  */
1144       cache->framereg = THUMB_FP_REGNUM;
1145       cache->framesize = -regs[THUMB_FP_REGNUM].k;
1146     }
1147   else if (pv_is_register (regs[ARM_SP_REGNUM], ARM_SP_REGNUM))
1148     {
1149       /* Try the stack pointer... this is a bit desperate.  */
1150       cache->framereg = ARM_SP_REGNUM;
1151       cache->framesize = -regs[ARM_SP_REGNUM].k;
1152     }
1153   else
1154     {
1155       /* We're just out of luck.  We don't know where the frame is.  */
1156       cache->framereg = -1;
1157       cache->framesize = 0;
1158     }
1159
1160   for (i = 0; i < 16; i++)
1161     if (pv_area_find_reg (stack, gdbarch, i, &offset))
1162       cache->saved_regs[i].addr = offset;
1163
1164   do_cleanups (back_to);
1165   return unrecognized_pc;
1166 }
1167
1168
1169 /* Try to analyze the instructions starting from PC, which load symbol
1170    __stack_chk_guard.  Return the address of instruction after loading this
1171    symbol, set the dest register number to *BASEREG, and set the size of
1172    instructions for loading symbol in OFFSET.  Return 0 if instructions are
1173    not recognized.  */
1174
1175 static CORE_ADDR
1176 arm_analyze_load_stack_chk_guard(CORE_ADDR pc, struct gdbarch *gdbarch,
1177                                  unsigned int *destreg, int *offset)
1178 {
1179   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1180   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1181   unsigned int low, high, address;
1182
1183   address = 0;
1184   if (is_thumb)
1185     {
1186       unsigned short insn1
1187         = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
1188
1189       if ((insn1 & 0xf800) == 0x4800) /* ldr Rd, #immed */
1190         {
1191           *destreg = bits (insn1, 8, 10);
1192           *offset = 2;
1193           address = bits (insn1, 0, 7);
1194         }
1195       else if ((insn1 & 0xfbf0) == 0xf240) /* movw Rd, #const */
1196         {
1197           unsigned short insn2
1198             = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
1199
1200           low = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1201
1202           insn1
1203             = read_memory_unsigned_integer (pc + 4, 2, byte_order_for_code);
1204           insn2
1205             = read_memory_unsigned_integer (pc + 6, 2, byte_order_for_code);
1206
1207           /* movt Rd, #const */
1208           if ((insn1 & 0xfbc0) == 0xf2c0)
1209             {
1210               high = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1211               *destreg = bits (insn2, 8, 11);
1212               *offset = 8;
1213               address = (high << 16 | low);
1214             }
1215         }
1216     }
1217   else
1218     {
1219       unsigned int insn
1220         = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
1221
1222       if ((insn & 0x0e5f0000) == 0x041f0000) /* ldr Rd, #immed */
1223         {
1224           address = bits (insn, 0, 11);
1225           *destreg = bits (insn, 12, 15);
1226           *offset = 4;
1227         }
1228       else if ((insn & 0x0ff00000) == 0x03000000) /* movw Rd, #const */
1229         {
1230           low = EXTRACT_MOVW_MOVT_IMM_A (insn);
1231
1232           insn
1233             = read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code);
1234
1235           if ((insn & 0x0ff00000) == 0x03400000) /* movt Rd, #const */
1236             {
1237               high = EXTRACT_MOVW_MOVT_IMM_A (insn);
1238               *destreg = bits (insn, 12, 15);
1239               *offset = 8;
1240               address = (high << 16 | low);
1241             }
1242         }
1243     }
1244
1245   return address;
1246 }
1247
1248 /* Try to skip a sequence of instructions used for stack protector.  If PC
1249    points to the first instruction of this sequence, return the address of
1250    first instruction after this sequence, otherwise, return original PC.
1251
1252    On arm, this sequence of instructions is composed of mainly three steps,
1253      Step 1: load symbol __stack_chk_guard,
1254      Step 2: load from address of __stack_chk_guard,
1255      Step 3: store it to somewhere else.
1256
1257    Usually, instructions on step 2 and step 3 are the same on various ARM
1258    architectures.  On step 2, it is one instruction 'ldr Rx, [Rn, #0]', and
1259    on step 3, it is also one instruction 'str Rx, [r7, #immd]'.  However,
1260    instructions in step 1 vary from different ARM architectures.  On ARMv7,
1261    they are,
1262
1263         movw    Rn, #:lower16:__stack_chk_guard
1264         movt    Rn, #:upper16:__stack_chk_guard
1265
1266    On ARMv5t, it is,
1267
1268         ldr     Rn, .Label
1269         ....
1270         .Lable:
1271         .word   __stack_chk_guard
1272
1273    Since ldr/str is a very popular instruction, we can't use them as
1274    'fingerprint' or 'signature' of stack protector sequence.  Here we choose
1275    sequence {movw/movt, ldr}/ldr/str plus symbol __stack_chk_guard, if not
1276    stripped, as the 'fingerprint' of a stack protector cdoe sequence.  */
1277
1278 static CORE_ADDR
1279 arm_skip_stack_protector(CORE_ADDR pc, struct gdbarch *gdbarch)
1280 {
1281   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1282   unsigned int address, basereg;
1283   struct minimal_symbol *stack_chk_guard;
1284   int offset;
1285   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1286   CORE_ADDR addr;
1287
1288   /* Try to parse the instructions in Step 1.  */
1289   addr = arm_analyze_load_stack_chk_guard (pc, gdbarch,
1290                                            &basereg, &offset);
1291   if (!addr)
1292     return pc;
1293
1294   stack_chk_guard = lookup_minimal_symbol_by_pc (addr);
1295   /* If name of symbol doesn't start with '__stack_chk_guard', this
1296      instruction sequence is not for stack protector.  If symbol is
1297      removed, we conservatively think this sequence is for stack protector.  */
1298   if (stack_chk_guard
1299       && strncmp (SYMBOL_LINKAGE_NAME (stack_chk_guard), "__stack_chk_guard",
1300                   strlen ("__stack_chk_guard")) != 0)
1301    return pc;
1302
1303   if (is_thumb)
1304     {
1305       unsigned int destreg;
1306       unsigned short insn
1307         = read_memory_unsigned_integer (pc + offset, 2, byte_order_for_code);
1308
1309       /* Step 2: ldr Rd, [Rn, #immed], encoding T1.  */
1310       if ((insn & 0xf800) != 0x6800)
1311         return pc;
1312       if (bits (insn, 3, 5) != basereg)
1313         return pc;
1314       destreg = bits (insn, 0, 2);
1315
1316       insn = read_memory_unsigned_integer (pc + offset + 2, 2,
1317                                            byte_order_for_code);
1318       /* Step 3: str Rd, [Rn, #immed], encoding T1.  */
1319       if ((insn & 0xf800) != 0x6000)
1320         return pc;
1321       if (destreg != bits (insn, 0, 2))
1322         return pc;
1323     }
1324   else
1325     {
1326       unsigned int destreg;
1327       unsigned int insn
1328         = read_memory_unsigned_integer (pc + offset, 4, byte_order_for_code);
1329
1330       /* Step 2: ldr Rd, [Rn, #immed], encoding A1.  */
1331       if ((insn & 0x0e500000) != 0x04100000)
1332         return pc;
1333       if (bits (insn, 16, 19) != basereg)
1334         return pc;
1335       destreg = bits (insn, 12, 15);
1336       /* Step 3: str Rd, [Rn, #immed], encoding A1.  */
1337       insn = read_memory_unsigned_integer (pc + offset + 4,
1338                                            4, byte_order_for_code);
1339       if ((insn & 0x0e500000) != 0x04000000)
1340         return pc;
1341       if (bits (insn, 12, 15) != destreg)
1342         return pc;
1343     }
1344   /* The size of total two instructions ldr/str is 4 on Thumb-2, while 8
1345      on arm.  */
1346   if (is_thumb)
1347     return pc + offset + 4;
1348   else
1349     return pc + offset + 8;
1350 }
1351
1352 /* Advance the PC across any function entry prologue instructions to
1353    reach some "real" code.
1354
1355    The APCS (ARM Procedure Call Standard) defines the following
1356    prologue:
1357
1358    mov          ip, sp
1359    [stmfd       sp!, {a1,a2,a3,a4}]
1360    stmfd        sp!, {...,fp,ip,lr,pc}
1361    [stfe        f7, [sp, #-12]!]
1362    [stfe        f6, [sp, #-12]!]
1363    [stfe        f5, [sp, #-12]!]
1364    [stfe        f4, [sp, #-12]!]
1365    sub fp, ip, #nn @@ nn == 20 or 4 depending on second insn.  */
1366
1367 static CORE_ADDR
1368 arm_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1369 {
1370   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1371   unsigned long inst;
1372   CORE_ADDR skip_pc;
1373   CORE_ADDR func_addr, limit_pc;
1374   struct symtab_and_line sal;
1375
1376   /* See if we can determine the end of the prologue via the symbol table.
1377      If so, then return either PC, or the PC after the prologue, whichever
1378      is greater.  */
1379   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1380     {
1381       CORE_ADDR post_prologue_pc
1382         = skip_prologue_using_sal (gdbarch, func_addr);
1383       struct symtab *s = find_pc_symtab (func_addr);
1384
1385       if (post_prologue_pc)
1386         post_prologue_pc
1387           = arm_skip_stack_protector (post_prologue_pc, gdbarch);
1388
1389
1390       /* GCC always emits a line note before the prologue and another
1391          one after, even if the two are at the same address or on the
1392          same line.  Take advantage of this so that we do not need to
1393          know every instruction that might appear in the prologue.  We
1394          will have producer information for most binaries; if it is
1395          missing (e.g. for -gstabs), assuming the GNU tools.  */
1396       if (post_prologue_pc
1397           && (s == NULL
1398               || s->producer == NULL
1399               || strncmp (s->producer, "GNU ", sizeof ("GNU ") - 1) == 0))
1400         return post_prologue_pc;
1401
1402       if (post_prologue_pc != 0)
1403         {
1404           CORE_ADDR analyzed_limit;
1405
1406           /* For non-GCC compilers, make sure the entire line is an
1407              acceptable prologue; GDB will round this function's
1408              return value up to the end of the following line so we
1409              can not skip just part of a line (and we do not want to).
1410
1411              RealView does not treat the prologue specially, but does
1412              associate prologue code with the opening brace; so this
1413              lets us skip the first line if we think it is the opening
1414              brace.  */
1415           if (arm_pc_is_thumb (gdbarch, func_addr))
1416             analyzed_limit = thumb_analyze_prologue (gdbarch, func_addr,
1417                                                      post_prologue_pc, NULL);
1418           else
1419             analyzed_limit = arm_analyze_prologue (gdbarch, func_addr,
1420                                                    post_prologue_pc, NULL);
1421
1422           if (analyzed_limit != post_prologue_pc)
1423             return func_addr;
1424
1425           return post_prologue_pc;
1426         }
1427     }
1428
1429   /* Can't determine prologue from the symbol table, need to examine
1430      instructions.  */
1431
1432   /* Find an upper limit on the function prologue using the debug
1433      information.  If the debug information could not be used to provide
1434      that bound, then use an arbitrary large number as the upper bound.  */
1435   /* Like arm_scan_prologue, stop no later than pc + 64.  */
1436   limit_pc = skip_prologue_using_sal (gdbarch, pc);
1437   if (limit_pc == 0)
1438     limit_pc = pc + 64;          /* Magic.  */
1439
1440
1441   /* Check if this is Thumb code.  */
1442   if (arm_pc_is_thumb (gdbarch, pc))
1443     return thumb_analyze_prologue (gdbarch, pc, limit_pc, NULL);
1444
1445   for (skip_pc = pc; skip_pc < limit_pc; skip_pc += 4)
1446     {
1447       inst = read_memory_unsigned_integer (skip_pc, 4, byte_order_for_code);
1448
1449       /* "mov ip, sp" is no longer a required part of the prologue.  */
1450       if (inst == 0xe1a0c00d)                   /* mov ip, sp */
1451         continue;
1452
1453       if ((inst & 0xfffff000) == 0xe28dc000)    /* add ip, sp #n */
1454         continue;
1455
1456       if ((inst & 0xfffff000) == 0xe24dc000)    /* sub ip, sp #n */
1457         continue;
1458
1459       /* Some prologues begin with "str lr, [sp, #-4]!".  */
1460       if (inst == 0xe52de004)                   /* str lr, [sp, #-4]! */
1461         continue;
1462
1463       if ((inst & 0xfffffff0) == 0xe92d0000)    /* stmfd sp!,{a1,a2,a3,a4} */
1464         continue;
1465
1466       if ((inst & 0xfffff800) == 0xe92dd800)    /* stmfd sp!,{fp,ip,lr,pc} */
1467         continue;
1468
1469       /* Any insns after this point may float into the code, if it makes
1470          for better instruction scheduling, so we skip them only if we
1471          find them, but still consider the function to be frame-ful.  */
1472
1473       /* We may have either one sfmfd instruction here, or several stfe
1474          insns, depending on the version of floating point code we
1475          support.  */
1476       if ((inst & 0xffbf0fff) == 0xec2d0200)    /* sfmfd fn, <cnt>, [sp]! */
1477         continue;
1478
1479       if ((inst & 0xffff8fff) == 0xed6d0103)    /* stfe fn, [sp, #-12]! */
1480         continue;
1481
1482       if ((inst & 0xfffff000) == 0xe24cb000)    /* sub fp, ip, #nn */
1483         continue;
1484
1485       if ((inst & 0xfffff000) == 0xe24dd000)    /* sub sp, sp, #nn */
1486         continue;
1487
1488       if ((inst & 0xffffc000) == 0xe54b0000     /* strb r(0123),[r11,#-nn] */
1489           || (inst & 0xffffc0f0) == 0xe14b00b0  /* strh r(0123),[r11,#-nn] */
1490           || (inst & 0xffffc000) == 0xe50b0000) /* str  r(0123),[r11,#-nn] */
1491         continue;
1492
1493       if ((inst & 0xffffc000) == 0xe5cd0000     /* strb r(0123),[sp,#nn] */
1494           || (inst & 0xffffc0f0) == 0xe1cd00b0  /* strh r(0123),[sp,#nn] */
1495           || (inst & 0xffffc000) == 0xe58d0000) /* str  r(0123),[sp,#nn] */
1496         continue;
1497
1498       /* Un-recognized instruction; stop scanning.  */
1499       break;
1500     }
1501
1502   return skip_pc;               /* End of prologue.  */
1503 }
1504
1505 /* *INDENT-OFF* */
1506 /* Function: thumb_scan_prologue (helper function for arm_scan_prologue)
1507    This function decodes a Thumb function prologue to determine:
1508      1) the size of the stack frame
1509      2) which registers are saved on it
1510      3) the offsets of saved regs
1511      4) the offset from the stack pointer to the frame pointer
1512
1513    A typical Thumb function prologue would create this stack frame
1514    (offsets relative to FP)
1515      old SP ->  24  stack parameters
1516                 20  LR
1517                 16  R7
1518      R7 ->       0  local variables (16 bytes)
1519      SP ->     -12  additional stack space (12 bytes)
1520    The frame size would thus be 36 bytes, and the frame offset would be
1521    12 bytes.  The frame register is R7.
1522    
1523    The comments for thumb_skip_prolog() describe the algorithm we use
1524    to detect the end of the prolog.  */
1525 /* *INDENT-ON* */
1526
1527 static void
1528 thumb_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR prev_pc,
1529                      CORE_ADDR block_addr, struct arm_prologue_cache *cache)
1530 {
1531   CORE_ADDR prologue_start;
1532   CORE_ADDR prologue_end;
1533   CORE_ADDR current_pc;
1534
1535   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1536                                 &prologue_end))
1537     {
1538       /* See comment in arm_scan_prologue for an explanation of
1539          this heuristics.  */
1540       if (prologue_end > prologue_start + 64)
1541         {
1542           prologue_end = prologue_start + 64;
1543         }
1544     }
1545   else
1546     /* We're in the boondocks: we have no idea where the start of the
1547        function is.  */
1548     return;
1549
1550   prologue_end = min (prologue_end, prev_pc);
1551
1552   thumb_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
1553 }
1554
1555 /* Return 1 if THIS_INSTR might change control flow, 0 otherwise.  */
1556
1557 static int
1558 arm_instruction_changes_pc (uint32_t this_instr)
1559 {
1560   if (bits (this_instr, 28, 31) == INST_NV)
1561     /* Unconditional instructions.  */
1562     switch (bits (this_instr, 24, 27))
1563       {
1564       case 0xa:
1565       case 0xb:
1566         /* Branch with Link and change to Thumb.  */
1567         return 1;
1568       case 0xc:
1569       case 0xd:
1570       case 0xe:
1571         /* Coprocessor register transfer.  */
1572         if (bits (this_instr, 12, 15) == 15)
1573           error (_("Invalid update to pc in instruction"));
1574         return 0;
1575       default:
1576         return 0;
1577       }
1578   else
1579     switch (bits (this_instr, 25, 27))
1580       {
1581       case 0x0:
1582         if (bits (this_instr, 23, 24) == 2 && bit (this_instr, 20) == 0)
1583           {
1584             /* Multiplies and extra load/stores.  */
1585             if (bit (this_instr, 4) == 1 && bit (this_instr, 7) == 1)
1586               /* Neither multiplies nor extension load/stores are allowed
1587                  to modify PC.  */
1588               return 0;
1589
1590             /* Otherwise, miscellaneous instructions.  */
1591
1592             /* BX <reg>, BXJ <reg>, BLX <reg> */
1593             if (bits (this_instr, 4, 27) == 0x12fff1
1594                 || bits (this_instr, 4, 27) == 0x12fff2
1595                 || bits (this_instr, 4, 27) == 0x12fff3)
1596               return 1;
1597
1598             /* Other miscellaneous instructions are unpredictable if they
1599                modify PC.  */
1600             return 0;
1601           }
1602         /* Data processing instruction.  Fall through.  */
1603
1604       case 0x1:
1605         if (bits (this_instr, 12, 15) == 15)
1606           return 1;
1607         else
1608           return 0;
1609
1610       case 0x2:
1611       case 0x3:
1612         /* Media instructions and architecturally undefined instructions.  */
1613         if (bits (this_instr, 25, 27) == 3 && bit (this_instr, 4) == 1)
1614           return 0;
1615
1616         /* Stores.  */
1617         if (bit (this_instr, 20) == 0)
1618           return 0;
1619
1620         /* Loads.  */
1621         if (bits (this_instr, 12, 15) == ARM_PC_REGNUM)
1622           return 1;
1623         else
1624           return 0;
1625
1626       case 0x4:
1627         /* Load/store multiple.  */
1628         if (bit (this_instr, 20) == 1 && bit (this_instr, 15) == 1)
1629           return 1;
1630         else
1631           return 0;
1632
1633       case 0x5:
1634         /* Branch and branch with link.  */
1635         return 1;
1636
1637       case 0x6:
1638       case 0x7:
1639         /* Coprocessor transfers or SWIs can not affect PC.  */
1640         return 0;
1641
1642       default:
1643         internal_error (__FILE__, __LINE__, _("bad value in switch"));
1644       }
1645 }
1646
1647 /* Analyze an ARM mode prologue starting at PROLOGUE_START and
1648    continuing no further than PROLOGUE_END.  If CACHE is non-NULL,
1649    fill it in.  Return the first address not recognized as a prologue
1650    instruction.
1651
1652    We recognize all the instructions typically found in ARM prologues,
1653    plus harmless instructions which can be skipped (either for analysis
1654    purposes, or a more restrictive set that can be skipped when finding
1655    the end of the prologue).  */
1656
1657 static CORE_ADDR
1658 arm_analyze_prologue (struct gdbarch *gdbarch,
1659                       CORE_ADDR prologue_start, CORE_ADDR prologue_end,
1660                       struct arm_prologue_cache *cache)
1661 {
1662   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1663   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1664   int regno;
1665   CORE_ADDR offset, current_pc;
1666   pv_t regs[ARM_FPS_REGNUM];
1667   struct pv_area *stack;
1668   struct cleanup *back_to;
1669   int framereg, framesize;
1670   CORE_ADDR unrecognized_pc = 0;
1671
1672   /* Search the prologue looking for instructions that set up the
1673      frame pointer, adjust the stack pointer, and save registers.
1674
1675      Be careful, however, and if it doesn't look like a prologue,
1676      don't try to scan it.  If, for instance, a frameless function
1677      begins with stmfd sp!, then we will tell ourselves there is
1678      a frame, which will confuse stack traceback, as well as "finish" 
1679      and other operations that rely on a knowledge of the stack
1680      traceback.  */
1681
1682   for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1683     regs[regno] = pv_register (regno, 0);
1684   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1685   back_to = make_cleanup_free_pv_area (stack);
1686
1687   for (current_pc = prologue_start;
1688        current_pc < prologue_end;
1689        current_pc += 4)
1690     {
1691       unsigned int insn
1692         = read_memory_unsigned_integer (current_pc, 4, byte_order_for_code);
1693
1694       if (insn == 0xe1a0c00d)           /* mov ip, sp */
1695         {
1696           regs[ARM_IP_REGNUM] = regs[ARM_SP_REGNUM];
1697           continue;
1698         }
1699       else if ((insn & 0xfff00000) == 0xe2800000        /* add Rd, Rn, #n */
1700                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1701         {
1702           unsigned imm = insn & 0xff;                   /* immediate value */
1703           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1704           int rd = bits (insn, 12, 15);
1705           imm = (imm >> rot) | (imm << (32 - rot));
1706           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], imm);
1707           continue;
1708         }
1709       else if ((insn & 0xfff00000) == 0xe2400000        /* sub Rd, Rn, #n */
1710                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1711         {
1712           unsigned imm = insn & 0xff;                   /* immediate value */
1713           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1714           int rd = bits (insn, 12, 15);
1715           imm = (imm >> rot) | (imm << (32 - rot));
1716           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], -imm);
1717           continue;
1718         }
1719       else if ((insn & 0xffff0fff) == 0xe52d0004)       /* str Rd,
1720                                                            [sp, #-4]! */
1721         {
1722           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1723             break;
1724           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1725           pv_area_store (stack, regs[ARM_SP_REGNUM], 4,
1726                          regs[bits (insn, 12, 15)]);
1727           continue;
1728         }
1729       else if ((insn & 0xffff0000) == 0xe92d0000)
1730         /* stmfd sp!, {..., fp, ip, lr, pc}
1731            or
1732            stmfd sp!, {a1, a2, a3, a4}  */
1733         {
1734           int mask = insn & 0xffff;
1735
1736           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1737             break;
1738
1739           /* Calculate offsets of saved registers.  */
1740           for (regno = ARM_PC_REGNUM; regno >= 0; regno--)
1741             if (mask & (1 << regno))
1742               {
1743                 regs[ARM_SP_REGNUM]
1744                   = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1745                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
1746               }
1747         }
1748       else if ((insn & 0xffff0000) == 0xe54b0000        /* strb rx,[r11,#-n] */
1749                || (insn & 0xffff00f0) == 0xe14b00b0     /* strh rx,[r11,#-n] */
1750                || (insn & 0xffffc000) == 0xe50b0000)    /* str  rx,[r11,#-n] */
1751         {
1752           /* No need to add this to saved_regs -- it's just an arg reg.  */
1753           continue;
1754         }
1755       else if ((insn & 0xffff0000) == 0xe5cd0000        /* strb rx,[sp,#n] */
1756                || (insn & 0xffff00f0) == 0xe1cd00b0     /* strh rx,[sp,#n] */
1757                || (insn & 0xffffc000) == 0xe58d0000)    /* str  rx,[sp,#n] */
1758         {
1759           /* No need to add this to saved_regs -- it's just an arg reg.  */
1760           continue;
1761         }
1762       else if ((insn & 0xfff00000) == 0xe8800000        /* stm Rn,
1763                                                            { registers } */
1764                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1765         {
1766           /* No need to add this to saved_regs -- it's just arg regs.  */
1767           continue;
1768         }
1769       else if ((insn & 0xfffff000) == 0xe24cb000)       /* sub fp, ip #n */
1770         {
1771           unsigned imm = insn & 0xff;                   /* immediate value */
1772           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1773           imm = (imm >> rot) | (imm << (32 - rot));
1774           regs[ARM_FP_REGNUM] = pv_add_constant (regs[ARM_IP_REGNUM], -imm);
1775         }
1776       else if ((insn & 0xfffff000) == 0xe24dd000)       /* sub sp, sp #n */
1777         {
1778           unsigned imm = insn & 0xff;                   /* immediate value */
1779           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1780           imm = (imm >> rot) | (imm << (32 - rot));
1781           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -imm);
1782         }
1783       else if ((insn & 0xffff7fff) == 0xed6d0103        /* stfe f?,
1784                                                            [sp, -#c]! */
1785                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1786         {
1787           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1788             break;
1789
1790           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1791           regno = ARM_F0_REGNUM + ((insn >> 12) & 0x07);
1792           pv_area_store (stack, regs[ARM_SP_REGNUM], 12, regs[regno]);
1793         }
1794       else if ((insn & 0xffbf0fff) == 0xec2d0200        /* sfmfd f0, 4,
1795                                                            [sp!] */
1796                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1797         {
1798           int n_saved_fp_regs;
1799           unsigned int fp_start_reg, fp_bound_reg;
1800
1801           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1802             break;
1803
1804           if ((insn & 0x800) == 0x800)          /* N0 is set */
1805             {
1806               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1807                 n_saved_fp_regs = 3;
1808               else
1809                 n_saved_fp_regs = 1;
1810             }
1811           else
1812             {
1813               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1814                 n_saved_fp_regs = 2;
1815               else
1816                 n_saved_fp_regs = 4;
1817             }
1818
1819           fp_start_reg = ARM_F0_REGNUM + ((insn >> 12) & 0x7);
1820           fp_bound_reg = fp_start_reg + n_saved_fp_regs;
1821           for (; fp_start_reg < fp_bound_reg; fp_start_reg++)
1822             {
1823               regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1824               pv_area_store (stack, regs[ARM_SP_REGNUM], 12,
1825                              regs[fp_start_reg++]);
1826             }
1827         }
1828       else if ((insn & 0xff000000) == 0xeb000000 && cache == NULL) /* bl */
1829         {
1830           /* Allow some special function calls when skipping the
1831              prologue; GCC generates these before storing arguments to
1832              the stack.  */
1833           CORE_ADDR dest = BranchDest (current_pc, insn);
1834
1835           if (skip_prologue_function (gdbarch, dest, 0))
1836             continue;
1837           else
1838             break;
1839         }
1840       else if ((insn & 0xf0000000) != 0xe0000000)
1841         break;                  /* Condition not true, exit early.  */
1842       else if (arm_instruction_changes_pc (insn))
1843         /* Don't scan past anything that might change control flow.  */
1844         break;
1845       else if ((insn & 0xfe500000) == 0xe8100000)       /* ldm */
1846         {
1847           /* Ignore block loads from the stack, potentially copying
1848              parameters from memory.  */
1849           if (pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1850             continue;
1851           else
1852             break;
1853         }
1854       else if ((insn & 0xfc500000) == 0xe4100000)
1855         {
1856           /* Similarly ignore single loads from the stack.  */
1857           if (pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1858             continue;
1859           else
1860             break;
1861         }
1862       else if ((insn & 0xffff0ff0) == 0xe1a00000)
1863         /* MOV Rd, Rm.  Skip register copies, i.e. saves to another
1864            register instead of the stack.  */
1865         continue;
1866       else
1867         {
1868           /* The optimizer might shove anything into the prologue,
1869              so we just skip what we don't recognize.  */
1870           unrecognized_pc = current_pc;
1871           continue;
1872         }
1873     }
1874
1875   if (unrecognized_pc == 0)
1876     unrecognized_pc = current_pc;
1877
1878   /* The frame size is just the distance from the frame register
1879      to the original stack pointer.  */
1880   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1881     {
1882       /* Frame pointer is fp.  */
1883       framereg = ARM_FP_REGNUM;
1884       framesize = -regs[ARM_FP_REGNUM].k;
1885     }
1886   else if (pv_is_register (regs[ARM_SP_REGNUM], ARM_SP_REGNUM))
1887     {
1888       /* Try the stack pointer... this is a bit desperate.  */
1889       framereg = ARM_SP_REGNUM;
1890       framesize = -regs[ARM_SP_REGNUM].k;
1891     }
1892   else
1893     {
1894       /* We're just out of luck.  We don't know where the frame is.  */
1895       framereg = -1;
1896       framesize = 0;
1897     }
1898
1899   if (cache)
1900     {
1901       cache->framereg = framereg;
1902       cache->framesize = framesize;
1903
1904       for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1905         if (pv_area_find_reg (stack, gdbarch, regno, &offset))
1906           cache->saved_regs[regno].addr = offset;
1907     }
1908
1909   if (arm_debug)
1910     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1911                         paddress (gdbarch, unrecognized_pc));
1912
1913   do_cleanups (back_to);
1914   return unrecognized_pc;
1915 }
1916
1917 static void
1918 arm_scan_prologue (struct frame_info *this_frame,
1919                    struct arm_prologue_cache *cache)
1920 {
1921   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1922   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1923   int regno;
1924   CORE_ADDR prologue_start, prologue_end, current_pc;
1925   CORE_ADDR prev_pc = get_frame_pc (this_frame);
1926   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1927   pv_t regs[ARM_FPS_REGNUM];
1928   struct pv_area *stack;
1929   struct cleanup *back_to;
1930   CORE_ADDR offset;
1931
1932   /* Assume there is no frame until proven otherwise.  */
1933   cache->framereg = ARM_SP_REGNUM;
1934   cache->framesize = 0;
1935
1936   /* Check for Thumb prologue.  */
1937   if (arm_frame_is_thumb (this_frame))
1938     {
1939       thumb_scan_prologue (gdbarch, prev_pc, block_addr, cache);
1940       return;
1941     }
1942
1943   /* Find the function prologue.  If we can't find the function in
1944      the symbol table, peek in the stack frame to find the PC.  */
1945   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1946                                 &prologue_end))
1947     {
1948       /* One way to find the end of the prologue (which works well
1949          for unoptimized code) is to do the following:
1950
1951             struct symtab_and_line sal = find_pc_line (prologue_start, 0);
1952
1953             if (sal.line == 0)
1954               prologue_end = prev_pc;
1955             else if (sal.end < prologue_end)
1956               prologue_end = sal.end;
1957
1958          This mechanism is very accurate so long as the optimizer
1959          doesn't move any instructions from the function body into the
1960          prologue.  If this happens, sal.end will be the last
1961          instruction in the first hunk of prologue code just before
1962          the first instruction that the scheduler has moved from
1963          the body to the prologue.
1964
1965          In order to make sure that we scan all of the prologue
1966          instructions, we use a slightly less accurate mechanism which
1967          may scan more than necessary.  To help compensate for this
1968          lack of accuracy, the prologue scanning loop below contains
1969          several clauses which'll cause the loop to terminate early if
1970          an implausible prologue instruction is encountered.
1971
1972          The expression
1973
1974               prologue_start + 64
1975
1976          is a suitable endpoint since it accounts for the largest
1977          possible prologue plus up to five instructions inserted by
1978          the scheduler.  */
1979
1980       if (prologue_end > prologue_start + 64)
1981         {
1982           prologue_end = prologue_start + 64;   /* See above.  */
1983         }
1984     }
1985   else
1986     {
1987       /* We have no symbol information.  Our only option is to assume this
1988          function has a standard stack frame and the normal frame register.
1989          Then, we can find the value of our frame pointer on entrance to
1990          the callee (or at the present moment if this is the innermost frame).
1991          The value stored there should be the address of the stmfd + 8.  */
1992       CORE_ADDR frame_loc;
1993       LONGEST return_value;
1994
1995       frame_loc = get_frame_register_unsigned (this_frame, ARM_FP_REGNUM);
1996       if (!safe_read_memory_integer (frame_loc, 4, byte_order, &return_value))
1997         return;
1998       else
1999         {
2000           prologue_start = gdbarch_addr_bits_remove
2001                              (gdbarch, return_value) - 8;
2002           prologue_end = prologue_start + 64;   /* See above.  */
2003         }
2004     }
2005
2006   if (prev_pc < prologue_end)
2007     prologue_end = prev_pc;
2008
2009   arm_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
2010 }
2011
2012 static struct arm_prologue_cache *
2013 arm_make_prologue_cache (struct frame_info *this_frame)
2014 {
2015   int reg;
2016   struct arm_prologue_cache *cache;
2017   CORE_ADDR unwound_fp;
2018
2019   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2020   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2021
2022   arm_scan_prologue (this_frame, cache);
2023
2024   unwound_fp = get_frame_register_unsigned (this_frame, cache->framereg);
2025   if (unwound_fp == 0)
2026     return cache;
2027
2028   cache->prev_sp = unwound_fp + cache->framesize;
2029
2030   /* Calculate actual addresses of saved registers using offsets
2031      determined by arm_scan_prologue.  */
2032   for (reg = 0; reg < gdbarch_num_regs (get_frame_arch (this_frame)); reg++)
2033     if (trad_frame_addr_p (cache->saved_regs, reg))
2034       cache->saved_regs[reg].addr += cache->prev_sp;
2035
2036   return cache;
2037 }
2038
2039 /* Our frame ID for a normal frame is the current function's starting PC
2040    and the caller's SP when we were called.  */
2041
2042 static void
2043 arm_prologue_this_id (struct frame_info *this_frame,
2044                       void **this_cache,
2045                       struct frame_id *this_id)
2046 {
2047   struct arm_prologue_cache *cache;
2048   struct frame_id id;
2049   CORE_ADDR pc, func;
2050
2051   if (*this_cache == NULL)
2052     *this_cache = arm_make_prologue_cache (this_frame);
2053   cache = *this_cache;
2054
2055   /* This is meant to halt the backtrace at "_start".  */
2056   pc = get_frame_pc (this_frame);
2057   if (pc <= gdbarch_tdep (get_frame_arch (this_frame))->lowest_pc)
2058     return;
2059
2060   /* If we've hit a wall, stop.  */
2061   if (cache->prev_sp == 0)
2062     return;
2063
2064   /* Use function start address as part of the frame ID.  If we cannot
2065      identify the start address (due to missing symbol information),
2066      fall back to just using the current PC.  */
2067   func = get_frame_func (this_frame);
2068   if (!func)
2069     func = pc;
2070
2071   id = frame_id_build (cache->prev_sp, func);
2072   *this_id = id;
2073 }
2074
2075 static struct value *
2076 arm_prologue_prev_register (struct frame_info *this_frame,
2077                             void **this_cache,
2078                             int prev_regnum)
2079 {
2080   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2081   struct arm_prologue_cache *cache;
2082
2083   if (*this_cache == NULL)
2084     *this_cache = arm_make_prologue_cache (this_frame);
2085   cache = *this_cache;
2086
2087   /* If we are asked to unwind the PC, then we need to return the LR
2088      instead.  The prologue may save PC, but it will point into this
2089      frame's prologue, not the next frame's resume location.  Also
2090      strip the saved T bit.  A valid LR may have the low bit set, but
2091      a valid PC never does.  */
2092   if (prev_regnum == ARM_PC_REGNUM)
2093     {
2094       CORE_ADDR lr;
2095
2096       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2097       return frame_unwind_got_constant (this_frame, prev_regnum,
2098                                         arm_addr_bits_remove (gdbarch, lr));
2099     }
2100
2101   /* SP is generally not saved to the stack, but this frame is
2102      identified by the next frame's stack pointer at the time of the call.
2103      The value was already reconstructed into PREV_SP.  */
2104   if (prev_regnum == ARM_SP_REGNUM)
2105     return frame_unwind_got_constant (this_frame, prev_regnum, cache->prev_sp);
2106
2107   /* The CPSR may have been changed by the call instruction and by the
2108      called function.  The only bit we can reconstruct is the T bit,
2109      by checking the low bit of LR as of the call.  This is a reliable
2110      indicator of Thumb-ness except for some ARM v4T pre-interworking
2111      Thumb code, which could get away with a clear low bit as long as
2112      the called function did not use bx.  Guess that all other
2113      bits are unchanged; the condition flags are presumably lost,
2114      but the processor status is likely valid.  */
2115   if (prev_regnum == ARM_PS_REGNUM)
2116     {
2117       CORE_ADDR lr, cpsr;
2118       ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
2119
2120       cpsr = get_frame_register_unsigned (this_frame, prev_regnum);
2121       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2122       if (IS_THUMB_ADDR (lr))
2123         cpsr |= t_bit;
2124       else
2125         cpsr &= ~t_bit;
2126       return frame_unwind_got_constant (this_frame, prev_regnum, cpsr);
2127     }
2128
2129   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
2130                                        prev_regnum);
2131 }
2132
2133 struct frame_unwind arm_prologue_unwind = {
2134   NORMAL_FRAME,
2135   arm_prologue_this_id,
2136   arm_prologue_prev_register,
2137   NULL,
2138   default_frame_sniffer
2139 };
2140
2141 /* Maintain a list of ARM exception table entries per objfile, similar to the
2142    list of mapping symbols.  We only cache entries for standard ARM-defined
2143    personality routines; the cache will contain only the frame unwinding
2144    instructions associated with the entry (not the descriptors).  */
2145
2146 static const struct objfile_data *arm_exidx_data_key;
2147
2148 struct arm_exidx_entry
2149 {
2150   bfd_vma addr;
2151   gdb_byte *entry;
2152 };
2153 typedef struct arm_exidx_entry arm_exidx_entry_s;
2154 DEF_VEC_O(arm_exidx_entry_s);
2155
2156 struct arm_exidx_data
2157 {
2158   VEC(arm_exidx_entry_s) **section_maps;
2159 };
2160
2161 static void
2162 arm_exidx_data_free (struct objfile *objfile, void *arg)
2163 {
2164   struct arm_exidx_data *data = arg;
2165   unsigned int i;
2166
2167   for (i = 0; i < objfile->obfd->section_count; i++)
2168     VEC_free (arm_exidx_entry_s, data->section_maps[i]);
2169 }
2170
2171 static inline int
2172 arm_compare_exidx_entries (const struct arm_exidx_entry *lhs,
2173                            const struct arm_exidx_entry *rhs)
2174 {
2175   return lhs->addr < rhs->addr;
2176 }
2177
2178 static struct obj_section *
2179 arm_obj_section_from_vma (struct objfile *objfile, bfd_vma vma)
2180 {
2181   struct obj_section *osect;
2182
2183   ALL_OBJFILE_OSECTIONS (objfile, osect)
2184     if (bfd_get_section_flags (objfile->obfd,
2185                                osect->the_bfd_section) & SEC_ALLOC)
2186       {
2187         bfd_vma start, size;
2188         start = bfd_get_section_vma (objfile->obfd, osect->the_bfd_section);
2189         size = bfd_get_section_size (osect->the_bfd_section);
2190
2191         if (start <= vma && vma < start + size)
2192           return osect;
2193       }
2194
2195   return NULL;
2196 }
2197
2198 /* Parse contents of exception table and exception index sections
2199    of OBJFILE, and fill in the exception table entry cache.
2200
2201    For each entry that refers to a standard ARM-defined personality
2202    routine, extract the frame unwinding instructions (from either
2203    the index or the table section).  The unwinding instructions
2204    are normalized by:
2205     - extracting them from the rest of the table data
2206     - converting to host endianness
2207     - appending the implicit 0xb0 ("Finish") code
2208
2209    The extracted and normalized instructions are stored for later
2210    retrieval by the arm_find_exidx_entry routine.  */
2211  
2212 static void
2213 arm_exidx_new_objfile (struct objfile *objfile)
2214 {
2215   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
2216   struct arm_exidx_data *data;
2217   asection *exidx, *extab;
2218   bfd_vma exidx_vma = 0, extab_vma = 0;
2219   bfd_size_type exidx_size = 0, extab_size = 0;
2220   gdb_byte *exidx_data = NULL, *extab_data = NULL;
2221   LONGEST i;
2222
2223   /* If we've already touched this file, do nothing.  */
2224   if (!objfile || objfile_data (objfile, arm_exidx_data_key) != NULL)
2225     return;
2226
2227   /* Read contents of exception table and index.  */
2228   exidx = bfd_get_section_by_name (objfile->obfd, ".ARM.exidx");
2229   if (exidx)
2230     {
2231       exidx_vma = bfd_section_vma (objfile->obfd, exidx);
2232       exidx_size = bfd_get_section_size (exidx);
2233       exidx_data = xmalloc (exidx_size);
2234       make_cleanup (xfree, exidx_data);
2235
2236       if (!bfd_get_section_contents (objfile->obfd, exidx,
2237                                      exidx_data, 0, exidx_size))
2238         {
2239           do_cleanups (cleanups);
2240           return;
2241         }
2242     }
2243
2244   extab = bfd_get_section_by_name (objfile->obfd, ".ARM.extab");
2245   if (extab)
2246     {
2247       extab_vma = bfd_section_vma (objfile->obfd, extab);
2248       extab_size = bfd_get_section_size (extab);
2249       extab_data = xmalloc (extab_size);
2250       make_cleanup (xfree, extab_data);
2251
2252       if (!bfd_get_section_contents (objfile->obfd, extab,
2253                                      extab_data, 0, extab_size))
2254         {
2255           do_cleanups (cleanups);
2256           return;
2257         }
2258     }
2259
2260   /* Allocate exception table data structure.  */
2261   data = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct arm_exidx_data);
2262   set_objfile_data (objfile, arm_exidx_data_key, data);
2263   data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
2264                                        objfile->obfd->section_count,
2265                                        VEC(arm_exidx_entry_s) *);
2266
2267   /* Fill in exception table.  */
2268   for (i = 0; i < exidx_size / 8; i++)
2269     {
2270       struct arm_exidx_entry new_exidx_entry;
2271       bfd_vma idx = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8);
2272       bfd_vma val = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8 + 4);
2273       bfd_vma addr = 0, word = 0;
2274       int n_bytes = 0, n_words = 0;
2275       struct obj_section *sec;
2276       gdb_byte *entry = NULL;
2277
2278       /* Extract address of start of function.  */
2279       idx = ((idx & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2280       idx += exidx_vma + i * 8;
2281
2282       /* Find section containing function and compute section offset.  */
2283       sec = arm_obj_section_from_vma (objfile, idx);
2284       if (sec == NULL)
2285         continue;
2286       idx -= bfd_get_section_vma (objfile->obfd, sec->the_bfd_section);
2287
2288       /* Determine address of exception table entry.  */
2289       if (val == 1)
2290         {
2291           /* EXIDX_CANTUNWIND -- no exception table entry present.  */
2292         }
2293       else if ((val & 0xff000000) == 0x80000000)
2294         {
2295           /* Exception table entry embedded in .ARM.exidx
2296              -- must be short form.  */
2297           word = val;
2298           n_bytes = 3;
2299         }
2300       else if (!(val & 0x80000000))
2301         {
2302           /* Exception table entry in .ARM.extab.  */
2303           addr = ((val & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2304           addr += exidx_vma + i * 8 + 4;
2305
2306           if (addr >= extab_vma && addr + 4 <= extab_vma + extab_size)
2307             {
2308               word = bfd_h_get_32 (objfile->obfd,
2309                                    extab_data + addr - extab_vma);
2310               addr += 4;
2311
2312               if ((word & 0xff000000) == 0x80000000)
2313                 {
2314                   /* Short form.  */
2315                   n_bytes = 3;
2316                 }
2317               else if ((word & 0xff000000) == 0x81000000
2318                        || (word & 0xff000000) == 0x82000000)
2319                 {
2320                   /* Long form.  */
2321                   n_bytes = 2;
2322                   n_words = ((word >> 16) & 0xff);
2323                 }
2324               else if (!(word & 0x80000000))
2325                 {
2326                   bfd_vma pers;
2327                   struct obj_section *pers_sec;
2328                   int gnu_personality = 0;
2329
2330                   /* Custom personality routine.  */
2331                   pers = ((word & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2332                   pers = UNMAKE_THUMB_ADDR (pers + addr - 4);
2333
2334                   /* Check whether we've got one of the variants of the
2335                      GNU personality routines.  */
2336                   pers_sec = arm_obj_section_from_vma (objfile, pers);
2337                   if (pers_sec)
2338                     {
2339                       static const char *personality[] = 
2340                         {
2341                           "__gcc_personality_v0",
2342                           "__gxx_personality_v0",
2343                           "__gcj_personality_v0",
2344                           "__gnu_objc_personality_v0",
2345                           NULL
2346                         };
2347
2348                       CORE_ADDR pc = pers + obj_section_offset (pers_sec);
2349                       int k;
2350
2351                       for (k = 0; personality[k]; k++)
2352                         if (lookup_minimal_symbol_by_pc_name
2353                               (pc, personality[k], objfile))
2354                           {
2355                             gnu_personality = 1;
2356                             break;
2357                           }
2358                     }
2359
2360                   /* If so, the next word contains a word count in the high
2361                      byte, followed by the same unwind instructions as the
2362                      pre-defined forms.  */
2363                   if (gnu_personality
2364                       && addr + 4 <= extab_vma + extab_size)
2365                     {
2366                       word = bfd_h_get_32 (objfile->obfd,
2367                                            extab_data + addr - extab_vma);
2368                       addr += 4;
2369                       n_bytes = 3;
2370                       n_words = ((word >> 24) & 0xff);
2371                     }
2372                 }
2373             }
2374         }
2375
2376       /* Sanity check address.  */
2377       if (n_words)
2378         if (addr < extab_vma || addr + 4 * n_words > extab_vma + extab_size)
2379           n_words = n_bytes = 0;
2380
2381       /* The unwind instructions reside in WORD (only the N_BYTES least
2382          significant bytes are valid), followed by N_WORDS words in the
2383          extab section starting at ADDR.  */
2384       if (n_bytes || n_words)
2385         {
2386           gdb_byte *p = entry = obstack_alloc (&objfile->objfile_obstack,
2387                                                n_bytes + n_words * 4 + 1);
2388
2389           while (n_bytes--)
2390             *p++ = (gdb_byte) ((word >> (8 * n_bytes)) & 0xff);
2391
2392           while (n_words--)
2393             {
2394               word = bfd_h_get_32 (objfile->obfd,
2395                                    extab_data + addr - extab_vma);
2396               addr += 4;
2397
2398               *p++ = (gdb_byte) ((word >> 24) & 0xff);
2399               *p++ = (gdb_byte) ((word >> 16) & 0xff);
2400               *p++ = (gdb_byte) ((word >> 8) & 0xff);
2401               *p++ = (gdb_byte) (word & 0xff);
2402             }
2403
2404           /* Implied "Finish" to terminate the list.  */
2405           *p++ = 0xb0;
2406         }
2407
2408       /* Push entry onto vector.  They are guaranteed to always
2409          appear in order of increasing addresses.  */
2410       new_exidx_entry.addr = idx;
2411       new_exidx_entry.entry = entry;
2412       VEC_safe_push (arm_exidx_entry_s,
2413                      data->section_maps[sec->the_bfd_section->index],
2414                      &new_exidx_entry);
2415     }
2416
2417   do_cleanups (cleanups);
2418 }
2419
2420 /* Search for the exception table entry covering MEMADDR.  If one is found,
2421    return a pointer to its data.  Otherwise, return 0.  If START is non-NULL,
2422    set *START to the start of the region covered by this entry.  */
2423
2424 static gdb_byte *
2425 arm_find_exidx_entry (CORE_ADDR memaddr, CORE_ADDR *start)
2426 {
2427   struct obj_section *sec;
2428
2429   sec = find_pc_section (memaddr);
2430   if (sec != NULL)
2431     {
2432       struct arm_exidx_data *data;
2433       VEC(arm_exidx_entry_s) *map;
2434       struct arm_exidx_entry map_key = { memaddr - obj_section_addr (sec), 0 };
2435       unsigned int idx;
2436
2437       data = objfile_data (sec->objfile, arm_exidx_data_key);
2438       if (data != NULL)
2439         {
2440           map = data->section_maps[sec->the_bfd_section->index];
2441           if (!VEC_empty (arm_exidx_entry_s, map))
2442             {
2443               struct arm_exidx_entry *map_sym;
2444
2445               idx = VEC_lower_bound (arm_exidx_entry_s, map, &map_key,
2446                                      arm_compare_exidx_entries);
2447
2448               /* VEC_lower_bound finds the earliest ordered insertion
2449                  point.  If the following symbol starts at this exact
2450                  address, we use that; otherwise, the preceding
2451                  exception table entry covers this address.  */
2452               if (idx < VEC_length (arm_exidx_entry_s, map))
2453                 {
2454                   map_sym = VEC_index (arm_exidx_entry_s, map, idx);
2455                   if (map_sym->addr == map_key.addr)
2456                     {
2457                       if (start)
2458                         *start = map_sym->addr + obj_section_addr (sec);
2459                       return map_sym->entry;
2460                     }
2461                 }
2462
2463               if (idx > 0)
2464                 {
2465                   map_sym = VEC_index (arm_exidx_entry_s, map, idx - 1);
2466                   if (start)
2467                     *start = map_sym->addr + obj_section_addr (sec);
2468                   return map_sym->entry;
2469                 }
2470             }
2471         }
2472     }
2473
2474   return NULL;
2475 }
2476
2477 /* Given the current frame THIS_FRAME, and its associated frame unwinding
2478    instruction list from the ARM exception table entry ENTRY, allocate and
2479    return a prologue cache structure describing how to unwind this frame.
2480
2481    Return NULL if the unwinding instruction list contains a "spare",
2482    "reserved" or "refuse to unwind" instruction as defined in section
2483    "9.3 Frame unwinding instructions" of the "Exception Handling ABI
2484    for the ARM Architecture" document.  */
2485
2486 static struct arm_prologue_cache *
2487 arm_exidx_fill_cache (struct frame_info *this_frame, gdb_byte *entry)
2488 {
2489   CORE_ADDR vsp = 0;
2490   int vsp_valid = 0;
2491
2492   struct arm_prologue_cache *cache;
2493   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2494   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2495
2496   for (;;)
2497     {
2498       gdb_byte insn;
2499
2500       /* Whenever we reload SP, we actually have to retrieve its
2501          actual value in the current frame.  */
2502       if (!vsp_valid)
2503         {
2504           if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2505             {
2506               int reg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2507               vsp = get_frame_register_unsigned (this_frame, reg);
2508             }
2509           else
2510             {
2511               CORE_ADDR addr = cache->saved_regs[ARM_SP_REGNUM].addr;
2512               vsp = get_frame_memory_unsigned (this_frame, addr, 4);
2513             }
2514
2515           vsp_valid = 1;
2516         }
2517
2518       /* Decode next unwind instruction.  */
2519       insn = *entry++;
2520
2521       if ((insn & 0xc0) == 0)
2522         {
2523           int offset = insn & 0x3f;
2524           vsp += (offset << 2) + 4;
2525         }
2526       else if ((insn & 0xc0) == 0x40)
2527         {
2528           int offset = insn & 0x3f;
2529           vsp -= (offset << 2) + 4;
2530         }
2531       else if ((insn & 0xf0) == 0x80)
2532         {
2533           int mask = ((insn & 0xf) << 8) | *entry++;
2534           int i;
2535
2536           /* The special case of an all-zero mask identifies
2537              "Refuse to unwind".  We return NULL to fall back
2538              to the prologue analyzer.  */
2539           if (mask == 0)
2540             return NULL;
2541
2542           /* Pop registers r4..r15 under mask.  */
2543           for (i = 0; i < 12; i++)
2544             if (mask & (1 << i))
2545               {
2546                 cache->saved_regs[4 + i].addr = vsp;
2547                 vsp += 4;
2548               }
2549
2550           /* Special-case popping SP -- we need to reload vsp.  */
2551           if (mask & (1 << (ARM_SP_REGNUM - 4)))
2552             vsp_valid = 0;
2553         }
2554       else if ((insn & 0xf0) == 0x90)
2555         {
2556           int reg = insn & 0xf;
2557
2558           /* Reserved cases.  */
2559           if (reg == ARM_SP_REGNUM || reg == ARM_PC_REGNUM)
2560             return NULL;
2561
2562           /* Set SP from another register and mark VSP for reload.  */
2563           cache->saved_regs[ARM_SP_REGNUM] = cache->saved_regs[reg];
2564           vsp_valid = 0;
2565         }
2566       else if ((insn & 0xf0) == 0xa0)
2567         {
2568           int count = insn & 0x7;
2569           int pop_lr = (insn & 0x8) != 0;
2570           int i;
2571
2572           /* Pop r4..r[4+count].  */
2573           for (i = 0; i <= count; i++)
2574             {
2575               cache->saved_regs[4 + i].addr = vsp;
2576               vsp += 4;
2577             }
2578
2579           /* If indicated by flag, pop LR as well.  */
2580           if (pop_lr)
2581             {
2582               cache->saved_regs[ARM_LR_REGNUM].addr = vsp;
2583               vsp += 4;
2584             }
2585         }
2586       else if (insn == 0xb0)
2587         {
2588           /* We could only have updated PC by popping into it; if so, it
2589              will show up as address.  Otherwise, copy LR into PC.  */
2590           if (!trad_frame_addr_p (cache->saved_regs, ARM_PC_REGNUM))
2591             cache->saved_regs[ARM_PC_REGNUM]
2592               = cache->saved_regs[ARM_LR_REGNUM];
2593
2594           /* We're done.  */
2595           break;
2596         }
2597       else if (insn == 0xb1)
2598         {
2599           int mask = *entry++;
2600           int i;
2601
2602           /* All-zero mask and mask >= 16 is "spare".  */
2603           if (mask == 0 || mask >= 16)
2604             return NULL;
2605
2606           /* Pop r0..r3 under mask.  */
2607           for (i = 0; i < 4; i++)
2608             if (mask & (1 << i))
2609               {
2610                 cache->saved_regs[i].addr = vsp;
2611                 vsp += 4;
2612               }
2613         }
2614       else if (insn == 0xb2)
2615         {
2616           ULONGEST offset = 0;
2617           unsigned shift = 0;
2618
2619           do
2620             {
2621               offset |= (*entry & 0x7f) << shift;
2622               shift += 7;
2623             }
2624           while (*entry++ & 0x80);
2625
2626           vsp += 0x204 + (offset << 2);
2627         }
2628       else if (insn == 0xb3)
2629         {
2630           int start = *entry >> 4;
2631           int count = (*entry++) & 0xf;
2632           int i;
2633
2634           /* Only registers D0..D15 are valid here.  */
2635           if (start + count >= 16)
2636             return NULL;
2637
2638           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2639           for (i = 0; i <= count; i++)
2640             {
2641               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2642               vsp += 8;
2643             }
2644
2645           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2646           vsp += 4;
2647         }
2648       else if ((insn & 0xf8) == 0xb8)
2649         {
2650           int count = insn & 0x7;
2651           int i;
2652
2653           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2654           for (i = 0; i <= count; i++)
2655             {
2656               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2657               vsp += 8;
2658             }
2659
2660           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2661           vsp += 4;
2662         }
2663       else if (insn == 0xc6)
2664         {
2665           int start = *entry >> 4;
2666           int count = (*entry++) & 0xf;
2667           int i;
2668
2669           /* Only registers WR0..WR15 are valid.  */
2670           if (start + count >= 16)
2671             return NULL;
2672
2673           /* Pop iwmmx registers WR[start]..WR[start+count].  */
2674           for (i = 0; i <= count; i++)
2675             {
2676               cache->saved_regs[ARM_WR0_REGNUM + start + i].addr = vsp;
2677               vsp += 8;
2678             }
2679         }
2680       else if (insn == 0xc7)
2681         {
2682           int mask = *entry++;
2683           int i;
2684
2685           /* All-zero mask and mask >= 16 is "spare".  */
2686           if (mask == 0 || mask >= 16)
2687             return NULL;
2688
2689           /* Pop iwmmx general-purpose registers WCGR0..WCGR3 under mask.  */
2690           for (i = 0; i < 4; i++)
2691             if (mask & (1 << i))
2692               {
2693                 cache->saved_regs[ARM_WCGR0_REGNUM + i].addr = vsp;
2694                 vsp += 4;
2695               }
2696         }
2697       else if ((insn & 0xf8) == 0xc0)
2698         {
2699           int count = insn & 0x7;
2700           int i;
2701
2702           /* Pop iwmmx registers WR[10]..WR[10+count].  */
2703           for (i = 0; i <= count; i++)
2704             {
2705               cache->saved_regs[ARM_WR0_REGNUM + 10 + i].addr = vsp;
2706               vsp += 8;
2707             }
2708         }
2709       else if (insn == 0xc8)
2710         {
2711           int start = *entry >> 4;
2712           int count = (*entry++) & 0xf;
2713           int i;
2714
2715           /* Only registers D0..D31 are valid.  */
2716           if (start + count >= 16)
2717             return NULL;
2718
2719           /* Pop VFP double-precision registers
2720              D[16+start]..D[16+start+count].  */
2721           for (i = 0; i <= count; i++)
2722             {
2723               cache->saved_regs[ARM_D0_REGNUM + 16 + start + i].addr = vsp;
2724               vsp += 8;
2725             }
2726         }
2727       else if (insn == 0xc9)
2728         {
2729           int start = *entry >> 4;
2730           int count = (*entry++) & 0xf;
2731           int i;
2732
2733           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2734           for (i = 0; i <= count; i++)
2735             {
2736               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2737               vsp += 8;
2738             }
2739         }
2740       else if ((insn & 0xf8) == 0xd0)
2741         {
2742           int count = insn & 0x7;
2743           int i;
2744
2745           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2746           for (i = 0; i <= count; i++)
2747             {
2748               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2749               vsp += 8;
2750             }
2751         }
2752       else
2753         {
2754           /* Everything else is "spare".  */
2755           return NULL;
2756         }
2757     }
2758
2759   /* If we restore SP from a register, assume this was the frame register.
2760      Otherwise just fall back to SP as frame register.  */
2761   if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2762     cache->framereg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2763   else
2764     cache->framereg = ARM_SP_REGNUM;
2765
2766   /* Determine offset to previous frame.  */
2767   cache->framesize
2768     = vsp - get_frame_register_unsigned (this_frame, cache->framereg);
2769
2770   /* We already got the previous SP.  */
2771   cache->prev_sp = vsp;
2772
2773   return cache;
2774 }
2775
2776 /* Unwinding via ARM exception table entries.  Note that the sniffer
2777    already computes a filled-in prologue cache, which is then used
2778    with the same arm_prologue_this_id and arm_prologue_prev_register
2779    routines also used for prologue-parsing based unwinding.  */
2780
2781 static int
2782 arm_exidx_unwind_sniffer (const struct frame_unwind *self,
2783                           struct frame_info *this_frame,
2784                           void **this_prologue_cache)
2785 {
2786   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2787   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
2788   CORE_ADDR addr_in_block, exidx_region, func_start;
2789   struct arm_prologue_cache *cache;
2790   gdb_byte *entry;
2791
2792   /* See if we have an ARM exception table entry covering this address.  */
2793   addr_in_block = get_frame_address_in_block (this_frame);
2794   entry = arm_find_exidx_entry (addr_in_block, &exidx_region);
2795   if (!entry)
2796     return 0;
2797
2798   /* The ARM exception table does not describe unwind information
2799      for arbitrary PC values, but is guaranteed to be correct only
2800      at call sites.  We have to decide here whether we want to use
2801      ARM exception table information for this frame, or fall back
2802      to using prologue parsing.  (Note that if we have DWARF CFI,
2803      this sniffer isn't even called -- CFI is always preferred.)
2804
2805      Before we make this decision, however, we check whether we
2806      actually have *symbol* information for the current frame.
2807      If not, prologue parsing would not work anyway, so we might
2808      as well use the exception table and hope for the best.  */
2809   if (find_pc_partial_function (addr_in_block, NULL, &func_start, NULL))
2810     {
2811       int exc_valid = 0;
2812
2813       /* If the next frame is "normal", we are at a call site in this
2814          frame, so exception information is guaranteed to be valid.  */
2815       if (get_next_frame (this_frame)
2816           && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME)
2817         exc_valid = 1;
2818
2819       /* We also assume exception information is valid if we're currently
2820          blocked in a system call.  The system library is supposed to
2821          ensure this, so that e.g. pthread cancellation works.  */
2822       if (arm_frame_is_thumb (this_frame))
2823         {
2824           LONGEST insn;
2825
2826           if (safe_read_memory_integer (get_frame_pc (this_frame) - 2, 2,
2827                                         byte_order_for_code, &insn)
2828               && (insn & 0xff00) == 0xdf00 /* svc */)
2829             exc_valid = 1;
2830         }
2831       else
2832         {
2833           LONGEST insn;
2834
2835           if (safe_read_memory_integer (get_frame_pc (this_frame) - 4, 4,
2836                                         byte_order_for_code, &insn)
2837               && (insn & 0x0f000000) == 0x0f000000 /* svc */)
2838             exc_valid = 1;
2839         }
2840         
2841       /* Bail out if we don't know that exception information is valid.  */
2842       if (!exc_valid)
2843         return 0;
2844
2845      /* The ARM exception index does not mark the *end* of the region
2846         covered by the entry, and some functions will not have any entry.
2847         To correctly recognize the end of the covered region, the linker
2848         should have inserted dummy records with a CANTUNWIND marker.
2849
2850         Unfortunately, current versions of GNU ld do not reliably do
2851         this, and thus we may have found an incorrect entry above.
2852         As a (temporary) sanity check, we only use the entry if it
2853         lies *within* the bounds of the function.  Note that this check
2854         might reject perfectly valid entries that just happen to cover
2855         multiple functions; therefore this check ought to be removed
2856         once the linker is fixed.  */
2857       if (func_start > exidx_region)
2858         return 0;
2859     }
2860
2861   /* Decode the list of unwinding instructions into a prologue cache.
2862      Note that this may fail due to e.g. a "refuse to unwind" code.  */
2863   cache = arm_exidx_fill_cache (this_frame, entry);
2864   if (!cache)
2865     return 0;
2866
2867   *this_prologue_cache = cache;
2868   return 1;
2869 }
2870
2871 struct frame_unwind arm_exidx_unwind = {
2872   NORMAL_FRAME,
2873   arm_prologue_this_id,
2874   arm_prologue_prev_register,
2875   NULL,
2876   arm_exidx_unwind_sniffer
2877 };
2878
2879 static struct arm_prologue_cache *
2880 arm_make_stub_cache (struct frame_info *this_frame)
2881 {
2882   struct arm_prologue_cache *cache;
2883
2884   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2885   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2886
2887   cache->prev_sp = get_frame_register_unsigned (this_frame, ARM_SP_REGNUM);
2888
2889   return cache;
2890 }
2891
2892 /* Our frame ID for a stub frame is the current SP and LR.  */
2893
2894 static void
2895 arm_stub_this_id (struct frame_info *this_frame,
2896                   void **this_cache,
2897                   struct frame_id *this_id)
2898 {
2899   struct arm_prologue_cache *cache;
2900
2901   if (*this_cache == NULL)
2902     *this_cache = arm_make_stub_cache (this_frame);
2903   cache = *this_cache;
2904
2905   *this_id = frame_id_build (cache->prev_sp, get_frame_pc (this_frame));
2906 }
2907
2908 static int
2909 arm_stub_unwind_sniffer (const struct frame_unwind *self,
2910                          struct frame_info *this_frame,
2911                          void **this_prologue_cache)
2912 {
2913   CORE_ADDR addr_in_block;
2914   char dummy[4];
2915
2916   addr_in_block = get_frame_address_in_block (this_frame);
2917   if (in_plt_section (addr_in_block, NULL)
2918       /* We also use the stub winder if the target memory is unreadable
2919          to avoid having the prologue unwinder trying to read it.  */
2920       || target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
2921     return 1;
2922
2923   return 0;
2924 }
2925
2926 struct frame_unwind arm_stub_unwind = {
2927   NORMAL_FRAME,
2928   arm_stub_this_id,
2929   arm_prologue_prev_register,
2930   NULL,
2931   arm_stub_unwind_sniffer
2932 };
2933
2934 static CORE_ADDR
2935 arm_normal_frame_base (struct frame_info *this_frame, void **this_cache)
2936 {
2937   struct arm_prologue_cache *cache;
2938
2939   if (*this_cache == NULL)
2940     *this_cache = arm_make_prologue_cache (this_frame);
2941   cache = *this_cache;
2942
2943   return cache->prev_sp - cache->framesize;
2944 }
2945
2946 struct frame_base arm_normal_base = {
2947   &arm_prologue_unwind,
2948   arm_normal_frame_base,
2949   arm_normal_frame_base,
2950   arm_normal_frame_base
2951 };
2952
2953 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
2954    dummy frame.  The frame ID's base needs to match the TOS value
2955    saved by save_dummy_frame_tos() and returned from
2956    arm_push_dummy_call, and the PC needs to match the dummy frame's
2957    breakpoint.  */
2958
2959 static struct frame_id
2960 arm_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2961 {
2962   return frame_id_build (get_frame_register_unsigned (this_frame,
2963                                                       ARM_SP_REGNUM),
2964                          get_frame_pc (this_frame));
2965 }
2966
2967 /* Given THIS_FRAME, find the previous frame's resume PC (which will
2968    be used to construct the previous frame's ID, after looking up the
2969    containing function).  */
2970
2971 static CORE_ADDR
2972 arm_unwind_pc (struct gdbarch *gdbarch, struct frame_info *this_frame)
2973 {
2974   CORE_ADDR pc;
2975   pc = frame_unwind_register_unsigned (this_frame, ARM_PC_REGNUM);
2976   return arm_addr_bits_remove (gdbarch, pc);
2977 }
2978
2979 static CORE_ADDR
2980 arm_unwind_sp (struct gdbarch *gdbarch, struct frame_info *this_frame)
2981 {
2982   return frame_unwind_register_unsigned (this_frame, ARM_SP_REGNUM);
2983 }
2984
2985 static struct value *
2986 arm_dwarf2_prev_register (struct frame_info *this_frame, void **this_cache,
2987                           int regnum)
2988 {
2989   struct gdbarch * gdbarch = get_frame_arch (this_frame);
2990   CORE_ADDR lr, cpsr;
2991   ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
2992
2993   switch (regnum)
2994     {
2995     case ARM_PC_REGNUM:
2996       /* The PC is normally copied from the return column, which
2997          describes saves of LR.  However, that version may have an
2998          extra bit set to indicate Thumb state.  The bit is not
2999          part of the PC.  */
3000       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3001       return frame_unwind_got_constant (this_frame, regnum,
3002                                         arm_addr_bits_remove (gdbarch, lr));
3003
3004     case ARM_PS_REGNUM:
3005       /* Reconstruct the T bit; see arm_prologue_prev_register for details.  */
3006       cpsr = get_frame_register_unsigned (this_frame, regnum);
3007       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3008       if (IS_THUMB_ADDR (lr))
3009         cpsr |= t_bit;
3010       else
3011         cpsr &= ~t_bit;
3012       return frame_unwind_got_constant (this_frame, regnum, cpsr);
3013
3014     default:
3015       internal_error (__FILE__, __LINE__,
3016                       _("Unexpected register %d"), regnum);
3017     }
3018 }
3019
3020 static void
3021 arm_dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
3022                            struct dwarf2_frame_state_reg *reg,
3023                            struct frame_info *this_frame)
3024 {
3025   switch (regnum)
3026     {
3027     case ARM_PC_REGNUM:
3028     case ARM_PS_REGNUM:
3029       reg->how = DWARF2_FRAME_REG_FN;
3030       reg->loc.fn = arm_dwarf2_prev_register;
3031       break;
3032     case ARM_SP_REGNUM:
3033       reg->how = DWARF2_FRAME_REG_CFA;
3034       break;
3035     }
3036 }
3037
3038 /* Return true if we are in the function's epilogue, i.e. after the
3039    instruction that destroyed the function's stack frame.  */
3040
3041 static int
3042 thumb_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3043 {
3044   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3045   unsigned int insn, insn2;
3046   int found_return = 0, found_stack_adjust = 0;
3047   CORE_ADDR func_start, func_end;
3048   CORE_ADDR scan_pc;
3049   gdb_byte buf[4];
3050
3051   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3052     return 0;
3053
3054   /* The epilogue is a sequence of instructions along the following lines:
3055
3056     - add stack frame size to SP or FP
3057     - [if frame pointer used] restore SP from FP
3058     - restore registers from SP [may include PC]
3059     - a return-type instruction [if PC wasn't already restored]
3060
3061     In a first pass, we scan forward from the current PC and verify the
3062     instructions we find as compatible with this sequence, ending in a
3063     return instruction.
3064
3065     However, this is not sufficient to distinguish indirect function calls
3066     within a function from indirect tail calls in the epilogue in some cases.
3067     Therefore, if we didn't already find any SP-changing instruction during
3068     forward scan, we add a backward scanning heuristic to ensure we actually
3069     are in the epilogue.  */
3070
3071   scan_pc = pc;
3072   while (scan_pc < func_end && !found_return)
3073     {
3074       if (target_read_memory (scan_pc, buf, 2))
3075         break;
3076
3077       scan_pc += 2;
3078       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3079
3080       if ((insn & 0xff80) == 0x4700)  /* bx <Rm> */
3081         found_return = 1;
3082       else if (insn == 0x46f7)  /* mov pc, lr */
3083         found_return = 1;
3084       else if (insn == 0x46bd)  /* mov sp, r7 */
3085         found_stack_adjust = 1;
3086       else if ((insn & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3087         found_stack_adjust = 1;
3088       else if ((insn & 0xfe00) == 0xbc00)  /* pop <registers> */
3089         {
3090           found_stack_adjust = 1;
3091           if (insn & 0x0100)  /* <registers> include PC.  */
3092             found_return = 1;
3093         }
3094       else if ((insn & 0xe000) == 0xe000)  /* 32-bit Thumb-2 instruction */
3095         {
3096           if (target_read_memory (scan_pc, buf, 2))
3097             break;
3098
3099           scan_pc += 2;
3100           insn2 = extract_unsigned_integer (buf, 2, byte_order_for_code);
3101
3102           if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3103             {
3104               found_stack_adjust = 1;
3105               if (insn2 & 0x8000)  /* <registers> include PC.  */
3106                 found_return = 1;
3107             }
3108           else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3109                    && (insn2 & 0x0fff) == 0x0b04)
3110             {
3111               found_stack_adjust = 1;
3112               if ((insn2 & 0xf000) == 0xf000) /* <Rt> is PC.  */
3113                 found_return = 1;
3114             }
3115           else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3116                    && (insn2 & 0x0e00) == 0x0a00)
3117             found_stack_adjust = 1;
3118           else
3119             break;
3120         }
3121       else
3122         break;
3123     }
3124
3125   if (!found_return)
3126     return 0;
3127
3128   /* Since any instruction in the epilogue sequence, with the possible
3129      exception of return itself, updates the stack pointer, we need to
3130      scan backwards for at most one instruction.  Try either a 16-bit or
3131      a 32-bit instruction.  This is just a heuristic, so we do not worry
3132      too much about false positives.  */
3133
3134   if (!found_stack_adjust)
3135     {
3136       if (pc - 4 < func_start)
3137         return 0;
3138       if (target_read_memory (pc - 4, buf, 4))
3139         return 0;
3140
3141       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3142       insn2 = extract_unsigned_integer (buf + 2, 2, byte_order_for_code);
3143
3144       if (insn2 == 0x46bd)  /* mov sp, r7 */
3145         found_stack_adjust = 1;
3146       else if ((insn2 & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3147         found_stack_adjust = 1;
3148       else if ((insn2 & 0xff00) == 0xbc00)  /* pop <registers> without PC */
3149         found_stack_adjust = 1;
3150       else if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3151         found_stack_adjust = 1;
3152       else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3153                && (insn2 & 0x0fff) == 0x0b04)
3154         found_stack_adjust = 1;
3155       else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3156                && (insn2 & 0x0e00) == 0x0a00)
3157         found_stack_adjust = 1;
3158     }
3159
3160   return found_stack_adjust;
3161 }
3162
3163 /* Return true if we are in the function's epilogue, i.e. after the
3164    instruction that destroyed the function's stack frame.  */
3165
3166 static int
3167 arm_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3168 {
3169   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3170   unsigned int insn;
3171   int found_return, found_stack_adjust;
3172   CORE_ADDR func_start, func_end;
3173
3174   if (arm_pc_is_thumb (gdbarch, pc))
3175     return thumb_in_function_epilogue_p (gdbarch, pc);
3176
3177   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3178     return 0;
3179
3180   /* We are in the epilogue if the previous instruction was a stack
3181      adjustment and the next instruction is a possible return (bx, mov
3182      pc, or pop).  We could have to scan backwards to find the stack
3183      adjustment, or forwards to find the return, but this is a decent
3184      approximation.  First scan forwards.  */
3185
3186   found_return = 0;
3187   insn = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
3188   if (bits (insn, 28, 31) != INST_NV)
3189     {
3190       if ((insn & 0x0ffffff0) == 0x012fff10)
3191         /* BX.  */
3192         found_return = 1;
3193       else if ((insn & 0x0ffffff0) == 0x01a0f000)
3194         /* MOV PC.  */
3195         found_return = 1;
3196       else if ((insn & 0x0fff0000) == 0x08bd0000
3197           && (insn & 0x0000c000) != 0)
3198         /* POP (LDMIA), including PC or LR.  */
3199         found_return = 1;
3200     }
3201
3202   if (!found_return)
3203     return 0;
3204
3205   /* Scan backwards.  This is just a heuristic, so do not worry about
3206      false positives from mode changes.  */
3207
3208   if (pc < func_start + 4)
3209     return 0;
3210
3211   found_stack_adjust = 0;
3212   insn = read_memory_unsigned_integer (pc - 4, 4, byte_order_for_code);
3213   if (bits (insn, 28, 31) != INST_NV)
3214     {
3215       if ((insn & 0x0df0f000) == 0x0080d000)
3216         /* ADD SP (register or immediate).  */
3217         found_stack_adjust = 1;
3218       else if ((insn & 0x0df0f000) == 0x0040d000)
3219         /* SUB SP (register or immediate).  */
3220         found_stack_adjust = 1;
3221       else if ((insn & 0x0ffffff0) == 0x01a0d000)
3222         /* MOV SP.  */
3223         found_stack_adjust = 1;
3224       else if ((insn & 0x0fff0000) == 0x08bd0000)
3225         /* POP (LDMIA).  */
3226         found_stack_adjust = 1;
3227     }
3228
3229   if (found_stack_adjust)
3230     return 1;
3231
3232   return 0;
3233 }
3234
3235
3236 /* When arguments must be pushed onto the stack, they go on in reverse
3237    order.  The code below implements a FILO (stack) to do this.  */
3238
3239 struct stack_item
3240 {
3241   int len;
3242   struct stack_item *prev;
3243   void *data;
3244 };
3245
3246 static struct stack_item *
3247 push_stack_item (struct stack_item *prev, const void *contents, int len)
3248 {
3249   struct stack_item *si;
3250   si = xmalloc (sizeof (struct stack_item));
3251   si->data = xmalloc (len);
3252   si->len = len;
3253   si->prev = prev;
3254   memcpy (si->data, contents, len);
3255   return si;
3256 }
3257
3258 static struct stack_item *
3259 pop_stack_item (struct stack_item *si)
3260 {
3261   struct stack_item *dead = si;
3262   si = si->prev;
3263   xfree (dead->data);
3264   xfree (dead);
3265   return si;
3266 }
3267
3268
3269 /* Return the alignment (in bytes) of the given type.  */
3270
3271 static int
3272 arm_type_align (struct type *t)
3273 {
3274   int n;
3275   int align;
3276   int falign;
3277
3278   t = check_typedef (t);
3279   switch (TYPE_CODE (t))
3280     {
3281     default:
3282       /* Should never happen.  */
3283       internal_error (__FILE__, __LINE__, _("unknown type alignment"));
3284       return 4;
3285
3286     case TYPE_CODE_PTR:
3287     case TYPE_CODE_ENUM:
3288     case TYPE_CODE_INT:
3289     case TYPE_CODE_FLT:
3290     case TYPE_CODE_SET:
3291     case TYPE_CODE_RANGE:
3292     case TYPE_CODE_BITSTRING:
3293     case TYPE_CODE_REF:
3294     case TYPE_CODE_CHAR:
3295     case TYPE_CODE_BOOL:
3296       return TYPE_LENGTH (t);
3297
3298     case TYPE_CODE_ARRAY:
3299     case TYPE_CODE_COMPLEX:
3300       /* TODO: What about vector types?  */
3301       return arm_type_align (TYPE_TARGET_TYPE (t));
3302
3303     case TYPE_CODE_STRUCT:
3304     case TYPE_CODE_UNION:
3305       align = 1;
3306       for (n = 0; n < TYPE_NFIELDS (t); n++)
3307         {
3308           falign = arm_type_align (TYPE_FIELD_TYPE (t, n));
3309           if (falign > align)
3310             align = falign;
3311         }
3312       return align;
3313     }
3314 }
3315
3316 /* Possible base types for a candidate for passing and returning in
3317    VFP registers.  */
3318
3319 enum arm_vfp_cprc_base_type
3320 {
3321   VFP_CPRC_UNKNOWN,
3322   VFP_CPRC_SINGLE,
3323   VFP_CPRC_DOUBLE,
3324   VFP_CPRC_VEC64,
3325   VFP_CPRC_VEC128
3326 };
3327
3328 /* The length of one element of base type B.  */
3329
3330 static unsigned
3331 arm_vfp_cprc_unit_length (enum arm_vfp_cprc_base_type b)
3332 {
3333   switch (b)
3334     {
3335     case VFP_CPRC_SINGLE:
3336       return 4;
3337     case VFP_CPRC_DOUBLE:
3338       return 8;
3339     case VFP_CPRC_VEC64:
3340       return 8;
3341     case VFP_CPRC_VEC128:
3342       return 16;
3343     default:
3344       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3345                       (int) b);
3346     }
3347 }
3348
3349 /* The character ('s', 'd' or 'q') for the type of VFP register used
3350    for passing base type B.  */
3351
3352 static int
3353 arm_vfp_cprc_reg_char (enum arm_vfp_cprc_base_type b)
3354 {
3355   switch (b)
3356     {
3357     case VFP_CPRC_SINGLE:
3358       return 's';
3359     case VFP_CPRC_DOUBLE:
3360       return 'd';
3361     case VFP_CPRC_VEC64:
3362       return 'd';
3363     case VFP_CPRC_VEC128:
3364       return 'q';
3365     default:
3366       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3367                       (int) b);
3368     }
3369 }
3370
3371 /* Determine whether T may be part of a candidate for passing and
3372    returning in VFP registers, ignoring the limit on the total number
3373    of components.  If *BASE_TYPE is VFP_CPRC_UNKNOWN, set it to the
3374    classification of the first valid component found; if it is not
3375    VFP_CPRC_UNKNOWN, all components must have the same classification
3376    as *BASE_TYPE.  If it is found that T contains a type not permitted
3377    for passing and returning in VFP registers, a type differently
3378    classified from *BASE_TYPE, or two types differently classified
3379    from each other, return -1, otherwise return the total number of
3380    base-type elements found (possibly 0 in an empty structure or
3381    array).  Vectors and complex types are not currently supported,
3382    matching the generic AAPCS support.  */
3383
3384 static int
3385 arm_vfp_cprc_sub_candidate (struct type *t,
3386                             enum arm_vfp_cprc_base_type *base_type)
3387 {
3388   t = check_typedef (t);
3389   switch (TYPE_CODE (t))
3390     {
3391     case TYPE_CODE_FLT:
3392       switch (TYPE_LENGTH (t))
3393         {
3394         case 4:
3395           if (*base_type == VFP_CPRC_UNKNOWN)
3396             *base_type = VFP_CPRC_SINGLE;
3397           else if (*base_type != VFP_CPRC_SINGLE)
3398             return -1;
3399           return 1;
3400
3401         case 8:
3402           if (*base_type == VFP_CPRC_UNKNOWN)
3403             *base_type = VFP_CPRC_DOUBLE;
3404           else if (*base_type != VFP_CPRC_DOUBLE)
3405             return -1;
3406           return 1;
3407
3408         default:
3409           return -1;
3410         }
3411       break;
3412
3413     case TYPE_CODE_ARRAY:
3414       {
3415         int count;
3416         unsigned unitlen;
3417         count = arm_vfp_cprc_sub_candidate (TYPE_TARGET_TYPE (t), base_type);
3418         if (count == -1)
3419           return -1;
3420         if (TYPE_LENGTH (t) == 0)
3421           {
3422             gdb_assert (count == 0);
3423             return 0;
3424           }
3425         else if (count == 0)
3426           return -1;
3427         unitlen = arm_vfp_cprc_unit_length (*base_type);
3428         gdb_assert ((TYPE_LENGTH (t) % unitlen) == 0);
3429         return TYPE_LENGTH (t) / unitlen;
3430       }
3431       break;
3432
3433     case TYPE_CODE_STRUCT:
3434       {
3435         int count = 0;
3436         unsigned unitlen;
3437         int i;
3438         for (i = 0; i < TYPE_NFIELDS (t); i++)
3439           {
3440             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3441                                                         base_type);
3442             if (sub_count == -1)
3443               return -1;
3444             count += sub_count;
3445           }
3446         if (TYPE_LENGTH (t) == 0)
3447           {
3448             gdb_assert (count == 0);
3449             return 0;
3450           }
3451         else if (count == 0)
3452           return -1;
3453         unitlen = arm_vfp_cprc_unit_length (*base_type);
3454         if (TYPE_LENGTH (t) != unitlen * count)
3455           return -1;
3456         return count;
3457       }
3458
3459     case TYPE_CODE_UNION:
3460       {
3461         int count = 0;
3462         unsigned unitlen;
3463         int i;
3464         for (i = 0; i < TYPE_NFIELDS (t); i++)
3465           {
3466             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3467                                                         base_type);
3468             if (sub_count == -1)
3469               return -1;
3470             count = (count > sub_count ? count : sub_count);
3471           }
3472         if (TYPE_LENGTH (t) == 0)
3473           {
3474             gdb_assert (count == 0);
3475             return 0;
3476           }
3477         else if (count == 0)
3478           return -1;
3479         unitlen = arm_vfp_cprc_unit_length (*base_type);
3480         if (TYPE_LENGTH (t) != unitlen * count)
3481           return -1;
3482         return count;
3483       }
3484
3485     default:
3486       break;
3487     }
3488
3489   return -1;
3490 }
3491
3492 /* Determine whether T is a VFP co-processor register candidate (CPRC)
3493    if passed to or returned from a non-variadic function with the VFP
3494    ABI in effect.  Return 1 if it is, 0 otherwise.  If it is, set
3495    *BASE_TYPE to the base type for T and *COUNT to the number of
3496    elements of that base type before returning.  */
3497
3498 static int
3499 arm_vfp_call_candidate (struct type *t, enum arm_vfp_cprc_base_type *base_type,
3500                         int *count)
3501 {
3502   enum arm_vfp_cprc_base_type b = VFP_CPRC_UNKNOWN;
3503   int c = arm_vfp_cprc_sub_candidate (t, &b);
3504   if (c <= 0 || c > 4)
3505     return 0;
3506   *base_type = b;
3507   *count = c;
3508   return 1;
3509 }
3510
3511 /* Return 1 if the VFP ABI should be used for passing arguments to and
3512    returning values from a function of type FUNC_TYPE, 0
3513    otherwise.  */
3514
3515 static int
3516 arm_vfp_abi_for_function (struct gdbarch *gdbarch, struct type *func_type)
3517 {
3518   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3519   /* Variadic functions always use the base ABI.  Assume that functions
3520      without debug info are not variadic.  */
3521   if (func_type && TYPE_VARARGS (check_typedef (func_type)))
3522     return 0;
3523   /* The VFP ABI is only supported as a variant of AAPCS.  */
3524   if (tdep->arm_abi != ARM_ABI_AAPCS)
3525     return 0;
3526   return gdbarch_tdep (gdbarch)->fp_model == ARM_FLOAT_VFP;
3527 }
3528
3529 /* We currently only support passing parameters in integer registers, which
3530    conforms with GCC's default model, and VFP argument passing following
3531    the VFP variant of AAPCS.  Several other variants exist and
3532    we should probably support some of them based on the selected ABI.  */
3533
3534 static CORE_ADDR
3535 arm_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
3536                      struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
3537                      struct value **args, CORE_ADDR sp, int struct_return,
3538                      CORE_ADDR struct_addr)
3539 {
3540   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3541   int argnum;
3542   int argreg;
3543   int nstack;
3544   struct stack_item *si = NULL;
3545   int use_vfp_abi;
3546   struct type *ftype;
3547   unsigned vfp_regs_free = (1 << 16) - 1;
3548
3549   /* Determine the type of this function and whether the VFP ABI
3550      applies.  */
3551   ftype = check_typedef (value_type (function));
3552   if (TYPE_CODE (ftype) == TYPE_CODE_PTR)
3553     ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
3554   use_vfp_abi = arm_vfp_abi_for_function (gdbarch, ftype);
3555
3556   /* Set the return address.  For the ARM, the return breakpoint is
3557      always at BP_ADDR.  */
3558   if (arm_pc_is_thumb (gdbarch, bp_addr))
3559     bp_addr |= 1;
3560   regcache_cooked_write_unsigned (regcache, ARM_LR_REGNUM, bp_addr);
3561
3562   /* Walk through the list of args and determine how large a temporary
3563      stack is required.  Need to take care here as structs may be
3564      passed on the stack, and we have to to push them.  */
3565   nstack = 0;
3566
3567   argreg = ARM_A1_REGNUM;
3568   nstack = 0;
3569
3570   /* The struct_return pointer occupies the first parameter
3571      passing register.  */
3572   if (struct_return)
3573     {
3574       if (arm_debug)
3575         fprintf_unfiltered (gdb_stdlog, "struct return in %s = %s\n",
3576                             gdbarch_register_name (gdbarch, argreg),
3577                             paddress (gdbarch, struct_addr));
3578       regcache_cooked_write_unsigned (regcache, argreg, struct_addr);
3579       argreg++;
3580     }
3581
3582   for (argnum = 0; argnum < nargs; argnum++)
3583     {
3584       int len;
3585       struct type *arg_type;
3586       struct type *target_type;
3587       enum type_code typecode;
3588       const bfd_byte *val;
3589       int align;
3590       enum arm_vfp_cprc_base_type vfp_base_type;
3591       int vfp_base_count;
3592       int may_use_core_reg = 1;
3593
3594       arg_type = check_typedef (value_type (args[argnum]));
3595       len = TYPE_LENGTH (arg_type);
3596       target_type = TYPE_TARGET_TYPE (arg_type);
3597       typecode = TYPE_CODE (arg_type);
3598       val = value_contents (args[argnum]);
3599
3600       align = arm_type_align (arg_type);
3601       /* Round alignment up to a whole number of words.  */
3602       align = (align + INT_REGISTER_SIZE - 1) & ~(INT_REGISTER_SIZE - 1);
3603       /* Different ABIs have different maximum alignments.  */
3604       if (gdbarch_tdep (gdbarch)->arm_abi == ARM_ABI_APCS)
3605         {
3606           /* The APCS ABI only requires word alignment.  */
3607           align = INT_REGISTER_SIZE;
3608         }
3609       else
3610         {
3611           /* The AAPCS requires at most doubleword alignment.  */
3612           if (align > INT_REGISTER_SIZE * 2)
3613             align = INT_REGISTER_SIZE * 2;
3614         }
3615
3616       if (use_vfp_abi
3617           && arm_vfp_call_candidate (arg_type, &vfp_base_type,
3618                                      &vfp_base_count))
3619         {
3620           int regno;
3621           int unit_length;
3622           int shift;
3623           unsigned mask;
3624
3625           /* Because this is a CPRC it cannot go in a core register or
3626              cause a core register to be skipped for alignment.
3627              Either it goes in VFP registers and the rest of this loop
3628              iteration is skipped for this argument, or it goes on the
3629              stack (and the stack alignment code is correct for this
3630              case).  */
3631           may_use_core_reg = 0;
3632
3633           unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
3634           shift = unit_length / 4;
3635           mask = (1 << (shift * vfp_base_count)) - 1;
3636           for (regno = 0; regno < 16; regno += shift)
3637             if (((vfp_regs_free >> regno) & mask) == mask)
3638               break;
3639
3640           if (regno < 16)
3641             {
3642               int reg_char;
3643               int reg_scaled;
3644               int i;
3645
3646               vfp_regs_free &= ~(mask << regno);
3647               reg_scaled = regno / shift;
3648               reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
3649               for (i = 0; i < vfp_base_count; i++)
3650                 {
3651                   char name_buf[4];
3652                   int regnum;
3653                   if (reg_char == 'q')
3654                     arm_neon_quad_write (gdbarch, regcache, reg_scaled + i,
3655                                          val + i * unit_length);
3656                   else
3657                     {
3658                       sprintf (name_buf, "%c%d", reg_char, reg_scaled + i);
3659                       regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
3660                                                             strlen (name_buf));
3661                       regcache_cooked_write (regcache, regnum,
3662                                              val + i * unit_length);
3663                     }
3664                 }
3665               continue;
3666             }
3667           else
3668             {
3669               /* This CPRC could not go in VFP registers, so all VFP
3670                  registers are now marked as used.  */
3671               vfp_regs_free = 0;
3672             }
3673         }
3674
3675       /* Push stack padding for dowubleword alignment.  */
3676       if (nstack & (align - 1))
3677         {
3678           si = push_stack_item (si, val, INT_REGISTER_SIZE);
3679           nstack += INT_REGISTER_SIZE;
3680         }
3681       
3682       /* Doubleword aligned quantities must go in even register pairs.  */
3683       if (may_use_core_reg
3684           && argreg <= ARM_LAST_ARG_REGNUM
3685           && align > INT_REGISTER_SIZE
3686           && argreg & 1)
3687         argreg++;
3688
3689       /* If the argument is a pointer to a function, and it is a
3690          Thumb function, create a LOCAL copy of the value and set
3691          the THUMB bit in it.  */
3692       if (TYPE_CODE_PTR == typecode
3693           && target_type != NULL
3694           && TYPE_CODE_FUNC == TYPE_CODE (check_typedef (target_type)))
3695         {
3696           CORE_ADDR regval = extract_unsigned_integer (val, len, byte_order);
3697           if (arm_pc_is_thumb (gdbarch, regval))
3698             {
3699               bfd_byte *copy = alloca (len);
3700               store_unsigned_integer (copy, len, byte_order,
3701                                       MAKE_THUMB_ADDR (regval));
3702               val = copy;
3703             }
3704         }
3705
3706       /* Copy the argument to general registers or the stack in
3707          register-sized pieces.  Large arguments are split between
3708          registers and stack.  */
3709       while (len > 0)
3710         {
3711           int partial_len = len < INT_REGISTER_SIZE ? len : INT_REGISTER_SIZE;
3712
3713           if (may_use_core_reg && argreg <= ARM_LAST_ARG_REGNUM)
3714             {
3715               /* The argument is being passed in a general purpose
3716                  register.  */
3717               CORE_ADDR regval
3718                 = extract_unsigned_integer (val, partial_len, byte_order);
3719               if (byte_order == BFD_ENDIAN_BIG)
3720                 regval <<= (INT_REGISTER_SIZE - partial_len) * 8;
3721               if (arm_debug)
3722                 fprintf_unfiltered (gdb_stdlog, "arg %d in %s = 0x%s\n",
3723                                     argnum,
3724                                     gdbarch_register_name
3725                                       (gdbarch, argreg),
3726                                     phex (regval, INT_REGISTER_SIZE));
3727               regcache_cooked_write_unsigned (regcache, argreg, regval);
3728               argreg++;
3729             }
3730           else
3731             {
3732               /* Push the arguments onto the stack.  */
3733               if (arm_debug)
3734                 fprintf_unfiltered (gdb_stdlog, "arg %d @ sp + %d\n",
3735                                     argnum, nstack);
3736               si = push_stack_item (si, val, INT_REGISTER_SIZE);
3737               nstack += INT_REGISTER_SIZE;
3738             }
3739               
3740           len -= partial_len;
3741           val += partial_len;
3742         }
3743     }
3744   /* If we have an odd number of words to push, then decrement the stack
3745      by one word now, so first stack argument will be dword aligned.  */
3746   if (nstack & 4)
3747     sp -= 4;
3748
3749   while (si)
3750     {
3751       sp -= si->len;
3752       write_memory (sp, si->data, si->len);
3753       si = pop_stack_item (si);
3754     }
3755
3756   /* Finally, update teh SP register.  */
3757   regcache_cooked_write_unsigned (regcache, ARM_SP_REGNUM, sp);
3758
3759   return sp;
3760 }
3761
3762
3763 /* Always align the frame to an 8-byte boundary.  This is required on
3764    some platforms and harmless on the rest.  */
3765
3766 static CORE_ADDR
3767 arm_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
3768 {
3769   /* Align the stack to eight bytes.  */
3770   return sp & ~ (CORE_ADDR) 7;
3771 }
3772
3773 static void
3774 print_fpu_flags (int flags)
3775 {
3776   if (flags & (1 << 0))
3777     fputs ("IVO ", stdout);
3778   if (flags & (1 << 1))
3779     fputs ("DVZ ", stdout);
3780   if (flags & (1 << 2))
3781     fputs ("OFL ", stdout);
3782   if (flags & (1 << 3))
3783     fputs ("UFL ", stdout);
3784   if (flags & (1 << 4))
3785     fputs ("INX ", stdout);
3786   putchar ('\n');
3787 }
3788
3789 /* Print interesting information about the floating point processor
3790    (if present) or emulator.  */
3791 static void
3792 arm_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
3793                       struct frame_info *frame, const char *args)
3794 {
3795   unsigned long status = get_frame_register_unsigned (frame, ARM_FPS_REGNUM);
3796   int type;
3797
3798   type = (status >> 24) & 127;
3799   if (status & (1 << 31))
3800     printf (_("Hardware FPU type %d\n"), type);
3801   else
3802     printf (_("Software FPU type %d\n"), type);
3803   /* i18n: [floating point unit] mask */
3804   fputs (_("mask: "), stdout);
3805   print_fpu_flags (status >> 16);
3806   /* i18n: [floating point unit] flags */
3807   fputs (_("flags: "), stdout);
3808   print_fpu_flags (status);
3809 }
3810
3811 /* Construct the ARM extended floating point type.  */
3812 static struct type *
3813 arm_ext_type (struct gdbarch *gdbarch)
3814 {
3815   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3816
3817   if (!tdep->arm_ext_type)
3818     tdep->arm_ext_type
3819       = arch_float_type (gdbarch, -1, "builtin_type_arm_ext",
3820                          floatformats_arm_ext);
3821
3822   return tdep->arm_ext_type;
3823 }
3824
3825 static struct type *
3826 arm_neon_double_type (struct gdbarch *gdbarch)
3827 {
3828   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3829
3830   if (tdep->neon_double_type == NULL)
3831     {
3832       struct type *t, *elem;
3833
3834       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_d",
3835                                TYPE_CODE_UNION);
3836       elem = builtin_type (gdbarch)->builtin_uint8;
3837       append_composite_type_field (t, "u8", init_vector_type (elem, 8));
3838       elem = builtin_type (gdbarch)->builtin_uint16;
3839       append_composite_type_field (t, "u16", init_vector_type (elem, 4));
3840       elem = builtin_type (gdbarch)->builtin_uint32;
3841       append_composite_type_field (t, "u32", init_vector_type (elem, 2));
3842       elem = builtin_type (gdbarch)->builtin_uint64;
3843       append_composite_type_field (t, "u64", elem);
3844       elem = builtin_type (gdbarch)->builtin_float;
3845       append_composite_type_field (t, "f32", init_vector_type (elem, 2));
3846       elem = builtin_type (gdbarch)->builtin_double;
3847       append_composite_type_field (t, "f64", elem);
3848
3849       TYPE_VECTOR (t) = 1;
3850       TYPE_NAME (t) = "neon_d";
3851       tdep->neon_double_type = t;
3852     }
3853
3854   return tdep->neon_double_type;
3855 }
3856
3857 /* FIXME: The vector types are not correctly ordered on big-endian
3858    targets.  Just as s0 is the low bits of d0, d0[0] is also the low
3859    bits of d0 - regardless of what unit size is being held in d0.  So
3860    the offset of the first uint8 in d0 is 7, but the offset of the
3861    first float is 4.  This code works as-is for little-endian
3862    targets.  */
3863
3864 static struct type *
3865 arm_neon_quad_type (struct gdbarch *gdbarch)
3866 {
3867   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3868
3869   if (tdep->neon_quad_type == NULL)
3870     {
3871       struct type *t, *elem;
3872
3873       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_q",
3874                                TYPE_CODE_UNION);
3875       elem = builtin_type (gdbarch)->builtin_uint8;
3876       append_composite_type_field (t, "u8", init_vector_type (elem, 16));
3877       elem = builtin_type (gdbarch)->builtin_uint16;
3878       append_composite_type_field (t, "u16", init_vector_type (elem, 8));
3879       elem = builtin_type (gdbarch)->builtin_uint32;
3880       append_composite_type_field (t, "u32", init_vector_type (elem, 4));
3881       elem = builtin_type (gdbarch)->builtin_uint64;
3882       append_composite_type_field (t, "u64", init_vector_type (elem, 2));
3883       elem = builtin_type (gdbarch)->builtin_float;
3884       append_composite_type_field (t, "f32", init_vector_type (elem, 4));
3885       elem = builtin_type (gdbarch)->builtin_double;
3886       append_composite_type_field (t, "f64", init_vector_type (elem, 2));
3887
3888       TYPE_VECTOR (t) = 1;
3889       TYPE_NAME (t) = "neon_q";
3890       tdep->neon_quad_type = t;
3891     }
3892
3893   return tdep->neon_quad_type;
3894 }
3895
3896 /* Return the GDB type object for the "standard" data type of data in
3897    register N.  */
3898
3899 static struct type *
3900 arm_register_type (struct gdbarch *gdbarch, int regnum)
3901 {
3902   int num_regs = gdbarch_num_regs (gdbarch);
3903
3904   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
3905       && regnum >= num_regs && regnum < num_regs + 32)
3906     return builtin_type (gdbarch)->builtin_float;
3907
3908   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
3909       && regnum >= num_regs + 32 && regnum < num_regs + 32 + 16)
3910     return arm_neon_quad_type (gdbarch);
3911
3912   /* If the target description has register information, we are only
3913      in this function so that we can override the types of
3914      double-precision registers for NEON.  */
3915   if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
3916     {
3917       struct type *t = tdesc_register_type (gdbarch, regnum);
3918
3919       if (regnum >= ARM_D0_REGNUM && regnum < ARM_D0_REGNUM + 32
3920           && TYPE_CODE (t) == TYPE_CODE_FLT
3921           && gdbarch_tdep (gdbarch)->have_neon)
3922         return arm_neon_double_type (gdbarch);
3923       else
3924         return t;
3925     }
3926
3927   if (regnum >= ARM_F0_REGNUM && regnum < ARM_F0_REGNUM + NUM_FREGS)
3928     {
3929       if (!gdbarch_tdep (gdbarch)->have_fpa_registers)
3930         return builtin_type (gdbarch)->builtin_void;
3931
3932       return arm_ext_type (gdbarch);
3933     }
3934   else if (regnum == ARM_SP_REGNUM)
3935     return builtin_type (gdbarch)->builtin_data_ptr;
3936   else if (regnum == ARM_PC_REGNUM)
3937     return builtin_type (gdbarch)->builtin_func_ptr;
3938   else if (regnum >= ARRAY_SIZE (arm_register_names))
3939     /* These registers are only supported on targets which supply
3940        an XML description.  */
3941     return builtin_type (gdbarch)->builtin_int0;
3942   else
3943     return builtin_type (gdbarch)->builtin_uint32;
3944 }
3945
3946 /* Map a DWARF register REGNUM onto the appropriate GDB register
3947    number.  */
3948
3949 static int
3950 arm_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
3951 {
3952   /* Core integer regs.  */
3953   if (reg >= 0 && reg <= 15)
3954     return reg;
3955
3956   /* Legacy FPA encoding.  These were once used in a way which
3957      overlapped with VFP register numbering, so their use is
3958      discouraged, but GDB doesn't support the ARM toolchain
3959      which used them for VFP.  */
3960   if (reg >= 16 && reg <= 23)
3961     return ARM_F0_REGNUM + reg - 16;
3962
3963   /* New assignments for the FPA registers.  */
3964   if (reg >= 96 && reg <= 103)
3965     return ARM_F0_REGNUM + reg - 96;
3966
3967   /* WMMX register assignments.  */
3968   if (reg >= 104 && reg <= 111)
3969     return ARM_WCGR0_REGNUM + reg - 104;
3970
3971   if (reg >= 112 && reg <= 127)
3972     return ARM_WR0_REGNUM + reg - 112;
3973
3974   if (reg >= 192 && reg <= 199)
3975     return ARM_WC0_REGNUM + reg - 192;
3976
3977   /* VFP v2 registers.  A double precision value is actually
3978      in d1 rather than s2, but the ABI only defines numbering
3979      for the single precision registers.  This will "just work"
3980      in GDB for little endian targets (we'll read eight bytes,
3981      starting in s0 and then progressing to s1), but will be
3982      reversed on big endian targets with VFP.  This won't
3983      be a problem for the new Neon quad registers; you're supposed
3984      to use DW_OP_piece for those.  */
3985   if (reg >= 64 && reg <= 95)
3986     {
3987       char name_buf[4];
3988
3989       sprintf (name_buf, "s%d", reg - 64);
3990       return user_reg_map_name_to_regnum (gdbarch, name_buf,
3991                                           strlen (name_buf));
3992     }
3993
3994   /* VFP v3 / Neon registers.  This range is also used for VFP v2
3995      registers, except that it now describes d0 instead of s0.  */
3996   if (reg >= 256 && reg <= 287)
3997     {
3998       char name_buf[4];
3999
4000       sprintf (name_buf, "d%d", reg - 256);
4001       return user_reg_map_name_to_regnum (gdbarch, name_buf,
4002                                           strlen (name_buf));
4003     }
4004
4005   return -1;
4006 }
4007
4008 /* Map GDB internal REGNUM onto the Arm simulator register numbers.  */
4009 static int
4010 arm_register_sim_regno (struct gdbarch *gdbarch, int regnum)
4011 {
4012   int reg = regnum;
4013   gdb_assert (reg >= 0 && reg < gdbarch_num_regs (gdbarch));
4014
4015   if (regnum >= ARM_WR0_REGNUM && regnum <= ARM_WR15_REGNUM)
4016     return regnum - ARM_WR0_REGNUM + SIM_ARM_IWMMXT_COP0R0_REGNUM;
4017
4018   if (regnum >= ARM_WC0_REGNUM && regnum <= ARM_WC7_REGNUM)
4019     return regnum - ARM_WC0_REGNUM + SIM_ARM_IWMMXT_COP1R0_REGNUM;
4020
4021   if (regnum >= ARM_WCGR0_REGNUM && regnum <= ARM_WCGR7_REGNUM)
4022     return regnum - ARM_WCGR0_REGNUM + SIM_ARM_IWMMXT_COP1R8_REGNUM;
4023
4024   if (reg < NUM_GREGS)
4025     return SIM_ARM_R0_REGNUM + reg;
4026   reg -= NUM_GREGS;
4027
4028   if (reg < NUM_FREGS)
4029     return SIM_ARM_FP0_REGNUM + reg;
4030   reg -= NUM_FREGS;
4031
4032   if (reg < NUM_SREGS)
4033     return SIM_ARM_FPS_REGNUM + reg;
4034   reg -= NUM_SREGS;
4035
4036   internal_error (__FILE__, __LINE__, _("Bad REGNUM %d"), regnum);
4037 }
4038
4039 /* NOTE: cagney/2001-08-20: Both convert_from_extended() and
4040    convert_to_extended() use floatformat_arm_ext_littlebyte_bigword.
4041    It is thought that this is is the floating-point register format on
4042    little-endian systems.  */
4043
4044 static void
4045 convert_from_extended (const struct floatformat *fmt, const void *ptr,
4046                        void *dbl, int endianess)
4047 {
4048   DOUBLEST d;
4049
4050   if (endianess == BFD_ENDIAN_BIG)
4051     floatformat_to_doublest (&floatformat_arm_ext_big, ptr, &d);
4052   else
4053     floatformat_to_doublest (&floatformat_arm_ext_littlebyte_bigword,
4054                              ptr, &d);
4055   floatformat_from_doublest (fmt, &d, dbl);
4056 }
4057
4058 static void
4059 convert_to_extended (const struct floatformat *fmt, void *dbl, const void *ptr,
4060                      int endianess)
4061 {
4062   DOUBLEST d;
4063
4064   floatformat_to_doublest (fmt, ptr, &d);
4065   if (endianess == BFD_ENDIAN_BIG)
4066     floatformat_from_doublest (&floatformat_arm_ext_big, &d, dbl);
4067   else
4068     floatformat_from_doublest (&floatformat_arm_ext_littlebyte_bigword,
4069                                &d, dbl);
4070 }
4071
4072 static int
4073 condition_true (unsigned long cond, unsigned long status_reg)
4074 {
4075   if (cond == INST_AL || cond == INST_NV)
4076     return 1;
4077
4078   switch (cond)
4079     {
4080     case INST_EQ:
4081       return ((status_reg & FLAG_Z) != 0);
4082     case INST_NE:
4083       return ((status_reg & FLAG_Z) == 0);
4084     case INST_CS:
4085       return ((status_reg & FLAG_C) != 0);
4086     case INST_CC:
4087       return ((status_reg & FLAG_C) == 0);
4088     case INST_MI:
4089       return ((status_reg & FLAG_N) != 0);
4090     case INST_PL:
4091       return ((status_reg & FLAG_N) == 0);
4092     case INST_VS:
4093       return ((status_reg & FLAG_V) != 0);
4094     case INST_VC:
4095       return ((status_reg & FLAG_V) == 0);
4096     case INST_HI:
4097       return ((status_reg & (FLAG_C | FLAG_Z)) == FLAG_C);
4098     case INST_LS:
4099       return ((status_reg & (FLAG_C | FLAG_Z)) != FLAG_C);
4100     case INST_GE:
4101       return (((status_reg & FLAG_N) == 0) == ((status_reg & FLAG_V) == 0));
4102     case INST_LT:
4103       return (((status_reg & FLAG_N) == 0) != ((status_reg & FLAG_V) == 0));
4104     case INST_GT:
4105       return (((status_reg & FLAG_Z) == 0)
4106               && (((status_reg & FLAG_N) == 0)
4107                   == ((status_reg & FLAG_V) == 0)));
4108     case INST_LE:
4109       return (((status_reg & FLAG_Z) != 0)
4110               || (((status_reg & FLAG_N) == 0)
4111                   != ((status_reg & FLAG_V) == 0)));
4112     }
4113   return 1;
4114 }
4115
4116 static unsigned long
4117 shifted_reg_val (struct frame_info *frame, unsigned long inst, int carry,
4118                  unsigned long pc_val, unsigned long status_reg)
4119 {
4120   unsigned long res, shift;
4121   int rm = bits (inst, 0, 3);
4122   unsigned long shifttype = bits (inst, 5, 6);
4123
4124   if (bit (inst, 4))
4125     {
4126       int rs = bits (inst, 8, 11);
4127       shift = (rs == 15 ? pc_val + 8
4128                         : get_frame_register_unsigned (frame, rs)) & 0xFF;
4129     }
4130   else
4131     shift = bits (inst, 7, 11);
4132
4133   res = (rm == 15
4134          ? (pc_val + (bit (inst, 4) ? 12 : 8))
4135          : get_frame_register_unsigned (frame, rm));
4136
4137   switch (shifttype)
4138     {
4139     case 0:                     /* LSL */
4140       res = shift >= 32 ? 0 : res << shift;
4141       break;
4142
4143     case 1:                     /* LSR */
4144       res = shift >= 32 ? 0 : res >> shift;
4145       break;
4146
4147     case 2:                     /* ASR */
4148       if (shift >= 32)
4149         shift = 31;
4150       res = ((res & 0x80000000L)
4151              ? ~((~res) >> shift) : res >> shift);
4152       break;
4153
4154     case 3:                     /* ROR/RRX */
4155       shift &= 31;
4156       if (shift == 0)
4157         res = (res >> 1) | (carry ? 0x80000000L : 0);
4158       else
4159         res = (res >> shift) | (res << (32 - shift));
4160       break;
4161     }
4162
4163   return res & 0xffffffff;
4164 }
4165
4166 /* Return number of 1-bits in VAL.  */
4167
4168 static int
4169 bitcount (unsigned long val)
4170 {
4171   int nbits;
4172   for (nbits = 0; val != 0; nbits++)
4173     val &= val - 1;             /* Delete rightmost 1-bit in val.  */
4174   return nbits;
4175 }
4176
4177 /* Return the size in bytes of the complete Thumb instruction whose
4178    first halfword is INST1.  */
4179
4180 static int
4181 thumb_insn_size (unsigned short inst1)
4182 {
4183   if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
4184     return 4;
4185   else
4186     return 2;
4187 }
4188
4189 static int
4190 thumb_advance_itstate (unsigned int itstate)
4191 {
4192   /* Preserve IT[7:5], the first three bits of the condition.  Shift
4193      the upcoming condition flags left by one bit.  */
4194   itstate = (itstate & 0xe0) | ((itstate << 1) & 0x1f);
4195
4196   /* If we have finished the IT block, clear the state.  */
4197   if ((itstate & 0x0f) == 0)
4198     itstate = 0;
4199
4200   return itstate;
4201 }
4202
4203 /* Find the next PC after the current instruction executes.  In some
4204    cases we can not statically determine the answer (see the IT state
4205    handling in this function); in that case, a breakpoint may be
4206    inserted in addition to the returned PC, which will be used to set
4207    another breakpoint by our caller.  */
4208
4209 static CORE_ADDR
4210 thumb_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc, int insert_bkpt)
4211 {
4212   struct gdbarch *gdbarch = get_frame_arch (frame);
4213   struct address_space *aspace = get_frame_address_space (frame);
4214   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4215   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4216   unsigned long pc_val = ((unsigned long) pc) + 4;      /* PC after prefetch */
4217   unsigned short inst1;
4218   CORE_ADDR nextpc = pc + 2;            /* Default is next instruction.  */
4219   unsigned long offset;
4220   ULONGEST status, itstate;
4221
4222   nextpc = MAKE_THUMB_ADDR (nextpc);
4223   pc_val = MAKE_THUMB_ADDR (pc_val);
4224
4225   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
4226
4227   /* Thumb-2 conditional execution support.  There are eight bits in
4228      the CPSR which describe conditional execution state.  Once
4229      reconstructed (they're in a funny order), the low five bits
4230      describe the low bit of the condition for each instruction and
4231      how many instructions remain.  The high three bits describe the
4232      base condition.  One of the low four bits will be set if an IT
4233      block is active.  These bits read as zero on earlier
4234      processors.  */
4235   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4236   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
4237
4238   /* If-Then handling.  On GNU/Linux, where this routine is used, we
4239      use an undefined instruction as a breakpoint.  Unlike BKPT, IT
4240      can disable execution of the undefined instruction.  So we might
4241      miss the breakpoint if we set it on a skipped conditional
4242      instruction.  Because conditional instructions can change the
4243      flags, affecting the execution of further instructions, we may
4244      need to set two breakpoints.  */
4245
4246   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint != NULL)
4247     {
4248       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
4249         {
4250           /* An IT instruction.  Because this instruction does not
4251              modify the flags, we can accurately predict the next
4252              executed instruction.  */
4253           itstate = inst1 & 0x00ff;
4254           pc += thumb_insn_size (inst1);
4255
4256           while (itstate != 0 && ! condition_true (itstate >> 4, status))
4257             {
4258               inst1 = read_memory_unsigned_integer (pc, 2,
4259                                                     byte_order_for_code);
4260               pc += thumb_insn_size (inst1);
4261               itstate = thumb_advance_itstate (itstate);
4262             }
4263
4264           return MAKE_THUMB_ADDR (pc);
4265         }
4266       else if (itstate != 0)
4267         {
4268           /* We are in a conditional block.  Check the condition.  */
4269           if (! condition_true (itstate >> 4, status))
4270             {
4271               /* Advance to the next executed instruction.  */
4272               pc += thumb_insn_size (inst1);
4273               itstate = thumb_advance_itstate (itstate);
4274
4275               while (itstate != 0 && ! condition_true (itstate >> 4, status))
4276                 {
4277                   inst1 = read_memory_unsigned_integer (pc, 2, 
4278                                                         byte_order_for_code);
4279                   pc += thumb_insn_size (inst1);
4280                   itstate = thumb_advance_itstate (itstate);
4281                 }
4282
4283               return MAKE_THUMB_ADDR (pc);
4284             }
4285           else if ((itstate & 0x0f) == 0x08)
4286             {
4287               /* This is the last instruction of the conditional
4288                  block, and it is executed.  We can handle it normally
4289                  because the following instruction is not conditional,
4290                  and we must handle it normally because it is
4291                  permitted to branch.  Fall through.  */
4292             }
4293           else
4294             {
4295               int cond_negated;
4296
4297               /* There are conditional instructions after this one.
4298                  If this instruction modifies the flags, then we can
4299                  not predict what the next executed instruction will
4300                  be.  Fortunately, this instruction is architecturally
4301                  forbidden to branch; we know it will fall through.
4302                  Start by skipping past it.  */
4303               pc += thumb_insn_size (inst1);
4304               itstate = thumb_advance_itstate (itstate);
4305
4306               /* Set a breakpoint on the following instruction.  */
4307               gdb_assert ((itstate & 0x0f) != 0);
4308               if (insert_bkpt)
4309                 insert_single_step_breakpoint (gdbarch, aspace, pc);
4310               cond_negated = (itstate >> 4) & 1;
4311
4312               /* Skip all following instructions with the same
4313                  condition.  If there is a later instruction in the IT
4314                  block with the opposite condition, set the other
4315                  breakpoint there.  If not, then set a breakpoint on
4316                  the instruction after the IT block.  */
4317               do
4318                 {
4319                   inst1 = read_memory_unsigned_integer (pc, 2,
4320                                                         byte_order_for_code);
4321                   pc += thumb_insn_size (inst1);
4322                   itstate = thumb_advance_itstate (itstate);
4323                 }
4324               while (itstate != 0 && ((itstate >> 4) & 1) == cond_negated);
4325
4326               return MAKE_THUMB_ADDR (pc);
4327             }
4328         }
4329     }
4330   else if (itstate & 0x0f)
4331     {
4332       /* We are in a conditional block.  Check the condition.  */
4333       int cond = itstate >> 4;
4334
4335       if (! condition_true (cond, status))
4336         {
4337           /* Advance to the next instruction.  All the 32-bit
4338              instructions share a common prefix.  */
4339           if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
4340             return MAKE_THUMB_ADDR (pc + 4);
4341           else
4342             return MAKE_THUMB_ADDR (pc + 2);
4343         }
4344
4345       /* Otherwise, handle the instruction normally.  */
4346     }
4347
4348   if ((inst1 & 0xff00) == 0xbd00)       /* pop {rlist, pc} */
4349     {
4350       CORE_ADDR sp;
4351
4352       /* Fetch the saved PC from the stack.  It's stored above
4353          all of the other registers.  */
4354       offset = bitcount (bits (inst1, 0, 7)) * INT_REGISTER_SIZE;
4355       sp = get_frame_register_unsigned (frame, ARM_SP_REGNUM);
4356       nextpc = read_memory_unsigned_integer (sp + offset, 4, byte_order);
4357     }
4358   else if ((inst1 & 0xf000) == 0xd000)  /* conditional branch */
4359     {
4360       unsigned long cond = bits (inst1, 8, 11);
4361       if (cond == 0x0f)  /* 0x0f = SWI */
4362         {
4363           struct gdbarch_tdep *tdep;
4364           tdep = gdbarch_tdep (gdbarch);
4365
4366           if (tdep->syscall_next_pc != NULL)
4367             nextpc = tdep->syscall_next_pc (frame);
4368
4369         }
4370       else if (cond != 0x0f && condition_true (cond, status))
4371         nextpc = pc_val + (sbits (inst1, 0, 7) << 1);
4372     }
4373   else if ((inst1 & 0xf800) == 0xe000)  /* unconditional branch */
4374     {
4375       nextpc = pc_val + (sbits (inst1, 0, 10) << 1);
4376     }
4377   else if ((inst1 & 0xe000) == 0xe000) /* 32-bit instruction */
4378     {
4379       unsigned short inst2;
4380       inst2 = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
4381
4382       /* Default to the next instruction.  */
4383       nextpc = pc + 4;
4384       nextpc = MAKE_THUMB_ADDR (nextpc);
4385
4386       if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
4387         {
4388           /* Branches and miscellaneous control instructions.  */
4389
4390           if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
4391             {
4392               /* B, BL, BLX.  */
4393               int j1, j2, imm1, imm2;
4394
4395               imm1 = sbits (inst1, 0, 10);
4396               imm2 = bits (inst2, 0, 10);
4397               j1 = bit (inst2, 13);
4398               j2 = bit (inst2, 11);
4399
4400               offset = ((imm1 << 12) + (imm2 << 1));
4401               offset ^= ((!j2) << 22) | ((!j1) << 23);
4402
4403               nextpc = pc_val + offset;
4404               /* For BLX make sure to clear the low bits.  */
4405               if (bit (inst2, 12) == 0)
4406                 nextpc = nextpc & 0xfffffffc;
4407             }
4408           else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
4409             {
4410               /* SUBS PC, LR, #imm8.  */
4411               nextpc = get_frame_register_unsigned (frame, ARM_LR_REGNUM);
4412               nextpc -= inst2 & 0x00ff;
4413             }
4414           else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
4415             {
4416               /* Conditional branch.  */
4417               if (condition_true (bits (inst1, 6, 9), status))
4418                 {
4419                   int sign, j1, j2, imm1, imm2;
4420
4421                   sign = sbits (inst1, 10, 10);
4422                   imm1 = bits (inst1, 0, 5);
4423                   imm2 = bits (inst2, 0, 10);
4424                   j1 = bit (inst2, 13);
4425                   j2 = bit (inst2, 11);
4426
4427                   offset = (sign << 20) + (j2 << 19) + (j1 << 18);
4428                   offset += (imm1 << 12) + (imm2 << 1);
4429
4430                   nextpc = pc_val + offset;
4431                 }
4432             }
4433         }
4434       else if ((inst1 & 0xfe50) == 0xe810)
4435         {
4436           /* Load multiple or RFE.  */
4437           int rn, offset, load_pc = 1;
4438
4439           rn = bits (inst1, 0, 3);
4440           if (bit (inst1, 7) && !bit (inst1, 8))
4441             {
4442               /* LDMIA or POP */
4443               if (!bit (inst2, 15))
4444                 load_pc = 0;
4445               offset = bitcount (inst2) * 4 - 4;
4446             }
4447           else if (!bit (inst1, 7) && bit (inst1, 8))
4448             {
4449               /* LDMDB */
4450               if (!bit (inst2, 15))
4451                 load_pc = 0;
4452               offset = -4;
4453             }
4454           else if (bit (inst1, 7) && bit (inst1, 8))
4455             {
4456               /* RFEIA */
4457               offset = 0;
4458             }
4459           else if (!bit (inst1, 7) && !bit (inst1, 8))
4460             {
4461               /* RFEDB */
4462               offset = -8;
4463             }
4464           else
4465             load_pc = 0;
4466
4467           if (load_pc)
4468             {
4469               CORE_ADDR addr = get_frame_register_unsigned (frame, rn);
4470               nextpc = get_frame_memory_unsigned (frame, addr + offset, 4);
4471             }
4472         }
4473       else if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
4474         {
4475           /* MOV PC or MOVS PC.  */
4476           nextpc = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4477           nextpc = MAKE_THUMB_ADDR (nextpc);
4478         }
4479       else if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
4480         {
4481           /* LDR PC.  */
4482           CORE_ADDR base;
4483           int rn, load_pc = 1;
4484
4485           rn = bits (inst1, 0, 3);
4486           base = get_frame_register_unsigned (frame, rn);
4487           if (rn == 15)
4488             {
4489               base = (base + 4) & ~(CORE_ADDR) 0x3;
4490               if (bit (inst1, 7))
4491                 base += bits (inst2, 0, 11);
4492               else
4493                 base -= bits (inst2, 0, 11);
4494             }
4495           else if (bit (inst1, 7))
4496             base += bits (inst2, 0, 11);
4497           else if (bit (inst2, 11))
4498             {
4499               if (bit (inst2, 10))
4500                 {
4501                   if (bit (inst2, 9))
4502                     base += bits (inst2, 0, 7);
4503                   else
4504                     base -= bits (inst2, 0, 7);
4505                 }
4506             }
4507           else if ((inst2 & 0x0fc0) == 0x0000)
4508             {
4509               int shift = bits (inst2, 4, 5), rm = bits (inst2, 0, 3);
4510               base += get_frame_register_unsigned (frame, rm) << shift;
4511             }
4512           else
4513             /* Reserved.  */
4514             load_pc = 0;
4515
4516           if (load_pc)
4517             nextpc = get_frame_memory_unsigned (frame, base, 4);
4518         }
4519       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
4520         {
4521           /* TBB.  */
4522           CORE_ADDR tbl_reg, table, offset, length;
4523
4524           tbl_reg = bits (inst1, 0, 3);
4525           if (tbl_reg == 0x0f)
4526             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4527           else
4528             table = get_frame_register_unsigned (frame, tbl_reg);
4529
4530           offset = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4531           length = 2 * get_frame_memory_unsigned (frame, table + offset, 1);
4532           nextpc = pc_val + length;
4533         }
4534       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
4535         {
4536           /* TBH.  */
4537           CORE_ADDR tbl_reg, table, offset, length;
4538
4539           tbl_reg = bits (inst1, 0, 3);
4540           if (tbl_reg == 0x0f)
4541             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4542           else
4543             table = get_frame_register_unsigned (frame, tbl_reg);
4544
4545           offset = 2 * get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4546           length = 2 * get_frame_memory_unsigned (frame, table + offset, 2);
4547           nextpc = pc_val + length;
4548         }
4549     }
4550   else if ((inst1 & 0xff00) == 0x4700)  /* bx REG, blx REG */
4551     {
4552       if (bits (inst1, 3, 6) == 0x0f)
4553         nextpc = pc_val;
4554       else
4555         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4556     }
4557   else if ((inst1 & 0xff87) == 0x4687)  /* mov pc, REG */
4558     {
4559       if (bits (inst1, 3, 6) == 0x0f)
4560         nextpc = pc_val;
4561       else
4562         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4563
4564       nextpc = MAKE_THUMB_ADDR (nextpc);
4565     }
4566   else if ((inst1 & 0xf500) == 0xb100)
4567     {
4568       /* CBNZ or CBZ.  */
4569       int imm = (bit (inst1, 9) << 6) + (bits (inst1, 3, 7) << 1);
4570       ULONGEST reg = get_frame_register_unsigned (frame, bits (inst1, 0, 2));
4571
4572       if (bit (inst1, 11) && reg != 0)
4573         nextpc = pc_val + imm;
4574       else if (!bit (inst1, 11) && reg == 0)
4575         nextpc = pc_val + imm;
4576     }
4577   return nextpc;
4578 }
4579
4580 /* Get the raw next address.  PC is the current program counter, in 
4581    FRAME.  INSERT_BKPT should be TRUE if we want a breakpoint set on 
4582    the alternative next instruction if there are two options.
4583
4584    The value returned has the execution state of the next instruction 
4585    encoded in it.  Use IS_THUMB_ADDR () to see whether the instruction is
4586    in Thumb-State, and gdbarch_addr_bits_remove () to get the plain memory
4587    address.  */
4588
4589 static CORE_ADDR
4590 arm_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc, int insert_bkpt)
4591 {
4592   struct gdbarch *gdbarch = get_frame_arch (frame);
4593   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4594   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4595   unsigned long pc_val;
4596   unsigned long this_instr;
4597   unsigned long status;
4598   CORE_ADDR nextpc;
4599
4600   if (arm_frame_is_thumb (frame))
4601     return thumb_get_next_pc_raw (frame, pc, insert_bkpt);
4602
4603   pc_val = (unsigned long) pc;
4604   this_instr = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
4605
4606   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4607   nextpc = (CORE_ADDR) (pc_val + 4);    /* Default case */
4608
4609   if (bits (this_instr, 28, 31) == INST_NV)
4610     switch (bits (this_instr, 24, 27))
4611       {
4612       case 0xa:
4613       case 0xb:
4614         {
4615           /* Branch with Link and change to Thumb.  */
4616           nextpc = BranchDest (pc, this_instr);
4617           nextpc |= bit (this_instr, 24) << 1;
4618           nextpc = MAKE_THUMB_ADDR (nextpc);
4619           break;
4620         }
4621       case 0xc:
4622       case 0xd:
4623       case 0xe:
4624         /* Coprocessor register transfer.  */
4625         if (bits (this_instr, 12, 15) == 15)
4626           error (_("Invalid update to pc in instruction"));
4627         break;
4628       }
4629   else if (condition_true (bits (this_instr, 28, 31), status))
4630     {
4631       switch (bits (this_instr, 24, 27))
4632         {
4633         case 0x0:
4634         case 0x1:                       /* data processing */
4635         case 0x2:
4636         case 0x3:
4637           {
4638             unsigned long operand1, operand2, result = 0;
4639             unsigned long rn;
4640             int c;
4641
4642             if (bits (this_instr, 12, 15) != 15)
4643               break;
4644
4645             if (bits (this_instr, 22, 25) == 0
4646                 && bits (this_instr, 4, 7) == 9)        /* multiply */
4647               error (_("Invalid update to pc in instruction"));
4648
4649             /* BX <reg>, BLX <reg> */
4650             if (bits (this_instr, 4, 27) == 0x12fff1
4651                 || bits (this_instr, 4, 27) == 0x12fff3)
4652               {
4653                 rn = bits (this_instr, 0, 3);
4654                 nextpc = (rn == 15) ? pc_val + 8
4655                                     : get_frame_register_unsigned (frame, rn);
4656                 return nextpc;
4657               }
4658
4659             /* Multiply into PC.  */
4660             c = (status & FLAG_C) ? 1 : 0;
4661             rn = bits (this_instr, 16, 19);
4662             operand1 = (rn == 15) ? pc_val + 8
4663                                   : get_frame_register_unsigned (frame, rn);
4664
4665             if (bit (this_instr, 25))
4666               {
4667                 unsigned long immval = bits (this_instr, 0, 7);
4668                 unsigned long rotate = 2 * bits (this_instr, 8, 11);
4669                 operand2 = ((immval >> rotate) | (immval << (32 - rotate)))
4670                   & 0xffffffff;
4671               }
4672             else                /* operand 2 is a shifted register.  */
4673               operand2 = shifted_reg_val (frame, this_instr, c,
4674                                           pc_val, status);
4675
4676             switch (bits (this_instr, 21, 24))
4677               {
4678               case 0x0: /*and */
4679                 result = operand1 & operand2;
4680                 break;
4681
4682               case 0x1: /*eor */
4683                 result = operand1 ^ operand2;
4684                 break;
4685
4686               case 0x2: /*sub */
4687                 result = operand1 - operand2;
4688                 break;
4689
4690               case 0x3: /*rsb */
4691                 result = operand2 - operand1;
4692                 break;
4693
4694               case 0x4: /*add */
4695                 result = operand1 + operand2;
4696                 break;
4697
4698               case 0x5: /*adc */
4699                 result = operand1 + operand2 + c;
4700                 break;
4701
4702               case 0x6: /*sbc */
4703                 result = operand1 - operand2 + c;
4704                 break;
4705
4706               case 0x7: /*rsc */
4707                 result = operand2 - operand1 + c;
4708                 break;
4709
4710               case 0x8:
4711               case 0x9:
4712               case 0xa:
4713               case 0xb: /* tst, teq, cmp, cmn */
4714                 result = (unsigned long) nextpc;
4715                 break;
4716
4717               case 0xc: /*orr */
4718                 result = operand1 | operand2;
4719                 break;
4720
4721               case 0xd: /*mov */
4722                 /* Always step into a function.  */
4723                 result = operand2;
4724                 break;
4725
4726               case 0xe: /*bic */
4727                 result = operand1 & ~operand2;
4728                 break;
4729
4730               case 0xf: /*mvn */
4731                 result = ~operand2;
4732                 break;
4733               }
4734
4735             /* In 26-bit APCS the bottom two bits of the result are 
4736                ignored, and we always end up in ARM state.  */
4737             if (!arm_apcs_32)
4738               nextpc = arm_addr_bits_remove (gdbarch, result);
4739             else
4740               nextpc = result;
4741
4742             break;
4743           }
4744
4745         case 0x4:
4746         case 0x5:               /* data transfer */
4747         case 0x6:
4748         case 0x7:
4749           if (bit (this_instr, 20))
4750             {
4751               /* load */
4752               if (bits (this_instr, 12, 15) == 15)
4753                 {
4754                   /* rd == pc */
4755                   unsigned long rn;
4756                   unsigned long base;
4757
4758                   if (bit (this_instr, 22))
4759                     error (_("Invalid update to pc in instruction"));
4760
4761                   /* byte write to PC */
4762                   rn = bits (this_instr, 16, 19);
4763                   base = (rn == 15) ? pc_val + 8
4764                                     : get_frame_register_unsigned (frame, rn);
4765                   if (bit (this_instr, 24))
4766                     {
4767                       /* pre-indexed */
4768                       int c = (status & FLAG_C) ? 1 : 0;
4769                       unsigned long offset =
4770                       (bit (this_instr, 25)
4771                        ? shifted_reg_val (frame, this_instr, c, pc_val, status)
4772                        : bits (this_instr, 0, 11));
4773
4774                       if (bit (this_instr, 23))
4775                         base += offset;
4776                       else
4777                         base -= offset;
4778                     }
4779                   nextpc = (CORE_ADDR) read_memory_integer ((CORE_ADDR) base,
4780                                                             4, byte_order);
4781                 }
4782             }
4783           break;
4784
4785         case 0x8:
4786         case 0x9:               /* block transfer */
4787           if (bit (this_instr, 20))
4788             {
4789               /* LDM */
4790               if (bit (this_instr, 15))
4791                 {
4792                   /* loading pc */
4793                   int offset = 0;
4794
4795                   if (bit (this_instr, 23))
4796                     {
4797                       /* up */
4798                       unsigned long reglist = bits (this_instr, 0, 14);
4799                       offset = bitcount (reglist) * 4;
4800                       if (bit (this_instr, 24))         /* pre */
4801                         offset += 4;
4802                     }
4803                   else if (bit (this_instr, 24))
4804                     offset = -4;
4805
4806                   {
4807                     unsigned long rn_val =
4808                     get_frame_register_unsigned (frame,
4809                                                  bits (this_instr, 16, 19));
4810                     nextpc =
4811                       (CORE_ADDR) read_memory_integer ((CORE_ADDR) (rn_val
4812                                                                   + offset),
4813                                                        4, byte_order);
4814                   }
4815                 }
4816             }
4817           break;
4818
4819         case 0xb:               /* branch & link */
4820         case 0xa:               /* branch */
4821           {
4822             nextpc = BranchDest (pc, this_instr);
4823             break;
4824           }
4825
4826         case 0xc:
4827         case 0xd:
4828         case 0xe:               /* coproc ops */
4829           break;
4830         case 0xf:               /* SWI */
4831           {
4832             struct gdbarch_tdep *tdep;
4833             tdep = gdbarch_tdep (gdbarch);
4834
4835             if (tdep->syscall_next_pc != NULL)
4836               nextpc = tdep->syscall_next_pc (frame);
4837
4838           }
4839           break;
4840
4841         default:
4842           fprintf_filtered (gdb_stderr, _("Bad bit-field extraction\n"));
4843           return (pc);
4844         }
4845     }
4846
4847   return nextpc;
4848 }
4849
4850 CORE_ADDR
4851 arm_get_next_pc (struct frame_info *frame, CORE_ADDR pc)
4852 {
4853   struct gdbarch *gdbarch = get_frame_arch (frame);
4854   CORE_ADDR nextpc = 
4855     gdbarch_addr_bits_remove (gdbarch, 
4856                               arm_get_next_pc_raw (frame, pc, TRUE));
4857   if (nextpc == pc)
4858     error (_("Infinite loop detected"));
4859   return nextpc;
4860 }
4861
4862 /* single_step() is called just before we want to resume the inferior,
4863    if we want to single-step it but there is no hardware or kernel
4864    single-step support.  We find the target of the coming instruction
4865    and breakpoint it.  */
4866
4867 int
4868 arm_software_single_step (struct frame_info *frame)
4869 {
4870   struct gdbarch *gdbarch = get_frame_arch (frame);
4871   struct address_space *aspace = get_frame_address_space (frame);
4872
4873   /* NOTE: This may insert the wrong breakpoint instruction when
4874      single-stepping over a mode-changing instruction, if the
4875      CPSR heuristics are used.  */
4876
4877   CORE_ADDR next_pc = arm_get_next_pc (frame, get_frame_pc (frame));
4878   insert_single_step_breakpoint (gdbarch, aspace, next_pc);
4879
4880   return 1;
4881 }
4882
4883 /* Given BUF, which is OLD_LEN bytes ending at ENDADDR, expand
4884    the buffer to be NEW_LEN bytes ending at ENDADDR.  Return
4885    NULL if an error occurs.  BUF is freed.  */
4886
4887 static gdb_byte *
4888 extend_buffer_earlier (gdb_byte *buf, CORE_ADDR endaddr,
4889                        int old_len, int new_len)
4890 {
4891   gdb_byte *new_buf, *middle;
4892   int bytes_to_read = new_len - old_len;
4893
4894   new_buf = xmalloc (new_len);
4895   memcpy (new_buf + bytes_to_read, buf, old_len);
4896   xfree (buf);
4897   if (target_read_memory (endaddr - new_len, new_buf, bytes_to_read) != 0)
4898     {
4899       xfree (new_buf);
4900       return NULL;
4901     }
4902   return new_buf;
4903 }
4904
4905 /* An IT block is at most the 2-byte IT instruction followed by
4906    four 4-byte instructions.  The furthest back we must search to
4907    find an IT block that affects the current instruction is thus
4908    2 + 3 * 4 == 14 bytes.  */
4909 #define MAX_IT_BLOCK_PREFIX 14
4910
4911 /* Use a quick scan if there are more than this many bytes of
4912    code.  */
4913 #define IT_SCAN_THRESHOLD 32
4914
4915 /* Adjust a breakpoint's address to move breakpoints out of IT blocks.
4916    A breakpoint in an IT block may not be hit, depending on the
4917    condition flags.  */
4918 static CORE_ADDR
4919 arm_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
4920 {
4921   gdb_byte *buf;
4922   char map_type;
4923   CORE_ADDR boundary, func_start;
4924   int buf_len, buf2_len;
4925   enum bfd_endian order = gdbarch_byte_order_for_code (gdbarch);
4926   int i, any, last_it, last_it_count;
4927
4928   /* If we are using BKPT breakpoints, none of this is necessary.  */
4929   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint == NULL)
4930     return bpaddr;
4931
4932   /* ARM mode does not have this problem.  */
4933   if (!arm_pc_is_thumb (gdbarch, bpaddr))
4934     return bpaddr;
4935
4936   /* We are setting a breakpoint in Thumb code that could potentially
4937      contain an IT block.  The first step is to find how much Thumb
4938      code there is; we do not need to read outside of known Thumb
4939      sequences.  */
4940   map_type = arm_find_mapping_symbol (bpaddr, &boundary);
4941   if (map_type == 0)
4942     /* Thumb-2 code must have mapping symbols to have a chance.  */
4943     return bpaddr;
4944
4945   bpaddr = gdbarch_addr_bits_remove (gdbarch, bpaddr);
4946
4947   if (find_pc_partial_function (bpaddr, NULL, &func_start, NULL)
4948       && func_start > boundary)
4949     boundary = func_start;
4950
4951   /* Search for a candidate IT instruction.  We have to do some fancy
4952      footwork to distinguish a real IT instruction from the second
4953      half of a 32-bit instruction, but there is no need for that if
4954      there's no candidate.  */
4955   buf_len = min (bpaddr - boundary, MAX_IT_BLOCK_PREFIX);
4956   if (buf_len == 0)
4957     /* No room for an IT instruction.  */
4958     return bpaddr;
4959
4960   buf = xmalloc (buf_len);
4961   if (target_read_memory (bpaddr - buf_len, buf, buf_len) != 0)
4962     return bpaddr;
4963   any = 0;
4964   for (i = 0; i < buf_len; i += 2)
4965     {
4966       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
4967       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
4968         {
4969           any = 1;
4970           break;
4971         }
4972     }
4973   if (any == 0)
4974     {
4975       xfree (buf);
4976       return bpaddr;
4977     }
4978
4979   /* OK, the code bytes before this instruction contain at least one
4980      halfword which resembles an IT instruction.  We know that it's
4981      Thumb code, but there are still two possibilities.  Either the
4982      halfword really is an IT instruction, or it is the second half of
4983      a 32-bit Thumb instruction.  The only way we can tell is to
4984      scan forwards from a known instruction boundary.  */
4985   if (bpaddr - boundary > IT_SCAN_THRESHOLD)
4986     {
4987       int definite;
4988
4989       /* There's a lot of code before this instruction.  Start with an
4990          optimistic search; it's easy to recognize halfwords that can
4991          not be the start of a 32-bit instruction, and use that to
4992          lock on to the instruction boundaries.  */
4993       buf = extend_buffer_earlier (buf, bpaddr, buf_len, IT_SCAN_THRESHOLD);
4994       if (buf == NULL)
4995         return bpaddr;
4996       buf_len = IT_SCAN_THRESHOLD;
4997
4998       definite = 0;
4999       for (i = 0; i < buf_len - sizeof (buf) && ! definite; i += 2)
5000         {
5001           unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5002           if (thumb_insn_size (inst1) == 2)
5003             {
5004               definite = 1;
5005               break;
5006             }
5007         }
5008
5009       /* At this point, if DEFINITE, BUF[I] is the first place we
5010          are sure that we know the instruction boundaries, and it is far
5011          enough from BPADDR that we could not miss an IT instruction
5012          affecting BPADDR.  If ! DEFINITE, give up - start from a
5013          known boundary.  */
5014       if (! definite)
5015         {
5016           buf = extend_buffer_earlier (buf, bpaddr, buf_len,
5017                                        bpaddr - boundary);
5018           if (buf == NULL)
5019             return bpaddr;
5020           buf_len = bpaddr - boundary;
5021           i = 0;
5022         }
5023     }
5024   else
5025     {
5026       buf = extend_buffer_earlier (buf, bpaddr, buf_len, bpaddr - boundary);
5027       if (buf == NULL)
5028         return bpaddr;
5029       buf_len = bpaddr - boundary;
5030       i = 0;
5031     }
5032
5033   /* Scan forwards.  Find the last IT instruction before BPADDR.  */
5034   last_it = -1;
5035   last_it_count = 0;
5036   while (i < buf_len)
5037     {
5038       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5039       last_it_count--;
5040       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
5041         {
5042           last_it = i;
5043           if (inst1 & 0x0001)
5044             last_it_count = 4;
5045           else if (inst1 & 0x0002)
5046             last_it_count = 3;
5047           else if (inst1 & 0x0004)
5048             last_it_count = 2;
5049           else
5050             last_it_count = 1;
5051         }
5052       i += thumb_insn_size (inst1);
5053     }
5054
5055   xfree (buf);
5056
5057   if (last_it == -1)
5058     /* There wasn't really an IT instruction after all.  */
5059     return bpaddr;
5060
5061   if (last_it_count < 1)
5062     /* It was too far away.  */
5063     return bpaddr;
5064
5065   /* This really is a trouble spot.  Move the breakpoint to the IT
5066      instruction.  */
5067   return bpaddr - buf_len + last_it;
5068 }
5069
5070 /* ARM displaced stepping support.
5071
5072    Generally ARM displaced stepping works as follows:
5073
5074    1. When an instruction is to be single-stepped, it is first decoded by
5075       arm_process_displaced_insn (called from arm_displaced_step_copy_insn).
5076       Depending on the type of instruction, it is then copied to a scratch
5077       location, possibly in a modified form.  The copy_* set of functions
5078       performs such modification, as necessary.  A breakpoint is placed after
5079       the modified instruction in the scratch space to return control to GDB.
5080       Note in particular that instructions which modify the PC will no longer
5081       do so after modification.
5082
5083    2. The instruction is single-stepped, by setting the PC to the scratch
5084       location address, and resuming.  Control returns to GDB when the
5085       breakpoint is hit.
5086
5087    3. A cleanup function (cleanup_*) is called corresponding to the copy_*
5088       function used for the current instruction.  This function's job is to
5089       put the CPU/memory state back to what it would have been if the
5090       instruction had been executed unmodified in its original location.  */
5091
5092 /* NOP instruction (mov r0, r0).  */
5093 #define ARM_NOP                         0xe1a00000
5094
5095 /* Helper for register reads for displaced stepping.  In particular, this
5096    returns the PC as it would be seen by the instruction at its original
5097    location.  */
5098
5099 ULONGEST
5100 displaced_read_reg (struct regcache *regs, CORE_ADDR from, int regno)
5101 {
5102   ULONGEST ret;
5103
5104   if (regno == 15)
5105     {
5106       if (debug_displaced)
5107         fprintf_unfiltered (gdb_stdlog, "displaced: read pc value %.8lx\n",
5108                             (unsigned long) from + 8);
5109       return (ULONGEST) from + 8;  /* Pipeline offset.  */
5110     }
5111   else
5112     {
5113       regcache_cooked_read_unsigned (regs, regno, &ret);
5114       if (debug_displaced)
5115         fprintf_unfiltered (gdb_stdlog, "displaced: read r%d value %.8lx\n",
5116                             regno, (unsigned long) ret);
5117       return ret;
5118     }
5119 }
5120
5121 static int
5122 displaced_in_arm_mode (struct regcache *regs)
5123 {
5124   ULONGEST ps;
5125   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5126
5127   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5128
5129   return (ps & t_bit) == 0;
5130 }
5131
5132 /* Write to the PC as from a branch instruction.  */
5133
5134 static void
5135 branch_write_pc (struct regcache *regs, ULONGEST val)
5136 {
5137   if (displaced_in_arm_mode (regs))
5138     /* Note: If bits 0/1 are set, this branch would be unpredictable for
5139        architecture versions < 6.  */
5140     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5141                                     val & ~(ULONGEST) 0x3);
5142   else
5143     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5144                                     val & ~(ULONGEST) 0x1);
5145 }
5146
5147 /* Write to the PC as from a branch-exchange instruction.  */
5148
5149 static void
5150 bx_write_pc (struct regcache *regs, ULONGEST val)
5151 {
5152   ULONGEST ps;
5153   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5154
5155   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5156
5157   if ((val & 1) == 1)
5158     {
5159       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps | t_bit);
5160       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffe);
5161     }
5162   else if ((val & 2) == 0)
5163     {
5164       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5165       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val);
5166     }
5167   else
5168     {
5169       /* Unpredictable behaviour.  Try to do something sensible (switch to ARM
5170           mode, align dest to 4 bytes).  */
5171       warning (_("Single-stepping BX to non-word-aligned ARM instruction."));
5172       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5173       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffc);
5174     }
5175 }
5176
5177 /* Write to the PC as if from a load instruction.  */
5178
5179 static void
5180 load_write_pc (struct regcache *regs, ULONGEST val)
5181 {
5182   if (DISPLACED_STEPPING_ARCH_VERSION >= 5)
5183     bx_write_pc (regs, val);
5184   else
5185     branch_write_pc (regs, val);
5186 }
5187
5188 /* Write to the PC as if from an ALU instruction.  */
5189
5190 static void
5191 alu_write_pc (struct regcache *regs, ULONGEST val)
5192 {
5193   if (DISPLACED_STEPPING_ARCH_VERSION >= 7 && displaced_in_arm_mode (regs))
5194     bx_write_pc (regs, val);
5195   else
5196     branch_write_pc (regs, val);
5197 }
5198
5199 /* Helper for writing to registers for displaced stepping.  Writing to the PC
5200    has a varying effects depending on the instruction which does the write:
5201    this is controlled by the WRITE_PC argument.  */
5202
5203 void
5204 displaced_write_reg (struct regcache *regs, struct displaced_step_closure *dsc,
5205                      int regno, ULONGEST val, enum pc_write_style write_pc)
5206 {
5207   if (regno == 15)
5208     {
5209       if (debug_displaced)
5210         fprintf_unfiltered (gdb_stdlog, "displaced: writing pc %.8lx\n",
5211                             (unsigned long) val);
5212       switch (write_pc)
5213         {
5214         case BRANCH_WRITE_PC:
5215           branch_write_pc (regs, val);
5216           break;
5217
5218         case BX_WRITE_PC:
5219           bx_write_pc (regs, val);
5220           break;
5221
5222         case LOAD_WRITE_PC:
5223           load_write_pc (regs, val);
5224           break;
5225
5226         case ALU_WRITE_PC:
5227           alu_write_pc (regs, val);
5228           break;
5229
5230         case CANNOT_WRITE_PC:
5231           warning (_("Instruction wrote to PC in an unexpected way when "
5232                      "single-stepping"));
5233           break;
5234
5235         default:
5236           internal_error (__FILE__, __LINE__,
5237                           _("Invalid argument to displaced_write_reg"));
5238         }
5239
5240       dsc->wrote_to_pc = 1;
5241     }
5242   else
5243     {
5244       if (debug_displaced)
5245         fprintf_unfiltered (gdb_stdlog, "displaced: writing r%d value %.8lx\n",
5246                             regno, (unsigned long) val);
5247       regcache_cooked_write_unsigned (regs, regno, val);
5248     }
5249 }
5250
5251 /* This function is used to concisely determine if an instruction INSN
5252    references PC.  Register fields of interest in INSN should have the
5253    corresponding fields of BITMASK set to 0b1111.  The function
5254    returns return 1 if any of these fields in INSN reference the PC
5255    (also 0b1111, r15), else it returns 0.  */
5256
5257 static int
5258 insn_references_pc (uint32_t insn, uint32_t bitmask)
5259 {
5260   uint32_t lowbit = 1;
5261
5262   while (bitmask != 0)
5263     {
5264       uint32_t mask;
5265
5266       for (; lowbit && (bitmask & lowbit) == 0; lowbit <<= 1)
5267         ;
5268
5269       if (!lowbit)
5270         break;
5271
5272       mask = lowbit * 0xf;
5273
5274       if ((insn & mask) == mask)
5275         return 1;
5276
5277       bitmask &= ~mask;
5278     }
5279
5280   return 0;
5281 }
5282
5283 /* The simplest copy function.  Many instructions have the same effect no
5284    matter what address they are executed at: in those cases, use this.  */
5285
5286 static int
5287 copy_unmodified (struct gdbarch *gdbarch, uint32_t insn,
5288                  const char *iname, struct displaced_step_closure *dsc)
5289 {
5290   if (debug_displaced)
5291     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx, "
5292                         "opcode/class '%s' unmodified\n", (unsigned long) insn,
5293                         iname);
5294
5295   dsc->modinsn[0] = insn;
5296
5297   return 0;
5298 }
5299
5300 /* Preload instructions with immediate offset.  */
5301
5302 static void
5303 cleanup_preload (struct gdbarch *gdbarch,
5304                  struct regcache *regs, struct displaced_step_closure *dsc)
5305 {
5306   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5307   if (!dsc->u.preload.immed)
5308     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5309 }
5310
5311 static int
5312 copy_preload (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
5313               struct displaced_step_closure *dsc)
5314 {
5315   unsigned int rn = bits (insn, 16, 19);
5316   ULONGEST rn_val;
5317   CORE_ADDR from = dsc->insn_addr;
5318
5319   if (!insn_references_pc (insn, 0x000f0000ul))
5320     return copy_unmodified (gdbarch, insn, "preload", dsc);
5321
5322   if (debug_displaced)
5323     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5324                         (unsigned long) insn);
5325
5326   /* Preload instructions:
5327
5328      {pli/pld} [rn, #+/-imm]
5329      ->
5330      {pli/pld} [r0, #+/-imm].  */
5331
5332   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5333   rn_val = displaced_read_reg (regs, from, rn);
5334   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5335
5336   dsc->u.preload.immed = 1;
5337
5338   dsc->modinsn[0] = insn & 0xfff0ffff;
5339
5340   dsc->cleanup = &cleanup_preload;
5341
5342   return 0;
5343 }
5344
5345 /* Preload instructions with register offset.  */
5346
5347 static int
5348 copy_preload_reg (struct gdbarch *gdbarch, uint32_t insn,
5349                   struct regcache *regs,
5350                   struct displaced_step_closure *dsc)
5351 {
5352   unsigned int rn = bits (insn, 16, 19);
5353   unsigned int rm = bits (insn, 0, 3);
5354   ULONGEST rn_val, rm_val;
5355   CORE_ADDR from = dsc->insn_addr;
5356
5357   if (!insn_references_pc (insn, 0x000f000ful))
5358     return copy_unmodified (gdbarch, insn, "preload reg", dsc);
5359
5360   if (debug_displaced)
5361     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5362                         (unsigned long) insn);
5363
5364   /* Preload register-offset instructions:
5365
5366      {pli/pld} [rn, rm {, shift}]
5367      ->
5368      {pli/pld} [r0, r1 {, shift}].  */
5369
5370   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5371   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
5372   rn_val = displaced_read_reg (regs, from, rn);
5373   rm_val = displaced_read_reg (regs, from, rm);
5374   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5375   displaced_write_reg (regs, dsc, 1, rm_val, CANNOT_WRITE_PC);
5376
5377   dsc->u.preload.immed = 0;
5378
5379   dsc->modinsn[0] = (insn & 0xfff0fff0) | 0x1;
5380
5381   dsc->cleanup = &cleanup_preload;
5382
5383   return 0;
5384 }
5385
5386 /* Copy/cleanup coprocessor load and store instructions.  */
5387
5388 static void
5389 cleanup_copro_load_store (struct gdbarch *gdbarch,
5390                           struct regcache *regs,
5391                           struct displaced_step_closure *dsc)
5392 {
5393   ULONGEST rn_val = displaced_read_reg (regs, dsc->insn_addr, 0);
5394
5395   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5396
5397   if (dsc->u.ldst.writeback)
5398     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, LOAD_WRITE_PC);
5399 }
5400
5401 static int
5402 copy_copro_load_store (struct gdbarch *gdbarch, uint32_t insn,
5403                        struct regcache *regs,
5404                        struct displaced_step_closure *dsc)
5405 {
5406   unsigned int rn = bits (insn, 16, 19);
5407   ULONGEST rn_val;
5408   CORE_ADDR from = dsc->insn_addr;
5409
5410   if (!insn_references_pc (insn, 0x000f0000ul))
5411     return copy_unmodified (gdbarch, insn, "copro load/store", dsc);
5412
5413   if (debug_displaced)
5414     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
5415                         "load/store insn %.8lx\n", (unsigned long) insn);
5416
5417   /* Coprocessor load/store instructions:
5418
5419      {stc/stc2} [<Rn>, #+/-imm]  (and other immediate addressing modes)
5420      ->
5421      {stc/stc2} [r0, #+/-imm].
5422
5423      ldc/ldc2 are handled identically.  */
5424
5425   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5426   rn_val = displaced_read_reg (regs, from, rn);
5427   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5428
5429   dsc->u.ldst.writeback = bit (insn, 25);
5430   dsc->u.ldst.rn = rn;
5431
5432   dsc->modinsn[0] = insn & 0xfff0ffff;
5433
5434   dsc->cleanup = &cleanup_copro_load_store;
5435
5436   return 0;
5437 }
5438
5439 /* Clean up branch instructions (actually perform the branch, by setting
5440    PC).  */
5441
5442 static void
5443 cleanup_branch (struct gdbarch *gdbarch, struct regcache *regs,
5444                 struct displaced_step_closure *dsc)
5445 {
5446   ULONGEST from = dsc->insn_addr;
5447   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
5448   int branch_taken = condition_true (dsc->u.branch.cond, status);
5449   enum pc_write_style write_pc = dsc->u.branch.exchange
5450                                  ? BX_WRITE_PC : BRANCH_WRITE_PC;
5451
5452   if (!branch_taken)
5453     return;
5454
5455   if (dsc->u.branch.link)
5456     {
5457       ULONGEST pc = displaced_read_reg (regs, from, 15);
5458       displaced_write_reg (regs, dsc, 14, pc - 4, CANNOT_WRITE_PC);
5459     }
5460
5461   displaced_write_reg (regs, dsc, 15, dsc->u.branch.dest, write_pc);
5462 }
5463
5464 /* Copy B/BL/BLX instructions with immediate destinations.  */
5465
5466 static int
5467 copy_b_bl_blx (struct gdbarch *gdbarch, uint32_t insn,
5468                struct regcache *regs, struct displaced_step_closure *dsc)
5469 {
5470   unsigned int cond = bits (insn, 28, 31);
5471   int exchange = (cond == 0xf);
5472   int link = exchange || bit (insn, 24);
5473   CORE_ADDR from = dsc->insn_addr;
5474   long offset;
5475
5476   if (debug_displaced)
5477     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s immediate insn "
5478                         "%.8lx\n", (exchange) ? "blx" : (link) ? "bl" : "b",
5479                         (unsigned long) insn);
5480
5481   /* Implement "BL<cond> <label>" as:
5482
5483      Preparation: cond <- instruction condition
5484      Insn: mov r0, r0  (nop)
5485      Cleanup: if (condition true) { r14 <- pc; pc <- label }.
5486
5487      B<cond> similar, but don't set r14 in cleanup.  */
5488
5489   if (exchange)
5490     /* For BLX, set bit 0 of the destination.  The cleanup_branch function will
5491        then arrange the switch into Thumb mode.  */
5492     offset = (bits (insn, 0, 23) << 2) | (bit (insn, 24) << 1) | 1;
5493   else
5494     offset = bits (insn, 0, 23) << 2;
5495
5496   if (bit (offset, 25))
5497     offset = offset | ~0x3ffffff;
5498
5499   dsc->u.branch.cond = cond;
5500   dsc->u.branch.link = link;
5501   dsc->u.branch.exchange = exchange;
5502   dsc->u.branch.dest = from + 8 + offset;
5503
5504   dsc->modinsn[0] = ARM_NOP;
5505
5506   dsc->cleanup = &cleanup_branch;
5507
5508   return 0;
5509 }
5510
5511 /* Copy BX/BLX with register-specified destinations.  */
5512
5513 static int
5514 copy_bx_blx_reg (struct gdbarch *gdbarch, uint32_t insn,
5515                  struct regcache *regs, struct displaced_step_closure *dsc)
5516 {
5517   unsigned int cond = bits (insn, 28, 31);
5518   /* BX:  x12xxx1x
5519      BLX: x12xxx3x.  */
5520   int link = bit (insn, 5);
5521   unsigned int rm = bits (insn, 0, 3);
5522   CORE_ADDR from = dsc->insn_addr;
5523
5524   if (debug_displaced)
5525     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s register insn "
5526                         "%.8lx\n", (link) ? "blx" : "bx",
5527                         (unsigned long) insn);
5528
5529   /* Implement {BX,BLX}<cond> <reg>" as:
5530
5531      Preparation: cond <- instruction condition
5532      Insn: mov r0, r0 (nop)
5533      Cleanup: if (condition true) { r14 <- pc; pc <- dest; }.
5534
5535      Don't set r14 in cleanup for BX.  */
5536
5537   dsc->u.branch.dest = displaced_read_reg (regs, from, rm);
5538
5539   dsc->u.branch.cond = cond;
5540   dsc->u.branch.link = link;
5541   dsc->u.branch.exchange = 1;
5542
5543   dsc->modinsn[0] = ARM_NOP;
5544
5545   dsc->cleanup = &cleanup_branch;
5546
5547   return 0;
5548 }
5549
5550 /* Copy/cleanup arithmetic/logic instruction with immediate RHS.  */
5551
5552 static void
5553 cleanup_alu_imm (struct gdbarch *gdbarch,
5554                  struct regcache *regs, struct displaced_step_closure *dsc)
5555 {
5556   ULONGEST rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
5557   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5558   displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5559   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
5560 }
5561
5562 static int
5563 copy_alu_imm (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
5564               struct displaced_step_closure *dsc)
5565 {
5566   unsigned int rn = bits (insn, 16, 19);
5567   unsigned int rd = bits (insn, 12, 15);
5568   unsigned int op = bits (insn, 21, 24);
5569   int is_mov = (op == 0xd);
5570   ULONGEST rd_val, rn_val;
5571   CORE_ADDR from = dsc->insn_addr;
5572
5573   if (!insn_references_pc (insn, 0x000ff000ul))
5574     return copy_unmodified (gdbarch, insn, "ALU immediate", dsc);
5575
5576   if (debug_displaced)
5577     fprintf_unfiltered (gdb_stdlog, "displaced: copying immediate %s insn "
5578                         "%.8lx\n", is_mov ? "move" : "ALU",
5579                         (unsigned long) insn);
5580
5581   /* Instruction is of form:
5582
5583      <op><cond> rd, [rn,] #imm
5584
5585      Rewrite as:
5586
5587      Preparation: tmp1, tmp2 <- r0, r1;
5588                   r0, r1 <- rd, rn
5589      Insn: <op><cond> r0, r1, #imm
5590      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
5591   */
5592
5593   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5594   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
5595   rn_val = displaced_read_reg (regs, from, rn);
5596   rd_val = displaced_read_reg (regs, from, rd);
5597   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
5598   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
5599   dsc->rd = rd;
5600
5601   if (is_mov)
5602     dsc->modinsn[0] = insn & 0xfff00fff;
5603   else
5604     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x10000;
5605
5606   dsc->cleanup = &cleanup_alu_imm;
5607
5608   return 0;
5609 }
5610
5611 /* Copy/cleanup arithmetic/logic insns with register RHS.  */
5612
5613 static void
5614 cleanup_alu_reg (struct gdbarch *gdbarch,
5615                  struct regcache *regs, struct displaced_step_closure *dsc)
5616 {
5617   ULONGEST rd_val;
5618   int i;
5619
5620   rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
5621
5622   for (i = 0; i < 3; i++)
5623     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
5624
5625   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
5626 }
5627
5628 static int
5629 copy_alu_reg (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
5630               struct displaced_step_closure *dsc)
5631 {
5632   unsigned int rn = bits (insn, 16, 19);
5633   unsigned int rm = bits (insn, 0, 3);
5634   unsigned int rd = bits (insn, 12, 15);
5635   unsigned int op = bits (insn, 21, 24);
5636   int is_mov = (op == 0xd);
5637   ULONGEST rd_val, rn_val, rm_val;
5638   CORE_ADDR from = dsc->insn_addr;
5639
5640   if (!insn_references_pc (insn, 0x000ff00ful))
5641     return copy_unmodified (gdbarch, insn, "ALU reg", dsc);
5642
5643   if (debug_displaced)
5644     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.8lx\n",
5645                         is_mov ? "move" : "ALU", (unsigned long) insn);
5646
5647   /* Instruction is of form:
5648
5649      <op><cond> rd, [rn,] rm [, <shift>]
5650
5651      Rewrite as:
5652
5653      Preparation: tmp1, tmp2, tmp3 <- r0, r1, r2;
5654                   r0, r1, r2 <- rd, rn, rm
5655      Insn: <op><cond> r0, r1, r2 [, <shift>]
5656      Cleanup: rd <- r0; r0, r1, r2 <- tmp1, tmp2, tmp3
5657   */
5658
5659   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5660   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
5661   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
5662   rd_val = displaced_read_reg (regs, from, rd);
5663   rn_val = displaced_read_reg (regs, from, rn);
5664   rm_val = displaced_read_reg (regs, from, rm);
5665   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
5666   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
5667   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
5668   dsc->rd = rd;
5669
5670   if (is_mov)
5671     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x2;
5672   else
5673     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x10002;
5674
5675   dsc->cleanup = &cleanup_alu_reg;
5676
5677   return 0;
5678 }
5679
5680 /* Cleanup/copy arithmetic/logic insns with shifted register RHS.  */
5681
5682 static void
5683 cleanup_alu_shifted_reg (struct gdbarch *gdbarch,
5684                          struct regcache *regs,
5685                          struct displaced_step_closure *dsc)
5686 {
5687   ULONGEST rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
5688   int i;
5689
5690   for (i = 0; i < 4; i++)
5691     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
5692
5693   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
5694 }
5695
5696 static int
5697 copy_alu_shifted_reg (struct gdbarch *gdbarch, uint32_t insn,
5698                       struct regcache *regs,
5699                       struct displaced_step_closure *dsc)
5700 {
5701   unsigned int rn = bits (insn, 16, 19);
5702   unsigned int rm = bits (insn, 0, 3);
5703   unsigned int rd = bits (insn, 12, 15);
5704   unsigned int rs = bits (insn, 8, 11);
5705   unsigned int op = bits (insn, 21, 24);
5706   int is_mov = (op == 0xd), i;
5707   ULONGEST rd_val, rn_val, rm_val, rs_val;
5708   CORE_ADDR from = dsc->insn_addr;
5709
5710   if (!insn_references_pc (insn, 0x000fff0ful))
5711     return copy_unmodified (gdbarch, insn, "ALU shifted reg", dsc);
5712
5713   if (debug_displaced)
5714     fprintf_unfiltered (gdb_stdlog, "displaced: copying shifted reg %s insn "
5715                         "%.8lx\n", is_mov ? "move" : "ALU",
5716                         (unsigned long) insn);
5717
5718   /* Instruction is of form:
5719
5720      <op><cond> rd, [rn,] rm, <shift> rs
5721
5722      Rewrite as:
5723
5724      Preparation: tmp1, tmp2, tmp3, tmp4 <- r0, r1, r2, r3
5725                   r0, r1, r2, r3 <- rd, rn, rm, rs
5726      Insn: <op><cond> r0, r1, r2, <shift> r3
5727      Cleanup: tmp5 <- r0
5728               r0, r1, r2, r3 <- tmp1, tmp2, tmp3, tmp4
5729               rd <- tmp5
5730   */
5731
5732   for (i = 0; i < 4; i++)
5733     dsc->tmp[i] = displaced_read_reg (regs, from, i);
5734
5735   rd_val = displaced_read_reg (regs, from, rd);
5736   rn_val = displaced_read_reg (regs, from, rn);
5737   rm_val = displaced_read_reg (regs, from, rm);
5738   rs_val = displaced_read_reg (regs, from, rs);
5739   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
5740   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
5741   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
5742   displaced_write_reg (regs, dsc, 3, rs_val, CANNOT_WRITE_PC);
5743   dsc->rd = rd;
5744
5745   if (is_mov)
5746     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x302;
5747   else
5748     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x10302;
5749
5750   dsc->cleanup = &cleanup_alu_shifted_reg;
5751
5752   return 0;
5753 }
5754
5755 /* Clean up load instructions.  */
5756
5757 static void
5758 cleanup_load (struct gdbarch *gdbarch, struct regcache *regs,
5759               struct displaced_step_closure *dsc)
5760 {
5761   ULONGEST rt_val, rt_val2 = 0, rn_val;
5762   CORE_ADDR from = dsc->insn_addr;
5763
5764   rt_val = displaced_read_reg (regs, from, 0);
5765   if (dsc->u.ldst.xfersize == 8)
5766     rt_val2 = displaced_read_reg (regs, from, 1);
5767   rn_val = displaced_read_reg (regs, from, 2);
5768
5769   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5770   if (dsc->u.ldst.xfersize > 4)
5771     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5772   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
5773   if (!dsc->u.ldst.immed)
5774     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
5775
5776   /* Handle register writeback.  */
5777   if (dsc->u.ldst.writeback)
5778     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
5779   /* Put result in right place.  */
5780   displaced_write_reg (regs, dsc, dsc->rd, rt_val, LOAD_WRITE_PC);
5781   if (dsc->u.ldst.xfersize == 8)
5782     displaced_write_reg (regs, dsc, dsc->rd + 1, rt_val2, LOAD_WRITE_PC);
5783 }
5784
5785 /* Clean up store instructions.  */
5786
5787 static void
5788 cleanup_store (struct gdbarch *gdbarch, struct regcache *regs,
5789                struct displaced_step_closure *dsc)
5790 {
5791   CORE_ADDR from = dsc->insn_addr;
5792   ULONGEST rn_val = displaced_read_reg (regs, from, 2);
5793
5794   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5795   if (dsc->u.ldst.xfersize > 4)
5796     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5797   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
5798   if (!dsc->u.ldst.immed)
5799     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
5800   if (!dsc->u.ldst.restore_r4)
5801     displaced_write_reg (regs, dsc, 4, dsc->tmp[4], CANNOT_WRITE_PC);
5802
5803   /* Writeback.  */
5804   if (dsc->u.ldst.writeback)
5805     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
5806 }
5807
5808 /* Copy "extra" load/store instructions.  These are halfword/doubleword
5809    transfers, which have a different encoding to byte/word transfers.  */
5810
5811 static int
5812 copy_extra_ld_st (struct gdbarch *gdbarch, uint32_t insn, int unpriveleged,
5813                   struct regcache *regs, struct displaced_step_closure *dsc)
5814 {
5815   unsigned int op1 = bits (insn, 20, 24);
5816   unsigned int op2 = bits (insn, 5, 6);
5817   unsigned int rt = bits (insn, 12, 15);
5818   unsigned int rn = bits (insn, 16, 19);
5819   unsigned int rm = bits (insn, 0, 3);
5820   char load[12]     = {0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1};
5821   char bytesize[12] = {2, 2, 2, 2, 8, 1, 8, 1, 8, 2, 8, 2};
5822   int immed = (op1 & 0x4) != 0;
5823   int opcode;
5824   ULONGEST rt_val, rt_val2 = 0, rn_val, rm_val = 0;
5825   CORE_ADDR from = dsc->insn_addr;
5826
5827   if (!insn_references_pc (insn, 0x000ff00ful))
5828     return copy_unmodified (gdbarch, insn, "extra load/store", dsc);
5829
5830   if (debug_displaced)
5831     fprintf_unfiltered (gdb_stdlog, "displaced: copying %sextra load/store "
5832                         "insn %.8lx\n", unpriveleged ? "unpriveleged " : "",
5833                         (unsigned long) insn);
5834
5835   opcode = ((op2 << 2) | (op1 & 0x1) | ((op1 & 0x4) >> 1)) - 4;
5836
5837   if (opcode < 0)
5838     internal_error (__FILE__, __LINE__,
5839                     _("copy_extra_ld_st: instruction decode error"));
5840
5841   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5842   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
5843   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
5844   if (!immed)
5845     dsc->tmp[3] = displaced_read_reg (regs, from, 3);
5846
5847   rt_val = displaced_read_reg (regs, from, rt);
5848   if (bytesize[opcode] == 8)
5849     rt_val2 = displaced_read_reg (regs, from, rt + 1);
5850   rn_val = displaced_read_reg (regs, from, rn);
5851   if (!immed)
5852     rm_val = displaced_read_reg (regs, from, rm);
5853
5854   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
5855   if (bytesize[opcode] == 8)
5856     displaced_write_reg (regs, dsc, 1, rt_val2, CANNOT_WRITE_PC);
5857   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
5858   if (!immed)
5859     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
5860
5861   dsc->rd = rt;
5862   dsc->u.ldst.xfersize = bytesize[opcode];
5863   dsc->u.ldst.rn = rn;
5864   dsc->u.ldst.immed = immed;
5865   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
5866   dsc->u.ldst.restore_r4 = 0;
5867
5868   if (immed)
5869     /* {ldr,str}<width><cond> rt, [rt2,] [rn, #imm]
5870         ->
5871        {ldr,str}<width><cond> r0, [r1,] [r2, #imm].  */
5872     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
5873   else
5874     /* {ldr,str}<width><cond> rt, [rt2,] [rn, +/-rm]
5875         ->
5876        {ldr,str}<width><cond> r0, [r1,] [r2, +/-r3].  */
5877     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
5878
5879   dsc->cleanup = load[opcode] ? &cleanup_load : &cleanup_store;
5880
5881   return 0;
5882 }
5883
5884 /* Copy byte/word loads and stores.  */
5885
5886 static int
5887 copy_ldr_str_ldrb_strb (struct gdbarch *gdbarch, uint32_t insn,
5888                         struct regcache *regs,
5889                         struct displaced_step_closure *dsc, int load, int byte,
5890                         int usermode)
5891 {
5892   int immed = !bit (insn, 25);
5893   unsigned int rt = bits (insn, 12, 15);
5894   unsigned int rn = bits (insn, 16, 19);
5895   unsigned int rm = bits (insn, 0, 3);  /* Only valid if !immed.  */
5896   ULONGEST rt_val, rn_val, rm_val = 0;
5897   CORE_ADDR from = dsc->insn_addr;
5898
5899   if (!insn_references_pc (insn, 0x000ff00ful))
5900     return copy_unmodified (gdbarch, insn, "load/store", dsc);
5901
5902   if (debug_displaced)
5903     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s%s insn %.8lx\n",
5904                         load ? (byte ? "ldrb" : "ldr")
5905                              : (byte ? "strb" : "str"), usermode ? "t" : "",
5906                         (unsigned long) insn);
5907
5908   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
5909   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
5910   if (!immed)
5911     dsc->tmp[3] = displaced_read_reg (regs, from, 3);
5912   if (!load)
5913     dsc->tmp[4] = displaced_read_reg (regs, from, 4);
5914
5915   rt_val = displaced_read_reg (regs, from, rt);
5916   rn_val = displaced_read_reg (regs, from, rn);
5917   if (!immed)
5918     rm_val = displaced_read_reg (regs, from, rm);
5919
5920   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
5921   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
5922   if (!immed)
5923     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
5924
5925   dsc->rd = rt;
5926   dsc->u.ldst.xfersize = byte ? 1 : 4;
5927   dsc->u.ldst.rn = rn;
5928   dsc->u.ldst.immed = immed;
5929   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
5930
5931   /* To write PC we can do:
5932
5933      Before this sequence of instructions:
5934      r0 is the PC value got from displaced_read_reg, so r0 = from + 8;
5935      r2 is the Rn value got from dispalced_read_reg.
5936
5937      Insn1: push {pc} Write address of STR instruction + offset on stack
5938      Insn2: pop  {r4} Read it back from stack, r4 = addr(Insn1) + offset
5939      Insn3: sub r4, r4, pc   r4 = addr(Insn1) + offset - pc
5940                                 = addr(Insn1) + offset - addr(Insn3) - 8
5941                                 = offset - 16
5942      Insn4: add r4, r4, #8   r4 = offset - 8
5943      Insn5: add r0, r0, r4   r0 = from + 8 + offset - 8
5944                                 = from + offset
5945      Insn6: str r0, [r2, #imm] (or str r0, [r2, r3])
5946
5947      Otherwise we don't know what value to write for PC, since the offset is
5948      architecture-dependent (sometimes PC+8, sometimes PC+12).  More details
5949      of this can be found in Section "Saving from r15" in
5950      http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204g/Cihbjifh.html */
5951
5952   if (load || rt != 15)
5953     {
5954       dsc->u.ldst.restore_r4 = 0;
5955
5956       if (immed)
5957         /* {ldr,str}[b]<cond> rt, [rn, #imm], etc.
5958            ->
5959            {ldr,str}[b]<cond> r0, [r2, #imm].  */
5960         dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
5961       else
5962         /* {ldr,str}[b]<cond> rt, [rn, rm], etc.
5963            ->
5964            {ldr,str}[b]<cond> r0, [r2, r3].  */
5965         dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
5966     }
5967   else
5968     {
5969       /* We need to use r4 as scratch.  Make sure it's restored afterwards.  */
5970       dsc->u.ldst.restore_r4 = 1;
5971       dsc->modinsn[0] = 0xe92d8000;  /* push {pc} */
5972       dsc->modinsn[1] = 0xe8bd0010;  /* pop  {r4} */
5973       dsc->modinsn[2] = 0xe044400f;  /* sub r4, r4, pc.  */
5974       dsc->modinsn[3] = 0xe2844008;  /* add r4, r4, #8.  */
5975       dsc->modinsn[4] = 0xe0800004;  /* add r0, r0, r4.  */
5976
5977       /* As above.  */
5978       if (immed)
5979         dsc->modinsn[5] = (insn & 0xfff00fff) | 0x20000;
5980       else
5981         dsc->modinsn[5] = (insn & 0xfff00ff0) | 0x20003;
5982
5983       dsc->modinsn[6] = 0x0;  /* breakpoint location.  */
5984       dsc->modinsn[7] = 0x0;  /* scratch space.  */
5985
5986       dsc->numinsns = 6;
5987     }
5988
5989   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
5990
5991   return 0;
5992 }
5993
5994 /* Cleanup LDM instructions with fully-populated register list.  This is an
5995    unfortunate corner case: it's impossible to implement correctly by modifying
5996    the instruction.  The issue is as follows: we have an instruction,
5997
5998    ldm rN, {r0-r15}
5999
6000    which we must rewrite to avoid loading PC.  A possible solution would be to
6001    do the load in two halves, something like (with suitable cleanup
6002    afterwards):
6003
6004    mov r8, rN
6005    ldm[id][ab] r8!, {r0-r7}
6006    str r7, <temp>
6007    ldm[id][ab] r8, {r7-r14}
6008    <bkpt>
6009
6010    but at present there's no suitable place for <temp>, since the scratch space
6011    is overwritten before the cleanup routine is called.  For now, we simply
6012    emulate the instruction.  */
6013
6014 static void
6015 cleanup_block_load_all (struct gdbarch *gdbarch, struct regcache *regs,
6016                         struct displaced_step_closure *dsc)
6017 {
6018   ULONGEST from = dsc->insn_addr;
6019   int inc = dsc->u.block.increment;
6020   int bump_before = dsc->u.block.before ? (inc ? 4 : -4) : 0;
6021   int bump_after = dsc->u.block.before ? 0 : (inc ? 4 : -4);
6022   uint32_t regmask = dsc->u.block.regmask;
6023   int regno = inc ? 0 : 15;
6024   CORE_ADDR xfer_addr = dsc->u.block.xfer_addr;
6025   int exception_return = dsc->u.block.load && dsc->u.block.user
6026                          && (regmask & 0x8000) != 0;
6027   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
6028   int do_transfer = condition_true (dsc->u.block.cond, status);
6029   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6030
6031   if (!do_transfer)
6032     return;
6033
6034   /* If the instruction is ldm rN, {...pc}^, I don't think there's anything
6035      sensible we can do here.  Complain loudly.  */
6036   if (exception_return)
6037     error (_("Cannot single-step exception return"));
6038
6039   /* We don't handle any stores here for now.  */
6040   gdb_assert (dsc->u.block.load != 0);
6041
6042   if (debug_displaced)
6043     fprintf_unfiltered (gdb_stdlog, "displaced: emulating block transfer: "
6044                         "%s %s %s\n", dsc->u.block.load ? "ldm" : "stm",
6045                         dsc->u.block.increment ? "inc" : "dec",
6046                         dsc->u.block.before ? "before" : "after");
6047
6048   while (regmask)
6049     {
6050       uint32_t memword;
6051
6052       if (inc)
6053         while (regno <= 15 && (regmask & (1 << regno)) == 0)
6054           regno++;
6055       else
6056         while (regno >= 0 && (regmask & (1 << regno)) == 0)
6057           regno--;
6058
6059       xfer_addr += bump_before;
6060
6061       memword = read_memory_unsigned_integer (xfer_addr, 4, byte_order);
6062       displaced_write_reg (regs, dsc, regno, memword, LOAD_WRITE_PC);
6063
6064       xfer_addr += bump_after;
6065
6066       regmask &= ~(1 << regno);
6067     }
6068
6069   if (dsc->u.block.writeback)
6070     displaced_write_reg (regs, dsc, dsc->u.block.rn, xfer_addr,
6071                          CANNOT_WRITE_PC);
6072 }
6073
6074 /* Clean up an STM which included the PC in the register list.  */
6075
6076 static void
6077 cleanup_block_store_pc (struct gdbarch *gdbarch, struct regcache *regs,
6078                         struct displaced_step_closure *dsc)
6079 {
6080   ULONGEST from = dsc->insn_addr;
6081   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
6082   int store_executed = condition_true (dsc->u.block.cond, status);
6083   CORE_ADDR pc_stored_at, transferred_regs = bitcount (dsc->u.block.regmask);
6084   CORE_ADDR stm_insn_addr;
6085   uint32_t pc_val;
6086   long offset;
6087   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6088
6089   /* If condition code fails, there's nothing else to do.  */
6090   if (!store_executed)
6091     return;
6092
6093   if (dsc->u.block.increment)
6094     {
6095       pc_stored_at = dsc->u.block.xfer_addr + 4 * transferred_regs;
6096
6097       if (dsc->u.block.before)
6098          pc_stored_at += 4;
6099     }
6100   else
6101     {
6102       pc_stored_at = dsc->u.block.xfer_addr;
6103
6104       if (dsc->u.block.before)
6105          pc_stored_at -= 4;
6106     }
6107
6108   pc_val = read_memory_unsigned_integer (pc_stored_at, 4, byte_order);
6109   stm_insn_addr = dsc->scratch_base;
6110   offset = pc_val - stm_insn_addr;
6111
6112   if (debug_displaced)
6113     fprintf_unfiltered (gdb_stdlog, "displaced: detected PC offset %.8lx for "
6114                         "STM instruction\n", offset);
6115
6116   /* Rewrite the stored PC to the proper value for the non-displaced original
6117      instruction.  */
6118   write_memory_unsigned_integer (pc_stored_at, 4, byte_order,
6119                                  dsc->insn_addr + offset);
6120 }
6121
6122 /* Clean up an LDM which includes the PC in the register list.  We clumped all
6123    the registers in the transferred list into a contiguous range r0...rX (to
6124    avoid loading PC directly and losing control of the debugged program), so we
6125    must undo that here.  */
6126
6127 static void
6128 cleanup_block_load_pc (struct gdbarch *gdbarch,
6129                        struct regcache *regs,
6130                        struct displaced_step_closure *dsc)
6131 {
6132   ULONGEST from = dsc->insn_addr;
6133   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
6134   int load_executed = condition_true (dsc->u.block.cond, status), i;
6135   unsigned int mask = dsc->u.block.regmask, write_reg = 15;
6136   unsigned int regs_loaded = bitcount (mask);
6137   unsigned int num_to_shuffle = regs_loaded, clobbered;
6138
6139   /* The method employed here will fail if the register list is fully populated
6140      (we need to avoid loading PC directly).  */
6141   gdb_assert (num_to_shuffle < 16);
6142
6143   if (!load_executed)
6144     return;
6145
6146   clobbered = (1 << num_to_shuffle) - 1;
6147
6148   while (num_to_shuffle > 0)
6149     {
6150       if ((mask & (1 << write_reg)) != 0)
6151         {
6152           unsigned int read_reg = num_to_shuffle - 1;
6153
6154           if (read_reg != write_reg)
6155             {
6156               ULONGEST rval = displaced_read_reg (regs, from, read_reg);
6157               displaced_write_reg (regs, dsc, write_reg, rval, LOAD_WRITE_PC);
6158               if (debug_displaced)
6159                 fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: move "
6160                                     "loaded register r%d to r%d\n"), read_reg,
6161                                     write_reg);
6162             }
6163           else if (debug_displaced)
6164             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: register "
6165                                 "r%d already in the right place\n"),
6166                                 write_reg);
6167
6168           clobbered &= ~(1 << write_reg);
6169
6170           num_to_shuffle--;
6171         }
6172
6173       write_reg--;
6174     }
6175
6176   /* Restore any registers we scribbled over.  */
6177   for (write_reg = 0; clobbered != 0; write_reg++)
6178     {
6179       if ((clobbered & (1 << write_reg)) != 0)
6180         {
6181           displaced_write_reg (regs, dsc, write_reg, dsc->tmp[write_reg],
6182                                CANNOT_WRITE_PC);
6183           if (debug_displaced)
6184             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: restored "
6185                                 "clobbered register r%d\n"), write_reg);
6186           clobbered &= ~(1 << write_reg);
6187         }
6188     }
6189
6190   /* Perform register writeback manually.  */
6191   if (dsc->u.block.writeback)
6192     {
6193       ULONGEST new_rn_val = dsc->u.block.xfer_addr;
6194
6195       if (dsc->u.block.increment)
6196         new_rn_val += regs_loaded * 4;
6197       else
6198         new_rn_val -= regs_loaded * 4;
6199
6200       displaced_write_reg (regs, dsc, dsc->u.block.rn, new_rn_val,
6201                            CANNOT_WRITE_PC);
6202     }
6203 }
6204
6205 /* Handle ldm/stm, apart from some tricky cases which are unlikely to occur
6206    in user-level code (in particular exception return, ldm rn, {...pc}^).  */
6207
6208 static int
6209 copy_block_xfer (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6210                  struct displaced_step_closure *dsc)
6211 {
6212   int load = bit (insn, 20);
6213   int user = bit (insn, 22);
6214   int increment = bit (insn, 23);
6215   int before = bit (insn, 24);
6216   int writeback = bit (insn, 21);
6217   int rn = bits (insn, 16, 19);
6218   CORE_ADDR from = dsc->insn_addr;
6219
6220   /* Block transfers which don't mention PC can be run directly
6221      out-of-line.  */
6222   if (rn != 15 && (insn & 0x8000) == 0)
6223     return copy_unmodified (gdbarch, insn, "ldm/stm", dsc);
6224
6225   if (rn == 15)
6226     {
6227       warning (_("displaced: Unpredictable LDM or STM with "
6228                  "base register r15"));
6229       return copy_unmodified (gdbarch, insn, "unpredictable ldm/stm", dsc);
6230     }
6231
6232   if (debug_displaced)
6233     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
6234                         "%.8lx\n", (unsigned long) insn);
6235
6236   dsc->u.block.xfer_addr = displaced_read_reg (regs, from, rn);
6237   dsc->u.block.rn = rn;
6238
6239   dsc->u.block.load = load;
6240   dsc->u.block.user = user;
6241   dsc->u.block.increment = increment;
6242   dsc->u.block.before = before;
6243   dsc->u.block.writeback = writeback;
6244   dsc->u.block.cond = bits (insn, 28, 31);
6245
6246   dsc->u.block.regmask = insn & 0xffff;
6247
6248   if (load)
6249     {
6250       if ((insn & 0xffff) == 0xffff)
6251         {
6252           /* LDM with a fully-populated register list.  This case is
6253              particularly tricky.  Implement for now by fully emulating the
6254              instruction (which might not behave perfectly in all cases, but
6255              these instructions should be rare enough for that not to matter
6256              too much).  */
6257           dsc->modinsn[0] = ARM_NOP;
6258
6259           dsc->cleanup = &cleanup_block_load_all;
6260         }
6261       else
6262         {
6263           /* LDM of a list of registers which includes PC.  Implement by
6264              rewriting the list of registers to be transferred into a
6265              contiguous chunk r0...rX before doing the transfer, then shuffling
6266              registers into the correct places in the cleanup routine.  */
6267           unsigned int regmask = insn & 0xffff;
6268           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
6269           unsigned int to = 0, from = 0, i, new_rn;
6270
6271           for (i = 0; i < num_in_list; i++)
6272             dsc->tmp[i] = displaced_read_reg (regs, from, i);
6273
6274           /* Writeback makes things complicated.  We need to avoid clobbering
6275              the base register with one of the registers in our modified
6276              register list, but just using a different register can't work in
6277              all cases, e.g.:
6278
6279                ldm r14!, {r0-r13,pc}
6280
6281              which would need to be rewritten as:
6282
6283                ldm rN!, {r0-r14}
6284
6285              but that can't work, because there's no free register for N.
6286
6287              Solve this by turning off the writeback bit, and emulating
6288              writeback manually in the cleanup routine.  */
6289
6290           if (writeback)
6291             insn &= ~(1 << 21);
6292
6293           new_regmask = (1 << num_in_list) - 1;
6294
6295           if (debug_displaced)
6296             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
6297                                 "{..., pc}: original reg list %.4x, modified "
6298                                 "list %.4x\n"), rn, writeback ? "!" : "",
6299                                 (int) insn & 0xffff, new_regmask);
6300
6301           dsc->modinsn[0] = (insn & ~0xffff) | (new_regmask & 0xffff);
6302
6303           dsc->cleanup = &cleanup_block_load_pc;
6304         }
6305     }
6306   else
6307     {
6308       /* STM of a list of registers which includes PC.  Run the instruction
6309          as-is, but out of line: this will store the wrong value for the PC,
6310          so we must manually fix up the memory in the cleanup routine.
6311          Doing things this way has the advantage that we can auto-detect
6312          the offset of the PC write (which is architecture-dependent) in
6313          the cleanup routine.  */
6314       dsc->modinsn[0] = insn;
6315
6316       dsc->cleanup = &cleanup_block_store_pc;
6317     }
6318
6319   return 0;
6320 }
6321
6322 /* Cleanup/copy SVC (SWI) instructions.  These two functions are overridden
6323    for Linux, where some SVC instructions must be treated specially.  */
6324
6325 static void
6326 cleanup_svc (struct gdbarch *gdbarch, struct regcache *regs,
6327              struct displaced_step_closure *dsc)
6328 {
6329   CORE_ADDR from = dsc->insn_addr;
6330   CORE_ADDR resume_addr = from + 4;
6331
6332   if (debug_displaced)
6333     fprintf_unfiltered (gdb_stdlog, "displaced: cleanup for svc, resume at "
6334                         "%.8lx\n", (unsigned long) resume_addr);
6335
6336   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, resume_addr, BRANCH_WRITE_PC);
6337 }
6338
6339 static int
6340 copy_svc (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
6341           struct regcache *regs, struct displaced_step_closure *dsc)
6342 {
6343   CORE_ADDR from = dsc->insn_addr;
6344
6345   /* Allow OS-specific code to override SVC handling.  */
6346   if (dsc->u.svc.copy_svc_os)
6347     return dsc->u.svc.copy_svc_os (gdbarch, insn, to, regs, dsc);
6348
6349   if (debug_displaced)
6350     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.8lx\n",
6351                         (unsigned long) insn);
6352
6353   /* Preparation: none.
6354      Insn: unmodified svc.
6355      Cleanup: pc <- insn_addr + 4.  */
6356
6357   dsc->modinsn[0] = insn;
6358
6359   dsc->cleanup = &cleanup_svc;
6360   /* Pretend we wrote to the PC, so cleanup doesn't set PC to the next
6361      instruction.  */
6362   dsc->wrote_to_pc = 1;
6363
6364   return 0;
6365 }
6366
6367 /* Copy undefined instructions.  */
6368
6369 static int
6370 copy_undef (struct gdbarch *gdbarch, uint32_t insn,
6371             struct displaced_step_closure *dsc)
6372 {
6373   if (debug_displaced)
6374     fprintf_unfiltered (gdb_stdlog,
6375                         "displaced: copying undefined insn %.8lx\n",
6376                         (unsigned long) insn);
6377
6378   dsc->modinsn[0] = insn;
6379
6380   return 0;
6381 }
6382
6383 /* Copy unpredictable instructions.  */
6384
6385 static int
6386 copy_unpred (struct gdbarch *gdbarch, uint32_t insn,
6387              struct displaced_step_closure *dsc)
6388 {
6389   if (debug_displaced)
6390     fprintf_unfiltered (gdb_stdlog, "displaced: copying unpredictable insn "
6391                         "%.8lx\n", (unsigned long) insn);
6392
6393   dsc->modinsn[0] = insn;
6394
6395   return 0;
6396 }
6397
6398 /* The decode_* functions are instruction decoding helpers.  They mostly follow
6399    the presentation in the ARM ARM.  */
6400
6401 static int
6402 decode_misc_memhint_neon (struct gdbarch *gdbarch, uint32_t insn,
6403                           struct regcache *regs,
6404                           struct displaced_step_closure *dsc)
6405 {
6406   unsigned int op1 = bits (insn, 20, 26), op2 = bits (insn, 4, 7);
6407   unsigned int rn = bits (insn, 16, 19);
6408
6409   if (op1 == 0x10 && (op2 & 0x2) == 0x0 && (rn & 0xe) == 0x0)
6410     return copy_unmodified (gdbarch, insn, "cps", dsc);
6411   else if (op1 == 0x10 && op2 == 0x0 && (rn & 0xe) == 0x1)
6412     return copy_unmodified (gdbarch, insn, "setend", dsc);
6413   else if ((op1 & 0x60) == 0x20)
6414     return copy_unmodified (gdbarch, insn, "neon dataproc", dsc);
6415   else if ((op1 & 0x71) == 0x40)
6416     return copy_unmodified (gdbarch, insn, "neon elt/struct load/store", dsc);
6417   else if ((op1 & 0x77) == 0x41)
6418     return copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
6419   else if ((op1 & 0x77) == 0x45)
6420     return copy_preload (gdbarch, insn, regs, dsc);  /* pli.  */
6421   else if ((op1 & 0x77) == 0x51)
6422     {
6423       if (rn != 0xf)
6424         return copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
6425       else
6426         return copy_unpred (gdbarch, insn, dsc);
6427     }
6428   else if ((op1 & 0x77) == 0x55)
6429     return copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
6430   else if (op1 == 0x57)
6431     switch (op2)
6432       {
6433       case 0x1: return copy_unmodified (gdbarch, insn, "clrex", dsc);
6434       case 0x4: return copy_unmodified (gdbarch, insn, "dsb", dsc);
6435       case 0x5: return copy_unmodified (gdbarch, insn, "dmb", dsc);
6436       case 0x6: return copy_unmodified (gdbarch, insn, "isb", dsc);
6437       default: return copy_unpred (gdbarch, insn, dsc);
6438       }
6439   else if ((op1 & 0x63) == 0x43)
6440     return copy_unpred (gdbarch, insn, dsc);
6441   else if ((op2 & 0x1) == 0x0)
6442     switch (op1 & ~0x80)
6443       {
6444       case 0x61:
6445         return copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
6446       case 0x65:
6447         return copy_preload_reg (gdbarch, insn, regs, dsc);  /* pli reg.  */
6448       case 0x71: case 0x75:
6449         /* pld/pldw reg.  */
6450         return copy_preload_reg (gdbarch, insn, regs, dsc);
6451       case 0x63: case 0x67: case 0x73: case 0x77:
6452         return copy_unpred (gdbarch, insn, dsc);
6453       default:
6454         return copy_undef (gdbarch, insn, dsc);
6455       }
6456   else
6457     return copy_undef (gdbarch, insn, dsc);  /* Probably unreachable.  */
6458 }
6459
6460 static int
6461 decode_unconditional (struct gdbarch *gdbarch, uint32_t insn,
6462                       struct regcache *regs,
6463                       struct displaced_step_closure *dsc)
6464 {
6465   if (bit (insn, 27) == 0)
6466     return decode_misc_memhint_neon (gdbarch, insn, regs, dsc);
6467   /* Switch on bits: 0bxxxxx321xxx0xxxxxxxxxxxxxxxxxxxx.  */
6468   else switch (((insn & 0x7000000) >> 23) | ((insn & 0x100000) >> 20))
6469     {
6470     case 0x0: case 0x2:
6471       return copy_unmodified (gdbarch, insn, "srs", dsc);
6472
6473     case 0x1: case 0x3:
6474       return copy_unmodified (gdbarch, insn, "rfe", dsc);
6475
6476     case 0x4: case 0x5: case 0x6: case 0x7:
6477       return copy_b_bl_blx (gdbarch, insn, regs, dsc);
6478
6479     case 0x8:
6480       switch ((insn & 0xe00000) >> 21)
6481         {
6482         case 0x1: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7:
6483           /* stc/stc2.  */
6484           return copy_copro_load_store (gdbarch, insn, regs, dsc);
6485
6486         case 0x2:
6487           return copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
6488
6489         default:
6490           return copy_undef (gdbarch, insn, dsc);
6491         }
6492
6493     case 0x9:
6494       {
6495          int rn_f = (bits (insn, 16, 19) == 0xf);
6496         switch ((insn & 0xe00000) >> 21)
6497           {
6498           case 0x1: case 0x3:
6499             /* ldc/ldc2 imm (undefined for rn == pc).  */
6500             return rn_f ? copy_undef (gdbarch, insn, dsc)
6501                         : copy_copro_load_store (gdbarch, insn, regs, dsc);
6502
6503           case 0x2:
6504             return copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
6505
6506           case 0x4: case 0x5: case 0x6: case 0x7:
6507             /* ldc/ldc2 lit (undefined for rn != pc).  */
6508             return rn_f ? copy_copro_load_store (gdbarch, insn, regs, dsc)
6509                         : copy_undef (gdbarch, insn, dsc);
6510
6511           default:
6512             return copy_undef (gdbarch, insn, dsc);
6513           }
6514       }
6515
6516     case 0xa:
6517       return copy_unmodified (gdbarch, insn, "stc/stc2", dsc);
6518
6519     case 0xb:
6520       if (bits (insn, 16, 19) == 0xf)
6521         /* ldc/ldc2 lit.  */
6522         return copy_copro_load_store (gdbarch, insn, regs, dsc);
6523       else
6524         return copy_undef (gdbarch, insn, dsc);
6525
6526     case 0xc:
6527       if (bit (insn, 4))
6528         return copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
6529       else
6530         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
6531
6532     case 0xd:
6533       if (bit (insn, 4))
6534         return copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
6535       else
6536         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
6537
6538     default:
6539       return copy_undef (gdbarch, insn, dsc);
6540     }
6541 }
6542
6543 /* Decode miscellaneous instructions in dp/misc encoding space.  */
6544
6545 static int
6546 decode_miscellaneous (struct gdbarch *gdbarch, uint32_t insn,
6547                       struct regcache *regs,
6548                       struct displaced_step_closure *dsc)
6549 {
6550   unsigned int op2 = bits (insn, 4, 6);
6551   unsigned int op = bits (insn, 21, 22);
6552   unsigned int op1 = bits (insn, 16, 19);
6553
6554   switch (op2)
6555     {
6556     case 0x0:
6557       return copy_unmodified (gdbarch, insn, "mrs/msr", dsc);
6558
6559     case 0x1:
6560       if (op == 0x1)  /* bx.  */
6561         return copy_bx_blx_reg (gdbarch, insn, regs, dsc);
6562       else if (op == 0x3)
6563         return copy_unmodified (gdbarch, insn, "clz", dsc);
6564       else
6565         return copy_undef (gdbarch, insn, dsc);
6566
6567     case 0x2:
6568       if (op == 0x1)
6569         /* Not really supported.  */
6570         return copy_unmodified (gdbarch, insn, "bxj", dsc);
6571       else
6572         return copy_undef (gdbarch, insn, dsc);
6573
6574     case 0x3:
6575       if (op == 0x1)
6576         return copy_bx_blx_reg (gdbarch, insn,
6577                                 regs, dsc);  /* blx register.  */
6578       else
6579         return copy_undef (gdbarch, insn, dsc);
6580
6581     case 0x5:
6582       return copy_unmodified (gdbarch, insn, "saturating add/sub", dsc);
6583
6584     case 0x7:
6585       if (op == 0x1)
6586         return copy_unmodified (gdbarch, insn, "bkpt", dsc);
6587       else if (op == 0x3)
6588         /* Not really supported.  */
6589         return copy_unmodified (gdbarch, insn, "smc", dsc);
6590
6591     default:
6592       return copy_undef (gdbarch, insn, dsc);
6593     }
6594 }
6595
6596 static int
6597 decode_dp_misc (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6598                 struct displaced_step_closure *dsc)
6599 {
6600   if (bit (insn, 25))
6601     switch (bits (insn, 20, 24))
6602       {
6603       case 0x10:
6604         return copy_unmodified (gdbarch, insn, "movw", dsc);
6605
6606       case 0x14:
6607         return copy_unmodified (gdbarch, insn, "movt", dsc);
6608
6609       case 0x12: case 0x16:
6610         return copy_unmodified (gdbarch, insn, "msr imm", dsc);
6611
6612       default:
6613         return copy_alu_imm (gdbarch, insn, regs, dsc);
6614       }
6615   else
6616     {
6617       uint32_t op1 = bits (insn, 20, 24), op2 = bits (insn, 4, 7);
6618
6619       if ((op1 & 0x19) != 0x10 && (op2 & 0x1) == 0x0)
6620         return copy_alu_reg (gdbarch, insn, regs, dsc);
6621       else if ((op1 & 0x19) != 0x10 && (op2 & 0x9) == 0x1)
6622         return copy_alu_shifted_reg (gdbarch, insn, regs, dsc);
6623       else if ((op1 & 0x19) == 0x10 && (op2 & 0x8) == 0x0)
6624         return decode_miscellaneous (gdbarch, insn, regs, dsc);
6625       else if ((op1 & 0x19) == 0x10 && (op2 & 0x9) == 0x8)
6626         return copy_unmodified (gdbarch, insn, "halfword mul/mla", dsc);
6627       else if ((op1 & 0x10) == 0x00 && op2 == 0x9)
6628         return copy_unmodified (gdbarch, insn, "mul/mla", dsc);
6629       else if ((op1 & 0x10) == 0x10 && op2 == 0x9)
6630         return copy_unmodified (gdbarch, insn, "synch", dsc);
6631       else if (op2 == 0xb || (op2 & 0xd) == 0xd)
6632         /* 2nd arg means "unpriveleged".  */
6633         return copy_extra_ld_st (gdbarch, insn, (op1 & 0x12) == 0x02, regs,
6634                                  dsc);
6635     }
6636
6637   /* Should be unreachable.  */
6638   return 1;
6639 }
6640
6641 static int
6642 decode_ld_st_word_ubyte (struct gdbarch *gdbarch, uint32_t insn,
6643                          struct regcache *regs,
6644                          struct displaced_step_closure *dsc)
6645 {
6646   int a = bit (insn, 25), b = bit (insn, 4);
6647   uint32_t op1 = bits (insn, 20, 24);
6648   int rn_f = bits (insn, 16, 19) == 0xf;
6649
6650   if ((!a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02)
6651       || (a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02 && !b))
6652     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 0, 0);
6653   else if ((!a && (op1 & 0x17) == 0x02)
6654             || (a && (op1 & 0x17) == 0x02 && !b))
6655     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 0, 1);
6656   else if ((!a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03)
6657             || (a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03 && !b))
6658     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 0, 0);
6659   else if ((!a && (op1 & 0x17) == 0x03)
6660            || (a && (op1 & 0x17) == 0x03 && !b))
6661     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 0, 1);
6662   else if ((!a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06)
6663             || (a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06 && !b))
6664     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 0);
6665   else if ((!a && (op1 & 0x17) == 0x06)
6666            || (a && (op1 & 0x17) == 0x06 && !b))
6667     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 1);
6668   else if ((!a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07)
6669            || (a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07 && !b))
6670     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 0);
6671   else if ((!a && (op1 & 0x17) == 0x07)
6672            || (a && (op1 & 0x17) == 0x07 && !b))
6673     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 1);
6674
6675   /* Should be unreachable.  */
6676   return 1;
6677 }
6678
6679 static int
6680 decode_media (struct gdbarch *gdbarch, uint32_t insn,
6681               struct displaced_step_closure *dsc)
6682 {
6683   switch (bits (insn, 20, 24))
6684     {
6685     case 0x00: case 0x01: case 0x02: case 0x03:
6686       return copy_unmodified (gdbarch, insn, "parallel add/sub signed", dsc);
6687
6688     case 0x04: case 0x05: case 0x06: case 0x07:
6689       return copy_unmodified (gdbarch, insn, "parallel add/sub unsigned", dsc);
6690
6691     case 0x08: case 0x09: case 0x0a: case 0x0b:
6692     case 0x0c: case 0x0d: case 0x0e: case 0x0f:
6693       return copy_unmodified (gdbarch, insn,
6694                               "decode/pack/unpack/saturate/reverse", dsc);
6695
6696     case 0x18:
6697       if (bits (insn, 5, 7) == 0)  /* op2.  */
6698          {
6699           if (bits (insn, 12, 15) == 0xf)
6700             return copy_unmodified (gdbarch, insn, "usad8", dsc);
6701           else
6702             return copy_unmodified (gdbarch, insn, "usada8", dsc);
6703         }
6704       else
6705          return copy_undef (gdbarch, insn, dsc);
6706
6707     case 0x1a: case 0x1b:
6708       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
6709         return copy_unmodified (gdbarch, insn, "sbfx", dsc);
6710       else
6711         return copy_undef (gdbarch, insn, dsc);
6712
6713     case 0x1c: case 0x1d:
6714       if (bits (insn, 5, 6) == 0x0)  /* op2[1:0].  */
6715          {
6716           if (bits (insn, 0, 3) == 0xf)
6717             return copy_unmodified (gdbarch, insn, "bfc", dsc);
6718           else
6719             return copy_unmodified (gdbarch, insn, "bfi", dsc);
6720         }
6721       else
6722         return copy_undef (gdbarch, insn, dsc);
6723
6724     case 0x1e: case 0x1f:
6725       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
6726         return copy_unmodified (gdbarch, insn, "ubfx", dsc);
6727       else
6728         return copy_undef (gdbarch, insn, dsc);
6729     }
6730
6731   /* Should be unreachable.  */
6732   return 1;
6733 }
6734
6735 static int
6736 decode_b_bl_ldmstm (struct gdbarch *gdbarch, int32_t insn,
6737                     struct regcache *regs, struct displaced_step_closure *dsc)
6738 {
6739   if (bit (insn, 25))
6740     return copy_b_bl_blx (gdbarch, insn, regs, dsc);
6741   else
6742     return copy_block_xfer (gdbarch, insn, regs, dsc);
6743 }
6744
6745 static int
6746 decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint32_t insn,
6747                       struct regcache *regs,
6748                       struct displaced_step_closure *dsc)
6749 {
6750   unsigned int opcode = bits (insn, 20, 24);
6751
6752   switch (opcode)
6753     {
6754     case 0x04: case 0x05:  /* VFP/Neon mrrc/mcrr.  */
6755       return copy_unmodified (gdbarch, insn, "vfp/neon mrrc/mcrr", dsc);
6756
6757     case 0x08: case 0x0a: case 0x0c: case 0x0e:
6758     case 0x12: case 0x16:
6759       return copy_unmodified (gdbarch, insn, "vfp/neon vstm/vpush", dsc);
6760
6761     case 0x09: case 0x0b: case 0x0d: case 0x0f:
6762     case 0x13: case 0x17:
6763       return copy_unmodified (gdbarch, insn, "vfp/neon vldm/vpop", dsc);
6764
6765     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
6766     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
6767       /* Note: no writeback for these instructions.  Bit 25 will always be
6768          zero though (via caller), so the following works OK.  */
6769       return copy_copro_load_store (gdbarch, insn, regs, dsc);
6770     }
6771
6772   /* Should be unreachable.  */
6773   return 1;
6774 }
6775
6776 static int
6777 decode_svc_copro (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
6778                   struct regcache *regs, struct displaced_step_closure *dsc)
6779 {
6780   unsigned int op1 = bits (insn, 20, 25);
6781   int op = bit (insn, 4);
6782   unsigned int coproc = bits (insn, 8, 11);
6783   unsigned int rn = bits (insn, 16, 19);
6784
6785   if ((op1 & 0x20) == 0x00 && (op1 & 0x3a) != 0x00 && (coproc & 0xe) == 0xa)
6786     return decode_ext_reg_ld_st (gdbarch, insn, regs, dsc);
6787   else if ((op1 & 0x21) == 0x00 && (op1 & 0x3a) != 0x00
6788            && (coproc & 0xe) != 0xa)
6789     /* stc/stc2.  */
6790     return copy_copro_load_store (gdbarch, insn, regs, dsc);
6791   else if ((op1 & 0x21) == 0x01 && (op1 & 0x3a) != 0x00
6792            && (coproc & 0xe) != 0xa)
6793     /* ldc/ldc2 imm/lit.  */
6794     return copy_copro_load_store (gdbarch, insn, regs, dsc);
6795   else if ((op1 & 0x3e) == 0x00)
6796     return copy_undef (gdbarch, insn, dsc);
6797   else if ((op1 & 0x3e) == 0x04 && (coproc & 0xe) == 0xa)
6798     return copy_unmodified (gdbarch, insn, "neon 64bit xfer", dsc);
6799   else if (op1 == 0x04 && (coproc & 0xe) != 0xa)
6800     return copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
6801   else if (op1 == 0x05 && (coproc & 0xe) != 0xa)
6802     return copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
6803   else if ((op1 & 0x30) == 0x20 && !op)
6804     {
6805       if ((coproc & 0xe) == 0xa)
6806         return copy_unmodified (gdbarch, insn, "vfp dataproc", dsc);
6807       else
6808         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
6809     }
6810   else if ((op1 & 0x30) == 0x20 && op)
6811     return copy_unmodified (gdbarch, insn, "neon 8/16/32 bit xfer", dsc);
6812   else if ((op1 & 0x31) == 0x20 && op && (coproc & 0xe) != 0xa)
6813     return copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
6814   else if ((op1 & 0x31) == 0x21 && op && (coproc & 0xe) != 0xa)
6815     return copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
6816   else if ((op1 & 0x30) == 0x30)
6817     return copy_svc (gdbarch, insn, to, regs, dsc);
6818   else
6819     return copy_undef (gdbarch, insn, dsc);  /* Possibly unreachable.  */
6820 }
6821
6822 void
6823 arm_process_displaced_insn (struct gdbarch *gdbarch, uint32_t insn,
6824                             CORE_ADDR from, CORE_ADDR to,
6825                             struct regcache *regs,
6826                             struct displaced_step_closure *dsc)
6827 {
6828   int err = 0;
6829
6830   if (!displaced_in_arm_mode (regs))
6831     error (_("Displaced stepping is only supported in ARM mode"));
6832
6833   /* Most displaced instructions use a 1-instruction scratch space, so set this
6834      here and override below if/when necessary.  */
6835   dsc->numinsns = 1;
6836   dsc->insn_addr = from;
6837   dsc->scratch_base = to;
6838   dsc->cleanup = NULL;
6839   dsc->wrote_to_pc = 0;
6840
6841   if ((insn & 0xf0000000) == 0xf0000000)
6842     err = decode_unconditional (gdbarch, insn, regs, dsc);
6843   else switch (((insn & 0x10) >> 4) | ((insn & 0xe000000) >> 24))
6844     {
6845     case 0x0: case 0x1: case 0x2: case 0x3:
6846       err = decode_dp_misc (gdbarch, insn, regs, dsc);
6847       break;
6848
6849     case 0x4: case 0x5: case 0x6:
6850       err = decode_ld_st_word_ubyte (gdbarch, insn, regs, dsc);
6851       break;
6852
6853     case 0x7:
6854       err = decode_media (gdbarch, insn, dsc);
6855       break;
6856
6857     case 0x8: case 0x9: case 0xa: case 0xb:
6858       err = decode_b_bl_ldmstm (gdbarch, insn, regs, dsc);
6859       break;
6860
6861     case 0xc: case 0xd: case 0xe: case 0xf:
6862       err = decode_svc_copro (gdbarch, insn, to, regs, dsc);
6863       break;
6864     }
6865
6866   if (err)
6867     internal_error (__FILE__, __LINE__,
6868                     _("arm_process_displaced_insn: Instruction decode error"));
6869 }
6870
6871 /* Actually set up the scratch space for a displaced instruction.  */
6872
6873 void
6874 arm_displaced_init_closure (struct gdbarch *gdbarch, CORE_ADDR from,
6875                             CORE_ADDR to, struct displaced_step_closure *dsc)
6876 {
6877   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
6878   unsigned int i;
6879   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
6880
6881   /* Poke modified instruction(s).  */
6882   for (i = 0; i < dsc->numinsns; i++)
6883     {
6884       if (debug_displaced)
6885         fprintf_unfiltered (gdb_stdlog, "displaced: writing insn %.8lx at "
6886                             "%.8lx\n", (unsigned long) dsc->modinsn[i],
6887                             (unsigned long) to + i * 4);
6888       write_memory_unsigned_integer (to + i * 4, 4, byte_order_for_code,
6889                                      dsc->modinsn[i]);
6890     }
6891
6892   /* Put breakpoint afterwards.  */
6893   write_memory (to + dsc->numinsns * 4, tdep->arm_breakpoint,
6894                 tdep->arm_breakpoint_size);
6895
6896   if (debug_displaced)
6897     fprintf_unfiltered (gdb_stdlog, "displaced: copy %s->%s: ",
6898                         paddress (gdbarch, from), paddress (gdbarch, to));
6899 }
6900
6901 /* Entry point for copying an instruction into scratch space for displaced
6902    stepping.  */
6903
6904 struct displaced_step_closure *
6905 arm_displaced_step_copy_insn (struct gdbarch *gdbarch,
6906                               CORE_ADDR from, CORE_ADDR to,
6907                               struct regcache *regs)
6908 {
6909   struct displaced_step_closure *dsc
6910     = xmalloc (sizeof (struct displaced_step_closure));
6911   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
6912   uint32_t insn = read_memory_unsigned_integer (from, 4, byte_order_for_code);
6913
6914   if (debug_displaced)
6915     fprintf_unfiltered (gdb_stdlog, "displaced: stepping insn %.8lx "
6916                         "at %.8lx\n", (unsigned long) insn,
6917                         (unsigned long) from);
6918
6919   arm_process_displaced_insn (gdbarch, insn, from, to, regs, dsc);
6920   arm_displaced_init_closure (gdbarch, from, to, dsc);
6921
6922   return dsc;
6923 }
6924
6925 /* Entry point for cleaning things up after a displaced instruction has been
6926    single-stepped.  */
6927
6928 void
6929 arm_displaced_step_fixup (struct gdbarch *gdbarch,
6930                           struct displaced_step_closure *dsc,
6931                           CORE_ADDR from, CORE_ADDR to,
6932                           struct regcache *regs)
6933 {
6934   if (dsc->cleanup)
6935     dsc->cleanup (gdbarch, regs, dsc);
6936
6937   if (!dsc->wrote_to_pc)
6938     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, dsc->insn_addr + 4);
6939 }
6940
6941 #include "bfd-in2.h"
6942 #include "libcoff.h"
6943
6944 static int
6945 gdb_print_insn_arm (bfd_vma memaddr, disassemble_info *info)
6946 {
6947   struct gdbarch *gdbarch = info->application_data;
6948
6949   if (arm_pc_is_thumb (gdbarch, memaddr))
6950     {
6951       static asymbol *asym;
6952       static combined_entry_type ce;
6953       static struct coff_symbol_struct csym;
6954       static struct bfd fake_bfd;
6955       static bfd_target fake_target;
6956
6957       if (csym.native == NULL)
6958         {
6959           /* Create a fake symbol vector containing a Thumb symbol.
6960              This is solely so that the code in print_insn_little_arm() 
6961              and print_insn_big_arm() in opcodes/arm-dis.c will detect
6962              the presence of a Thumb symbol and switch to decoding
6963              Thumb instructions.  */
6964
6965           fake_target.flavour = bfd_target_coff_flavour;
6966           fake_bfd.xvec = &fake_target;
6967           ce.u.syment.n_sclass = C_THUMBEXTFUNC;
6968           csym.native = &ce;
6969           csym.symbol.the_bfd = &fake_bfd;
6970           csym.symbol.name = "fake";
6971           asym = (asymbol *) & csym;
6972         }
6973
6974       memaddr = UNMAKE_THUMB_ADDR (memaddr);
6975       info->symbols = &asym;
6976     }
6977   else
6978     info->symbols = NULL;
6979
6980   if (info->endian == BFD_ENDIAN_BIG)
6981     return print_insn_big_arm (memaddr, info);
6982   else
6983     return print_insn_little_arm (memaddr, info);
6984 }
6985
6986 /* The following define instruction sequences that will cause ARM
6987    cpu's to take an undefined instruction trap.  These are used to
6988    signal a breakpoint to GDB.
6989    
6990    The newer ARMv4T cpu's are capable of operating in ARM or Thumb
6991    modes.  A different instruction is required for each mode.  The ARM
6992    cpu's can also be big or little endian.  Thus four different
6993    instructions are needed to support all cases.
6994    
6995    Note: ARMv4 defines several new instructions that will take the
6996    undefined instruction trap.  ARM7TDMI is nominally ARMv4T, but does
6997    not in fact add the new instructions.  The new undefined
6998    instructions in ARMv4 are all instructions that had no defined
6999    behaviour in earlier chips.  There is no guarantee that they will
7000    raise an exception, but may be treated as NOP's.  In practice, it
7001    may only safe to rely on instructions matching:
7002    
7003    3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 
7004    1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
7005    C C C C 0 1 1 x x x x x x x x x x x x x x x x x x x x 1 x x x x
7006    
7007    Even this may only true if the condition predicate is true.  The
7008    following use a condition predicate of ALWAYS so it is always TRUE.
7009    
7010    There are other ways of forcing a breakpoint.  GNU/Linux, RISC iX,
7011    and NetBSD all use a software interrupt rather than an undefined
7012    instruction to force a trap.  This can be handled by by the
7013    abi-specific code during establishment of the gdbarch vector.  */
7014
7015 #define ARM_LE_BREAKPOINT {0xFE,0xDE,0xFF,0xE7}
7016 #define ARM_BE_BREAKPOINT {0xE7,0xFF,0xDE,0xFE}
7017 #define THUMB_LE_BREAKPOINT {0xbe,0xbe}
7018 #define THUMB_BE_BREAKPOINT {0xbe,0xbe}
7019
7020 static const char arm_default_arm_le_breakpoint[] = ARM_LE_BREAKPOINT;
7021 static const char arm_default_arm_be_breakpoint[] = ARM_BE_BREAKPOINT;
7022 static const char arm_default_thumb_le_breakpoint[] = THUMB_LE_BREAKPOINT;
7023 static const char arm_default_thumb_be_breakpoint[] = THUMB_BE_BREAKPOINT;
7024
7025 /* Determine the type and size of breakpoint to insert at PCPTR.  Uses
7026    the program counter value to determine whether a 16-bit or 32-bit
7027    breakpoint should be used.  It returns a pointer to a string of
7028    bytes that encode a breakpoint instruction, stores the length of
7029    the string to *lenptr, and adjusts the program counter (if
7030    necessary) to point to the actual memory location where the
7031    breakpoint should be inserted.  */
7032
7033 static const unsigned char *
7034 arm_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr, int *lenptr)
7035 {
7036   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
7037   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
7038
7039   if (arm_pc_is_thumb (gdbarch, *pcptr))
7040     {
7041       *pcptr = UNMAKE_THUMB_ADDR (*pcptr);
7042
7043       /* If we have a separate 32-bit breakpoint instruction for Thumb-2,
7044          check whether we are replacing a 32-bit instruction.  */
7045       if (tdep->thumb2_breakpoint != NULL)
7046         {
7047           gdb_byte buf[2];
7048           if (target_read_memory (*pcptr, buf, 2) == 0)
7049             {
7050               unsigned short inst1;
7051               inst1 = extract_unsigned_integer (buf, 2, byte_order_for_code);
7052               if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
7053                 {
7054                   *lenptr = tdep->thumb2_breakpoint_size;
7055                   return tdep->thumb2_breakpoint;
7056                 }
7057             }
7058         }
7059
7060       *lenptr = tdep->thumb_breakpoint_size;
7061       return tdep->thumb_breakpoint;
7062     }
7063   else
7064     {
7065       *lenptr = tdep->arm_breakpoint_size;
7066       return tdep->arm_breakpoint;
7067     }
7068 }
7069
7070 static void
7071 arm_remote_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
7072                                int *kindptr)
7073 {
7074   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
7075
7076   arm_breakpoint_from_pc (gdbarch, pcptr, kindptr);
7077
7078   if (arm_pc_is_thumb (gdbarch, *pcptr) && *kindptr == 4)
7079     /* The documented magic value for a 32-bit Thumb-2 breakpoint, so
7080        that this is not confused with a 32-bit ARM breakpoint.  */
7081     *kindptr = 3;
7082 }
7083
7084 /* Extract from an array REGBUF containing the (raw) register state a
7085    function return value of type TYPE, and copy that, in virtual
7086    format, into VALBUF.  */
7087
7088 static void
7089 arm_extract_return_value (struct type *type, struct regcache *regs,
7090                           gdb_byte *valbuf)
7091 {
7092   struct gdbarch *gdbarch = get_regcache_arch (regs);
7093   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7094
7095   if (TYPE_CODE_FLT == TYPE_CODE (type))
7096     {
7097       switch (gdbarch_tdep (gdbarch)->fp_model)
7098         {
7099         case ARM_FLOAT_FPA:
7100           {
7101             /* The value is in register F0 in internal format.  We need to
7102                extract the raw value and then convert it to the desired
7103                internal type.  */
7104             bfd_byte tmpbuf[FP_REGISTER_SIZE];
7105
7106             regcache_cooked_read (regs, ARM_F0_REGNUM, tmpbuf);
7107             convert_from_extended (floatformat_from_type (type), tmpbuf,
7108                                    valbuf, gdbarch_byte_order (gdbarch));
7109           }
7110           break;
7111
7112         case ARM_FLOAT_SOFT_FPA:
7113         case ARM_FLOAT_SOFT_VFP:
7114           /* ARM_FLOAT_VFP can arise if this is a variadic function so
7115              not using the VFP ABI code.  */
7116         case ARM_FLOAT_VFP:
7117           regcache_cooked_read (regs, ARM_A1_REGNUM, valbuf);
7118           if (TYPE_LENGTH (type) > 4)
7119             regcache_cooked_read (regs, ARM_A1_REGNUM + 1,
7120                                   valbuf + INT_REGISTER_SIZE);
7121           break;
7122
7123         default:
7124           internal_error (__FILE__, __LINE__,
7125                           _("arm_extract_return_value: "
7126                             "Floating point model not supported"));
7127           break;
7128         }
7129     }
7130   else if (TYPE_CODE (type) == TYPE_CODE_INT
7131            || TYPE_CODE (type) == TYPE_CODE_CHAR
7132            || TYPE_CODE (type) == TYPE_CODE_BOOL
7133            || TYPE_CODE (type) == TYPE_CODE_PTR
7134            || TYPE_CODE (type) == TYPE_CODE_REF
7135            || TYPE_CODE (type) == TYPE_CODE_ENUM)
7136     {
7137       /* If the the type is a plain integer, then the access is
7138          straight-forward.  Otherwise we have to play around a bit more.  */
7139       int len = TYPE_LENGTH (type);
7140       int regno = ARM_A1_REGNUM;
7141       ULONGEST tmp;
7142
7143       while (len > 0)
7144         {
7145           /* By using store_unsigned_integer we avoid having to do
7146              anything special for small big-endian values.  */
7147           regcache_cooked_read_unsigned (regs, regno++, &tmp);
7148           store_unsigned_integer (valbuf, 
7149                                   (len > INT_REGISTER_SIZE
7150                                    ? INT_REGISTER_SIZE : len),
7151                                   byte_order, tmp);
7152           len -= INT_REGISTER_SIZE;
7153           valbuf += INT_REGISTER_SIZE;
7154         }
7155     }
7156   else
7157     {
7158       /* For a structure or union the behaviour is as if the value had
7159          been stored to word-aligned memory and then loaded into 
7160          registers with 32-bit load instruction(s).  */
7161       int len = TYPE_LENGTH (type);
7162       int regno = ARM_A1_REGNUM;
7163       bfd_byte tmpbuf[INT_REGISTER_SIZE];
7164
7165       while (len > 0)
7166         {
7167           regcache_cooked_read (regs, regno++, tmpbuf);
7168           memcpy (valbuf, tmpbuf,
7169                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
7170           len -= INT_REGISTER_SIZE;
7171           valbuf += INT_REGISTER_SIZE;
7172         }
7173     }
7174 }
7175
7176
7177 /* Will a function return an aggregate type in memory or in a
7178    register?  Return 0 if an aggregate type can be returned in a
7179    register, 1 if it must be returned in memory.  */
7180
7181 static int
7182 arm_return_in_memory (struct gdbarch *gdbarch, struct type *type)
7183 {
7184   int nRc;
7185   enum type_code code;
7186
7187   CHECK_TYPEDEF (type);
7188
7189   /* In the ARM ABI, "integer" like aggregate types are returned in
7190      registers.  For an aggregate type to be integer like, its size
7191      must be less than or equal to INT_REGISTER_SIZE and the
7192      offset of each addressable subfield must be zero.  Note that bit
7193      fields are not addressable, and all addressable subfields of
7194      unions always start at offset zero.
7195
7196      This function is based on the behaviour of GCC 2.95.1.
7197      See: gcc/arm.c: arm_return_in_memory() for details.
7198
7199      Note: All versions of GCC before GCC 2.95.2 do not set up the
7200      parameters correctly for a function returning the following
7201      structure: struct { float f;}; This should be returned in memory,
7202      not a register.  Richard Earnshaw sent me a patch, but I do not
7203      know of any way to detect if a function like the above has been
7204      compiled with the correct calling convention.  */
7205
7206   /* All aggregate types that won't fit in a register must be returned
7207      in memory.  */
7208   if (TYPE_LENGTH (type) > INT_REGISTER_SIZE)
7209     {
7210       return 1;
7211     }
7212
7213   /* The AAPCS says all aggregates not larger than a word are returned
7214      in a register.  */
7215   if (gdbarch_tdep (gdbarch)->arm_abi != ARM_ABI_APCS)
7216     return 0;
7217
7218   /* The only aggregate types that can be returned in a register are
7219      structs and unions.  Arrays must be returned in memory.  */
7220   code = TYPE_CODE (type);
7221   if ((TYPE_CODE_STRUCT != code) && (TYPE_CODE_UNION != code))
7222     {
7223       return 1;
7224     }
7225
7226   /* Assume all other aggregate types can be returned in a register.
7227      Run a check for structures, unions and arrays.  */
7228   nRc = 0;
7229
7230   if ((TYPE_CODE_STRUCT == code) || (TYPE_CODE_UNION == code))
7231     {
7232       int i;
7233       /* Need to check if this struct/union is "integer" like.  For
7234          this to be true, its size must be less than or equal to
7235          INT_REGISTER_SIZE and the offset of each addressable
7236          subfield must be zero.  Note that bit fields are not
7237          addressable, and unions always start at offset zero.  If any
7238          of the subfields is a floating point type, the struct/union
7239          cannot be an integer type.  */
7240
7241       /* For each field in the object, check:
7242          1) Is it FP? --> yes, nRc = 1;
7243          2) Is it addressable (bitpos != 0) and
7244          not packed (bitsize == 0)?
7245          --> yes, nRc = 1  
7246        */
7247
7248       for (i = 0; i < TYPE_NFIELDS (type); i++)
7249         {
7250           enum type_code field_type_code;
7251           field_type_code = TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type,
7252                                                                        i)));
7253
7254           /* Is it a floating point type field?  */
7255           if (field_type_code == TYPE_CODE_FLT)
7256             {
7257               nRc = 1;
7258               break;
7259             }
7260
7261           /* If bitpos != 0, then we have to care about it.  */
7262           if (TYPE_FIELD_BITPOS (type, i) != 0)
7263             {
7264               /* Bitfields are not addressable.  If the field bitsize is 
7265                  zero, then the field is not packed.  Hence it cannot be
7266                  a bitfield or any other packed type.  */
7267               if (TYPE_FIELD_BITSIZE (type, i) == 0)
7268                 {
7269                   nRc = 1;
7270                   break;
7271                 }
7272             }
7273         }
7274     }
7275
7276   return nRc;
7277 }
7278
7279 /* Write into appropriate registers a function return value of type
7280    TYPE, given in virtual format.  */
7281
7282 static void
7283 arm_store_return_value (struct type *type, struct regcache *regs,
7284                         const gdb_byte *valbuf)
7285 {
7286   struct gdbarch *gdbarch = get_regcache_arch (regs);
7287   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7288
7289   if (TYPE_CODE (type) == TYPE_CODE_FLT)
7290     {
7291       char buf[MAX_REGISTER_SIZE];
7292
7293       switch (gdbarch_tdep (gdbarch)->fp_model)
7294         {
7295         case ARM_FLOAT_FPA:
7296
7297           convert_to_extended (floatformat_from_type (type), buf, valbuf,
7298                                gdbarch_byte_order (gdbarch));
7299           regcache_cooked_write (regs, ARM_F0_REGNUM, buf);
7300           break;
7301
7302         case ARM_FLOAT_SOFT_FPA:
7303         case ARM_FLOAT_SOFT_VFP:
7304           /* ARM_FLOAT_VFP can arise if this is a variadic function so
7305              not using the VFP ABI code.  */
7306         case ARM_FLOAT_VFP:
7307           regcache_cooked_write (regs, ARM_A1_REGNUM, valbuf);
7308           if (TYPE_LENGTH (type) > 4)
7309             regcache_cooked_write (regs, ARM_A1_REGNUM + 1, 
7310                                    valbuf + INT_REGISTER_SIZE);
7311           break;
7312
7313         default:
7314           internal_error (__FILE__, __LINE__,
7315                           _("arm_store_return_value: Floating "
7316                             "point model not supported"));
7317           break;
7318         }
7319     }
7320   else if (TYPE_CODE (type) == TYPE_CODE_INT
7321            || TYPE_CODE (type) == TYPE_CODE_CHAR
7322            || TYPE_CODE (type) == TYPE_CODE_BOOL
7323            || TYPE_CODE (type) == TYPE_CODE_PTR
7324            || TYPE_CODE (type) == TYPE_CODE_REF
7325            || TYPE_CODE (type) == TYPE_CODE_ENUM)
7326     {
7327       if (TYPE_LENGTH (type) <= 4)
7328         {
7329           /* Values of one word or less are zero/sign-extended and
7330              returned in r0.  */
7331           bfd_byte tmpbuf[INT_REGISTER_SIZE];
7332           LONGEST val = unpack_long (type, valbuf);
7333
7334           store_signed_integer (tmpbuf, INT_REGISTER_SIZE, byte_order, val);
7335           regcache_cooked_write (regs, ARM_A1_REGNUM, tmpbuf);
7336         }
7337       else
7338         {
7339           /* Integral values greater than one word are stored in consecutive
7340              registers starting with r0.  This will always be a multiple of
7341              the regiser size.  */
7342           int len = TYPE_LENGTH (type);
7343           int regno = ARM_A1_REGNUM;
7344
7345           while (len > 0)
7346             {
7347               regcache_cooked_write (regs, regno++, valbuf);
7348               len -= INT_REGISTER_SIZE;
7349               valbuf += INT_REGISTER_SIZE;
7350             }
7351         }
7352     }
7353   else
7354     {
7355       /* For a structure or union the behaviour is as if the value had
7356          been stored to word-aligned memory and then loaded into 
7357          registers with 32-bit load instruction(s).  */
7358       int len = TYPE_LENGTH (type);
7359       int regno = ARM_A1_REGNUM;
7360       bfd_byte tmpbuf[INT_REGISTER_SIZE];
7361
7362       while (len > 0)
7363         {
7364           memcpy (tmpbuf, valbuf,
7365                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
7366           regcache_cooked_write (regs, regno++, tmpbuf);
7367           len -= INT_REGISTER_SIZE;
7368           valbuf += INT_REGISTER_SIZE;
7369         }
7370     }
7371 }
7372
7373
7374 /* Handle function return values.  */
7375
7376 static enum return_value_convention
7377 arm_return_value (struct gdbarch *gdbarch, struct type *func_type,
7378                   struct type *valtype, struct regcache *regcache,
7379                   gdb_byte *readbuf, const gdb_byte *writebuf)
7380 {
7381   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
7382   enum arm_vfp_cprc_base_type vfp_base_type;
7383   int vfp_base_count;
7384
7385   if (arm_vfp_abi_for_function (gdbarch, func_type)
7386       && arm_vfp_call_candidate (valtype, &vfp_base_type, &vfp_base_count))
7387     {
7388       int reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
7389       int unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
7390       int i;
7391       for (i = 0; i < vfp_base_count; i++)
7392         {
7393           if (reg_char == 'q')
7394             {
7395               if (writebuf)
7396                 arm_neon_quad_write (gdbarch, regcache, i,
7397                                      writebuf + i * unit_length);
7398
7399               if (readbuf)
7400                 arm_neon_quad_read (gdbarch, regcache, i,
7401                                     readbuf + i * unit_length);
7402             }
7403           else
7404             {
7405               char name_buf[4];
7406               int regnum;
7407
7408               sprintf (name_buf, "%c%d", reg_char, i);
7409               regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
7410                                                     strlen (name_buf));
7411               if (writebuf)
7412                 regcache_cooked_write (regcache, regnum,
7413                                        writebuf + i * unit_length);
7414               if (readbuf)
7415                 regcache_cooked_read (regcache, regnum,
7416                                       readbuf + i * unit_length);
7417             }
7418         }
7419       return RETURN_VALUE_REGISTER_CONVENTION;
7420     }
7421
7422   if (TYPE_CODE (valtype) == TYPE_CODE_STRUCT
7423       || TYPE_CODE (valtype) == TYPE_CODE_UNION
7424       || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
7425     {
7426       if (tdep->struct_return == pcc_struct_return
7427           || arm_return_in_memory (gdbarch, valtype))
7428         return RETURN_VALUE_STRUCT_CONVENTION;
7429     }
7430
7431   if (writebuf)
7432     arm_store_return_value (valtype, regcache, writebuf);
7433
7434   if (readbuf)
7435     arm_extract_return_value (valtype, regcache, readbuf);
7436
7437   return RETURN_VALUE_REGISTER_CONVENTION;
7438 }
7439
7440
7441 static int
7442 arm_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
7443 {
7444   struct gdbarch *gdbarch = get_frame_arch (frame);
7445   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
7446   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
7447   CORE_ADDR jb_addr;
7448   char buf[INT_REGISTER_SIZE];
7449   
7450   jb_addr = get_frame_register_unsigned (frame, ARM_A1_REGNUM);
7451
7452   if (target_read_memory (jb_addr + tdep->jb_pc * tdep->jb_elt_size, buf,
7453                           INT_REGISTER_SIZE))
7454     return 0;
7455
7456   *pc = extract_unsigned_integer (buf, INT_REGISTER_SIZE, byte_order);
7457   return 1;
7458 }
7459
7460 /* Recognize GCC and GNU ld's trampolines.  If we are in a trampoline,
7461    return the target PC.  Otherwise return 0.  */
7462
7463 CORE_ADDR
7464 arm_skip_stub (struct frame_info *frame, CORE_ADDR pc)
7465 {
7466   char *name;
7467   int namelen;
7468   CORE_ADDR start_addr;
7469
7470   /* Find the starting address and name of the function containing the PC.  */
7471   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
7472     return 0;
7473
7474   /* If PC is in a Thumb call or return stub, return the address of the
7475      target PC, which is in a register.  The thunk functions are called
7476      _call_via_xx, where x is the register name.  The possible names
7477      are r0-r9, sl, fp, ip, sp, and lr.  ARM RealView has similar
7478      functions, named __ARM_call_via_r[0-7].  */
7479   if (strncmp (name, "_call_via_", 10) == 0
7480       || strncmp (name, "__ARM_call_via_", strlen ("__ARM_call_via_")) == 0)
7481     {
7482       /* Use the name suffix to determine which register contains the
7483          target PC.  */
7484       static char *table[15] =
7485       {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
7486        "r8", "r9", "sl", "fp", "ip", "sp", "lr"
7487       };
7488       int regno;
7489       int offset = strlen (name) - 2;
7490
7491       for (regno = 0; regno <= 14; regno++)
7492         if (strcmp (&name[offset], table[regno]) == 0)
7493           return get_frame_register_unsigned (frame, regno);
7494     }
7495
7496   /* GNU ld generates __foo_from_arm or __foo_from_thumb for
7497      non-interworking calls to foo.  We could decode the stubs
7498      to find the target but it's easier to use the symbol table.  */
7499   namelen = strlen (name);
7500   if (name[0] == '_' && name[1] == '_'
7501       && ((namelen > 2 + strlen ("_from_thumb")
7502            && strncmp (name + namelen - strlen ("_from_thumb"), "_from_thumb",
7503                        strlen ("_from_thumb")) == 0)
7504           || (namelen > 2 + strlen ("_from_arm")
7505               && strncmp (name + namelen - strlen ("_from_arm"), "_from_arm",
7506                           strlen ("_from_arm")) == 0)))
7507     {
7508       char *target_name;
7509       int target_len = namelen - 2;
7510       struct minimal_symbol *minsym;
7511       struct objfile *objfile;
7512       struct obj_section *sec;
7513
7514       if (name[namelen - 1] == 'b')
7515         target_len -= strlen ("_from_thumb");
7516       else
7517         target_len -= strlen ("_from_arm");
7518
7519       target_name = alloca (target_len + 1);
7520       memcpy (target_name, name + 2, target_len);
7521       target_name[target_len] = '\0';
7522
7523       sec = find_pc_section (pc);
7524       objfile = (sec == NULL) ? NULL : sec->objfile;
7525       minsym = lookup_minimal_symbol (target_name, NULL, objfile);
7526       if (minsym != NULL)
7527         return SYMBOL_VALUE_ADDRESS (minsym);
7528       else
7529         return 0;
7530     }
7531
7532   return 0;                     /* not a stub */
7533 }
7534
7535 static void
7536 set_arm_command (char *args, int from_tty)
7537 {
7538   printf_unfiltered (_("\
7539 \"set arm\" must be followed by an apporpriate subcommand.\n"));
7540   help_list (setarmcmdlist, "set arm ", all_commands, gdb_stdout);
7541 }
7542
7543 static void
7544 show_arm_command (char *args, int from_tty)
7545 {
7546   cmd_show_list (showarmcmdlist, from_tty, "");
7547 }
7548
7549 static void
7550 arm_update_current_architecture (void)
7551 {
7552   struct gdbarch_info info;
7553
7554   /* If the current architecture is not ARM, we have nothing to do.  */
7555   if (gdbarch_bfd_arch_info (target_gdbarch)->arch != bfd_arch_arm)
7556     return;
7557
7558   /* Update the architecture.  */
7559   gdbarch_info_init (&info);
7560
7561   if (!gdbarch_update_p (info))
7562     internal_error (__FILE__, __LINE__, _("could not update architecture"));
7563 }
7564
7565 static void
7566 set_fp_model_sfunc (char *args, int from_tty,
7567                     struct cmd_list_element *c)
7568 {
7569   enum arm_float_model fp_model;
7570
7571   for (fp_model = ARM_FLOAT_AUTO; fp_model != ARM_FLOAT_LAST; fp_model++)
7572     if (strcmp (current_fp_model, fp_model_strings[fp_model]) == 0)
7573       {
7574         arm_fp_model = fp_model;
7575         break;
7576       }
7577
7578   if (fp_model == ARM_FLOAT_LAST)
7579     internal_error (__FILE__, __LINE__, _("Invalid fp model accepted: %s."),
7580                     current_fp_model);
7581
7582   arm_update_current_architecture ();
7583 }
7584
7585 static void
7586 show_fp_model (struct ui_file *file, int from_tty,
7587                struct cmd_list_element *c, const char *value)
7588 {
7589   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
7590
7591   if (arm_fp_model == ARM_FLOAT_AUTO
7592       && gdbarch_bfd_arch_info (target_gdbarch)->arch == bfd_arch_arm)
7593     fprintf_filtered (file, _("\
7594 The current ARM floating point model is \"auto\" (currently \"%s\").\n"),
7595                       fp_model_strings[tdep->fp_model]);
7596   else
7597     fprintf_filtered (file, _("\
7598 The current ARM floating point model is \"%s\".\n"),
7599                       fp_model_strings[arm_fp_model]);
7600 }
7601
7602 static void
7603 arm_set_abi (char *args, int from_tty,
7604              struct cmd_list_element *c)
7605 {
7606   enum arm_abi_kind arm_abi;
7607
7608   for (arm_abi = ARM_ABI_AUTO; arm_abi != ARM_ABI_LAST; arm_abi++)
7609     if (strcmp (arm_abi_string, arm_abi_strings[arm_abi]) == 0)
7610       {
7611         arm_abi_global = arm_abi;
7612         break;
7613       }
7614
7615   if (arm_abi == ARM_ABI_LAST)
7616     internal_error (__FILE__, __LINE__, _("Invalid ABI accepted: %s."),
7617                     arm_abi_string);
7618
7619   arm_update_current_architecture ();
7620 }
7621
7622 static void
7623 arm_show_abi (struct ui_file *file, int from_tty,
7624              struct cmd_list_element *c, const char *value)
7625 {
7626   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
7627
7628   if (arm_abi_global == ARM_ABI_AUTO
7629       && gdbarch_bfd_arch_info (target_gdbarch)->arch == bfd_arch_arm)
7630     fprintf_filtered (file, _("\
7631 The current ARM ABI is \"auto\" (currently \"%s\").\n"),
7632                       arm_abi_strings[tdep->arm_abi]);
7633   else
7634     fprintf_filtered (file, _("The current ARM ABI is \"%s\".\n"),
7635                       arm_abi_string);
7636 }
7637
7638 static void
7639 arm_show_fallback_mode (struct ui_file *file, int from_tty,
7640                         struct cmd_list_element *c, const char *value)
7641 {
7642   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
7643
7644   fprintf_filtered (file,
7645                     _("The current execution mode assumed "
7646                       "(when symbols are unavailable) is \"%s\".\n"),
7647                     arm_fallback_mode_string);
7648 }
7649
7650 static void
7651 arm_show_force_mode (struct ui_file *file, int from_tty,
7652                      struct cmd_list_element *c, const char *value)
7653 {
7654   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
7655
7656   fprintf_filtered (file,
7657                     _("The current execution mode assumed "
7658                       "(even when symbols are available) is \"%s\".\n"),
7659                     arm_force_mode_string);
7660 }
7661
7662 /* If the user changes the register disassembly style used for info
7663    register and other commands, we have to also switch the style used
7664    in opcodes for disassembly output.  This function is run in the "set
7665    arm disassembly" command, and does that.  */
7666
7667 static void
7668 set_disassembly_style_sfunc (char *args, int from_tty,
7669                               struct cmd_list_element *c)
7670 {
7671   set_disassembly_style ();
7672 }
7673 \f
7674 /* Return the ARM register name corresponding to register I.  */
7675 static const char *
7676 arm_register_name (struct gdbarch *gdbarch, int i)
7677 {
7678   const int num_regs = gdbarch_num_regs (gdbarch);
7679
7680   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
7681       && i >= num_regs && i < num_regs + 32)
7682     {
7683       static const char *const vfp_pseudo_names[] = {
7684         "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
7685         "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
7686         "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
7687         "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
7688       };
7689
7690       return vfp_pseudo_names[i - num_regs];
7691     }
7692
7693   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
7694       && i >= num_regs + 32 && i < num_regs + 32 + 16)
7695     {
7696       static const char *const neon_pseudo_names[] = {
7697         "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
7698         "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15",
7699       };
7700
7701       return neon_pseudo_names[i - num_regs - 32];
7702     }
7703
7704   if (i >= ARRAY_SIZE (arm_register_names))
7705     /* These registers are only supported on targets which supply
7706        an XML description.  */
7707     return "";
7708
7709   return arm_register_names[i];
7710 }
7711
7712 static void
7713 set_disassembly_style (void)
7714 {
7715   int current;
7716
7717   /* Find the style that the user wants.  */
7718   for (current = 0; current < num_disassembly_options; current++)
7719     if (disassembly_style == valid_disassembly_styles[current])
7720       break;
7721   gdb_assert (current < num_disassembly_options);
7722
7723   /* Synchronize the disassembler.  */
7724   set_arm_regname_option (current);
7725 }
7726
7727 /* Test whether the coff symbol specific value corresponds to a Thumb
7728    function.  */
7729
7730 static int
7731 coff_sym_is_thumb (int val)
7732 {
7733   return (val == C_THUMBEXT
7734           || val == C_THUMBSTAT
7735           || val == C_THUMBEXTFUNC
7736           || val == C_THUMBSTATFUNC
7737           || val == C_THUMBLABEL);
7738 }
7739
7740 /* arm_coff_make_msymbol_special()
7741    arm_elf_make_msymbol_special()
7742    
7743    These functions test whether the COFF or ELF symbol corresponds to
7744    an address in thumb code, and set a "special" bit in a minimal
7745    symbol to indicate that it does.  */
7746    
7747 static void
7748 arm_elf_make_msymbol_special(asymbol *sym, struct minimal_symbol *msym)
7749 {
7750   /* Thumb symbols are of type STT_LOPROC, (synonymous with
7751      STT_ARM_TFUNC).  */
7752   if (ELF_ST_TYPE (((elf_symbol_type *)sym)->internal_elf_sym.st_info)
7753       == STT_LOPROC)
7754     MSYMBOL_SET_SPECIAL (msym);
7755 }
7756
7757 static void
7758 arm_coff_make_msymbol_special(int val, struct minimal_symbol *msym)
7759 {
7760   if (coff_sym_is_thumb (val))
7761     MSYMBOL_SET_SPECIAL (msym);
7762 }
7763
7764 static void
7765 arm_objfile_data_free (struct objfile *objfile, void *arg)
7766 {
7767   struct arm_per_objfile *data = arg;
7768   unsigned int i;
7769
7770   for (i = 0; i < objfile->obfd->section_count; i++)
7771     VEC_free (arm_mapping_symbol_s, data->section_maps[i]);
7772 }
7773
7774 static void
7775 arm_record_special_symbol (struct gdbarch *gdbarch, struct objfile *objfile,
7776                            asymbol *sym)
7777 {
7778   const char *name = bfd_asymbol_name (sym);
7779   struct arm_per_objfile *data;
7780   VEC(arm_mapping_symbol_s) **map_p;
7781   struct arm_mapping_symbol new_map_sym;
7782
7783   gdb_assert (name[0] == '$');
7784   if (name[1] != 'a' && name[1] != 't' && name[1] != 'd')
7785     return;
7786
7787   data = objfile_data (objfile, arm_objfile_data_key);
7788   if (data == NULL)
7789     {
7790       data = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7791                              struct arm_per_objfile);
7792       set_objfile_data (objfile, arm_objfile_data_key, data);
7793       data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
7794                                            objfile->obfd->section_count,
7795                                            VEC(arm_mapping_symbol_s) *);
7796     }
7797   map_p = &data->section_maps[bfd_get_section (sym)->index];
7798
7799   new_map_sym.value = sym->value;
7800   new_map_sym.type = name[1];
7801
7802   /* Assume that most mapping symbols appear in order of increasing
7803      value.  If they were randomly distributed, it would be faster to
7804      always push here and then sort at first use.  */
7805   if (!VEC_empty (arm_mapping_symbol_s, *map_p))
7806     {
7807       struct arm_mapping_symbol *prev_map_sym;
7808
7809       prev_map_sym = VEC_last (arm_mapping_symbol_s, *map_p);
7810       if (prev_map_sym->value >= sym->value)
7811         {
7812           unsigned int idx;
7813           idx = VEC_lower_bound (arm_mapping_symbol_s, *map_p, &new_map_sym,
7814                                  arm_compare_mapping_symbols);
7815           VEC_safe_insert (arm_mapping_symbol_s, *map_p, idx, &new_map_sym);
7816           return;
7817         }
7818     }
7819
7820   VEC_safe_push (arm_mapping_symbol_s, *map_p, &new_map_sym);
7821 }
7822
7823 static void
7824 arm_write_pc (struct regcache *regcache, CORE_ADDR pc)
7825 {
7826   struct gdbarch *gdbarch = get_regcache_arch (regcache);
7827   regcache_cooked_write_unsigned (regcache, ARM_PC_REGNUM, pc);
7828
7829   /* If necessary, set the T bit.  */
7830   if (arm_apcs_32)
7831     {
7832       ULONGEST val, t_bit;
7833       regcache_cooked_read_unsigned (regcache, ARM_PS_REGNUM, &val);
7834       t_bit = arm_psr_thumb_bit (gdbarch);
7835       if (arm_pc_is_thumb (gdbarch, pc))
7836         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
7837                                         val | t_bit);
7838       else
7839         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
7840                                         val & ~t_bit);
7841     }
7842 }
7843
7844 /* Read the contents of a NEON quad register, by reading from two
7845    double registers.  This is used to implement the quad pseudo
7846    registers, and for argument passing in case the quad registers are
7847    missing; vectors are passed in quad registers when using the VFP
7848    ABI, even if a NEON unit is not present.  REGNUM is the index of
7849    the quad register, in [0, 15].  */
7850
7851 static void
7852 arm_neon_quad_read (struct gdbarch *gdbarch, struct regcache *regcache,
7853                     int regnum, gdb_byte *buf)
7854 {
7855   char name_buf[4];
7856   gdb_byte reg_buf[8];
7857   int offset, double_regnum;
7858
7859   sprintf (name_buf, "d%d", regnum << 1);
7860   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
7861                                                strlen (name_buf));
7862
7863   /* d0 is always the least significant half of q0.  */
7864   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
7865     offset = 8;
7866   else
7867     offset = 0;
7868
7869   regcache_raw_read (regcache, double_regnum, reg_buf);
7870   memcpy (buf + offset, reg_buf, 8);
7871
7872   offset = 8 - offset;
7873   regcache_raw_read (regcache, double_regnum + 1, reg_buf);
7874   memcpy (buf + offset, reg_buf, 8);
7875 }
7876
7877 static void
7878 arm_pseudo_read (struct gdbarch *gdbarch, struct regcache *regcache,
7879                  int regnum, gdb_byte *buf)
7880 {
7881   const int num_regs = gdbarch_num_regs (gdbarch);
7882   char name_buf[4];
7883   gdb_byte reg_buf[8];
7884   int offset, double_regnum;
7885
7886   gdb_assert (regnum >= num_regs);
7887   regnum -= num_regs;
7888
7889   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
7890     /* Quad-precision register.  */
7891     arm_neon_quad_read (gdbarch, regcache, regnum - 32, buf);
7892   else
7893     {
7894       /* Single-precision register.  */
7895       gdb_assert (regnum < 32);
7896
7897       /* s0 is always the least significant half of d0.  */
7898       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
7899         offset = (regnum & 1) ? 0 : 4;
7900       else
7901         offset = (regnum & 1) ? 4 : 0;
7902
7903       sprintf (name_buf, "d%d", regnum >> 1);
7904       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
7905                                                    strlen (name_buf));
7906
7907       regcache_raw_read (regcache, double_regnum, reg_buf);
7908       memcpy (buf, reg_buf + offset, 4);
7909     }
7910 }
7911
7912 /* Store the contents of BUF to a NEON quad register, by writing to
7913    two double registers.  This is used to implement the quad pseudo
7914    registers, and for argument passing in case the quad registers are
7915    missing; vectors are passed in quad registers when using the VFP
7916    ABI, even if a NEON unit is not present.  REGNUM is the index
7917    of the quad register, in [0, 15].  */
7918
7919 static void
7920 arm_neon_quad_write (struct gdbarch *gdbarch, struct regcache *regcache,
7921                      int regnum, const gdb_byte *buf)
7922 {
7923   char name_buf[4];
7924   gdb_byte reg_buf[8];
7925   int offset, double_regnum;
7926
7927   sprintf (name_buf, "d%d", regnum << 1);
7928   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
7929                                                strlen (name_buf));
7930
7931   /* d0 is always the least significant half of q0.  */
7932   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
7933     offset = 8;
7934   else
7935     offset = 0;
7936
7937   regcache_raw_write (regcache, double_regnum, buf + offset);
7938   offset = 8 - offset;
7939   regcache_raw_write (regcache, double_regnum + 1, buf + offset);
7940 }
7941
7942 static void
7943 arm_pseudo_write (struct gdbarch *gdbarch, struct regcache *regcache,
7944                   int regnum, const gdb_byte *buf)
7945 {
7946   const int num_regs = gdbarch_num_regs (gdbarch);
7947   char name_buf[4];
7948   gdb_byte reg_buf[8];
7949   int offset, double_regnum;
7950
7951   gdb_assert (regnum >= num_regs);
7952   regnum -= num_regs;
7953
7954   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
7955     /* Quad-precision register.  */
7956     arm_neon_quad_write (gdbarch, regcache, regnum - 32, buf);
7957   else
7958     {
7959       /* Single-precision register.  */
7960       gdb_assert (regnum < 32);
7961
7962       /* s0 is always the least significant half of d0.  */
7963       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
7964         offset = (regnum & 1) ? 0 : 4;
7965       else
7966         offset = (regnum & 1) ? 4 : 0;
7967
7968       sprintf (name_buf, "d%d", regnum >> 1);
7969       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
7970                                                    strlen (name_buf));
7971
7972       regcache_raw_read (regcache, double_regnum, reg_buf);
7973       memcpy (reg_buf + offset, buf, 4);
7974       regcache_raw_write (regcache, double_regnum, reg_buf);
7975     }
7976 }
7977
7978 static struct value *
7979 value_of_arm_user_reg (struct frame_info *frame, const void *baton)
7980 {
7981   const int *reg_p = baton;
7982   return value_of_register (*reg_p, frame);
7983 }
7984 \f
7985 static enum gdb_osabi
7986 arm_elf_osabi_sniffer (bfd *abfd)
7987 {
7988   unsigned int elfosabi;
7989   enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
7990
7991   elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI];
7992
7993   if (elfosabi == ELFOSABI_ARM)
7994     /* GNU tools use this value.  Check note sections in this case,
7995        as well.  */
7996     bfd_map_over_sections (abfd,
7997                            generic_elf_osabi_sniff_abi_tag_sections, 
7998                            &osabi);
7999
8000   /* Anything else will be handled by the generic ELF sniffer.  */
8001   return osabi;
8002 }
8003
8004 static int
8005 arm_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
8006                           struct reggroup *group)
8007 {
8008   /* FPS register's type is INT, but belongs to float_reggroup.  Beside
8009      this, FPS register belongs to save_regroup, restore_reggroup, and
8010      all_reggroup, of course.  */
8011   if (regnum == ARM_FPS_REGNUM)
8012     return (group == float_reggroup
8013             || group == save_reggroup
8014             || group == restore_reggroup
8015             || group == all_reggroup);
8016   else
8017     return default_register_reggroup_p (gdbarch, regnum, group);
8018 }
8019
8020 \f
8021 /* Initialize the current architecture based on INFO.  If possible,
8022    re-use an architecture from ARCHES, which is a list of
8023    architectures already created during this debugging session.
8024
8025    Called e.g. at program startup, when reading a core file, and when
8026    reading a binary file.  */
8027
8028 static struct gdbarch *
8029 arm_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
8030 {
8031   struct gdbarch_tdep *tdep;
8032   struct gdbarch *gdbarch;
8033   struct gdbarch_list *best_arch;
8034   enum arm_abi_kind arm_abi = arm_abi_global;
8035   enum arm_float_model fp_model = arm_fp_model;
8036   struct tdesc_arch_data *tdesc_data = NULL;
8037   int i, is_m = 0;
8038   int have_vfp_registers = 0, have_vfp_pseudos = 0, have_neon_pseudos = 0;
8039   int have_neon = 0;
8040   int have_fpa_registers = 1;
8041   const struct target_desc *tdesc = info.target_desc;
8042
8043   /* If we have an object to base this architecture on, try to determine
8044      its ABI.  */
8045
8046   if (arm_abi == ARM_ABI_AUTO && info.abfd != NULL)
8047     {
8048       int ei_osabi, e_flags;
8049
8050       switch (bfd_get_flavour (info.abfd))
8051         {
8052         case bfd_target_aout_flavour:
8053           /* Assume it's an old APCS-style ABI.  */
8054           arm_abi = ARM_ABI_APCS;
8055           break;
8056
8057         case bfd_target_coff_flavour:
8058           /* Assume it's an old APCS-style ABI.  */
8059           /* XXX WinCE?  */
8060           arm_abi = ARM_ABI_APCS;
8061           break;
8062
8063         case bfd_target_elf_flavour:
8064           ei_osabi = elf_elfheader (info.abfd)->e_ident[EI_OSABI];
8065           e_flags = elf_elfheader (info.abfd)->e_flags;
8066
8067           if (ei_osabi == ELFOSABI_ARM)
8068             {
8069               /* GNU tools used to use this value, but do not for EABI
8070                  objects.  There's nowhere to tag an EABI version
8071                  anyway, so assume APCS.  */
8072               arm_abi = ARM_ABI_APCS;
8073             }
8074           else if (ei_osabi == ELFOSABI_NONE)
8075             {
8076               int eabi_ver = EF_ARM_EABI_VERSION (e_flags);
8077               int attr_arch, attr_profile;
8078
8079               switch (eabi_ver)
8080                 {
8081                 case EF_ARM_EABI_UNKNOWN:
8082                   /* Assume GNU tools.  */
8083                   arm_abi = ARM_ABI_APCS;
8084                   break;
8085
8086                 case EF_ARM_EABI_VER4:
8087                 case EF_ARM_EABI_VER5:
8088                   arm_abi = ARM_ABI_AAPCS;
8089                   /* EABI binaries default to VFP float ordering.
8090                      They may also contain build attributes that can
8091                      be used to identify if the VFP argument-passing
8092                      ABI is in use.  */
8093                   if (fp_model == ARM_FLOAT_AUTO)
8094                     {
8095 #ifdef HAVE_ELF
8096                       switch (bfd_elf_get_obj_attr_int (info.abfd,
8097                                                         OBJ_ATTR_PROC,
8098                                                         Tag_ABI_VFP_args))
8099                         {
8100                         case 0:
8101                           /* "The user intended FP parameter/result
8102                              passing to conform to AAPCS, base
8103                              variant".  */
8104                           fp_model = ARM_FLOAT_SOFT_VFP;
8105                           break;
8106                         case 1:
8107                           /* "The user intended FP parameter/result
8108                              passing to conform to AAPCS, VFP
8109                              variant".  */
8110                           fp_model = ARM_FLOAT_VFP;
8111                           break;
8112                         case 2:
8113                           /* "The user intended FP parameter/result
8114                              passing to conform to tool chain-specific
8115                              conventions" - we don't know any such
8116                              conventions, so leave it as "auto".  */
8117                           break;
8118                         default:
8119                           /* Attribute value not mentioned in the
8120                              October 2008 ABI, so leave it as
8121                              "auto".  */
8122                           break;
8123                         }
8124 #else
8125                       fp_model = ARM_FLOAT_SOFT_VFP;
8126 #endif
8127                     }
8128                   break;
8129
8130                 default:
8131                   /* Leave it as "auto".  */
8132                   warning (_("unknown ARM EABI version 0x%x"), eabi_ver);
8133                   break;
8134                 }
8135
8136 #ifdef HAVE_ELF
8137               /* Detect M-profile programs.  This only works if the
8138                  executable file includes build attributes; GCC does
8139                  copy them to the executable, but e.g. RealView does
8140                  not.  */
8141               attr_arch = bfd_elf_get_obj_attr_int (info.abfd, OBJ_ATTR_PROC,
8142                                                     Tag_CPU_arch);
8143               attr_profile = bfd_elf_get_obj_attr_int (info.abfd,
8144                                                        OBJ_ATTR_PROC,
8145                                                        Tag_CPU_arch_profile);
8146               /* GCC specifies the profile for v6-M; RealView only
8147                  specifies the profile for architectures starting with
8148                  V7 (as opposed to architectures with a tag
8149                  numerically greater than TAG_CPU_ARCH_V7).  */
8150               if (!tdesc_has_registers (tdesc)
8151                   && (attr_arch == TAG_CPU_ARCH_V6_M
8152                       || attr_arch == TAG_CPU_ARCH_V6S_M
8153                       || attr_profile == 'M'))
8154                 tdesc = tdesc_arm_with_m;
8155 #endif
8156             }
8157
8158           if (fp_model == ARM_FLOAT_AUTO)
8159             {
8160               int e_flags = elf_elfheader (info.abfd)->e_flags;
8161
8162               switch (e_flags & (EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT))
8163                 {
8164                 case 0:
8165                   /* Leave it as "auto".  Strictly speaking this case
8166                      means FPA, but almost nobody uses that now, and
8167                      many toolchains fail to set the appropriate bits
8168                      for the floating-point model they use.  */
8169                   break;
8170                 case EF_ARM_SOFT_FLOAT:
8171                   fp_model = ARM_FLOAT_SOFT_FPA;
8172                   break;
8173                 case EF_ARM_VFP_FLOAT:
8174                   fp_model = ARM_FLOAT_VFP;
8175                   break;
8176                 case EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT:
8177                   fp_model = ARM_FLOAT_SOFT_VFP;
8178                   break;
8179                 }
8180             }
8181
8182           if (e_flags & EF_ARM_BE8)
8183             info.byte_order_for_code = BFD_ENDIAN_LITTLE;
8184
8185           break;
8186
8187         default:
8188           /* Leave it as "auto".  */
8189           break;
8190         }
8191     }
8192
8193   /* Check any target description for validity.  */
8194   if (tdesc_has_registers (tdesc))
8195     {
8196       /* For most registers we require GDB's default names; but also allow
8197          the numeric names for sp / lr / pc, as a convenience.  */
8198       static const char *const arm_sp_names[] = { "r13", "sp", NULL };
8199       static const char *const arm_lr_names[] = { "r14", "lr", NULL };
8200       static const char *const arm_pc_names[] = { "r15", "pc", NULL };
8201
8202       const struct tdesc_feature *feature;
8203       int valid_p;
8204
8205       feature = tdesc_find_feature (tdesc,
8206                                     "org.gnu.gdb.arm.core");
8207       if (feature == NULL)
8208         {
8209           feature = tdesc_find_feature (tdesc,
8210                                         "org.gnu.gdb.arm.m-profile");
8211           if (feature == NULL)
8212             return NULL;
8213           else
8214             is_m = 1;
8215         }
8216
8217       tdesc_data = tdesc_data_alloc ();
8218
8219       valid_p = 1;
8220       for (i = 0; i < ARM_SP_REGNUM; i++)
8221         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
8222                                             arm_register_names[i]);
8223       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
8224                                                   ARM_SP_REGNUM,
8225                                                   arm_sp_names);
8226       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
8227                                                   ARM_LR_REGNUM,
8228                                                   arm_lr_names);
8229       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
8230                                                   ARM_PC_REGNUM,
8231                                                   arm_pc_names);
8232       if (is_m)
8233         valid_p &= tdesc_numbered_register (feature, tdesc_data,
8234                                             ARM_PS_REGNUM, "xpsr");
8235       else
8236         valid_p &= tdesc_numbered_register (feature, tdesc_data,
8237                                             ARM_PS_REGNUM, "cpsr");
8238
8239       if (!valid_p)
8240         {
8241           tdesc_data_cleanup (tdesc_data);
8242           return NULL;
8243         }
8244
8245       feature = tdesc_find_feature (tdesc,
8246                                     "org.gnu.gdb.arm.fpa");
8247       if (feature != NULL)
8248         {
8249           valid_p = 1;
8250           for (i = ARM_F0_REGNUM; i <= ARM_FPS_REGNUM; i++)
8251             valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
8252                                                 arm_register_names[i]);
8253           if (!valid_p)
8254             {
8255               tdesc_data_cleanup (tdesc_data);
8256               return NULL;
8257             }
8258         }
8259       else
8260         have_fpa_registers = 0;
8261
8262       feature = tdesc_find_feature (tdesc,
8263                                     "org.gnu.gdb.xscale.iwmmxt");
8264       if (feature != NULL)
8265         {
8266           static const char *const iwmmxt_names[] = {
8267             "wR0", "wR1", "wR2", "wR3", "wR4", "wR5", "wR6", "wR7",
8268             "wR8", "wR9", "wR10", "wR11", "wR12", "wR13", "wR14", "wR15",
8269             "wCID", "wCon", "wCSSF", "wCASF", "", "", "", "",
8270             "wCGR0", "wCGR1", "wCGR2", "wCGR3", "", "", "", "",
8271           };
8272
8273           valid_p = 1;
8274           for (i = ARM_WR0_REGNUM; i <= ARM_WR15_REGNUM; i++)
8275             valid_p
8276               &= tdesc_numbered_register (feature, tdesc_data, i,
8277                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
8278
8279           /* Check for the control registers, but do not fail if they
8280              are missing.  */
8281           for (i = ARM_WC0_REGNUM; i <= ARM_WCASF_REGNUM; i++)
8282             tdesc_numbered_register (feature, tdesc_data, i,
8283                                      iwmmxt_names[i - ARM_WR0_REGNUM]);
8284
8285           for (i = ARM_WCGR0_REGNUM; i <= ARM_WCGR3_REGNUM; i++)
8286             valid_p
8287               &= tdesc_numbered_register (feature, tdesc_data, i,
8288                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
8289
8290           if (!valid_p)
8291             {
8292               tdesc_data_cleanup (tdesc_data);
8293               return NULL;
8294             }
8295         }
8296
8297       /* If we have a VFP unit, check whether the single precision registers
8298          are present.  If not, then we will synthesize them as pseudo
8299          registers.  */
8300       feature = tdesc_find_feature (tdesc,
8301                                     "org.gnu.gdb.arm.vfp");
8302       if (feature != NULL)
8303         {
8304           static const char *const vfp_double_names[] = {
8305             "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
8306             "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
8307             "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
8308             "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
8309           };
8310
8311           /* Require the double precision registers.  There must be either
8312              16 or 32.  */
8313           valid_p = 1;
8314           for (i = 0; i < 32; i++)
8315             {
8316               valid_p &= tdesc_numbered_register (feature, tdesc_data,
8317                                                   ARM_D0_REGNUM + i,
8318                                                   vfp_double_names[i]);
8319               if (!valid_p)
8320                 break;
8321             }
8322
8323           if (!valid_p && i != 16)
8324             {
8325               tdesc_data_cleanup (tdesc_data);
8326               return NULL;
8327             }
8328
8329           if (tdesc_unnumbered_register (feature, "s0") == 0)
8330             have_vfp_pseudos = 1;
8331
8332           have_vfp_registers = 1;
8333
8334           /* If we have VFP, also check for NEON.  The architecture allows
8335              NEON without VFP (integer vector operations only), but GDB
8336              does not support that.  */
8337           feature = tdesc_find_feature (tdesc,
8338                                         "org.gnu.gdb.arm.neon");
8339           if (feature != NULL)
8340             {
8341               /* NEON requires 32 double-precision registers.  */
8342               if (i != 32)
8343                 {
8344                   tdesc_data_cleanup (tdesc_data);
8345                   return NULL;
8346                 }
8347
8348               /* If there are quad registers defined by the stub, use
8349                  their type; otherwise (normally) provide them with
8350                  the default type.  */
8351               if (tdesc_unnumbered_register (feature, "q0") == 0)
8352                 have_neon_pseudos = 1;
8353
8354               have_neon = 1;
8355             }
8356         }
8357     }
8358
8359   /* If there is already a candidate, use it.  */
8360   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
8361        best_arch != NULL;
8362        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
8363     {
8364       if (arm_abi != ARM_ABI_AUTO
8365           && arm_abi != gdbarch_tdep (best_arch->gdbarch)->arm_abi)
8366         continue;
8367
8368       if (fp_model != ARM_FLOAT_AUTO
8369           && fp_model != gdbarch_tdep (best_arch->gdbarch)->fp_model)
8370         continue;
8371
8372       /* There are various other properties in tdep that we do not
8373          need to check here: those derived from a target description,
8374          since gdbarches with a different target description are
8375          automatically disqualified.  */
8376
8377       /* Do check is_m, though, since it might come from the binary.  */
8378       if (is_m != gdbarch_tdep (best_arch->gdbarch)->is_m)
8379         continue;
8380
8381       /* Found a match.  */
8382       break;
8383     }
8384
8385   if (best_arch != NULL)
8386     {
8387       if (tdesc_data != NULL)
8388         tdesc_data_cleanup (tdesc_data);
8389       return best_arch->gdbarch;
8390     }
8391
8392   tdep = xcalloc (1, sizeof (struct gdbarch_tdep));
8393   gdbarch = gdbarch_alloc (&info, tdep);
8394
8395   /* Record additional information about the architecture we are defining.
8396      These are gdbarch discriminators, like the OSABI.  */
8397   tdep->arm_abi = arm_abi;
8398   tdep->fp_model = fp_model;
8399   tdep->is_m = is_m;
8400   tdep->have_fpa_registers = have_fpa_registers;
8401   tdep->have_vfp_registers = have_vfp_registers;
8402   tdep->have_vfp_pseudos = have_vfp_pseudos;
8403   tdep->have_neon_pseudos = have_neon_pseudos;
8404   tdep->have_neon = have_neon;
8405
8406   /* Breakpoints.  */
8407   switch (info.byte_order_for_code)
8408     {
8409     case BFD_ENDIAN_BIG:
8410       tdep->arm_breakpoint = arm_default_arm_be_breakpoint;
8411       tdep->arm_breakpoint_size = sizeof (arm_default_arm_be_breakpoint);
8412       tdep->thumb_breakpoint = arm_default_thumb_be_breakpoint;
8413       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_be_breakpoint);
8414
8415       break;
8416
8417     case BFD_ENDIAN_LITTLE:
8418       tdep->arm_breakpoint = arm_default_arm_le_breakpoint;
8419       tdep->arm_breakpoint_size = sizeof (arm_default_arm_le_breakpoint);
8420       tdep->thumb_breakpoint = arm_default_thumb_le_breakpoint;
8421       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_le_breakpoint);
8422
8423       break;
8424
8425     default:
8426       internal_error (__FILE__, __LINE__,
8427                       _("arm_gdbarch_init: bad byte order for float format"));
8428     }
8429
8430   /* On ARM targets char defaults to unsigned.  */
8431   set_gdbarch_char_signed (gdbarch, 0);
8432
8433   /* Note: for displaced stepping, this includes the breakpoint, and one word
8434      of additional scratch space.  This setting isn't used for anything beside
8435      displaced stepping at present.  */
8436   set_gdbarch_max_insn_length (gdbarch, 4 * DISPLACED_MODIFIED_INSNS);
8437
8438   /* This should be low enough for everything.  */
8439   tdep->lowest_pc = 0x20;
8440   tdep->jb_pc = -1;     /* Longjump support not enabled by default.  */
8441
8442   /* The default, for both APCS and AAPCS, is to return small
8443      structures in registers.  */
8444   tdep->struct_return = reg_struct_return;
8445
8446   set_gdbarch_push_dummy_call (gdbarch, arm_push_dummy_call);
8447   set_gdbarch_frame_align (gdbarch, arm_frame_align);
8448
8449   set_gdbarch_write_pc (gdbarch, arm_write_pc);
8450
8451   /* Frame handling.  */
8452   set_gdbarch_dummy_id (gdbarch, arm_dummy_id);
8453   set_gdbarch_unwind_pc (gdbarch, arm_unwind_pc);
8454   set_gdbarch_unwind_sp (gdbarch, arm_unwind_sp);
8455
8456   frame_base_set_default (gdbarch, &arm_normal_base);
8457
8458   /* Address manipulation.  */
8459   set_gdbarch_smash_text_address (gdbarch, arm_smash_text_address);
8460   set_gdbarch_addr_bits_remove (gdbarch, arm_addr_bits_remove);
8461
8462   /* Advance PC across function entry code.  */
8463   set_gdbarch_skip_prologue (gdbarch, arm_skip_prologue);
8464
8465   /* Detect whether PC is in function epilogue.  */
8466   set_gdbarch_in_function_epilogue_p (gdbarch, arm_in_function_epilogue_p);
8467
8468   /* Skip trampolines.  */
8469   set_gdbarch_skip_trampoline_code (gdbarch, arm_skip_stub);
8470
8471   /* The stack grows downward.  */
8472   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
8473
8474   /* Breakpoint manipulation.  */
8475   set_gdbarch_breakpoint_from_pc (gdbarch, arm_breakpoint_from_pc);
8476   set_gdbarch_remote_breakpoint_from_pc (gdbarch,
8477                                          arm_remote_breakpoint_from_pc);
8478
8479   /* Information about registers, etc.  */
8480   set_gdbarch_sp_regnum (gdbarch, ARM_SP_REGNUM);
8481   set_gdbarch_pc_regnum (gdbarch, ARM_PC_REGNUM);
8482   set_gdbarch_num_regs (gdbarch, ARM_NUM_REGS);
8483   set_gdbarch_register_type (gdbarch, arm_register_type);
8484   set_gdbarch_register_reggroup_p (gdbarch, arm_register_reggroup_p);
8485
8486   /* This "info float" is FPA-specific.  Use the generic version if we
8487      do not have FPA.  */
8488   if (gdbarch_tdep (gdbarch)->have_fpa_registers)
8489     set_gdbarch_print_float_info (gdbarch, arm_print_float_info);
8490
8491   /* Internal <-> external register number maps.  */
8492   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, arm_dwarf_reg_to_regnum);
8493   set_gdbarch_register_sim_regno (gdbarch, arm_register_sim_regno);
8494
8495   set_gdbarch_register_name (gdbarch, arm_register_name);
8496
8497   /* Returning results.  */
8498   set_gdbarch_return_value (gdbarch, arm_return_value);
8499
8500   /* Disassembly.  */
8501   set_gdbarch_print_insn (gdbarch, gdb_print_insn_arm);
8502
8503   /* Minsymbol frobbing.  */
8504   set_gdbarch_elf_make_msymbol_special (gdbarch, arm_elf_make_msymbol_special);
8505   set_gdbarch_coff_make_msymbol_special (gdbarch,
8506                                          arm_coff_make_msymbol_special);
8507   set_gdbarch_record_special_symbol (gdbarch, arm_record_special_symbol);
8508
8509   /* Thumb-2 IT block support.  */
8510   set_gdbarch_adjust_breakpoint_address (gdbarch,
8511                                          arm_adjust_breakpoint_address);
8512
8513   /* Virtual tables.  */
8514   set_gdbarch_vbit_in_delta (gdbarch, 1);
8515
8516   /* Hook in the ABI-specific overrides, if they have been registered.  */
8517   gdbarch_init_osabi (info, gdbarch);
8518
8519   dwarf2_frame_set_init_reg (gdbarch, arm_dwarf2_frame_init_reg);
8520
8521   /* Add some default predicates.  */
8522   frame_unwind_append_unwinder (gdbarch, &arm_stub_unwind);
8523   dwarf2_append_unwinders (gdbarch);
8524   frame_unwind_append_unwinder (gdbarch, &arm_exidx_unwind);
8525   frame_unwind_append_unwinder (gdbarch, &arm_prologue_unwind);
8526
8527   /* Now we have tuned the configuration, set a few final things,
8528      based on what the OS ABI has told us.  */
8529
8530   /* If the ABI is not otherwise marked, assume the old GNU APCS.  EABI
8531      binaries are always marked.  */
8532   if (tdep->arm_abi == ARM_ABI_AUTO)
8533     tdep->arm_abi = ARM_ABI_APCS;
8534
8535   /* We used to default to FPA for generic ARM, but almost nobody
8536      uses that now, and we now provide a way for the user to force
8537      the model.  So default to the most useful variant.  */
8538   if (tdep->fp_model == ARM_FLOAT_AUTO)
8539     tdep->fp_model = ARM_FLOAT_SOFT_FPA;
8540
8541   if (tdep->jb_pc >= 0)
8542     set_gdbarch_get_longjmp_target (gdbarch, arm_get_longjmp_target);
8543
8544   /* Floating point sizes and format.  */
8545   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
8546   if (tdep->fp_model == ARM_FLOAT_SOFT_FPA || tdep->fp_model == ARM_FLOAT_FPA)
8547     {
8548       set_gdbarch_double_format
8549         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
8550       set_gdbarch_long_double_format
8551         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
8552     }
8553   else
8554     {
8555       set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
8556       set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double);
8557     }
8558
8559   if (have_vfp_pseudos)
8560     {
8561       /* NOTE: These are the only pseudo registers used by
8562          the ARM target at the moment.  If more are added, a
8563          little more care in numbering will be needed.  */
8564
8565       int num_pseudos = 32;
8566       if (have_neon_pseudos)
8567         num_pseudos += 16;
8568       set_gdbarch_num_pseudo_regs (gdbarch, num_pseudos);
8569       set_gdbarch_pseudo_register_read (gdbarch, arm_pseudo_read);
8570       set_gdbarch_pseudo_register_write (gdbarch, arm_pseudo_write);
8571     }
8572
8573   if (tdesc_data)
8574     {
8575       set_tdesc_pseudo_register_name (gdbarch, arm_register_name);
8576
8577       tdesc_use_registers (gdbarch, tdesc, tdesc_data);
8578
8579       /* Override tdesc_register_type to adjust the types of VFP
8580          registers for NEON.  */
8581       set_gdbarch_register_type (gdbarch, arm_register_type);
8582     }
8583
8584   /* Add standard register aliases.  We add aliases even for those
8585      nanes which are used by the current architecture - it's simpler,
8586      and does no harm, since nothing ever lists user registers.  */
8587   for (i = 0; i < ARRAY_SIZE (arm_register_aliases); i++)
8588     user_reg_add (gdbarch, arm_register_aliases[i].name,
8589                   value_of_arm_user_reg, &arm_register_aliases[i].regnum);
8590
8591   return gdbarch;
8592 }
8593
8594 static void
8595 arm_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
8596 {
8597   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8598
8599   if (tdep == NULL)
8600     return;
8601
8602   fprintf_unfiltered (file, _("arm_dump_tdep: Lowest pc = 0x%lx"),
8603                       (unsigned long) tdep->lowest_pc);
8604 }
8605
8606 extern initialize_file_ftype _initialize_arm_tdep; /* -Wmissing-prototypes */
8607
8608 void
8609 _initialize_arm_tdep (void)
8610 {
8611   struct ui_file *stb;
8612   long length;
8613   struct cmd_list_element *new_set, *new_show;
8614   const char *setname;
8615   const char *setdesc;
8616   const char *const *regnames;
8617   int numregs, i, j;
8618   static char *helptext;
8619   char regdesc[1024], *rdptr = regdesc;
8620   size_t rest = sizeof (regdesc);
8621
8622   gdbarch_register (bfd_arch_arm, arm_gdbarch_init, arm_dump_tdep);
8623
8624   arm_objfile_data_key
8625     = register_objfile_data_with_cleanup (NULL, arm_objfile_data_free);
8626
8627   /* Add ourselves to objfile event chain.  */
8628   observer_attach_new_objfile (arm_exidx_new_objfile);
8629   arm_exidx_data_key
8630     = register_objfile_data_with_cleanup (NULL, arm_exidx_data_free);
8631
8632   /* Register an ELF OS ABI sniffer for ARM binaries.  */
8633   gdbarch_register_osabi_sniffer (bfd_arch_arm,
8634                                   bfd_target_elf_flavour,
8635                                   arm_elf_osabi_sniffer);
8636
8637   /* Initialize the standard target descriptions.  */
8638   initialize_tdesc_arm_with_m ();
8639
8640   /* Get the number of possible sets of register names defined in opcodes.  */
8641   num_disassembly_options = get_arm_regname_num_options ();
8642
8643   /* Add root prefix command for all "set arm"/"show arm" commands.  */
8644   add_prefix_cmd ("arm", no_class, set_arm_command,
8645                   _("Various ARM-specific commands."),
8646                   &setarmcmdlist, "set arm ", 0, &setlist);
8647
8648   add_prefix_cmd ("arm", no_class, show_arm_command,
8649                   _("Various ARM-specific commands."),
8650                   &showarmcmdlist, "show arm ", 0, &showlist);
8651
8652   /* Sync the opcode insn printer with our register viewer.  */
8653   parse_arm_disassembler_option ("reg-names-std");
8654
8655   /* Initialize the array that will be passed to
8656      add_setshow_enum_cmd().  */
8657   valid_disassembly_styles
8658     = xmalloc ((num_disassembly_options + 1) * sizeof (char *));
8659   for (i = 0; i < num_disassembly_options; i++)
8660     {
8661       numregs = get_arm_regnames (i, &setname, &setdesc, &regnames);
8662       valid_disassembly_styles[i] = setname;
8663       length = snprintf (rdptr, rest, "%s - %s\n", setname, setdesc);
8664       rdptr += length;
8665       rest -= length;
8666       /* When we find the default names, tell the disassembler to use
8667          them.  */
8668       if (!strcmp (setname, "std"))
8669         {
8670           disassembly_style = setname;
8671           set_arm_regname_option (i);
8672         }
8673     }
8674   /* Mark the end of valid options.  */
8675   valid_disassembly_styles[num_disassembly_options] = NULL;
8676
8677   /* Create the help text.  */
8678   stb = mem_fileopen ();
8679   fprintf_unfiltered (stb, "%s%s%s",
8680                       _("The valid values are:\n"),
8681                       regdesc,
8682                       _("The default is \"std\"."));
8683   helptext = ui_file_xstrdup (stb, NULL);
8684   ui_file_delete (stb);
8685
8686   add_setshow_enum_cmd("disassembler", no_class,
8687                        valid_disassembly_styles, &disassembly_style,
8688                        _("Set the disassembly style."),
8689                        _("Show the disassembly style."),
8690                        helptext,
8691                        set_disassembly_style_sfunc,
8692                        NULL, /* FIXME: i18n: The disassembly style is
8693                                 \"%s\".  */
8694                        &setarmcmdlist, &showarmcmdlist);
8695
8696   add_setshow_boolean_cmd ("apcs32", no_class, &arm_apcs_32,
8697                            _("Set usage of ARM 32-bit mode."),
8698                            _("Show usage of ARM 32-bit mode."),
8699                            _("When off, a 26-bit PC will be used."),
8700                            NULL,
8701                            NULL, /* FIXME: i18n: Usage of ARM 32-bit
8702                                     mode is %s.  */
8703                            &setarmcmdlist, &showarmcmdlist);
8704
8705   /* Add a command to allow the user to force the FPU model.  */
8706   add_setshow_enum_cmd ("fpu", no_class, fp_model_strings, &current_fp_model,
8707                         _("Set the floating point type."),
8708                         _("Show the floating point type."),
8709                         _("auto - Determine the FP typefrom the OS-ABI.\n\
8710 softfpa - Software FP, mixed-endian doubles on little-endian ARMs.\n\
8711 fpa - FPA co-processor (GCC compiled).\n\
8712 softvfp - Software FP with pure-endian doubles.\n\
8713 vfp - VFP co-processor."),
8714                         set_fp_model_sfunc, show_fp_model,
8715                         &setarmcmdlist, &showarmcmdlist);
8716
8717   /* Add a command to allow the user to force the ABI.  */
8718   add_setshow_enum_cmd ("abi", class_support, arm_abi_strings, &arm_abi_string,
8719                         _("Set the ABI."),
8720                         _("Show the ABI."),
8721                         NULL, arm_set_abi, arm_show_abi,
8722                         &setarmcmdlist, &showarmcmdlist);
8723
8724   /* Add two commands to allow the user to force the assumed
8725      execution mode.  */
8726   add_setshow_enum_cmd ("fallback-mode", class_support,
8727                         arm_mode_strings, &arm_fallback_mode_string,
8728                         _("Set the mode assumed when symbols are unavailable."),
8729                         _("Show the mode assumed when symbols are unavailable."),
8730                         NULL, NULL, arm_show_fallback_mode,
8731                         &setarmcmdlist, &showarmcmdlist);
8732   add_setshow_enum_cmd ("force-mode", class_support,
8733                         arm_mode_strings, &arm_force_mode_string,
8734                         _("Set the mode assumed even when symbols are available."),
8735                         _("Show the mode assumed even when symbols are available."),
8736                         NULL, NULL, arm_show_force_mode,
8737                         &setarmcmdlist, &showarmcmdlist);
8738
8739   /* Debugging flag.  */
8740   add_setshow_boolean_cmd ("arm", class_maintenance, &arm_debug,
8741                            _("Set ARM debugging."),
8742                            _("Show ARM debugging."),
8743                            _("When on, arm-specific debugging is enabled."),
8744                            NULL,
8745                            NULL, /* FIXME: i18n: "ARM debugging is %s.  */
8746                            &setdebuglist, &showdebuglist);
8747 }