* arm-tdep.c (arm_stub_unwind_sniffer): Add comment.
[external/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
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 "doublest.h"
33 #include "value.h"
34 #include "arch-utils.h"
35 #include "osabi.h"
36 #include "frame-unwind.h"
37 #include "frame-base.h"
38 #include "trad-frame.h"
39 #include "objfiles.h"
40 #include "dwarf2-frame.h"
41 #include "gdbtypes.h"
42 #include "prologue-value.h"
43 #include "target-descriptions.h"
44 #include "user-regs.h"
45
46 #include "arm-tdep.h"
47 #include "gdb/sim-arm.h"
48
49 #include "elf-bfd.h"
50 #include "coff/internal.h"
51 #include "elf/arm.h"
52
53 #include "gdb_assert.h"
54 #include "vec.h"
55
56 static int arm_debug;
57
58 /* Macros for setting and testing a bit in a minimal symbol that marks
59    it as Thumb function.  The MSB of the minimal symbol's "info" field
60    is used for this purpose.
61
62    MSYMBOL_SET_SPECIAL  Actually sets the "special" bit.
63    MSYMBOL_IS_SPECIAL   Tests the "special" bit in a minimal symbol.  */
64
65 #define MSYMBOL_SET_SPECIAL(msym)                                       \
66         MSYMBOL_TARGET_FLAG_1 (msym) = 1
67
68 #define MSYMBOL_IS_SPECIAL(msym)                                \
69         MSYMBOL_TARGET_FLAG_1 (msym)
70
71 /* Per-objfile data used for mapping symbols.  */
72 static const struct objfile_data *arm_objfile_data_key;
73
74 struct arm_mapping_symbol
75 {
76   bfd_vma value;
77   char type;
78 };
79 typedef struct arm_mapping_symbol arm_mapping_symbol_s;
80 DEF_VEC_O(arm_mapping_symbol_s);
81
82 struct arm_per_objfile
83 {
84   VEC(arm_mapping_symbol_s) **section_maps;
85 };
86
87 /* The list of available "set arm ..." and "show arm ..." commands.  */
88 static struct cmd_list_element *setarmcmdlist = NULL;
89 static struct cmd_list_element *showarmcmdlist = NULL;
90
91 /* The type of floating-point to use.  Keep this in sync with enum
92    arm_float_model, and the help string in _initialize_arm_tdep.  */
93 static const char *fp_model_strings[] =
94 {
95   "auto",
96   "softfpa",
97   "fpa",
98   "softvfp",
99   "vfp",
100   NULL
101 };
102
103 /* A variable that can be configured by the user.  */
104 static enum arm_float_model arm_fp_model = ARM_FLOAT_AUTO;
105 static const char *current_fp_model = "auto";
106
107 /* The ABI to use.  Keep this in sync with arm_abi_kind.  */
108 static const char *arm_abi_strings[] =
109 {
110   "auto",
111   "APCS",
112   "AAPCS",
113   NULL
114 };
115
116 /* A variable that can be configured by the user.  */
117 static enum arm_abi_kind arm_abi_global = ARM_ABI_AUTO;
118 static const char *arm_abi_string = "auto";
119
120 /* The execution mode to assume.  */
121 static const char *arm_mode_strings[] =
122   {
123     "auto",
124     "arm",
125     "thumb"
126   };
127
128 static const char *arm_fallback_mode_string = "auto";
129 static const char *arm_force_mode_string = "auto";
130
131 /* Number of different reg name sets (options).  */
132 static int num_disassembly_options;
133
134 /* The standard register names, and all the valid aliases for them.  */
135 static const struct
136 {
137   const char *name;
138   int regnum;
139 } arm_register_aliases[] = {
140   /* Basic register numbers.  */
141   { "r0", 0 },
142   { "r1", 1 },
143   { "r2", 2 },
144   { "r3", 3 },
145   { "r4", 4 },
146   { "r5", 5 },
147   { "r6", 6 },
148   { "r7", 7 },
149   { "r8", 8 },
150   { "r9", 9 },
151   { "r10", 10 },
152   { "r11", 11 },
153   { "r12", 12 },
154   { "r13", 13 },
155   { "r14", 14 },
156   { "r15", 15 },
157   /* Synonyms (argument and variable registers).  */
158   { "a1", 0 },
159   { "a2", 1 },
160   { "a3", 2 },
161   { "a4", 3 },
162   { "v1", 4 },
163   { "v2", 5 },
164   { "v3", 6 },
165   { "v4", 7 },
166   { "v5", 8 },
167   { "v6", 9 },
168   { "v7", 10 },
169   { "v8", 11 },
170   /* Other platform-specific names for r9.  */
171   { "sb", 9 },
172   { "tr", 9 },
173   /* Special names.  */
174   { "ip", 12 },
175   { "sp", 13 },
176   { "lr", 14 },
177   { "pc", 15 },
178   /* Names used by GCC (not listed in the ARM EABI).  */
179   { "sl", 10 },
180   { "fp", 11 },
181   /* A special name from the older ATPCS.  */
182   { "wr", 7 },
183 };
184
185 static const char *const arm_register_names[] =
186 {"r0",  "r1",  "r2",  "r3",     /*  0  1  2  3 */
187  "r4",  "r5",  "r6",  "r7",     /*  4  5  6  7 */
188  "r8",  "r9",  "r10", "r11",    /*  8  9 10 11 */
189  "r12", "sp",  "lr",  "pc",     /* 12 13 14 15 */
190  "f0",  "f1",  "f2",  "f3",     /* 16 17 18 19 */
191  "f4",  "f5",  "f6",  "f7",     /* 20 21 22 23 */
192  "fps", "cpsr" };               /* 24 25       */
193
194 /* Valid register name styles.  */
195 static const char **valid_disassembly_styles;
196
197 /* Disassembly style to use. Default to "std" register names.  */
198 static const char *disassembly_style;
199
200 /* This is used to keep the bfd arch_info in sync with the disassembly
201    style.  */
202 static void set_disassembly_style_sfunc(char *, int,
203                                          struct cmd_list_element *);
204 static void set_disassembly_style (void);
205
206 static void convert_from_extended (const struct floatformat *, const void *,
207                                    void *, int);
208 static void convert_to_extended (const struct floatformat *, void *,
209                                  const void *, int);
210
211 static void arm_neon_quad_read (struct gdbarch *gdbarch,
212                                 struct regcache *regcache,
213                                 int regnum, gdb_byte *buf);
214 static void arm_neon_quad_write (struct gdbarch *gdbarch,
215                                  struct regcache *regcache,
216                                  int regnum, const gdb_byte *buf);
217
218 struct arm_prologue_cache
219 {
220   /* The stack pointer at the time this frame was created; i.e. the
221      caller's stack pointer when this function was called.  It is used
222      to identify this frame.  */
223   CORE_ADDR prev_sp;
224
225   /* The frame base for this frame is just prev_sp - frame size.
226      FRAMESIZE is the distance from the frame pointer to the
227      initial stack pointer.  */
228
229   int framesize;
230
231   /* The register used to hold the frame pointer for this frame.  */
232   int framereg;
233
234   /* Saved register offsets.  */
235   struct trad_frame_saved_reg *saved_regs;
236 };
237
238 /* Architecture version for displaced stepping.  This effects the behaviour of
239    certain instructions, and really should not be hard-wired.  */
240
241 #define DISPLACED_STEPPING_ARCH_VERSION         5
242
243 /* Addresses for calling Thumb functions have the bit 0 set.
244    Here are some macros to test, set, or clear bit 0 of addresses.  */
245 #define IS_THUMB_ADDR(addr)     ((addr) & 1)
246 #define MAKE_THUMB_ADDR(addr)   ((addr) | 1)
247 #define UNMAKE_THUMB_ADDR(addr) ((addr) & ~1)
248
249 /* Set to true if the 32-bit mode is in use.  */
250
251 int arm_apcs_32 = 1;
252
253 /* Determine if FRAME is executing in Thumb mode.  */
254
255 static int
256 arm_frame_is_thumb (struct frame_info *frame)
257 {
258   CORE_ADDR cpsr;
259
260   /* Every ARM frame unwinder can unwind the T bit of the CPSR, either
261      directly (from a signal frame or dummy frame) or by interpreting
262      the saved LR (from a prologue or DWARF frame).  So consult it and
263      trust the unwinders.  */
264   cpsr = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
265
266   return (cpsr & CPSR_T) != 0;
267 }
268
269 /* Callback for VEC_lower_bound.  */
270
271 static inline int
272 arm_compare_mapping_symbols (const struct arm_mapping_symbol *lhs,
273                              const struct arm_mapping_symbol *rhs)
274 {
275   return lhs->value < rhs->value;
276 }
277
278 /* Search for the mapping symbol covering MEMADDR.  If one is found,
279    return its type.  Otherwise, return 0.  If START is non-NULL,
280    set *START to the location of the mapping symbol.  */
281
282 static char
283 arm_find_mapping_symbol (CORE_ADDR memaddr, CORE_ADDR *start)
284 {
285   struct obj_section *sec;
286
287   /* If there are mapping symbols, consult them.  */
288   sec = find_pc_section (memaddr);
289   if (sec != NULL)
290     {
291       struct arm_per_objfile *data;
292       VEC(arm_mapping_symbol_s) *map;
293       struct arm_mapping_symbol map_key = { memaddr - obj_section_addr (sec),
294                                             0 };
295       unsigned int idx;
296
297       data = objfile_data (sec->objfile, arm_objfile_data_key);
298       if (data != NULL)
299         {
300           map = data->section_maps[sec->the_bfd_section->index];
301           if (!VEC_empty (arm_mapping_symbol_s, map))
302             {
303               struct arm_mapping_symbol *map_sym;
304
305               idx = VEC_lower_bound (arm_mapping_symbol_s, map, &map_key,
306                                      arm_compare_mapping_symbols);
307
308               /* VEC_lower_bound finds the earliest ordered insertion
309                  point.  If the following symbol starts at this exact
310                  address, we use that; otherwise, the preceding
311                  mapping symbol covers this address.  */
312               if (idx < VEC_length (arm_mapping_symbol_s, map))
313                 {
314                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx);
315                   if (map_sym->value == map_key.value)
316                     {
317                       if (start)
318                         *start = map_sym->value + obj_section_addr (sec);
319                       return map_sym->type;
320                     }
321                 }
322
323               if (idx > 0)
324                 {
325                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx - 1);
326                   if (start)
327                     *start = map_sym->value + obj_section_addr (sec);
328                   return map_sym->type;
329                 }
330             }
331         }
332     }
333
334   return 0;
335 }
336
337 static CORE_ADDR arm_get_next_pc_raw (struct frame_info *frame, 
338                                       CORE_ADDR pc, int insert_bkpt);
339
340 /* Determine if the program counter specified in MEMADDR is in a Thumb
341    function.  This function should be called for addresses unrelated to
342    any executing frame; otherwise, prefer arm_frame_is_thumb.  */
343
344 static int
345 arm_pc_is_thumb (CORE_ADDR memaddr)
346 {
347   struct obj_section *sec;
348   struct minimal_symbol *sym;
349   char type;
350
351   /* If bit 0 of the address is set, assume this is a Thumb address.  */
352   if (IS_THUMB_ADDR (memaddr))
353     return 1;
354
355   /* If the user wants to override the symbol table, let him.  */
356   if (strcmp (arm_force_mode_string, "arm") == 0)
357     return 0;
358   if (strcmp (arm_force_mode_string, "thumb") == 0)
359     return 1;
360
361   /* If there are mapping symbols, consult them.  */
362   type = arm_find_mapping_symbol (memaddr, NULL);
363   if (type)
364     return type == 't';
365
366   /* Thumb functions have a "special" bit set in minimal symbols.  */
367   sym = lookup_minimal_symbol_by_pc (memaddr);
368   if (sym)
369     return (MSYMBOL_IS_SPECIAL (sym));
370
371   /* If the user wants to override the fallback mode, let them.  */
372   if (strcmp (arm_fallback_mode_string, "arm") == 0)
373     return 0;
374   if (strcmp (arm_fallback_mode_string, "thumb") == 0)
375     return 1;
376
377   /* If we couldn't find any symbol, but we're talking to a running
378      target, then trust the current value of $cpsr.  This lets
379      "display/i $pc" always show the correct mode (though if there is
380      a symbol table we will not reach here, so it still may not be
381      displayed in the mode it will be executed).  
382    
383      As a further heuristic if we detect that we are doing a single-step we
384      see what state executing the current instruction ends up with us being
385      in.  */
386   if (target_has_registers)
387     {
388       struct frame_info *current_frame = get_current_frame ();
389       CORE_ADDR current_pc = get_frame_pc (current_frame);
390       int is_thumb = arm_frame_is_thumb (current_frame);
391       CORE_ADDR next_pc;
392       if (memaddr == current_pc)
393         return is_thumb;
394       else
395         {
396           struct gdbarch *gdbarch = get_frame_arch (current_frame);
397           next_pc = arm_get_next_pc_raw (current_frame, current_pc, FALSE);
398           if (memaddr == gdbarch_addr_bits_remove (gdbarch, next_pc))
399             return IS_THUMB_ADDR (next_pc);
400           else
401             return is_thumb;
402         }
403     }
404
405   /* Otherwise we're out of luck; we assume ARM.  */
406   return 0;
407 }
408
409 /* Remove useless bits from addresses in a running program.  */
410 static CORE_ADDR
411 arm_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR val)
412 {
413   if (arm_apcs_32)
414     return UNMAKE_THUMB_ADDR (val);
415   else
416     return (val & 0x03fffffc);
417 }
418
419 /* When reading symbols, we need to zap the low bit of the address,
420    which may be set to 1 for Thumb functions.  */
421 static CORE_ADDR
422 arm_smash_text_address (struct gdbarch *gdbarch, CORE_ADDR val)
423 {
424   return val & ~1;
425 }
426
427 /* Analyze a Thumb prologue, looking for a recognizable stack frame
428    and frame pointer.  Scan until we encounter a store that could
429    clobber the stack frame unexpectedly, or an unknown instruction.  */
430
431 static CORE_ADDR
432 thumb_analyze_prologue (struct gdbarch *gdbarch,
433                         CORE_ADDR start, CORE_ADDR limit,
434                         struct arm_prologue_cache *cache)
435 {
436   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
437   int i;
438   pv_t regs[16];
439   struct pv_area *stack;
440   struct cleanup *back_to;
441   CORE_ADDR offset;
442
443   for (i = 0; i < 16; i++)
444     regs[i] = pv_register (i, 0);
445   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
446   back_to = make_cleanup_free_pv_area (stack);
447
448   while (start < limit)
449     {
450       unsigned short insn;
451
452       insn = read_memory_unsigned_integer (start, 2, byte_order_for_code);
453
454       if ((insn & 0xfe00) == 0xb400)            /* push { rlist } */
455         {
456           int regno;
457           int mask;
458
459           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
460             break;
461
462           /* Bits 0-7 contain a mask for registers R0-R7.  Bit 8 says
463              whether to save LR (R14).  */
464           mask = (insn & 0xff) | ((insn & 0x100) << 6);
465
466           /* Calculate offsets of saved R0-R7 and LR.  */
467           for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
468             if (mask & (1 << regno))
469               {
470                 regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
471                                                        -4);
472                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
473               }
474         }
475       else if ((insn & 0xff00) == 0xb000)       /* add sp, #simm  OR  
476                                                    sub sp, #simm */
477         {
478           offset = (insn & 0x7f) << 2;          /* get scaled offset */
479           if (insn & 0x80)                      /* Check for SUB.  */
480             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
481                                                    -offset);
482           else
483             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
484                                                    offset);
485         }
486       else if ((insn & 0xff00) == 0xaf00)       /* add r7, sp, #imm */
487         regs[THUMB_FP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
488                                                  (insn & 0xff) << 2);
489       else if ((insn & 0xff00) == 0x4600)       /* mov hi, lo or mov lo, hi */
490         {
491           int dst_reg = (insn & 0x7) + ((insn & 0x80) >> 4);
492           int src_reg = (insn & 0x78) >> 3;
493           regs[dst_reg] = regs[src_reg];
494         }
495       else if ((insn & 0xf800) == 0x9000)       /* str rd, [sp, #off] */
496         {
497           /* Handle stores to the stack.  Normally pushes are used,
498              but with GCC -mtpcs-frame, there may be other stores
499              in the prologue to create the frame.  */
500           int regno = (insn >> 8) & 0x7;
501           pv_t addr;
502
503           offset = (insn & 0xff) << 2;
504           addr = pv_add_constant (regs[ARM_SP_REGNUM], offset);
505
506           if (pv_area_store_would_trash (stack, addr))
507             break;
508
509           pv_area_store (stack, addr, 4, regs[regno]);
510         }
511       else
512         {
513           /* We don't know what this instruction is.  We're finished
514              scanning.  NOTE: Recognizing more safe-to-ignore
515              instructions here will improve support for optimized
516              code.  */
517           break;
518         }
519
520       start += 2;
521     }
522
523   if (cache == NULL)
524     {
525       do_cleanups (back_to);
526       return start;
527     }
528
529   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
530     {
531       /* Frame pointer is fp.  Frame size is constant.  */
532       cache->framereg = ARM_FP_REGNUM;
533       cache->framesize = -regs[ARM_FP_REGNUM].k;
534     }
535   else if (pv_is_register (regs[THUMB_FP_REGNUM], ARM_SP_REGNUM))
536     {
537       /* Frame pointer is r7.  Frame size is constant.  */
538       cache->framereg = THUMB_FP_REGNUM;
539       cache->framesize = -regs[THUMB_FP_REGNUM].k;
540     }
541   else if (pv_is_register (regs[ARM_SP_REGNUM], ARM_SP_REGNUM))
542     {
543       /* Try the stack pointer... this is a bit desperate.  */
544       cache->framereg = ARM_SP_REGNUM;
545       cache->framesize = -regs[ARM_SP_REGNUM].k;
546     }
547   else
548     {
549       /* We're just out of luck.  We don't know where the frame is.  */
550       cache->framereg = -1;
551       cache->framesize = 0;
552     }
553
554   for (i = 0; i < 16; i++)
555     if (pv_area_find_reg (stack, gdbarch, i, &offset))
556       cache->saved_regs[i].addr = offset;
557
558   do_cleanups (back_to);
559   return start;
560 }
561
562 /* Advance the PC across any function entry prologue instructions to
563    reach some "real" code.
564
565    The APCS (ARM Procedure Call Standard) defines the following
566    prologue:
567
568    mov          ip, sp
569    [stmfd       sp!, {a1,a2,a3,a4}]
570    stmfd        sp!, {...,fp,ip,lr,pc}
571    [stfe        f7, [sp, #-12]!]
572    [stfe        f6, [sp, #-12]!]
573    [stfe        f5, [sp, #-12]!]
574    [stfe        f4, [sp, #-12]!]
575    sub fp, ip, #nn @@ nn == 20 or 4 depending on second insn */
576
577 static CORE_ADDR
578 arm_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
579 {
580   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
581   unsigned long inst;
582   CORE_ADDR skip_pc;
583   CORE_ADDR func_addr, limit_pc;
584   struct symtab_and_line sal;
585
586   /* If we're in a dummy frame, don't even try to skip the prologue.  */
587   if (deprecated_pc_in_call_dummy (gdbarch, pc))
588     return pc;
589
590   /* See if we can determine the end of the prologue via the symbol table.
591      If so, then return either PC, or the PC after the prologue, whichever
592      is greater.  */
593   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
594     {
595       CORE_ADDR post_prologue_pc
596         = skip_prologue_using_sal (gdbarch, func_addr);
597       if (post_prologue_pc != 0)
598         return max (pc, post_prologue_pc);
599     }
600
601   /* Can't determine prologue from the symbol table, need to examine
602      instructions.  */
603
604   /* Find an upper limit on the function prologue using the debug
605      information.  If the debug information could not be used to provide
606      that bound, then use an arbitrary large number as the upper bound.  */
607   /* Like arm_scan_prologue, stop no later than pc + 64. */
608   limit_pc = skip_prologue_using_sal (gdbarch, pc);
609   if (limit_pc == 0)
610     limit_pc = pc + 64;          /* Magic.  */
611
612
613   /* Check if this is Thumb code.  */
614   if (arm_pc_is_thumb (pc))
615     return thumb_analyze_prologue (gdbarch, pc, limit_pc, NULL);
616
617   for (skip_pc = pc; skip_pc < limit_pc; skip_pc += 4)
618     {
619       inst = read_memory_unsigned_integer (skip_pc, 4, byte_order_for_code);
620
621       /* "mov ip, sp" is no longer a required part of the prologue.  */
622       if (inst == 0xe1a0c00d)                   /* mov ip, sp */
623         continue;
624
625       if ((inst & 0xfffff000) == 0xe28dc000)    /* add ip, sp #n */
626         continue;
627
628       if ((inst & 0xfffff000) == 0xe24dc000)    /* sub ip, sp #n */
629         continue;
630
631       /* Some prologues begin with "str lr, [sp, #-4]!".  */
632       if (inst == 0xe52de004)                   /* str lr, [sp, #-4]! */
633         continue;
634
635       if ((inst & 0xfffffff0) == 0xe92d0000)    /* stmfd sp!,{a1,a2,a3,a4} */
636         continue;
637
638       if ((inst & 0xfffff800) == 0xe92dd800)    /* stmfd sp!,{fp,ip,lr,pc} */
639         continue;
640
641       /* Any insns after this point may float into the code, if it makes
642          for better instruction scheduling, so we skip them only if we
643          find them, but still consider the function to be frame-ful.  */
644
645       /* We may have either one sfmfd instruction here, or several stfe
646          insns, depending on the version of floating point code we
647          support.  */
648       if ((inst & 0xffbf0fff) == 0xec2d0200)    /* sfmfd fn, <cnt>, [sp]! */
649         continue;
650
651       if ((inst & 0xffff8fff) == 0xed6d0103)    /* stfe fn, [sp, #-12]! */
652         continue;
653
654       if ((inst & 0xfffff000) == 0xe24cb000)    /* sub fp, ip, #nn */
655         continue;
656
657       if ((inst & 0xfffff000) == 0xe24dd000)    /* sub sp, sp, #nn */
658         continue;
659
660       if ((inst & 0xffffc000) == 0xe54b0000     /* strb r(0123),[r11,#-nn] */
661           || (inst & 0xffffc0f0) == 0xe14b00b0  /* strh r(0123),[r11,#-nn] */
662           || (inst & 0xffffc000) == 0xe50b0000) /* str  r(0123),[r11,#-nn] */
663         continue;
664
665       if ((inst & 0xffffc000) == 0xe5cd0000     /* strb r(0123),[sp,#nn] */
666           || (inst & 0xffffc0f0) == 0xe1cd00b0  /* strh r(0123),[sp,#nn] */
667           || (inst & 0xffffc000) == 0xe58d0000) /* str  r(0123),[sp,#nn] */
668         continue;
669
670       /* Un-recognized instruction; stop scanning.  */
671       break;
672     }
673
674   return skip_pc;               /* End of prologue */
675 }
676
677 /* *INDENT-OFF* */
678 /* Function: thumb_scan_prologue (helper function for arm_scan_prologue)
679    This function decodes a Thumb function prologue to determine:
680      1) the size of the stack frame
681      2) which registers are saved on it
682      3) the offsets of saved regs
683      4) the offset from the stack pointer to the frame pointer
684
685    A typical Thumb function prologue would create this stack frame
686    (offsets relative to FP)
687      old SP ->  24  stack parameters
688                 20  LR
689                 16  R7
690      R7 ->       0  local variables (16 bytes)
691      SP ->     -12  additional stack space (12 bytes)
692    The frame size would thus be 36 bytes, and the frame offset would be
693    12 bytes.  The frame register is R7. 
694    
695    The comments for thumb_skip_prolog() describe the algorithm we use
696    to detect the end of the prolog.  */
697 /* *INDENT-ON* */
698
699 static void
700 thumb_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR prev_pc,
701                      CORE_ADDR block_addr, struct arm_prologue_cache *cache)
702 {
703   CORE_ADDR prologue_start;
704   CORE_ADDR prologue_end;
705   CORE_ADDR current_pc;
706
707   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
708                                 &prologue_end))
709     {
710       struct symtab_and_line sal = find_pc_line (prologue_start, 0);
711
712       if (sal.line == 0)                /* no line info, use current PC  */
713         prologue_end = prev_pc;
714       else if (sal.end < prologue_end)  /* next line begins after fn end */
715         prologue_end = sal.end;         /* (probably means no prologue)  */
716     }
717   else
718     /* We're in the boondocks: we have no idea where the start of the
719        function is.  */
720     return;
721
722   prologue_end = min (prologue_end, prev_pc);
723
724   thumb_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
725 }
726
727 /* This function decodes an ARM function prologue to determine:
728    1) the size of the stack frame
729    2) which registers are saved on it
730    3) the offsets of saved regs
731    4) the offset from the stack pointer to the frame pointer
732    This information is stored in the "extra" fields of the frame_info.
733
734    There are two basic forms for the ARM prologue.  The fixed argument
735    function call will look like:
736
737    mov    ip, sp
738    stmfd  sp!, {fp, ip, lr, pc}
739    sub    fp, ip, #4
740    [sub sp, sp, #4]
741
742    Which would create this stack frame (offsets relative to FP):
743    IP ->   4    (caller's stack)
744    FP ->   0    PC (points to address of stmfd instruction + 8 in callee)
745    -4   LR (return address in caller)
746    -8   IP (copy of caller's SP)
747    -12  FP (caller's FP)
748    SP -> -28    Local variables
749
750    The frame size would thus be 32 bytes, and the frame offset would be
751    28 bytes.  The stmfd call can also save any of the vN registers it
752    plans to use, which increases the frame size accordingly.
753
754    Note: The stored PC is 8 off of the STMFD instruction that stored it
755    because the ARM Store instructions always store PC + 8 when you read
756    the PC register.
757
758    A variable argument function call will look like:
759
760    mov    ip, sp
761    stmfd  sp!, {a1, a2, a3, a4}
762    stmfd  sp!, {fp, ip, lr, pc}
763    sub    fp, ip, #20
764
765    Which would create this stack frame (offsets relative to FP):
766    IP ->  20    (caller's stack)
767    16  A4
768    12  A3
769    8  A2
770    4  A1
771    FP ->   0    PC (points to address of stmfd instruction + 8 in callee)
772    -4   LR (return address in caller)
773    -8   IP (copy of caller's SP)
774    -12  FP (caller's FP)
775    SP -> -28    Local variables
776
777    The frame size would thus be 48 bytes, and the frame offset would be
778    28 bytes.
779
780    There is another potential complication, which is that the optimizer
781    will try to separate the store of fp in the "stmfd" instruction from
782    the "sub fp, ip, #NN" instruction.  Almost anything can be there, so
783    we just key on the stmfd, and then scan for the "sub fp, ip, #NN"...
784
785    Also, note, the original version of the ARM toolchain claimed that there
786    should be an
787
788    instruction at the end of the prologue.  I have never seen GCC produce
789    this, and the ARM docs don't mention it.  We still test for it below in
790    case it happens...
791
792  */
793
794 static void
795 arm_scan_prologue (struct frame_info *this_frame,
796                    struct arm_prologue_cache *cache)
797 {
798   struct gdbarch *gdbarch = get_frame_arch (this_frame);
799   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
800   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
801   int regno;
802   CORE_ADDR prologue_start, prologue_end, current_pc;
803   CORE_ADDR prev_pc = get_frame_pc (this_frame);
804   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
805   pv_t regs[ARM_FPS_REGNUM];
806   struct pv_area *stack;
807   struct cleanup *back_to;
808   CORE_ADDR offset;
809
810   /* Assume there is no frame until proven otherwise.  */
811   cache->framereg = ARM_SP_REGNUM;
812   cache->framesize = 0;
813
814   /* Check for Thumb prologue.  */
815   if (arm_frame_is_thumb (this_frame))
816     {
817       thumb_scan_prologue (gdbarch, prev_pc, block_addr, cache);
818       return;
819     }
820
821   /* Find the function prologue.  If we can't find the function in
822      the symbol table, peek in the stack frame to find the PC.  */
823   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
824                                 &prologue_end))
825     {
826       /* One way to find the end of the prologue (which works well
827          for unoptimized code) is to do the following:
828
829             struct symtab_and_line sal = find_pc_line (prologue_start, 0);
830
831             if (sal.line == 0)
832               prologue_end = prev_pc;
833             else if (sal.end < prologue_end)
834               prologue_end = sal.end;
835
836          This mechanism is very accurate so long as the optimizer
837          doesn't move any instructions from the function body into the
838          prologue.  If this happens, sal.end will be the last
839          instruction in the first hunk of prologue code just before
840          the first instruction that the scheduler has moved from
841          the body to the prologue.
842
843          In order to make sure that we scan all of the prologue
844          instructions, we use a slightly less accurate mechanism which
845          may scan more than necessary.  To help compensate for this
846          lack of accuracy, the prologue scanning loop below contains
847          several clauses which'll cause the loop to terminate early if
848          an implausible prologue instruction is encountered.  
849          
850          The expression
851          
852               prologue_start + 64
853             
854          is a suitable endpoint since it accounts for the largest
855          possible prologue plus up to five instructions inserted by
856          the scheduler.  */
857          
858       if (prologue_end > prologue_start + 64)
859         {
860           prologue_end = prologue_start + 64;   /* See above.  */
861         }
862     }
863   else
864     {
865       /* We have no symbol information.  Our only option is to assume this
866          function has a standard stack frame and the normal frame register.
867          Then, we can find the value of our frame pointer on entrance to
868          the callee (or at the present moment if this is the innermost frame).
869          The value stored there should be the address of the stmfd + 8.  */
870       CORE_ADDR frame_loc;
871       LONGEST return_value;
872
873       frame_loc = get_frame_register_unsigned (this_frame, ARM_FP_REGNUM);
874       if (!safe_read_memory_integer (frame_loc, 4, byte_order, &return_value))
875         return;
876       else
877         {
878           prologue_start = gdbarch_addr_bits_remove 
879                              (gdbarch, return_value) - 8;
880           prologue_end = prologue_start + 64;   /* See above.  */
881         }
882     }
883
884   if (prev_pc < prologue_end)
885     prologue_end = prev_pc;
886
887   /* Now search the prologue looking for instructions that set up the
888      frame pointer, adjust the stack pointer, and save registers.
889
890      Be careful, however, and if it doesn't look like a prologue,
891      don't try to scan it.  If, for instance, a frameless function
892      begins with stmfd sp!, then we will tell ourselves there is
893      a frame, which will confuse stack traceback, as well as "finish" 
894      and other operations that rely on a knowledge of the stack
895      traceback.
896
897      In the APCS, the prologue should start with  "mov ip, sp" so
898      if we don't see this as the first insn, we will stop.  
899
900      [Note: This doesn't seem to be true any longer, so it's now an
901      optional part of the prologue.  - Kevin Buettner, 2001-11-20]
902
903      [Note further: The "mov ip,sp" only seems to be missing in
904      frameless functions at optimization level "-O2" or above,
905      in which case it is often (but not always) replaced by
906      "str lr, [sp, #-4]!".  - Michael Snyder, 2002-04-23]  */
907
908   for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
909     regs[regno] = pv_register (regno, 0);
910   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
911   back_to = make_cleanup_free_pv_area (stack);
912
913   for (current_pc = prologue_start;
914        current_pc < prologue_end;
915        current_pc += 4)
916     {
917       unsigned int insn
918         = read_memory_unsigned_integer (current_pc, 4, byte_order_for_code);
919
920       if (insn == 0xe1a0c00d)           /* mov ip, sp */
921         {
922           regs[ARM_IP_REGNUM] = regs[ARM_SP_REGNUM];
923           continue;
924         }
925       else if ((insn & 0xfffff000) == 0xe28dc000) /* add ip, sp #n */
926         {
927           unsigned imm = insn & 0xff;                   /* immediate value */
928           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
929           imm = (imm >> rot) | (imm << (32 - rot));
930           regs[ARM_IP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], imm);
931           continue;
932         }
933       else if ((insn & 0xfffff000) == 0xe24dc000) /* sub ip, sp #n */
934         {
935           unsigned imm = insn & 0xff;                   /* immediate value */
936           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
937           imm = (imm >> rot) | (imm << (32 - rot));
938           regs[ARM_IP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -imm);
939           continue;
940         }
941       else if (insn == 0xe52de004)      /* str lr, [sp, #-4]! */
942         {
943           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
944             break;
945           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -4);
946           pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[ARM_LR_REGNUM]);
947           continue;
948         }
949       else if ((insn & 0xffff0000) == 0xe92d0000)
950         /* stmfd sp!, {..., fp, ip, lr, pc}
951            or
952            stmfd sp!, {a1, a2, a3, a4}  */
953         {
954           int mask = insn & 0xffff;
955
956           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
957             break;
958
959           /* Calculate offsets of saved registers.  */
960           for (regno = ARM_PC_REGNUM; regno >= 0; regno--)
961             if (mask & (1 << regno))
962               {
963                 regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -4);
964                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
965               }
966         }
967       else if ((insn & 0xffffc000) == 0xe54b0000        /* strb rx,[r11,#-n] */
968                || (insn & 0xffffc0f0) == 0xe14b00b0     /* strh rx,[r11,#-n] */
969                || (insn & 0xffffc000) == 0xe50b0000)    /* str  rx,[r11,#-n] */
970         {
971           /* No need to add this to saved_regs -- it's just an arg reg.  */
972           continue;
973         }
974       else if ((insn & 0xffffc000) == 0xe5cd0000        /* strb rx,[sp,#n] */
975                || (insn & 0xffffc0f0) == 0xe1cd00b0     /* strh rx,[sp,#n] */
976                || (insn & 0xffffc000) == 0xe58d0000)    /* str  rx,[sp,#n] */
977         {
978           /* No need to add this to saved_regs -- it's just an arg reg.  */
979           continue;
980         }
981       else if ((insn & 0xfffff000) == 0xe24cb000)       /* sub fp, ip #n */
982         {
983           unsigned imm = insn & 0xff;                   /* immediate value */
984           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
985           imm = (imm >> rot) | (imm << (32 - rot));
986           regs[ARM_FP_REGNUM] = pv_add_constant (regs[ARM_IP_REGNUM], -imm);
987         }
988       else if ((insn & 0xfffff000) == 0xe24dd000)       /* sub sp, sp #n */
989         {
990           unsigned imm = insn & 0xff;                   /* immediate value */
991           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
992           imm = (imm >> rot) | (imm << (32 - rot));
993           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -imm);
994         }
995       else if ((insn & 0xffff7fff) == 0xed6d0103        /* stfe f?, [sp, -#c]! */
996                && gdbarch_tdep (gdbarch)->have_fpa_registers)
997         {
998           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
999             break;
1000
1001           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1002           regno = ARM_F0_REGNUM + ((insn >> 12) & 0x07);
1003           pv_area_store (stack, regs[ARM_SP_REGNUM], 12, regs[regno]);
1004         }
1005       else if ((insn & 0xffbf0fff) == 0xec2d0200        /* sfmfd f0, 4, [sp!] */
1006                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1007         {
1008           int n_saved_fp_regs;
1009           unsigned int fp_start_reg, fp_bound_reg;
1010
1011           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1012             break;
1013
1014           if ((insn & 0x800) == 0x800)          /* N0 is set */
1015             {
1016               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1017                 n_saved_fp_regs = 3;
1018               else
1019                 n_saved_fp_regs = 1;
1020             }
1021           else
1022             {
1023               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1024                 n_saved_fp_regs = 2;
1025               else
1026                 n_saved_fp_regs = 4;
1027             }
1028
1029           fp_start_reg = ARM_F0_REGNUM + ((insn >> 12) & 0x7);
1030           fp_bound_reg = fp_start_reg + n_saved_fp_regs;
1031           for (; fp_start_reg < fp_bound_reg; fp_start_reg++)
1032             {
1033               regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1034               pv_area_store (stack, regs[ARM_SP_REGNUM], 12,
1035                              regs[fp_start_reg++]);
1036             }
1037         }
1038       else if ((insn & 0xf0000000) != 0xe0000000)
1039         break;                  /* Condition not true, exit early */
1040       else if ((insn & 0xfe200000) == 0xe8200000)       /* ldm? */
1041         break;                  /* Don't scan past a block load */
1042       else
1043         /* The optimizer might shove anything into the prologue,
1044            so we just skip what we don't recognize.  */
1045         continue;
1046     }
1047
1048   /* The frame size is just the distance from the frame register
1049      to the original stack pointer.  */
1050   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1051     {
1052       /* Frame pointer is fp.  */
1053       cache->framereg = ARM_FP_REGNUM;
1054       cache->framesize = -regs[ARM_FP_REGNUM].k;
1055     }
1056   else if (pv_is_register (regs[ARM_SP_REGNUM], ARM_SP_REGNUM))
1057     {
1058       /* Try the stack pointer... this is a bit desperate.  */
1059       cache->framereg = ARM_SP_REGNUM;
1060       cache->framesize = -regs[ARM_SP_REGNUM].k;
1061     }
1062   else
1063     {
1064       /* We're just out of luck.  We don't know where the frame is.  */
1065       cache->framereg = -1;
1066       cache->framesize = 0;
1067     }
1068
1069   for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1070     if (pv_area_find_reg (stack, gdbarch, regno, &offset))
1071       cache->saved_regs[regno].addr = offset;
1072
1073   do_cleanups (back_to);
1074 }
1075
1076 static struct arm_prologue_cache *
1077 arm_make_prologue_cache (struct frame_info *this_frame)
1078 {
1079   int reg;
1080   struct arm_prologue_cache *cache;
1081   CORE_ADDR unwound_fp;
1082
1083   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
1084   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
1085
1086   arm_scan_prologue (this_frame, cache);
1087
1088   unwound_fp = get_frame_register_unsigned (this_frame, cache->framereg);
1089   if (unwound_fp == 0)
1090     return cache;
1091
1092   cache->prev_sp = unwound_fp + cache->framesize;
1093
1094   /* Calculate actual addresses of saved registers using offsets
1095      determined by arm_scan_prologue.  */
1096   for (reg = 0; reg < gdbarch_num_regs (get_frame_arch (this_frame)); reg++)
1097     if (trad_frame_addr_p (cache->saved_regs, reg))
1098       cache->saved_regs[reg].addr += cache->prev_sp;
1099
1100   return cache;
1101 }
1102
1103 /* Our frame ID for a normal frame is the current function's starting PC
1104    and the caller's SP when we were called.  */
1105
1106 static void
1107 arm_prologue_this_id (struct frame_info *this_frame,
1108                       void **this_cache,
1109                       struct frame_id *this_id)
1110 {
1111   struct arm_prologue_cache *cache;
1112   struct frame_id id;
1113   CORE_ADDR pc, func;
1114
1115   if (*this_cache == NULL)
1116     *this_cache = arm_make_prologue_cache (this_frame);
1117   cache = *this_cache;
1118
1119   /* This is meant to halt the backtrace at "_start".  */
1120   pc = get_frame_pc (this_frame);
1121   if (pc <= gdbarch_tdep (get_frame_arch (this_frame))->lowest_pc)
1122     return;
1123
1124   /* If we've hit a wall, stop.  */
1125   if (cache->prev_sp == 0)
1126     return;
1127
1128   func = get_frame_func (this_frame);
1129   id = frame_id_build (cache->prev_sp, func);
1130   *this_id = id;
1131 }
1132
1133 static struct value *
1134 arm_prologue_prev_register (struct frame_info *this_frame,
1135                             void **this_cache,
1136                             int prev_regnum)
1137 {
1138   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1139   struct arm_prologue_cache *cache;
1140
1141   if (*this_cache == NULL)
1142     *this_cache = arm_make_prologue_cache (this_frame);
1143   cache = *this_cache;
1144
1145   /* If we are asked to unwind the PC, then we need to return the LR
1146      instead.  The prologue may save PC, but it will point into this
1147      frame's prologue, not the next frame's resume location.  Also
1148      strip the saved T bit.  A valid LR may have the low bit set, but
1149      a valid PC never does.  */
1150   if (prev_regnum == ARM_PC_REGNUM)
1151     {
1152       CORE_ADDR lr;
1153
1154       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
1155       return frame_unwind_got_constant (this_frame, prev_regnum,
1156                                         arm_addr_bits_remove (gdbarch, lr));
1157     }
1158
1159   /* SP is generally not saved to the stack, but this frame is
1160      identified by the next frame's stack pointer at the time of the call.
1161      The value was already reconstructed into PREV_SP.  */
1162   if (prev_regnum == ARM_SP_REGNUM)
1163     return frame_unwind_got_constant (this_frame, prev_regnum, cache->prev_sp);
1164
1165   /* The CPSR may have been changed by the call instruction and by the
1166      called function.  The only bit we can reconstruct is the T bit,
1167      by checking the low bit of LR as of the call.  This is a reliable
1168      indicator of Thumb-ness except for some ARM v4T pre-interworking
1169      Thumb code, which could get away with a clear low bit as long as
1170      the called function did not use bx.  Guess that all other
1171      bits are unchanged; the condition flags are presumably lost,
1172      but the processor status is likely valid.  */
1173   if (prev_regnum == ARM_PS_REGNUM)
1174     {
1175       CORE_ADDR lr, cpsr;
1176
1177       cpsr = get_frame_register_unsigned (this_frame, prev_regnum);
1178       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
1179       if (IS_THUMB_ADDR (lr))
1180         cpsr |= CPSR_T;
1181       else
1182         cpsr &= ~CPSR_T;
1183       return frame_unwind_got_constant (this_frame, prev_regnum, cpsr);
1184     }
1185
1186   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
1187                                        prev_regnum);
1188 }
1189
1190 struct frame_unwind arm_prologue_unwind = {
1191   NORMAL_FRAME,
1192   arm_prologue_this_id,
1193   arm_prologue_prev_register,
1194   NULL,
1195   default_frame_sniffer
1196 };
1197
1198 static struct arm_prologue_cache *
1199 arm_make_stub_cache (struct frame_info *this_frame)
1200 {
1201   int reg;
1202   struct arm_prologue_cache *cache;
1203   CORE_ADDR unwound_fp;
1204
1205   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
1206   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
1207
1208   cache->prev_sp = get_frame_register_unsigned (this_frame, ARM_SP_REGNUM);
1209
1210   return cache;
1211 }
1212
1213 /* Our frame ID for a stub frame is the current SP and LR.  */
1214
1215 static void
1216 arm_stub_this_id (struct frame_info *this_frame,
1217                   void **this_cache,
1218                   struct frame_id *this_id)
1219 {
1220   struct arm_prologue_cache *cache;
1221
1222   if (*this_cache == NULL)
1223     *this_cache = arm_make_stub_cache (this_frame);
1224   cache = *this_cache;
1225
1226   *this_id = frame_id_build (cache->prev_sp, get_frame_pc (this_frame));
1227 }
1228
1229 static int
1230 arm_stub_unwind_sniffer (const struct frame_unwind *self,
1231                          struct frame_info *this_frame,
1232                          void **this_prologue_cache)
1233 {
1234   CORE_ADDR addr_in_block;
1235   char dummy[4];
1236
1237   addr_in_block = get_frame_address_in_block (this_frame);
1238   if (in_plt_section (addr_in_block, NULL)
1239       /* We also use the stub winder if the target memory is unreadable
1240          to avoid having the prologue unwinder trying to read it.  */
1241       || target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
1242     return 1;
1243
1244   return 0;
1245 }
1246
1247 struct frame_unwind arm_stub_unwind = {
1248   NORMAL_FRAME,
1249   arm_stub_this_id,
1250   arm_prologue_prev_register,
1251   NULL,
1252   arm_stub_unwind_sniffer
1253 };
1254
1255 static CORE_ADDR
1256 arm_normal_frame_base (struct frame_info *this_frame, void **this_cache)
1257 {
1258   struct arm_prologue_cache *cache;
1259
1260   if (*this_cache == NULL)
1261     *this_cache = arm_make_prologue_cache (this_frame);
1262   cache = *this_cache;
1263
1264   return cache->prev_sp - cache->framesize;
1265 }
1266
1267 struct frame_base arm_normal_base = {
1268   &arm_prologue_unwind,
1269   arm_normal_frame_base,
1270   arm_normal_frame_base,
1271   arm_normal_frame_base
1272 };
1273
1274 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
1275    dummy frame.  The frame ID's base needs to match the TOS value
1276    saved by save_dummy_frame_tos() and returned from
1277    arm_push_dummy_call, and the PC needs to match the dummy frame's
1278    breakpoint.  */
1279
1280 static struct frame_id
1281 arm_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
1282 {
1283   return frame_id_build (get_frame_register_unsigned (this_frame, ARM_SP_REGNUM),
1284                          get_frame_pc (this_frame));
1285 }
1286
1287 /* Given THIS_FRAME, find the previous frame's resume PC (which will
1288    be used to construct the previous frame's ID, after looking up the
1289    containing function).  */
1290
1291 static CORE_ADDR
1292 arm_unwind_pc (struct gdbarch *gdbarch, struct frame_info *this_frame)
1293 {
1294   CORE_ADDR pc;
1295   pc = frame_unwind_register_unsigned (this_frame, ARM_PC_REGNUM);
1296   return arm_addr_bits_remove (gdbarch, pc);
1297 }
1298
1299 static CORE_ADDR
1300 arm_unwind_sp (struct gdbarch *gdbarch, struct frame_info *this_frame)
1301 {
1302   return frame_unwind_register_unsigned (this_frame, ARM_SP_REGNUM);
1303 }
1304
1305 static struct value *
1306 arm_dwarf2_prev_register (struct frame_info *this_frame, void **this_cache,
1307                           int regnum)
1308 {
1309   struct gdbarch * gdbarch = get_frame_arch (this_frame);
1310   CORE_ADDR lr, cpsr;
1311
1312   switch (regnum)
1313     {
1314     case ARM_PC_REGNUM:
1315       /* The PC is normally copied from the return column, which
1316          describes saves of LR.  However, that version may have an
1317          extra bit set to indicate Thumb state.  The bit is not
1318          part of the PC.  */
1319       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
1320       return frame_unwind_got_constant (this_frame, regnum,
1321                                         arm_addr_bits_remove (gdbarch, lr));
1322
1323     case ARM_PS_REGNUM:
1324       /* Reconstruct the T bit; see arm_prologue_prev_register for details.  */
1325       cpsr = get_frame_register_unsigned (this_frame, regnum);
1326       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
1327       if (IS_THUMB_ADDR (lr))
1328         cpsr |= CPSR_T;
1329       else
1330         cpsr &= ~CPSR_T;
1331       return frame_unwind_got_constant (this_frame, regnum, cpsr);
1332
1333     default:
1334       internal_error (__FILE__, __LINE__,
1335                       _("Unexpected register %d"), regnum);
1336     }
1337 }
1338
1339 static void
1340 arm_dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
1341                            struct dwarf2_frame_state_reg *reg,
1342                            struct frame_info *this_frame)
1343 {
1344   switch (regnum)
1345     {
1346     case ARM_PC_REGNUM:
1347     case ARM_PS_REGNUM:
1348       reg->how = DWARF2_FRAME_REG_FN;
1349       reg->loc.fn = arm_dwarf2_prev_register;
1350       break;
1351     case ARM_SP_REGNUM:
1352       reg->how = DWARF2_FRAME_REG_CFA;
1353       break;
1354     }
1355 }
1356
1357 /* When arguments must be pushed onto the stack, they go on in reverse
1358    order.  The code below implements a FILO (stack) to do this.  */
1359
1360 struct stack_item
1361 {
1362   int len;
1363   struct stack_item *prev;
1364   void *data;
1365 };
1366
1367 static struct stack_item *
1368 push_stack_item (struct stack_item *prev, void *contents, int len)
1369 {
1370   struct stack_item *si;
1371   si = xmalloc (sizeof (struct stack_item));
1372   si->data = xmalloc (len);
1373   si->len = len;
1374   si->prev = prev;
1375   memcpy (si->data, contents, len);
1376   return si;
1377 }
1378
1379 static struct stack_item *
1380 pop_stack_item (struct stack_item *si)
1381 {
1382   struct stack_item *dead = si;
1383   si = si->prev;
1384   xfree (dead->data);
1385   xfree (dead);
1386   return si;
1387 }
1388
1389
1390 /* Return the alignment (in bytes) of the given type.  */
1391
1392 static int
1393 arm_type_align (struct type *t)
1394 {
1395   int n;
1396   int align;
1397   int falign;
1398
1399   t = check_typedef (t);
1400   switch (TYPE_CODE (t))
1401     {
1402     default:
1403       /* Should never happen.  */
1404       internal_error (__FILE__, __LINE__, _("unknown type alignment"));
1405       return 4;
1406
1407     case TYPE_CODE_PTR:
1408     case TYPE_CODE_ENUM:
1409     case TYPE_CODE_INT:
1410     case TYPE_CODE_FLT:
1411     case TYPE_CODE_SET:
1412     case TYPE_CODE_RANGE:
1413     case TYPE_CODE_BITSTRING:
1414     case TYPE_CODE_REF:
1415     case TYPE_CODE_CHAR:
1416     case TYPE_CODE_BOOL:
1417       return TYPE_LENGTH (t);
1418
1419     case TYPE_CODE_ARRAY:
1420     case TYPE_CODE_COMPLEX:
1421       /* TODO: What about vector types?  */
1422       return arm_type_align (TYPE_TARGET_TYPE (t));
1423
1424     case TYPE_CODE_STRUCT:
1425     case TYPE_CODE_UNION:
1426       align = 1;
1427       for (n = 0; n < TYPE_NFIELDS (t); n++)
1428         {
1429           falign = arm_type_align (TYPE_FIELD_TYPE (t, n));
1430           if (falign > align)
1431             align = falign;
1432         }
1433       return align;
1434     }
1435 }
1436
1437 /* Possible base types for a candidate for passing and returning in
1438    VFP registers.  */
1439
1440 enum arm_vfp_cprc_base_type
1441 {
1442   VFP_CPRC_UNKNOWN,
1443   VFP_CPRC_SINGLE,
1444   VFP_CPRC_DOUBLE,
1445   VFP_CPRC_VEC64,
1446   VFP_CPRC_VEC128
1447 };
1448
1449 /* The length of one element of base type B.  */
1450
1451 static unsigned
1452 arm_vfp_cprc_unit_length (enum arm_vfp_cprc_base_type b)
1453 {
1454   switch (b)
1455     {
1456     case VFP_CPRC_SINGLE:
1457       return 4;
1458     case VFP_CPRC_DOUBLE:
1459       return 8;
1460     case VFP_CPRC_VEC64:
1461       return 8;
1462     case VFP_CPRC_VEC128:
1463       return 16;
1464     default:
1465       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
1466                       (int) b);
1467     }
1468 }
1469
1470 /* The character ('s', 'd' or 'q') for the type of VFP register used
1471    for passing base type B.  */
1472
1473 static int
1474 arm_vfp_cprc_reg_char (enum arm_vfp_cprc_base_type b)
1475 {
1476   switch (b)
1477     {
1478     case VFP_CPRC_SINGLE:
1479       return 's';
1480     case VFP_CPRC_DOUBLE:
1481       return 'd';
1482     case VFP_CPRC_VEC64:
1483       return 'd';
1484     case VFP_CPRC_VEC128:
1485       return 'q';
1486     default:
1487       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
1488                       (int) b);
1489     }
1490 }
1491
1492 /* Determine whether T may be part of a candidate for passing and
1493    returning in VFP registers, ignoring the limit on the total number
1494    of components.  If *BASE_TYPE is VFP_CPRC_UNKNOWN, set it to the
1495    classification of the first valid component found; if it is not
1496    VFP_CPRC_UNKNOWN, all components must have the same classification
1497    as *BASE_TYPE.  If it is found that T contains a type not permitted
1498    for passing and returning in VFP registers, a type differently
1499    classified from *BASE_TYPE, or two types differently classified
1500    from each other, return -1, otherwise return the total number of
1501    base-type elements found (possibly 0 in an empty structure or
1502    array).  Vectors and complex types are not currently supported,
1503    matching the generic AAPCS support.  */
1504
1505 static int
1506 arm_vfp_cprc_sub_candidate (struct type *t,
1507                             enum arm_vfp_cprc_base_type *base_type)
1508 {
1509   t = check_typedef (t);
1510   switch (TYPE_CODE (t))
1511     {
1512     case TYPE_CODE_FLT:
1513       switch (TYPE_LENGTH (t))
1514         {
1515         case 4:
1516           if (*base_type == VFP_CPRC_UNKNOWN)
1517             *base_type = VFP_CPRC_SINGLE;
1518           else if (*base_type != VFP_CPRC_SINGLE)
1519             return -1;
1520           return 1;
1521
1522         case 8:
1523           if (*base_type == VFP_CPRC_UNKNOWN)
1524             *base_type = VFP_CPRC_DOUBLE;
1525           else if (*base_type != VFP_CPRC_DOUBLE)
1526             return -1;
1527           return 1;
1528
1529         default:
1530           return -1;
1531         }
1532       break;
1533
1534     case TYPE_CODE_ARRAY:
1535       {
1536         int count;
1537         unsigned unitlen;
1538         count = arm_vfp_cprc_sub_candidate (TYPE_TARGET_TYPE (t), base_type);
1539         if (count == -1)
1540           return -1;
1541         if (TYPE_LENGTH (t) == 0)
1542           {
1543             gdb_assert (count == 0);
1544             return 0;
1545           }
1546         else if (count == 0)
1547           return -1;
1548         unitlen = arm_vfp_cprc_unit_length (*base_type);
1549         gdb_assert ((TYPE_LENGTH (t) % unitlen) == 0);
1550         return TYPE_LENGTH (t) / unitlen;
1551       }
1552       break;
1553
1554     case TYPE_CODE_STRUCT:
1555       {
1556         int count = 0;
1557         unsigned unitlen;
1558         int i;
1559         for (i = 0; i < TYPE_NFIELDS (t); i++)
1560           {
1561             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
1562                                                         base_type);
1563             if (sub_count == -1)
1564               return -1;
1565             count += sub_count;
1566           }
1567         if (TYPE_LENGTH (t) == 0)
1568           {
1569             gdb_assert (count == 0);
1570             return 0;
1571           }
1572         else if (count == 0)
1573           return -1;
1574         unitlen = arm_vfp_cprc_unit_length (*base_type);
1575         if (TYPE_LENGTH (t) != unitlen * count)
1576           return -1;
1577         return count;
1578       }
1579
1580     case TYPE_CODE_UNION:
1581       {
1582         int count = 0;
1583         unsigned unitlen;
1584         int i;
1585         for (i = 0; i < TYPE_NFIELDS (t); i++)
1586           {
1587             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
1588                                                         base_type);
1589             if (sub_count == -1)
1590               return -1;
1591             count = (count > sub_count ? count : sub_count);
1592           }
1593         if (TYPE_LENGTH (t) == 0)
1594           {
1595             gdb_assert (count == 0);
1596             return 0;
1597           }
1598         else if (count == 0)
1599           return -1;
1600         unitlen = arm_vfp_cprc_unit_length (*base_type);
1601         if (TYPE_LENGTH (t) != unitlen * count)
1602           return -1;
1603         return count;
1604       }
1605
1606     default:
1607       break;
1608     }
1609
1610   return -1;
1611 }
1612
1613 /* Determine whether T is a VFP co-processor register candidate (CPRC)
1614    if passed to or returned from a non-variadic function with the VFP
1615    ABI in effect.  Return 1 if it is, 0 otherwise.  If it is, set
1616    *BASE_TYPE to the base type for T and *COUNT to the number of
1617    elements of that base type before returning.  */
1618
1619 static int
1620 arm_vfp_call_candidate (struct type *t, enum arm_vfp_cprc_base_type *base_type,
1621                         int *count)
1622 {
1623   enum arm_vfp_cprc_base_type b = VFP_CPRC_UNKNOWN;
1624   int c = arm_vfp_cprc_sub_candidate (t, &b);
1625   if (c <= 0 || c > 4)
1626     return 0;
1627   *base_type = b;
1628   *count = c;
1629   return 1;
1630 }
1631
1632 /* Return 1 if the VFP ABI should be used for passing arguments to and
1633    returning values from a function of type FUNC_TYPE, 0
1634    otherwise.  */
1635
1636 static int
1637 arm_vfp_abi_for_function (struct gdbarch *gdbarch, struct type *func_type)
1638 {
1639   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1640   /* Variadic functions always use the base ABI.  Assume that functions
1641      without debug info are not variadic.  */
1642   if (func_type && TYPE_VARARGS (check_typedef (func_type)))
1643     return 0;
1644   /* The VFP ABI is only supported as a variant of AAPCS.  */
1645   if (tdep->arm_abi != ARM_ABI_AAPCS)
1646     return 0;
1647   return gdbarch_tdep (gdbarch)->fp_model == ARM_FLOAT_VFP;
1648 }
1649
1650 /* We currently only support passing parameters in integer registers, which
1651    conforms with GCC's default model, and VFP argument passing following
1652    the VFP variant of AAPCS.  Several other variants exist and
1653    we should probably support some of them based on the selected ABI.  */
1654
1655 static CORE_ADDR
1656 arm_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
1657                      struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
1658                      struct value **args, CORE_ADDR sp, int struct_return,
1659                      CORE_ADDR struct_addr)
1660 {
1661   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1662   int argnum;
1663   int argreg;
1664   int nstack;
1665   struct stack_item *si = NULL;
1666   int use_vfp_abi;
1667   struct type *ftype;
1668   unsigned vfp_regs_free = (1 << 16) - 1;
1669
1670   /* Determine the type of this function and whether the VFP ABI
1671      applies.  */
1672   ftype = check_typedef (value_type (function));
1673   if (TYPE_CODE (ftype) == TYPE_CODE_PTR)
1674     ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
1675   use_vfp_abi = arm_vfp_abi_for_function (gdbarch, ftype);
1676
1677   /* Set the return address.  For the ARM, the return breakpoint is
1678      always at BP_ADDR.  */
1679   if (arm_pc_is_thumb (bp_addr))
1680     bp_addr |= 1;
1681   regcache_cooked_write_unsigned (regcache, ARM_LR_REGNUM, bp_addr);
1682
1683   /* Walk through the list of args and determine how large a temporary
1684      stack is required.  Need to take care here as structs may be
1685      passed on the stack, and we have to to push them.  */
1686   nstack = 0;
1687
1688   argreg = ARM_A1_REGNUM;
1689   nstack = 0;
1690
1691   /* The struct_return pointer occupies the first parameter
1692      passing register.  */
1693   if (struct_return)
1694     {
1695       if (arm_debug)
1696         fprintf_unfiltered (gdb_stdlog, "struct return in %s = %s\n",
1697                             gdbarch_register_name (gdbarch, argreg),
1698                             paddress (gdbarch, struct_addr));
1699       regcache_cooked_write_unsigned (regcache, argreg, struct_addr);
1700       argreg++;
1701     }
1702
1703   for (argnum = 0; argnum < nargs; argnum++)
1704     {
1705       int len;
1706       struct type *arg_type;
1707       struct type *target_type;
1708       enum type_code typecode;
1709       bfd_byte *val;
1710       int align;
1711       enum arm_vfp_cprc_base_type vfp_base_type;
1712       int vfp_base_count;
1713       int may_use_core_reg = 1;
1714
1715       arg_type = check_typedef (value_type (args[argnum]));
1716       len = TYPE_LENGTH (arg_type);
1717       target_type = TYPE_TARGET_TYPE (arg_type);
1718       typecode = TYPE_CODE (arg_type);
1719       val = value_contents_writeable (args[argnum]);
1720
1721       align = arm_type_align (arg_type);
1722       /* Round alignment up to a whole number of words.  */
1723       align = (align + INT_REGISTER_SIZE - 1) & ~(INT_REGISTER_SIZE - 1);
1724       /* Different ABIs have different maximum alignments.  */
1725       if (gdbarch_tdep (gdbarch)->arm_abi == ARM_ABI_APCS)
1726         {
1727           /* The APCS ABI only requires word alignment.  */
1728           align = INT_REGISTER_SIZE;
1729         }
1730       else
1731         {
1732           /* The AAPCS requires at most doubleword alignment.  */
1733           if (align > INT_REGISTER_SIZE * 2)
1734             align = INT_REGISTER_SIZE * 2;
1735         }
1736
1737       if (use_vfp_abi
1738           && arm_vfp_call_candidate (arg_type, &vfp_base_type,
1739                                      &vfp_base_count))
1740         {
1741           int regno;
1742           int unit_length;
1743           int shift;
1744           unsigned mask;
1745
1746           /* Because this is a CPRC it cannot go in a core register or
1747              cause a core register to be skipped for alignment.
1748              Either it goes in VFP registers and the rest of this loop
1749              iteration is skipped for this argument, or it goes on the
1750              stack (and the stack alignment code is correct for this
1751              case).  */
1752           may_use_core_reg = 0;
1753
1754           unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
1755           shift = unit_length / 4;
1756           mask = (1 << (shift * vfp_base_count)) - 1;
1757           for (regno = 0; regno < 16; regno += shift)
1758             if (((vfp_regs_free >> regno) & mask) == mask)
1759               break;
1760
1761           if (regno < 16)
1762             {
1763               int reg_char;
1764               int reg_scaled;
1765               int i;
1766
1767               vfp_regs_free &= ~(mask << regno);
1768               reg_scaled = regno / shift;
1769               reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
1770               for (i = 0; i < vfp_base_count; i++)
1771                 {
1772                   char name_buf[4];
1773                   int regnum;
1774                   if (reg_char == 'q')
1775                     arm_neon_quad_write (gdbarch, regcache, reg_scaled + i,
1776                                          val + i * unit_length);
1777                   else
1778                     {
1779                       sprintf (name_buf, "%c%d", reg_char, reg_scaled + i);
1780                       regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
1781                                                             strlen (name_buf));
1782                       regcache_cooked_write (regcache, regnum,
1783                                              val + i * unit_length);
1784                     }
1785                 }
1786               continue;
1787             }
1788           else
1789             {
1790               /* This CPRC could not go in VFP registers, so all VFP
1791                  registers are now marked as used.  */
1792               vfp_regs_free = 0;
1793             }
1794         }
1795
1796       /* Push stack padding for dowubleword alignment.  */
1797       if (nstack & (align - 1))
1798         {
1799           si = push_stack_item (si, val, INT_REGISTER_SIZE);
1800           nstack += INT_REGISTER_SIZE;
1801         }
1802       
1803       /* Doubleword aligned quantities must go in even register pairs.  */
1804       if (may_use_core_reg
1805           && argreg <= ARM_LAST_ARG_REGNUM
1806           && align > INT_REGISTER_SIZE
1807           && argreg & 1)
1808         argreg++;
1809
1810       /* If the argument is a pointer to a function, and it is a
1811          Thumb function, create a LOCAL copy of the value and set
1812          the THUMB bit in it.  */
1813       if (TYPE_CODE_PTR == typecode
1814           && target_type != NULL
1815           && TYPE_CODE_FUNC == TYPE_CODE (target_type))
1816         {
1817           CORE_ADDR regval = extract_unsigned_integer (val, len, byte_order);
1818           if (arm_pc_is_thumb (regval))
1819             {
1820               val = alloca (len);
1821               store_unsigned_integer (val, len, byte_order,
1822                                       MAKE_THUMB_ADDR (regval));
1823             }
1824         }
1825
1826       /* Copy the argument to general registers or the stack in
1827          register-sized pieces.  Large arguments are split between
1828          registers and stack.  */
1829       while (len > 0)
1830         {
1831           int partial_len = len < INT_REGISTER_SIZE ? len : INT_REGISTER_SIZE;
1832
1833           if (may_use_core_reg && argreg <= ARM_LAST_ARG_REGNUM)
1834             {
1835               /* The argument is being passed in a general purpose
1836                  register.  */
1837               CORE_ADDR regval
1838                 = extract_unsigned_integer (val, partial_len, byte_order);
1839               if (byte_order == BFD_ENDIAN_BIG)
1840                 regval <<= (INT_REGISTER_SIZE - partial_len) * 8;
1841               if (arm_debug)
1842                 fprintf_unfiltered (gdb_stdlog, "arg %d in %s = 0x%s\n",
1843                                     argnum,
1844                                     gdbarch_register_name
1845                                       (gdbarch, argreg),
1846                                     phex (regval, INT_REGISTER_SIZE));
1847               regcache_cooked_write_unsigned (regcache, argreg, regval);
1848               argreg++;
1849             }
1850           else
1851             {
1852               /* Push the arguments onto the stack.  */
1853               if (arm_debug)
1854                 fprintf_unfiltered (gdb_stdlog, "arg %d @ sp + %d\n",
1855                                     argnum, nstack);
1856               si = push_stack_item (si, val, INT_REGISTER_SIZE);
1857               nstack += INT_REGISTER_SIZE;
1858             }
1859               
1860           len -= partial_len;
1861           val += partial_len;
1862         }
1863     }
1864   /* If we have an odd number of words to push, then decrement the stack
1865      by one word now, so first stack argument will be dword aligned.  */
1866   if (nstack & 4)
1867     sp -= 4;
1868
1869   while (si)
1870     {
1871       sp -= si->len;
1872       write_memory (sp, si->data, si->len);
1873       si = pop_stack_item (si);
1874     }
1875
1876   /* Finally, update teh SP register.  */
1877   regcache_cooked_write_unsigned (regcache, ARM_SP_REGNUM, sp);
1878
1879   return sp;
1880 }
1881
1882
1883 /* Always align the frame to an 8-byte boundary.  This is required on
1884    some platforms and harmless on the rest.  */
1885
1886 static CORE_ADDR
1887 arm_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
1888 {
1889   /* Align the stack to eight bytes.  */
1890   return sp & ~ (CORE_ADDR) 7;
1891 }
1892
1893 static void
1894 print_fpu_flags (int flags)
1895 {
1896   if (flags & (1 << 0))
1897     fputs ("IVO ", stdout);
1898   if (flags & (1 << 1))
1899     fputs ("DVZ ", stdout);
1900   if (flags & (1 << 2))
1901     fputs ("OFL ", stdout);
1902   if (flags & (1 << 3))
1903     fputs ("UFL ", stdout);
1904   if (flags & (1 << 4))
1905     fputs ("INX ", stdout);
1906   putchar ('\n');
1907 }
1908
1909 /* Print interesting information about the floating point processor
1910    (if present) or emulator.  */
1911 static void
1912 arm_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
1913                       struct frame_info *frame, const char *args)
1914 {
1915   unsigned long status = get_frame_register_unsigned (frame, ARM_FPS_REGNUM);
1916   int type;
1917
1918   type = (status >> 24) & 127;
1919   if (status & (1 << 31))
1920     printf (_("Hardware FPU type %d\n"), type);
1921   else
1922     printf (_("Software FPU type %d\n"), type);
1923   /* i18n: [floating point unit] mask */
1924   fputs (_("mask: "), stdout);
1925   print_fpu_flags (status >> 16);
1926   /* i18n: [floating point unit] flags */
1927   fputs (_("flags: "), stdout);
1928   print_fpu_flags (status);
1929 }
1930
1931 /* Construct the ARM extended floating point type.  */
1932 static struct type *
1933 arm_ext_type (struct gdbarch *gdbarch)
1934 {
1935   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1936
1937   if (!tdep->arm_ext_type)
1938     tdep->arm_ext_type
1939       = arch_float_type (gdbarch, -1, "builtin_type_arm_ext",
1940                          floatformats_arm_ext);
1941
1942   return tdep->arm_ext_type;
1943 }
1944
1945 static struct type *
1946 arm_neon_double_type (struct gdbarch *gdbarch)
1947 {
1948   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1949
1950   if (tdep->neon_double_type == NULL)
1951     {
1952       struct type *t, *elem;
1953
1954       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_d",
1955                                TYPE_CODE_UNION);
1956       elem = builtin_type (gdbarch)->builtin_uint8;
1957       append_composite_type_field (t, "u8", init_vector_type (elem, 8));
1958       elem = builtin_type (gdbarch)->builtin_uint16;
1959       append_composite_type_field (t, "u16", init_vector_type (elem, 4));
1960       elem = builtin_type (gdbarch)->builtin_uint32;
1961       append_composite_type_field (t, "u32", init_vector_type (elem, 2));
1962       elem = builtin_type (gdbarch)->builtin_uint64;
1963       append_composite_type_field (t, "u64", elem);
1964       elem = builtin_type (gdbarch)->builtin_float;
1965       append_composite_type_field (t, "f32", init_vector_type (elem, 2));
1966       elem = builtin_type (gdbarch)->builtin_double;
1967       append_composite_type_field (t, "f64", elem);
1968
1969       TYPE_VECTOR (t) = 1;
1970       TYPE_NAME (t) = "neon_d";
1971       tdep->neon_double_type = t;
1972     }
1973
1974   return tdep->neon_double_type;
1975 }
1976
1977 /* FIXME: The vector types are not correctly ordered on big-endian
1978    targets.  Just as s0 is the low bits of d0, d0[0] is also the low
1979    bits of d0 - regardless of what unit size is being held in d0.  So
1980    the offset of the first uint8 in d0 is 7, but the offset of the
1981    first float is 4.  This code works as-is for little-endian
1982    targets.  */
1983
1984 static struct type *
1985 arm_neon_quad_type (struct gdbarch *gdbarch)
1986 {
1987   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1988
1989   if (tdep->neon_quad_type == NULL)
1990     {
1991       struct type *t, *elem;
1992
1993       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_q",
1994                                TYPE_CODE_UNION);
1995       elem = builtin_type (gdbarch)->builtin_uint8;
1996       append_composite_type_field (t, "u8", init_vector_type (elem, 16));
1997       elem = builtin_type (gdbarch)->builtin_uint16;
1998       append_composite_type_field (t, "u16", init_vector_type (elem, 8));
1999       elem = builtin_type (gdbarch)->builtin_uint32;
2000       append_composite_type_field (t, "u32", init_vector_type (elem, 4));
2001       elem = builtin_type (gdbarch)->builtin_uint64;
2002       append_composite_type_field (t, "u64", init_vector_type (elem, 2));
2003       elem = builtin_type (gdbarch)->builtin_float;
2004       append_composite_type_field (t, "f32", init_vector_type (elem, 4));
2005       elem = builtin_type (gdbarch)->builtin_double;
2006       append_composite_type_field (t, "f64", init_vector_type (elem, 2));
2007
2008       TYPE_VECTOR (t) = 1;
2009       TYPE_NAME (t) = "neon_q";
2010       tdep->neon_quad_type = t;
2011     }
2012
2013   return tdep->neon_quad_type;
2014 }
2015
2016 /* Return the GDB type object for the "standard" data type of data in
2017    register N.  */
2018
2019 static struct type *
2020 arm_register_type (struct gdbarch *gdbarch, int regnum)
2021 {
2022   int num_regs = gdbarch_num_regs (gdbarch);
2023
2024   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
2025       && regnum >= num_regs && regnum < num_regs + 32)
2026     return builtin_type (gdbarch)->builtin_float;
2027
2028   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
2029       && regnum >= num_regs + 32 && regnum < num_regs + 32 + 16)
2030     return arm_neon_quad_type (gdbarch);
2031
2032   /* If the target description has register information, we are only
2033      in this function so that we can override the types of
2034      double-precision registers for NEON.  */
2035   if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
2036     {
2037       struct type *t = tdesc_register_type (gdbarch, regnum);
2038
2039       if (regnum >= ARM_D0_REGNUM && regnum < ARM_D0_REGNUM + 32
2040           && TYPE_CODE (t) == TYPE_CODE_FLT
2041           && gdbarch_tdep (gdbarch)->have_neon)
2042         return arm_neon_double_type (gdbarch);
2043       else
2044         return t;
2045     }
2046
2047   if (regnum >= ARM_F0_REGNUM && regnum < ARM_F0_REGNUM + NUM_FREGS)
2048     {
2049       if (!gdbarch_tdep (gdbarch)->have_fpa_registers)
2050         return builtin_type (gdbarch)->builtin_void;
2051
2052       return arm_ext_type (gdbarch);
2053     }
2054   else if (regnum == ARM_SP_REGNUM)
2055     return builtin_type (gdbarch)->builtin_data_ptr;
2056   else if (regnum == ARM_PC_REGNUM)
2057     return builtin_type (gdbarch)->builtin_func_ptr;
2058   else if (regnum >= ARRAY_SIZE (arm_register_names))
2059     /* These registers are only supported on targets which supply
2060        an XML description.  */
2061     return builtin_type (gdbarch)->builtin_int0;
2062   else
2063     return builtin_type (gdbarch)->builtin_uint32;
2064 }
2065
2066 /* Map a DWARF register REGNUM onto the appropriate GDB register
2067    number.  */
2068
2069 static int
2070 arm_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
2071 {
2072   /* Core integer regs.  */
2073   if (reg >= 0 && reg <= 15)
2074     return reg;
2075
2076   /* Legacy FPA encoding.  These were once used in a way which
2077      overlapped with VFP register numbering, so their use is
2078      discouraged, but GDB doesn't support the ARM toolchain
2079      which used them for VFP.  */
2080   if (reg >= 16 && reg <= 23)
2081     return ARM_F0_REGNUM + reg - 16;
2082
2083   /* New assignments for the FPA registers.  */
2084   if (reg >= 96 && reg <= 103)
2085     return ARM_F0_REGNUM + reg - 96;
2086
2087   /* WMMX register assignments.  */
2088   if (reg >= 104 && reg <= 111)
2089     return ARM_WCGR0_REGNUM + reg - 104;
2090
2091   if (reg >= 112 && reg <= 127)
2092     return ARM_WR0_REGNUM + reg - 112;
2093
2094   if (reg >= 192 && reg <= 199)
2095     return ARM_WC0_REGNUM + reg - 192;
2096
2097   /* VFP v2 registers.  A double precision value is actually
2098      in d1 rather than s2, but the ABI only defines numbering
2099      for the single precision registers.  This will "just work"
2100      in GDB for little endian targets (we'll read eight bytes,
2101      starting in s0 and then progressing to s1), but will be
2102      reversed on big endian targets with VFP.  This won't
2103      be a problem for the new Neon quad registers; you're supposed
2104      to use DW_OP_piece for those.  */
2105   if (reg >= 64 && reg <= 95)
2106     {
2107       char name_buf[4];
2108
2109       sprintf (name_buf, "s%d", reg - 64);
2110       return user_reg_map_name_to_regnum (gdbarch, name_buf,
2111                                           strlen (name_buf));
2112     }
2113
2114   /* VFP v3 / Neon registers.  This range is also used for VFP v2
2115      registers, except that it now describes d0 instead of s0.  */
2116   if (reg >= 256 && reg <= 287)
2117     {
2118       char name_buf[4];
2119
2120       sprintf (name_buf, "d%d", reg - 256);
2121       return user_reg_map_name_to_regnum (gdbarch, name_buf,
2122                                           strlen (name_buf));
2123     }
2124
2125   return -1;
2126 }
2127
2128 /* Map GDB internal REGNUM onto the Arm simulator register numbers.  */
2129 static int
2130 arm_register_sim_regno (struct gdbarch *gdbarch, int regnum)
2131 {
2132   int reg = regnum;
2133   gdb_assert (reg >= 0 && reg < gdbarch_num_regs (gdbarch));
2134
2135   if (regnum >= ARM_WR0_REGNUM && regnum <= ARM_WR15_REGNUM)
2136     return regnum - ARM_WR0_REGNUM + SIM_ARM_IWMMXT_COP0R0_REGNUM;
2137
2138   if (regnum >= ARM_WC0_REGNUM && regnum <= ARM_WC7_REGNUM)
2139     return regnum - ARM_WC0_REGNUM + SIM_ARM_IWMMXT_COP1R0_REGNUM;
2140
2141   if (regnum >= ARM_WCGR0_REGNUM && regnum <= ARM_WCGR7_REGNUM)
2142     return regnum - ARM_WCGR0_REGNUM + SIM_ARM_IWMMXT_COP1R8_REGNUM;
2143
2144   if (reg < NUM_GREGS)
2145     return SIM_ARM_R0_REGNUM + reg;
2146   reg -= NUM_GREGS;
2147
2148   if (reg < NUM_FREGS)
2149     return SIM_ARM_FP0_REGNUM + reg;
2150   reg -= NUM_FREGS;
2151
2152   if (reg < NUM_SREGS)
2153     return SIM_ARM_FPS_REGNUM + reg;
2154   reg -= NUM_SREGS;
2155
2156   internal_error (__FILE__, __LINE__, _("Bad REGNUM %d"), regnum);
2157 }
2158
2159 /* NOTE: cagney/2001-08-20: Both convert_from_extended() and
2160    convert_to_extended() use floatformat_arm_ext_littlebyte_bigword.
2161    It is thought that this is is the floating-point register format on
2162    little-endian systems.  */
2163
2164 static void
2165 convert_from_extended (const struct floatformat *fmt, const void *ptr,
2166                        void *dbl, int endianess)
2167 {
2168   DOUBLEST d;
2169
2170   if (endianess == BFD_ENDIAN_BIG)
2171     floatformat_to_doublest (&floatformat_arm_ext_big, ptr, &d);
2172   else
2173     floatformat_to_doublest (&floatformat_arm_ext_littlebyte_bigword,
2174                              ptr, &d);
2175   floatformat_from_doublest (fmt, &d, dbl);
2176 }
2177
2178 static void
2179 convert_to_extended (const struct floatformat *fmt, void *dbl, const void *ptr,
2180                      int endianess)
2181 {
2182   DOUBLEST d;
2183
2184   floatformat_to_doublest (fmt, ptr, &d);
2185   if (endianess == BFD_ENDIAN_BIG)
2186     floatformat_from_doublest (&floatformat_arm_ext_big, &d, dbl);
2187   else
2188     floatformat_from_doublest (&floatformat_arm_ext_littlebyte_bigword,
2189                                &d, dbl);
2190 }
2191
2192 static int
2193 condition_true (unsigned long cond, unsigned long status_reg)
2194 {
2195   if (cond == INST_AL || cond == INST_NV)
2196     return 1;
2197
2198   switch (cond)
2199     {
2200     case INST_EQ:
2201       return ((status_reg & FLAG_Z) != 0);
2202     case INST_NE:
2203       return ((status_reg & FLAG_Z) == 0);
2204     case INST_CS:
2205       return ((status_reg & FLAG_C) != 0);
2206     case INST_CC:
2207       return ((status_reg & FLAG_C) == 0);
2208     case INST_MI:
2209       return ((status_reg & FLAG_N) != 0);
2210     case INST_PL:
2211       return ((status_reg & FLAG_N) == 0);
2212     case INST_VS:
2213       return ((status_reg & FLAG_V) != 0);
2214     case INST_VC:
2215       return ((status_reg & FLAG_V) == 0);
2216     case INST_HI:
2217       return ((status_reg & (FLAG_C | FLAG_Z)) == FLAG_C);
2218     case INST_LS:
2219       return ((status_reg & (FLAG_C | FLAG_Z)) != FLAG_C);
2220     case INST_GE:
2221       return (((status_reg & FLAG_N) == 0) == ((status_reg & FLAG_V) == 0));
2222     case INST_LT:
2223       return (((status_reg & FLAG_N) == 0) != ((status_reg & FLAG_V) == 0));
2224     case INST_GT:
2225       return (((status_reg & FLAG_Z) == 0)
2226               && (((status_reg & FLAG_N) == 0)
2227                   == ((status_reg & FLAG_V) == 0)));
2228     case INST_LE:
2229       return (((status_reg & FLAG_Z) != 0)
2230               || (((status_reg & FLAG_N) == 0)
2231                   != ((status_reg & FLAG_V) == 0)));
2232     }
2233   return 1;
2234 }
2235
2236 /* Support routines for single stepping.  Calculate the next PC value.  */
2237 #define submask(x) ((1L << ((x) + 1)) - 1)
2238 #define bit(obj,st) (((obj) >> (st)) & 1)
2239 #define bits(obj,st,fn) (((obj) >> (st)) & submask ((fn) - (st)))
2240 #define sbits(obj,st,fn) \
2241   ((long) (bits(obj,st,fn) | ((long) bit(obj,fn) * ~ submask (fn - st))))
2242 #define BranchDest(addr,instr) \
2243   ((CORE_ADDR) (((long) (addr)) + 8 + (sbits (instr, 0, 23) << 2)))
2244 #define ARM_PC_32 1
2245
2246 static unsigned long
2247 shifted_reg_val (struct frame_info *frame, unsigned long inst, int carry,
2248                  unsigned long pc_val, unsigned long status_reg)
2249 {
2250   unsigned long res, shift;
2251   int rm = bits (inst, 0, 3);
2252   unsigned long shifttype = bits (inst, 5, 6);
2253
2254   if (bit (inst, 4))
2255     {
2256       int rs = bits (inst, 8, 11);
2257       shift = (rs == 15 ? pc_val + 8
2258                         : get_frame_register_unsigned (frame, rs)) & 0xFF;
2259     }
2260   else
2261     shift = bits (inst, 7, 11);
2262
2263   res = (rm == 15
2264          ? ((pc_val | (ARM_PC_32 ? 0 : status_reg))
2265             + (bit (inst, 4) ? 12 : 8))
2266          : get_frame_register_unsigned (frame, rm));
2267
2268   switch (shifttype)
2269     {
2270     case 0:                     /* LSL */
2271       res = shift >= 32 ? 0 : res << shift;
2272       break;
2273
2274     case 1:                     /* LSR */
2275       res = shift >= 32 ? 0 : res >> shift;
2276       break;
2277
2278     case 2:                     /* ASR */
2279       if (shift >= 32)
2280         shift = 31;
2281       res = ((res & 0x80000000L)
2282              ? ~((~res) >> shift) : res >> shift);
2283       break;
2284
2285     case 3:                     /* ROR/RRX */
2286       shift &= 31;
2287       if (shift == 0)
2288         res = (res >> 1) | (carry ? 0x80000000L : 0);
2289       else
2290         res = (res >> shift) | (res << (32 - shift));
2291       break;
2292     }
2293
2294   return res & 0xffffffff;
2295 }
2296
2297 /* Return number of 1-bits in VAL.  */
2298
2299 static int
2300 bitcount (unsigned long val)
2301 {
2302   int nbits;
2303   for (nbits = 0; val != 0; nbits++)
2304     val &= val - 1;             /* delete rightmost 1-bit in val */
2305   return nbits;
2306 }
2307
2308 /* Return the size in bytes of the complete Thumb instruction whose
2309    first halfword is INST1.  */
2310
2311 static int
2312 thumb_insn_size (unsigned short inst1)
2313 {
2314   if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
2315     return 4;
2316   else
2317     return 2;
2318 }
2319
2320 static int
2321 thumb_advance_itstate (unsigned int itstate)
2322 {
2323   /* Preserve IT[7:5], the first three bits of the condition.  Shift
2324      the upcoming condition flags left by one bit.  */
2325   itstate = (itstate & 0xe0) | ((itstate << 1) & 0x1f);
2326
2327   /* If we have finished the IT block, clear the state.  */
2328   if ((itstate & 0x0f) == 0)
2329     itstate = 0;
2330
2331   return itstate;
2332 }
2333
2334 /* Find the next PC after the current instruction executes.  In some
2335    cases we can not statically determine the answer (see the IT state
2336    handling in this function); in that case, a breakpoint may be
2337    inserted in addition to the returned PC, which will be used to set
2338    another breakpoint by our caller.  */
2339
2340 static CORE_ADDR
2341 thumb_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc, int insert_bkpt)
2342 {
2343   struct gdbarch *gdbarch = get_frame_arch (frame);
2344   struct address_space *aspace = get_frame_address_space (frame);
2345   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2346   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
2347   unsigned long pc_val = ((unsigned long) pc) + 4;      /* PC after prefetch */
2348   unsigned short inst1;
2349   CORE_ADDR nextpc = pc + 2;            /* default is next instruction */
2350   unsigned long offset;
2351   ULONGEST status, itstate;
2352
2353   nextpc = MAKE_THUMB_ADDR (nextpc);
2354   pc_val = MAKE_THUMB_ADDR (pc_val);
2355
2356   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
2357
2358   /* Thumb-2 conditional execution support.  There are eight bits in
2359      the CPSR which describe conditional execution state.  Once
2360      reconstructed (they're in a funny order), the low five bits
2361      describe the low bit of the condition for each instruction and
2362      how many instructions remain.  The high three bits describe the
2363      base condition.  One of the low four bits will be set if an IT
2364      block is active.  These bits read as zero on earlier
2365      processors.  */
2366   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
2367   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
2368
2369   /* If-Then handling.  On GNU/Linux, where this routine is used, we
2370      use an undefined instruction as a breakpoint.  Unlike BKPT, IT
2371      can disable execution of the undefined instruction.  So we might
2372      miss the breakpoint if we set it on a skipped conditional
2373      instruction.  Because conditional instructions can change the
2374      flags, affecting the execution of further instructions, we may
2375      need to set two breakpoints.  */
2376
2377   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint != NULL)
2378     {
2379       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
2380         {
2381           /* An IT instruction.  Because this instruction does not
2382              modify the flags, we can accurately predict the next
2383              executed instruction.  */
2384           itstate = inst1 & 0x00ff;
2385           pc += thumb_insn_size (inst1);
2386
2387           while (itstate != 0 && ! condition_true (itstate >> 4, status))
2388             {
2389               inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
2390               pc += thumb_insn_size (inst1);
2391               itstate = thumb_advance_itstate (itstate);
2392             }
2393
2394           return MAKE_THUMB_ADDR (pc);
2395         }
2396       else if (itstate != 0)
2397         {
2398           /* We are in a conditional block.  Check the condition.  */
2399           if (! condition_true (itstate >> 4, status))
2400             {
2401               /* Advance to the next executed instruction.  */
2402               pc += thumb_insn_size (inst1);
2403               itstate = thumb_advance_itstate (itstate);
2404
2405               while (itstate != 0 && ! condition_true (itstate >> 4, status))
2406                 {
2407                   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
2408                   pc += thumb_insn_size (inst1);
2409                   itstate = thumb_advance_itstate (itstate);
2410                 }
2411
2412               return MAKE_THUMB_ADDR (pc);
2413             }
2414           else if ((itstate & 0x0f) == 0x08)
2415             {
2416               /* This is the last instruction of the conditional
2417                  block, and it is executed.  We can handle it normally
2418                  because the following instruction is not conditional,
2419                  and we must handle it normally because it is
2420                  permitted to branch.  Fall through.  */
2421             }
2422           else
2423             {
2424               int cond_negated;
2425
2426               /* There are conditional instructions after this one.
2427                  If this instruction modifies the flags, then we can
2428                  not predict what the next executed instruction will
2429                  be.  Fortunately, this instruction is architecturally
2430                  forbidden to branch; we know it will fall through.
2431                  Start by skipping past it.  */
2432               pc += thumb_insn_size (inst1);
2433               itstate = thumb_advance_itstate (itstate);
2434
2435               /* Set a breakpoint on the following instruction.  */
2436               gdb_assert ((itstate & 0x0f) != 0);
2437               if (insert_bkpt)
2438                 insert_single_step_breakpoint (gdbarch, aspace, pc);
2439               cond_negated = (itstate >> 4) & 1;
2440
2441               /* Skip all following instructions with the same
2442                  condition.  If there is a later instruction in the IT
2443                  block with the opposite condition, set the other
2444                  breakpoint there.  If not, then set a breakpoint on
2445                  the instruction after the IT block.  */
2446               do
2447                 {
2448                   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
2449                   pc += thumb_insn_size (inst1);
2450                   itstate = thumb_advance_itstate (itstate);
2451                 }
2452               while (itstate != 0 && ((itstate >> 4) & 1) == cond_negated);
2453
2454               return MAKE_THUMB_ADDR (pc);
2455             }
2456         }
2457     }
2458   else if (itstate & 0x0f)
2459     {
2460       /* We are in a conditional block.  Check the condition.  */
2461       int cond = itstate >> 4;
2462
2463       if (! condition_true (cond, status))
2464         {
2465           /* Advance to the next instruction.  All the 32-bit
2466              instructions share a common prefix.  */
2467           if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
2468             return MAKE_THUMB_ADDR (pc + 4);
2469           else
2470             return MAKE_THUMB_ADDR (pc + 2);
2471         }
2472
2473       /* Otherwise, handle the instruction normally.  */
2474     }
2475
2476   if ((inst1 & 0xff00) == 0xbd00)       /* pop {rlist, pc} */
2477     {
2478       CORE_ADDR sp;
2479
2480       /* Fetch the saved PC from the stack.  It's stored above
2481          all of the other registers.  */
2482       offset = bitcount (bits (inst1, 0, 7)) * INT_REGISTER_SIZE;
2483       sp = get_frame_register_unsigned (frame, ARM_SP_REGNUM);
2484       nextpc = read_memory_unsigned_integer (sp + offset, 4, byte_order);
2485     }
2486   else if ((inst1 & 0xf000) == 0xd000)  /* conditional branch */
2487     {
2488       unsigned long cond = bits (inst1, 8, 11);
2489       if (cond != 0x0f && condition_true (cond, status))    /* 0x0f = SWI */
2490         nextpc = pc_val + (sbits (inst1, 0, 7) << 1);
2491     }
2492   else if ((inst1 & 0xf800) == 0xe000)  /* unconditional branch */
2493     {
2494       nextpc = pc_val + (sbits (inst1, 0, 10) << 1);
2495     }
2496   else if ((inst1 & 0xe000) == 0xe000) /* 32-bit instruction */
2497     {
2498       unsigned short inst2;
2499       inst2 = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
2500
2501       /* Default to the next instruction.  */
2502       nextpc = pc + 4;
2503       nextpc = MAKE_THUMB_ADDR (nextpc);
2504
2505       if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
2506         {
2507           /* Branches and miscellaneous control instructions.  */
2508
2509           if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
2510             {
2511               /* B, BL, BLX.  */
2512               int j1, j2, imm1, imm2;
2513
2514               imm1 = sbits (inst1, 0, 10);
2515               imm2 = bits (inst2, 0, 10);
2516               j1 = bit (inst2, 13);
2517               j2 = bit (inst2, 11);
2518
2519               offset = ((imm1 << 12) + (imm2 << 1));
2520               offset ^= ((!j2) << 22) | ((!j1) << 23);
2521
2522               nextpc = pc_val + offset;
2523               /* For BLX make sure to clear the low bits.  */
2524               if (bit (inst2, 12) == 0)
2525                 nextpc = nextpc & 0xfffffffc;
2526             }
2527           else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
2528             {
2529               /* SUBS PC, LR, #imm8.  */
2530               nextpc = get_frame_register_unsigned (frame, ARM_LR_REGNUM);
2531               nextpc -= inst2 & 0x00ff;
2532             }
2533           else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
2534             {
2535               /* Conditional branch.  */
2536               if (condition_true (bits (inst1, 6, 9), status))
2537                 {
2538                   int sign, j1, j2, imm1, imm2;
2539
2540                   sign = sbits (inst1, 10, 10);
2541                   imm1 = bits (inst1, 0, 5);
2542                   imm2 = bits (inst2, 0, 10);
2543                   j1 = bit (inst2, 13);
2544                   j2 = bit (inst2, 11);
2545
2546                   offset = (sign << 20) + (j2 << 19) + (j1 << 18);
2547                   offset += (imm1 << 12) + (imm2 << 1);
2548
2549                   nextpc = pc_val + offset;
2550                 }
2551             }
2552         }
2553       else if ((inst1 & 0xfe50) == 0xe810)
2554         {
2555           /* Load multiple or RFE.  */
2556           int rn, offset, load_pc = 1;
2557
2558           rn = bits (inst1, 0, 3);
2559           if (bit (inst1, 7) && !bit (inst1, 8))
2560             {
2561               /* LDMIA or POP */
2562               if (!bit (inst2, 15))
2563                 load_pc = 0;
2564               offset = bitcount (inst2) * 4 - 4;
2565             }
2566           else if (!bit (inst1, 7) && bit (inst1, 8))
2567             {
2568               /* LDMDB */
2569               if (!bit (inst2, 15))
2570                 load_pc = 0;
2571               offset = -4;
2572             }
2573           else if (bit (inst1, 7) && bit (inst1, 8))
2574             {
2575               /* RFEIA */
2576               offset = 0;
2577             }
2578           else if (!bit (inst1, 7) && !bit (inst1, 8))
2579             {
2580               /* RFEDB */
2581               offset = -8;
2582             }
2583           else
2584             load_pc = 0;
2585
2586           if (load_pc)
2587             {
2588               CORE_ADDR addr = get_frame_register_unsigned (frame, rn);
2589               nextpc = get_frame_memory_unsigned (frame, addr + offset, 4);
2590             }
2591         }
2592       else if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
2593         {
2594           /* MOV PC or MOVS PC.  */
2595           nextpc = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
2596           nextpc = MAKE_THUMB_ADDR (nextpc);
2597         }
2598       else if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
2599         {
2600           /* LDR PC.  */
2601           CORE_ADDR base;
2602           int rn, load_pc = 1;
2603
2604           rn = bits (inst1, 0, 3);
2605           base = get_frame_register_unsigned (frame, rn);
2606           if (rn == 15)
2607             {
2608               base = (base + 4) & ~(CORE_ADDR) 0x3;
2609               if (bit (inst1, 7))
2610                 base += bits (inst2, 0, 11);
2611               else
2612                 base -= bits (inst2, 0, 11);
2613             }
2614           else if (bit (inst1, 7))
2615             base += bits (inst2, 0, 11);
2616           else if (bit (inst2, 11))
2617             {
2618               if (bit (inst2, 10))
2619                 {
2620                   if (bit (inst2, 9))
2621                     base += bits (inst2, 0, 7);
2622                   else
2623                     base -= bits (inst2, 0, 7);
2624                 }
2625             }
2626           else if ((inst2 & 0x0fc0) == 0x0000)
2627             {
2628               int shift = bits (inst2, 4, 5), rm = bits (inst2, 0, 3);
2629               base += get_frame_register_unsigned (frame, rm) << shift;
2630             }
2631           else
2632             /* Reserved.  */
2633             load_pc = 0;
2634
2635           if (load_pc)
2636             nextpc = get_frame_memory_unsigned (frame, base, 4);
2637         }
2638       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
2639         {
2640           /* TBB.  */
2641           CORE_ADDR table, offset, length;
2642
2643           table = get_frame_register_unsigned (frame, bits (inst1, 0, 3));
2644           offset = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
2645           length = 2 * get_frame_memory_unsigned (frame, table + offset, 1);
2646           nextpc = pc_val + length;
2647         }
2648       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
2649         {
2650           /* TBH.  */
2651           CORE_ADDR table, offset, length;
2652
2653           table = get_frame_register_unsigned (frame, bits (inst1, 0, 3));
2654           offset = 2 * get_frame_register_unsigned (frame, bits (inst2, 0, 3));
2655           length = 2 * get_frame_memory_unsigned (frame, table + offset, 2);
2656           nextpc = pc_val + length;
2657         }
2658     }
2659   else if ((inst1 & 0xff00) == 0x4700)  /* bx REG, blx REG */
2660     {
2661       if (bits (inst1, 3, 6) == 0x0f)
2662         nextpc = pc_val;
2663       else
2664         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
2665     }
2666   else if ((inst1 & 0xf500) == 0xb100)
2667     {
2668       /* CBNZ or CBZ.  */
2669       int imm = (bit (inst1, 9) << 6) + (bits (inst1, 3, 7) << 1);
2670       ULONGEST reg = get_frame_register_unsigned (frame, bits (inst1, 0, 2));
2671
2672       if (bit (inst1, 11) && reg != 0)
2673         nextpc = pc_val + imm;
2674       else if (!bit (inst1, 11) && reg == 0)
2675         nextpc = pc_val + imm;
2676     }
2677   return nextpc;
2678 }
2679
2680 /* Get the raw next address.  PC is the current program counter, in 
2681    FRAME.  INSERT_BKPT should be TRUE if we want a breakpoint set on 
2682    the alternative next instruction if there are two options.
2683
2684    The value returned has the execution state of the next instruction 
2685    encoded in it.  Use IS_THUMB_ADDR () to see whether the instruction is
2686    in Thumb-State, and gdbarch_addr_bits_remove () to get the plain memory
2687    address.
2688 */
2689 static CORE_ADDR
2690 arm_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc, int insert_bkpt)
2691 {
2692   struct gdbarch *gdbarch = get_frame_arch (frame);
2693   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2694   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
2695   unsigned long pc_val;
2696   unsigned long this_instr;
2697   unsigned long status;
2698   CORE_ADDR nextpc;
2699
2700   if (arm_frame_is_thumb (frame))
2701     return thumb_get_next_pc_raw (frame, pc, insert_bkpt);
2702
2703   pc_val = (unsigned long) pc;
2704   this_instr = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
2705
2706   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
2707   nextpc = (CORE_ADDR) (pc_val + 4);    /* Default case */
2708
2709   if (bits (this_instr, 28, 31) == INST_NV)
2710     switch (bits (this_instr, 24, 27))
2711       {
2712       case 0xa:
2713       case 0xb:
2714         {
2715           /* Branch with Link and change to Thumb.  */
2716           nextpc = BranchDest (pc, this_instr);
2717           nextpc |= bit (this_instr, 24) << 1;
2718           nextpc = MAKE_THUMB_ADDR (nextpc);
2719           break;
2720         }
2721       case 0xc:
2722       case 0xd:
2723       case 0xe:
2724         /* Coprocessor register transfer.  */
2725         if (bits (this_instr, 12, 15) == 15)
2726           error (_("Invalid update to pc in instruction"));
2727         break;
2728       }
2729   else if (condition_true (bits (this_instr, 28, 31), status))
2730     {
2731       switch (bits (this_instr, 24, 27))
2732         {
2733         case 0x0:
2734         case 0x1:                       /* data processing */
2735         case 0x2:
2736         case 0x3:
2737           {
2738             unsigned long operand1, operand2, result = 0;
2739             unsigned long rn;
2740             int c;
2741
2742             if (bits (this_instr, 12, 15) != 15)
2743               break;
2744
2745             if (bits (this_instr, 22, 25) == 0
2746                 && bits (this_instr, 4, 7) == 9)        /* multiply */
2747               error (_("Invalid update to pc in instruction"));
2748
2749             /* BX <reg>, BLX <reg> */
2750             if (bits (this_instr, 4, 27) == 0x12fff1
2751                 || bits (this_instr, 4, 27) == 0x12fff3)
2752               {
2753                 rn = bits (this_instr, 0, 3);
2754                 nextpc = (rn == 15) ? pc_val + 8
2755                                     : get_frame_register_unsigned (frame, rn);
2756                 return nextpc;
2757               }
2758
2759             /* Multiply into PC */
2760             c = (status & FLAG_C) ? 1 : 0;
2761             rn = bits (this_instr, 16, 19);
2762             operand1 = (rn == 15) ? pc_val + 8
2763                                   : get_frame_register_unsigned (frame, rn);
2764
2765             if (bit (this_instr, 25))
2766               {
2767                 unsigned long immval = bits (this_instr, 0, 7);
2768                 unsigned long rotate = 2 * bits (this_instr, 8, 11);
2769                 operand2 = ((immval >> rotate) | (immval << (32 - rotate)))
2770                   & 0xffffffff;
2771               }
2772             else                /* operand 2 is a shifted register */
2773               operand2 = shifted_reg_val (frame, this_instr, c, pc_val, status);
2774
2775             switch (bits (this_instr, 21, 24))
2776               {
2777               case 0x0: /*and */
2778                 result = operand1 & operand2;
2779                 break;
2780
2781               case 0x1: /*eor */
2782                 result = operand1 ^ operand2;
2783                 break;
2784
2785               case 0x2: /*sub */
2786                 result = operand1 - operand2;
2787                 break;
2788
2789               case 0x3: /*rsb */
2790                 result = operand2 - operand1;
2791                 break;
2792
2793               case 0x4: /*add */
2794                 result = operand1 + operand2;
2795                 break;
2796
2797               case 0x5: /*adc */
2798                 result = operand1 + operand2 + c;
2799                 break;
2800
2801               case 0x6: /*sbc */
2802                 result = operand1 - operand2 + c;
2803                 break;
2804
2805               case 0x7: /*rsc */
2806                 result = operand2 - operand1 + c;
2807                 break;
2808
2809               case 0x8:
2810               case 0x9:
2811               case 0xa:
2812               case 0xb: /* tst, teq, cmp, cmn */
2813                 result = (unsigned long) nextpc;
2814                 break;
2815
2816               case 0xc: /*orr */
2817                 result = operand1 | operand2;
2818                 break;
2819
2820               case 0xd: /*mov */
2821                 /* Always step into a function.  */
2822                 result = operand2;
2823                 break;
2824
2825               case 0xe: /*bic */
2826                 result = operand1 & ~operand2;
2827                 break;
2828
2829               case 0xf: /*mvn */
2830                 result = ~operand2;
2831                 break;
2832               }
2833
2834             /* In 26-bit APCS the bottom two bits of the result are 
2835                ignored, and we always end up in ARM state.  */
2836             if (!arm_apcs_32)
2837               nextpc = arm_addr_bits_remove (gdbarch, result);
2838             else
2839               nextpc = result;
2840
2841             break;
2842           }
2843
2844         case 0x4:
2845         case 0x5:               /* data transfer */
2846         case 0x6:
2847         case 0x7:
2848           if (bit (this_instr, 20))
2849             {
2850               /* load */
2851               if (bits (this_instr, 12, 15) == 15)
2852                 {
2853                   /* rd == pc */
2854                   unsigned long rn;
2855                   unsigned long base;
2856
2857                   if (bit (this_instr, 22))
2858                     error (_("Invalid update to pc in instruction"));
2859
2860                   /* byte write to PC */
2861                   rn = bits (this_instr, 16, 19);
2862                   base = (rn == 15) ? pc_val + 8
2863                                     : get_frame_register_unsigned (frame, rn);
2864                   if (bit (this_instr, 24))
2865                     {
2866                       /* pre-indexed */
2867                       int c = (status & FLAG_C) ? 1 : 0;
2868                       unsigned long offset =
2869                       (bit (this_instr, 25)
2870                        ? shifted_reg_val (frame, this_instr, c, pc_val, status)
2871                        : bits (this_instr, 0, 11));
2872
2873                       if (bit (this_instr, 23))
2874                         base += offset;
2875                       else
2876                         base -= offset;
2877                     }
2878                   nextpc = (CORE_ADDR) read_memory_integer ((CORE_ADDR) base,
2879                                                             4, byte_order);
2880                 }
2881             }
2882           break;
2883
2884         case 0x8:
2885         case 0x9:               /* block transfer */
2886           if (bit (this_instr, 20))
2887             {
2888               /* LDM */
2889               if (bit (this_instr, 15))
2890                 {
2891                   /* loading pc */
2892                   int offset = 0;
2893
2894                   if (bit (this_instr, 23))
2895                     {
2896                       /* up */
2897                       unsigned long reglist = bits (this_instr, 0, 14);
2898                       offset = bitcount (reglist) * 4;
2899                       if (bit (this_instr, 24))         /* pre */
2900                         offset += 4;
2901                     }
2902                   else if (bit (this_instr, 24))
2903                     offset = -4;
2904
2905                   {
2906                     unsigned long rn_val =
2907                     get_frame_register_unsigned (frame,
2908                                                  bits (this_instr, 16, 19));
2909                     nextpc =
2910                       (CORE_ADDR) read_memory_integer ((CORE_ADDR) (rn_val
2911                                                                   + offset),
2912                                                        4, byte_order);
2913                   }
2914                 }
2915             }
2916           break;
2917
2918         case 0xb:               /* branch & link */
2919         case 0xa:               /* branch */
2920           {
2921             nextpc = BranchDest (pc, this_instr);
2922             break;
2923           }
2924
2925         case 0xc:
2926         case 0xd:
2927         case 0xe:               /* coproc ops */
2928         case 0xf:               /* SWI */
2929           break;
2930
2931         default:
2932           fprintf_filtered (gdb_stderr, _("Bad bit-field extraction\n"));
2933           return (pc);
2934         }
2935     }
2936
2937   return nextpc;
2938 }
2939
2940 CORE_ADDR
2941 arm_get_next_pc (struct frame_info *frame, CORE_ADDR pc)
2942 {
2943   struct gdbarch *gdbarch = get_frame_arch (frame);
2944   CORE_ADDR nextpc = 
2945     gdbarch_addr_bits_remove (gdbarch, 
2946                               arm_get_next_pc_raw (frame, pc, TRUE));
2947   if (nextpc == pc)
2948     error (_("Infinite loop detected"));
2949   return nextpc;
2950 }
2951
2952 /* single_step() is called just before we want to resume the inferior,
2953    if we want to single-step it but there is no hardware or kernel
2954    single-step support.  We find the target of the coming instruction
2955    and breakpoint it.  */
2956
2957 int
2958 arm_software_single_step (struct frame_info *frame)
2959 {
2960   struct gdbarch *gdbarch = get_frame_arch (frame);
2961   struct address_space *aspace = get_frame_address_space (frame);
2962
2963   /* NOTE: This may insert the wrong breakpoint instruction when
2964      single-stepping over a mode-changing instruction, if the
2965      CPSR heuristics are used.  */
2966
2967   CORE_ADDR next_pc = arm_get_next_pc (frame, get_frame_pc (frame));
2968   insert_single_step_breakpoint (gdbarch, aspace, next_pc);
2969
2970   return 1;
2971 }
2972
2973 /* Given BUF, which is OLD_LEN bytes ending at ENDADDR, expand
2974    the buffer to be NEW_LEN bytes ending at ENDADDR.  Return
2975    NULL if an error occurs.  BUF is freed.  */
2976
2977 static gdb_byte *
2978 extend_buffer_earlier (gdb_byte *buf, CORE_ADDR endaddr,
2979                        int old_len, int new_len)
2980 {
2981   gdb_byte *new_buf, *middle;
2982   int bytes_to_read = new_len - old_len;
2983
2984   new_buf = xmalloc (new_len);
2985   memcpy (new_buf + bytes_to_read, buf, old_len);
2986   xfree (buf);
2987   if (target_read_memory (endaddr - new_len, new_buf, bytes_to_read) != 0)
2988     {
2989       xfree (new_buf);
2990       return NULL;
2991     }
2992   return new_buf;
2993 }
2994
2995 /* An IT block is at most the 2-byte IT instruction followed by
2996    four 4-byte instructions.  The furthest back we must search to
2997    find an IT block that affects the current instruction is thus
2998    2 + 3 * 4 == 14 bytes.  */
2999 #define MAX_IT_BLOCK_PREFIX 14
3000
3001 /* Use a quick scan if there are more than this many bytes of
3002    code.  */
3003 #define IT_SCAN_THRESHOLD 32
3004
3005 /* Adjust a breakpoint's address to move breakpoints out of IT blocks.
3006    A breakpoint in an IT block may not be hit, depending on the
3007    condition flags.  */
3008 static CORE_ADDR
3009 arm_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
3010 {
3011   gdb_byte *buf;
3012   char map_type;
3013   CORE_ADDR boundary, func_start;
3014   int buf_len, buf2_len;
3015   enum bfd_endian order = gdbarch_byte_order_for_code (gdbarch);
3016   int i, any, last_it, last_it_count;
3017
3018   /* If we are using BKPT breakpoints, none of this is necessary.  */
3019   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint == NULL)
3020     return bpaddr;
3021
3022   /* ARM mode does not have this problem.  */
3023   if (!arm_pc_is_thumb (bpaddr))
3024     return bpaddr;
3025
3026   /* We are setting a breakpoint in Thumb code that could potentially
3027      contain an IT block.  The first step is to find how much Thumb
3028      code there is; we do not need to read outside of known Thumb
3029      sequences.  */
3030   map_type = arm_find_mapping_symbol (bpaddr, &boundary);
3031   if (map_type == 0)
3032     /* Thumb-2 code must have mapping symbols to have a chance.  */
3033     return bpaddr;
3034
3035   bpaddr = gdbarch_addr_bits_remove (gdbarch, bpaddr);
3036
3037   if (find_pc_partial_function (bpaddr, NULL, &func_start, NULL)
3038       && func_start > boundary)
3039     boundary = func_start;
3040
3041   /* Search for a candidate IT instruction.  We have to do some fancy
3042      footwork to distinguish a real IT instruction from the second
3043      half of a 32-bit instruction, but there is no need for that if
3044      there's no candidate.  */
3045   buf_len = min (bpaddr - boundary, MAX_IT_BLOCK_PREFIX);
3046   if (buf_len == 0)
3047     /* No room for an IT instruction.  */
3048     return bpaddr;
3049
3050   buf = xmalloc (buf_len);
3051   if (target_read_memory (bpaddr - buf_len, buf, buf_len) != 0)
3052     return bpaddr;
3053   any = 0;
3054   for (i = 0; i < buf_len; i += 2)
3055     {
3056       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
3057       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
3058         {
3059           any = 1;
3060           break;
3061         }
3062     }
3063   if (any == 0)
3064     {
3065       xfree (buf);
3066       return bpaddr;
3067     }
3068
3069   /* OK, the code bytes before this instruction contain at least one
3070      halfword which resembles an IT instruction.  We know that it's
3071      Thumb code, but there are still two possibilities.  Either the
3072      halfword really is an IT instruction, or it is the second half of
3073      a 32-bit Thumb instruction.  The only way we can tell is to
3074      scan forwards from a known instruction boundary.  */
3075   if (bpaddr - boundary > IT_SCAN_THRESHOLD)
3076     {
3077       int definite;
3078
3079       /* There's a lot of code before this instruction.  Start with an
3080          optimistic search; it's easy to recognize halfwords that can
3081          not be the start of a 32-bit instruction, and use that to
3082          lock on to the instruction boundaries.  */
3083       buf = extend_buffer_earlier (buf, bpaddr, buf_len, IT_SCAN_THRESHOLD);
3084       if (buf == NULL)
3085         return bpaddr;
3086       buf_len = IT_SCAN_THRESHOLD;
3087
3088       definite = 0;
3089       for (i = 0; i < buf_len - sizeof (buf) && ! definite; i += 2)
3090         {
3091           unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
3092           if (thumb_insn_size (inst1) == 2)
3093             {
3094               definite = 1;
3095               break;
3096             }
3097         }
3098
3099       /* At this point, if DEFINITE, BUF[I] is the first place we
3100          are sure that we know the instruction boundaries, and it is far
3101          enough from BPADDR that we could not miss an IT instruction
3102          affecting BPADDR.  If ! DEFINITE, give up - start from a
3103          known boundary.  */
3104       if (! definite)
3105         {
3106           buf = extend_buffer_earlier (buf, bpaddr, buf_len, bpaddr - boundary);
3107           if (buf == NULL)
3108             return bpaddr;
3109           buf_len = bpaddr - boundary;
3110           i = 0;
3111         }
3112     }
3113   else
3114     {
3115       buf = extend_buffer_earlier (buf, bpaddr, buf_len, bpaddr - boundary);
3116       if (buf == NULL)
3117         return bpaddr;
3118       buf_len = bpaddr - boundary;
3119       i = 0;
3120     }
3121
3122   /* Scan forwards.  Find the last IT instruction before BPADDR.  */
3123   last_it = -1;
3124   last_it_count = 0;
3125   while (i < buf_len)
3126     {
3127       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
3128       last_it_count--;
3129       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
3130         {
3131           last_it = i;
3132           if (inst1 & 0x0001)
3133             last_it_count = 4;
3134           else if (inst1 & 0x0002)
3135             last_it_count = 3;
3136           else if (inst1 & 0x0004)
3137             last_it_count = 2;
3138           else
3139             last_it_count = 1;
3140         }
3141       i += thumb_insn_size (inst1);
3142     }
3143
3144   xfree (buf);
3145
3146   if (last_it == -1)
3147     /* There wasn't really an IT instruction after all.  */
3148     return bpaddr;
3149
3150   if (last_it_count < 1)
3151     /* It was too far away.  */
3152     return bpaddr;
3153
3154   /* This really is a trouble spot.  Move the breakpoint to the IT
3155      instruction.  */
3156   return bpaddr - buf_len + last_it;
3157 }
3158
3159 /* ARM displaced stepping support.
3160
3161    Generally ARM displaced stepping works as follows:
3162
3163    1. When an instruction is to be single-stepped, it is first decoded by
3164       arm_process_displaced_insn (called from arm_displaced_step_copy_insn).
3165       Depending on the type of instruction, it is then copied to a scratch
3166       location, possibly in a modified form.  The copy_* set of functions
3167       performs such modification, as necessary. A breakpoint is placed after
3168       the modified instruction in the scratch space to return control to GDB.
3169       Note in particular that instructions which modify the PC will no longer
3170       do so after modification.
3171
3172    2. The instruction is single-stepped, by setting the PC to the scratch
3173       location address, and resuming.  Control returns to GDB when the
3174       breakpoint is hit.
3175
3176    3. A cleanup function (cleanup_*) is called corresponding to the copy_*
3177       function used for the current instruction.  This function's job is to
3178       put the CPU/memory state back to what it would have been if the
3179       instruction had been executed unmodified in its original location.  */
3180
3181 /* NOP instruction (mov r0, r0).  */
3182 #define ARM_NOP                         0xe1a00000
3183
3184 /* Helper for register reads for displaced stepping.  In particular, this
3185    returns the PC as it would be seen by the instruction at its original
3186    location.  */
3187
3188 ULONGEST
3189 displaced_read_reg (struct regcache *regs, CORE_ADDR from, int regno)
3190 {
3191   ULONGEST ret;
3192
3193   if (regno == 15)
3194     {
3195       if (debug_displaced)
3196         fprintf_unfiltered (gdb_stdlog, "displaced: read pc value %.8lx\n",
3197                             (unsigned long) from + 8);
3198       return (ULONGEST) from + 8;  /* Pipeline offset.  */
3199     }
3200   else
3201     {
3202       regcache_cooked_read_unsigned (regs, regno, &ret);
3203       if (debug_displaced)
3204         fprintf_unfiltered (gdb_stdlog, "displaced: read r%d value %.8lx\n",
3205                             regno, (unsigned long) ret);
3206       return ret;
3207     }
3208 }
3209
3210 static int
3211 displaced_in_arm_mode (struct regcache *regs)
3212 {
3213   ULONGEST ps;
3214
3215   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
3216
3217   return (ps & CPSR_T) == 0;
3218 }
3219
3220 /* Write to the PC as from a branch instruction.  */
3221
3222 static void
3223 branch_write_pc (struct regcache *regs, ULONGEST val)
3224 {
3225   if (displaced_in_arm_mode (regs))
3226     /* Note: If bits 0/1 are set, this branch would be unpredictable for
3227        architecture versions < 6.  */
3228     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & ~(ULONGEST) 0x3);
3229   else
3230     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & ~(ULONGEST) 0x1);
3231 }
3232
3233 /* Write to the PC as from a branch-exchange instruction.  */
3234
3235 static void
3236 bx_write_pc (struct regcache *regs, ULONGEST val)
3237 {
3238   ULONGEST ps;
3239
3240   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
3241
3242   if ((val & 1) == 1)
3243     {
3244       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps | CPSR_T);
3245       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffe);
3246     }
3247   else if ((val & 2) == 0)
3248     {
3249       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM,
3250                                       ps & ~(ULONGEST) CPSR_T);
3251       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val);
3252     }
3253   else
3254     {
3255       /* Unpredictable behaviour.  Try to do something sensible (switch to ARM
3256           mode, align dest to 4 bytes).  */
3257       warning (_("Single-stepping BX to non-word-aligned ARM instruction."));
3258       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM,
3259                                       ps & ~(ULONGEST) CPSR_T);
3260       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffc);
3261     }
3262 }
3263
3264 /* Write to the PC as if from a load instruction.  */
3265
3266 static void
3267 load_write_pc (struct regcache *regs, ULONGEST val)
3268 {
3269   if (DISPLACED_STEPPING_ARCH_VERSION >= 5)
3270     bx_write_pc (regs, val);
3271   else
3272     branch_write_pc (regs, val);
3273 }
3274
3275 /* Write to the PC as if from an ALU instruction.  */
3276
3277 static void
3278 alu_write_pc (struct regcache *regs, ULONGEST val)
3279 {
3280   if (DISPLACED_STEPPING_ARCH_VERSION >= 7 && displaced_in_arm_mode (regs))
3281     bx_write_pc (regs, val);
3282   else
3283     branch_write_pc (regs, val);
3284 }
3285
3286 /* Helper for writing to registers for displaced stepping.  Writing to the PC
3287    has a varying effects depending on the instruction which does the write:
3288    this is controlled by the WRITE_PC argument.  */
3289
3290 void
3291 displaced_write_reg (struct regcache *regs, struct displaced_step_closure *dsc,
3292                      int regno, ULONGEST val, enum pc_write_style write_pc)
3293 {
3294   if (regno == 15)
3295     {
3296       if (debug_displaced)
3297         fprintf_unfiltered (gdb_stdlog, "displaced: writing pc %.8lx\n",
3298                             (unsigned long) val);
3299       switch (write_pc)
3300         {
3301         case BRANCH_WRITE_PC:
3302           branch_write_pc (regs, val);
3303           break;
3304
3305         case BX_WRITE_PC:
3306           bx_write_pc (regs, val);
3307           break;
3308
3309         case LOAD_WRITE_PC:
3310           load_write_pc (regs, val);
3311           break;
3312
3313         case ALU_WRITE_PC:
3314           alu_write_pc (regs, val);
3315           break;
3316
3317         case CANNOT_WRITE_PC:
3318           warning (_("Instruction wrote to PC in an unexpected way when "
3319                      "single-stepping"));
3320           break;
3321
3322         default:
3323           internal_error (__FILE__, __LINE__,
3324                           _("Invalid argument to displaced_write_reg"));
3325         }
3326
3327       dsc->wrote_to_pc = 1;
3328     }
3329   else
3330     {
3331       if (debug_displaced)
3332         fprintf_unfiltered (gdb_stdlog, "displaced: writing r%d value %.8lx\n",
3333                             regno, (unsigned long) val);
3334       regcache_cooked_write_unsigned (regs, regno, val);
3335     }
3336 }
3337
3338 /* This function is used to concisely determine if an instruction INSN
3339    references PC.  Register fields of interest in INSN should have the
3340    corresponding fields of BITMASK set to 0b1111.  The function returns return 1
3341    if any of these fields in INSN reference the PC (also 0b1111, r15), else it
3342    returns 0.  */
3343
3344 static int
3345 insn_references_pc (uint32_t insn, uint32_t bitmask)
3346 {
3347   uint32_t lowbit = 1;
3348
3349   while (bitmask != 0)
3350     {
3351       uint32_t mask;
3352
3353       for (; lowbit && (bitmask & lowbit) == 0; lowbit <<= 1)
3354         ;
3355
3356       if (!lowbit)
3357         break;
3358
3359       mask = lowbit * 0xf;
3360
3361       if ((insn & mask) == mask)
3362         return 1;
3363
3364       bitmask &= ~mask;
3365     }
3366
3367   return 0;
3368 }
3369
3370 /* The simplest copy function.  Many instructions have the same effect no
3371    matter what address they are executed at: in those cases, use this.  */
3372
3373 static int
3374 copy_unmodified (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, uint32_t insn,
3375                  const char *iname, struct displaced_step_closure *dsc)
3376 {
3377   if (debug_displaced)
3378     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx, "
3379                         "opcode/class '%s' unmodified\n", (unsigned long) insn,
3380                         iname);
3381
3382   dsc->modinsn[0] = insn;
3383
3384   return 0;
3385 }
3386
3387 /* Preload instructions with immediate offset.  */
3388
3389 static void
3390 cleanup_preload (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
3391                  struct regcache *regs, struct displaced_step_closure *dsc)
3392 {
3393   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
3394   if (!dsc->u.preload.immed)
3395     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
3396 }
3397
3398 static int
3399 copy_preload (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
3400               struct displaced_step_closure *dsc)
3401 {
3402   unsigned int rn = bits (insn, 16, 19);
3403   ULONGEST rn_val;
3404   CORE_ADDR from = dsc->insn_addr;
3405
3406   if (!insn_references_pc (insn, 0x000f0000ul))
3407     return copy_unmodified (gdbarch, insn, "preload", dsc);
3408
3409   if (debug_displaced)
3410     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
3411                         (unsigned long) insn);
3412
3413   /* Preload instructions:
3414
3415      {pli/pld} [rn, #+/-imm]
3416      ->
3417      {pli/pld} [r0, #+/-imm].  */
3418
3419   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3420   rn_val = displaced_read_reg (regs, from, rn);
3421   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
3422
3423   dsc->u.preload.immed = 1;
3424
3425   dsc->modinsn[0] = insn & 0xfff0ffff;
3426
3427   dsc->cleanup = &cleanup_preload;
3428
3429   return 0;
3430 }
3431
3432 /* Preload instructions with register offset.  */
3433
3434 static int
3435 copy_preload_reg (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
3436                   struct displaced_step_closure *dsc)
3437 {
3438   unsigned int rn = bits (insn, 16, 19);
3439   unsigned int rm = bits (insn, 0, 3);
3440   ULONGEST rn_val, rm_val;
3441   CORE_ADDR from = dsc->insn_addr;
3442
3443   if (!insn_references_pc (insn, 0x000f000ful))
3444     return copy_unmodified (gdbarch, insn, "preload reg", dsc);
3445
3446   if (debug_displaced)
3447     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
3448                         (unsigned long) insn);
3449
3450   /* Preload register-offset instructions:
3451
3452      {pli/pld} [rn, rm {, shift}]
3453      ->
3454      {pli/pld} [r0, r1 {, shift}].  */
3455
3456   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3457   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
3458   rn_val = displaced_read_reg (regs, from, rn);
3459   rm_val = displaced_read_reg (regs, from, rm);
3460   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
3461   displaced_write_reg (regs, dsc, 1, rm_val, CANNOT_WRITE_PC);
3462
3463   dsc->u.preload.immed = 0;
3464
3465   dsc->modinsn[0] = (insn & 0xfff0fff0) | 0x1;
3466
3467   dsc->cleanup = &cleanup_preload;
3468
3469   return 0;
3470 }
3471
3472 /* Copy/cleanup coprocessor load and store instructions.  */
3473
3474 static void
3475 cleanup_copro_load_store (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
3476                           struct regcache *regs,
3477                           struct displaced_step_closure *dsc)
3478 {
3479   ULONGEST rn_val = displaced_read_reg (regs, dsc->insn_addr, 0);
3480
3481   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
3482
3483   if (dsc->u.ldst.writeback)
3484     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, LOAD_WRITE_PC);
3485 }
3486
3487 static int
3488 copy_copro_load_store (struct gdbarch *gdbarch, uint32_t insn,
3489                        struct regcache *regs,
3490                        struct displaced_step_closure *dsc)
3491 {
3492   unsigned int rn = bits (insn, 16, 19);
3493   ULONGEST rn_val;
3494   CORE_ADDR from = dsc->insn_addr;
3495
3496   if (!insn_references_pc (insn, 0x000f0000ul))
3497     return copy_unmodified (gdbarch, insn, "copro load/store", dsc);
3498
3499   if (debug_displaced)
3500     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
3501                         "load/store insn %.8lx\n", (unsigned long) insn);
3502
3503   /* Coprocessor load/store instructions:
3504
3505      {stc/stc2} [<Rn>, #+/-imm]  (and other immediate addressing modes)
3506      ->
3507      {stc/stc2} [r0, #+/-imm].
3508
3509      ldc/ldc2 are handled identically.  */
3510
3511   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3512   rn_val = displaced_read_reg (regs, from, rn);
3513   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
3514
3515   dsc->u.ldst.writeback = bit (insn, 25);
3516   dsc->u.ldst.rn = rn;
3517
3518   dsc->modinsn[0] = insn & 0xfff0ffff;
3519
3520   dsc->cleanup = &cleanup_copro_load_store;
3521
3522   return 0;
3523 }
3524
3525 /* Clean up branch instructions (actually perform the branch, by setting
3526    PC).  */
3527
3528 static void
3529 cleanup_branch (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, struct regcache *regs,
3530                 struct displaced_step_closure *dsc)
3531 {
3532   ULONGEST from = dsc->insn_addr;
3533   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
3534   int branch_taken = condition_true (dsc->u.branch.cond, status);
3535   enum pc_write_style write_pc = dsc->u.branch.exchange
3536                                  ? BX_WRITE_PC : BRANCH_WRITE_PC;
3537
3538   if (!branch_taken)
3539     return;
3540
3541   if (dsc->u.branch.link)
3542     {
3543       ULONGEST pc = displaced_read_reg (regs, from, 15);
3544       displaced_write_reg (regs, dsc, 14, pc - 4, CANNOT_WRITE_PC);
3545     }
3546
3547   displaced_write_reg (regs, dsc, 15, dsc->u.branch.dest, write_pc);
3548 }
3549
3550 /* Copy B/BL/BLX instructions with immediate destinations.  */
3551
3552 static int
3553 copy_b_bl_blx (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, uint32_t insn,
3554                struct regcache *regs, struct displaced_step_closure *dsc)
3555 {
3556   unsigned int cond = bits (insn, 28, 31);
3557   int exchange = (cond == 0xf);
3558   int link = exchange || bit (insn, 24);
3559   CORE_ADDR from = dsc->insn_addr;
3560   long offset;
3561
3562   if (debug_displaced)
3563     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s immediate insn "
3564                         "%.8lx\n", (exchange) ? "blx" : (link) ? "bl" : "b",
3565                         (unsigned long) insn);
3566
3567   /* Implement "BL<cond> <label>" as:
3568
3569      Preparation: cond <- instruction condition
3570      Insn: mov r0, r0  (nop)
3571      Cleanup: if (condition true) { r14 <- pc; pc <- label }.
3572
3573      B<cond> similar, but don't set r14 in cleanup.  */
3574
3575   if (exchange)
3576     /* For BLX, set bit 0 of the destination.  The cleanup_branch function will
3577        then arrange the switch into Thumb mode.  */
3578     offset = (bits (insn, 0, 23) << 2) | (bit (insn, 24) << 1) | 1;
3579   else
3580     offset = bits (insn, 0, 23) << 2;
3581
3582   if (bit (offset, 25))
3583     offset = offset | ~0x3ffffff;
3584
3585   dsc->u.branch.cond = cond;
3586   dsc->u.branch.link = link;
3587   dsc->u.branch.exchange = exchange;
3588   dsc->u.branch.dest = from + 8 + offset;
3589
3590   dsc->modinsn[0] = ARM_NOP;
3591
3592   dsc->cleanup = &cleanup_branch;
3593
3594   return 0;
3595 }
3596
3597 /* Copy BX/BLX with register-specified destinations.  */
3598
3599 static int
3600 copy_bx_blx_reg (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, uint32_t insn,
3601                  struct regcache *regs, struct displaced_step_closure *dsc)
3602 {
3603   unsigned int cond = bits (insn, 28, 31);
3604   /* BX:  x12xxx1x
3605      BLX: x12xxx3x.  */
3606   int link = bit (insn, 5);
3607   unsigned int rm = bits (insn, 0, 3);
3608   CORE_ADDR from = dsc->insn_addr;
3609
3610   if (debug_displaced)
3611     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s register insn "
3612                         "%.8lx\n", (link) ? "blx" : "bx", (unsigned long) insn);
3613
3614   /* Implement {BX,BLX}<cond> <reg>" as:
3615
3616      Preparation: cond <- instruction condition
3617      Insn: mov r0, r0 (nop)
3618      Cleanup: if (condition true) { r14 <- pc; pc <- dest; }.
3619
3620      Don't set r14 in cleanup for BX.  */
3621
3622   dsc->u.branch.dest = displaced_read_reg (regs, from, rm);
3623
3624   dsc->u.branch.cond = cond;
3625   dsc->u.branch.link = link;
3626   dsc->u.branch.exchange = 1;
3627
3628   dsc->modinsn[0] = ARM_NOP;
3629
3630   dsc->cleanup = &cleanup_branch;
3631
3632   return 0;
3633 }
3634
3635 /* Copy/cleanup arithmetic/logic instruction with immediate RHS. */
3636
3637 static void
3638 cleanup_alu_imm (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
3639                  struct regcache *regs, struct displaced_step_closure *dsc)
3640 {
3641   ULONGEST rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
3642   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
3643   displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
3644   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
3645 }
3646
3647 static int
3648 copy_alu_imm (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
3649               struct displaced_step_closure *dsc)
3650 {
3651   unsigned int rn = bits (insn, 16, 19);
3652   unsigned int rd = bits (insn, 12, 15);
3653   unsigned int op = bits (insn, 21, 24);
3654   int is_mov = (op == 0xd);
3655   ULONGEST rd_val, rn_val;
3656   CORE_ADDR from = dsc->insn_addr;
3657
3658   if (!insn_references_pc (insn, 0x000ff000ul))
3659     return copy_unmodified (gdbarch, insn, "ALU immediate", dsc);
3660
3661   if (debug_displaced)
3662     fprintf_unfiltered (gdb_stdlog, "displaced: copying immediate %s insn "
3663                         "%.8lx\n", is_mov ? "move" : "ALU",
3664                         (unsigned long) insn);
3665
3666   /* Instruction is of form:
3667
3668      <op><cond> rd, [rn,] #imm
3669
3670      Rewrite as:
3671
3672      Preparation: tmp1, tmp2 <- r0, r1;
3673                   r0, r1 <- rd, rn
3674      Insn: <op><cond> r0, r1, #imm
3675      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
3676   */
3677
3678   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3679   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
3680   rn_val = displaced_read_reg (regs, from, rn);
3681   rd_val = displaced_read_reg (regs, from, rd);
3682   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
3683   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
3684   dsc->rd = rd;
3685
3686   if (is_mov)
3687     dsc->modinsn[0] = insn & 0xfff00fff;
3688   else
3689     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x10000;
3690
3691   dsc->cleanup = &cleanup_alu_imm;
3692
3693   return 0;
3694 }
3695
3696 /* Copy/cleanup arithmetic/logic insns with register RHS.  */
3697
3698 static void
3699 cleanup_alu_reg (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
3700                  struct regcache *regs, struct displaced_step_closure *dsc)
3701 {
3702   ULONGEST rd_val;
3703   int i;
3704
3705   rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
3706
3707   for (i = 0; i < 3; i++)
3708     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
3709
3710   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
3711 }
3712
3713 static int
3714 copy_alu_reg (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
3715               struct displaced_step_closure *dsc)
3716 {
3717   unsigned int rn = bits (insn, 16, 19);
3718   unsigned int rm = bits (insn, 0, 3);
3719   unsigned int rd = bits (insn, 12, 15);
3720   unsigned int op = bits (insn, 21, 24);
3721   int is_mov = (op == 0xd);
3722   ULONGEST rd_val, rn_val, rm_val;
3723   CORE_ADDR from = dsc->insn_addr;
3724
3725   if (!insn_references_pc (insn, 0x000ff00ful))
3726     return copy_unmodified (gdbarch, insn, "ALU reg", dsc);
3727
3728   if (debug_displaced)
3729     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.8lx\n",
3730                         is_mov ? "move" : "ALU", (unsigned long) insn);
3731
3732   /* Instruction is of form:
3733
3734      <op><cond> rd, [rn,] rm [, <shift>]
3735
3736      Rewrite as:
3737
3738      Preparation: tmp1, tmp2, tmp3 <- r0, r1, r2;
3739                   r0, r1, r2 <- rd, rn, rm
3740      Insn: <op><cond> r0, r1, r2 [, <shift>]
3741      Cleanup: rd <- r0; r0, r1, r2 <- tmp1, tmp2, tmp3
3742   */
3743
3744   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3745   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
3746   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
3747   rd_val = displaced_read_reg (regs, from, rd);
3748   rn_val = displaced_read_reg (regs, from, rn);
3749   rm_val = displaced_read_reg (regs, from, rm);
3750   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
3751   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
3752   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
3753   dsc->rd = rd;
3754
3755   if (is_mov)
3756     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x2;
3757   else
3758     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x10002;
3759
3760   dsc->cleanup = &cleanup_alu_reg;
3761
3762   return 0;
3763 }
3764
3765 /* Cleanup/copy arithmetic/logic insns with shifted register RHS.  */
3766
3767 static void
3768 cleanup_alu_shifted_reg (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
3769                          struct regcache *regs,
3770                          struct displaced_step_closure *dsc)
3771 {
3772   ULONGEST rd_val = displaced_read_reg (regs, dsc->insn_addr, 0);
3773   int i;
3774
3775   for (i = 0; i < 4; i++)
3776     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
3777
3778   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
3779 }
3780
3781 static int
3782 copy_alu_shifted_reg (struct gdbarch *gdbarch, uint32_t insn,
3783                       struct regcache *regs, struct displaced_step_closure *dsc)
3784 {
3785   unsigned int rn = bits (insn, 16, 19);
3786   unsigned int rm = bits (insn, 0, 3);
3787   unsigned int rd = bits (insn, 12, 15);
3788   unsigned int rs = bits (insn, 8, 11);
3789   unsigned int op = bits (insn, 21, 24);
3790   int is_mov = (op == 0xd), i;
3791   ULONGEST rd_val, rn_val, rm_val, rs_val;
3792   CORE_ADDR from = dsc->insn_addr;
3793
3794   if (!insn_references_pc (insn, 0x000fff0ful))
3795     return copy_unmodified (gdbarch, insn, "ALU shifted reg", dsc);
3796
3797   if (debug_displaced)
3798     fprintf_unfiltered (gdb_stdlog, "displaced: copying shifted reg %s insn "
3799                         "%.8lx\n", is_mov ? "move" : "ALU",
3800                         (unsigned long) insn);
3801
3802   /* Instruction is of form:
3803
3804      <op><cond> rd, [rn,] rm, <shift> rs
3805
3806      Rewrite as:
3807
3808      Preparation: tmp1, tmp2, tmp3, tmp4 <- r0, r1, r2, r3
3809                   r0, r1, r2, r3 <- rd, rn, rm, rs
3810      Insn: <op><cond> r0, r1, r2, <shift> r3
3811      Cleanup: tmp5 <- r0
3812               r0, r1, r2, r3 <- tmp1, tmp2, tmp3, tmp4
3813               rd <- tmp5
3814   */
3815
3816   for (i = 0; i < 4; i++)
3817     dsc->tmp[i] = displaced_read_reg (regs, from, i);
3818
3819   rd_val = displaced_read_reg (regs, from, rd);
3820   rn_val = displaced_read_reg (regs, from, rn);
3821   rm_val = displaced_read_reg (regs, from, rm);
3822   rs_val = displaced_read_reg (regs, from, rs);
3823   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
3824   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
3825   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
3826   displaced_write_reg (regs, dsc, 3, rs_val, CANNOT_WRITE_PC);
3827   dsc->rd = rd;
3828
3829   if (is_mov)
3830     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x302;
3831   else
3832     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x10302;
3833
3834   dsc->cleanup = &cleanup_alu_shifted_reg;
3835
3836   return 0;
3837 }
3838
3839 /* Clean up load instructions.  */
3840
3841 static void
3842 cleanup_load (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, struct regcache *regs,
3843               struct displaced_step_closure *dsc)
3844 {
3845   ULONGEST rt_val, rt_val2 = 0, rn_val;
3846   CORE_ADDR from = dsc->insn_addr;
3847
3848   rt_val = displaced_read_reg (regs, from, 0);
3849   if (dsc->u.ldst.xfersize == 8)
3850     rt_val2 = displaced_read_reg (regs, from, 1);
3851   rn_val = displaced_read_reg (regs, from, 2);
3852
3853   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
3854   if (dsc->u.ldst.xfersize > 4)
3855     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
3856   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
3857   if (!dsc->u.ldst.immed)
3858     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
3859
3860   /* Handle register writeback.  */
3861   if (dsc->u.ldst.writeback)
3862     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
3863   /* Put result in right place.  */
3864   displaced_write_reg (regs, dsc, dsc->rd, rt_val, LOAD_WRITE_PC);
3865   if (dsc->u.ldst.xfersize == 8)
3866     displaced_write_reg (regs, dsc, dsc->rd + 1, rt_val2, LOAD_WRITE_PC);
3867 }
3868
3869 /* Clean up store instructions.  */
3870
3871 static void
3872 cleanup_store (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, struct regcache *regs,
3873                struct displaced_step_closure *dsc)
3874 {
3875   CORE_ADDR from = dsc->insn_addr;
3876   ULONGEST rn_val = displaced_read_reg (regs, from, 2);
3877
3878   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
3879   if (dsc->u.ldst.xfersize > 4)
3880     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
3881   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
3882   if (!dsc->u.ldst.immed)
3883     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
3884   if (!dsc->u.ldst.restore_r4)
3885     displaced_write_reg (regs, dsc, 4, dsc->tmp[4], CANNOT_WRITE_PC);
3886
3887   /* Writeback.  */
3888   if (dsc->u.ldst.writeback)
3889     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
3890 }
3891
3892 /* Copy "extra" load/store instructions.  These are halfword/doubleword
3893    transfers, which have a different encoding to byte/word transfers.  */
3894
3895 static int
3896 copy_extra_ld_st (struct gdbarch *gdbarch, uint32_t insn, int unpriveleged,
3897                   struct regcache *regs, struct displaced_step_closure *dsc)
3898 {
3899   unsigned int op1 = bits (insn, 20, 24);
3900   unsigned int op2 = bits (insn, 5, 6);
3901   unsigned int rt = bits (insn, 12, 15);
3902   unsigned int rn = bits (insn, 16, 19);
3903   unsigned int rm = bits (insn, 0, 3);
3904   char load[12]     = {0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1};
3905   char bytesize[12] = {2, 2, 2, 2, 8, 1, 8, 1, 8, 2, 8, 2};
3906   int immed = (op1 & 0x4) != 0;
3907   int opcode;
3908   ULONGEST rt_val, rt_val2 = 0, rn_val, rm_val = 0;
3909   CORE_ADDR from = dsc->insn_addr;
3910
3911   if (!insn_references_pc (insn, 0x000ff00ful))
3912     return copy_unmodified (gdbarch, insn, "extra load/store", dsc);
3913
3914   if (debug_displaced)
3915     fprintf_unfiltered (gdb_stdlog, "displaced: copying %sextra load/store "
3916                         "insn %.8lx\n", unpriveleged ? "unpriveleged " : "",
3917                         (unsigned long) insn);
3918
3919   opcode = ((op2 << 2) | (op1 & 0x1) | ((op1 & 0x4) >> 1)) - 4;
3920
3921   if (opcode < 0)
3922     internal_error (__FILE__, __LINE__,
3923                     _("copy_extra_ld_st: instruction decode error"));
3924
3925   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3926   dsc->tmp[1] = displaced_read_reg (regs, from, 1);
3927   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
3928   if (!immed)
3929     dsc->tmp[3] = displaced_read_reg (regs, from, 3);
3930
3931   rt_val = displaced_read_reg (regs, from, rt);
3932   if (bytesize[opcode] == 8)
3933     rt_val2 = displaced_read_reg (regs, from, rt + 1);
3934   rn_val = displaced_read_reg (regs, from, rn);
3935   if (!immed)
3936     rm_val = displaced_read_reg (regs, from, rm);
3937
3938   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
3939   if (bytesize[opcode] == 8)
3940     displaced_write_reg (regs, dsc, 1, rt_val2, CANNOT_WRITE_PC);
3941   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
3942   if (!immed)
3943     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
3944
3945   dsc->rd = rt;
3946   dsc->u.ldst.xfersize = bytesize[opcode];
3947   dsc->u.ldst.rn = rn;
3948   dsc->u.ldst.immed = immed;
3949   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
3950   dsc->u.ldst.restore_r4 = 0;
3951
3952   if (immed)
3953     /* {ldr,str}<width><cond> rt, [rt2,] [rn, #imm]
3954         ->
3955        {ldr,str}<width><cond> r0, [r1,] [r2, #imm].  */
3956     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
3957   else
3958     /* {ldr,str}<width><cond> rt, [rt2,] [rn, +/-rm]
3959         ->
3960        {ldr,str}<width><cond> r0, [r1,] [r2, +/-r3].  */
3961     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
3962
3963   dsc->cleanup = load[opcode] ? &cleanup_load : &cleanup_store;
3964
3965   return 0;
3966 }
3967
3968 /* Copy byte/word loads and stores.  */
3969
3970 static int
3971 copy_ldr_str_ldrb_strb (struct gdbarch *gdbarch, uint32_t insn,
3972                         struct regcache *regs,
3973                         struct displaced_step_closure *dsc, int load, int byte,
3974                         int usermode)
3975 {
3976   int immed = !bit (insn, 25);
3977   unsigned int rt = bits (insn, 12, 15);
3978   unsigned int rn = bits (insn, 16, 19);
3979   unsigned int rm = bits (insn, 0, 3);  /* Only valid if !immed.  */
3980   ULONGEST rt_val, rn_val, rm_val = 0;
3981   CORE_ADDR from = dsc->insn_addr;
3982
3983   if (!insn_references_pc (insn, 0x000ff00ful))
3984     return copy_unmodified (gdbarch, insn, "load/store", dsc);
3985
3986   if (debug_displaced)
3987     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s%s insn %.8lx\n",
3988                         load ? (byte ? "ldrb" : "ldr")
3989                              : (byte ? "strb" : "str"), usermode ? "t" : "",
3990                         (unsigned long) insn);
3991
3992   dsc->tmp[0] = displaced_read_reg (regs, from, 0);
3993   dsc->tmp[2] = displaced_read_reg (regs, from, 2);
3994   if (!immed)
3995     dsc->tmp[3] = displaced_read_reg (regs, from, 3);
3996   if (!load)
3997     dsc->tmp[4] = displaced_read_reg (regs, from, 4);
3998
3999   rt_val = displaced_read_reg (regs, from, rt);
4000   rn_val = displaced_read_reg (regs, from, rn);
4001   if (!immed)
4002     rm_val = displaced_read_reg (regs, from, rm);
4003
4004   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
4005   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
4006   if (!immed)
4007     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
4008
4009   dsc->rd = rt;
4010   dsc->u.ldst.xfersize = byte ? 1 : 4;
4011   dsc->u.ldst.rn = rn;
4012   dsc->u.ldst.immed = immed;
4013   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
4014
4015   /* To write PC we can do:
4016
4017      scratch+0:  str pc, temp  (*temp = scratch + 8 + offset)
4018      scratch+4:  ldr r4, temp
4019      scratch+8:  sub r4, r4, pc  (r4 = scratch + 8 + offset - scratch - 8 - 8)
4020      scratch+12: add r4, r4, #8  (r4 = offset)
4021      scratch+16: add r0, r0, r4
4022      scratch+20: str r0, [r2, #imm] (or str r0, [r2, r3])
4023      scratch+24: <temp>
4024
4025      Otherwise we don't know what value to write for PC, since the offset is
4026      architecture-dependent (sometimes PC+8, sometimes PC+12).  */
4027
4028   if (load || rt != 15)
4029     {
4030       dsc->u.ldst.restore_r4 = 0;
4031
4032       if (immed)
4033         /* {ldr,str}[b]<cond> rt, [rn, #imm], etc.
4034            ->
4035            {ldr,str}[b]<cond> r0, [r2, #imm].  */
4036         dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
4037       else
4038         /* {ldr,str}[b]<cond> rt, [rn, rm], etc.
4039            ->
4040            {ldr,str}[b]<cond> r0, [r2, r3].  */
4041         dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
4042     }
4043   else
4044     {
4045       /* We need to use r4 as scratch.  Make sure it's restored afterwards.  */
4046       dsc->u.ldst.restore_r4 = 1;
4047
4048       dsc->modinsn[0] = 0xe58ff014;  /* str pc, [pc, #20].  */
4049       dsc->modinsn[1] = 0xe59f4010;  /* ldr r4, [pc, #16].  */
4050       dsc->modinsn[2] = 0xe044400f;  /* sub r4, r4, pc.  */
4051       dsc->modinsn[3] = 0xe2844008;  /* add r4, r4, #8.  */
4052       dsc->modinsn[4] = 0xe0800004;  /* add r0, r0, r4.  */
4053
4054       /* As above.  */
4055       if (immed)
4056         dsc->modinsn[5] = (insn & 0xfff00fff) | 0x20000;
4057       else
4058         dsc->modinsn[5] = (insn & 0xfff00ff0) | 0x20003;
4059
4060       dsc->modinsn[6] = 0x0;  /* breakpoint location.  */
4061       dsc->modinsn[7] = 0x0;  /* scratch space.  */
4062
4063       dsc->numinsns = 6;
4064     }
4065
4066   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
4067
4068   return 0;
4069 }
4070
4071 /* Cleanup LDM instructions with fully-populated register list.  This is an
4072    unfortunate corner case: it's impossible to implement correctly by modifying
4073    the instruction.  The issue is as follows: we have an instruction,
4074
4075    ldm rN, {r0-r15}
4076
4077    which we must rewrite to avoid loading PC.  A possible solution would be to
4078    do the load in two halves, something like (with suitable cleanup
4079    afterwards):
4080
4081    mov r8, rN
4082    ldm[id][ab] r8!, {r0-r7}
4083    str r7, <temp>
4084    ldm[id][ab] r8, {r7-r14}
4085    <bkpt>
4086
4087    but at present there's no suitable place for <temp>, since the scratch space
4088    is overwritten before the cleanup routine is called.  For now, we simply
4089    emulate the instruction.  */
4090
4091 static void
4092 cleanup_block_load_all (struct gdbarch *gdbarch, struct regcache *regs,
4093                         struct displaced_step_closure *dsc)
4094 {
4095   ULONGEST from = dsc->insn_addr;
4096   int inc = dsc->u.block.increment;
4097   int bump_before = dsc->u.block.before ? (inc ? 4 : -4) : 0;
4098   int bump_after = dsc->u.block.before ? 0 : (inc ? 4 : -4);
4099   uint32_t regmask = dsc->u.block.regmask;
4100   int regno = inc ? 0 : 15;
4101   CORE_ADDR xfer_addr = dsc->u.block.xfer_addr;
4102   int exception_return = dsc->u.block.load && dsc->u.block.user
4103                          && (regmask & 0x8000) != 0;
4104   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
4105   int do_transfer = condition_true (dsc->u.block.cond, status);
4106   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4107
4108   if (!do_transfer)
4109     return;
4110
4111   /* If the instruction is ldm rN, {...pc}^, I don't think there's anything
4112      sensible we can do here.  Complain loudly.  */
4113   if (exception_return)
4114     error (_("Cannot single-step exception return"));
4115
4116   /* We don't handle any stores here for now.  */
4117   gdb_assert (dsc->u.block.load != 0);
4118
4119   if (debug_displaced)
4120     fprintf_unfiltered (gdb_stdlog, "displaced: emulating block transfer: "
4121                         "%s %s %s\n", dsc->u.block.load ? "ldm" : "stm",
4122                         dsc->u.block.increment ? "inc" : "dec",
4123                         dsc->u.block.before ? "before" : "after");
4124
4125   while (regmask)
4126     {
4127       uint32_t memword;
4128
4129       if (inc)
4130         while (regno <= 15 && (regmask & (1 << regno)) == 0)
4131           regno++;
4132       else
4133         while (regno >= 0 && (regmask & (1 << regno)) == 0)
4134           regno--;
4135
4136       xfer_addr += bump_before;
4137
4138       memword = read_memory_unsigned_integer (xfer_addr, 4, byte_order);
4139       displaced_write_reg (regs, dsc, regno, memword, LOAD_WRITE_PC);
4140
4141       xfer_addr += bump_after;
4142
4143       regmask &= ~(1 << regno);
4144     }
4145
4146   if (dsc->u.block.writeback)
4147     displaced_write_reg (regs, dsc, dsc->u.block.rn, xfer_addr,
4148                          CANNOT_WRITE_PC);
4149 }
4150
4151 /* Clean up an STM which included the PC in the register list.  */
4152
4153 static void
4154 cleanup_block_store_pc (struct gdbarch *gdbarch, struct regcache *regs,
4155                         struct displaced_step_closure *dsc)
4156 {
4157   ULONGEST from = dsc->insn_addr;
4158   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
4159   int store_executed = condition_true (dsc->u.block.cond, status);
4160   CORE_ADDR pc_stored_at, transferred_regs = bitcount (dsc->u.block.regmask);
4161   CORE_ADDR stm_insn_addr;
4162   uint32_t pc_val;
4163   long offset;
4164   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4165
4166   /* If condition code fails, there's nothing else to do.  */
4167   if (!store_executed)
4168     return;
4169
4170   if (dsc->u.block.increment)
4171     {
4172       pc_stored_at = dsc->u.block.xfer_addr + 4 * transferred_regs;
4173
4174       if (dsc->u.block.before)
4175          pc_stored_at += 4;
4176     }
4177   else
4178     {
4179       pc_stored_at = dsc->u.block.xfer_addr;
4180
4181       if (dsc->u.block.before)
4182          pc_stored_at -= 4;
4183     }
4184
4185   pc_val = read_memory_unsigned_integer (pc_stored_at, 4, byte_order);
4186   stm_insn_addr = dsc->scratch_base;
4187   offset = pc_val - stm_insn_addr;
4188
4189   if (debug_displaced)
4190     fprintf_unfiltered (gdb_stdlog, "displaced: detected PC offset %.8lx for "
4191                         "STM instruction\n", offset);
4192
4193   /* Rewrite the stored PC to the proper value for the non-displaced original
4194      instruction.  */
4195   write_memory_unsigned_integer (pc_stored_at, 4, byte_order,
4196                                  dsc->insn_addr + offset);
4197 }
4198
4199 /* Clean up an LDM which includes the PC in the register list.  We clumped all
4200    the registers in the transferred list into a contiguous range r0...rX (to
4201    avoid loading PC directly and losing control of the debugged program), so we
4202    must undo that here.  */
4203
4204 static void
4205 cleanup_block_load_pc (struct gdbarch *gdbarch ATTRIBUTE_UNUSED,
4206                        struct regcache *regs,
4207                        struct displaced_step_closure *dsc)
4208 {
4209   ULONGEST from = dsc->insn_addr;
4210   uint32_t status = displaced_read_reg (regs, from, ARM_PS_REGNUM);
4211   int load_executed = condition_true (dsc->u.block.cond, status), i;
4212   unsigned int mask = dsc->u.block.regmask, write_reg = 15;
4213   unsigned int regs_loaded = bitcount (mask);
4214   unsigned int num_to_shuffle = regs_loaded, clobbered;
4215
4216   /* The method employed here will fail if the register list is fully populated
4217      (we need to avoid loading PC directly).  */
4218   gdb_assert (num_to_shuffle < 16);
4219
4220   if (!load_executed)
4221     return;
4222
4223   clobbered = (1 << num_to_shuffle) - 1;
4224
4225   while (num_to_shuffle > 0)
4226     {
4227       if ((mask & (1 << write_reg)) != 0)
4228         {
4229           unsigned int read_reg = num_to_shuffle - 1;
4230
4231           if (read_reg != write_reg)
4232             {
4233               ULONGEST rval = displaced_read_reg (regs, from, read_reg);
4234               displaced_write_reg (regs, dsc, write_reg, rval, LOAD_WRITE_PC);
4235               if (debug_displaced)
4236                 fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: move "
4237                                     "loaded register r%d to r%d\n"), read_reg,
4238                                     write_reg);
4239             }
4240           else if (debug_displaced)
4241             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: register "
4242                                 "r%d already in the right place\n"),
4243                                 write_reg);
4244
4245           clobbered &= ~(1 << write_reg);
4246
4247           num_to_shuffle--;
4248         }
4249
4250       write_reg--;
4251     }
4252
4253   /* Restore any registers we scribbled over.  */
4254   for (write_reg = 0; clobbered != 0; write_reg++)
4255     {
4256       if ((clobbered & (1 << write_reg)) != 0)
4257         {
4258           displaced_write_reg (regs, dsc, write_reg, dsc->tmp[write_reg],
4259                                CANNOT_WRITE_PC);
4260           if (debug_displaced)
4261             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: restored "
4262                                 "clobbered register r%d\n"), write_reg);
4263           clobbered &= ~(1 << write_reg);
4264         }
4265     }
4266
4267   /* Perform register writeback manually.  */
4268   if (dsc->u.block.writeback)
4269     {
4270       ULONGEST new_rn_val = dsc->u.block.xfer_addr;
4271
4272       if (dsc->u.block.increment)
4273         new_rn_val += regs_loaded * 4;
4274       else
4275         new_rn_val -= regs_loaded * 4;
4276
4277       displaced_write_reg (regs, dsc, dsc->u.block.rn, new_rn_val,
4278                            CANNOT_WRITE_PC);
4279     }
4280 }
4281
4282 /* Handle ldm/stm, apart from some tricky cases which are unlikely to occur
4283    in user-level code (in particular exception return, ldm rn, {...pc}^).  */
4284
4285 static int
4286 copy_block_xfer (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
4287                  struct displaced_step_closure *dsc)
4288 {
4289   int load = bit (insn, 20);
4290   int user = bit (insn, 22);
4291   int increment = bit (insn, 23);
4292   int before = bit (insn, 24);
4293   int writeback = bit (insn, 21);
4294   int rn = bits (insn, 16, 19);
4295   CORE_ADDR from = dsc->insn_addr;
4296
4297   /* Block transfers which don't mention PC can be run directly out-of-line.  */
4298   if (rn != 15 && (insn & 0x8000) == 0)
4299     return copy_unmodified (gdbarch, insn, "ldm/stm", dsc);
4300
4301   if (rn == 15)
4302     {
4303       warning (_("displaced: Unpredictable LDM or STM with base register r15"));
4304       return copy_unmodified (gdbarch, insn, "unpredictable ldm/stm", dsc);
4305     }
4306
4307   if (debug_displaced)
4308     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
4309                         "%.8lx\n", (unsigned long) insn);
4310
4311   dsc->u.block.xfer_addr = displaced_read_reg (regs, from, rn);
4312   dsc->u.block.rn = rn;
4313
4314   dsc->u.block.load = load;
4315   dsc->u.block.user = user;
4316   dsc->u.block.increment = increment;
4317   dsc->u.block.before = before;
4318   dsc->u.block.writeback = writeback;
4319   dsc->u.block.cond = bits (insn, 28, 31);
4320
4321   dsc->u.block.regmask = insn & 0xffff;
4322
4323   if (load)
4324     {
4325       if ((insn & 0xffff) == 0xffff)
4326         {
4327           /* LDM with a fully-populated register list.  This case is
4328              particularly tricky.  Implement for now by fully emulating the
4329              instruction (which might not behave perfectly in all cases, but
4330              these instructions should be rare enough for that not to matter
4331              too much).  */
4332           dsc->modinsn[0] = ARM_NOP;
4333
4334           dsc->cleanup = &cleanup_block_load_all;
4335         }
4336       else
4337         {
4338           /* LDM of a list of registers which includes PC.  Implement by
4339              rewriting the list of registers to be transferred into a
4340              contiguous chunk r0...rX before doing the transfer, then shuffling
4341              registers into the correct places in the cleanup routine.  */
4342           unsigned int regmask = insn & 0xffff;
4343           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
4344           unsigned int to = 0, from = 0, i, new_rn;
4345
4346           for (i = 0; i < num_in_list; i++)
4347             dsc->tmp[i] = displaced_read_reg (regs, from, i);
4348
4349           /* Writeback makes things complicated.  We need to avoid clobbering
4350              the base register with one of the registers in our modified
4351              register list, but just using a different register can't work in
4352              all cases, e.g.:
4353
4354                ldm r14!, {r0-r13,pc}
4355
4356              which would need to be rewritten as:
4357
4358                ldm rN!, {r0-r14}
4359
4360              but that can't work, because there's no free register for N.
4361
4362              Solve this by turning off the writeback bit, and emulating
4363              writeback manually in the cleanup routine.  */
4364
4365           if (writeback)
4366             insn &= ~(1 << 21);
4367
4368           new_regmask = (1 << num_in_list) - 1;
4369
4370           if (debug_displaced)
4371             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
4372                                 "{..., pc}: original reg list %.4x, modified "
4373                                 "list %.4x\n"), rn, writeback ? "!" : "",
4374                                 (int) insn & 0xffff, new_regmask);
4375
4376           dsc->modinsn[0] = (insn & ~0xffff) | (new_regmask & 0xffff);
4377
4378           dsc->cleanup = &cleanup_block_load_pc;
4379         }
4380     }
4381   else
4382     {
4383       /* STM of a list of registers which includes PC.  Run the instruction
4384          as-is, but out of line: this will store the wrong value for the PC,
4385          so we must manually fix up the memory in the cleanup routine.
4386          Doing things this way has the advantage that we can auto-detect
4387          the offset of the PC write (which is architecture-dependent) in
4388          the cleanup routine.  */
4389       dsc->modinsn[0] = insn;
4390
4391       dsc->cleanup = &cleanup_block_store_pc;
4392     }
4393
4394   return 0;
4395 }
4396
4397 /* Cleanup/copy SVC (SWI) instructions.  These two functions are overridden
4398    for Linux, where some SVC instructions must be treated specially.  */
4399
4400 static void
4401 cleanup_svc (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, struct regcache *regs,
4402              struct displaced_step_closure *dsc)
4403 {
4404   CORE_ADDR from = dsc->insn_addr;
4405   CORE_ADDR resume_addr = from + 4;
4406
4407   if (debug_displaced)
4408     fprintf_unfiltered (gdb_stdlog, "displaced: cleanup for svc, resume at "
4409                         "%.8lx\n", (unsigned long) resume_addr);
4410
4411   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, resume_addr, BRANCH_WRITE_PC);
4412 }
4413
4414 static int
4415 copy_svc (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
4416           struct regcache *regs, struct displaced_step_closure *dsc)
4417 {
4418   CORE_ADDR from = dsc->insn_addr;
4419
4420   /* Allow OS-specific code to override SVC handling.  */
4421   if (dsc->u.svc.copy_svc_os)
4422     return dsc->u.svc.copy_svc_os (gdbarch, insn, to, regs, dsc);
4423
4424   if (debug_displaced)
4425     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.8lx\n",
4426                         (unsigned long) insn);
4427
4428   /* Preparation: none.
4429      Insn: unmodified svc.
4430      Cleanup: pc <- insn_addr + 4.  */
4431
4432   dsc->modinsn[0] = insn;
4433
4434   dsc->cleanup = &cleanup_svc;
4435   /* Pretend we wrote to the PC, so cleanup doesn't set PC to the next
4436      instruction.  */
4437   dsc->wrote_to_pc = 1;
4438
4439   return 0;
4440 }
4441
4442 /* Copy undefined instructions.  */
4443
4444 static int
4445 copy_undef (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, uint32_t insn,
4446             struct displaced_step_closure *dsc)
4447 {
4448   if (debug_displaced)
4449     fprintf_unfiltered (gdb_stdlog, "displaced: copying undefined insn %.8lx\n",
4450                         (unsigned long) insn);
4451
4452   dsc->modinsn[0] = insn;
4453
4454   return 0;
4455 }
4456
4457 /* Copy unpredictable instructions.  */
4458
4459 static int
4460 copy_unpred (struct gdbarch *gdbarch ATTRIBUTE_UNUSED, uint32_t insn,
4461              struct displaced_step_closure *dsc)
4462 {
4463   if (debug_displaced)
4464     fprintf_unfiltered (gdb_stdlog, "displaced: copying unpredictable insn "
4465                         "%.8lx\n", (unsigned long) insn);
4466
4467   dsc->modinsn[0] = insn;
4468
4469   return 0;
4470 }
4471
4472 /* The decode_* functions are instruction decoding helpers.  They mostly follow
4473    the presentation in the ARM ARM.  */
4474
4475 static int
4476 decode_misc_memhint_neon (struct gdbarch *gdbarch, uint32_t insn,
4477                           struct regcache *regs,
4478                           struct displaced_step_closure *dsc)
4479 {
4480   unsigned int op1 = bits (insn, 20, 26), op2 = bits (insn, 4, 7);
4481   unsigned int rn = bits (insn, 16, 19);
4482
4483   if (op1 == 0x10 && (op2 & 0x2) == 0x0 && (rn & 0xe) == 0x0)
4484     return copy_unmodified (gdbarch, insn, "cps", dsc);
4485   else if (op1 == 0x10 && op2 == 0x0 && (rn & 0xe) == 0x1)
4486     return copy_unmodified (gdbarch, insn, "setend", dsc);
4487   else if ((op1 & 0x60) == 0x20)
4488     return copy_unmodified (gdbarch, insn, "neon dataproc", dsc);
4489   else if ((op1 & 0x71) == 0x40)
4490     return copy_unmodified (gdbarch, insn, "neon elt/struct load/store", dsc);
4491   else if ((op1 & 0x77) == 0x41)
4492     return copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
4493   else if ((op1 & 0x77) == 0x45)
4494     return copy_preload (gdbarch, insn, regs, dsc);  /* pli.  */
4495   else if ((op1 & 0x77) == 0x51)
4496     {
4497       if (rn != 0xf)
4498         return copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
4499       else
4500         return copy_unpred (gdbarch, insn, dsc);
4501     }
4502   else if ((op1 & 0x77) == 0x55)
4503     return copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
4504   else if (op1 == 0x57)
4505     switch (op2)
4506       {
4507       case 0x1: return copy_unmodified (gdbarch, insn, "clrex", dsc);
4508       case 0x4: return copy_unmodified (gdbarch, insn, "dsb", dsc);
4509       case 0x5: return copy_unmodified (gdbarch, insn, "dmb", dsc);
4510       case 0x6: return copy_unmodified (gdbarch, insn, "isb", dsc);
4511       default: return copy_unpred (gdbarch, insn, dsc);
4512       }
4513   else if ((op1 & 0x63) == 0x43)
4514     return copy_unpred (gdbarch, insn, dsc);
4515   else if ((op2 & 0x1) == 0x0)
4516     switch (op1 & ~0x80)
4517       {
4518       case 0x61:
4519         return copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
4520       case 0x65:
4521         return copy_preload_reg (gdbarch, insn, regs, dsc);  /* pli reg.  */
4522       case 0x71: case 0x75:
4523         /* pld/pldw reg.  */
4524         return copy_preload_reg (gdbarch, insn, regs, dsc);
4525       case 0x63: case 0x67: case 0x73: case 0x77:
4526         return copy_unpred (gdbarch, insn, dsc);
4527       default:
4528         return copy_undef (gdbarch, insn, dsc);
4529       }
4530   else
4531     return copy_undef (gdbarch, insn, dsc);  /* Probably unreachable.  */
4532 }
4533
4534 static int
4535 decode_unconditional (struct gdbarch *gdbarch, uint32_t insn,
4536                       struct regcache *regs, struct displaced_step_closure *dsc)
4537 {
4538   if (bit (insn, 27) == 0)
4539     return decode_misc_memhint_neon (gdbarch, insn, regs, dsc);
4540   /* Switch on bits: 0bxxxxx321xxx0xxxxxxxxxxxxxxxxxxxx.  */
4541   else switch (((insn & 0x7000000) >> 23) | ((insn & 0x100000) >> 20))
4542     {
4543     case 0x0: case 0x2:
4544       return copy_unmodified (gdbarch, insn, "srs", dsc);
4545
4546     case 0x1: case 0x3:
4547       return copy_unmodified (gdbarch, insn, "rfe", dsc);
4548
4549     case 0x4: case 0x5: case 0x6: case 0x7:
4550       return copy_b_bl_blx (gdbarch, insn, regs, dsc);
4551
4552     case 0x8:
4553       switch ((insn & 0xe00000) >> 21)
4554         {
4555         case 0x1: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7:
4556           /* stc/stc2.  */
4557           return copy_copro_load_store (gdbarch, insn, regs, dsc);
4558
4559         case 0x2:
4560           return copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
4561
4562         default:
4563           return copy_undef (gdbarch, insn, dsc);
4564         }
4565
4566     case 0x9:
4567       {
4568          int rn_f = (bits (insn, 16, 19) == 0xf);
4569         switch ((insn & 0xe00000) >> 21)
4570           {
4571           case 0x1: case 0x3:
4572             /* ldc/ldc2 imm (undefined for rn == pc).  */
4573             return rn_f ? copy_undef (gdbarch, insn, dsc)
4574                         : copy_copro_load_store (gdbarch, insn, regs, dsc);
4575
4576           case 0x2:
4577             return copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
4578
4579           case 0x4: case 0x5: case 0x6: case 0x7:
4580             /* ldc/ldc2 lit (undefined for rn != pc).  */
4581             return rn_f ? copy_copro_load_store (gdbarch, insn, regs, dsc)
4582                         : copy_undef (gdbarch, insn, dsc);
4583
4584           default:
4585             return copy_undef (gdbarch, insn, dsc);
4586           }
4587       }
4588
4589     case 0xa:
4590       return copy_unmodified (gdbarch, insn, "stc/stc2", dsc);
4591
4592     case 0xb:
4593       if (bits (insn, 16, 19) == 0xf)
4594         /* ldc/ldc2 lit.  */
4595         return copy_copro_load_store (gdbarch, insn, regs, dsc);
4596       else
4597         return copy_undef (gdbarch, insn, dsc);
4598
4599     case 0xc:
4600       if (bit (insn, 4))
4601         return copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
4602       else
4603         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
4604
4605     case 0xd:
4606       if (bit (insn, 4))
4607         return copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
4608       else
4609         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
4610
4611     default:
4612       return copy_undef (gdbarch, insn, dsc);
4613     }
4614 }
4615
4616 /* Decode miscellaneous instructions in dp/misc encoding space.  */
4617
4618 static int
4619 decode_miscellaneous (struct gdbarch *gdbarch, uint32_t insn,
4620                       struct regcache *regs, struct displaced_step_closure *dsc)
4621 {
4622   unsigned int op2 = bits (insn, 4, 6);
4623   unsigned int op = bits (insn, 21, 22);
4624   unsigned int op1 = bits (insn, 16, 19);
4625
4626   switch (op2)
4627     {
4628     case 0x0:
4629       return copy_unmodified (gdbarch, insn, "mrs/msr", dsc);
4630
4631     case 0x1:
4632       if (op == 0x1)  /* bx.  */
4633         return copy_bx_blx_reg (gdbarch, insn, regs, dsc);
4634       else if (op == 0x3)
4635         return copy_unmodified (gdbarch, insn, "clz", dsc);
4636       else
4637         return copy_undef (gdbarch, insn, dsc);
4638
4639     case 0x2:
4640       if (op == 0x1)
4641         /* Not really supported.  */
4642         return copy_unmodified (gdbarch, insn, "bxj", dsc);
4643       else
4644         return copy_undef (gdbarch, insn, dsc);
4645
4646     case 0x3:
4647       if (op == 0x1)
4648         return copy_bx_blx_reg (gdbarch, insn, regs, dsc);  /* blx register.  */
4649       else
4650         return copy_undef (gdbarch, insn, dsc);
4651
4652     case 0x5:
4653       return copy_unmodified (gdbarch, insn, "saturating add/sub", dsc);
4654
4655     case 0x7:
4656       if (op == 0x1)
4657         return copy_unmodified (gdbarch, insn, "bkpt", dsc);
4658       else if (op == 0x3)
4659         /* Not really supported.  */
4660         return copy_unmodified (gdbarch, insn, "smc", dsc);
4661
4662     default:
4663       return copy_undef (gdbarch, insn, dsc);
4664     }
4665 }
4666
4667 static int
4668 decode_dp_misc (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
4669                 struct displaced_step_closure *dsc)
4670 {
4671   if (bit (insn, 25))
4672     switch (bits (insn, 20, 24))
4673       {
4674       case 0x10:
4675         return copy_unmodified (gdbarch, insn, "movw", dsc);
4676
4677       case 0x14:
4678         return copy_unmodified (gdbarch, insn, "movt", dsc);
4679
4680       case 0x12: case 0x16:
4681         return copy_unmodified (gdbarch, insn, "msr imm", dsc);
4682
4683       default:
4684         return copy_alu_imm (gdbarch, insn, regs, dsc);
4685       }
4686   else
4687     {
4688       uint32_t op1 = bits (insn, 20, 24), op2 = bits (insn, 4, 7);
4689
4690       if ((op1 & 0x19) != 0x10 && (op2 & 0x1) == 0x0)
4691         return copy_alu_reg (gdbarch, insn, regs, dsc);
4692       else if ((op1 & 0x19) != 0x10 && (op2 & 0x9) == 0x1)
4693         return copy_alu_shifted_reg (gdbarch, insn, regs, dsc);
4694       else if ((op1 & 0x19) == 0x10 && (op2 & 0x8) == 0x0)
4695         return decode_miscellaneous (gdbarch, insn, regs, dsc);
4696       else if ((op1 & 0x19) == 0x10 && (op2 & 0x9) == 0x8)
4697         return copy_unmodified (gdbarch, insn, "halfword mul/mla", dsc);
4698       else if ((op1 & 0x10) == 0x00 && op2 == 0x9)
4699         return copy_unmodified (gdbarch, insn, "mul/mla", dsc);
4700       else if ((op1 & 0x10) == 0x10 && op2 == 0x9)
4701         return copy_unmodified (gdbarch, insn, "synch", dsc);
4702       else if (op2 == 0xb || (op2 & 0xd) == 0xd)
4703         /* 2nd arg means "unpriveleged".  */
4704         return copy_extra_ld_st (gdbarch, insn, (op1 & 0x12) == 0x02, regs,
4705                                  dsc);
4706     }
4707
4708   /* Should be unreachable.  */
4709   return 1;
4710 }
4711
4712 static int
4713 decode_ld_st_word_ubyte (struct gdbarch *gdbarch, uint32_t insn,
4714                          struct regcache *regs,
4715                          struct displaced_step_closure *dsc)
4716 {
4717   int a = bit (insn, 25), b = bit (insn, 4);
4718   uint32_t op1 = bits (insn, 20, 24);
4719   int rn_f = bits (insn, 16, 19) == 0xf;
4720
4721   if ((!a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02)
4722       || (a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02 && !b))
4723     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 0, 0);
4724   else if ((!a && (op1 & 0x17) == 0x02)
4725             || (a && (op1 & 0x17) == 0x02 && !b))
4726     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 0, 1);
4727   else if ((!a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03)
4728             || (a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03 && !b))
4729     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 0, 0);
4730   else if ((!a && (op1 & 0x17) == 0x03)
4731            || (a && (op1 & 0x17) == 0x03 && !b))
4732     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 0, 1);
4733   else if ((!a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06)
4734             || (a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06 && !b))
4735     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 0);
4736   else if ((!a && (op1 & 0x17) == 0x06)
4737            || (a && (op1 & 0x17) == 0x06 && !b))
4738     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 1);
4739   else if ((!a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07)
4740            || (a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07 && !b))
4741     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 0);
4742   else if ((!a && (op1 & 0x17) == 0x07)
4743            || (a && (op1 & 0x17) == 0x07 && !b))
4744     return copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 1);
4745
4746   /* Should be unreachable.  */
4747   return 1;
4748 }
4749
4750 static int
4751 decode_media (struct gdbarch *gdbarch, uint32_t insn,
4752               struct displaced_step_closure *dsc)
4753 {
4754   switch (bits (insn, 20, 24))
4755     {
4756     case 0x00: case 0x01: case 0x02: case 0x03:
4757       return copy_unmodified (gdbarch, insn, "parallel add/sub signed", dsc);
4758
4759     case 0x04: case 0x05: case 0x06: case 0x07:
4760       return copy_unmodified (gdbarch, insn, "parallel add/sub unsigned", dsc);
4761
4762     case 0x08: case 0x09: case 0x0a: case 0x0b:
4763     case 0x0c: case 0x0d: case 0x0e: case 0x0f:
4764       return copy_unmodified (gdbarch, insn,
4765                               "decode/pack/unpack/saturate/reverse", dsc);
4766
4767     case 0x18:
4768       if (bits (insn, 5, 7) == 0)  /* op2.  */
4769          {
4770           if (bits (insn, 12, 15) == 0xf)
4771             return copy_unmodified (gdbarch, insn, "usad8", dsc);
4772           else
4773             return copy_unmodified (gdbarch, insn, "usada8", dsc);
4774         }
4775       else
4776          return copy_undef (gdbarch, insn, dsc);
4777
4778     case 0x1a: case 0x1b:
4779       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
4780         return copy_unmodified (gdbarch, insn, "sbfx", dsc);
4781       else
4782         return copy_undef (gdbarch, insn, dsc);
4783
4784     case 0x1c: case 0x1d:
4785       if (bits (insn, 5, 6) == 0x0)  /* op2[1:0].  */
4786          {
4787           if (bits (insn, 0, 3) == 0xf)
4788             return copy_unmodified (gdbarch, insn, "bfc", dsc);
4789           else
4790             return copy_unmodified (gdbarch, insn, "bfi", dsc);
4791         }
4792       else
4793         return copy_undef (gdbarch, insn, dsc);
4794
4795     case 0x1e: case 0x1f:
4796       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
4797         return copy_unmodified (gdbarch, insn, "ubfx", dsc);
4798       else
4799         return copy_undef (gdbarch, insn, dsc);
4800     }
4801
4802   /* Should be unreachable.  */
4803   return 1;
4804 }
4805
4806 static int
4807 decode_b_bl_ldmstm (struct gdbarch *gdbarch, int32_t insn,
4808                     struct regcache *regs, struct displaced_step_closure *dsc)
4809 {
4810   if (bit (insn, 25))
4811     return copy_b_bl_blx (gdbarch, insn, regs, dsc);
4812   else
4813     return copy_block_xfer (gdbarch, insn, regs, dsc);
4814 }
4815
4816 static int
4817 decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint32_t insn,
4818                       struct regcache *regs, struct displaced_step_closure *dsc)
4819 {
4820   unsigned int opcode = bits (insn, 20, 24);
4821
4822   switch (opcode)
4823     {
4824     case 0x04: case 0x05:  /* VFP/Neon mrrc/mcrr.  */
4825       return copy_unmodified (gdbarch, insn, "vfp/neon mrrc/mcrr", dsc);
4826
4827     case 0x08: case 0x0a: case 0x0c: case 0x0e:
4828     case 0x12: case 0x16:
4829       return copy_unmodified (gdbarch, insn, "vfp/neon vstm/vpush", dsc);
4830
4831     case 0x09: case 0x0b: case 0x0d: case 0x0f:
4832     case 0x13: case 0x17:
4833       return copy_unmodified (gdbarch, insn, "vfp/neon vldm/vpop", dsc);
4834
4835     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
4836     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
4837       /* Note: no writeback for these instructions.  Bit 25 will always be
4838          zero though (via caller), so the following works OK.  */
4839       return copy_copro_load_store (gdbarch, insn, regs, dsc);
4840     }
4841
4842   /* Should be unreachable.  */
4843   return 1;
4844 }
4845
4846 static int
4847 decode_svc_copro (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
4848                   struct regcache *regs, struct displaced_step_closure *dsc)
4849 {
4850   unsigned int op1 = bits (insn, 20, 25);
4851   int op = bit (insn, 4);
4852   unsigned int coproc = bits (insn, 8, 11);
4853   unsigned int rn = bits (insn, 16, 19);
4854
4855   if ((op1 & 0x20) == 0x00 && (op1 & 0x3a) != 0x00 && (coproc & 0xe) == 0xa)
4856     return decode_ext_reg_ld_st (gdbarch, insn, regs, dsc);
4857   else if ((op1 & 0x21) == 0x00 && (op1 & 0x3a) != 0x00
4858            && (coproc & 0xe) != 0xa)
4859     /* stc/stc2.  */
4860     return copy_copro_load_store (gdbarch, insn, regs, dsc);
4861   else if ((op1 & 0x21) == 0x01 && (op1 & 0x3a) != 0x00
4862            && (coproc & 0xe) != 0xa)
4863     /* ldc/ldc2 imm/lit.  */
4864     return copy_copro_load_store (gdbarch, insn, regs, dsc);
4865   else if ((op1 & 0x3e) == 0x00)
4866     return copy_undef (gdbarch, insn, dsc);
4867   else if ((op1 & 0x3e) == 0x04 && (coproc & 0xe) == 0xa)
4868     return copy_unmodified (gdbarch, insn, "neon 64bit xfer", dsc);
4869   else if (op1 == 0x04 && (coproc & 0xe) != 0xa)
4870     return copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
4871   else if (op1 == 0x05 && (coproc & 0xe) != 0xa)
4872     return copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
4873   else if ((op1 & 0x30) == 0x20 && !op)
4874     {
4875       if ((coproc & 0xe) == 0xa)
4876         return copy_unmodified (gdbarch, insn, "vfp dataproc", dsc);
4877       else
4878         return copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
4879     }
4880   else if ((op1 & 0x30) == 0x20 && op)
4881     return copy_unmodified (gdbarch, insn, "neon 8/16/32 bit xfer", dsc);
4882   else if ((op1 & 0x31) == 0x20 && op && (coproc & 0xe) != 0xa)
4883     return copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
4884   else if ((op1 & 0x31) == 0x21 && op && (coproc & 0xe) != 0xa)
4885     return copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
4886   else if ((op1 & 0x30) == 0x30)
4887     return copy_svc (gdbarch, insn, to, regs, dsc);
4888   else
4889     return copy_undef (gdbarch, insn, dsc);  /* Possibly unreachable.  */
4890 }
4891
4892 void
4893 arm_process_displaced_insn (struct gdbarch *gdbarch, uint32_t insn,
4894                             CORE_ADDR from, CORE_ADDR to, struct regcache *regs,
4895                             struct displaced_step_closure *dsc)
4896 {
4897   int err = 0;
4898
4899   if (!displaced_in_arm_mode (regs))
4900     error (_("Displaced stepping is only supported in ARM mode"));
4901
4902   /* Most displaced instructions use a 1-instruction scratch space, so set this
4903      here and override below if/when necessary.  */
4904   dsc->numinsns = 1;
4905   dsc->insn_addr = from;
4906   dsc->scratch_base = to;
4907   dsc->cleanup = NULL;
4908   dsc->wrote_to_pc = 0;
4909
4910   if ((insn & 0xf0000000) == 0xf0000000)
4911     err = decode_unconditional (gdbarch, insn, regs, dsc);
4912   else switch (((insn & 0x10) >> 4) | ((insn & 0xe000000) >> 24))
4913     {
4914     case 0x0: case 0x1: case 0x2: case 0x3:
4915       err = decode_dp_misc (gdbarch, insn, regs, dsc);
4916       break;
4917
4918     case 0x4: case 0x5: case 0x6:
4919       err = decode_ld_st_word_ubyte (gdbarch, insn, regs, dsc);
4920       break;
4921
4922     case 0x7:
4923       err = decode_media (gdbarch, insn, dsc);
4924       break;
4925
4926     case 0x8: case 0x9: case 0xa: case 0xb:
4927       err = decode_b_bl_ldmstm (gdbarch, insn, regs, dsc);
4928       break;
4929
4930     case 0xc: case 0xd: case 0xe: case 0xf:
4931       err = decode_svc_copro (gdbarch, insn, to, regs, dsc);
4932       break;
4933     }
4934
4935   if (err)
4936     internal_error (__FILE__, __LINE__,
4937                     _("arm_process_displaced_insn: Instruction decode error"));
4938 }
4939
4940 /* Actually set up the scratch space for a displaced instruction.  */
4941
4942 void
4943 arm_displaced_init_closure (struct gdbarch *gdbarch, CORE_ADDR from,
4944                             CORE_ADDR to, struct displaced_step_closure *dsc)
4945 {
4946   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
4947   unsigned int i;
4948   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4949
4950   /* Poke modified instruction(s).  */
4951   for (i = 0; i < dsc->numinsns; i++)
4952     {
4953       if (debug_displaced)
4954         fprintf_unfiltered (gdb_stdlog, "displaced: writing insn %.8lx at "
4955                             "%.8lx\n", (unsigned long) dsc->modinsn[i],
4956                             (unsigned long) to + i * 4);
4957       write_memory_unsigned_integer (to + i * 4, 4, byte_order_for_code,
4958                                      dsc->modinsn[i]);
4959     }
4960
4961   /* Put breakpoint afterwards.  */
4962   write_memory (to + dsc->numinsns * 4, tdep->arm_breakpoint,
4963                 tdep->arm_breakpoint_size);
4964
4965   if (debug_displaced)
4966     fprintf_unfiltered (gdb_stdlog, "displaced: copy %s->%s: ",
4967                         paddress (gdbarch, from), paddress (gdbarch, to));
4968 }
4969
4970 /* Entry point for copying an instruction into scratch space for displaced
4971    stepping.  */
4972
4973 struct displaced_step_closure *
4974 arm_displaced_step_copy_insn (struct gdbarch *gdbarch,
4975                               CORE_ADDR from, CORE_ADDR to,
4976                               struct regcache *regs)
4977 {
4978   struct displaced_step_closure *dsc
4979     = xmalloc (sizeof (struct displaced_step_closure));
4980   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4981   uint32_t insn = read_memory_unsigned_integer (from, 4, byte_order_for_code);
4982
4983   if (debug_displaced)
4984     fprintf_unfiltered (gdb_stdlog, "displaced: stepping insn %.8lx "
4985                         "at %.8lx\n", (unsigned long) insn,
4986                         (unsigned long) from);
4987
4988   arm_process_displaced_insn (gdbarch, insn, from, to, regs, dsc);
4989   arm_displaced_init_closure (gdbarch, from, to, dsc);
4990
4991   return dsc;
4992 }
4993
4994 /* Entry point for cleaning things up after a displaced instruction has been
4995    single-stepped.  */
4996
4997 void
4998 arm_displaced_step_fixup (struct gdbarch *gdbarch,
4999                           struct displaced_step_closure *dsc,
5000                           CORE_ADDR from, CORE_ADDR to,
5001                           struct regcache *regs)
5002 {
5003   if (dsc->cleanup)
5004     dsc->cleanup (gdbarch, regs, dsc);
5005
5006   if (!dsc->wrote_to_pc)
5007     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, dsc->insn_addr + 4);
5008 }
5009
5010 #include "bfd-in2.h"
5011 #include "libcoff.h"
5012
5013 static int
5014 gdb_print_insn_arm (bfd_vma memaddr, disassemble_info *info)
5015 {
5016   if (arm_pc_is_thumb (memaddr))
5017     {
5018       static asymbol *asym;
5019       static combined_entry_type ce;
5020       static struct coff_symbol_struct csym;
5021       static struct bfd fake_bfd;
5022       static bfd_target fake_target;
5023
5024       if (csym.native == NULL)
5025         {
5026           /* Create a fake symbol vector containing a Thumb symbol.
5027              This is solely so that the code in print_insn_little_arm() 
5028              and print_insn_big_arm() in opcodes/arm-dis.c will detect
5029              the presence of a Thumb symbol and switch to decoding
5030              Thumb instructions.  */
5031
5032           fake_target.flavour = bfd_target_coff_flavour;
5033           fake_bfd.xvec = &fake_target;
5034           ce.u.syment.n_sclass = C_THUMBEXTFUNC;
5035           csym.native = &ce;
5036           csym.symbol.the_bfd = &fake_bfd;
5037           csym.symbol.name = "fake";
5038           asym = (asymbol *) & csym;
5039         }
5040
5041       memaddr = UNMAKE_THUMB_ADDR (memaddr);
5042       info->symbols = &asym;
5043     }
5044   else
5045     info->symbols = NULL;
5046
5047   if (info->endian == BFD_ENDIAN_BIG)
5048     return print_insn_big_arm (memaddr, info);
5049   else
5050     return print_insn_little_arm (memaddr, info);
5051 }
5052
5053 /* The following define instruction sequences that will cause ARM
5054    cpu's to take an undefined instruction trap.  These are used to
5055    signal a breakpoint to GDB.
5056    
5057    The newer ARMv4T cpu's are capable of operating in ARM or Thumb
5058    modes.  A different instruction is required for each mode.  The ARM
5059    cpu's can also be big or little endian.  Thus four different
5060    instructions are needed to support all cases.
5061    
5062    Note: ARMv4 defines several new instructions that will take the
5063    undefined instruction trap.  ARM7TDMI is nominally ARMv4T, but does
5064    not in fact add the new instructions.  The new undefined
5065    instructions in ARMv4 are all instructions that had no defined
5066    behaviour in earlier chips.  There is no guarantee that they will
5067    raise an exception, but may be treated as NOP's.  In practice, it
5068    may only safe to rely on instructions matching:
5069    
5070    3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 
5071    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
5072    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
5073    
5074    Even this may only true if the condition predicate is true. The
5075    following use a condition predicate of ALWAYS so it is always TRUE.
5076    
5077    There are other ways of forcing a breakpoint.  GNU/Linux, RISC iX,
5078    and NetBSD all use a software interrupt rather than an undefined
5079    instruction to force a trap.  This can be handled by by the
5080    abi-specific code during establishment of the gdbarch vector.  */
5081
5082 #define ARM_LE_BREAKPOINT {0xFE,0xDE,0xFF,0xE7}
5083 #define ARM_BE_BREAKPOINT {0xE7,0xFF,0xDE,0xFE}
5084 #define THUMB_LE_BREAKPOINT {0xbe,0xbe}
5085 #define THUMB_BE_BREAKPOINT {0xbe,0xbe}
5086
5087 static const char arm_default_arm_le_breakpoint[] = ARM_LE_BREAKPOINT;
5088 static const char arm_default_arm_be_breakpoint[] = ARM_BE_BREAKPOINT;
5089 static const char arm_default_thumb_le_breakpoint[] = THUMB_LE_BREAKPOINT;
5090 static const char arm_default_thumb_be_breakpoint[] = THUMB_BE_BREAKPOINT;
5091
5092 /* Determine the type and size of breakpoint to insert at PCPTR.  Uses
5093    the program counter value to determine whether a 16-bit or 32-bit
5094    breakpoint should be used.  It returns a pointer to a string of
5095    bytes that encode a breakpoint instruction, stores the length of
5096    the string to *lenptr, and adjusts the program counter (if
5097    necessary) to point to the actual memory location where the
5098    breakpoint should be inserted.  */
5099
5100 static const unsigned char *
5101 arm_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr, int *lenptr)
5102 {
5103   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5104   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
5105
5106   if (arm_pc_is_thumb (*pcptr))
5107     {
5108       *pcptr = UNMAKE_THUMB_ADDR (*pcptr);
5109
5110       /* If we have a separate 32-bit breakpoint instruction for Thumb-2,
5111          check whether we are replacing a 32-bit instruction.  */
5112       if (tdep->thumb2_breakpoint != NULL)
5113         {
5114           gdb_byte buf[2];
5115           if (target_read_memory (*pcptr, buf, 2) == 0)
5116             {
5117               unsigned short inst1;
5118               inst1 = extract_unsigned_integer (buf, 2, byte_order_for_code);
5119               if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
5120                 {
5121                   *lenptr = tdep->thumb2_breakpoint_size;
5122                   return tdep->thumb2_breakpoint;
5123                 }
5124             }
5125         }
5126
5127       *lenptr = tdep->thumb_breakpoint_size;
5128       return tdep->thumb_breakpoint;
5129     }
5130   else
5131     {
5132       *lenptr = tdep->arm_breakpoint_size;
5133       return tdep->arm_breakpoint;
5134     }
5135 }
5136
5137 static void
5138 arm_remote_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
5139                                int *kindptr)
5140 {
5141   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5142
5143   arm_breakpoint_from_pc (gdbarch, pcptr, kindptr);
5144
5145   if (arm_pc_is_thumb (*pcptr) && *kindptr == 4)
5146     /* The documented magic value for a 32-bit Thumb-2 breakpoint, so
5147        that this is not confused with a 32-bit ARM breakpoint.  */
5148     *kindptr = 3;
5149 }
5150
5151 /* Extract from an array REGBUF containing the (raw) register state a
5152    function return value of type TYPE, and copy that, in virtual
5153    format, into VALBUF.  */
5154
5155 static void
5156 arm_extract_return_value (struct type *type, struct regcache *regs,
5157                           gdb_byte *valbuf)
5158 {
5159   struct gdbarch *gdbarch = get_regcache_arch (regs);
5160   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5161
5162   if (TYPE_CODE_FLT == TYPE_CODE (type))
5163     {
5164       switch (gdbarch_tdep (gdbarch)->fp_model)
5165         {
5166         case ARM_FLOAT_FPA:
5167           {
5168             /* The value is in register F0 in internal format.  We need to
5169                extract the raw value and then convert it to the desired
5170                internal type.  */
5171             bfd_byte tmpbuf[FP_REGISTER_SIZE];
5172
5173             regcache_cooked_read (regs, ARM_F0_REGNUM, tmpbuf);
5174             convert_from_extended (floatformat_from_type (type), tmpbuf,
5175                                    valbuf, gdbarch_byte_order (gdbarch));
5176           }
5177           break;
5178
5179         case ARM_FLOAT_SOFT_FPA:
5180         case ARM_FLOAT_SOFT_VFP:
5181           /* ARM_FLOAT_VFP can arise if this is a variadic function so
5182              not using the VFP ABI code.  */
5183         case ARM_FLOAT_VFP:
5184           regcache_cooked_read (regs, ARM_A1_REGNUM, valbuf);
5185           if (TYPE_LENGTH (type) > 4)
5186             regcache_cooked_read (regs, ARM_A1_REGNUM + 1,
5187                                   valbuf + INT_REGISTER_SIZE);
5188           break;
5189
5190         default:
5191           internal_error
5192             (__FILE__, __LINE__,
5193              _("arm_extract_return_value: Floating point model not supported"));
5194           break;
5195         }
5196     }
5197   else if (TYPE_CODE (type) == TYPE_CODE_INT
5198            || TYPE_CODE (type) == TYPE_CODE_CHAR
5199            || TYPE_CODE (type) == TYPE_CODE_BOOL
5200            || TYPE_CODE (type) == TYPE_CODE_PTR
5201            || TYPE_CODE (type) == TYPE_CODE_REF
5202            || TYPE_CODE (type) == TYPE_CODE_ENUM)
5203     {
5204       /* If the the type is a plain integer, then the access is
5205          straight-forward.  Otherwise we have to play around a bit more.  */
5206       int len = TYPE_LENGTH (type);
5207       int regno = ARM_A1_REGNUM;
5208       ULONGEST tmp;
5209
5210       while (len > 0)
5211         {
5212           /* By using store_unsigned_integer we avoid having to do
5213              anything special for small big-endian values.  */
5214           regcache_cooked_read_unsigned (regs, regno++, &tmp);
5215           store_unsigned_integer (valbuf, 
5216                                   (len > INT_REGISTER_SIZE
5217                                    ? INT_REGISTER_SIZE : len),
5218                                   byte_order, tmp);
5219           len -= INT_REGISTER_SIZE;
5220           valbuf += INT_REGISTER_SIZE;
5221         }
5222     }
5223   else
5224     {
5225       /* For a structure or union the behaviour is as if the value had
5226          been stored to word-aligned memory and then loaded into 
5227          registers with 32-bit load instruction(s).  */
5228       int len = TYPE_LENGTH (type);
5229       int regno = ARM_A1_REGNUM;
5230       bfd_byte tmpbuf[INT_REGISTER_SIZE];
5231
5232       while (len > 0)
5233         {
5234           regcache_cooked_read (regs, regno++, tmpbuf);
5235           memcpy (valbuf, tmpbuf,
5236                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
5237           len -= INT_REGISTER_SIZE;
5238           valbuf += INT_REGISTER_SIZE;
5239         }
5240     }
5241 }
5242
5243
5244 /* Will a function return an aggregate type in memory or in a
5245    register?  Return 0 if an aggregate type can be returned in a
5246    register, 1 if it must be returned in memory.  */
5247
5248 static int
5249 arm_return_in_memory (struct gdbarch *gdbarch, struct type *type)
5250 {
5251   int nRc;
5252   enum type_code code;
5253
5254   CHECK_TYPEDEF (type);
5255
5256   /* In the ARM ABI, "integer" like aggregate types are returned in
5257      registers.  For an aggregate type to be integer like, its size
5258      must be less than or equal to INT_REGISTER_SIZE and the
5259      offset of each addressable subfield must be zero.  Note that bit
5260      fields are not addressable, and all addressable subfields of
5261      unions always start at offset zero.
5262
5263      This function is based on the behaviour of GCC 2.95.1.
5264      See: gcc/arm.c: arm_return_in_memory() for details.
5265
5266      Note: All versions of GCC before GCC 2.95.2 do not set up the
5267      parameters correctly for a function returning the following
5268      structure: struct { float f;}; This should be returned in memory,
5269      not a register.  Richard Earnshaw sent me a patch, but I do not
5270      know of any way to detect if a function like the above has been
5271      compiled with the correct calling convention.  */
5272
5273   /* All aggregate types that won't fit in a register must be returned
5274      in memory.  */
5275   if (TYPE_LENGTH (type) > INT_REGISTER_SIZE)
5276     {
5277       return 1;
5278     }
5279
5280   /* The AAPCS says all aggregates not larger than a word are returned
5281      in a register.  */
5282   if (gdbarch_tdep (gdbarch)->arm_abi != ARM_ABI_APCS)
5283     return 0;
5284
5285   /* The only aggregate types that can be returned in a register are
5286      structs and unions.  Arrays must be returned in memory.  */
5287   code = TYPE_CODE (type);
5288   if ((TYPE_CODE_STRUCT != code) && (TYPE_CODE_UNION != code))
5289     {
5290       return 1;
5291     }
5292
5293   /* Assume all other aggregate types can be returned in a register.
5294      Run a check for structures, unions and arrays.  */
5295   nRc = 0;
5296
5297   if ((TYPE_CODE_STRUCT == code) || (TYPE_CODE_UNION == code))
5298     {
5299       int i;
5300       /* Need to check if this struct/union is "integer" like.  For
5301          this to be true, its size must be less than or equal to
5302          INT_REGISTER_SIZE and the offset of each addressable
5303          subfield must be zero.  Note that bit fields are not
5304          addressable, and unions always start at offset zero.  If any
5305          of the subfields is a floating point type, the struct/union
5306          cannot be an integer type.  */
5307
5308       /* For each field in the object, check:
5309          1) Is it FP? --> yes, nRc = 1;
5310          2) Is it addressable (bitpos != 0) and
5311          not packed (bitsize == 0)?
5312          --> yes, nRc = 1  
5313        */
5314
5315       for (i = 0; i < TYPE_NFIELDS (type); i++)
5316         {
5317           enum type_code field_type_code;
5318           field_type_code = TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type, i)));
5319
5320           /* Is it a floating point type field?  */
5321           if (field_type_code == TYPE_CODE_FLT)
5322             {
5323               nRc = 1;
5324               break;
5325             }
5326
5327           /* If bitpos != 0, then we have to care about it.  */
5328           if (TYPE_FIELD_BITPOS (type, i) != 0)
5329             {
5330               /* Bitfields are not addressable.  If the field bitsize is 
5331                  zero, then the field is not packed.  Hence it cannot be
5332                  a bitfield or any other packed type.  */
5333               if (TYPE_FIELD_BITSIZE (type, i) == 0)
5334                 {
5335                   nRc = 1;
5336                   break;
5337                 }
5338             }
5339         }
5340     }
5341
5342   return nRc;
5343 }
5344
5345 /* Write into appropriate registers a function return value of type
5346    TYPE, given in virtual format.  */
5347
5348 static void
5349 arm_store_return_value (struct type *type, struct regcache *regs,
5350                         const gdb_byte *valbuf)
5351 {
5352   struct gdbarch *gdbarch = get_regcache_arch (regs);
5353   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5354
5355   if (TYPE_CODE (type) == TYPE_CODE_FLT)
5356     {
5357       char buf[MAX_REGISTER_SIZE];
5358
5359       switch (gdbarch_tdep (gdbarch)->fp_model)
5360         {
5361         case ARM_FLOAT_FPA:
5362
5363           convert_to_extended (floatformat_from_type (type), buf, valbuf,
5364                                gdbarch_byte_order (gdbarch));
5365           regcache_cooked_write (regs, ARM_F0_REGNUM, buf);
5366           break;
5367
5368         case ARM_FLOAT_SOFT_FPA:
5369         case ARM_FLOAT_SOFT_VFP:
5370           /* ARM_FLOAT_VFP can arise if this is a variadic function so
5371              not using the VFP ABI code.  */
5372         case ARM_FLOAT_VFP:
5373           regcache_cooked_write (regs, ARM_A1_REGNUM, valbuf);
5374           if (TYPE_LENGTH (type) > 4)
5375             regcache_cooked_write (regs, ARM_A1_REGNUM + 1, 
5376                                    valbuf + INT_REGISTER_SIZE);
5377           break;
5378
5379         default:
5380           internal_error
5381             (__FILE__, __LINE__,
5382              _("arm_store_return_value: Floating point model not supported"));
5383           break;
5384         }
5385     }
5386   else if (TYPE_CODE (type) == TYPE_CODE_INT
5387            || TYPE_CODE (type) == TYPE_CODE_CHAR
5388            || TYPE_CODE (type) == TYPE_CODE_BOOL
5389            || TYPE_CODE (type) == TYPE_CODE_PTR
5390            || TYPE_CODE (type) == TYPE_CODE_REF
5391            || TYPE_CODE (type) == TYPE_CODE_ENUM)
5392     {
5393       if (TYPE_LENGTH (type) <= 4)
5394         {
5395           /* Values of one word or less are zero/sign-extended and
5396              returned in r0.  */
5397           bfd_byte tmpbuf[INT_REGISTER_SIZE];
5398           LONGEST val = unpack_long (type, valbuf);
5399
5400           store_signed_integer (tmpbuf, INT_REGISTER_SIZE, byte_order, val);
5401           regcache_cooked_write (regs, ARM_A1_REGNUM, tmpbuf);
5402         }
5403       else
5404         {
5405           /* Integral values greater than one word are stored in consecutive
5406              registers starting with r0.  This will always be a multiple of
5407              the regiser size.  */
5408           int len = TYPE_LENGTH (type);
5409           int regno = ARM_A1_REGNUM;
5410
5411           while (len > 0)
5412             {
5413               regcache_cooked_write (regs, regno++, valbuf);
5414               len -= INT_REGISTER_SIZE;
5415               valbuf += INT_REGISTER_SIZE;
5416             }
5417         }
5418     }
5419   else
5420     {
5421       /* For a structure or union the behaviour is as if the value had
5422          been stored to word-aligned memory and then loaded into 
5423          registers with 32-bit load instruction(s).  */
5424       int len = TYPE_LENGTH (type);
5425       int regno = ARM_A1_REGNUM;
5426       bfd_byte tmpbuf[INT_REGISTER_SIZE];
5427
5428       while (len > 0)
5429         {
5430           memcpy (tmpbuf, valbuf,
5431                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
5432           regcache_cooked_write (regs, regno++, tmpbuf);
5433           len -= INT_REGISTER_SIZE;
5434           valbuf += INT_REGISTER_SIZE;
5435         }
5436     }
5437 }
5438
5439
5440 /* Handle function return values.  */
5441
5442 static enum return_value_convention
5443 arm_return_value (struct gdbarch *gdbarch, struct type *func_type,
5444                   struct type *valtype, struct regcache *regcache,
5445                   gdb_byte *readbuf, const gdb_byte *writebuf)
5446 {
5447   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5448   enum arm_vfp_cprc_base_type vfp_base_type;
5449   int vfp_base_count;
5450
5451   if (arm_vfp_abi_for_function (gdbarch, func_type)
5452       && arm_vfp_call_candidate (valtype, &vfp_base_type, &vfp_base_count))
5453     {
5454       int reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
5455       int unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
5456       int i;
5457       for (i = 0; i < vfp_base_count; i++)
5458         {
5459           if (reg_char == 'q')
5460             {
5461               if (writebuf)
5462                 arm_neon_quad_write (gdbarch, regcache, i,
5463                                      writebuf + i * unit_length);
5464
5465               if (readbuf)
5466                 arm_neon_quad_read (gdbarch, regcache, i,
5467                                     readbuf + i * unit_length);
5468             }
5469           else
5470             {
5471               char name_buf[4];
5472               int regnum;
5473
5474               sprintf (name_buf, "%c%d", reg_char, i);
5475               regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
5476                                                     strlen (name_buf));
5477               if (writebuf)
5478                 regcache_cooked_write (regcache, regnum,
5479                                        writebuf + i * unit_length);
5480               if (readbuf)
5481                 regcache_cooked_read (regcache, regnum,
5482                                       readbuf + i * unit_length);
5483             }
5484         }
5485       return RETURN_VALUE_REGISTER_CONVENTION;
5486     }
5487
5488   if (TYPE_CODE (valtype) == TYPE_CODE_STRUCT
5489       || TYPE_CODE (valtype) == TYPE_CODE_UNION
5490       || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
5491     {
5492       if (tdep->struct_return == pcc_struct_return
5493           || arm_return_in_memory (gdbarch, valtype))
5494         return RETURN_VALUE_STRUCT_CONVENTION;
5495     }
5496
5497   if (writebuf)
5498     arm_store_return_value (valtype, regcache, writebuf);
5499
5500   if (readbuf)
5501     arm_extract_return_value (valtype, regcache, readbuf);
5502
5503   return RETURN_VALUE_REGISTER_CONVENTION;
5504 }
5505
5506
5507 static int
5508 arm_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
5509 {
5510   struct gdbarch *gdbarch = get_frame_arch (frame);
5511   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
5512   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
5513   CORE_ADDR jb_addr;
5514   char buf[INT_REGISTER_SIZE];
5515   
5516   jb_addr = get_frame_register_unsigned (frame, ARM_A1_REGNUM);
5517
5518   if (target_read_memory (jb_addr + tdep->jb_pc * tdep->jb_elt_size, buf,
5519                           INT_REGISTER_SIZE))
5520     return 0;
5521
5522   *pc = extract_unsigned_integer (buf, INT_REGISTER_SIZE, byte_order);
5523   return 1;
5524 }
5525
5526 /* Recognize GCC and GNU ld's trampolines.  If we are in a trampoline,
5527    return the target PC.  Otherwise return 0.  */
5528
5529 CORE_ADDR
5530 arm_skip_stub (struct frame_info *frame, CORE_ADDR pc)
5531 {
5532   char *name;
5533   int namelen;
5534   CORE_ADDR start_addr;
5535
5536   /* Find the starting address and name of the function containing the PC.  */
5537   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
5538     return 0;
5539
5540   /* If PC is in a Thumb call or return stub, return the address of the
5541      target PC, which is in a register.  The thunk functions are called
5542      _call_via_xx, where x is the register name.  The possible names
5543      are r0-r9, sl, fp, ip, sp, and lr.  ARM RealView has similar
5544      functions, named __ARM_call_via_r[0-7].  */
5545   if (strncmp (name, "_call_via_", 10) == 0
5546       || strncmp (name, "__ARM_call_via_", strlen ("__ARM_call_via_")) == 0)
5547     {
5548       /* Use the name suffix to determine which register contains the
5549          target PC.  */
5550       static char *table[15] =
5551       {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
5552        "r8", "r9", "sl", "fp", "ip", "sp", "lr"
5553       };
5554       int regno;
5555       int offset = strlen (name) - 2;
5556
5557       for (regno = 0; regno <= 14; regno++)
5558         if (strcmp (&name[offset], table[regno]) == 0)
5559           return get_frame_register_unsigned (frame, regno);
5560     }
5561
5562   /* GNU ld generates __foo_from_arm or __foo_from_thumb for
5563      non-interworking calls to foo.  We could decode the stubs
5564      to find the target but it's easier to use the symbol table.  */
5565   namelen = strlen (name);
5566   if (name[0] == '_' && name[1] == '_'
5567       && ((namelen > 2 + strlen ("_from_thumb")
5568            && strncmp (name + namelen - strlen ("_from_thumb"), "_from_thumb",
5569                        strlen ("_from_thumb")) == 0)
5570           || (namelen > 2 + strlen ("_from_arm")
5571               && strncmp (name + namelen - strlen ("_from_arm"), "_from_arm",
5572                           strlen ("_from_arm")) == 0)))
5573     {
5574       char *target_name;
5575       int target_len = namelen - 2;
5576       struct minimal_symbol *minsym;
5577       struct objfile *objfile;
5578       struct obj_section *sec;
5579
5580       if (name[namelen - 1] == 'b')
5581         target_len -= strlen ("_from_thumb");
5582       else
5583         target_len -= strlen ("_from_arm");
5584
5585       target_name = alloca (target_len + 1);
5586       memcpy (target_name, name + 2, target_len);
5587       target_name[target_len] = '\0';
5588
5589       sec = find_pc_section (pc);
5590       objfile = (sec == NULL) ? NULL : sec->objfile;
5591       minsym = lookup_minimal_symbol (target_name, NULL, objfile);
5592       if (minsym != NULL)
5593         return SYMBOL_VALUE_ADDRESS (minsym);
5594       else
5595         return 0;
5596     }
5597
5598   return 0;                     /* not a stub */
5599 }
5600
5601 static void
5602 set_arm_command (char *args, int from_tty)
5603 {
5604   printf_unfiltered (_("\
5605 \"set arm\" must be followed by an apporpriate subcommand.\n"));
5606   help_list (setarmcmdlist, "set arm ", all_commands, gdb_stdout);
5607 }
5608
5609 static void
5610 show_arm_command (char *args, int from_tty)
5611 {
5612   cmd_show_list (showarmcmdlist, from_tty, "");
5613 }
5614
5615 static void
5616 arm_update_current_architecture (void)
5617 {
5618   struct gdbarch_info info;
5619
5620   /* If the current architecture is not ARM, we have nothing to do.  */
5621   if (gdbarch_bfd_arch_info (target_gdbarch)->arch != bfd_arch_arm)
5622     return;
5623
5624   /* Update the architecture.  */
5625   gdbarch_info_init (&info);
5626
5627   if (!gdbarch_update_p (info))
5628     internal_error (__FILE__, __LINE__, "could not update architecture");
5629 }
5630
5631 static void
5632 set_fp_model_sfunc (char *args, int from_tty,
5633                     struct cmd_list_element *c)
5634 {
5635   enum arm_float_model fp_model;
5636
5637   for (fp_model = ARM_FLOAT_AUTO; fp_model != ARM_FLOAT_LAST; fp_model++)
5638     if (strcmp (current_fp_model, fp_model_strings[fp_model]) == 0)
5639       {
5640         arm_fp_model = fp_model;
5641         break;
5642       }
5643
5644   if (fp_model == ARM_FLOAT_LAST)
5645     internal_error (__FILE__, __LINE__, _("Invalid fp model accepted: %s."),
5646                     current_fp_model);
5647
5648   arm_update_current_architecture ();
5649 }
5650
5651 static void
5652 show_fp_model (struct ui_file *file, int from_tty,
5653                struct cmd_list_element *c, const char *value)
5654 {
5655   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
5656
5657   if (arm_fp_model == ARM_FLOAT_AUTO
5658       && gdbarch_bfd_arch_info (target_gdbarch)->arch == bfd_arch_arm)
5659     fprintf_filtered (file, _("\
5660 The current ARM floating point model is \"auto\" (currently \"%s\").\n"),
5661                       fp_model_strings[tdep->fp_model]);
5662   else
5663     fprintf_filtered (file, _("\
5664 The current ARM floating point model is \"%s\".\n"),
5665                       fp_model_strings[arm_fp_model]);
5666 }
5667
5668 static void
5669 arm_set_abi (char *args, int from_tty,
5670              struct cmd_list_element *c)
5671 {
5672   enum arm_abi_kind arm_abi;
5673
5674   for (arm_abi = ARM_ABI_AUTO; arm_abi != ARM_ABI_LAST; arm_abi++)
5675     if (strcmp (arm_abi_string, arm_abi_strings[arm_abi]) == 0)
5676       {
5677         arm_abi_global = arm_abi;
5678         break;
5679       }
5680
5681   if (arm_abi == ARM_ABI_LAST)
5682     internal_error (__FILE__, __LINE__, _("Invalid ABI accepted: %s."),
5683                     arm_abi_string);
5684
5685   arm_update_current_architecture ();
5686 }
5687
5688 static void
5689 arm_show_abi (struct ui_file *file, int from_tty,
5690              struct cmd_list_element *c, const char *value)
5691 {
5692   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
5693
5694   if (arm_abi_global == ARM_ABI_AUTO
5695       && gdbarch_bfd_arch_info (target_gdbarch)->arch == bfd_arch_arm)
5696     fprintf_filtered (file, _("\
5697 The current ARM ABI is \"auto\" (currently \"%s\").\n"),
5698                       arm_abi_strings[tdep->arm_abi]);
5699   else
5700     fprintf_filtered (file, _("The current ARM ABI is \"%s\".\n"),
5701                       arm_abi_string);
5702 }
5703
5704 static void
5705 arm_show_fallback_mode (struct ui_file *file, int from_tty,
5706                         struct cmd_list_element *c, const char *value)
5707 {
5708   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
5709
5710   fprintf_filtered (file, _("\
5711 The current execution mode assumed (when symbols are unavailable) is \"%s\".\n"),
5712                     arm_fallback_mode_string);
5713 }
5714
5715 static void
5716 arm_show_force_mode (struct ui_file *file, int from_tty,
5717                      struct cmd_list_element *c, const char *value)
5718 {
5719   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch);
5720
5721   fprintf_filtered (file, _("\
5722 The current execution mode assumed (even when symbols are available) is \"%s\".\n"),
5723                     arm_force_mode_string);
5724 }
5725
5726 /* If the user changes the register disassembly style used for info
5727    register and other commands, we have to also switch the style used
5728    in opcodes for disassembly output.  This function is run in the "set
5729    arm disassembly" command, and does that.  */
5730
5731 static void
5732 set_disassembly_style_sfunc (char *args, int from_tty,
5733                               struct cmd_list_element *c)
5734 {
5735   set_disassembly_style ();
5736 }
5737 \f
5738 /* Return the ARM register name corresponding to register I.  */
5739 static const char *
5740 arm_register_name (struct gdbarch *gdbarch, int i)
5741 {
5742   const int num_regs = gdbarch_num_regs (gdbarch);
5743
5744   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
5745       && i >= num_regs && i < num_regs + 32)
5746     {
5747       static const char *const vfp_pseudo_names[] = {
5748         "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
5749         "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
5750         "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
5751         "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
5752       };
5753
5754       return vfp_pseudo_names[i - num_regs];
5755     }
5756
5757   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
5758       && i >= num_regs + 32 && i < num_regs + 32 + 16)
5759     {
5760       static const char *const neon_pseudo_names[] = {
5761         "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
5762         "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15",
5763       };
5764
5765       return neon_pseudo_names[i - num_regs - 32];
5766     }
5767
5768   if (i >= ARRAY_SIZE (arm_register_names))
5769     /* These registers are only supported on targets which supply
5770        an XML description.  */
5771     return "";
5772
5773   return arm_register_names[i];
5774 }
5775
5776 static void
5777 set_disassembly_style (void)
5778 {
5779   int current;
5780
5781   /* Find the style that the user wants.  */
5782   for (current = 0; current < num_disassembly_options; current++)
5783     if (disassembly_style == valid_disassembly_styles[current])
5784       break;
5785   gdb_assert (current < num_disassembly_options);
5786
5787   /* Synchronize the disassembler.  */
5788   set_arm_regname_option (current);
5789 }
5790
5791 /* Test whether the coff symbol specific value corresponds to a Thumb
5792    function.  */
5793
5794 static int
5795 coff_sym_is_thumb (int val)
5796 {
5797   return (val == C_THUMBEXT
5798           || val == C_THUMBSTAT
5799           || val == C_THUMBEXTFUNC
5800           || val == C_THUMBSTATFUNC
5801           || val == C_THUMBLABEL);
5802 }
5803
5804 /* arm_coff_make_msymbol_special()
5805    arm_elf_make_msymbol_special()
5806    
5807    These functions test whether the COFF or ELF symbol corresponds to
5808    an address in thumb code, and set a "special" bit in a minimal
5809    symbol to indicate that it does.  */
5810    
5811 static void
5812 arm_elf_make_msymbol_special(asymbol *sym, struct minimal_symbol *msym)
5813 {
5814   /* Thumb symbols are of type STT_LOPROC, (synonymous with
5815      STT_ARM_TFUNC).  */
5816   if (ELF_ST_TYPE (((elf_symbol_type *)sym)->internal_elf_sym.st_info)
5817       == STT_LOPROC)
5818     MSYMBOL_SET_SPECIAL (msym);
5819 }
5820
5821 static void
5822 arm_coff_make_msymbol_special(int val, struct minimal_symbol *msym)
5823 {
5824   if (coff_sym_is_thumb (val))
5825     MSYMBOL_SET_SPECIAL (msym);
5826 }
5827
5828 static void
5829 arm_objfile_data_free (struct objfile *objfile, void *arg)
5830 {
5831   struct arm_per_objfile *data = arg;
5832   unsigned int i;
5833
5834   for (i = 0; i < objfile->obfd->section_count; i++)
5835     VEC_free (arm_mapping_symbol_s, data->section_maps[i]);
5836 }
5837
5838 static void
5839 arm_record_special_symbol (struct gdbarch *gdbarch, struct objfile *objfile,
5840                            asymbol *sym)
5841 {
5842   const char *name = bfd_asymbol_name (sym);
5843   struct arm_per_objfile *data;
5844   VEC(arm_mapping_symbol_s) **map_p;
5845   struct arm_mapping_symbol new_map_sym;
5846
5847   gdb_assert (name[0] == '$');
5848   if (name[1] != 'a' && name[1] != 't' && name[1] != 'd')
5849     return;
5850
5851   data = objfile_data (objfile, arm_objfile_data_key);
5852   if (data == NULL)
5853     {
5854       data = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5855                              struct arm_per_objfile);
5856       set_objfile_data (objfile, arm_objfile_data_key, data);
5857       data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
5858                                            objfile->obfd->section_count,
5859                                            VEC(arm_mapping_symbol_s) *);
5860     }
5861   map_p = &data->section_maps[bfd_get_section (sym)->index];
5862
5863   new_map_sym.value = sym->value;
5864   new_map_sym.type = name[1];
5865
5866   /* Assume that most mapping symbols appear in order of increasing
5867      value.  If they were randomly distributed, it would be faster to
5868      always push here and then sort at first use.  */
5869   if (!VEC_empty (arm_mapping_symbol_s, *map_p))
5870     {
5871       struct arm_mapping_symbol *prev_map_sym;
5872
5873       prev_map_sym = VEC_last (arm_mapping_symbol_s, *map_p);
5874       if (prev_map_sym->value >= sym->value)
5875         {
5876           unsigned int idx;
5877           idx = VEC_lower_bound (arm_mapping_symbol_s, *map_p, &new_map_sym,
5878                                  arm_compare_mapping_symbols);
5879           VEC_safe_insert (arm_mapping_symbol_s, *map_p, idx, &new_map_sym);
5880           return;
5881         }
5882     }
5883
5884   VEC_safe_push (arm_mapping_symbol_s, *map_p, &new_map_sym);
5885 }
5886
5887 static void
5888 arm_write_pc (struct regcache *regcache, CORE_ADDR pc)
5889 {
5890   regcache_cooked_write_unsigned (regcache, ARM_PC_REGNUM, pc);
5891
5892   /* If necessary, set the T bit.  */
5893   if (arm_apcs_32)
5894     {
5895       ULONGEST val;
5896       regcache_cooked_read_unsigned (regcache, ARM_PS_REGNUM, &val);
5897       if (arm_pc_is_thumb (pc))
5898         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM, val | CPSR_T);
5899       else
5900         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
5901                                         val & ~(ULONGEST) CPSR_T);
5902     }
5903 }
5904
5905 /* Read the contents of a NEON quad register, by reading from two
5906    double registers.  This is used to implement the quad pseudo
5907    registers, and for argument passing in case the quad registers are
5908    missing; vectors are passed in quad registers when using the VFP
5909    ABI, even if a NEON unit is not present.  REGNUM is the index of
5910    the quad register, in [0, 15].  */
5911
5912 static void
5913 arm_neon_quad_read (struct gdbarch *gdbarch, struct regcache *regcache,
5914                     int regnum, gdb_byte *buf)
5915 {
5916   char name_buf[4];
5917   gdb_byte reg_buf[8];
5918   int offset, double_regnum;
5919
5920   sprintf (name_buf, "d%d", regnum << 1);
5921   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
5922                                                strlen (name_buf));
5923
5924   /* d0 is always the least significant half of q0.  */
5925   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5926     offset = 8;
5927   else
5928     offset = 0;
5929
5930   regcache_raw_read (regcache, double_regnum, reg_buf);
5931   memcpy (buf + offset, reg_buf, 8);
5932
5933   offset = 8 - offset;
5934   regcache_raw_read (regcache, double_regnum + 1, reg_buf);
5935   memcpy (buf + offset, reg_buf, 8);
5936 }
5937
5938 static void
5939 arm_pseudo_read (struct gdbarch *gdbarch, struct regcache *regcache,
5940                  int regnum, gdb_byte *buf)
5941 {
5942   const int num_regs = gdbarch_num_regs (gdbarch);
5943   char name_buf[4];
5944   gdb_byte reg_buf[8];
5945   int offset, double_regnum;
5946
5947   gdb_assert (regnum >= num_regs);
5948   regnum -= num_regs;
5949
5950   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
5951     /* Quad-precision register.  */
5952     arm_neon_quad_read (gdbarch, regcache, regnum - 32, buf);
5953   else
5954     {
5955       /* Single-precision register.  */
5956       gdb_assert (regnum < 32);
5957
5958       /* s0 is always the least significant half of d0.  */
5959       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5960         offset = (regnum & 1) ? 0 : 4;
5961       else
5962         offset = (regnum & 1) ? 4 : 0;
5963
5964       sprintf (name_buf, "d%d", regnum >> 1);
5965       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
5966                                                    strlen (name_buf));
5967
5968       regcache_raw_read (regcache, double_regnum, reg_buf);
5969       memcpy (buf, reg_buf + offset, 4);
5970     }
5971 }
5972
5973 /* Store the contents of BUF to a NEON quad register, by writing to
5974    two double registers.  This is used to implement the quad pseudo
5975    registers, and for argument passing in case the quad registers are
5976    missing; vectors are passed in quad registers when using the VFP
5977    ABI, even if a NEON unit is not present.  REGNUM is the index
5978    of the quad register, in [0, 15].  */
5979
5980 static void
5981 arm_neon_quad_write (struct gdbarch *gdbarch, struct regcache *regcache,
5982                      int regnum, const gdb_byte *buf)
5983 {
5984   char name_buf[4];
5985   gdb_byte reg_buf[8];
5986   int offset, double_regnum;
5987
5988   sprintf (name_buf, "d%d", regnum << 1);
5989   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
5990                                                strlen (name_buf));
5991
5992   /* d0 is always the least significant half of q0.  */
5993   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
5994     offset = 8;
5995   else
5996     offset = 0;
5997
5998   regcache_raw_write (regcache, double_regnum, buf + offset);
5999   offset = 8 - offset;
6000   regcache_raw_write (regcache, double_regnum + 1, buf + offset);
6001 }
6002
6003 static void
6004 arm_pseudo_write (struct gdbarch *gdbarch, struct regcache *regcache,
6005                   int regnum, const gdb_byte *buf)
6006 {
6007   const int num_regs = gdbarch_num_regs (gdbarch);
6008   char name_buf[4];
6009   gdb_byte reg_buf[8];
6010   int offset, double_regnum;
6011
6012   gdb_assert (regnum >= num_regs);
6013   regnum -= num_regs;
6014
6015   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
6016     /* Quad-precision register.  */
6017     arm_neon_quad_write (gdbarch, regcache, regnum - 32, buf);
6018   else
6019     {
6020       /* Single-precision register.  */
6021       gdb_assert (regnum < 32);
6022
6023       /* s0 is always the least significant half of d0.  */
6024       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
6025         offset = (regnum & 1) ? 0 : 4;
6026       else
6027         offset = (regnum & 1) ? 4 : 0;
6028
6029       sprintf (name_buf, "d%d", regnum >> 1);
6030       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
6031                                                    strlen (name_buf));
6032
6033       regcache_raw_read (regcache, double_regnum, reg_buf);
6034       memcpy (reg_buf + offset, buf, 4);
6035       regcache_raw_write (regcache, double_regnum, reg_buf);
6036     }
6037 }
6038
6039 static struct value *
6040 value_of_arm_user_reg (struct frame_info *frame, const void *baton)
6041 {
6042   const int *reg_p = baton;
6043   return value_of_register (*reg_p, frame);
6044 }
6045 \f
6046 static enum gdb_osabi
6047 arm_elf_osabi_sniffer (bfd *abfd)
6048 {
6049   unsigned int elfosabi;
6050   enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
6051
6052   elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI];
6053
6054   if (elfosabi == ELFOSABI_ARM)
6055     /* GNU tools use this value.  Check note sections in this case,
6056        as well.  */
6057     bfd_map_over_sections (abfd,
6058                            generic_elf_osabi_sniff_abi_tag_sections, 
6059                            &osabi);
6060
6061   /* Anything else will be handled by the generic ELF sniffer.  */
6062   return osabi;
6063 }
6064
6065 \f
6066 /* Initialize the current architecture based on INFO.  If possible,
6067    re-use an architecture from ARCHES, which is a list of
6068    architectures already created during this debugging session.
6069
6070    Called e.g. at program startup, when reading a core file, and when
6071    reading a binary file.  */
6072
6073 static struct gdbarch *
6074 arm_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
6075 {
6076   struct gdbarch_tdep *tdep;
6077   struct gdbarch *gdbarch;
6078   struct gdbarch_list *best_arch;
6079   enum arm_abi_kind arm_abi = arm_abi_global;
6080   enum arm_float_model fp_model = arm_fp_model;
6081   struct tdesc_arch_data *tdesc_data = NULL;
6082   int i;
6083   int have_vfp_registers = 0, have_vfp_pseudos = 0, have_neon_pseudos = 0;
6084   int have_neon = 0;
6085   int have_fpa_registers = 1;
6086
6087   /* Check any target description for validity.  */
6088   if (tdesc_has_registers (info.target_desc))
6089     {
6090       /* For most registers we require GDB's default names; but also allow
6091          the numeric names for sp / lr / pc, as a convenience.  */
6092       static const char *const arm_sp_names[] = { "r13", "sp", NULL };
6093       static const char *const arm_lr_names[] = { "r14", "lr", NULL };
6094       static const char *const arm_pc_names[] = { "r15", "pc", NULL };
6095
6096       const struct tdesc_feature *feature;
6097       int valid_p;
6098
6099       feature = tdesc_find_feature (info.target_desc,
6100                                     "org.gnu.gdb.arm.core");
6101       if (feature == NULL)
6102         return NULL;
6103
6104       tdesc_data = tdesc_data_alloc ();
6105
6106       valid_p = 1;
6107       for (i = 0; i < ARM_SP_REGNUM; i++)
6108         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
6109                                             arm_register_names[i]);
6110       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
6111                                                   ARM_SP_REGNUM,
6112                                                   arm_sp_names);
6113       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
6114                                                   ARM_LR_REGNUM,
6115                                                   arm_lr_names);
6116       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
6117                                                   ARM_PC_REGNUM,
6118                                                   arm_pc_names);
6119       valid_p &= tdesc_numbered_register (feature, tdesc_data,
6120                                           ARM_PS_REGNUM, "cpsr");
6121
6122       if (!valid_p)
6123         {
6124           tdesc_data_cleanup (tdesc_data);
6125           return NULL;
6126         }
6127
6128       feature = tdesc_find_feature (info.target_desc,
6129                                     "org.gnu.gdb.arm.fpa");
6130       if (feature != NULL)
6131         {
6132           valid_p = 1;
6133           for (i = ARM_F0_REGNUM; i <= ARM_FPS_REGNUM; i++)
6134             valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
6135                                                 arm_register_names[i]);
6136           if (!valid_p)
6137             {
6138               tdesc_data_cleanup (tdesc_data);
6139               return NULL;
6140             }
6141         }
6142       else
6143         have_fpa_registers = 0;
6144
6145       feature = tdesc_find_feature (info.target_desc,
6146                                     "org.gnu.gdb.xscale.iwmmxt");
6147       if (feature != NULL)
6148         {
6149           static const char *const iwmmxt_names[] = {
6150             "wR0", "wR1", "wR2", "wR3", "wR4", "wR5", "wR6", "wR7",
6151             "wR8", "wR9", "wR10", "wR11", "wR12", "wR13", "wR14", "wR15",
6152             "wCID", "wCon", "wCSSF", "wCASF", "", "", "", "",
6153             "wCGR0", "wCGR1", "wCGR2", "wCGR3", "", "", "", "",
6154           };
6155
6156           valid_p = 1;
6157           for (i = ARM_WR0_REGNUM; i <= ARM_WR15_REGNUM; i++)
6158             valid_p
6159               &= tdesc_numbered_register (feature, tdesc_data, i,
6160                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
6161
6162           /* Check for the control registers, but do not fail if they
6163              are missing.  */
6164           for (i = ARM_WC0_REGNUM; i <= ARM_WCASF_REGNUM; i++)
6165             tdesc_numbered_register (feature, tdesc_data, i,
6166                                      iwmmxt_names[i - ARM_WR0_REGNUM]);
6167
6168           for (i = ARM_WCGR0_REGNUM; i <= ARM_WCGR3_REGNUM; i++)
6169             valid_p
6170               &= tdesc_numbered_register (feature, tdesc_data, i,
6171                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
6172
6173           if (!valid_p)
6174             {
6175               tdesc_data_cleanup (tdesc_data);
6176               return NULL;
6177             }
6178         }
6179
6180       /* If we have a VFP unit, check whether the single precision registers
6181          are present.  If not, then we will synthesize them as pseudo
6182          registers.  */
6183       feature = tdesc_find_feature (info.target_desc,
6184                                     "org.gnu.gdb.arm.vfp");
6185       if (feature != NULL)
6186         {
6187           static const char *const vfp_double_names[] = {
6188             "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
6189             "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
6190             "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
6191             "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
6192           };
6193
6194           /* Require the double precision registers.  There must be either
6195              16 or 32.  */
6196           valid_p = 1;
6197           for (i = 0; i < 32; i++)
6198             {
6199               valid_p &= tdesc_numbered_register (feature, tdesc_data,
6200                                                   ARM_D0_REGNUM + i,
6201                                                   vfp_double_names[i]);
6202               if (!valid_p)
6203                 break;
6204             }
6205
6206           if (!valid_p && i != 16)
6207             {
6208               tdesc_data_cleanup (tdesc_data);
6209               return NULL;
6210             }
6211
6212           if (tdesc_unnumbered_register (feature, "s0") == 0)
6213             have_vfp_pseudos = 1;
6214
6215           have_vfp_registers = 1;
6216
6217           /* If we have VFP, also check for NEON.  The architecture allows
6218              NEON without VFP (integer vector operations only), but GDB
6219              does not support that.  */
6220           feature = tdesc_find_feature (info.target_desc,
6221                                         "org.gnu.gdb.arm.neon");
6222           if (feature != NULL)
6223             {
6224               /* NEON requires 32 double-precision registers.  */
6225               if (i != 32)
6226                 {
6227                   tdesc_data_cleanup (tdesc_data);
6228                   return NULL;
6229                 }
6230
6231               /* If there are quad registers defined by the stub, use
6232                  their type; otherwise (normally) provide them with
6233                  the default type.  */
6234               if (tdesc_unnumbered_register (feature, "q0") == 0)
6235                 have_neon_pseudos = 1;
6236
6237               have_neon = 1;
6238             }
6239         }
6240     }
6241
6242   /* If we have an object to base this architecture on, try to determine
6243      its ABI.  */
6244
6245   if (arm_abi == ARM_ABI_AUTO && info.abfd != NULL)
6246     {
6247       int ei_osabi, e_flags;
6248
6249       switch (bfd_get_flavour (info.abfd))
6250         {
6251         case bfd_target_aout_flavour:
6252           /* Assume it's an old APCS-style ABI.  */
6253           arm_abi = ARM_ABI_APCS;
6254           break;
6255
6256         case bfd_target_coff_flavour:
6257           /* Assume it's an old APCS-style ABI.  */
6258           /* XXX WinCE?  */
6259           arm_abi = ARM_ABI_APCS;
6260           break;
6261
6262         case bfd_target_elf_flavour:
6263           ei_osabi = elf_elfheader (info.abfd)->e_ident[EI_OSABI];
6264           e_flags = elf_elfheader (info.abfd)->e_flags;
6265
6266           if (ei_osabi == ELFOSABI_ARM)
6267             {
6268               /* GNU tools used to use this value, but do not for EABI
6269                  objects.  There's nowhere to tag an EABI version
6270                  anyway, so assume APCS.  */
6271               arm_abi = ARM_ABI_APCS;
6272             }
6273           else if (ei_osabi == ELFOSABI_NONE)
6274             {
6275               int eabi_ver = EF_ARM_EABI_VERSION (e_flags);
6276
6277               switch (eabi_ver)
6278                 {
6279                 case EF_ARM_EABI_UNKNOWN:
6280                   /* Assume GNU tools.  */
6281                   arm_abi = ARM_ABI_APCS;
6282                   break;
6283
6284                 case EF_ARM_EABI_VER4:
6285                 case EF_ARM_EABI_VER5:
6286                   arm_abi = ARM_ABI_AAPCS;
6287                   /* EABI binaries default to VFP float ordering.
6288                      They may also contain build attributes that can
6289                      be used to identify if the VFP argument-passing
6290                      ABI is in use.  */
6291                   if (fp_model == ARM_FLOAT_AUTO)
6292                     {
6293 #ifdef HAVE_ELF
6294                       switch (bfd_elf_get_obj_attr_int (info.abfd,
6295                                                         OBJ_ATTR_PROC,
6296                                                         Tag_ABI_VFP_args))
6297                         {
6298                         case 0:
6299                           /* "The user intended FP parameter/result
6300                              passing to conform to AAPCS, base
6301                              variant".  */
6302                           fp_model = ARM_FLOAT_SOFT_VFP;
6303                           break;
6304                         case 1:
6305                           /* "The user intended FP parameter/result
6306                              passing to conform to AAPCS, VFP
6307                              variant".  */
6308                           fp_model = ARM_FLOAT_VFP;
6309                           break;
6310                         case 2:
6311                           /* "The user intended FP parameter/result
6312                              passing to conform to tool chain-specific
6313                              conventions" - we don't know any such
6314                              conventions, so leave it as "auto".  */
6315                           break;
6316                         default:
6317                           /* Attribute value not mentioned in the
6318                              October 2008 ABI, so leave it as
6319                              "auto".  */
6320                           break;
6321                         }
6322 #else
6323                       fp_model = ARM_FLOAT_SOFT_VFP;
6324 #endif
6325                     }
6326                   break;
6327
6328                 default:
6329                   /* Leave it as "auto".  */
6330                   warning (_("unknown ARM EABI version 0x%x"), eabi_ver);
6331                   break;
6332                 }
6333             }
6334
6335           if (fp_model == ARM_FLOAT_AUTO)
6336             {
6337               int e_flags = elf_elfheader (info.abfd)->e_flags;
6338
6339               switch (e_flags & (EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT))
6340                 {
6341                 case 0:
6342                   /* Leave it as "auto".  Strictly speaking this case
6343                      means FPA, but almost nobody uses that now, and
6344                      many toolchains fail to set the appropriate bits
6345                      for the floating-point model they use.  */
6346                   break;
6347                 case EF_ARM_SOFT_FLOAT:
6348                   fp_model = ARM_FLOAT_SOFT_FPA;
6349                   break;
6350                 case EF_ARM_VFP_FLOAT:
6351                   fp_model = ARM_FLOAT_VFP;
6352                   break;
6353                 case EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT:
6354                   fp_model = ARM_FLOAT_SOFT_VFP;
6355                   break;
6356                 }
6357             }
6358
6359           if (e_flags & EF_ARM_BE8)
6360             info.byte_order_for_code = BFD_ENDIAN_LITTLE;
6361
6362           break;
6363
6364         default:
6365           /* Leave it as "auto".  */
6366           break;
6367         }
6368     }
6369
6370   /* If there is already a candidate, use it.  */
6371   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
6372        best_arch != NULL;
6373        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
6374     {
6375       if (arm_abi != ARM_ABI_AUTO
6376           && arm_abi != gdbarch_tdep (best_arch->gdbarch)->arm_abi)
6377         continue;
6378
6379       if (fp_model != ARM_FLOAT_AUTO
6380           && fp_model != gdbarch_tdep (best_arch->gdbarch)->fp_model)
6381         continue;
6382
6383       /* There are various other properties in tdep that we do not
6384          need to check here: those derived from a target description,
6385          since gdbarches with a different target description are
6386          automatically disqualified.  */
6387
6388       /* Found a match.  */
6389       break;
6390     }
6391
6392   if (best_arch != NULL)
6393     {
6394       if (tdesc_data != NULL)
6395         tdesc_data_cleanup (tdesc_data);
6396       return best_arch->gdbarch;
6397     }
6398
6399   tdep = xcalloc (1, sizeof (struct gdbarch_tdep));
6400   gdbarch = gdbarch_alloc (&info, tdep);
6401
6402   /* Record additional information about the architecture we are defining.
6403      These are gdbarch discriminators, like the OSABI.  */
6404   tdep->arm_abi = arm_abi;
6405   tdep->fp_model = fp_model;
6406   tdep->have_fpa_registers = have_fpa_registers;
6407   tdep->have_vfp_registers = have_vfp_registers;
6408   tdep->have_vfp_pseudos = have_vfp_pseudos;
6409   tdep->have_neon_pseudos = have_neon_pseudos;
6410   tdep->have_neon = have_neon;
6411
6412   /* Breakpoints.  */
6413   switch (info.byte_order_for_code)
6414     {
6415     case BFD_ENDIAN_BIG:
6416       tdep->arm_breakpoint = arm_default_arm_be_breakpoint;
6417       tdep->arm_breakpoint_size = sizeof (arm_default_arm_be_breakpoint);
6418       tdep->thumb_breakpoint = arm_default_thumb_be_breakpoint;
6419       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_be_breakpoint);
6420
6421       break;
6422
6423     case BFD_ENDIAN_LITTLE:
6424       tdep->arm_breakpoint = arm_default_arm_le_breakpoint;
6425       tdep->arm_breakpoint_size = sizeof (arm_default_arm_le_breakpoint);
6426       tdep->thumb_breakpoint = arm_default_thumb_le_breakpoint;
6427       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_le_breakpoint);
6428
6429       break;
6430
6431     default:
6432       internal_error (__FILE__, __LINE__,
6433                       _("arm_gdbarch_init: bad byte order for float format"));
6434     }
6435
6436   /* On ARM targets char defaults to unsigned.  */
6437   set_gdbarch_char_signed (gdbarch, 0);
6438
6439   /* Note: for displaced stepping, this includes the breakpoint, and one word
6440      of additional scratch space.  This setting isn't used for anything beside
6441      displaced stepping at present.  */
6442   set_gdbarch_max_insn_length (gdbarch, 4 * DISPLACED_MODIFIED_INSNS);
6443
6444   /* This should be low enough for everything.  */
6445   tdep->lowest_pc = 0x20;
6446   tdep->jb_pc = -1;     /* Longjump support not enabled by default.  */
6447
6448   /* The default, for both APCS and AAPCS, is to return small
6449      structures in registers.  */
6450   tdep->struct_return = reg_struct_return;
6451
6452   set_gdbarch_push_dummy_call (gdbarch, arm_push_dummy_call);
6453   set_gdbarch_frame_align (gdbarch, arm_frame_align);
6454
6455   set_gdbarch_write_pc (gdbarch, arm_write_pc);
6456
6457   /* Frame handling.  */
6458   set_gdbarch_dummy_id (gdbarch, arm_dummy_id);
6459   set_gdbarch_unwind_pc (gdbarch, arm_unwind_pc);
6460   set_gdbarch_unwind_sp (gdbarch, arm_unwind_sp);
6461
6462   frame_base_set_default (gdbarch, &arm_normal_base);
6463
6464   /* Address manipulation.  */
6465   set_gdbarch_smash_text_address (gdbarch, arm_smash_text_address);
6466   set_gdbarch_addr_bits_remove (gdbarch, arm_addr_bits_remove);
6467
6468   /* Advance PC across function entry code.  */
6469   set_gdbarch_skip_prologue (gdbarch, arm_skip_prologue);
6470
6471   /* Skip trampolines.  */
6472   set_gdbarch_skip_trampoline_code (gdbarch, arm_skip_stub);
6473
6474   /* The stack grows downward.  */
6475   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
6476
6477   /* Breakpoint manipulation.  */
6478   set_gdbarch_breakpoint_from_pc (gdbarch, arm_breakpoint_from_pc);
6479   set_gdbarch_remote_breakpoint_from_pc (gdbarch,
6480                                          arm_remote_breakpoint_from_pc);
6481
6482   /* Information about registers, etc.  */
6483   set_gdbarch_deprecated_fp_regnum (gdbarch, ARM_FP_REGNUM);    /* ??? */
6484   set_gdbarch_sp_regnum (gdbarch, ARM_SP_REGNUM);
6485   set_gdbarch_pc_regnum (gdbarch, ARM_PC_REGNUM);
6486   set_gdbarch_num_regs (gdbarch, ARM_NUM_REGS);
6487   set_gdbarch_register_type (gdbarch, arm_register_type);
6488
6489   /* This "info float" is FPA-specific.  Use the generic version if we
6490      do not have FPA.  */
6491   if (gdbarch_tdep (gdbarch)->have_fpa_registers)
6492     set_gdbarch_print_float_info (gdbarch, arm_print_float_info);
6493
6494   /* Internal <-> external register number maps.  */
6495   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, arm_dwarf_reg_to_regnum);
6496   set_gdbarch_register_sim_regno (gdbarch, arm_register_sim_regno);
6497
6498   set_gdbarch_register_name (gdbarch, arm_register_name);
6499
6500   /* Returning results.  */
6501   set_gdbarch_return_value (gdbarch, arm_return_value);
6502
6503   /* Disassembly.  */
6504   set_gdbarch_print_insn (gdbarch, gdb_print_insn_arm);
6505
6506   /* Minsymbol frobbing.  */
6507   set_gdbarch_elf_make_msymbol_special (gdbarch, arm_elf_make_msymbol_special);
6508   set_gdbarch_coff_make_msymbol_special (gdbarch,
6509                                          arm_coff_make_msymbol_special);
6510   set_gdbarch_record_special_symbol (gdbarch, arm_record_special_symbol);
6511
6512   /* Thumb-2 IT block support.  */
6513   set_gdbarch_adjust_breakpoint_address (gdbarch,
6514                                          arm_adjust_breakpoint_address);
6515
6516   /* Virtual tables.  */
6517   set_gdbarch_vbit_in_delta (gdbarch, 1);
6518
6519   /* Hook in the ABI-specific overrides, if they have been registered.  */
6520   gdbarch_init_osabi (info, gdbarch);
6521
6522   dwarf2_frame_set_init_reg (gdbarch, arm_dwarf2_frame_init_reg);
6523
6524   /* Add some default predicates.  */
6525   frame_unwind_append_unwinder (gdbarch, &arm_stub_unwind);
6526   dwarf2_append_unwinders (gdbarch);
6527   frame_unwind_append_unwinder (gdbarch, &arm_prologue_unwind);
6528
6529   /* Now we have tuned the configuration, set a few final things,
6530      based on what the OS ABI has told us.  */
6531
6532   /* If the ABI is not otherwise marked, assume the old GNU APCS.  EABI
6533      binaries are always marked.  */
6534   if (tdep->arm_abi == ARM_ABI_AUTO)
6535     tdep->arm_abi = ARM_ABI_APCS;
6536
6537   /* We used to default to FPA for generic ARM, but almost nobody
6538      uses that now, and we now provide a way for the user to force
6539      the model.  So default to the most useful variant.  */
6540   if (tdep->fp_model == ARM_FLOAT_AUTO)
6541     tdep->fp_model = ARM_FLOAT_SOFT_FPA;
6542
6543   if (tdep->jb_pc >= 0)
6544     set_gdbarch_get_longjmp_target (gdbarch, arm_get_longjmp_target);
6545
6546   /* Floating point sizes and format.  */
6547   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
6548   if (tdep->fp_model == ARM_FLOAT_SOFT_FPA || tdep->fp_model == ARM_FLOAT_FPA)
6549     {
6550       set_gdbarch_double_format
6551         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
6552       set_gdbarch_long_double_format
6553         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
6554     }
6555   else
6556     {
6557       set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
6558       set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double);
6559     }
6560
6561   if (have_vfp_pseudos)
6562     {
6563       /* NOTE: These are the only pseudo registers used by
6564          the ARM target at the moment.  If more are added, a
6565          little more care in numbering will be needed.  */
6566
6567       int num_pseudos = 32;
6568       if (have_neon_pseudos)
6569         num_pseudos += 16;
6570       set_gdbarch_num_pseudo_regs (gdbarch, num_pseudos);
6571       set_gdbarch_pseudo_register_read (gdbarch, arm_pseudo_read);
6572       set_gdbarch_pseudo_register_write (gdbarch, arm_pseudo_write);
6573     }
6574
6575   if (tdesc_data)
6576     {
6577       set_tdesc_pseudo_register_name (gdbarch, arm_register_name);
6578
6579       tdesc_use_registers (gdbarch, info.target_desc, tdesc_data);
6580
6581       /* Override tdesc_register_type to adjust the types of VFP
6582          registers for NEON.  */
6583       set_gdbarch_register_type (gdbarch, arm_register_type);
6584     }
6585
6586   /* Add standard register aliases.  We add aliases even for those
6587      nanes which are used by the current architecture - it's simpler,
6588      and does no harm, since nothing ever lists user registers.  */
6589   for (i = 0; i < ARRAY_SIZE (arm_register_aliases); i++)
6590     user_reg_add (gdbarch, arm_register_aliases[i].name,
6591                   value_of_arm_user_reg, &arm_register_aliases[i].regnum);
6592
6593   return gdbarch;
6594 }
6595
6596 static void
6597 arm_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
6598 {
6599   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
6600
6601   if (tdep == NULL)
6602     return;
6603
6604   fprintf_unfiltered (file, _("arm_dump_tdep: Lowest pc = 0x%lx"),
6605                       (unsigned long) tdep->lowest_pc);
6606 }
6607
6608 extern initialize_file_ftype _initialize_arm_tdep; /* -Wmissing-prototypes */
6609
6610 void
6611 _initialize_arm_tdep (void)
6612 {
6613   struct ui_file *stb;
6614   long length;
6615   struct cmd_list_element *new_set, *new_show;
6616   const char *setname;
6617   const char *setdesc;
6618   const char *const *regnames;
6619   int numregs, i, j;
6620   static char *helptext;
6621   char regdesc[1024], *rdptr = regdesc;
6622   size_t rest = sizeof (regdesc);
6623
6624   gdbarch_register (bfd_arch_arm, arm_gdbarch_init, arm_dump_tdep);
6625
6626   arm_objfile_data_key
6627     = register_objfile_data_with_cleanup (NULL, arm_objfile_data_free);
6628
6629   /* Register an ELF OS ABI sniffer for ARM binaries.  */
6630   gdbarch_register_osabi_sniffer (bfd_arch_arm,
6631                                   bfd_target_elf_flavour,
6632                                   arm_elf_osabi_sniffer);
6633
6634   /* Get the number of possible sets of register names defined in opcodes.  */
6635   num_disassembly_options = get_arm_regname_num_options ();
6636
6637   /* Add root prefix command for all "set arm"/"show arm" commands.  */
6638   add_prefix_cmd ("arm", no_class, set_arm_command,
6639                   _("Various ARM-specific commands."),
6640                   &setarmcmdlist, "set arm ", 0, &setlist);
6641
6642   add_prefix_cmd ("arm", no_class, show_arm_command,
6643                   _("Various ARM-specific commands."),
6644                   &showarmcmdlist, "show arm ", 0, &showlist);
6645
6646   /* Sync the opcode insn printer with our register viewer.  */
6647   parse_arm_disassembler_option ("reg-names-std");
6648
6649   /* Initialize the array that will be passed to
6650      add_setshow_enum_cmd().  */
6651   valid_disassembly_styles
6652     = xmalloc ((num_disassembly_options + 1) * sizeof (char *));
6653   for (i = 0; i < num_disassembly_options; i++)
6654     {
6655       numregs = get_arm_regnames (i, &setname, &setdesc, &regnames);
6656       valid_disassembly_styles[i] = setname;
6657       length = snprintf (rdptr, rest, "%s - %s\n", setname, setdesc);
6658       rdptr += length;
6659       rest -= length;
6660       /* When we find the default names, tell the disassembler to use
6661          them.  */
6662       if (!strcmp (setname, "std"))
6663         {
6664           disassembly_style = setname;
6665           set_arm_regname_option (i);
6666         }
6667     }
6668   /* Mark the end of valid options.  */
6669   valid_disassembly_styles[num_disassembly_options] = NULL;
6670
6671   /* Create the help text.  */
6672   stb = mem_fileopen ();
6673   fprintf_unfiltered (stb, "%s%s%s",
6674                       _("The valid values are:\n"),
6675                       regdesc,
6676                       _("The default is \"std\"."));
6677   helptext = ui_file_xstrdup (stb, NULL);
6678   ui_file_delete (stb);
6679
6680   add_setshow_enum_cmd("disassembler", no_class,
6681                        valid_disassembly_styles, &disassembly_style,
6682                        _("Set the disassembly style."),
6683                        _("Show the disassembly style."),
6684                        helptext,
6685                        set_disassembly_style_sfunc,
6686                        NULL, /* FIXME: i18n: The disassembly style is \"%s\".  */
6687                        &setarmcmdlist, &showarmcmdlist);
6688
6689   add_setshow_boolean_cmd ("apcs32", no_class, &arm_apcs_32,
6690                            _("Set usage of ARM 32-bit mode."),
6691                            _("Show usage of ARM 32-bit mode."),
6692                            _("When off, a 26-bit PC will be used."),
6693                            NULL,
6694                            NULL, /* FIXME: i18n: Usage of ARM 32-bit mode is %s.  */
6695                            &setarmcmdlist, &showarmcmdlist);
6696
6697   /* Add a command to allow the user to force the FPU model.  */
6698   add_setshow_enum_cmd ("fpu", no_class, fp_model_strings, &current_fp_model,
6699                         _("Set the floating point type."),
6700                         _("Show the floating point type."),
6701                         _("auto - Determine the FP typefrom the OS-ABI.\n\
6702 softfpa - Software FP, mixed-endian doubles on little-endian ARMs.\n\
6703 fpa - FPA co-processor (GCC compiled).\n\
6704 softvfp - Software FP with pure-endian doubles.\n\
6705 vfp - VFP co-processor."),
6706                         set_fp_model_sfunc, show_fp_model,
6707                         &setarmcmdlist, &showarmcmdlist);
6708
6709   /* Add a command to allow the user to force the ABI.  */
6710   add_setshow_enum_cmd ("abi", class_support, arm_abi_strings, &arm_abi_string,
6711                         _("Set the ABI."),
6712                         _("Show the ABI."),
6713                         NULL, arm_set_abi, arm_show_abi,
6714                         &setarmcmdlist, &showarmcmdlist);
6715
6716   /* Add two commands to allow the user to force the assumed
6717      execution mode.  */
6718   add_setshow_enum_cmd ("fallback-mode", class_support,
6719                         arm_mode_strings, &arm_fallback_mode_string,
6720                         _("Set the mode assumed when symbols are unavailable."),
6721                         _("Show the mode assumed when symbols are unavailable."),
6722                         NULL, NULL, arm_show_fallback_mode,
6723                         &setarmcmdlist, &showarmcmdlist);
6724   add_setshow_enum_cmd ("force-mode", class_support,
6725                         arm_mode_strings, &arm_force_mode_string,
6726                         _("Set the mode assumed even when symbols are available."),
6727                         _("Show the mode assumed even when symbols are available."),
6728                         NULL, NULL, arm_show_force_mode,
6729                         &setarmcmdlist, &showarmcmdlist);
6730
6731   /* Debugging flag.  */
6732   add_setshow_boolean_cmd ("arm", class_maintenance, &arm_debug,
6733                            _("Set ARM debugging."),
6734                            _("Show ARM debugging."),
6735                            _("When on, arm-specific debugging is enabled."),
6736                            NULL,
6737                            NULL, /* FIXME: i18n: "ARM debugging is %s.  */
6738                            &setdebuglist, &showdebuglist);
6739 }