Add new infrun.h header.
[external/binutils.git] / gdb / arm-tdep.c
1 /* Common target dependent code for GDB on ARM systems.
2
3    Copyright (C) 1988-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21
22 #include <ctype.h>              /* XXX for isupper ().  */
23
24 #include "frame.h"
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include <string.h>
30 #include "dis-asm.h"            /* For register styles.  */
31 #include "regcache.h"
32 #include "reggroups.h"
33 #include "doublest.h"
34 #include "value.h"
35 #include "arch-utils.h"
36 #include "osabi.h"
37 #include "frame-unwind.h"
38 #include "frame-base.h"
39 #include "trad-frame.h"
40 #include "objfiles.h"
41 #include "dwarf2-frame.h"
42 #include "gdbtypes.h"
43 #include "prologue-value.h"
44 #include "remote.h"
45 #include "target-descriptions.h"
46 #include "user-regs.h"
47 #include "observer.h"
48
49 #include "arm-tdep.h"
50 #include "gdb/sim-arm.h"
51
52 #include "elf-bfd.h"
53 #include "coff/internal.h"
54 #include "elf/arm.h"
55
56 #include "gdb_assert.h"
57 #include "vec.h"
58
59 #include "record.h"
60 #include "record-full.h"
61
62 #include "features/arm-with-m.c"
63 #include "features/arm-with-m-fpa-layout.c"
64 #include "features/arm-with-m-vfp-d16.c"
65 #include "features/arm-with-iwmmxt.c"
66 #include "features/arm-with-vfpv2.c"
67 #include "features/arm-with-vfpv3.c"
68 #include "features/arm-with-neon.c"
69
70 static int arm_debug;
71
72 /* Macros for setting and testing a bit in a minimal symbol that marks
73    it as Thumb function.  The MSB of the minimal symbol's "info" field
74    is used for this purpose.
75
76    MSYMBOL_SET_SPECIAL  Actually sets the "special" bit.
77    MSYMBOL_IS_SPECIAL   Tests the "special" bit in a minimal symbol.  */
78
79 #define MSYMBOL_SET_SPECIAL(msym)                               \
80         MSYMBOL_TARGET_FLAG_1 (msym) = 1
81
82 #define MSYMBOL_IS_SPECIAL(msym)                                \
83         MSYMBOL_TARGET_FLAG_1 (msym)
84
85 /* Per-objfile data used for mapping symbols.  */
86 static const struct objfile_data *arm_objfile_data_key;
87
88 struct arm_mapping_symbol
89 {
90   bfd_vma value;
91   char type;
92 };
93 typedef struct arm_mapping_symbol arm_mapping_symbol_s;
94 DEF_VEC_O(arm_mapping_symbol_s);
95
96 struct arm_per_objfile
97 {
98   VEC(arm_mapping_symbol_s) **section_maps;
99 };
100
101 /* The list of available "set arm ..." and "show arm ..." commands.  */
102 static struct cmd_list_element *setarmcmdlist = NULL;
103 static struct cmd_list_element *showarmcmdlist = NULL;
104
105 /* The type of floating-point to use.  Keep this in sync with enum
106    arm_float_model, and the help string in _initialize_arm_tdep.  */
107 static const char *const fp_model_strings[] =
108 {
109   "auto",
110   "softfpa",
111   "fpa",
112   "softvfp",
113   "vfp",
114   NULL
115 };
116
117 /* A variable that can be configured by the user.  */
118 static enum arm_float_model arm_fp_model = ARM_FLOAT_AUTO;
119 static const char *current_fp_model = "auto";
120
121 /* The ABI to use.  Keep this in sync with arm_abi_kind.  */
122 static const char *const arm_abi_strings[] =
123 {
124   "auto",
125   "APCS",
126   "AAPCS",
127   NULL
128 };
129
130 /* A variable that can be configured by the user.  */
131 static enum arm_abi_kind arm_abi_global = ARM_ABI_AUTO;
132 static const char *arm_abi_string = "auto";
133
134 /* The execution mode to assume.  */
135 static const char *const arm_mode_strings[] =
136   {
137     "auto",
138     "arm",
139     "thumb",
140     NULL
141   };
142
143 static const char *arm_fallback_mode_string = "auto";
144 static const char *arm_force_mode_string = "auto";
145
146 /* Internal override of the execution mode.  -1 means no override,
147    0 means override to ARM mode, 1 means override to Thumb mode.
148    The effect is the same as if arm_force_mode has been set by the
149    user (except the internal override has precedence over a user's
150    arm_force_mode override).  */
151 static int arm_override_mode = -1;
152
153 /* Number of different reg name sets (options).  */
154 static int num_disassembly_options;
155
156 /* The standard register names, and all the valid aliases for them.  Note
157    that `fp', `sp' and `pc' are not added in this alias list, because they
158    have been added as builtin user registers in
159    std-regs.c:_initialize_frame_reg.  */
160 static const struct
161 {
162   const char *name;
163   int regnum;
164 } arm_register_aliases[] = {
165   /* Basic register numbers.  */
166   { "r0", 0 },
167   { "r1", 1 },
168   { "r2", 2 },
169   { "r3", 3 },
170   { "r4", 4 },
171   { "r5", 5 },
172   { "r6", 6 },
173   { "r7", 7 },
174   { "r8", 8 },
175   { "r9", 9 },
176   { "r10", 10 },
177   { "r11", 11 },
178   { "r12", 12 },
179   { "r13", 13 },
180   { "r14", 14 },
181   { "r15", 15 },
182   /* Synonyms (argument and variable registers).  */
183   { "a1", 0 },
184   { "a2", 1 },
185   { "a3", 2 },
186   { "a4", 3 },
187   { "v1", 4 },
188   { "v2", 5 },
189   { "v3", 6 },
190   { "v4", 7 },
191   { "v5", 8 },
192   { "v6", 9 },
193   { "v7", 10 },
194   { "v8", 11 },
195   /* Other platform-specific names for r9.  */
196   { "sb", 9 },
197   { "tr", 9 },
198   /* Special names.  */
199   { "ip", 12 },
200   { "lr", 14 },
201   /* Names used by GCC (not listed in the ARM EABI).  */
202   { "sl", 10 },
203   /* A special name from the older ATPCS.  */
204   { "wr", 7 },
205 };
206
207 static const char *const arm_register_names[] =
208 {"r0",  "r1",  "r2",  "r3",     /*  0  1  2  3 */
209  "r4",  "r5",  "r6",  "r7",     /*  4  5  6  7 */
210  "r8",  "r9",  "r10", "r11",    /*  8  9 10 11 */
211  "r12", "sp",  "lr",  "pc",     /* 12 13 14 15 */
212  "f0",  "f1",  "f2",  "f3",     /* 16 17 18 19 */
213  "f4",  "f5",  "f6",  "f7",     /* 20 21 22 23 */
214  "fps", "cpsr" };               /* 24 25       */
215
216 /* Valid register name styles.  */
217 static const char **valid_disassembly_styles;
218
219 /* Disassembly style to use. Default to "std" register names.  */
220 static const char *disassembly_style;
221
222 /* This is used to keep the bfd arch_info in sync with the disassembly
223    style.  */
224 static void set_disassembly_style_sfunc(char *, int,
225                                          struct cmd_list_element *);
226 static void set_disassembly_style (void);
227
228 static void convert_from_extended (const struct floatformat *, const void *,
229                                    void *, int);
230 static void convert_to_extended (const struct floatformat *, void *,
231                                  const void *, int);
232
233 static enum register_status arm_neon_quad_read (struct gdbarch *gdbarch,
234                                                 struct regcache *regcache,
235                                                 int regnum, gdb_byte *buf);
236 static void arm_neon_quad_write (struct gdbarch *gdbarch,
237                                  struct regcache *regcache,
238                                  int regnum, const gdb_byte *buf);
239
240 static int thumb_insn_size (unsigned short inst1);
241
242 struct arm_prologue_cache
243 {
244   /* The stack pointer at the time this frame was created; i.e. the
245      caller's stack pointer when this function was called.  It is used
246      to identify this frame.  */
247   CORE_ADDR prev_sp;
248
249   /* The frame base for this frame is just prev_sp - frame size.
250      FRAMESIZE is the distance from the frame pointer to the
251      initial stack pointer.  */
252
253   int framesize;
254
255   /* The register used to hold the frame pointer for this frame.  */
256   int framereg;
257
258   /* Saved register offsets.  */
259   struct trad_frame_saved_reg *saved_regs;
260 };
261
262 static CORE_ADDR arm_analyze_prologue (struct gdbarch *gdbarch,
263                                        CORE_ADDR prologue_start,
264                                        CORE_ADDR prologue_end,
265                                        struct arm_prologue_cache *cache);
266
267 /* Architecture version for displaced stepping.  This effects the behaviour of
268    certain instructions, and really should not be hard-wired.  */
269
270 #define DISPLACED_STEPPING_ARCH_VERSION         5
271
272 /* Addresses for calling Thumb functions have the bit 0 set.
273    Here are some macros to test, set, or clear bit 0 of addresses.  */
274 #define IS_THUMB_ADDR(addr)     ((addr) & 1)
275 #define MAKE_THUMB_ADDR(addr)   ((addr) | 1)
276 #define UNMAKE_THUMB_ADDR(addr) ((addr) & ~1)
277
278 /* Set to true if the 32-bit mode is in use.  */
279
280 int arm_apcs_32 = 1;
281
282 /* Return the bit mask in ARM_PS_REGNUM that indicates Thumb mode.  */
283
284 int
285 arm_psr_thumb_bit (struct gdbarch *gdbarch)
286 {
287   if (gdbarch_tdep (gdbarch)->is_m)
288     return XPSR_T;
289   else
290     return CPSR_T;
291 }
292
293 /* Determine if FRAME is executing in Thumb mode.  */
294
295 int
296 arm_frame_is_thumb (struct frame_info *frame)
297 {
298   CORE_ADDR cpsr;
299   ULONGEST t_bit = arm_psr_thumb_bit (get_frame_arch (frame));
300
301   /* Every ARM frame unwinder can unwind the T bit of the CPSR, either
302      directly (from a signal frame or dummy frame) or by interpreting
303      the saved LR (from a prologue or DWARF frame).  So consult it and
304      trust the unwinders.  */
305   cpsr = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
306
307   return (cpsr & t_bit) != 0;
308 }
309
310 /* Callback for VEC_lower_bound.  */
311
312 static inline int
313 arm_compare_mapping_symbols (const struct arm_mapping_symbol *lhs,
314                              const struct arm_mapping_symbol *rhs)
315 {
316   return lhs->value < rhs->value;
317 }
318
319 /* Search for the mapping symbol covering MEMADDR.  If one is found,
320    return its type.  Otherwise, return 0.  If START is non-NULL,
321    set *START to the location of the mapping symbol.  */
322
323 static char
324 arm_find_mapping_symbol (CORE_ADDR memaddr, CORE_ADDR *start)
325 {
326   struct obj_section *sec;
327
328   /* If there are mapping symbols, consult them.  */
329   sec = find_pc_section (memaddr);
330   if (sec != NULL)
331     {
332       struct arm_per_objfile *data;
333       VEC(arm_mapping_symbol_s) *map;
334       struct arm_mapping_symbol map_key = { memaddr - obj_section_addr (sec),
335                                             0 };
336       unsigned int idx;
337
338       data = objfile_data (sec->objfile, arm_objfile_data_key);
339       if (data != NULL)
340         {
341           map = data->section_maps[sec->the_bfd_section->index];
342           if (!VEC_empty (arm_mapping_symbol_s, map))
343             {
344               struct arm_mapping_symbol *map_sym;
345
346               idx = VEC_lower_bound (arm_mapping_symbol_s, map, &map_key,
347                                      arm_compare_mapping_symbols);
348
349               /* VEC_lower_bound finds the earliest ordered insertion
350                  point.  If the following symbol starts at this exact
351                  address, we use that; otherwise, the preceding
352                  mapping symbol covers this address.  */
353               if (idx < VEC_length (arm_mapping_symbol_s, map))
354                 {
355                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx);
356                   if (map_sym->value == map_key.value)
357                     {
358                       if (start)
359                         *start = map_sym->value + obj_section_addr (sec);
360                       return map_sym->type;
361                     }
362                 }
363
364               if (idx > 0)
365                 {
366                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx - 1);
367                   if (start)
368                     *start = map_sym->value + obj_section_addr (sec);
369                   return map_sym->type;
370                 }
371             }
372         }
373     }
374
375   return 0;
376 }
377
378 /* Determine if the program counter specified in MEMADDR is in a Thumb
379    function.  This function should be called for addresses unrelated to
380    any executing frame; otherwise, prefer arm_frame_is_thumb.  */
381
382 int
383 arm_pc_is_thumb (struct gdbarch *gdbarch, CORE_ADDR memaddr)
384 {
385   struct bound_minimal_symbol sym;
386   char type;
387   struct displaced_step_closure* dsc
388     = get_displaced_step_closure_by_addr(memaddr);
389
390   /* If checking the mode of displaced instruction in copy area, the mode
391      should be determined by instruction on the original address.  */
392   if (dsc)
393     {
394       if (debug_displaced)
395         fprintf_unfiltered (gdb_stdlog,
396                             "displaced: check mode of %.8lx instead of %.8lx\n",
397                             (unsigned long) dsc->insn_addr,
398                             (unsigned long) memaddr);
399       memaddr = dsc->insn_addr;
400     }
401
402   /* If bit 0 of the address is set, assume this is a Thumb address.  */
403   if (IS_THUMB_ADDR (memaddr))
404     return 1;
405
406   /* Respect internal mode override if active.  */
407   if (arm_override_mode != -1)
408     return arm_override_mode;
409
410   /* If the user wants to override the symbol table, let him.  */
411   if (strcmp (arm_force_mode_string, "arm") == 0)
412     return 0;
413   if (strcmp (arm_force_mode_string, "thumb") == 0)
414     return 1;
415
416   /* ARM v6-M and v7-M are always in Thumb mode.  */
417   if (gdbarch_tdep (gdbarch)->is_m)
418     return 1;
419
420   /* If there are mapping symbols, consult them.  */
421   type = arm_find_mapping_symbol (memaddr, NULL);
422   if (type)
423     return type == 't';
424
425   /* Thumb functions have a "special" bit set in minimal symbols.  */
426   sym = lookup_minimal_symbol_by_pc (memaddr);
427   if (sym.minsym)
428     return (MSYMBOL_IS_SPECIAL (sym.minsym));
429
430   /* If the user wants to override the fallback mode, let them.  */
431   if (strcmp (arm_fallback_mode_string, "arm") == 0)
432     return 0;
433   if (strcmp (arm_fallback_mode_string, "thumb") == 0)
434     return 1;
435
436   /* If we couldn't find any symbol, but we're talking to a running
437      target, then trust the current value of $cpsr.  This lets
438      "display/i $pc" always show the correct mode (though if there is
439      a symbol table we will not reach here, so it still may not be
440      displayed in the mode it will be executed).  */
441   if (target_has_registers)
442     return arm_frame_is_thumb (get_current_frame ());
443
444   /* Otherwise we're out of luck; we assume ARM.  */
445   return 0;
446 }
447
448 /* Remove useless bits from addresses in a running program.  */
449 static CORE_ADDR
450 arm_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR val)
451 {
452   /* On M-profile devices, do not strip the low bit from EXC_RETURN
453      (the magic exception return address).  */
454   if (gdbarch_tdep (gdbarch)->is_m
455       && (val & 0xfffffff0) == 0xfffffff0)
456     return val;
457
458   if (arm_apcs_32)
459     return UNMAKE_THUMB_ADDR (val);
460   else
461     return (val & 0x03fffffc);
462 }
463
464 /* Return 1 if PC is the start of a compiler helper function which
465    can be safely ignored during prologue skipping.  IS_THUMB is true
466    if the function is known to be a Thumb function due to the way it
467    is being called.  */
468 static int
469 skip_prologue_function (struct gdbarch *gdbarch, CORE_ADDR pc, int is_thumb)
470 {
471   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
472   struct bound_minimal_symbol msym;
473
474   msym = lookup_minimal_symbol_by_pc (pc);
475   if (msym.minsym != NULL
476       && BMSYMBOL_VALUE_ADDRESS (msym) == pc
477       && MSYMBOL_LINKAGE_NAME (msym.minsym) != NULL)
478     {
479       const char *name = MSYMBOL_LINKAGE_NAME (msym.minsym);
480
481       /* The GNU linker's Thumb call stub to foo is named
482          __foo_from_thumb.  */
483       if (strstr (name, "_from_thumb") != NULL)
484         name += 2;
485
486       /* On soft-float targets, __truncdfsf2 is called to convert promoted
487          arguments to their argument types in non-prototyped
488          functions.  */
489       if (strncmp (name, "__truncdfsf2", strlen ("__truncdfsf2")) == 0)
490         return 1;
491       if (strncmp (name, "__aeabi_d2f", strlen ("__aeabi_d2f")) == 0)
492         return 1;
493
494       /* Internal functions related to thread-local storage.  */
495       if (strncmp (name, "__tls_get_addr", strlen ("__tls_get_addr")) == 0)
496         return 1;
497       if (strncmp (name, "__aeabi_read_tp", strlen ("__aeabi_read_tp")) == 0)
498         return 1;
499     }
500   else
501     {
502       /* If we run against a stripped glibc, we may be unable to identify
503          special functions by name.  Check for one important case,
504          __aeabi_read_tp, by comparing the *code* against the default
505          implementation (this is hand-written ARM assembler in glibc).  */
506
507       if (!is_thumb
508           && read_memory_unsigned_integer (pc, 4, byte_order_for_code)
509              == 0xe3e00a0f /* mov r0, #0xffff0fff */
510           && read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code)
511              == 0xe240f01f) /* sub pc, r0, #31 */
512         return 1;
513     }
514
515   return 0;
516 }
517
518 /* Support routines for instruction parsing.  */
519 #define submask(x) ((1L << ((x) + 1)) - 1)
520 #define bit(obj,st) (((obj) >> (st)) & 1)
521 #define bits(obj,st,fn) (((obj) >> (st)) & submask ((fn) - (st)))
522 #define sbits(obj,st,fn) \
523   ((long) (bits(obj,st,fn) | ((long) bit(obj,fn) * ~ submask (fn - st))))
524 #define BranchDest(addr,instr) \
525   ((CORE_ADDR) (((unsigned long) (addr)) + 8 + (sbits (instr, 0, 23) << 2)))
526
527 /* Extract the immediate from instruction movw/movt of encoding T.  INSN1 is
528    the first 16-bit of instruction, and INSN2 is the second 16-bit of
529    instruction.  */
530 #define EXTRACT_MOVW_MOVT_IMM_T(insn1, insn2) \
531   ((bits ((insn1), 0, 3) << 12)               \
532    | (bits ((insn1), 10, 10) << 11)           \
533    | (bits ((insn2), 12, 14) << 8)            \
534    | bits ((insn2), 0, 7))
535
536 /* Extract the immediate from instruction movw/movt of encoding A.  INSN is
537    the 32-bit instruction.  */
538 #define EXTRACT_MOVW_MOVT_IMM_A(insn) \
539   ((bits ((insn), 16, 19) << 12) \
540    | bits ((insn), 0, 11))
541
542 /* Decode immediate value; implements ThumbExpandImmediate pseudo-op.  */
543
544 static unsigned int
545 thumb_expand_immediate (unsigned int imm)
546 {
547   unsigned int count = imm >> 7;
548
549   if (count < 8)
550     switch (count / 2)
551       {
552       case 0:
553         return imm & 0xff;
554       case 1:
555         return (imm & 0xff) | ((imm & 0xff) << 16);
556       case 2:
557         return ((imm & 0xff) << 8) | ((imm & 0xff) << 24);
558       case 3:
559         return (imm & 0xff) | ((imm & 0xff) << 8)
560                 | ((imm & 0xff) << 16) | ((imm & 0xff) << 24);
561       }
562
563   return (0x80 | (imm & 0x7f)) << (32 - count);
564 }
565
566 /* Return 1 if the 16-bit Thumb instruction INST might change
567    control flow, 0 otherwise.  */
568
569 static int
570 thumb_instruction_changes_pc (unsigned short inst)
571 {
572   if ((inst & 0xff00) == 0xbd00)        /* pop {rlist, pc} */
573     return 1;
574
575   if ((inst & 0xf000) == 0xd000)        /* conditional branch */
576     return 1;
577
578   if ((inst & 0xf800) == 0xe000)        /* unconditional branch */
579     return 1;
580
581   if ((inst & 0xff00) == 0x4700)        /* bx REG, blx REG */
582     return 1;
583
584   if ((inst & 0xff87) == 0x4687)        /* mov pc, REG */
585     return 1;
586
587   if ((inst & 0xf500) == 0xb100)        /* CBNZ or CBZ.  */
588     return 1;
589
590   return 0;
591 }
592
593 /* Return 1 if the 32-bit Thumb instruction in INST1 and INST2
594    might change control flow, 0 otherwise.  */
595
596 static int
597 thumb2_instruction_changes_pc (unsigned short inst1, unsigned short inst2)
598 {
599   if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
600     {
601       /* Branches and miscellaneous control instructions.  */
602
603       if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
604         {
605           /* B, BL, BLX.  */
606           return 1;
607         }
608       else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
609         {
610           /* SUBS PC, LR, #imm8.  */
611           return 1;
612         }
613       else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
614         {
615           /* Conditional branch.  */
616           return 1;
617         }
618
619       return 0;
620     }
621
622   if ((inst1 & 0xfe50) == 0xe810)
623     {
624       /* Load multiple or RFE.  */
625
626       if (bit (inst1, 7) && !bit (inst1, 8))
627         {
628           /* LDMIA or POP */
629           if (bit (inst2, 15))
630             return 1;
631         }
632       else if (!bit (inst1, 7) && bit (inst1, 8))
633         {
634           /* LDMDB */
635           if (bit (inst2, 15))
636             return 1;
637         }
638       else if (bit (inst1, 7) && bit (inst1, 8))
639         {
640           /* RFEIA */
641           return 1;
642         }
643       else if (!bit (inst1, 7) && !bit (inst1, 8))
644         {
645           /* RFEDB */
646           return 1;
647         }
648
649       return 0;
650     }
651
652   if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
653     {
654       /* MOV PC or MOVS PC.  */
655       return 1;
656     }
657
658   if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
659     {
660       /* LDR PC.  */
661       if (bits (inst1, 0, 3) == 15)
662         return 1;
663       if (bit (inst1, 7))
664         return 1;
665       if (bit (inst2, 11))
666         return 1;
667       if ((inst2 & 0x0fc0) == 0x0000)
668         return 1;       
669
670       return 0;
671     }
672
673   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
674     {
675       /* TBB.  */
676       return 1;
677     }
678
679   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
680     {
681       /* TBH.  */
682       return 1;
683     }
684
685   return 0;
686 }
687
688 /* Analyze a Thumb prologue, looking for a recognizable stack frame
689    and frame pointer.  Scan until we encounter a store that could
690    clobber the stack frame unexpectedly, or an unknown instruction.
691    Return the last address which is definitely safe to skip for an
692    initial breakpoint.  */
693
694 static CORE_ADDR
695 thumb_analyze_prologue (struct gdbarch *gdbarch,
696                         CORE_ADDR start, CORE_ADDR limit,
697                         struct arm_prologue_cache *cache)
698 {
699   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
700   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
701   int i;
702   pv_t regs[16];
703   struct pv_area *stack;
704   struct cleanup *back_to;
705   CORE_ADDR offset;
706   CORE_ADDR unrecognized_pc = 0;
707
708   for (i = 0; i < 16; i++)
709     regs[i] = pv_register (i, 0);
710   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
711   back_to = make_cleanup_free_pv_area (stack);
712
713   while (start < limit)
714     {
715       unsigned short insn;
716
717       insn = read_memory_unsigned_integer (start, 2, byte_order_for_code);
718
719       if ((insn & 0xfe00) == 0xb400)            /* push { rlist } */
720         {
721           int regno;
722           int mask;
723
724           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
725             break;
726
727           /* Bits 0-7 contain a mask for registers R0-R7.  Bit 8 says
728              whether to save LR (R14).  */
729           mask = (insn & 0xff) | ((insn & 0x100) << 6);
730
731           /* Calculate offsets of saved R0-R7 and LR.  */
732           for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
733             if (mask & (1 << regno))
734               {
735                 regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
736                                                        -4);
737                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
738               }
739         }
740       else if ((insn & 0xff00) == 0xb000)       /* add sp, #simm  OR  
741                                                    sub sp, #simm */
742         {
743           offset = (insn & 0x7f) << 2;          /* get scaled offset */
744           if (insn & 0x80)                      /* Check for SUB.  */
745             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
746                                                    -offset);
747           else
748             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
749                                                    offset);
750         }
751       else if ((insn & 0xf800) == 0xa800)       /* add Rd, sp, #imm */
752         regs[bits (insn, 8, 10)] = pv_add_constant (regs[ARM_SP_REGNUM],
753                                                     (insn & 0xff) << 2);
754       else if ((insn & 0xfe00) == 0x1c00        /* add Rd, Rn, #imm */
755                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
756         regs[bits (insn, 0, 2)] = pv_add_constant (regs[bits (insn, 3, 5)],
757                                                    bits (insn, 6, 8));
758       else if ((insn & 0xf800) == 0x3000        /* add Rd, #imm */
759                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
760         regs[bits (insn, 8, 10)] = pv_add_constant (regs[bits (insn, 8, 10)],
761                                                     bits (insn, 0, 7));
762       else if ((insn & 0xfe00) == 0x1800        /* add Rd, Rn, Rm */
763                && pv_is_register (regs[bits (insn, 6, 8)], ARM_SP_REGNUM)
764                && pv_is_constant (regs[bits (insn, 3, 5)]))
765         regs[bits (insn, 0, 2)] = pv_add (regs[bits (insn, 3, 5)],
766                                           regs[bits (insn, 6, 8)]);
767       else if ((insn & 0xff00) == 0x4400        /* add Rd, Rm */
768                && pv_is_constant (regs[bits (insn, 3, 6)]))
769         {
770           int rd = (bit (insn, 7) << 3) + bits (insn, 0, 2);
771           int rm = bits (insn, 3, 6);
772           regs[rd] = pv_add (regs[rd], regs[rm]);
773         }
774       else if ((insn & 0xff00) == 0x4600)       /* mov hi, lo or mov lo, hi */
775         {
776           int dst_reg = (insn & 0x7) + ((insn & 0x80) >> 4);
777           int src_reg = (insn & 0x78) >> 3;
778           regs[dst_reg] = regs[src_reg];
779         }
780       else if ((insn & 0xf800) == 0x9000)       /* str rd, [sp, #off] */
781         {
782           /* Handle stores to the stack.  Normally pushes are used,
783              but with GCC -mtpcs-frame, there may be other stores
784              in the prologue to create the frame.  */
785           int regno = (insn >> 8) & 0x7;
786           pv_t addr;
787
788           offset = (insn & 0xff) << 2;
789           addr = pv_add_constant (regs[ARM_SP_REGNUM], offset);
790
791           if (pv_area_store_would_trash (stack, addr))
792             break;
793
794           pv_area_store (stack, addr, 4, regs[regno]);
795         }
796       else if ((insn & 0xf800) == 0x6000)       /* str rd, [rn, #off] */
797         {
798           int rd = bits (insn, 0, 2);
799           int rn = bits (insn, 3, 5);
800           pv_t addr;
801
802           offset = bits (insn, 6, 10) << 2;
803           addr = pv_add_constant (regs[rn], offset);
804
805           if (pv_area_store_would_trash (stack, addr))
806             break;
807
808           pv_area_store (stack, addr, 4, regs[rd]);
809         }
810       else if (((insn & 0xf800) == 0x7000       /* strb Rd, [Rn, #off] */
811                 || (insn & 0xf800) == 0x8000)   /* strh Rd, [Rn, #off] */
812                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
813         /* Ignore stores of argument registers to the stack.  */
814         ;
815       else if ((insn & 0xf800) == 0xc800        /* ldmia Rn!, { registers } */
816                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
817         /* Ignore block loads from the stack, potentially copying
818            parameters from memory.  */
819         ;
820       else if ((insn & 0xf800) == 0x9800        /* ldr Rd, [Rn, #immed] */
821                || ((insn & 0xf800) == 0x6800    /* ldr Rd, [sp, #immed] */
822                    && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM)))
823         /* Similarly ignore single loads from the stack.  */
824         ;
825       else if ((insn & 0xffc0) == 0x0000        /* lsls Rd, Rm, #0 */
826                || (insn & 0xffc0) == 0x1c00)    /* add Rd, Rn, #0 */
827         /* Skip register copies, i.e. saves to another register
828            instead of the stack.  */
829         ;
830       else if ((insn & 0xf800) == 0x2000)       /* movs Rd, #imm */
831         /* Recognize constant loads; even with small stacks these are necessary
832            on Thumb.  */
833         regs[bits (insn, 8, 10)] = pv_constant (bits (insn, 0, 7));
834       else if ((insn & 0xf800) == 0x4800)       /* ldr Rd, [pc, #imm] */
835         {
836           /* Constant pool loads, for the same reason.  */
837           unsigned int constant;
838           CORE_ADDR loc;
839
840           loc = start + 4 + bits (insn, 0, 7) * 4;
841           constant = read_memory_unsigned_integer (loc, 4, byte_order);
842           regs[bits (insn, 8, 10)] = pv_constant (constant);
843         }
844       else if (thumb_insn_size (insn) == 4) /* 32-bit Thumb-2 instructions.  */
845         {
846           unsigned short inst2;
847
848           inst2 = read_memory_unsigned_integer (start + 2, 2,
849                                                 byte_order_for_code);
850
851           if ((insn & 0xf800) == 0xf000 && (inst2 & 0xe800) == 0xe800)
852             {
853               /* BL, BLX.  Allow some special function calls when
854                  skipping the prologue; GCC generates these before
855                  storing arguments to the stack.  */
856               CORE_ADDR nextpc;
857               int j1, j2, imm1, imm2;
858
859               imm1 = sbits (insn, 0, 10);
860               imm2 = bits (inst2, 0, 10);
861               j1 = bit (inst2, 13);
862               j2 = bit (inst2, 11);
863
864               offset = ((imm1 << 12) + (imm2 << 1));
865               offset ^= ((!j2) << 22) | ((!j1) << 23);
866
867               nextpc = start + 4 + offset;
868               /* For BLX make sure to clear the low bits.  */
869               if (bit (inst2, 12) == 0)
870                 nextpc = nextpc & 0xfffffffc;
871
872               if (!skip_prologue_function (gdbarch, nextpc,
873                                            bit (inst2, 12) != 0))
874                 break;
875             }
876
877           else if ((insn & 0xffd0) == 0xe900    /* stmdb Rn{!},
878                                                    { registers } */
879                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
880             {
881               pv_t addr = regs[bits (insn, 0, 3)];
882               int regno;
883
884               if (pv_area_store_would_trash (stack, addr))
885                 break;
886
887               /* Calculate offsets of saved registers.  */
888               for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
889                 if (inst2 & (1 << regno))
890                   {
891                     addr = pv_add_constant (addr, -4);
892                     pv_area_store (stack, addr, 4, regs[regno]);
893                   }
894
895               if (insn & 0x0020)
896                 regs[bits (insn, 0, 3)] = addr;
897             }
898
899           else if ((insn & 0xff50) == 0xe940    /* strd Rt, Rt2,
900                                                    [Rn, #+/-imm]{!} */
901                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
902             {
903               int regno1 = bits (inst2, 12, 15);
904               int regno2 = bits (inst2, 8, 11);
905               pv_t addr = regs[bits (insn, 0, 3)];
906
907               offset = inst2 & 0xff;
908               if (insn & 0x0080)
909                 addr = pv_add_constant (addr, offset);
910               else
911                 addr = pv_add_constant (addr, -offset);
912
913               if (pv_area_store_would_trash (stack, addr))
914                 break;
915
916               pv_area_store (stack, addr, 4, regs[regno1]);
917               pv_area_store (stack, pv_add_constant (addr, 4),
918                              4, regs[regno2]);
919
920               if (insn & 0x0020)
921                 regs[bits (insn, 0, 3)] = addr;
922             }
923
924           else if ((insn & 0xfff0) == 0xf8c0    /* str Rt,[Rn,+/-#imm]{!} */
925                    && (inst2 & 0x0c00) == 0x0c00
926                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
927             {
928               int regno = bits (inst2, 12, 15);
929               pv_t addr = regs[bits (insn, 0, 3)];
930
931               offset = inst2 & 0xff;
932               if (inst2 & 0x0200)
933                 addr = pv_add_constant (addr, offset);
934               else
935                 addr = pv_add_constant (addr, -offset);
936
937               if (pv_area_store_would_trash (stack, addr))
938                 break;
939
940               pv_area_store (stack, addr, 4, regs[regno]);
941
942               if (inst2 & 0x0100)
943                 regs[bits (insn, 0, 3)] = addr;
944             }
945
946           else if ((insn & 0xfff0) == 0xf8c0    /* str.w Rt,[Rn,#imm] */
947                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
948             {
949               int regno = bits (inst2, 12, 15);
950               pv_t addr;
951
952               offset = inst2 & 0xfff;
953               addr = pv_add_constant (regs[bits (insn, 0, 3)], offset);
954
955               if (pv_area_store_would_trash (stack, addr))
956                 break;
957
958               pv_area_store (stack, addr, 4, regs[regno]);
959             }
960
961           else if ((insn & 0xffd0) == 0xf880    /* str{bh}.w Rt,[Rn,#imm] */
962                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
963             /* Ignore stores of argument registers to the stack.  */
964             ;
965
966           else if ((insn & 0xffd0) == 0xf800    /* str{bh} Rt,[Rn,#+/-imm] */
967                    && (inst2 & 0x0d00) == 0x0c00
968                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
969             /* Ignore stores of argument registers to the stack.  */
970             ;
971
972           else if ((insn & 0xffd0) == 0xe890    /* ldmia Rn[!],
973                                                    { registers } */
974                    && (inst2 & 0x8000) == 0x0000
975                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
976             /* Ignore block loads from the stack, potentially copying
977                parameters from memory.  */
978             ;
979
980           else if ((insn & 0xffb0) == 0xe950    /* ldrd Rt, Rt2,
981                                                    [Rn, #+/-imm] */
982                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
983             /* Similarly ignore dual loads from the stack.  */
984             ;
985
986           else if ((insn & 0xfff0) == 0xf850    /* ldr Rt,[Rn,#+/-imm] */
987                    && (inst2 & 0x0d00) == 0x0c00
988                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
989             /* Similarly ignore single loads from the stack.  */
990             ;
991
992           else if ((insn & 0xfff0) == 0xf8d0    /* ldr.w Rt,[Rn,#imm] */
993                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
994             /* Similarly ignore single loads from the stack.  */
995             ;
996
997           else if ((insn & 0xfbf0) == 0xf100    /* add.w Rd, Rn, #imm */
998                    && (inst2 & 0x8000) == 0x0000)
999             {
1000               unsigned int imm = ((bits (insn, 10, 10) << 11)
1001                                   | (bits (inst2, 12, 14) << 8)
1002                                   | bits (inst2, 0, 7));
1003
1004               regs[bits (inst2, 8, 11)]
1005                 = pv_add_constant (regs[bits (insn, 0, 3)],
1006                                    thumb_expand_immediate (imm));
1007             }
1008
1009           else if ((insn & 0xfbf0) == 0xf200    /* addw Rd, Rn, #imm */
1010                    && (inst2 & 0x8000) == 0x0000)
1011             {
1012               unsigned int imm = ((bits (insn, 10, 10) << 11)
1013                                   | (bits (inst2, 12, 14) << 8)
1014                                   | bits (inst2, 0, 7));
1015
1016               regs[bits (inst2, 8, 11)]
1017                 = pv_add_constant (regs[bits (insn, 0, 3)], imm);
1018             }
1019
1020           else if ((insn & 0xfbf0) == 0xf1a0    /* sub.w Rd, Rn, #imm */
1021                    && (inst2 & 0x8000) == 0x0000)
1022             {
1023               unsigned int imm = ((bits (insn, 10, 10) << 11)
1024                                   | (bits (inst2, 12, 14) << 8)
1025                                   | bits (inst2, 0, 7));
1026
1027               regs[bits (inst2, 8, 11)]
1028                 = pv_add_constant (regs[bits (insn, 0, 3)],
1029                                    - (CORE_ADDR) thumb_expand_immediate (imm));
1030             }
1031
1032           else if ((insn & 0xfbf0) == 0xf2a0    /* subw Rd, Rn, #imm */
1033                    && (inst2 & 0x8000) == 0x0000)
1034             {
1035               unsigned int imm = ((bits (insn, 10, 10) << 11)
1036                                   | (bits (inst2, 12, 14) << 8)
1037                                   | bits (inst2, 0, 7));
1038
1039               regs[bits (inst2, 8, 11)]
1040                 = pv_add_constant (regs[bits (insn, 0, 3)], - (CORE_ADDR) imm);
1041             }
1042
1043           else if ((insn & 0xfbff) == 0xf04f)   /* mov.w Rd, #const */
1044             {
1045               unsigned int imm = ((bits (insn, 10, 10) << 11)
1046                                   | (bits (inst2, 12, 14) << 8)
1047                                   | bits (inst2, 0, 7));
1048
1049               regs[bits (inst2, 8, 11)]
1050                 = pv_constant (thumb_expand_immediate (imm));
1051             }
1052
1053           else if ((insn & 0xfbf0) == 0xf240)   /* movw Rd, #const */
1054             {
1055               unsigned int imm
1056                 = EXTRACT_MOVW_MOVT_IMM_T (insn, inst2);
1057
1058               regs[bits (inst2, 8, 11)] = pv_constant (imm);
1059             }
1060
1061           else if (insn == 0xea5f               /* mov.w Rd,Rm */
1062                    && (inst2 & 0xf0f0) == 0)
1063             {
1064               int dst_reg = (inst2 & 0x0f00) >> 8;
1065               int src_reg = inst2 & 0xf;
1066               regs[dst_reg] = regs[src_reg];
1067             }
1068
1069           else if ((insn & 0xff7f) == 0xf85f)   /* ldr.w Rt,<label> */
1070             {
1071               /* Constant pool loads.  */
1072               unsigned int constant;
1073               CORE_ADDR loc;
1074
1075               offset = bits (inst2, 0, 11);
1076               if (insn & 0x0080)
1077                 loc = start + 4 + offset;
1078               else
1079                 loc = start + 4 - offset;
1080
1081               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1082               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1083             }
1084
1085           else if ((insn & 0xff7f) == 0xe95f)   /* ldrd Rt,Rt2,<label> */
1086             {
1087               /* Constant pool loads.  */
1088               unsigned int constant;
1089               CORE_ADDR loc;
1090
1091               offset = bits (inst2, 0, 7) << 2;
1092               if (insn & 0x0080)
1093                 loc = start + 4 + offset;
1094               else
1095                 loc = start + 4 - offset;
1096
1097               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1098               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1099
1100               constant = read_memory_unsigned_integer (loc + 4, 4, byte_order);
1101               regs[bits (inst2, 8, 11)] = pv_constant (constant);
1102             }
1103
1104           else if (thumb2_instruction_changes_pc (insn, inst2))
1105             {
1106               /* Don't scan past anything that might change control flow.  */
1107               break;
1108             }
1109           else
1110             {
1111               /* The optimizer might shove anything into the prologue,
1112                  so we just skip what we don't recognize.  */
1113               unrecognized_pc = start;
1114             }
1115
1116           start += 2;
1117         }
1118       else if (thumb_instruction_changes_pc (insn))
1119         {
1120           /* Don't scan past anything that might change control flow.  */
1121           break;
1122         }
1123       else
1124         {
1125           /* The optimizer might shove anything into the prologue,
1126              so we just skip what we don't recognize.  */
1127           unrecognized_pc = start;
1128         }
1129
1130       start += 2;
1131     }
1132
1133   if (arm_debug)
1134     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1135                         paddress (gdbarch, start));
1136
1137   if (unrecognized_pc == 0)
1138     unrecognized_pc = start;
1139
1140   if (cache == NULL)
1141     {
1142       do_cleanups (back_to);
1143       return unrecognized_pc;
1144     }
1145
1146   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1147     {
1148       /* Frame pointer is fp.  Frame size is constant.  */
1149       cache->framereg = ARM_FP_REGNUM;
1150       cache->framesize = -regs[ARM_FP_REGNUM].k;
1151     }
1152   else if (pv_is_register (regs[THUMB_FP_REGNUM], ARM_SP_REGNUM))
1153     {
1154       /* Frame pointer is r7.  Frame size is constant.  */
1155       cache->framereg = THUMB_FP_REGNUM;
1156       cache->framesize = -regs[THUMB_FP_REGNUM].k;
1157     }
1158   else
1159     {
1160       /* Try the stack pointer... this is a bit desperate.  */
1161       cache->framereg = ARM_SP_REGNUM;
1162       cache->framesize = -regs[ARM_SP_REGNUM].k;
1163     }
1164
1165   for (i = 0; i < 16; i++)
1166     if (pv_area_find_reg (stack, gdbarch, i, &offset))
1167       cache->saved_regs[i].addr = offset;
1168
1169   do_cleanups (back_to);
1170   return unrecognized_pc;
1171 }
1172
1173
1174 /* Try to analyze the instructions starting from PC, which load symbol
1175    __stack_chk_guard.  Return the address of instruction after loading this
1176    symbol, set the dest register number to *BASEREG, and set the size of
1177    instructions for loading symbol in OFFSET.  Return 0 if instructions are
1178    not recognized.  */
1179
1180 static CORE_ADDR
1181 arm_analyze_load_stack_chk_guard(CORE_ADDR pc, struct gdbarch *gdbarch,
1182                                  unsigned int *destreg, int *offset)
1183 {
1184   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1185   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1186   unsigned int low, high, address;
1187
1188   address = 0;
1189   if (is_thumb)
1190     {
1191       unsigned short insn1
1192         = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
1193
1194       if ((insn1 & 0xf800) == 0x4800) /* ldr Rd, #immed */
1195         {
1196           *destreg = bits (insn1, 8, 10);
1197           *offset = 2;
1198           address = bits (insn1, 0, 7);
1199         }
1200       else if ((insn1 & 0xfbf0) == 0xf240) /* movw Rd, #const */
1201         {
1202           unsigned short insn2
1203             = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
1204
1205           low = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1206
1207           insn1
1208             = read_memory_unsigned_integer (pc + 4, 2, byte_order_for_code);
1209           insn2
1210             = read_memory_unsigned_integer (pc + 6, 2, byte_order_for_code);
1211
1212           /* movt Rd, #const */
1213           if ((insn1 & 0xfbc0) == 0xf2c0)
1214             {
1215               high = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1216               *destreg = bits (insn2, 8, 11);
1217               *offset = 8;
1218               address = (high << 16 | low);
1219             }
1220         }
1221     }
1222   else
1223     {
1224       unsigned int insn
1225         = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
1226
1227       if ((insn & 0x0e5f0000) == 0x041f0000) /* ldr Rd, #immed */
1228         {
1229           address = bits (insn, 0, 11);
1230           *destreg = bits (insn, 12, 15);
1231           *offset = 4;
1232         }
1233       else if ((insn & 0x0ff00000) == 0x03000000) /* movw Rd, #const */
1234         {
1235           low = EXTRACT_MOVW_MOVT_IMM_A (insn);
1236
1237           insn
1238             = read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code);
1239
1240           if ((insn & 0x0ff00000) == 0x03400000) /* movt Rd, #const */
1241             {
1242               high = EXTRACT_MOVW_MOVT_IMM_A (insn);
1243               *destreg = bits (insn, 12, 15);
1244               *offset = 8;
1245               address = (high << 16 | low);
1246             }
1247         }
1248     }
1249
1250   return address;
1251 }
1252
1253 /* Try to skip a sequence of instructions used for stack protector.  If PC
1254    points to the first instruction of this sequence, return the address of
1255    first instruction after this sequence, otherwise, return original PC.
1256
1257    On arm, this sequence of instructions is composed of mainly three steps,
1258      Step 1: load symbol __stack_chk_guard,
1259      Step 2: load from address of __stack_chk_guard,
1260      Step 3: store it to somewhere else.
1261
1262    Usually, instructions on step 2 and step 3 are the same on various ARM
1263    architectures.  On step 2, it is one instruction 'ldr Rx, [Rn, #0]', and
1264    on step 3, it is also one instruction 'str Rx, [r7, #immd]'.  However,
1265    instructions in step 1 vary from different ARM architectures.  On ARMv7,
1266    they are,
1267
1268         movw    Rn, #:lower16:__stack_chk_guard
1269         movt    Rn, #:upper16:__stack_chk_guard
1270
1271    On ARMv5t, it is,
1272
1273         ldr     Rn, .Label
1274         ....
1275         .Lable:
1276         .word   __stack_chk_guard
1277
1278    Since ldr/str is a very popular instruction, we can't use them as
1279    'fingerprint' or 'signature' of stack protector sequence.  Here we choose
1280    sequence {movw/movt, ldr}/ldr/str plus symbol __stack_chk_guard, if not
1281    stripped, as the 'fingerprint' of a stack protector cdoe sequence.  */
1282
1283 static CORE_ADDR
1284 arm_skip_stack_protector(CORE_ADDR pc, struct gdbarch *gdbarch)
1285 {
1286   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1287   unsigned int basereg;
1288   struct bound_minimal_symbol stack_chk_guard;
1289   int offset;
1290   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1291   CORE_ADDR addr;
1292
1293   /* Try to parse the instructions in Step 1.  */
1294   addr = arm_analyze_load_stack_chk_guard (pc, gdbarch,
1295                                            &basereg, &offset);
1296   if (!addr)
1297     return pc;
1298
1299   stack_chk_guard = lookup_minimal_symbol_by_pc (addr);
1300   /* If name of symbol doesn't start with '__stack_chk_guard', this
1301      instruction sequence is not for stack protector.  If symbol is
1302      removed, we conservatively think this sequence is for stack protector.  */
1303   if (stack_chk_guard.minsym
1304       && strncmp (MSYMBOL_LINKAGE_NAME (stack_chk_guard.minsym),
1305                   "__stack_chk_guard",
1306                   strlen ("__stack_chk_guard")) != 0)
1307    return pc;
1308
1309   if (is_thumb)
1310     {
1311       unsigned int destreg;
1312       unsigned short insn
1313         = read_memory_unsigned_integer (pc + offset, 2, byte_order_for_code);
1314
1315       /* Step 2: ldr Rd, [Rn, #immed], encoding T1.  */
1316       if ((insn & 0xf800) != 0x6800)
1317         return pc;
1318       if (bits (insn, 3, 5) != basereg)
1319         return pc;
1320       destreg = bits (insn, 0, 2);
1321
1322       insn = read_memory_unsigned_integer (pc + offset + 2, 2,
1323                                            byte_order_for_code);
1324       /* Step 3: str Rd, [Rn, #immed], encoding T1.  */
1325       if ((insn & 0xf800) != 0x6000)
1326         return pc;
1327       if (destreg != bits (insn, 0, 2))
1328         return pc;
1329     }
1330   else
1331     {
1332       unsigned int destreg;
1333       unsigned int insn
1334         = read_memory_unsigned_integer (pc + offset, 4, byte_order_for_code);
1335
1336       /* Step 2: ldr Rd, [Rn, #immed], encoding A1.  */
1337       if ((insn & 0x0e500000) != 0x04100000)
1338         return pc;
1339       if (bits (insn, 16, 19) != basereg)
1340         return pc;
1341       destreg = bits (insn, 12, 15);
1342       /* Step 3: str Rd, [Rn, #immed], encoding A1.  */
1343       insn = read_memory_unsigned_integer (pc + offset + 4,
1344                                            4, byte_order_for_code);
1345       if ((insn & 0x0e500000) != 0x04000000)
1346         return pc;
1347       if (bits (insn, 12, 15) != destreg)
1348         return pc;
1349     }
1350   /* The size of total two instructions ldr/str is 4 on Thumb-2, while 8
1351      on arm.  */
1352   if (is_thumb)
1353     return pc + offset + 4;
1354   else
1355     return pc + offset + 8;
1356 }
1357
1358 /* Advance the PC across any function entry prologue instructions to
1359    reach some "real" code.
1360
1361    The APCS (ARM Procedure Call Standard) defines the following
1362    prologue:
1363
1364    mov          ip, sp
1365    [stmfd       sp!, {a1,a2,a3,a4}]
1366    stmfd        sp!, {...,fp,ip,lr,pc}
1367    [stfe        f7, [sp, #-12]!]
1368    [stfe        f6, [sp, #-12]!]
1369    [stfe        f5, [sp, #-12]!]
1370    [stfe        f4, [sp, #-12]!]
1371    sub fp, ip, #nn @@ nn == 20 or 4 depending on second insn.  */
1372
1373 static CORE_ADDR
1374 arm_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1375 {
1376   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1377   unsigned long inst;
1378   CORE_ADDR skip_pc;
1379   CORE_ADDR func_addr, limit_pc;
1380
1381   /* See if we can determine the end of the prologue via the symbol table.
1382      If so, then return either PC, or the PC after the prologue, whichever
1383      is greater.  */
1384   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1385     {
1386       CORE_ADDR post_prologue_pc
1387         = skip_prologue_using_sal (gdbarch, func_addr);
1388       struct symtab *s = find_pc_symtab (func_addr);
1389
1390       if (post_prologue_pc)
1391         post_prologue_pc
1392           = arm_skip_stack_protector (post_prologue_pc, gdbarch);
1393
1394
1395       /* GCC always emits a line note before the prologue and another
1396          one after, even if the two are at the same address or on the
1397          same line.  Take advantage of this so that we do not need to
1398          know every instruction that might appear in the prologue.  We
1399          will have producer information for most binaries; if it is
1400          missing (e.g. for -gstabs), assuming the GNU tools.  */
1401       if (post_prologue_pc
1402           && (s == NULL
1403               || s->producer == NULL
1404               || strncmp (s->producer, "GNU ", sizeof ("GNU ") - 1) == 0 
1405               || strncmp (s->producer, "clang ", sizeof ("clang ") - 1) == 0))
1406         return post_prologue_pc;
1407
1408       if (post_prologue_pc != 0)
1409         {
1410           CORE_ADDR analyzed_limit;
1411
1412           /* For non-GCC compilers, make sure the entire line is an
1413              acceptable prologue; GDB will round this function's
1414              return value up to the end of the following line so we
1415              can not skip just part of a line (and we do not want to).
1416
1417              RealView does not treat the prologue specially, but does
1418              associate prologue code with the opening brace; so this
1419              lets us skip the first line if we think it is the opening
1420              brace.  */
1421           if (arm_pc_is_thumb (gdbarch, func_addr))
1422             analyzed_limit = thumb_analyze_prologue (gdbarch, func_addr,
1423                                                      post_prologue_pc, NULL);
1424           else
1425             analyzed_limit = arm_analyze_prologue (gdbarch, func_addr,
1426                                                    post_prologue_pc, NULL);
1427
1428           if (analyzed_limit != post_prologue_pc)
1429             return func_addr;
1430
1431           return post_prologue_pc;
1432         }
1433     }
1434
1435   /* Can't determine prologue from the symbol table, need to examine
1436      instructions.  */
1437
1438   /* Find an upper limit on the function prologue using the debug
1439      information.  If the debug information could not be used to provide
1440      that bound, then use an arbitrary large number as the upper bound.  */
1441   /* Like arm_scan_prologue, stop no later than pc + 64.  */
1442   limit_pc = skip_prologue_using_sal (gdbarch, pc);
1443   if (limit_pc == 0)
1444     limit_pc = pc + 64;          /* Magic.  */
1445
1446
1447   /* Check if this is Thumb code.  */
1448   if (arm_pc_is_thumb (gdbarch, pc))
1449     return thumb_analyze_prologue (gdbarch, pc, limit_pc, NULL);
1450
1451   for (skip_pc = pc; skip_pc < limit_pc; skip_pc += 4)
1452     {
1453       inst = read_memory_unsigned_integer (skip_pc, 4, byte_order_for_code);
1454
1455       /* "mov ip, sp" is no longer a required part of the prologue.  */
1456       if (inst == 0xe1a0c00d)                   /* mov ip, sp */
1457         continue;
1458
1459       if ((inst & 0xfffff000) == 0xe28dc000)    /* add ip, sp #n */
1460         continue;
1461
1462       if ((inst & 0xfffff000) == 0xe24dc000)    /* sub ip, sp #n */
1463         continue;
1464
1465       /* Some prologues begin with "str lr, [sp, #-4]!".  */
1466       if (inst == 0xe52de004)                   /* str lr, [sp, #-4]! */
1467         continue;
1468
1469       if ((inst & 0xfffffff0) == 0xe92d0000)    /* stmfd sp!,{a1,a2,a3,a4} */
1470         continue;
1471
1472       if ((inst & 0xfffff800) == 0xe92dd800)    /* stmfd sp!,{fp,ip,lr,pc} */
1473         continue;
1474
1475       /* Any insns after this point may float into the code, if it makes
1476          for better instruction scheduling, so we skip them only if we
1477          find them, but still consider the function to be frame-ful.  */
1478
1479       /* We may have either one sfmfd instruction here, or several stfe
1480          insns, depending on the version of floating point code we
1481          support.  */
1482       if ((inst & 0xffbf0fff) == 0xec2d0200)    /* sfmfd fn, <cnt>, [sp]! */
1483         continue;
1484
1485       if ((inst & 0xffff8fff) == 0xed6d0103)    /* stfe fn, [sp, #-12]! */
1486         continue;
1487
1488       if ((inst & 0xfffff000) == 0xe24cb000)    /* sub fp, ip, #nn */
1489         continue;
1490
1491       if ((inst & 0xfffff000) == 0xe24dd000)    /* sub sp, sp, #nn */
1492         continue;
1493
1494       if ((inst & 0xffffc000) == 0xe54b0000     /* strb r(0123),[r11,#-nn] */
1495           || (inst & 0xffffc0f0) == 0xe14b00b0  /* strh r(0123),[r11,#-nn] */
1496           || (inst & 0xffffc000) == 0xe50b0000) /* str  r(0123),[r11,#-nn] */
1497         continue;
1498
1499       if ((inst & 0xffffc000) == 0xe5cd0000     /* strb r(0123),[sp,#nn] */
1500           || (inst & 0xffffc0f0) == 0xe1cd00b0  /* strh r(0123),[sp,#nn] */
1501           || (inst & 0xffffc000) == 0xe58d0000) /* str  r(0123),[sp,#nn] */
1502         continue;
1503
1504       /* Un-recognized instruction; stop scanning.  */
1505       break;
1506     }
1507
1508   return skip_pc;               /* End of prologue.  */
1509 }
1510
1511 /* *INDENT-OFF* */
1512 /* Function: thumb_scan_prologue (helper function for arm_scan_prologue)
1513    This function decodes a Thumb function prologue to determine:
1514      1) the size of the stack frame
1515      2) which registers are saved on it
1516      3) the offsets of saved regs
1517      4) the offset from the stack pointer to the frame pointer
1518
1519    A typical Thumb function prologue would create this stack frame
1520    (offsets relative to FP)
1521      old SP ->  24  stack parameters
1522                 20  LR
1523                 16  R7
1524      R7 ->       0  local variables (16 bytes)
1525      SP ->     -12  additional stack space (12 bytes)
1526    The frame size would thus be 36 bytes, and the frame offset would be
1527    12 bytes.  The frame register is R7.
1528    
1529    The comments for thumb_skip_prolog() describe the algorithm we use
1530    to detect the end of the prolog.  */
1531 /* *INDENT-ON* */
1532
1533 static void
1534 thumb_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR prev_pc,
1535                      CORE_ADDR block_addr, struct arm_prologue_cache *cache)
1536 {
1537   CORE_ADDR prologue_start;
1538   CORE_ADDR prologue_end;
1539
1540   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1541                                 &prologue_end))
1542     {
1543       /* See comment in arm_scan_prologue for an explanation of
1544          this heuristics.  */
1545       if (prologue_end > prologue_start + 64)
1546         {
1547           prologue_end = prologue_start + 64;
1548         }
1549     }
1550   else
1551     /* We're in the boondocks: we have no idea where the start of the
1552        function is.  */
1553     return;
1554
1555   prologue_end = min (prologue_end, prev_pc);
1556
1557   thumb_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
1558 }
1559
1560 /* Return 1 if THIS_INSTR might change control flow, 0 otherwise.  */
1561
1562 static int
1563 arm_instruction_changes_pc (uint32_t this_instr)
1564 {
1565   if (bits (this_instr, 28, 31) == INST_NV)
1566     /* Unconditional instructions.  */
1567     switch (bits (this_instr, 24, 27))
1568       {
1569       case 0xa:
1570       case 0xb:
1571         /* Branch with Link and change to Thumb.  */
1572         return 1;
1573       case 0xc:
1574       case 0xd:
1575       case 0xe:
1576         /* Coprocessor register transfer.  */
1577         if (bits (this_instr, 12, 15) == 15)
1578           error (_("Invalid update to pc in instruction"));
1579         return 0;
1580       default:
1581         return 0;
1582       }
1583   else
1584     switch (bits (this_instr, 25, 27))
1585       {
1586       case 0x0:
1587         if (bits (this_instr, 23, 24) == 2 && bit (this_instr, 20) == 0)
1588           {
1589             /* Multiplies and extra load/stores.  */
1590             if (bit (this_instr, 4) == 1 && bit (this_instr, 7) == 1)
1591               /* Neither multiplies nor extension load/stores are allowed
1592                  to modify PC.  */
1593               return 0;
1594
1595             /* Otherwise, miscellaneous instructions.  */
1596
1597             /* BX <reg>, BXJ <reg>, BLX <reg> */
1598             if (bits (this_instr, 4, 27) == 0x12fff1
1599                 || bits (this_instr, 4, 27) == 0x12fff2
1600                 || bits (this_instr, 4, 27) == 0x12fff3)
1601               return 1;
1602
1603             /* Other miscellaneous instructions are unpredictable if they
1604                modify PC.  */
1605             return 0;
1606           }
1607         /* Data processing instruction.  Fall through.  */
1608
1609       case 0x1:
1610         if (bits (this_instr, 12, 15) == 15)
1611           return 1;
1612         else
1613           return 0;
1614
1615       case 0x2:
1616       case 0x3:
1617         /* Media instructions and architecturally undefined instructions.  */
1618         if (bits (this_instr, 25, 27) == 3 && bit (this_instr, 4) == 1)
1619           return 0;
1620
1621         /* Stores.  */
1622         if (bit (this_instr, 20) == 0)
1623           return 0;
1624
1625         /* Loads.  */
1626         if (bits (this_instr, 12, 15) == ARM_PC_REGNUM)
1627           return 1;
1628         else
1629           return 0;
1630
1631       case 0x4:
1632         /* Load/store multiple.  */
1633         if (bit (this_instr, 20) == 1 && bit (this_instr, 15) == 1)
1634           return 1;
1635         else
1636           return 0;
1637
1638       case 0x5:
1639         /* Branch and branch with link.  */
1640         return 1;
1641
1642       case 0x6:
1643       case 0x7:
1644         /* Coprocessor transfers or SWIs can not affect PC.  */
1645         return 0;
1646
1647       default:
1648         internal_error (__FILE__, __LINE__, _("bad value in switch"));
1649       }
1650 }
1651
1652 /* Analyze an ARM mode prologue starting at PROLOGUE_START and
1653    continuing no further than PROLOGUE_END.  If CACHE is non-NULL,
1654    fill it in.  Return the first address not recognized as a prologue
1655    instruction.
1656
1657    We recognize all the instructions typically found in ARM prologues,
1658    plus harmless instructions which can be skipped (either for analysis
1659    purposes, or a more restrictive set that can be skipped when finding
1660    the end of the prologue).  */
1661
1662 static CORE_ADDR
1663 arm_analyze_prologue (struct gdbarch *gdbarch,
1664                       CORE_ADDR prologue_start, CORE_ADDR prologue_end,
1665                       struct arm_prologue_cache *cache)
1666 {
1667   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1668   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1669   int regno;
1670   CORE_ADDR offset, current_pc;
1671   pv_t regs[ARM_FPS_REGNUM];
1672   struct pv_area *stack;
1673   struct cleanup *back_to;
1674   int framereg, framesize;
1675   CORE_ADDR unrecognized_pc = 0;
1676
1677   /* Search the prologue looking for instructions that set up the
1678      frame pointer, adjust the stack pointer, and save registers.
1679
1680      Be careful, however, and if it doesn't look like a prologue,
1681      don't try to scan it.  If, for instance, a frameless function
1682      begins with stmfd sp!, then we will tell ourselves there is
1683      a frame, which will confuse stack traceback, as well as "finish" 
1684      and other operations that rely on a knowledge of the stack
1685      traceback.  */
1686
1687   for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1688     regs[regno] = pv_register (regno, 0);
1689   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1690   back_to = make_cleanup_free_pv_area (stack);
1691
1692   for (current_pc = prologue_start;
1693        current_pc < prologue_end;
1694        current_pc += 4)
1695     {
1696       unsigned int insn
1697         = read_memory_unsigned_integer (current_pc, 4, byte_order_for_code);
1698
1699       if (insn == 0xe1a0c00d)           /* mov ip, sp */
1700         {
1701           regs[ARM_IP_REGNUM] = regs[ARM_SP_REGNUM];
1702           continue;
1703         }
1704       else if ((insn & 0xfff00000) == 0xe2800000        /* add Rd, Rn, #n */
1705                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1706         {
1707           unsigned imm = insn & 0xff;                   /* immediate value */
1708           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1709           int rd = bits (insn, 12, 15);
1710           imm = (imm >> rot) | (imm << (32 - rot));
1711           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], imm);
1712           continue;
1713         }
1714       else if ((insn & 0xfff00000) == 0xe2400000        /* sub Rd, Rn, #n */
1715                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1716         {
1717           unsigned imm = insn & 0xff;                   /* immediate value */
1718           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1719           int rd = bits (insn, 12, 15);
1720           imm = (imm >> rot) | (imm << (32 - rot));
1721           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], -imm);
1722           continue;
1723         }
1724       else if ((insn & 0xffff0fff) == 0xe52d0004)       /* str Rd,
1725                                                            [sp, #-4]! */
1726         {
1727           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1728             break;
1729           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1730           pv_area_store (stack, regs[ARM_SP_REGNUM], 4,
1731                          regs[bits (insn, 12, 15)]);
1732           continue;
1733         }
1734       else if ((insn & 0xffff0000) == 0xe92d0000)
1735         /* stmfd sp!, {..., fp, ip, lr, pc}
1736            or
1737            stmfd sp!, {a1, a2, a3, a4}  */
1738         {
1739           int mask = insn & 0xffff;
1740
1741           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1742             break;
1743
1744           /* Calculate offsets of saved registers.  */
1745           for (regno = ARM_PC_REGNUM; regno >= 0; regno--)
1746             if (mask & (1 << regno))
1747               {
1748                 regs[ARM_SP_REGNUM]
1749                   = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1750                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
1751               }
1752         }
1753       else if ((insn & 0xffff0000) == 0xe54b0000        /* strb rx,[r11,#-n] */
1754                || (insn & 0xffff00f0) == 0xe14b00b0     /* strh rx,[r11,#-n] */
1755                || (insn & 0xffffc000) == 0xe50b0000)    /* str  rx,[r11,#-n] */
1756         {
1757           /* No need to add this to saved_regs -- it's just an arg reg.  */
1758           continue;
1759         }
1760       else if ((insn & 0xffff0000) == 0xe5cd0000        /* strb rx,[sp,#n] */
1761                || (insn & 0xffff00f0) == 0xe1cd00b0     /* strh rx,[sp,#n] */
1762                || (insn & 0xffffc000) == 0xe58d0000)    /* str  rx,[sp,#n] */
1763         {
1764           /* No need to add this to saved_regs -- it's just an arg reg.  */
1765           continue;
1766         }
1767       else if ((insn & 0xfff00000) == 0xe8800000        /* stm Rn,
1768                                                            { registers } */
1769                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1770         {
1771           /* No need to add this to saved_regs -- it's just arg regs.  */
1772           continue;
1773         }
1774       else if ((insn & 0xfffff000) == 0xe24cb000)       /* sub fp, ip #n */
1775         {
1776           unsigned imm = insn & 0xff;                   /* immediate value */
1777           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1778           imm = (imm >> rot) | (imm << (32 - rot));
1779           regs[ARM_FP_REGNUM] = pv_add_constant (regs[ARM_IP_REGNUM], -imm);
1780         }
1781       else if ((insn & 0xfffff000) == 0xe24dd000)       /* sub sp, sp #n */
1782         {
1783           unsigned imm = insn & 0xff;                   /* immediate value */
1784           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1785           imm = (imm >> rot) | (imm << (32 - rot));
1786           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -imm);
1787         }
1788       else if ((insn & 0xffff7fff) == 0xed6d0103        /* stfe f?,
1789                                                            [sp, -#c]! */
1790                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1791         {
1792           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1793             break;
1794
1795           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1796           regno = ARM_F0_REGNUM + ((insn >> 12) & 0x07);
1797           pv_area_store (stack, regs[ARM_SP_REGNUM], 12, regs[regno]);
1798         }
1799       else if ((insn & 0xffbf0fff) == 0xec2d0200        /* sfmfd f0, 4,
1800                                                            [sp!] */
1801                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1802         {
1803           int n_saved_fp_regs;
1804           unsigned int fp_start_reg, fp_bound_reg;
1805
1806           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1807             break;
1808
1809           if ((insn & 0x800) == 0x800)          /* N0 is set */
1810             {
1811               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1812                 n_saved_fp_regs = 3;
1813               else
1814                 n_saved_fp_regs = 1;
1815             }
1816           else
1817             {
1818               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1819                 n_saved_fp_regs = 2;
1820               else
1821                 n_saved_fp_regs = 4;
1822             }
1823
1824           fp_start_reg = ARM_F0_REGNUM + ((insn >> 12) & 0x7);
1825           fp_bound_reg = fp_start_reg + n_saved_fp_regs;
1826           for (; fp_start_reg < fp_bound_reg; fp_start_reg++)
1827             {
1828               regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1829               pv_area_store (stack, regs[ARM_SP_REGNUM], 12,
1830                              regs[fp_start_reg++]);
1831             }
1832         }
1833       else if ((insn & 0xff000000) == 0xeb000000 && cache == NULL) /* bl */
1834         {
1835           /* Allow some special function calls when skipping the
1836              prologue; GCC generates these before storing arguments to
1837              the stack.  */
1838           CORE_ADDR dest = BranchDest (current_pc, insn);
1839
1840           if (skip_prologue_function (gdbarch, dest, 0))
1841             continue;
1842           else
1843             break;
1844         }
1845       else if ((insn & 0xf0000000) != 0xe0000000)
1846         break;                  /* Condition not true, exit early.  */
1847       else if (arm_instruction_changes_pc (insn))
1848         /* Don't scan past anything that might change control flow.  */
1849         break;
1850       else if ((insn & 0xfe500000) == 0xe8100000        /* ldm */
1851                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1852         /* Ignore block loads from the stack, potentially copying
1853            parameters from memory.  */
1854         continue;
1855       else if ((insn & 0xfc500000) == 0xe4100000
1856                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1857         /* Similarly ignore single loads from the stack.  */
1858         continue;
1859       else if ((insn & 0xffff0ff0) == 0xe1a00000)
1860         /* MOV Rd, Rm.  Skip register copies, i.e. saves to another
1861            register instead of the stack.  */
1862         continue;
1863       else
1864         {
1865           /* The optimizer might shove anything into the prologue,
1866              so we just skip what we don't recognize.  */
1867           unrecognized_pc = current_pc;
1868           continue;
1869         }
1870     }
1871
1872   if (unrecognized_pc == 0)
1873     unrecognized_pc = current_pc;
1874
1875   /* The frame size is just the distance from the frame register
1876      to the original stack pointer.  */
1877   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1878     {
1879       /* Frame pointer is fp.  */
1880       framereg = ARM_FP_REGNUM;
1881       framesize = -regs[ARM_FP_REGNUM].k;
1882     }
1883   else
1884     {
1885       /* Try the stack pointer... this is a bit desperate.  */
1886       framereg = ARM_SP_REGNUM;
1887       framesize = -regs[ARM_SP_REGNUM].k;
1888     }
1889
1890   if (cache)
1891     {
1892       cache->framereg = framereg;
1893       cache->framesize = framesize;
1894
1895       for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1896         if (pv_area_find_reg (stack, gdbarch, regno, &offset))
1897           cache->saved_regs[regno].addr = offset;
1898     }
1899
1900   if (arm_debug)
1901     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1902                         paddress (gdbarch, unrecognized_pc));
1903
1904   do_cleanups (back_to);
1905   return unrecognized_pc;
1906 }
1907
1908 static void
1909 arm_scan_prologue (struct frame_info *this_frame,
1910                    struct arm_prologue_cache *cache)
1911 {
1912   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1913   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1914   int regno;
1915   CORE_ADDR prologue_start, prologue_end, current_pc;
1916   CORE_ADDR prev_pc = get_frame_pc (this_frame);
1917   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1918   pv_t regs[ARM_FPS_REGNUM];
1919   struct pv_area *stack;
1920   struct cleanup *back_to;
1921   CORE_ADDR offset;
1922
1923   /* Assume there is no frame until proven otherwise.  */
1924   cache->framereg = ARM_SP_REGNUM;
1925   cache->framesize = 0;
1926
1927   /* Check for Thumb prologue.  */
1928   if (arm_frame_is_thumb (this_frame))
1929     {
1930       thumb_scan_prologue (gdbarch, prev_pc, block_addr, cache);
1931       return;
1932     }
1933
1934   /* Find the function prologue.  If we can't find the function in
1935      the symbol table, peek in the stack frame to find the PC.  */
1936   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1937                                 &prologue_end))
1938     {
1939       /* One way to find the end of the prologue (which works well
1940          for unoptimized code) is to do the following:
1941
1942             struct symtab_and_line sal = find_pc_line (prologue_start, 0);
1943
1944             if (sal.line == 0)
1945               prologue_end = prev_pc;
1946             else if (sal.end < prologue_end)
1947               prologue_end = sal.end;
1948
1949          This mechanism is very accurate so long as the optimizer
1950          doesn't move any instructions from the function body into the
1951          prologue.  If this happens, sal.end will be the last
1952          instruction in the first hunk of prologue code just before
1953          the first instruction that the scheduler has moved from
1954          the body to the prologue.
1955
1956          In order to make sure that we scan all of the prologue
1957          instructions, we use a slightly less accurate mechanism which
1958          may scan more than necessary.  To help compensate for this
1959          lack of accuracy, the prologue scanning loop below contains
1960          several clauses which'll cause the loop to terminate early if
1961          an implausible prologue instruction is encountered.
1962
1963          The expression
1964
1965               prologue_start + 64
1966
1967          is a suitable endpoint since it accounts for the largest
1968          possible prologue plus up to five instructions inserted by
1969          the scheduler.  */
1970
1971       if (prologue_end > prologue_start + 64)
1972         {
1973           prologue_end = prologue_start + 64;   /* See above.  */
1974         }
1975     }
1976   else
1977     {
1978       /* We have no symbol information.  Our only option is to assume this
1979          function has a standard stack frame and the normal frame register.
1980          Then, we can find the value of our frame pointer on entrance to
1981          the callee (or at the present moment if this is the innermost frame).
1982          The value stored there should be the address of the stmfd + 8.  */
1983       CORE_ADDR frame_loc;
1984       LONGEST return_value;
1985
1986       frame_loc = get_frame_register_unsigned (this_frame, ARM_FP_REGNUM);
1987       if (!safe_read_memory_integer (frame_loc, 4, byte_order, &return_value))
1988         return;
1989       else
1990         {
1991           prologue_start = gdbarch_addr_bits_remove
1992                              (gdbarch, return_value) - 8;
1993           prologue_end = prologue_start + 64;   /* See above.  */
1994         }
1995     }
1996
1997   if (prev_pc < prologue_end)
1998     prologue_end = prev_pc;
1999
2000   arm_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
2001 }
2002
2003 static struct arm_prologue_cache *
2004 arm_make_prologue_cache (struct frame_info *this_frame)
2005 {
2006   int reg;
2007   struct arm_prologue_cache *cache;
2008   CORE_ADDR unwound_fp;
2009
2010   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2011   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2012
2013   arm_scan_prologue (this_frame, cache);
2014
2015   unwound_fp = get_frame_register_unsigned (this_frame, cache->framereg);
2016   if (unwound_fp == 0)
2017     return cache;
2018
2019   cache->prev_sp = unwound_fp + cache->framesize;
2020
2021   /* Calculate actual addresses of saved registers using offsets
2022      determined by arm_scan_prologue.  */
2023   for (reg = 0; reg < gdbarch_num_regs (get_frame_arch (this_frame)); reg++)
2024     if (trad_frame_addr_p (cache->saved_regs, reg))
2025       cache->saved_regs[reg].addr += cache->prev_sp;
2026
2027   return cache;
2028 }
2029
2030 /* Our frame ID for a normal frame is the current function's starting PC
2031    and the caller's SP when we were called.  */
2032
2033 static void
2034 arm_prologue_this_id (struct frame_info *this_frame,
2035                       void **this_cache,
2036                       struct frame_id *this_id)
2037 {
2038   struct arm_prologue_cache *cache;
2039   struct frame_id id;
2040   CORE_ADDR pc, func;
2041
2042   if (*this_cache == NULL)
2043     *this_cache = arm_make_prologue_cache (this_frame);
2044   cache = *this_cache;
2045
2046   /* This is meant to halt the backtrace at "_start".  */
2047   pc = get_frame_pc (this_frame);
2048   if (pc <= gdbarch_tdep (get_frame_arch (this_frame))->lowest_pc)
2049     return;
2050
2051   /* If we've hit a wall, stop.  */
2052   if (cache->prev_sp == 0)
2053     return;
2054
2055   /* Use function start address as part of the frame ID.  If we cannot
2056      identify the start address (due to missing symbol information),
2057      fall back to just using the current PC.  */
2058   func = get_frame_func (this_frame);
2059   if (!func)
2060     func = pc;
2061
2062   id = frame_id_build (cache->prev_sp, func);
2063   *this_id = id;
2064 }
2065
2066 static struct value *
2067 arm_prologue_prev_register (struct frame_info *this_frame,
2068                             void **this_cache,
2069                             int prev_regnum)
2070 {
2071   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2072   struct arm_prologue_cache *cache;
2073
2074   if (*this_cache == NULL)
2075     *this_cache = arm_make_prologue_cache (this_frame);
2076   cache = *this_cache;
2077
2078   /* If we are asked to unwind the PC, then we need to return the LR
2079      instead.  The prologue may save PC, but it will point into this
2080      frame's prologue, not the next frame's resume location.  Also
2081      strip the saved T bit.  A valid LR may have the low bit set, but
2082      a valid PC never does.  */
2083   if (prev_regnum == ARM_PC_REGNUM)
2084     {
2085       CORE_ADDR lr;
2086
2087       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2088       return frame_unwind_got_constant (this_frame, prev_regnum,
2089                                         arm_addr_bits_remove (gdbarch, lr));
2090     }
2091
2092   /* SP is generally not saved to the stack, but this frame is
2093      identified by the next frame's stack pointer at the time of the call.
2094      The value was already reconstructed into PREV_SP.  */
2095   if (prev_regnum == ARM_SP_REGNUM)
2096     return frame_unwind_got_constant (this_frame, prev_regnum, cache->prev_sp);
2097
2098   /* The CPSR may have been changed by the call instruction and by the
2099      called function.  The only bit we can reconstruct is the T bit,
2100      by checking the low bit of LR as of the call.  This is a reliable
2101      indicator of Thumb-ness except for some ARM v4T pre-interworking
2102      Thumb code, which could get away with a clear low bit as long as
2103      the called function did not use bx.  Guess that all other
2104      bits are unchanged; the condition flags are presumably lost,
2105      but the processor status is likely valid.  */
2106   if (prev_regnum == ARM_PS_REGNUM)
2107     {
2108       CORE_ADDR lr, cpsr;
2109       ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
2110
2111       cpsr = get_frame_register_unsigned (this_frame, prev_regnum);
2112       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2113       if (IS_THUMB_ADDR (lr))
2114         cpsr |= t_bit;
2115       else
2116         cpsr &= ~t_bit;
2117       return frame_unwind_got_constant (this_frame, prev_regnum, cpsr);
2118     }
2119
2120   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
2121                                        prev_regnum);
2122 }
2123
2124 struct frame_unwind arm_prologue_unwind = {
2125   NORMAL_FRAME,
2126   default_frame_unwind_stop_reason,
2127   arm_prologue_this_id,
2128   arm_prologue_prev_register,
2129   NULL,
2130   default_frame_sniffer
2131 };
2132
2133 /* Maintain a list of ARM exception table entries per objfile, similar to the
2134    list of mapping symbols.  We only cache entries for standard ARM-defined
2135    personality routines; the cache will contain only the frame unwinding
2136    instructions associated with the entry (not the descriptors).  */
2137
2138 static const struct objfile_data *arm_exidx_data_key;
2139
2140 struct arm_exidx_entry
2141 {
2142   bfd_vma addr;
2143   gdb_byte *entry;
2144 };
2145 typedef struct arm_exidx_entry arm_exidx_entry_s;
2146 DEF_VEC_O(arm_exidx_entry_s);
2147
2148 struct arm_exidx_data
2149 {
2150   VEC(arm_exidx_entry_s) **section_maps;
2151 };
2152
2153 static void
2154 arm_exidx_data_free (struct objfile *objfile, void *arg)
2155 {
2156   struct arm_exidx_data *data = arg;
2157   unsigned int i;
2158
2159   for (i = 0; i < objfile->obfd->section_count; i++)
2160     VEC_free (arm_exidx_entry_s, data->section_maps[i]);
2161 }
2162
2163 static inline int
2164 arm_compare_exidx_entries (const struct arm_exidx_entry *lhs,
2165                            const struct arm_exidx_entry *rhs)
2166 {
2167   return lhs->addr < rhs->addr;
2168 }
2169
2170 static struct obj_section *
2171 arm_obj_section_from_vma (struct objfile *objfile, bfd_vma vma)
2172 {
2173   struct obj_section *osect;
2174
2175   ALL_OBJFILE_OSECTIONS (objfile, osect)
2176     if (bfd_get_section_flags (objfile->obfd,
2177                                osect->the_bfd_section) & SEC_ALLOC)
2178       {
2179         bfd_vma start, size;
2180         start = bfd_get_section_vma (objfile->obfd, osect->the_bfd_section);
2181         size = bfd_get_section_size (osect->the_bfd_section);
2182
2183         if (start <= vma && vma < start + size)
2184           return osect;
2185       }
2186
2187   return NULL;
2188 }
2189
2190 /* Parse contents of exception table and exception index sections
2191    of OBJFILE, and fill in the exception table entry cache.
2192
2193    For each entry that refers to a standard ARM-defined personality
2194    routine, extract the frame unwinding instructions (from either
2195    the index or the table section).  The unwinding instructions
2196    are normalized by:
2197     - extracting them from the rest of the table data
2198     - converting to host endianness
2199     - appending the implicit 0xb0 ("Finish") code
2200
2201    The extracted and normalized instructions are stored for later
2202    retrieval by the arm_find_exidx_entry routine.  */
2203  
2204 static void
2205 arm_exidx_new_objfile (struct objfile *objfile)
2206 {
2207   struct cleanup *cleanups;
2208   struct arm_exidx_data *data;
2209   asection *exidx, *extab;
2210   bfd_vma exidx_vma = 0, extab_vma = 0;
2211   bfd_size_type exidx_size = 0, extab_size = 0;
2212   gdb_byte *exidx_data = NULL, *extab_data = NULL;
2213   LONGEST i;
2214
2215   /* If we've already touched this file, do nothing.  */
2216   if (!objfile || objfile_data (objfile, arm_exidx_data_key) != NULL)
2217     return;
2218   cleanups = make_cleanup (null_cleanup, NULL);
2219
2220   /* Read contents of exception table and index.  */
2221   exidx = bfd_get_section_by_name (objfile->obfd, ".ARM.exidx");
2222   if (exidx)
2223     {
2224       exidx_vma = bfd_section_vma (objfile->obfd, exidx);
2225       exidx_size = bfd_get_section_size (exidx);
2226       exidx_data = xmalloc (exidx_size);
2227       make_cleanup (xfree, exidx_data);
2228
2229       if (!bfd_get_section_contents (objfile->obfd, exidx,
2230                                      exidx_data, 0, exidx_size))
2231         {
2232           do_cleanups (cleanups);
2233           return;
2234         }
2235     }
2236
2237   extab = bfd_get_section_by_name (objfile->obfd, ".ARM.extab");
2238   if (extab)
2239     {
2240       extab_vma = bfd_section_vma (objfile->obfd, extab);
2241       extab_size = bfd_get_section_size (extab);
2242       extab_data = xmalloc (extab_size);
2243       make_cleanup (xfree, extab_data);
2244
2245       if (!bfd_get_section_contents (objfile->obfd, extab,
2246                                      extab_data, 0, extab_size))
2247         {
2248           do_cleanups (cleanups);
2249           return;
2250         }
2251     }
2252
2253   /* Allocate exception table data structure.  */
2254   data = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct arm_exidx_data);
2255   set_objfile_data (objfile, arm_exidx_data_key, data);
2256   data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
2257                                        objfile->obfd->section_count,
2258                                        VEC(arm_exidx_entry_s) *);
2259
2260   /* Fill in exception table.  */
2261   for (i = 0; i < exidx_size / 8; i++)
2262     {
2263       struct arm_exidx_entry new_exidx_entry;
2264       bfd_vma idx = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8);
2265       bfd_vma val = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8 + 4);
2266       bfd_vma addr = 0, word = 0;
2267       int n_bytes = 0, n_words = 0;
2268       struct obj_section *sec;
2269       gdb_byte *entry = NULL;
2270
2271       /* Extract address of start of function.  */
2272       idx = ((idx & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2273       idx += exidx_vma + i * 8;
2274
2275       /* Find section containing function and compute section offset.  */
2276       sec = arm_obj_section_from_vma (objfile, idx);
2277       if (sec == NULL)
2278         continue;
2279       idx -= bfd_get_section_vma (objfile->obfd, sec->the_bfd_section);
2280
2281       /* Determine address of exception table entry.  */
2282       if (val == 1)
2283         {
2284           /* EXIDX_CANTUNWIND -- no exception table entry present.  */
2285         }
2286       else if ((val & 0xff000000) == 0x80000000)
2287         {
2288           /* Exception table entry embedded in .ARM.exidx
2289              -- must be short form.  */
2290           word = val;
2291           n_bytes = 3;
2292         }
2293       else if (!(val & 0x80000000))
2294         {
2295           /* Exception table entry in .ARM.extab.  */
2296           addr = ((val & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2297           addr += exidx_vma + i * 8 + 4;
2298
2299           if (addr >= extab_vma && addr + 4 <= extab_vma + extab_size)
2300             {
2301               word = bfd_h_get_32 (objfile->obfd,
2302                                    extab_data + addr - extab_vma);
2303               addr += 4;
2304
2305               if ((word & 0xff000000) == 0x80000000)
2306                 {
2307                   /* Short form.  */
2308                   n_bytes = 3;
2309                 }
2310               else if ((word & 0xff000000) == 0x81000000
2311                        || (word & 0xff000000) == 0x82000000)
2312                 {
2313                   /* Long form.  */
2314                   n_bytes = 2;
2315                   n_words = ((word >> 16) & 0xff);
2316                 }
2317               else if (!(word & 0x80000000))
2318                 {
2319                   bfd_vma pers;
2320                   struct obj_section *pers_sec;
2321                   int gnu_personality = 0;
2322
2323                   /* Custom personality routine.  */
2324                   pers = ((word & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2325                   pers = UNMAKE_THUMB_ADDR (pers + addr - 4);
2326
2327                   /* Check whether we've got one of the variants of the
2328                      GNU personality routines.  */
2329                   pers_sec = arm_obj_section_from_vma (objfile, pers);
2330                   if (pers_sec)
2331                     {
2332                       static const char *personality[] = 
2333                         {
2334                           "__gcc_personality_v0",
2335                           "__gxx_personality_v0",
2336                           "__gcj_personality_v0",
2337                           "__gnu_objc_personality_v0",
2338                           NULL
2339                         };
2340
2341                       CORE_ADDR pc = pers + obj_section_offset (pers_sec);
2342                       int k;
2343
2344                       for (k = 0; personality[k]; k++)
2345                         if (lookup_minimal_symbol_by_pc_name
2346                               (pc, personality[k], objfile))
2347                           {
2348                             gnu_personality = 1;
2349                             break;
2350                           }
2351                     }
2352
2353                   /* If so, the next word contains a word count in the high
2354                      byte, followed by the same unwind instructions as the
2355                      pre-defined forms.  */
2356                   if (gnu_personality
2357                       && addr + 4 <= extab_vma + extab_size)
2358                     {
2359                       word = bfd_h_get_32 (objfile->obfd,
2360                                            extab_data + addr - extab_vma);
2361                       addr += 4;
2362                       n_bytes = 3;
2363                       n_words = ((word >> 24) & 0xff);
2364                     }
2365                 }
2366             }
2367         }
2368
2369       /* Sanity check address.  */
2370       if (n_words)
2371         if (addr < extab_vma || addr + 4 * n_words > extab_vma + extab_size)
2372           n_words = n_bytes = 0;
2373
2374       /* The unwind instructions reside in WORD (only the N_BYTES least
2375          significant bytes are valid), followed by N_WORDS words in the
2376          extab section starting at ADDR.  */
2377       if (n_bytes || n_words)
2378         {
2379           gdb_byte *p = entry = obstack_alloc (&objfile->objfile_obstack,
2380                                                n_bytes + n_words * 4 + 1);
2381
2382           while (n_bytes--)
2383             *p++ = (gdb_byte) ((word >> (8 * n_bytes)) & 0xff);
2384
2385           while (n_words--)
2386             {
2387               word = bfd_h_get_32 (objfile->obfd,
2388                                    extab_data + addr - extab_vma);
2389               addr += 4;
2390
2391               *p++ = (gdb_byte) ((word >> 24) & 0xff);
2392               *p++ = (gdb_byte) ((word >> 16) & 0xff);
2393               *p++ = (gdb_byte) ((word >> 8) & 0xff);
2394               *p++ = (gdb_byte) (word & 0xff);
2395             }
2396
2397           /* Implied "Finish" to terminate the list.  */
2398           *p++ = 0xb0;
2399         }
2400
2401       /* Push entry onto vector.  They are guaranteed to always
2402          appear in order of increasing addresses.  */
2403       new_exidx_entry.addr = idx;
2404       new_exidx_entry.entry = entry;
2405       VEC_safe_push (arm_exidx_entry_s,
2406                      data->section_maps[sec->the_bfd_section->index],
2407                      &new_exidx_entry);
2408     }
2409
2410   do_cleanups (cleanups);
2411 }
2412
2413 /* Search for the exception table entry covering MEMADDR.  If one is found,
2414    return a pointer to its data.  Otherwise, return 0.  If START is non-NULL,
2415    set *START to the start of the region covered by this entry.  */
2416
2417 static gdb_byte *
2418 arm_find_exidx_entry (CORE_ADDR memaddr, CORE_ADDR *start)
2419 {
2420   struct obj_section *sec;
2421
2422   sec = find_pc_section (memaddr);
2423   if (sec != NULL)
2424     {
2425       struct arm_exidx_data *data;
2426       VEC(arm_exidx_entry_s) *map;
2427       struct arm_exidx_entry map_key = { memaddr - obj_section_addr (sec), 0 };
2428       unsigned int idx;
2429
2430       data = objfile_data (sec->objfile, arm_exidx_data_key);
2431       if (data != NULL)
2432         {
2433           map = data->section_maps[sec->the_bfd_section->index];
2434           if (!VEC_empty (arm_exidx_entry_s, map))
2435             {
2436               struct arm_exidx_entry *map_sym;
2437
2438               idx = VEC_lower_bound (arm_exidx_entry_s, map, &map_key,
2439                                      arm_compare_exidx_entries);
2440
2441               /* VEC_lower_bound finds the earliest ordered insertion
2442                  point.  If the following symbol starts at this exact
2443                  address, we use that; otherwise, the preceding
2444                  exception table entry covers this address.  */
2445               if (idx < VEC_length (arm_exidx_entry_s, map))
2446                 {
2447                   map_sym = VEC_index (arm_exidx_entry_s, map, idx);
2448                   if (map_sym->addr == map_key.addr)
2449                     {
2450                       if (start)
2451                         *start = map_sym->addr + obj_section_addr (sec);
2452                       return map_sym->entry;
2453                     }
2454                 }
2455
2456               if (idx > 0)
2457                 {
2458                   map_sym = VEC_index (arm_exidx_entry_s, map, idx - 1);
2459                   if (start)
2460                     *start = map_sym->addr + obj_section_addr (sec);
2461                   return map_sym->entry;
2462                 }
2463             }
2464         }
2465     }
2466
2467   return NULL;
2468 }
2469
2470 /* Given the current frame THIS_FRAME, and its associated frame unwinding
2471    instruction list from the ARM exception table entry ENTRY, allocate and
2472    return a prologue cache structure describing how to unwind this frame.
2473
2474    Return NULL if the unwinding instruction list contains a "spare",
2475    "reserved" or "refuse to unwind" instruction as defined in section
2476    "9.3 Frame unwinding instructions" of the "Exception Handling ABI
2477    for the ARM Architecture" document.  */
2478
2479 static struct arm_prologue_cache *
2480 arm_exidx_fill_cache (struct frame_info *this_frame, gdb_byte *entry)
2481 {
2482   CORE_ADDR vsp = 0;
2483   int vsp_valid = 0;
2484
2485   struct arm_prologue_cache *cache;
2486   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2487   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2488
2489   for (;;)
2490     {
2491       gdb_byte insn;
2492
2493       /* Whenever we reload SP, we actually have to retrieve its
2494          actual value in the current frame.  */
2495       if (!vsp_valid)
2496         {
2497           if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2498             {
2499               int reg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2500               vsp = get_frame_register_unsigned (this_frame, reg);
2501             }
2502           else
2503             {
2504               CORE_ADDR addr = cache->saved_regs[ARM_SP_REGNUM].addr;
2505               vsp = get_frame_memory_unsigned (this_frame, addr, 4);
2506             }
2507
2508           vsp_valid = 1;
2509         }
2510
2511       /* Decode next unwind instruction.  */
2512       insn = *entry++;
2513
2514       if ((insn & 0xc0) == 0)
2515         {
2516           int offset = insn & 0x3f;
2517           vsp += (offset << 2) + 4;
2518         }
2519       else if ((insn & 0xc0) == 0x40)
2520         {
2521           int offset = insn & 0x3f;
2522           vsp -= (offset << 2) + 4;
2523         }
2524       else if ((insn & 0xf0) == 0x80)
2525         {
2526           int mask = ((insn & 0xf) << 8) | *entry++;
2527           int i;
2528
2529           /* The special case of an all-zero mask identifies
2530              "Refuse to unwind".  We return NULL to fall back
2531              to the prologue analyzer.  */
2532           if (mask == 0)
2533             return NULL;
2534
2535           /* Pop registers r4..r15 under mask.  */
2536           for (i = 0; i < 12; i++)
2537             if (mask & (1 << i))
2538               {
2539                 cache->saved_regs[4 + i].addr = vsp;
2540                 vsp += 4;
2541               }
2542
2543           /* Special-case popping SP -- we need to reload vsp.  */
2544           if (mask & (1 << (ARM_SP_REGNUM - 4)))
2545             vsp_valid = 0;
2546         }
2547       else if ((insn & 0xf0) == 0x90)
2548         {
2549           int reg = insn & 0xf;
2550
2551           /* Reserved cases.  */
2552           if (reg == ARM_SP_REGNUM || reg == ARM_PC_REGNUM)
2553             return NULL;
2554
2555           /* Set SP from another register and mark VSP for reload.  */
2556           cache->saved_regs[ARM_SP_REGNUM] = cache->saved_regs[reg];
2557           vsp_valid = 0;
2558         }
2559       else if ((insn & 0xf0) == 0xa0)
2560         {
2561           int count = insn & 0x7;
2562           int pop_lr = (insn & 0x8) != 0;
2563           int i;
2564
2565           /* Pop r4..r[4+count].  */
2566           for (i = 0; i <= count; i++)
2567             {
2568               cache->saved_regs[4 + i].addr = vsp;
2569               vsp += 4;
2570             }
2571
2572           /* If indicated by flag, pop LR as well.  */
2573           if (pop_lr)
2574             {
2575               cache->saved_regs[ARM_LR_REGNUM].addr = vsp;
2576               vsp += 4;
2577             }
2578         }
2579       else if (insn == 0xb0)
2580         {
2581           /* We could only have updated PC by popping into it; if so, it
2582              will show up as address.  Otherwise, copy LR into PC.  */
2583           if (!trad_frame_addr_p (cache->saved_regs, ARM_PC_REGNUM))
2584             cache->saved_regs[ARM_PC_REGNUM]
2585               = cache->saved_regs[ARM_LR_REGNUM];
2586
2587           /* We're done.  */
2588           break;
2589         }
2590       else if (insn == 0xb1)
2591         {
2592           int mask = *entry++;
2593           int i;
2594
2595           /* All-zero mask and mask >= 16 is "spare".  */
2596           if (mask == 0 || mask >= 16)
2597             return NULL;
2598
2599           /* Pop r0..r3 under mask.  */
2600           for (i = 0; i < 4; i++)
2601             if (mask & (1 << i))
2602               {
2603                 cache->saved_regs[i].addr = vsp;
2604                 vsp += 4;
2605               }
2606         }
2607       else if (insn == 0xb2)
2608         {
2609           ULONGEST offset = 0;
2610           unsigned shift = 0;
2611
2612           do
2613             {
2614               offset |= (*entry & 0x7f) << shift;
2615               shift += 7;
2616             }
2617           while (*entry++ & 0x80);
2618
2619           vsp += 0x204 + (offset << 2);
2620         }
2621       else if (insn == 0xb3)
2622         {
2623           int start = *entry >> 4;
2624           int count = (*entry++) & 0xf;
2625           int i;
2626
2627           /* Only registers D0..D15 are valid here.  */
2628           if (start + count >= 16)
2629             return NULL;
2630
2631           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2632           for (i = 0; i <= count; i++)
2633             {
2634               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2635               vsp += 8;
2636             }
2637
2638           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2639           vsp += 4;
2640         }
2641       else if ((insn & 0xf8) == 0xb8)
2642         {
2643           int count = insn & 0x7;
2644           int i;
2645
2646           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2647           for (i = 0; i <= count; i++)
2648             {
2649               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2650               vsp += 8;
2651             }
2652
2653           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2654           vsp += 4;
2655         }
2656       else if (insn == 0xc6)
2657         {
2658           int start = *entry >> 4;
2659           int count = (*entry++) & 0xf;
2660           int i;
2661
2662           /* Only registers WR0..WR15 are valid.  */
2663           if (start + count >= 16)
2664             return NULL;
2665
2666           /* Pop iwmmx registers WR[start]..WR[start+count].  */
2667           for (i = 0; i <= count; i++)
2668             {
2669               cache->saved_regs[ARM_WR0_REGNUM + start + i].addr = vsp;
2670               vsp += 8;
2671             }
2672         }
2673       else if (insn == 0xc7)
2674         {
2675           int mask = *entry++;
2676           int i;
2677
2678           /* All-zero mask and mask >= 16 is "spare".  */
2679           if (mask == 0 || mask >= 16)
2680             return NULL;
2681
2682           /* Pop iwmmx general-purpose registers WCGR0..WCGR3 under mask.  */
2683           for (i = 0; i < 4; i++)
2684             if (mask & (1 << i))
2685               {
2686                 cache->saved_regs[ARM_WCGR0_REGNUM + i].addr = vsp;
2687                 vsp += 4;
2688               }
2689         }
2690       else if ((insn & 0xf8) == 0xc0)
2691         {
2692           int count = insn & 0x7;
2693           int i;
2694
2695           /* Pop iwmmx registers WR[10]..WR[10+count].  */
2696           for (i = 0; i <= count; i++)
2697             {
2698               cache->saved_regs[ARM_WR0_REGNUM + 10 + i].addr = vsp;
2699               vsp += 8;
2700             }
2701         }
2702       else if (insn == 0xc8)
2703         {
2704           int start = *entry >> 4;
2705           int count = (*entry++) & 0xf;
2706           int i;
2707
2708           /* Only registers D0..D31 are valid.  */
2709           if (start + count >= 16)
2710             return NULL;
2711
2712           /* Pop VFP double-precision registers
2713              D[16+start]..D[16+start+count].  */
2714           for (i = 0; i <= count; i++)
2715             {
2716               cache->saved_regs[ARM_D0_REGNUM + 16 + start + i].addr = vsp;
2717               vsp += 8;
2718             }
2719         }
2720       else if (insn == 0xc9)
2721         {
2722           int start = *entry >> 4;
2723           int count = (*entry++) & 0xf;
2724           int i;
2725
2726           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2727           for (i = 0; i <= count; i++)
2728             {
2729               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2730               vsp += 8;
2731             }
2732         }
2733       else if ((insn & 0xf8) == 0xd0)
2734         {
2735           int count = insn & 0x7;
2736           int i;
2737
2738           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2739           for (i = 0; i <= count; i++)
2740             {
2741               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2742               vsp += 8;
2743             }
2744         }
2745       else
2746         {
2747           /* Everything else is "spare".  */
2748           return NULL;
2749         }
2750     }
2751
2752   /* If we restore SP from a register, assume this was the frame register.
2753      Otherwise just fall back to SP as frame register.  */
2754   if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2755     cache->framereg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2756   else
2757     cache->framereg = ARM_SP_REGNUM;
2758
2759   /* Determine offset to previous frame.  */
2760   cache->framesize
2761     = vsp - get_frame_register_unsigned (this_frame, cache->framereg);
2762
2763   /* We already got the previous SP.  */
2764   cache->prev_sp = vsp;
2765
2766   return cache;
2767 }
2768
2769 /* Unwinding via ARM exception table entries.  Note that the sniffer
2770    already computes a filled-in prologue cache, which is then used
2771    with the same arm_prologue_this_id and arm_prologue_prev_register
2772    routines also used for prologue-parsing based unwinding.  */
2773
2774 static int
2775 arm_exidx_unwind_sniffer (const struct frame_unwind *self,
2776                           struct frame_info *this_frame,
2777                           void **this_prologue_cache)
2778 {
2779   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2780   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
2781   CORE_ADDR addr_in_block, exidx_region, func_start;
2782   struct arm_prologue_cache *cache;
2783   gdb_byte *entry;
2784
2785   /* See if we have an ARM exception table entry covering this address.  */
2786   addr_in_block = get_frame_address_in_block (this_frame);
2787   entry = arm_find_exidx_entry (addr_in_block, &exidx_region);
2788   if (!entry)
2789     return 0;
2790
2791   /* The ARM exception table does not describe unwind information
2792      for arbitrary PC values, but is guaranteed to be correct only
2793      at call sites.  We have to decide here whether we want to use
2794      ARM exception table information for this frame, or fall back
2795      to using prologue parsing.  (Note that if we have DWARF CFI,
2796      this sniffer isn't even called -- CFI is always preferred.)
2797
2798      Before we make this decision, however, we check whether we
2799      actually have *symbol* information for the current frame.
2800      If not, prologue parsing would not work anyway, so we might
2801      as well use the exception table and hope for the best.  */
2802   if (find_pc_partial_function (addr_in_block, NULL, &func_start, NULL))
2803     {
2804       int exc_valid = 0;
2805
2806       /* If the next frame is "normal", we are at a call site in this
2807          frame, so exception information is guaranteed to be valid.  */
2808       if (get_next_frame (this_frame)
2809           && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME)
2810         exc_valid = 1;
2811
2812       /* We also assume exception information is valid if we're currently
2813          blocked in a system call.  The system library is supposed to
2814          ensure this, so that e.g. pthread cancellation works.  */
2815       if (arm_frame_is_thumb (this_frame))
2816         {
2817           LONGEST insn;
2818
2819           if (safe_read_memory_integer (get_frame_pc (this_frame) - 2, 2,
2820                                         byte_order_for_code, &insn)
2821               && (insn & 0xff00) == 0xdf00 /* svc */)
2822             exc_valid = 1;
2823         }
2824       else
2825         {
2826           LONGEST insn;
2827
2828           if (safe_read_memory_integer (get_frame_pc (this_frame) - 4, 4,
2829                                         byte_order_for_code, &insn)
2830               && (insn & 0x0f000000) == 0x0f000000 /* svc */)
2831             exc_valid = 1;
2832         }
2833         
2834       /* Bail out if we don't know that exception information is valid.  */
2835       if (!exc_valid)
2836         return 0;
2837
2838      /* The ARM exception index does not mark the *end* of the region
2839         covered by the entry, and some functions will not have any entry.
2840         To correctly recognize the end of the covered region, the linker
2841         should have inserted dummy records with a CANTUNWIND marker.
2842
2843         Unfortunately, current versions of GNU ld do not reliably do
2844         this, and thus we may have found an incorrect entry above.
2845         As a (temporary) sanity check, we only use the entry if it
2846         lies *within* the bounds of the function.  Note that this check
2847         might reject perfectly valid entries that just happen to cover
2848         multiple functions; therefore this check ought to be removed
2849         once the linker is fixed.  */
2850       if (func_start > exidx_region)
2851         return 0;
2852     }
2853
2854   /* Decode the list of unwinding instructions into a prologue cache.
2855      Note that this may fail due to e.g. a "refuse to unwind" code.  */
2856   cache = arm_exidx_fill_cache (this_frame, entry);
2857   if (!cache)
2858     return 0;
2859
2860   *this_prologue_cache = cache;
2861   return 1;
2862 }
2863
2864 struct frame_unwind arm_exidx_unwind = {
2865   NORMAL_FRAME,
2866   default_frame_unwind_stop_reason,
2867   arm_prologue_this_id,
2868   arm_prologue_prev_register,
2869   NULL,
2870   arm_exidx_unwind_sniffer
2871 };
2872
2873 static struct arm_prologue_cache *
2874 arm_make_stub_cache (struct frame_info *this_frame)
2875 {
2876   struct arm_prologue_cache *cache;
2877
2878   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2879   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2880
2881   cache->prev_sp = get_frame_register_unsigned (this_frame, ARM_SP_REGNUM);
2882
2883   return cache;
2884 }
2885
2886 /* Our frame ID for a stub frame is the current SP and LR.  */
2887
2888 static void
2889 arm_stub_this_id (struct frame_info *this_frame,
2890                   void **this_cache,
2891                   struct frame_id *this_id)
2892 {
2893   struct arm_prologue_cache *cache;
2894
2895   if (*this_cache == NULL)
2896     *this_cache = arm_make_stub_cache (this_frame);
2897   cache = *this_cache;
2898
2899   *this_id = frame_id_build (cache->prev_sp, get_frame_pc (this_frame));
2900 }
2901
2902 static int
2903 arm_stub_unwind_sniffer (const struct frame_unwind *self,
2904                          struct frame_info *this_frame,
2905                          void **this_prologue_cache)
2906 {
2907   CORE_ADDR addr_in_block;
2908   gdb_byte dummy[4];
2909
2910   addr_in_block = get_frame_address_in_block (this_frame);
2911   if (in_plt_section (addr_in_block)
2912       /* We also use the stub winder if the target memory is unreadable
2913          to avoid having the prologue unwinder trying to read it.  */
2914       || target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
2915     return 1;
2916
2917   return 0;
2918 }
2919
2920 struct frame_unwind arm_stub_unwind = {
2921   NORMAL_FRAME,
2922   default_frame_unwind_stop_reason,
2923   arm_stub_this_id,
2924   arm_prologue_prev_register,
2925   NULL,
2926   arm_stub_unwind_sniffer
2927 };
2928
2929 /* Put here the code to store, into CACHE->saved_regs, the addresses
2930    of the saved registers of frame described by THIS_FRAME.  CACHE is
2931    returned.  */
2932
2933 static struct arm_prologue_cache *
2934 arm_m_exception_cache (struct frame_info *this_frame)
2935 {
2936   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2937   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2938   struct arm_prologue_cache *cache;
2939   CORE_ADDR unwound_sp;
2940   LONGEST xpsr;
2941
2942   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2943   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2944
2945   unwound_sp = get_frame_register_unsigned (this_frame,
2946                                             ARM_SP_REGNUM);
2947
2948   /* The hardware saves eight 32-bit words, comprising xPSR,
2949      ReturnAddress, LR (R14), R12, R3, R2, R1, R0.  See details in
2950      "B1.5.6 Exception entry behavior" in
2951      "ARMv7-M Architecture Reference Manual".  */
2952   cache->saved_regs[0].addr = unwound_sp;
2953   cache->saved_regs[1].addr = unwound_sp + 4;
2954   cache->saved_regs[2].addr = unwound_sp + 8;
2955   cache->saved_regs[3].addr = unwound_sp + 12;
2956   cache->saved_regs[12].addr = unwound_sp + 16;
2957   cache->saved_regs[14].addr = unwound_sp + 20;
2958   cache->saved_regs[15].addr = unwound_sp + 24;
2959   cache->saved_regs[ARM_PS_REGNUM].addr = unwound_sp + 28;
2960
2961   /* If bit 9 of the saved xPSR is set, then there is a four-byte
2962      aligner between the top of the 32-byte stack frame and the
2963      previous context's stack pointer.  */
2964   cache->prev_sp = unwound_sp + 32;
2965   if (safe_read_memory_integer (unwound_sp + 28, 4, byte_order, &xpsr)
2966       && (xpsr & (1 << 9)) != 0)
2967     cache->prev_sp += 4;
2968
2969   return cache;
2970 }
2971
2972 /* Implementation of function hook 'this_id' in
2973    'struct frame_uwnind'.  */
2974
2975 static void
2976 arm_m_exception_this_id (struct frame_info *this_frame,
2977                          void **this_cache,
2978                          struct frame_id *this_id)
2979 {
2980   struct arm_prologue_cache *cache;
2981
2982   if (*this_cache == NULL)
2983     *this_cache = arm_m_exception_cache (this_frame);
2984   cache = *this_cache;
2985
2986   /* Our frame ID for a stub frame is the current SP and LR.  */
2987   *this_id = frame_id_build (cache->prev_sp,
2988                              get_frame_pc (this_frame));
2989 }
2990
2991 /* Implementation of function hook 'prev_register' in
2992    'struct frame_uwnind'.  */
2993
2994 static struct value *
2995 arm_m_exception_prev_register (struct frame_info *this_frame,
2996                                void **this_cache,
2997                                int prev_regnum)
2998 {
2999   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3000   struct arm_prologue_cache *cache;
3001
3002   if (*this_cache == NULL)
3003     *this_cache = arm_m_exception_cache (this_frame);
3004   cache = *this_cache;
3005
3006   /* The value was already reconstructed into PREV_SP.  */
3007   if (prev_regnum == ARM_SP_REGNUM)
3008     return frame_unwind_got_constant (this_frame, prev_regnum,
3009                                       cache->prev_sp);
3010
3011   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
3012                                        prev_regnum);
3013 }
3014
3015 /* Implementation of function hook 'sniffer' in
3016    'struct frame_uwnind'.  */
3017
3018 static int
3019 arm_m_exception_unwind_sniffer (const struct frame_unwind *self,
3020                                 struct frame_info *this_frame,
3021                                 void **this_prologue_cache)
3022 {
3023   CORE_ADDR this_pc = get_frame_pc (this_frame);
3024
3025   /* No need to check is_m; this sniffer is only registered for
3026      M-profile architectures.  */
3027
3028   /* Exception frames return to one of these magic PCs.  Other values
3029      are not defined as of v7-M.  See details in "B1.5.8 Exception
3030      return behavior" in "ARMv7-M Architecture Reference Manual".  */
3031   if (this_pc == 0xfffffff1 || this_pc == 0xfffffff9
3032       || this_pc == 0xfffffffd)
3033     return 1;
3034
3035   return 0;
3036 }
3037
3038 /* Frame unwinder for M-profile exceptions.  */
3039
3040 struct frame_unwind arm_m_exception_unwind =
3041 {
3042   SIGTRAMP_FRAME,
3043   default_frame_unwind_stop_reason,
3044   arm_m_exception_this_id,
3045   arm_m_exception_prev_register,
3046   NULL,
3047   arm_m_exception_unwind_sniffer
3048 };
3049
3050 static CORE_ADDR
3051 arm_normal_frame_base (struct frame_info *this_frame, void **this_cache)
3052 {
3053   struct arm_prologue_cache *cache;
3054
3055   if (*this_cache == NULL)
3056     *this_cache = arm_make_prologue_cache (this_frame);
3057   cache = *this_cache;
3058
3059   return cache->prev_sp - cache->framesize;
3060 }
3061
3062 struct frame_base arm_normal_base = {
3063   &arm_prologue_unwind,
3064   arm_normal_frame_base,
3065   arm_normal_frame_base,
3066   arm_normal_frame_base
3067 };
3068
3069 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
3070    dummy frame.  The frame ID's base needs to match the TOS value
3071    saved by save_dummy_frame_tos() and returned from
3072    arm_push_dummy_call, and the PC needs to match the dummy frame's
3073    breakpoint.  */
3074
3075 static struct frame_id
3076 arm_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
3077 {
3078   return frame_id_build (get_frame_register_unsigned (this_frame,
3079                                                       ARM_SP_REGNUM),
3080                          get_frame_pc (this_frame));
3081 }
3082
3083 /* Given THIS_FRAME, find the previous frame's resume PC (which will
3084    be used to construct the previous frame's ID, after looking up the
3085    containing function).  */
3086
3087 static CORE_ADDR
3088 arm_unwind_pc (struct gdbarch *gdbarch, struct frame_info *this_frame)
3089 {
3090   CORE_ADDR pc;
3091   pc = frame_unwind_register_unsigned (this_frame, ARM_PC_REGNUM);
3092   return arm_addr_bits_remove (gdbarch, pc);
3093 }
3094
3095 static CORE_ADDR
3096 arm_unwind_sp (struct gdbarch *gdbarch, struct frame_info *this_frame)
3097 {
3098   return frame_unwind_register_unsigned (this_frame, ARM_SP_REGNUM);
3099 }
3100
3101 static struct value *
3102 arm_dwarf2_prev_register (struct frame_info *this_frame, void **this_cache,
3103                           int regnum)
3104 {
3105   struct gdbarch * gdbarch = get_frame_arch (this_frame);
3106   CORE_ADDR lr, cpsr;
3107   ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
3108
3109   switch (regnum)
3110     {
3111     case ARM_PC_REGNUM:
3112       /* The PC is normally copied from the return column, which
3113          describes saves of LR.  However, that version may have an
3114          extra bit set to indicate Thumb state.  The bit is not
3115          part of the PC.  */
3116       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3117       return frame_unwind_got_constant (this_frame, regnum,
3118                                         arm_addr_bits_remove (gdbarch, lr));
3119
3120     case ARM_PS_REGNUM:
3121       /* Reconstruct the T bit; see arm_prologue_prev_register for details.  */
3122       cpsr = get_frame_register_unsigned (this_frame, regnum);
3123       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3124       if (IS_THUMB_ADDR (lr))
3125         cpsr |= t_bit;
3126       else
3127         cpsr &= ~t_bit;
3128       return frame_unwind_got_constant (this_frame, regnum, cpsr);
3129
3130     default:
3131       internal_error (__FILE__, __LINE__,
3132                       _("Unexpected register %d"), regnum);
3133     }
3134 }
3135
3136 static void
3137 arm_dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
3138                            struct dwarf2_frame_state_reg *reg,
3139                            struct frame_info *this_frame)
3140 {
3141   switch (regnum)
3142     {
3143     case ARM_PC_REGNUM:
3144     case ARM_PS_REGNUM:
3145       reg->how = DWARF2_FRAME_REG_FN;
3146       reg->loc.fn = arm_dwarf2_prev_register;
3147       break;
3148     case ARM_SP_REGNUM:
3149       reg->how = DWARF2_FRAME_REG_CFA;
3150       break;
3151     }
3152 }
3153
3154 /* Return true if we are in the function's epilogue, i.e. after the
3155    instruction that destroyed the function's stack frame.  */
3156
3157 static int
3158 thumb_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3159 {
3160   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3161   unsigned int insn, insn2;
3162   int found_return = 0, found_stack_adjust = 0;
3163   CORE_ADDR func_start, func_end;
3164   CORE_ADDR scan_pc;
3165   gdb_byte buf[4];
3166
3167   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3168     return 0;
3169
3170   /* The epilogue is a sequence of instructions along the following lines:
3171
3172     - add stack frame size to SP or FP
3173     - [if frame pointer used] restore SP from FP
3174     - restore registers from SP [may include PC]
3175     - a return-type instruction [if PC wasn't already restored]
3176
3177     In a first pass, we scan forward from the current PC and verify the
3178     instructions we find as compatible with this sequence, ending in a
3179     return instruction.
3180
3181     However, this is not sufficient to distinguish indirect function calls
3182     within a function from indirect tail calls in the epilogue in some cases.
3183     Therefore, if we didn't already find any SP-changing instruction during
3184     forward scan, we add a backward scanning heuristic to ensure we actually
3185     are in the epilogue.  */
3186
3187   scan_pc = pc;
3188   while (scan_pc < func_end && !found_return)
3189     {
3190       if (target_read_memory (scan_pc, buf, 2))
3191         break;
3192
3193       scan_pc += 2;
3194       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3195
3196       if ((insn & 0xff80) == 0x4700)  /* bx <Rm> */
3197         found_return = 1;
3198       else if (insn == 0x46f7)  /* mov pc, lr */
3199         found_return = 1;
3200       else if (insn == 0x46bd)  /* mov sp, r7 */
3201         found_stack_adjust = 1;
3202       else if ((insn & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3203         found_stack_adjust = 1;
3204       else if ((insn & 0xfe00) == 0xbc00)  /* pop <registers> */
3205         {
3206           found_stack_adjust = 1;
3207           if (insn & 0x0100)  /* <registers> include PC.  */
3208             found_return = 1;
3209         }
3210       else if (thumb_insn_size (insn) == 4)  /* 32-bit Thumb-2 instruction */
3211         {
3212           if (target_read_memory (scan_pc, buf, 2))
3213             break;
3214
3215           scan_pc += 2;
3216           insn2 = extract_unsigned_integer (buf, 2, byte_order_for_code);
3217
3218           if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3219             {
3220               found_stack_adjust = 1;
3221               if (insn2 & 0x8000)  /* <registers> include PC.  */
3222                 found_return = 1;
3223             }
3224           else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3225                    && (insn2 & 0x0fff) == 0x0b04)
3226             {
3227               found_stack_adjust = 1;
3228               if ((insn2 & 0xf000) == 0xf000) /* <Rt> is PC.  */
3229                 found_return = 1;
3230             }
3231           else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3232                    && (insn2 & 0x0e00) == 0x0a00)
3233             found_stack_adjust = 1;
3234           else
3235             break;
3236         }
3237       else
3238         break;
3239     }
3240
3241   if (!found_return)
3242     return 0;
3243
3244   /* Since any instruction in the epilogue sequence, with the possible
3245      exception of return itself, updates the stack pointer, we need to
3246      scan backwards for at most one instruction.  Try either a 16-bit or
3247      a 32-bit instruction.  This is just a heuristic, so we do not worry
3248      too much about false positives.  */
3249
3250   if (!found_stack_adjust)
3251     {
3252       if (pc - 4 < func_start)
3253         return 0;
3254       if (target_read_memory (pc - 4, buf, 4))
3255         return 0;
3256
3257       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3258       insn2 = extract_unsigned_integer (buf + 2, 2, byte_order_for_code);
3259
3260       if (insn2 == 0x46bd)  /* mov sp, r7 */
3261         found_stack_adjust = 1;
3262       else if ((insn2 & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3263         found_stack_adjust = 1;
3264       else if ((insn2 & 0xff00) == 0xbc00)  /* pop <registers> without PC */
3265         found_stack_adjust = 1;
3266       else if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3267         found_stack_adjust = 1;
3268       else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3269                && (insn2 & 0x0fff) == 0x0b04)
3270         found_stack_adjust = 1;
3271       else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3272                && (insn2 & 0x0e00) == 0x0a00)
3273         found_stack_adjust = 1;
3274     }
3275
3276   return found_stack_adjust;
3277 }
3278
3279 /* Return true if we are in the function's epilogue, i.e. after the
3280    instruction that destroyed the function's stack frame.  */
3281
3282 static int
3283 arm_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3284 {
3285   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3286   unsigned int insn;
3287   int found_return, found_stack_adjust;
3288   CORE_ADDR func_start, func_end;
3289
3290   if (arm_pc_is_thumb (gdbarch, pc))
3291     return thumb_in_function_epilogue_p (gdbarch, pc);
3292
3293   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3294     return 0;
3295
3296   /* We are in the epilogue if the previous instruction was a stack
3297      adjustment and the next instruction is a possible return (bx, mov
3298      pc, or pop).  We could have to scan backwards to find the stack
3299      adjustment, or forwards to find the return, but this is a decent
3300      approximation.  First scan forwards.  */
3301
3302   found_return = 0;
3303   insn = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
3304   if (bits (insn, 28, 31) != INST_NV)
3305     {
3306       if ((insn & 0x0ffffff0) == 0x012fff10)
3307         /* BX.  */
3308         found_return = 1;
3309       else if ((insn & 0x0ffffff0) == 0x01a0f000)
3310         /* MOV PC.  */
3311         found_return = 1;
3312       else if ((insn & 0x0fff0000) == 0x08bd0000
3313           && (insn & 0x0000c000) != 0)
3314         /* POP (LDMIA), including PC or LR.  */
3315         found_return = 1;
3316     }
3317
3318   if (!found_return)
3319     return 0;
3320
3321   /* Scan backwards.  This is just a heuristic, so do not worry about
3322      false positives from mode changes.  */
3323
3324   if (pc < func_start + 4)
3325     return 0;
3326
3327   found_stack_adjust = 0;
3328   insn = read_memory_unsigned_integer (pc - 4, 4, byte_order_for_code);
3329   if (bits (insn, 28, 31) != INST_NV)
3330     {
3331       if ((insn & 0x0df0f000) == 0x0080d000)
3332         /* ADD SP (register or immediate).  */
3333         found_stack_adjust = 1;
3334       else if ((insn & 0x0df0f000) == 0x0040d000)
3335         /* SUB SP (register or immediate).  */
3336         found_stack_adjust = 1;
3337       else if ((insn & 0x0ffffff0) == 0x01a0d000)
3338         /* MOV SP.  */
3339         found_stack_adjust = 1;
3340       else if ((insn & 0x0fff0000) == 0x08bd0000)
3341         /* POP (LDMIA).  */
3342         found_stack_adjust = 1;
3343       else if ((insn & 0x0fff0000) == 0x049d0000)
3344         /* POP of a single register.  */
3345         found_stack_adjust = 1;
3346     }
3347
3348   if (found_stack_adjust)
3349     return 1;
3350
3351   return 0;
3352 }
3353
3354
3355 /* When arguments must be pushed onto the stack, they go on in reverse
3356    order.  The code below implements a FILO (stack) to do this.  */
3357
3358 struct stack_item
3359 {
3360   int len;
3361   struct stack_item *prev;
3362   void *data;
3363 };
3364
3365 static struct stack_item *
3366 push_stack_item (struct stack_item *prev, const void *contents, int len)
3367 {
3368   struct stack_item *si;
3369   si = xmalloc (sizeof (struct stack_item));
3370   si->data = xmalloc (len);
3371   si->len = len;
3372   si->prev = prev;
3373   memcpy (si->data, contents, len);
3374   return si;
3375 }
3376
3377 static struct stack_item *
3378 pop_stack_item (struct stack_item *si)
3379 {
3380   struct stack_item *dead = si;
3381   si = si->prev;
3382   xfree (dead->data);
3383   xfree (dead);
3384   return si;
3385 }
3386
3387
3388 /* Return the alignment (in bytes) of the given type.  */
3389
3390 static int
3391 arm_type_align (struct type *t)
3392 {
3393   int n;
3394   int align;
3395   int falign;
3396
3397   t = check_typedef (t);
3398   switch (TYPE_CODE (t))
3399     {
3400     default:
3401       /* Should never happen.  */
3402       internal_error (__FILE__, __LINE__, _("unknown type alignment"));
3403       return 4;
3404
3405     case TYPE_CODE_PTR:
3406     case TYPE_CODE_ENUM:
3407     case TYPE_CODE_INT:
3408     case TYPE_CODE_FLT:
3409     case TYPE_CODE_SET:
3410     case TYPE_CODE_RANGE:
3411     case TYPE_CODE_REF:
3412     case TYPE_CODE_CHAR:
3413     case TYPE_CODE_BOOL:
3414       return TYPE_LENGTH (t);
3415
3416     case TYPE_CODE_ARRAY:
3417     case TYPE_CODE_COMPLEX:
3418       /* TODO: What about vector types?  */
3419       return arm_type_align (TYPE_TARGET_TYPE (t));
3420
3421     case TYPE_CODE_STRUCT:
3422     case TYPE_CODE_UNION:
3423       align = 1;
3424       for (n = 0; n < TYPE_NFIELDS (t); n++)
3425         {
3426           falign = arm_type_align (TYPE_FIELD_TYPE (t, n));
3427           if (falign > align)
3428             align = falign;
3429         }
3430       return align;
3431     }
3432 }
3433
3434 /* Possible base types for a candidate for passing and returning in
3435    VFP registers.  */
3436
3437 enum arm_vfp_cprc_base_type
3438 {
3439   VFP_CPRC_UNKNOWN,
3440   VFP_CPRC_SINGLE,
3441   VFP_CPRC_DOUBLE,
3442   VFP_CPRC_VEC64,
3443   VFP_CPRC_VEC128
3444 };
3445
3446 /* The length of one element of base type B.  */
3447
3448 static unsigned
3449 arm_vfp_cprc_unit_length (enum arm_vfp_cprc_base_type b)
3450 {
3451   switch (b)
3452     {
3453     case VFP_CPRC_SINGLE:
3454       return 4;
3455     case VFP_CPRC_DOUBLE:
3456       return 8;
3457     case VFP_CPRC_VEC64:
3458       return 8;
3459     case VFP_CPRC_VEC128:
3460       return 16;
3461     default:
3462       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3463                       (int) b);
3464     }
3465 }
3466
3467 /* The character ('s', 'd' or 'q') for the type of VFP register used
3468    for passing base type B.  */
3469
3470 static int
3471 arm_vfp_cprc_reg_char (enum arm_vfp_cprc_base_type b)
3472 {
3473   switch (b)
3474     {
3475     case VFP_CPRC_SINGLE:
3476       return 's';
3477     case VFP_CPRC_DOUBLE:
3478       return 'd';
3479     case VFP_CPRC_VEC64:
3480       return 'd';
3481     case VFP_CPRC_VEC128:
3482       return 'q';
3483     default:
3484       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3485                       (int) b);
3486     }
3487 }
3488
3489 /* Determine whether T may be part of a candidate for passing and
3490    returning in VFP registers, ignoring the limit on the total number
3491    of components.  If *BASE_TYPE is VFP_CPRC_UNKNOWN, set it to the
3492    classification of the first valid component found; if it is not
3493    VFP_CPRC_UNKNOWN, all components must have the same classification
3494    as *BASE_TYPE.  If it is found that T contains a type not permitted
3495    for passing and returning in VFP registers, a type differently
3496    classified from *BASE_TYPE, or two types differently classified
3497    from each other, return -1, otherwise return the total number of
3498    base-type elements found (possibly 0 in an empty structure or
3499    array).  Vectors and complex types are not currently supported,
3500    matching the generic AAPCS support.  */
3501
3502 static int
3503 arm_vfp_cprc_sub_candidate (struct type *t,
3504                             enum arm_vfp_cprc_base_type *base_type)
3505 {
3506   t = check_typedef (t);
3507   switch (TYPE_CODE (t))
3508     {
3509     case TYPE_CODE_FLT:
3510       switch (TYPE_LENGTH (t))
3511         {
3512         case 4:
3513           if (*base_type == VFP_CPRC_UNKNOWN)
3514             *base_type = VFP_CPRC_SINGLE;
3515           else if (*base_type != VFP_CPRC_SINGLE)
3516             return -1;
3517           return 1;
3518
3519         case 8:
3520           if (*base_type == VFP_CPRC_UNKNOWN)
3521             *base_type = VFP_CPRC_DOUBLE;
3522           else if (*base_type != VFP_CPRC_DOUBLE)
3523             return -1;
3524           return 1;
3525
3526         default:
3527           return -1;
3528         }
3529       break;
3530
3531     case TYPE_CODE_ARRAY:
3532       {
3533         int count;
3534         unsigned unitlen;
3535         count = arm_vfp_cprc_sub_candidate (TYPE_TARGET_TYPE (t), base_type);
3536         if (count == -1)
3537           return -1;
3538         if (TYPE_LENGTH (t) == 0)
3539           {
3540             gdb_assert (count == 0);
3541             return 0;
3542           }
3543         else if (count == 0)
3544           return -1;
3545         unitlen = arm_vfp_cprc_unit_length (*base_type);
3546         gdb_assert ((TYPE_LENGTH (t) % unitlen) == 0);
3547         return TYPE_LENGTH (t) / unitlen;
3548       }
3549       break;
3550
3551     case TYPE_CODE_STRUCT:
3552       {
3553         int count = 0;
3554         unsigned unitlen;
3555         int i;
3556         for (i = 0; i < TYPE_NFIELDS (t); i++)
3557           {
3558             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3559                                                         base_type);
3560             if (sub_count == -1)
3561               return -1;
3562             count += sub_count;
3563           }
3564         if (TYPE_LENGTH (t) == 0)
3565           {
3566             gdb_assert (count == 0);
3567             return 0;
3568           }
3569         else if (count == 0)
3570           return -1;
3571         unitlen = arm_vfp_cprc_unit_length (*base_type);
3572         if (TYPE_LENGTH (t) != unitlen * count)
3573           return -1;
3574         return count;
3575       }
3576
3577     case TYPE_CODE_UNION:
3578       {
3579         int count = 0;
3580         unsigned unitlen;
3581         int i;
3582         for (i = 0; i < TYPE_NFIELDS (t); i++)
3583           {
3584             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3585                                                         base_type);
3586             if (sub_count == -1)
3587               return -1;
3588             count = (count > sub_count ? count : sub_count);
3589           }
3590         if (TYPE_LENGTH (t) == 0)
3591           {
3592             gdb_assert (count == 0);
3593             return 0;
3594           }
3595         else if (count == 0)
3596           return -1;
3597         unitlen = arm_vfp_cprc_unit_length (*base_type);
3598         if (TYPE_LENGTH (t) != unitlen * count)
3599           return -1;
3600         return count;
3601       }
3602
3603     default:
3604       break;
3605     }
3606
3607   return -1;
3608 }
3609
3610 /* Determine whether T is a VFP co-processor register candidate (CPRC)
3611    if passed to or returned from a non-variadic function with the VFP
3612    ABI in effect.  Return 1 if it is, 0 otherwise.  If it is, set
3613    *BASE_TYPE to the base type for T and *COUNT to the number of
3614    elements of that base type before returning.  */
3615
3616 static int
3617 arm_vfp_call_candidate (struct type *t, enum arm_vfp_cprc_base_type *base_type,
3618                         int *count)
3619 {
3620   enum arm_vfp_cprc_base_type b = VFP_CPRC_UNKNOWN;
3621   int c = arm_vfp_cprc_sub_candidate (t, &b);
3622   if (c <= 0 || c > 4)
3623     return 0;
3624   *base_type = b;
3625   *count = c;
3626   return 1;
3627 }
3628
3629 /* Return 1 if the VFP ABI should be used for passing arguments to and
3630    returning values from a function of type FUNC_TYPE, 0
3631    otherwise.  */
3632
3633 static int
3634 arm_vfp_abi_for_function (struct gdbarch *gdbarch, struct type *func_type)
3635 {
3636   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3637   /* Variadic functions always use the base ABI.  Assume that functions
3638      without debug info are not variadic.  */
3639   if (func_type && TYPE_VARARGS (check_typedef (func_type)))
3640     return 0;
3641   /* The VFP ABI is only supported as a variant of AAPCS.  */
3642   if (tdep->arm_abi != ARM_ABI_AAPCS)
3643     return 0;
3644   return gdbarch_tdep (gdbarch)->fp_model == ARM_FLOAT_VFP;
3645 }
3646
3647 /* We currently only support passing parameters in integer registers, which
3648    conforms with GCC's default model, and VFP argument passing following
3649    the VFP variant of AAPCS.  Several other variants exist and
3650    we should probably support some of them based on the selected ABI.  */
3651
3652 static CORE_ADDR
3653 arm_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
3654                      struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
3655                      struct value **args, CORE_ADDR sp, int struct_return,
3656                      CORE_ADDR struct_addr)
3657 {
3658   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3659   int argnum;
3660   int argreg;
3661   int nstack;
3662   struct stack_item *si = NULL;
3663   int use_vfp_abi;
3664   struct type *ftype;
3665   unsigned vfp_regs_free = (1 << 16) - 1;
3666
3667   /* Determine the type of this function and whether the VFP ABI
3668      applies.  */
3669   ftype = check_typedef (value_type (function));
3670   if (TYPE_CODE (ftype) == TYPE_CODE_PTR)
3671     ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
3672   use_vfp_abi = arm_vfp_abi_for_function (gdbarch, ftype);
3673
3674   /* Set the return address.  For the ARM, the return breakpoint is
3675      always at BP_ADDR.  */
3676   if (arm_pc_is_thumb (gdbarch, bp_addr))
3677     bp_addr |= 1;
3678   regcache_cooked_write_unsigned (regcache, ARM_LR_REGNUM, bp_addr);
3679
3680   /* Walk through the list of args and determine how large a temporary
3681      stack is required.  Need to take care here as structs may be
3682      passed on the stack, and we have to push them.  */
3683   nstack = 0;
3684
3685   argreg = ARM_A1_REGNUM;
3686   nstack = 0;
3687
3688   /* The struct_return pointer occupies the first parameter
3689      passing register.  */
3690   if (struct_return)
3691     {
3692       if (arm_debug)
3693         fprintf_unfiltered (gdb_stdlog, "struct return in %s = %s\n",
3694                             gdbarch_register_name (gdbarch, argreg),
3695                             paddress (gdbarch, struct_addr));
3696       regcache_cooked_write_unsigned (regcache, argreg, struct_addr);
3697       argreg++;
3698     }
3699
3700   for (argnum = 0; argnum < nargs; argnum++)
3701     {
3702       int len;
3703       struct type *arg_type;
3704       struct type *target_type;
3705       enum type_code typecode;
3706       const bfd_byte *val;
3707       int align;
3708       enum arm_vfp_cprc_base_type vfp_base_type;
3709       int vfp_base_count;
3710       int may_use_core_reg = 1;
3711
3712       arg_type = check_typedef (value_type (args[argnum]));
3713       len = TYPE_LENGTH (arg_type);
3714       target_type = TYPE_TARGET_TYPE (arg_type);
3715       typecode = TYPE_CODE (arg_type);
3716       val = value_contents (args[argnum]);
3717
3718       align = arm_type_align (arg_type);
3719       /* Round alignment up to a whole number of words.  */
3720       align = (align + INT_REGISTER_SIZE - 1) & ~(INT_REGISTER_SIZE - 1);
3721       /* Different ABIs have different maximum alignments.  */
3722       if (gdbarch_tdep (gdbarch)->arm_abi == ARM_ABI_APCS)
3723         {
3724           /* The APCS ABI only requires word alignment.  */
3725           align = INT_REGISTER_SIZE;
3726         }
3727       else
3728         {
3729           /* The AAPCS requires at most doubleword alignment.  */
3730           if (align > INT_REGISTER_SIZE * 2)
3731             align = INT_REGISTER_SIZE * 2;
3732         }
3733
3734       if (use_vfp_abi
3735           && arm_vfp_call_candidate (arg_type, &vfp_base_type,
3736                                      &vfp_base_count))
3737         {
3738           int regno;
3739           int unit_length;
3740           int shift;
3741           unsigned mask;
3742
3743           /* Because this is a CPRC it cannot go in a core register or
3744              cause a core register to be skipped for alignment.
3745              Either it goes in VFP registers and the rest of this loop
3746              iteration is skipped for this argument, or it goes on the
3747              stack (and the stack alignment code is correct for this
3748              case).  */
3749           may_use_core_reg = 0;
3750
3751           unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
3752           shift = unit_length / 4;
3753           mask = (1 << (shift * vfp_base_count)) - 1;
3754           for (regno = 0; regno < 16; regno += shift)
3755             if (((vfp_regs_free >> regno) & mask) == mask)
3756               break;
3757
3758           if (regno < 16)
3759             {
3760               int reg_char;
3761               int reg_scaled;
3762               int i;
3763
3764               vfp_regs_free &= ~(mask << regno);
3765               reg_scaled = regno / shift;
3766               reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
3767               for (i = 0; i < vfp_base_count; i++)
3768                 {
3769                   char name_buf[4];
3770                   int regnum;
3771                   if (reg_char == 'q')
3772                     arm_neon_quad_write (gdbarch, regcache, reg_scaled + i,
3773                                          val + i * unit_length);
3774                   else
3775                     {
3776                       xsnprintf (name_buf, sizeof (name_buf), "%c%d",
3777                                  reg_char, reg_scaled + i);
3778                       regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
3779                                                             strlen (name_buf));
3780                       regcache_cooked_write (regcache, regnum,
3781                                              val + i * unit_length);
3782                     }
3783                 }
3784               continue;
3785             }
3786           else
3787             {
3788               /* This CPRC could not go in VFP registers, so all VFP
3789                  registers are now marked as used.  */
3790               vfp_regs_free = 0;
3791             }
3792         }
3793
3794       /* Push stack padding for dowubleword alignment.  */
3795       if (nstack & (align - 1))
3796         {
3797           si = push_stack_item (si, val, INT_REGISTER_SIZE);
3798           nstack += INT_REGISTER_SIZE;
3799         }
3800       
3801       /* Doubleword aligned quantities must go in even register pairs.  */
3802       if (may_use_core_reg
3803           && argreg <= ARM_LAST_ARG_REGNUM
3804           && align > INT_REGISTER_SIZE
3805           && argreg & 1)
3806         argreg++;
3807
3808       /* If the argument is a pointer to a function, and it is a
3809          Thumb function, create a LOCAL copy of the value and set
3810          the THUMB bit in it.  */
3811       if (TYPE_CODE_PTR == typecode
3812           && target_type != NULL
3813           && TYPE_CODE_FUNC == TYPE_CODE (check_typedef (target_type)))
3814         {
3815           CORE_ADDR regval = extract_unsigned_integer (val, len, byte_order);
3816           if (arm_pc_is_thumb (gdbarch, regval))
3817             {
3818               bfd_byte *copy = alloca (len);
3819               store_unsigned_integer (copy, len, byte_order,
3820                                       MAKE_THUMB_ADDR (regval));
3821               val = copy;
3822             }
3823         }
3824
3825       /* Copy the argument to general registers or the stack in
3826          register-sized pieces.  Large arguments are split between
3827          registers and stack.  */
3828       while (len > 0)
3829         {
3830           int partial_len = len < INT_REGISTER_SIZE ? len : INT_REGISTER_SIZE;
3831
3832           if (may_use_core_reg && argreg <= ARM_LAST_ARG_REGNUM)
3833             {
3834               /* The argument is being passed in a general purpose
3835                  register.  */
3836               CORE_ADDR regval
3837                 = extract_unsigned_integer (val, partial_len, byte_order);
3838               if (byte_order == BFD_ENDIAN_BIG)
3839                 regval <<= (INT_REGISTER_SIZE - partial_len) * 8;
3840               if (arm_debug)
3841                 fprintf_unfiltered (gdb_stdlog, "arg %d in %s = 0x%s\n",
3842                                     argnum,
3843                                     gdbarch_register_name
3844                                       (gdbarch, argreg),
3845                                     phex (regval, INT_REGISTER_SIZE));
3846               regcache_cooked_write_unsigned (regcache, argreg, regval);
3847               argreg++;
3848             }
3849           else
3850             {
3851               /* Push the arguments onto the stack.  */
3852               if (arm_debug)
3853                 fprintf_unfiltered (gdb_stdlog, "arg %d @ sp + %d\n",
3854                                     argnum, nstack);
3855               si = push_stack_item (si, val, INT_REGISTER_SIZE);
3856               nstack += INT_REGISTER_SIZE;
3857             }
3858               
3859           len -= partial_len;
3860           val += partial_len;
3861         }
3862     }
3863   /* If we have an odd number of words to push, then decrement the stack
3864      by one word now, so first stack argument will be dword aligned.  */
3865   if (nstack & 4)
3866     sp -= 4;
3867
3868   while (si)
3869     {
3870       sp -= si->len;
3871       write_memory (sp, si->data, si->len);
3872       si = pop_stack_item (si);
3873     }
3874
3875   /* Finally, update teh SP register.  */
3876   regcache_cooked_write_unsigned (regcache, ARM_SP_REGNUM, sp);
3877
3878   return sp;
3879 }
3880
3881
3882 /* Always align the frame to an 8-byte boundary.  This is required on
3883    some platforms and harmless on the rest.  */
3884
3885 static CORE_ADDR
3886 arm_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
3887 {
3888   /* Align the stack to eight bytes.  */
3889   return sp & ~ (CORE_ADDR) 7;
3890 }
3891
3892 static void
3893 print_fpu_flags (struct ui_file *file, int flags)
3894 {
3895   if (flags & (1 << 0))
3896     fputs_filtered ("IVO ", file);
3897   if (flags & (1 << 1))
3898     fputs_filtered ("DVZ ", file);
3899   if (flags & (1 << 2))
3900     fputs_filtered ("OFL ", file);
3901   if (flags & (1 << 3))
3902     fputs_filtered ("UFL ", file);
3903   if (flags & (1 << 4))
3904     fputs_filtered ("INX ", file);
3905   fputc_filtered ('\n', file);
3906 }
3907
3908 /* Print interesting information about the floating point processor
3909    (if present) or emulator.  */
3910 static void
3911 arm_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
3912                       struct frame_info *frame, const char *args)
3913 {
3914   unsigned long status = get_frame_register_unsigned (frame, ARM_FPS_REGNUM);
3915   int type;
3916
3917   type = (status >> 24) & 127;
3918   if (status & (1 << 31))
3919     fprintf_filtered (file, _("Hardware FPU type %d\n"), type);
3920   else
3921     fprintf_filtered (file, _("Software FPU type %d\n"), type);
3922   /* i18n: [floating point unit] mask */
3923   fputs_filtered (_("mask: "), file);
3924   print_fpu_flags (file, status >> 16);
3925   /* i18n: [floating point unit] flags */
3926   fputs_filtered (_("flags: "), file);
3927   print_fpu_flags (file, status);
3928 }
3929
3930 /* Construct the ARM extended floating point type.  */
3931 static struct type *
3932 arm_ext_type (struct gdbarch *gdbarch)
3933 {
3934   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3935
3936   if (!tdep->arm_ext_type)
3937     tdep->arm_ext_type
3938       = arch_float_type (gdbarch, -1, "builtin_type_arm_ext",
3939                          floatformats_arm_ext);
3940
3941   return tdep->arm_ext_type;
3942 }
3943
3944 static struct type *
3945 arm_neon_double_type (struct gdbarch *gdbarch)
3946 {
3947   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3948
3949   if (tdep->neon_double_type == NULL)
3950     {
3951       struct type *t, *elem;
3952
3953       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_d",
3954                                TYPE_CODE_UNION);
3955       elem = builtin_type (gdbarch)->builtin_uint8;
3956       append_composite_type_field (t, "u8", init_vector_type (elem, 8));
3957       elem = builtin_type (gdbarch)->builtin_uint16;
3958       append_composite_type_field (t, "u16", init_vector_type (elem, 4));
3959       elem = builtin_type (gdbarch)->builtin_uint32;
3960       append_composite_type_field (t, "u32", init_vector_type (elem, 2));
3961       elem = builtin_type (gdbarch)->builtin_uint64;
3962       append_composite_type_field (t, "u64", elem);
3963       elem = builtin_type (gdbarch)->builtin_float;
3964       append_composite_type_field (t, "f32", init_vector_type (elem, 2));
3965       elem = builtin_type (gdbarch)->builtin_double;
3966       append_composite_type_field (t, "f64", elem);
3967
3968       TYPE_VECTOR (t) = 1;
3969       TYPE_NAME (t) = "neon_d";
3970       tdep->neon_double_type = t;
3971     }
3972
3973   return tdep->neon_double_type;
3974 }
3975
3976 /* FIXME: The vector types are not correctly ordered on big-endian
3977    targets.  Just as s0 is the low bits of d0, d0[0] is also the low
3978    bits of d0 - regardless of what unit size is being held in d0.  So
3979    the offset of the first uint8 in d0 is 7, but the offset of the
3980    first float is 4.  This code works as-is for little-endian
3981    targets.  */
3982
3983 static struct type *
3984 arm_neon_quad_type (struct gdbarch *gdbarch)
3985 {
3986   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3987
3988   if (tdep->neon_quad_type == NULL)
3989     {
3990       struct type *t, *elem;
3991
3992       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_q",
3993                                TYPE_CODE_UNION);
3994       elem = builtin_type (gdbarch)->builtin_uint8;
3995       append_composite_type_field (t, "u8", init_vector_type (elem, 16));
3996       elem = builtin_type (gdbarch)->builtin_uint16;
3997       append_composite_type_field (t, "u16", init_vector_type (elem, 8));
3998       elem = builtin_type (gdbarch)->builtin_uint32;
3999       append_composite_type_field (t, "u32", init_vector_type (elem, 4));
4000       elem = builtin_type (gdbarch)->builtin_uint64;
4001       append_composite_type_field (t, "u64", init_vector_type (elem, 2));
4002       elem = builtin_type (gdbarch)->builtin_float;
4003       append_composite_type_field (t, "f32", init_vector_type (elem, 4));
4004       elem = builtin_type (gdbarch)->builtin_double;
4005       append_composite_type_field (t, "f64", init_vector_type (elem, 2));
4006
4007       TYPE_VECTOR (t) = 1;
4008       TYPE_NAME (t) = "neon_q";
4009       tdep->neon_quad_type = t;
4010     }
4011
4012   return tdep->neon_quad_type;
4013 }
4014
4015 /* Return the GDB type object for the "standard" data type of data in
4016    register N.  */
4017
4018 static struct type *
4019 arm_register_type (struct gdbarch *gdbarch, int regnum)
4020 {
4021   int num_regs = gdbarch_num_regs (gdbarch);
4022
4023   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
4024       && regnum >= num_regs && regnum < num_regs + 32)
4025     return builtin_type (gdbarch)->builtin_float;
4026
4027   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
4028       && regnum >= num_regs + 32 && regnum < num_regs + 32 + 16)
4029     return arm_neon_quad_type (gdbarch);
4030
4031   /* If the target description has register information, we are only
4032      in this function so that we can override the types of
4033      double-precision registers for NEON.  */
4034   if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
4035     {
4036       struct type *t = tdesc_register_type (gdbarch, regnum);
4037
4038       if (regnum >= ARM_D0_REGNUM && regnum < ARM_D0_REGNUM + 32
4039           && TYPE_CODE (t) == TYPE_CODE_FLT
4040           && gdbarch_tdep (gdbarch)->have_neon)
4041         return arm_neon_double_type (gdbarch);
4042       else
4043         return t;
4044     }
4045
4046   if (regnum >= ARM_F0_REGNUM && regnum < ARM_F0_REGNUM + NUM_FREGS)
4047     {
4048       if (!gdbarch_tdep (gdbarch)->have_fpa_registers)
4049         return builtin_type (gdbarch)->builtin_void;
4050
4051       return arm_ext_type (gdbarch);
4052     }
4053   else if (regnum == ARM_SP_REGNUM)
4054     return builtin_type (gdbarch)->builtin_data_ptr;
4055   else if (regnum == ARM_PC_REGNUM)
4056     return builtin_type (gdbarch)->builtin_func_ptr;
4057   else if (regnum >= ARRAY_SIZE (arm_register_names))
4058     /* These registers are only supported on targets which supply
4059        an XML description.  */
4060     return builtin_type (gdbarch)->builtin_int0;
4061   else
4062     return builtin_type (gdbarch)->builtin_uint32;
4063 }
4064
4065 /* Map a DWARF register REGNUM onto the appropriate GDB register
4066    number.  */
4067
4068 static int
4069 arm_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
4070 {
4071   /* Core integer regs.  */
4072   if (reg >= 0 && reg <= 15)
4073     return reg;
4074
4075   /* Legacy FPA encoding.  These were once used in a way which
4076      overlapped with VFP register numbering, so their use is
4077      discouraged, but GDB doesn't support the ARM toolchain
4078      which used them for VFP.  */
4079   if (reg >= 16 && reg <= 23)
4080     return ARM_F0_REGNUM + reg - 16;
4081
4082   /* New assignments for the FPA registers.  */
4083   if (reg >= 96 && reg <= 103)
4084     return ARM_F0_REGNUM + reg - 96;
4085
4086   /* WMMX register assignments.  */
4087   if (reg >= 104 && reg <= 111)
4088     return ARM_WCGR0_REGNUM + reg - 104;
4089
4090   if (reg >= 112 && reg <= 127)
4091     return ARM_WR0_REGNUM + reg - 112;
4092
4093   if (reg >= 192 && reg <= 199)
4094     return ARM_WC0_REGNUM + reg - 192;
4095
4096   /* VFP v2 registers.  A double precision value is actually
4097      in d1 rather than s2, but the ABI only defines numbering
4098      for the single precision registers.  This will "just work"
4099      in GDB for little endian targets (we'll read eight bytes,
4100      starting in s0 and then progressing to s1), but will be
4101      reversed on big endian targets with VFP.  This won't
4102      be a problem for the new Neon quad registers; you're supposed
4103      to use DW_OP_piece for those.  */
4104   if (reg >= 64 && reg <= 95)
4105     {
4106       char name_buf[4];
4107
4108       xsnprintf (name_buf, sizeof (name_buf), "s%d", reg - 64);
4109       return user_reg_map_name_to_regnum (gdbarch, name_buf,
4110                                           strlen (name_buf));
4111     }
4112
4113   /* VFP v3 / Neon registers.  This range is also used for VFP v2
4114      registers, except that it now describes d0 instead of s0.  */
4115   if (reg >= 256 && reg <= 287)
4116     {
4117       char name_buf[4];
4118
4119       xsnprintf (name_buf, sizeof (name_buf), "d%d", reg - 256);
4120       return user_reg_map_name_to_regnum (gdbarch, name_buf,
4121                                           strlen (name_buf));
4122     }
4123
4124   return -1;
4125 }
4126
4127 /* Map GDB internal REGNUM onto the Arm simulator register numbers.  */
4128 static int
4129 arm_register_sim_regno (struct gdbarch *gdbarch, int regnum)
4130 {
4131   int reg = regnum;
4132   gdb_assert (reg >= 0 && reg < gdbarch_num_regs (gdbarch));
4133
4134   if (regnum >= ARM_WR0_REGNUM && regnum <= ARM_WR15_REGNUM)
4135     return regnum - ARM_WR0_REGNUM + SIM_ARM_IWMMXT_COP0R0_REGNUM;
4136
4137   if (regnum >= ARM_WC0_REGNUM && regnum <= ARM_WC7_REGNUM)
4138     return regnum - ARM_WC0_REGNUM + SIM_ARM_IWMMXT_COP1R0_REGNUM;
4139
4140   if (regnum >= ARM_WCGR0_REGNUM && regnum <= ARM_WCGR7_REGNUM)
4141     return regnum - ARM_WCGR0_REGNUM + SIM_ARM_IWMMXT_COP1R8_REGNUM;
4142
4143   if (reg < NUM_GREGS)
4144     return SIM_ARM_R0_REGNUM + reg;
4145   reg -= NUM_GREGS;
4146
4147   if (reg < NUM_FREGS)
4148     return SIM_ARM_FP0_REGNUM + reg;
4149   reg -= NUM_FREGS;
4150
4151   if (reg < NUM_SREGS)
4152     return SIM_ARM_FPS_REGNUM + reg;
4153   reg -= NUM_SREGS;
4154
4155   internal_error (__FILE__, __LINE__, _("Bad REGNUM %d"), regnum);
4156 }
4157
4158 /* NOTE: cagney/2001-08-20: Both convert_from_extended() and
4159    convert_to_extended() use floatformat_arm_ext_littlebyte_bigword.
4160    It is thought that this is is the floating-point register format on
4161    little-endian systems.  */
4162
4163 static void
4164 convert_from_extended (const struct floatformat *fmt, const void *ptr,
4165                        void *dbl, int endianess)
4166 {
4167   DOUBLEST d;
4168
4169   if (endianess == BFD_ENDIAN_BIG)
4170     floatformat_to_doublest (&floatformat_arm_ext_big, ptr, &d);
4171   else
4172     floatformat_to_doublest (&floatformat_arm_ext_littlebyte_bigword,
4173                              ptr, &d);
4174   floatformat_from_doublest (fmt, &d, dbl);
4175 }
4176
4177 static void
4178 convert_to_extended (const struct floatformat *fmt, void *dbl, const void *ptr,
4179                      int endianess)
4180 {
4181   DOUBLEST d;
4182
4183   floatformat_to_doublest (fmt, ptr, &d);
4184   if (endianess == BFD_ENDIAN_BIG)
4185     floatformat_from_doublest (&floatformat_arm_ext_big, &d, dbl);
4186   else
4187     floatformat_from_doublest (&floatformat_arm_ext_littlebyte_bigword,
4188                                &d, dbl);
4189 }
4190
4191 static int
4192 condition_true (unsigned long cond, unsigned long status_reg)
4193 {
4194   if (cond == INST_AL || cond == INST_NV)
4195     return 1;
4196
4197   switch (cond)
4198     {
4199     case INST_EQ:
4200       return ((status_reg & FLAG_Z) != 0);
4201     case INST_NE:
4202       return ((status_reg & FLAG_Z) == 0);
4203     case INST_CS:
4204       return ((status_reg & FLAG_C) != 0);
4205     case INST_CC:
4206       return ((status_reg & FLAG_C) == 0);
4207     case INST_MI:
4208       return ((status_reg & FLAG_N) != 0);
4209     case INST_PL:
4210       return ((status_reg & FLAG_N) == 0);
4211     case INST_VS:
4212       return ((status_reg & FLAG_V) != 0);
4213     case INST_VC:
4214       return ((status_reg & FLAG_V) == 0);
4215     case INST_HI:
4216       return ((status_reg & (FLAG_C | FLAG_Z)) == FLAG_C);
4217     case INST_LS:
4218       return ((status_reg & (FLAG_C | FLAG_Z)) != FLAG_C);
4219     case INST_GE:
4220       return (((status_reg & FLAG_N) == 0) == ((status_reg & FLAG_V) == 0));
4221     case INST_LT:
4222       return (((status_reg & FLAG_N) == 0) != ((status_reg & FLAG_V) == 0));
4223     case INST_GT:
4224       return (((status_reg & FLAG_Z) == 0)
4225               && (((status_reg & FLAG_N) == 0)
4226                   == ((status_reg & FLAG_V) == 0)));
4227     case INST_LE:
4228       return (((status_reg & FLAG_Z) != 0)
4229               || (((status_reg & FLAG_N) == 0)
4230                   != ((status_reg & FLAG_V) == 0)));
4231     }
4232   return 1;
4233 }
4234
4235 static unsigned long
4236 shifted_reg_val (struct frame_info *frame, unsigned long inst, int carry,
4237                  unsigned long pc_val, unsigned long status_reg)
4238 {
4239   unsigned long res, shift;
4240   int rm = bits (inst, 0, 3);
4241   unsigned long shifttype = bits (inst, 5, 6);
4242
4243   if (bit (inst, 4))
4244     {
4245       int rs = bits (inst, 8, 11);
4246       shift = (rs == 15 ? pc_val + 8
4247                         : get_frame_register_unsigned (frame, rs)) & 0xFF;
4248     }
4249   else
4250     shift = bits (inst, 7, 11);
4251
4252   res = (rm == ARM_PC_REGNUM
4253          ? (pc_val + (bit (inst, 4) ? 12 : 8))
4254          : get_frame_register_unsigned (frame, rm));
4255
4256   switch (shifttype)
4257     {
4258     case 0:                     /* LSL */
4259       res = shift >= 32 ? 0 : res << shift;
4260       break;
4261
4262     case 1:                     /* LSR */
4263       res = shift >= 32 ? 0 : res >> shift;
4264       break;
4265
4266     case 2:                     /* ASR */
4267       if (shift >= 32)
4268         shift = 31;
4269       res = ((res & 0x80000000L)
4270              ? ~((~res) >> shift) : res >> shift);
4271       break;
4272
4273     case 3:                     /* ROR/RRX */
4274       shift &= 31;
4275       if (shift == 0)
4276         res = (res >> 1) | (carry ? 0x80000000L : 0);
4277       else
4278         res = (res >> shift) | (res << (32 - shift));
4279       break;
4280     }
4281
4282   return res & 0xffffffff;
4283 }
4284
4285 /* Return number of 1-bits in VAL.  */
4286
4287 static int
4288 bitcount (unsigned long val)
4289 {
4290   int nbits;
4291   for (nbits = 0; val != 0; nbits++)
4292     val &= val - 1;             /* Delete rightmost 1-bit in val.  */
4293   return nbits;
4294 }
4295
4296 /* Return the size in bytes of the complete Thumb instruction whose
4297    first halfword is INST1.  */
4298
4299 static int
4300 thumb_insn_size (unsigned short inst1)
4301 {
4302   if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
4303     return 4;
4304   else
4305     return 2;
4306 }
4307
4308 static int
4309 thumb_advance_itstate (unsigned int itstate)
4310 {
4311   /* Preserve IT[7:5], the first three bits of the condition.  Shift
4312      the upcoming condition flags left by one bit.  */
4313   itstate = (itstate & 0xe0) | ((itstate << 1) & 0x1f);
4314
4315   /* If we have finished the IT block, clear the state.  */
4316   if ((itstate & 0x0f) == 0)
4317     itstate = 0;
4318
4319   return itstate;
4320 }
4321
4322 /* Find the next PC after the current instruction executes.  In some
4323    cases we can not statically determine the answer (see the IT state
4324    handling in this function); in that case, a breakpoint may be
4325    inserted in addition to the returned PC, which will be used to set
4326    another breakpoint by our caller.  */
4327
4328 static CORE_ADDR
4329 thumb_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc)
4330 {
4331   struct gdbarch *gdbarch = get_frame_arch (frame);
4332   struct address_space *aspace = get_frame_address_space (frame);
4333   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4334   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4335   unsigned long pc_val = ((unsigned long) pc) + 4;      /* PC after prefetch */
4336   unsigned short inst1;
4337   CORE_ADDR nextpc = pc + 2;            /* Default is next instruction.  */
4338   unsigned long offset;
4339   ULONGEST status, itstate;
4340
4341   nextpc = MAKE_THUMB_ADDR (nextpc);
4342   pc_val = MAKE_THUMB_ADDR (pc_val);
4343
4344   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
4345
4346   /* Thumb-2 conditional execution support.  There are eight bits in
4347      the CPSR which describe conditional execution state.  Once
4348      reconstructed (they're in a funny order), the low five bits
4349      describe the low bit of the condition for each instruction and
4350      how many instructions remain.  The high three bits describe the
4351      base condition.  One of the low four bits will be set if an IT
4352      block is active.  These bits read as zero on earlier
4353      processors.  */
4354   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4355   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
4356
4357   /* If-Then handling.  On GNU/Linux, where this routine is used, we
4358      use an undefined instruction as a breakpoint.  Unlike BKPT, IT
4359      can disable execution of the undefined instruction.  So we might
4360      miss the breakpoint if we set it on a skipped conditional
4361      instruction.  Because conditional instructions can change the
4362      flags, affecting the execution of further instructions, we may
4363      need to set two breakpoints.  */
4364
4365   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint != NULL)
4366     {
4367       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
4368         {
4369           /* An IT instruction.  Because this instruction does not
4370              modify the flags, we can accurately predict the next
4371              executed instruction.  */
4372           itstate = inst1 & 0x00ff;
4373           pc += thumb_insn_size (inst1);
4374
4375           while (itstate != 0 && ! condition_true (itstate >> 4, status))
4376             {
4377               inst1 = read_memory_unsigned_integer (pc, 2,
4378                                                     byte_order_for_code);
4379               pc += thumb_insn_size (inst1);
4380               itstate = thumb_advance_itstate (itstate);
4381             }
4382
4383           return MAKE_THUMB_ADDR (pc);
4384         }
4385       else if (itstate != 0)
4386         {
4387           /* We are in a conditional block.  Check the condition.  */
4388           if (! condition_true (itstate >> 4, status))
4389             {
4390               /* Advance to the next executed instruction.  */
4391               pc += thumb_insn_size (inst1);
4392               itstate = thumb_advance_itstate (itstate);
4393
4394               while (itstate != 0 && ! condition_true (itstate >> 4, status))
4395                 {
4396                   inst1 = read_memory_unsigned_integer (pc, 2, 
4397                                                         byte_order_for_code);
4398                   pc += thumb_insn_size (inst1);
4399                   itstate = thumb_advance_itstate (itstate);
4400                 }
4401
4402               return MAKE_THUMB_ADDR (pc);
4403             }
4404           else if ((itstate & 0x0f) == 0x08)
4405             {
4406               /* This is the last instruction of the conditional
4407                  block, and it is executed.  We can handle it normally
4408                  because the following instruction is not conditional,
4409                  and we must handle it normally because it is
4410                  permitted to branch.  Fall through.  */
4411             }
4412           else
4413             {
4414               int cond_negated;
4415
4416               /* There are conditional instructions after this one.
4417                  If this instruction modifies the flags, then we can
4418                  not predict what the next executed instruction will
4419                  be.  Fortunately, this instruction is architecturally
4420                  forbidden to branch; we know it will fall through.
4421                  Start by skipping past it.  */
4422               pc += thumb_insn_size (inst1);
4423               itstate = thumb_advance_itstate (itstate);
4424
4425               /* Set a breakpoint on the following instruction.  */
4426               gdb_assert ((itstate & 0x0f) != 0);
4427               arm_insert_single_step_breakpoint (gdbarch, aspace,
4428                                                  MAKE_THUMB_ADDR (pc));
4429               cond_negated = (itstate >> 4) & 1;
4430
4431               /* Skip all following instructions with the same
4432                  condition.  If there is a later instruction in the IT
4433                  block with the opposite condition, set the other
4434                  breakpoint there.  If not, then set a breakpoint on
4435                  the instruction after the IT block.  */
4436               do
4437                 {
4438                   inst1 = read_memory_unsigned_integer (pc, 2,
4439                                                         byte_order_for_code);
4440                   pc += thumb_insn_size (inst1);
4441                   itstate = thumb_advance_itstate (itstate);
4442                 }
4443               while (itstate != 0 && ((itstate >> 4) & 1) == cond_negated);
4444
4445               return MAKE_THUMB_ADDR (pc);
4446             }
4447         }
4448     }
4449   else if (itstate & 0x0f)
4450     {
4451       /* We are in a conditional block.  Check the condition.  */
4452       int cond = itstate >> 4;
4453
4454       if (! condition_true (cond, status))
4455         /* Advance to the next instruction.  All the 32-bit
4456            instructions share a common prefix.  */
4457         return MAKE_THUMB_ADDR (pc + thumb_insn_size (inst1));
4458
4459       /* Otherwise, handle the instruction normally.  */
4460     }
4461
4462   if ((inst1 & 0xff00) == 0xbd00)       /* pop {rlist, pc} */
4463     {
4464       CORE_ADDR sp;
4465
4466       /* Fetch the saved PC from the stack.  It's stored above
4467          all of the other registers.  */
4468       offset = bitcount (bits (inst1, 0, 7)) * INT_REGISTER_SIZE;
4469       sp = get_frame_register_unsigned (frame, ARM_SP_REGNUM);
4470       nextpc = read_memory_unsigned_integer (sp + offset, 4, byte_order);
4471     }
4472   else if ((inst1 & 0xf000) == 0xd000)  /* conditional branch */
4473     {
4474       unsigned long cond = bits (inst1, 8, 11);
4475       if (cond == 0x0f)  /* 0x0f = SWI */
4476         {
4477           struct gdbarch_tdep *tdep;
4478           tdep = gdbarch_tdep (gdbarch);
4479
4480           if (tdep->syscall_next_pc != NULL)
4481             nextpc = tdep->syscall_next_pc (frame);
4482
4483         }
4484       else if (cond != 0x0f && condition_true (cond, status))
4485         nextpc = pc_val + (sbits (inst1, 0, 7) << 1);
4486     }
4487   else if ((inst1 & 0xf800) == 0xe000)  /* unconditional branch */
4488     {
4489       nextpc = pc_val + (sbits (inst1, 0, 10) << 1);
4490     }
4491   else if (thumb_insn_size (inst1) == 4) /* 32-bit instruction */
4492     {
4493       unsigned short inst2;
4494       inst2 = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
4495
4496       /* Default to the next instruction.  */
4497       nextpc = pc + 4;
4498       nextpc = MAKE_THUMB_ADDR (nextpc);
4499
4500       if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
4501         {
4502           /* Branches and miscellaneous control instructions.  */
4503
4504           if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
4505             {
4506               /* B, BL, BLX.  */
4507               int j1, j2, imm1, imm2;
4508
4509               imm1 = sbits (inst1, 0, 10);
4510               imm2 = bits (inst2, 0, 10);
4511               j1 = bit (inst2, 13);
4512               j2 = bit (inst2, 11);
4513
4514               offset = ((imm1 << 12) + (imm2 << 1));
4515               offset ^= ((!j2) << 22) | ((!j1) << 23);
4516
4517               nextpc = pc_val + offset;
4518               /* For BLX make sure to clear the low bits.  */
4519               if (bit (inst2, 12) == 0)
4520                 nextpc = nextpc & 0xfffffffc;
4521             }
4522           else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
4523             {
4524               /* SUBS PC, LR, #imm8.  */
4525               nextpc = get_frame_register_unsigned (frame, ARM_LR_REGNUM);
4526               nextpc -= inst2 & 0x00ff;
4527             }
4528           else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
4529             {
4530               /* Conditional branch.  */
4531               if (condition_true (bits (inst1, 6, 9), status))
4532                 {
4533                   int sign, j1, j2, imm1, imm2;
4534
4535                   sign = sbits (inst1, 10, 10);
4536                   imm1 = bits (inst1, 0, 5);
4537                   imm2 = bits (inst2, 0, 10);
4538                   j1 = bit (inst2, 13);
4539                   j2 = bit (inst2, 11);
4540
4541                   offset = (sign << 20) + (j2 << 19) + (j1 << 18);
4542                   offset += (imm1 << 12) + (imm2 << 1);
4543
4544                   nextpc = pc_val + offset;
4545                 }
4546             }
4547         }
4548       else if ((inst1 & 0xfe50) == 0xe810)
4549         {
4550           /* Load multiple or RFE.  */
4551           int rn, offset, load_pc = 1;
4552
4553           rn = bits (inst1, 0, 3);
4554           if (bit (inst1, 7) && !bit (inst1, 8))
4555             {
4556               /* LDMIA or POP */
4557               if (!bit (inst2, 15))
4558                 load_pc = 0;
4559               offset = bitcount (inst2) * 4 - 4;
4560             }
4561           else if (!bit (inst1, 7) && bit (inst1, 8))
4562             {
4563               /* LDMDB */
4564               if (!bit (inst2, 15))
4565                 load_pc = 0;
4566               offset = -4;
4567             }
4568           else if (bit (inst1, 7) && bit (inst1, 8))
4569             {
4570               /* RFEIA */
4571               offset = 0;
4572             }
4573           else if (!bit (inst1, 7) && !bit (inst1, 8))
4574             {
4575               /* RFEDB */
4576               offset = -8;
4577             }
4578           else
4579             load_pc = 0;
4580
4581           if (load_pc)
4582             {
4583               CORE_ADDR addr = get_frame_register_unsigned (frame, rn);
4584               nextpc = get_frame_memory_unsigned (frame, addr + offset, 4);
4585             }
4586         }
4587       else if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
4588         {
4589           /* MOV PC or MOVS PC.  */
4590           nextpc = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4591           nextpc = MAKE_THUMB_ADDR (nextpc);
4592         }
4593       else if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
4594         {
4595           /* LDR PC.  */
4596           CORE_ADDR base;
4597           int rn, load_pc = 1;
4598
4599           rn = bits (inst1, 0, 3);
4600           base = get_frame_register_unsigned (frame, rn);
4601           if (rn == ARM_PC_REGNUM)
4602             {
4603               base = (base + 4) & ~(CORE_ADDR) 0x3;
4604               if (bit (inst1, 7))
4605                 base += bits (inst2, 0, 11);
4606               else
4607                 base -= bits (inst2, 0, 11);
4608             }
4609           else if (bit (inst1, 7))
4610             base += bits (inst2, 0, 11);
4611           else if (bit (inst2, 11))
4612             {
4613               if (bit (inst2, 10))
4614                 {
4615                   if (bit (inst2, 9))
4616                     base += bits (inst2, 0, 7);
4617                   else
4618                     base -= bits (inst2, 0, 7);
4619                 }
4620             }
4621           else if ((inst2 & 0x0fc0) == 0x0000)
4622             {
4623               int shift = bits (inst2, 4, 5), rm = bits (inst2, 0, 3);
4624               base += get_frame_register_unsigned (frame, rm) << shift;
4625             }
4626           else
4627             /* Reserved.  */
4628             load_pc = 0;
4629
4630           if (load_pc)
4631             nextpc = get_frame_memory_unsigned (frame, base, 4);
4632         }
4633       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
4634         {
4635           /* TBB.  */
4636           CORE_ADDR tbl_reg, table, offset, length;
4637
4638           tbl_reg = bits (inst1, 0, 3);
4639           if (tbl_reg == 0x0f)
4640             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4641           else
4642             table = get_frame_register_unsigned (frame, tbl_reg);
4643
4644           offset = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4645           length = 2 * get_frame_memory_unsigned (frame, table + offset, 1);
4646           nextpc = pc_val + length;
4647         }
4648       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
4649         {
4650           /* TBH.  */
4651           CORE_ADDR tbl_reg, table, offset, length;
4652
4653           tbl_reg = bits (inst1, 0, 3);
4654           if (tbl_reg == 0x0f)
4655             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4656           else
4657             table = get_frame_register_unsigned (frame, tbl_reg);
4658
4659           offset = 2 * get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4660           length = 2 * get_frame_memory_unsigned (frame, table + offset, 2);
4661           nextpc = pc_val + length;
4662         }
4663     }
4664   else if ((inst1 & 0xff00) == 0x4700)  /* bx REG, blx REG */
4665     {
4666       if (bits (inst1, 3, 6) == 0x0f)
4667         nextpc = UNMAKE_THUMB_ADDR (pc_val);
4668       else
4669         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4670     }
4671   else if ((inst1 & 0xff87) == 0x4687)  /* mov pc, REG */
4672     {
4673       if (bits (inst1, 3, 6) == 0x0f)
4674         nextpc = pc_val;
4675       else
4676         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4677
4678       nextpc = MAKE_THUMB_ADDR (nextpc);
4679     }
4680   else if ((inst1 & 0xf500) == 0xb100)
4681     {
4682       /* CBNZ or CBZ.  */
4683       int imm = (bit (inst1, 9) << 6) + (bits (inst1, 3, 7) << 1);
4684       ULONGEST reg = get_frame_register_unsigned (frame, bits (inst1, 0, 2));
4685
4686       if (bit (inst1, 11) && reg != 0)
4687         nextpc = pc_val + imm;
4688       else if (!bit (inst1, 11) && reg == 0)
4689         nextpc = pc_val + imm;
4690     }
4691   return nextpc;
4692 }
4693
4694 /* Get the raw next address.  PC is the current program counter, in 
4695    FRAME, which is assumed to be executing in ARM mode.
4696
4697    The value returned has the execution state of the next instruction 
4698    encoded in it.  Use IS_THUMB_ADDR () to see whether the instruction is
4699    in Thumb-State, and gdbarch_addr_bits_remove () to get the plain memory
4700    address.  */
4701
4702 static CORE_ADDR
4703 arm_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc)
4704 {
4705   struct gdbarch *gdbarch = get_frame_arch (frame);
4706   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4707   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4708   unsigned long pc_val;
4709   unsigned long this_instr;
4710   unsigned long status;
4711   CORE_ADDR nextpc;
4712
4713   pc_val = (unsigned long) pc;
4714   this_instr = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
4715
4716   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4717   nextpc = (CORE_ADDR) (pc_val + 4);    /* Default case */
4718
4719   if (bits (this_instr, 28, 31) == INST_NV)
4720     switch (bits (this_instr, 24, 27))
4721       {
4722       case 0xa:
4723       case 0xb:
4724         {
4725           /* Branch with Link and change to Thumb.  */
4726           nextpc = BranchDest (pc, this_instr);
4727           nextpc |= bit (this_instr, 24) << 1;
4728           nextpc = MAKE_THUMB_ADDR (nextpc);
4729           break;
4730         }
4731       case 0xc:
4732       case 0xd:
4733       case 0xe:
4734         /* Coprocessor register transfer.  */
4735         if (bits (this_instr, 12, 15) == 15)
4736           error (_("Invalid update to pc in instruction"));
4737         break;
4738       }
4739   else if (condition_true (bits (this_instr, 28, 31), status))
4740     {
4741       switch (bits (this_instr, 24, 27))
4742         {
4743         case 0x0:
4744         case 0x1:                       /* data processing */
4745         case 0x2:
4746         case 0x3:
4747           {
4748             unsigned long operand1, operand2, result = 0;
4749             unsigned long rn;
4750             int c;
4751
4752             if (bits (this_instr, 12, 15) != 15)
4753               break;
4754
4755             if (bits (this_instr, 22, 25) == 0
4756                 && bits (this_instr, 4, 7) == 9)        /* multiply */
4757               error (_("Invalid update to pc in instruction"));
4758
4759             /* BX <reg>, BLX <reg> */
4760             if (bits (this_instr, 4, 27) == 0x12fff1
4761                 || bits (this_instr, 4, 27) == 0x12fff3)
4762               {
4763                 rn = bits (this_instr, 0, 3);
4764                 nextpc = ((rn == ARM_PC_REGNUM)
4765                           ? (pc_val + 8)
4766                           : get_frame_register_unsigned (frame, rn));
4767
4768                 return nextpc;
4769               }
4770
4771             /* Multiply into PC.  */
4772             c = (status & FLAG_C) ? 1 : 0;
4773             rn = bits (this_instr, 16, 19);
4774             operand1 = ((rn == ARM_PC_REGNUM)
4775                         ? (pc_val + 8)
4776                         : get_frame_register_unsigned (frame, rn));
4777
4778             if (bit (this_instr, 25))
4779               {
4780                 unsigned long immval = bits (this_instr, 0, 7);
4781                 unsigned long rotate = 2 * bits (this_instr, 8, 11);
4782                 operand2 = ((immval >> rotate) | (immval << (32 - rotate)))
4783                   & 0xffffffff;
4784               }
4785             else                /* operand 2 is a shifted register.  */
4786               operand2 = shifted_reg_val (frame, this_instr, c,
4787                                           pc_val, status);
4788
4789             switch (bits (this_instr, 21, 24))
4790               {
4791               case 0x0: /*and */
4792                 result = operand1 & operand2;
4793                 break;
4794
4795               case 0x1: /*eor */
4796                 result = operand1 ^ operand2;
4797                 break;
4798
4799               case 0x2: /*sub */
4800                 result = operand1 - operand2;
4801                 break;
4802
4803               case 0x3: /*rsb */
4804                 result = operand2 - operand1;
4805                 break;
4806
4807               case 0x4: /*add */
4808                 result = operand1 + operand2;
4809                 break;
4810
4811               case 0x5: /*adc */
4812                 result = operand1 + operand2 + c;
4813                 break;
4814
4815               case 0x6: /*sbc */
4816                 result = operand1 - operand2 + c;
4817                 break;
4818
4819               case 0x7: /*rsc */
4820                 result = operand2 - operand1 + c;
4821                 break;
4822
4823               case 0x8:
4824               case 0x9:
4825               case 0xa:
4826               case 0xb: /* tst, teq, cmp, cmn */
4827                 result = (unsigned long) nextpc;
4828                 break;
4829
4830               case 0xc: /*orr */
4831                 result = operand1 | operand2;
4832                 break;
4833
4834               case 0xd: /*mov */
4835                 /* Always step into a function.  */
4836                 result = operand2;
4837                 break;
4838
4839               case 0xe: /*bic */
4840                 result = operand1 & ~operand2;
4841                 break;
4842
4843               case 0xf: /*mvn */
4844                 result = ~operand2;
4845                 break;
4846               }
4847
4848             /* In 26-bit APCS the bottom two bits of the result are 
4849                ignored, and we always end up in ARM state.  */
4850             if (!arm_apcs_32)
4851               nextpc = arm_addr_bits_remove (gdbarch, result);
4852             else
4853               nextpc = result;
4854
4855             break;
4856           }
4857
4858         case 0x4:
4859         case 0x5:               /* data transfer */
4860         case 0x6:
4861         case 0x7:
4862           if (bit (this_instr, 20))
4863             {
4864               /* load */
4865               if (bits (this_instr, 12, 15) == 15)
4866                 {
4867                   /* rd == pc */
4868                   unsigned long rn;
4869                   unsigned long base;
4870
4871                   if (bit (this_instr, 22))
4872                     error (_("Invalid update to pc in instruction"));
4873
4874                   /* byte write to PC */
4875                   rn = bits (this_instr, 16, 19);
4876                   base = ((rn == ARM_PC_REGNUM)
4877                           ? (pc_val + 8)
4878                           : get_frame_register_unsigned (frame, rn));
4879
4880                   if (bit (this_instr, 24))
4881                     {
4882                       /* pre-indexed */
4883                       int c = (status & FLAG_C) ? 1 : 0;
4884                       unsigned long offset =
4885                       (bit (this_instr, 25)
4886                        ? shifted_reg_val (frame, this_instr, c, pc_val, status)
4887                        : bits (this_instr, 0, 11));
4888
4889                       if (bit (this_instr, 23))
4890                         base += offset;
4891                       else
4892                         base -= offset;
4893                     }
4894                   nextpc =
4895                     (CORE_ADDR) read_memory_unsigned_integer ((CORE_ADDR) base,
4896                                                               4, byte_order);
4897                 }
4898             }
4899           break;
4900
4901         case 0x8:
4902         case 0x9:               /* block transfer */
4903           if (bit (this_instr, 20))
4904             {
4905               /* LDM */
4906               if (bit (this_instr, 15))
4907                 {
4908                   /* loading pc */
4909                   int offset = 0;
4910                   unsigned long rn_val
4911                     = get_frame_register_unsigned (frame,
4912                                                    bits (this_instr, 16, 19));
4913
4914                   if (bit (this_instr, 23))
4915                     {
4916                       /* up */
4917                       unsigned long reglist = bits (this_instr, 0, 14);
4918                       offset = bitcount (reglist) * 4;
4919                       if (bit (this_instr, 24))         /* pre */
4920                         offset += 4;
4921                     }
4922                   else if (bit (this_instr, 24))
4923                     offset = -4;
4924
4925                   nextpc =
4926                     (CORE_ADDR) read_memory_unsigned_integer ((CORE_ADDR)
4927                                                               (rn_val + offset),
4928                                                               4, byte_order);
4929                 }
4930             }
4931           break;
4932
4933         case 0xb:               /* branch & link */
4934         case 0xa:               /* branch */
4935           {
4936             nextpc = BranchDest (pc, this_instr);
4937             break;
4938           }
4939
4940         case 0xc:
4941         case 0xd:
4942         case 0xe:               /* coproc ops */
4943           break;
4944         case 0xf:               /* SWI */
4945           {
4946             struct gdbarch_tdep *tdep;
4947             tdep = gdbarch_tdep (gdbarch);
4948
4949             if (tdep->syscall_next_pc != NULL)
4950               nextpc = tdep->syscall_next_pc (frame);
4951
4952           }
4953           break;
4954
4955         default:
4956           fprintf_filtered (gdb_stderr, _("Bad bit-field extraction\n"));
4957           return (pc);
4958         }
4959     }
4960
4961   return nextpc;
4962 }
4963
4964 /* Determine next PC after current instruction executes.  Will call either
4965    arm_get_next_pc_raw or thumb_get_next_pc_raw.  Error out if infinite
4966    loop is detected.  */
4967
4968 CORE_ADDR
4969 arm_get_next_pc (struct frame_info *frame, CORE_ADDR pc)
4970 {
4971   CORE_ADDR nextpc;
4972
4973   if (arm_frame_is_thumb (frame))
4974     nextpc = thumb_get_next_pc_raw (frame, pc);
4975   else
4976     nextpc = arm_get_next_pc_raw (frame, pc);
4977
4978   return nextpc;
4979 }
4980
4981 /* Like insert_single_step_breakpoint, but make sure we use a breakpoint
4982    of the appropriate mode (as encoded in the PC value), even if this
4983    differs from what would be expected according to the symbol tables.  */
4984
4985 void
4986 arm_insert_single_step_breakpoint (struct gdbarch *gdbarch,
4987                                    struct address_space *aspace,
4988                                    CORE_ADDR pc)
4989 {
4990   struct cleanup *old_chain
4991     = make_cleanup_restore_integer (&arm_override_mode);
4992
4993   arm_override_mode = IS_THUMB_ADDR (pc);
4994   pc = gdbarch_addr_bits_remove (gdbarch, pc);
4995
4996   insert_single_step_breakpoint (gdbarch, aspace, pc);
4997
4998   do_cleanups (old_chain);
4999 }
5000
5001 /* Checks for an atomic sequence of instructions beginning with a LDREX{,B,H,D}
5002    instruction and ending with a STREX{,B,H,D} instruction.  If such a sequence
5003    is found, attempt to step through it.  A breakpoint is placed at the end of
5004    the sequence.  */
5005
5006 static int
5007 thumb_deal_with_atomic_sequence_raw (struct frame_info *frame)
5008 {
5009   struct gdbarch *gdbarch = get_frame_arch (frame);
5010   struct address_space *aspace = get_frame_address_space (frame);
5011   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
5012   CORE_ADDR pc = get_frame_pc (frame);
5013   CORE_ADDR breaks[2] = {-1, -1};
5014   CORE_ADDR loc = pc;
5015   unsigned short insn1, insn2;
5016   int insn_count;
5017   int index;
5018   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
5019   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
5020   ULONGEST status, itstate;
5021
5022   /* We currently do not support atomic sequences within an IT block.  */
5023   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
5024   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
5025   if (itstate & 0x0f)
5026     return 0;
5027
5028   /* Assume all atomic sequences start with a ldrex{,b,h,d} instruction.  */
5029   insn1 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5030   loc += 2;
5031   if (thumb_insn_size (insn1) != 4)
5032     return 0;
5033
5034   insn2 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5035   loc += 2;
5036   if (!((insn1 & 0xfff0) == 0xe850
5037         || ((insn1 & 0xfff0) == 0xe8d0 && (insn2 & 0x00c0) == 0x0040)))
5038     return 0;
5039
5040   /* Assume that no atomic sequence is longer than "atomic_sequence_length"
5041      instructions.  */
5042   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
5043     {
5044       insn1 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5045       loc += 2;
5046
5047       if (thumb_insn_size (insn1) != 4)
5048         {
5049           /* Assume that there is at most one conditional branch in the
5050              atomic sequence.  If a conditional branch is found, put a
5051              breakpoint in its destination address.  */
5052           if ((insn1 & 0xf000) == 0xd000 && bits (insn1, 8, 11) != 0x0f)
5053             {
5054               if (last_breakpoint > 0)
5055                 return 0; /* More than one conditional branch found,
5056                              fallback to the standard code.  */
5057
5058               breaks[1] = loc + 2 + (sbits (insn1, 0, 7) << 1);
5059               last_breakpoint++;
5060             }
5061
5062           /* We do not support atomic sequences that use any *other*
5063              instructions but conditional branches to change the PC.
5064              Fall back to standard code to avoid losing control of
5065              execution.  */
5066           else if (thumb_instruction_changes_pc (insn1))
5067             return 0;
5068         }
5069       else
5070         {
5071           insn2 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5072           loc += 2;
5073
5074           /* Assume that there is at most one conditional branch in the
5075              atomic sequence.  If a conditional branch is found, put a
5076              breakpoint in its destination address.  */
5077           if ((insn1 & 0xf800) == 0xf000
5078               && (insn2 & 0xd000) == 0x8000
5079               && (insn1 & 0x0380) != 0x0380)
5080             {
5081               int sign, j1, j2, imm1, imm2;
5082               unsigned int offset;
5083
5084               sign = sbits (insn1, 10, 10);
5085               imm1 = bits (insn1, 0, 5);
5086               imm2 = bits (insn2, 0, 10);
5087               j1 = bit (insn2, 13);
5088               j2 = bit (insn2, 11);
5089
5090               offset = (sign << 20) + (j2 << 19) + (j1 << 18);
5091               offset += (imm1 << 12) + (imm2 << 1);
5092
5093               if (last_breakpoint > 0)
5094                 return 0; /* More than one conditional branch found,
5095                              fallback to the standard code.  */
5096
5097               breaks[1] = loc + offset;
5098               last_breakpoint++;
5099             }
5100
5101           /* We do not support atomic sequences that use any *other*
5102              instructions but conditional branches to change the PC.
5103              Fall back to standard code to avoid losing control of
5104              execution.  */
5105           else if (thumb2_instruction_changes_pc (insn1, insn2))
5106             return 0;
5107
5108           /* If we find a strex{,b,h,d}, we're done.  */
5109           if ((insn1 & 0xfff0) == 0xe840
5110               || ((insn1 & 0xfff0) == 0xe8c0 && (insn2 & 0x00c0) == 0x0040))
5111             break;
5112         }
5113     }
5114
5115   /* If we didn't find the strex{,b,h,d}, we cannot handle the sequence.  */
5116   if (insn_count == atomic_sequence_length)
5117     return 0;
5118
5119   /* Insert a breakpoint right after the end of the atomic sequence.  */
5120   breaks[0] = loc;
5121
5122   /* Check for duplicated breakpoints.  Check also for a breakpoint
5123      placed (branch instruction's destination) anywhere in sequence.  */
5124   if (last_breakpoint
5125       && (breaks[1] == breaks[0]
5126           || (breaks[1] >= pc && breaks[1] < loc)))
5127     last_breakpoint = 0;
5128
5129   /* Effectively inserts the breakpoints.  */
5130   for (index = 0; index <= last_breakpoint; index++)
5131     arm_insert_single_step_breakpoint (gdbarch, aspace,
5132                                        MAKE_THUMB_ADDR (breaks[index]));
5133
5134   return 1;
5135 }
5136
5137 static int
5138 arm_deal_with_atomic_sequence_raw (struct frame_info *frame)
5139 {
5140   struct gdbarch *gdbarch = get_frame_arch (frame);
5141   struct address_space *aspace = get_frame_address_space (frame);
5142   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
5143   CORE_ADDR pc = get_frame_pc (frame);
5144   CORE_ADDR breaks[2] = {-1, -1};
5145   CORE_ADDR loc = pc;
5146   unsigned int insn;
5147   int insn_count;
5148   int index;
5149   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
5150   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
5151
5152   /* Assume all atomic sequences start with a ldrex{,b,h,d} instruction.
5153      Note that we do not currently support conditionally executed atomic
5154      instructions.  */
5155   insn = read_memory_unsigned_integer (loc, 4, byte_order_for_code);
5156   loc += 4;
5157   if ((insn & 0xff9000f0) != 0xe1900090)
5158     return 0;
5159
5160   /* Assume that no atomic sequence is longer than "atomic_sequence_length"
5161      instructions.  */
5162   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
5163     {
5164       insn = read_memory_unsigned_integer (loc, 4, byte_order_for_code);
5165       loc += 4;
5166
5167       /* Assume that there is at most one conditional branch in the atomic
5168          sequence.  If a conditional branch is found, put a breakpoint in
5169          its destination address.  */
5170       if (bits (insn, 24, 27) == 0xa)
5171         {
5172           if (last_breakpoint > 0)
5173             return 0; /* More than one conditional branch found, fallback
5174                          to the standard single-step code.  */
5175
5176           breaks[1] = BranchDest (loc - 4, insn);
5177           last_breakpoint++;
5178         }
5179
5180       /* We do not support atomic sequences that use any *other* instructions
5181          but conditional branches to change the PC.  Fall back to standard
5182          code to avoid losing control of execution.  */
5183       else if (arm_instruction_changes_pc (insn))
5184         return 0;
5185
5186       /* If we find a strex{,b,h,d}, we're done.  */
5187       if ((insn & 0xff9000f0) == 0xe1800090)
5188         break;
5189     }
5190
5191   /* If we didn't find the strex{,b,h,d}, we cannot handle the sequence.  */
5192   if (insn_count == atomic_sequence_length)
5193     return 0;
5194
5195   /* Insert a breakpoint right after the end of the atomic sequence.  */
5196   breaks[0] = loc;
5197
5198   /* Check for duplicated breakpoints.  Check also for a breakpoint
5199      placed (branch instruction's destination) anywhere in sequence.  */
5200   if (last_breakpoint
5201       && (breaks[1] == breaks[0]
5202           || (breaks[1] >= pc && breaks[1] < loc)))
5203     last_breakpoint = 0;
5204
5205   /* Effectively inserts the breakpoints.  */
5206   for (index = 0; index <= last_breakpoint; index++)
5207     arm_insert_single_step_breakpoint (gdbarch, aspace, breaks[index]);
5208
5209   return 1;
5210 }
5211
5212 int
5213 arm_deal_with_atomic_sequence (struct frame_info *frame)
5214 {
5215   if (arm_frame_is_thumb (frame))
5216     return thumb_deal_with_atomic_sequence_raw (frame);
5217   else
5218     return arm_deal_with_atomic_sequence_raw (frame);
5219 }
5220
5221 /* single_step() is called just before we want to resume the inferior,
5222    if we want to single-step it but there is no hardware or kernel
5223    single-step support.  We find the target of the coming instruction
5224    and breakpoint it.  */
5225
5226 int
5227 arm_software_single_step (struct frame_info *frame)
5228 {
5229   struct gdbarch *gdbarch = get_frame_arch (frame);
5230   struct address_space *aspace = get_frame_address_space (frame);
5231   CORE_ADDR next_pc;
5232
5233   if (arm_deal_with_atomic_sequence (frame))
5234     return 1;
5235
5236   next_pc = arm_get_next_pc (frame, get_frame_pc (frame));
5237   arm_insert_single_step_breakpoint (gdbarch, aspace, next_pc);
5238
5239   return 1;
5240 }
5241
5242 /* Given BUF, which is OLD_LEN bytes ending at ENDADDR, expand
5243    the buffer to be NEW_LEN bytes ending at ENDADDR.  Return
5244    NULL if an error occurs.  BUF is freed.  */
5245
5246 static gdb_byte *
5247 extend_buffer_earlier (gdb_byte *buf, CORE_ADDR endaddr,
5248                        int old_len, int new_len)
5249 {
5250   gdb_byte *new_buf;
5251   int bytes_to_read = new_len - old_len;
5252
5253   new_buf = xmalloc (new_len);
5254   memcpy (new_buf + bytes_to_read, buf, old_len);
5255   xfree (buf);
5256   if (target_read_memory (endaddr - new_len, new_buf, bytes_to_read) != 0)
5257     {
5258       xfree (new_buf);
5259       return NULL;
5260     }
5261   return new_buf;
5262 }
5263
5264 /* An IT block is at most the 2-byte IT instruction followed by
5265    four 4-byte instructions.  The furthest back we must search to
5266    find an IT block that affects the current instruction is thus
5267    2 + 3 * 4 == 14 bytes.  */
5268 #define MAX_IT_BLOCK_PREFIX 14
5269
5270 /* Use a quick scan if there are more than this many bytes of
5271    code.  */
5272 #define IT_SCAN_THRESHOLD 32
5273
5274 /* Adjust a breakpoint's address to move breakpoints out of IT blocks.
5275    A breakpoint in an IT block may not be hit, depending on the
5276    condition flags.  */
5277 static CORE_ADDR
5278 arm_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
5279 {
5280   gdb_byte *buf;
5281   char map_type;
5282   CORE_ADDR boundary, func_start;
5283   int buf_len;
5284   enum bfd_endian order = gdbarch_byte_order_for_code (gdbarch);
5285   int i, any, last_it, last_it_count;
5286
5287   /* If we are using BKPT breakpoints, none of this is necessary.  */
5288   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint == NULL)
5289     return bpaddr;
5290
5291   /* ARM mode does not have this problem.  */
5292   if (!arm_pc_is_thumb (gdbarch, bpaddr))
5293     return bpaddr;
5294
5295   /* We are setting a breakpoint in Thumb code that could potentially
5296      contain an IT block.  The first step is to find how much Thumb
5297      code there is; we do not need to read outside of known Thumb
5298      sequences.  */
5299   map_type = arm_find_mapping_symbol (bpaddr, &boundary);
5300   if (map_type == 0)
5301     /* Thumb-2 code must have mapping symbols to have a chance.  */
5302     return bpaddr;
5303
5304   bpaddr = gdbarch_addr_bits_remove (gdbarch, bpaddr);
5305
5306   if (find_pc_partial_function (bpaddr, NULL, &func_start, NULL)
5307       && func_start > boundary)
5308     boundary = func_start;
5309
5310   /* Search for a candidate IT instruction.  We have to do some fancy
5311      footwork to distinguish a real IT instruction from the second
5312      half of a 32-bit instruction, but there is no need for that if
5313      there's no candidate.  */
5314   buf_len = min (bpaddr - boundary, MAX_IT_BLOCK_PREFIX);
5315   if (buf_len == 0)
5316     /* No room for an IT instruction.  */
5317     return bpaddr;
5318
5319   buf = xmalloc (buf_len);
5320   if (target_read_memory (bpaddr - buf_len, buf, buf_len) != 0)
5321     return bpaddr;
5322   any = 0;
5323   for (i = 0; i < buf_len; i += 2)
5324     {
5325       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5326       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
5327         {
5328           any = 1;
5329           break;
5330         }
5331     }
5332   if (any == 0)
5333     {
5334       xfree (buf);
5335       return bpaddr;
5336     }
5337
5338   /* OK, the code bytes before this instruction contain at least one
5339      halfword which resembles an IT instruction.  We know that it's
5340      Thumb code, but there are still two possibilities.  Either the
5341      halfword really is an IT instruction, or it is the second half of
5342      a 32-bit Thumb instruction.  The only way we can tell is to
5343      scan forwards from a known instruction boundary.  */
5344   if (bpaddr - boundary > IT_SCAN_THRESHOLD)
5345     {
5346       int definite;
5347
5348       /* There's a lot of code before this instruction.  Start with an
5349          optimistic search; it's easy to recognize halfwords that can
5350          not be the start of a 32-bit instruction, and use that to
5351          lock on to the instruction boundaries.  */
5352       buf = extend_buffer_earlier (buf, bpaddr, buf_len, IT_SCAN_THRESHOLD);
5353       if (buf == NULL)
5354         return bpaddr;
5355       buf_len = IT_SCAN_THRESHOLD;
5356
5357       definite = 0;
5358       for (i = 0; i < buf_len - sizeof (buf) && ! definite; i += 2)
5359         {
5360           unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5361           if (thumb_insn_size (inst1) == 2)
5362             {
5363               definite = 1;
5364               break;
5365             }
5366         }
5367
5368       /* At this point, if DEFINITE, BUF[I] is the first place we
5369          are sure that we know the instruction boundaries, and it is far
5370          enough from BPADDR that we could not miss an IT instruction
5371          affecting BPADDR.  If ! DEFINITE, give up - start from a
5372          known boundary.  */
5373       if (! definite)
5374         {
5375           buf = extend_buffer_earlier (buf, bpaddr, buf_len,
5376                                        bpaddr - boundary);
5377           if (buf == NULL)
5378             return bpaddr;
5379           buf_len = bpaddr - boundary;
5380           i = 0;
5381         }
5382     }
5383   else
5384     {
5385       buf = extend_buffer_earlier (buf, bpaddr, buf_len, bpaddr - boundary);
5386       if (buf == NULL)
5387         return bpaddr;
5388       buf_len = bpaddr - boundary;
5389       i = 0;
5390     }
5391
5392   /* Scan forwards.  Find the last IT instruction before BPADDR.  */
5393   last_it = -1;
5394   last_it_count = 0;
5395   while (i < buf_len)
5396     {
5397       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5398       last_it_count--;
5399       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
5400         {
5401           last_it = i;
5402           if (inst1 & 0x0001)
5403             last_it_count = 4;
5404           else if (inst1 & 0x0002)
5405             last_it_count = 3;
5406           else if (inst1 & 0x0004)
5407             last_it_count = 2;
5408           else
5409             last_it_count = 1;
5410         }
5411       i += thumb_insn_size (inst1);
5412     }
5413
5414   xfree (buf);
5415
5416   if (last_it == -1)
5417     /* There wasn't really an IT instruction after all.  */
5418     return bpaddr;
5419
5420   if (last_it_count < 1)
5421     /* It was too far away.  */
5422     return bpaddr;
5423
5424   /* This really is a trouble spot.  Move the breakpoint to the IT
5425      instruction.  */
5426   return bpaddr - buf_len + last_it;
5427 }
5428
5429 /* ARM displaced stepping support.
5430
5431    Generally ARM displaced stepping works as follows:
5432
5433    1. When an instruction is to be single-stepped, it is first decoded by
5434       arm_process_displaced_insn (called from arm_displaced_step_copy_insn).
5435       Depending on the type of instruction, it is then copied to a scratch
5436       location, possibly in a modified form.  The copy_* set of functions
5437       performs such modification, as necessary.  A breakpoint is placed after
5438       the modified instruction in the scratch space to return control to GDB.
5439       Note in particular that instructions which modify the PC will no longer
5440       do so after modification.
5441
5442    2. The instruction is single-stepped, by setting the PC to the scratch
5443       location address, and resuming.  Control returns to GDB when the
5444       breakpoint is hit.
5445
5446    3. A cleanup function (cleanup_*) is called corresponding to the copy_*
5447       function used for the current instruction.  This function's job is to
5448       put the CPU/memory state back to what it would have been if the
5449       instruction had been executed unmodified in its original location.  */
5450
5451 /* NOP instruction (mov r0, r0).  */
5452 #define ARM_NOP                         0xe1a00000
5453 #define THUMB_NOP 0x4600
5454
5455 /* Helper for register reads for displaced stepping.  In particular, this
5456    returns the PC as it would be seen by the instruction at its original
5457    location.  */
5458
5459 ULONGEST
5460 displaced_read_reg (struct regcache *regs, struct displaced_step_closure *dsc,
5461                     int regno)
5462 {
5463   ULONGEST ret;
5464   CORE_ADDR from = dsc->insn_addr;
5465
5466   if (regno == ARM_PC_REGNUM)
5467     {
5468       /* Compute pipeline offset:
5469          - When executing an ARM instruction, PC reads as the address of the
5470          current instruction plus 8.
5471          - When executing a Thumb instruction, PC reads as the address of the
5472          current instruction plus 4.  */
5473
5474       if (!dsc->is_thumb)
5475         from += 8;
5476       else
5477         from += 4;
5478
5479       if (debug_displaced)
5480         fprintf_unfiltered (gdb_stdlog, "displaced: read pc value %.8lx\n",
5481                             (unsigned long) from);
5482       return (ULONGEST) from;
5483     }
5484   else
5485     {
5486       regcache_cooked_read_unsigned (regs, regno, &ret);
5487       if (debug_displaced)
5488         fprintf_unfiltered (gdb_stdlog, "displaced: read r%d value %.8lx\n",
5489                             regno, (unsigned long) ret);
5490       return ret;
5491     }
5492 }
5493
5494 static int
5495 displaced_in_arm_mode (struct regcache *regs)
5496 {
5497   ULONGEST ps;
5498   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5499
5500   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5501
5502   return (ps & t_bit) == 0;
5503 }
5504
5505 /* Write to the PC as from a branch instruction.  */
5506
5507 static void
5508 branch_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5509                  ULONGEST val)
5510 {
5511   if (!dsc->is_thumb)
5512     /* Note: If bits 0/1 are set, this branch would be unpredictable for
5513        architecture versions < 6.  */
5514     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5515                                     val & ~(ULONGEST) 0x3);
5516   else
5517     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5518                                     val & ~(ULONGEST) 0x1);
5519 }
5520
5521 /* Write to the PC as from a branch-exchange instruction.  */
5522
5523 static void
5524 bx_write_pc (struct regcache *regs, ULONGEST val)
5525 {
5526   ULONGEST ps;
5527   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5528
5529   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5530
5531   if ((val & 1) == 1)
5532     {
5533       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps | t_bit);
5534       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffe);
5535     }
5536   else if ((val & 2) == 0)
5537     {
5538       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5539       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val);
5540     }
5541   else
5542     {
5543       /* Unpredictable behaviour.  Try to do something sensible (switch to ARM
5544           mode, align dest to 4 bytes).  */
5545       warning (_("Single-stepping BX to non-word-aligned ARM instruction."));
5546       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5547       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffc);
5548     }
5549 }
5550
5551 /* Write to the PC as if from a load instruction.  */
5552
5553 static void
5554 load_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5555                ULONGEST val)
5556 {
5557   if (DISPLACED_STEPPING_ARCH_VERSION >= 5)
5558     bx_write_pc (regs, val);
5559   else
5560     branch_write_pc (regs, dsc, val);
5561 }
5562
5563 /* Write to the PC as if from an ALU instruction.  */
5564
5565 static void
5566 alu_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5567               ULONGEST val)
5568 {
5569   if (DISPLACED_STEPPING_ARCH_VERSION >= 7 && !dsc->is_thumb)
5570     bx_write_pc (regs, val);
5571   else
5572     branch_write_pc (regs, dsc, val);
5573 }
5574
5575 /* Helper for writing to registers for displaced stepping.  Writing to the PC
5576    has a varying effects depending on the instruction which does the write:
5577    this is controlled by the WRITE_PC argument.  */
5578
5579 void
5580 displaced_write_reg (struct regcache *regs, struct displaced_step_closure *dsc,
5581                      int regno, ULONGEST val, enum pc_write_style write_pc)
5582 {
5583   if (regno == ARM_PC_REGNUM)
5584     {
5585       if (debug_displaced)
5586         fprintf_unfiltered (gdb_stdlog, "displaced: writing pc %.8lx\n",
5587                             (unsigned long) val);
5588       switch (write_pc)
5589         {
5590         case BRANCH_WRITE_PC:
5591           branch_write_pc (regs, dsc, val);
5592           break;
5593
5594         case BX_WRITE_PC:
5595           bx_write_pc (regs, val);
5596           break;
5597
5598         case LOAD_WRITE_PC:
5599           load_write_pc (regs, dsc, val);
5600           break;
5601
5602         case ALU_WRITE_PC:
5603           alu_write_pc (regs, dsc, val);
5604           break;
5605
5606         case CANNOT_WRITE_PC:
5607           warning (_("Instruction wrote to PC in an unexpected way when "
5608                      "single-stepping"));
5609           break;
5610
5611         default:
5612           internal_error (__FILE__, __LINE__,
5613                           _("Invalid argument to displaced_write_reg"));
5614         }
5615
5616       dsc->wrote_to_pc = 1;
5617     }
5618   else
5619     {
5620       if (debug_displaced)
5621         fprintf_unfiltered (gdb_stdlog, "displaced: writing r%d value %.8lx\n",
5622                             regno, (unsigned long) val);
5623       regcache_cooked_write_unsigned (regs, regno, val);
5624     }
5625 }
5626
5627 /* This function is used to concisely determine if an instruction INSN
5628    references PC.  Register fields of interest in INSN should have the
5629    corresponding fields of BITMASK set to 0b1111.  The function
5630    returns return 1 if any of these fields in INSN reference the PC
5631    (also 0b1111, r15), else it returns 0.  */
5632
5633 static int
5634 insn_references_pc (uint32_t insn, uint32_t bitmask)
5635 {
5636   uint32_t lowbit = 1;
5637
5638   while (bitmask != 0)
5639     {
5640       uint32_t mask;
5641
5642       for (; lowbit && (bitmask & lowbit) == 0; lowbit <<= 1)
5643         ;
5644
5645       if (!lowbit)
5646         break;
5647
5648       mask = lowbit * 0xf;
5649
5650       if ((insn & mask) == mask)
5651         return 1;
5652
5653       bitmask &= ~mask;
5654     }
5655
5656   return 0;
5657 }
5658
5659 /* The simplest copy function.  Many instructions have the same effect no
5660    matter what address they are executed at: in those cases, use this.  */
5661
5662 static int
5663 arm_copy_unmodified (struct gdbarch *gdbarch, uint32_t insn,
5664                      const char *iname, struct displaced_step_closure *dsc)
5665 {
5666   if (debug_displaced)
5667     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx, "
5668                         "opcode/class '%s' unmodified\n", (unsigned long) insn,
5669                         iname);
5670
5671   dsc->modinsn[0] = insn;
5672
5673   return 0;
5674 }
5675
5676 static int
5677 thumb_copy_unmodified_32bit (struct gdbarch *gdbarch, uint16_t insn1,
5678                              uint16_t insn2, const char *iname,
5679                              struct displaced_step_closure *dsc)
5680 {
5681   if (debug_displaced)
5682     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x %.4x, "
5683                         "opcode/class '%s' unmodified\n", insn1, insn2,
5684                         iname);
5685
5686   dsc->modinsn[0] = insn1;
5687   dsc->modinsn[1] = insn2;
5688   dsc->numinsns = 2;
5689
5690   return 0;
5691 }
5692
5693 /* Copy 16-bit Thumb(Thumb and 16-bit Thumb-2) instruction without any
5694    modification.  */
5695 static int
5696 thumb_copy_unmodified_16bit (struct gdbarch *gdbarch, unsigned int insn,
5697                              const char *iname,
5698                              struct displaced_step_closure *dsc)
5699 {
5700   if (debug_displaced)
5701     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x, "
5702                         "opcode/class '%s' unmodified\n", insn,
5703                         iname);
5704
5705   dsc->modinsn[0] = insn;
5706
5707   return 0;
5708 }
5709
5710 /* Preload instructions with immediate offset.  */
5711
5712 static void
5713 cleanup_preload (struct gdbarch *gdbarch,
5714                  struct regcache *regs, struct displaced_step_closure *dsc)
5715 {
5716   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5717   if (!dsc->u.preload.immed)
5718     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5719 }
5720
5721 static void
5722 install_preload (struct gdbarch *gdbarch, struct regcache *regs,
5723                  struct displaced_step_closure *dsc, unsigned int rn)
5724 {
5725   ULONGEST rn_val;
5726   /* Preload instructions:
5727
5728      {pli/pld} [rn, #+/-imm]
5729      ->
5730      {pli/pld} [r0, #+/-imm].  */
5731
5732   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5733   rn_val = displaced_read_reg (regs, dsc, rn);
5734   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5735   dsc->u.preload.immed = 1;
5736
5737   dsc->cleanup = &cleanup_preload;
5738 }
5739
5740 static int
5741 arm_copy_preload (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
5742                   struct displaced_step_closure *dsc)
5743 {
5744   unsigned int rn = bits (insn, 16, 19);
5745
5746   if (!insn_references_pc (insn, 0x000f0000ul))
5747     return arm_copy_unmodified (gdbarch, insn, "preload", dsc);
5748
5749   if (debug_displaced)
5750     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5751                         (unsigned long) insn);
5752
5753   dsc->modinsn[0] = insn & 0xfff0ffff;
5754
5755   install_preload (gdbarch, regs, dsc, rn);
5756
5757   return 0;
5758 }
5759
5760 static int
5761 thumb2_copy_preload (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
5762                      struct regcache *regs, struct displaced_step_closure *dsc)
5763 {
5764   unsigned int rn = bits (insn1, 0, 3);
5765   unsigned int u_bit = bit (insn1, 7);
5766   int imm12 = bits (insn2, 0, 11);
5767   ULONGEST pc_val;
5768
5769   if (rn != ARM_PC_REGNUM)
5770     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "preload", dsc);
5771
5772   /* PC is only allowed to use in PLI (immediate,literal) Encoding T3, and
5773      PLD (literal) Encoding T1.  */
5774   if (debug_displaced)
5775     fprintf_unfiltered (gdb_stdlog,
5776                         "displaced: copying pld/pli pc (0x%x) %c imm12 %.4x\n",
5777                         (unsigned int) dsc->insn_addr, u_bit ? '+' : '-',
5778                         imm12);
5779
5780   if (!u_bit)
5781     imm12 = -1 * imm12;
5782
5783   /* Rewrite instruction {pli/pld} PC imm12 into:
5784      Prepare: tmp[0] <- r0, tmp[1] <- r1, r0 <- pc, r1 <- imm12
5785
5786      {pli/pld} [r0, r1]
5787
5788      Cleanup: r0 <- tmp[0], r1 <- tmp[1].  */
5789
5790   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5791   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
5792
5793   pc_val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
5794
5795   displaced_write_reg (regs, dsc, 0, pc_val, CANNOT_WRITE_PC);
5796   displaced_write_reg (regs, dsc, 1, imm12, CANNOT_WRITE_PC);
5797   dsc->u.preload.immed = 0;
5798
5799   /* {pli/pld} [r0, r1] */
5800   dsc->modinsn[0] = insn1 & 0xfff0;
5801   dsc->modinsn[1] = 0xf001;
5802   dsc->numinsns = 2;
5803
5804   dsc->cleanup = &cleanup_preload;
5805   return 0;
5806 }
5807
5808 /* Preload instructions with register offset.  */
5809
5810 static void
5811 install_preload_reg(struct gdbarch *gdbarch, struct regcache *regs,
5812                     struct displaced_step_closure *dsc, unsigned int rn,
5813                     unsigned int rm)
5814 {
5815   ULONGEST rn_val, rm_val;
5816
5817   /* Preload register-offset instructions:
5818
5819      {pli/pld} [rn, rm {, shift}]
5820      ->
5821      {pli/pld} [r0, r1 {, shift}].  */
5822
5823   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5824   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
5825   rn_val = displaced_read_reg (regs, dsc, rn);
5826   rm_val = displaced_read_reg (regs, dsc, rm);
5827   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5828   displaced_write_reg (regs, dsc, 1, rm_val, CANNOT_WRITE_PC);
5829   dsc->u.preload.immed = 0;
5830
5831   dsc->cleanup = &cleanup_preload;
5832 }
5833
5834 static int
5835 arm_copy_preload_reg (struct gdbarch *gdbarch, uint32_t insn,
5836                       struct regcache *regs,
5837                       struct displaced_step_closure *dsc)
5838 {
5839   unsigned int rn = bits (insn, 16, 19);
5840   unsigned int rm = bits (insn, 0, 3);
5841
5842
5843   if (!insn_references_pc (insn, 0x000f000ful))
5844     return arm_copy_unmodified (gdbarch, insn, "preload reg", dsc);
5845
5846   if (debug_displaced)
5847     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5848                         (unsigned long) insn);
5849
5850   dsc->modinsn[0] = (insn & 0xfff0fff0) | 0x1;
5851
5852   install_preload_reg (gdbarch, regs, dsc, rn, rm);
5853   return 0;
5854 }
5855
5856 /* Copy/cleanup coprocessor load and store instructions.  */
5857
5858 static void
5859 cleanup_copro_load_store (struct gdbarch *gdbarch,
5860                           struct regcache *regs,
5861                           struct displaced_step_closure *dsc)
5862 {
5863   ULONGEST rn_val = displaced_read_reg (regs, dsc, 0);
5864
5865   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5866
5867   if (dsc->u.ldst.writeback)
5868     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, LOAD_WRITE_PC);
5869 }
5870
5871 static void
5872 install_copro_load_store (struct gdbarch *gdbarch, struct regcache *regs,
5873                           struct displaced_step_closure *dsc,
5874                           int writeback, unsigned int rn)
5875 {
5876   ULONGEST rn_val;
5877
5878   /* Coprocessor load/store instructions:
5879
5880      {stc/stc2} [<Rn>, #+/-imm]  (and other immediate addressing modes)
5881      ->
5882      {stc/stc2} [r0, #+/-imm].
5883
5884      ldc/ldc2 are handled identically.  */
5885
5886   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5887   rn_val = displaced_read_reg (regs, dsc, rn);
5888   /* PC should be 4-byte aligned.  */
5889   rn_val = rn_val & 0xfffffffc;
5890   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5891
5892   dsc->u.ldst.writeback = writeback;
5893   dsc->u.ldst.rn = rn;
5894
5895   dsc->cleanup = &cleanup_copro_load_store;
5896 }
5897
5898 static int
5899 arm_copy_copro_load_store (struct gdbarch *gdbarch, uint32_t insn,
5900                            struct regcache *regs,
5901                            struct displaced_step_closure *dsc)
5902 {
5903   unsigned int rn = bits (insn, 16, 19);
5904
5905   if (!insn_references_pc (insn, 0x000f0000ul))
5906     return arm_copy_unmodified (gdbarch, insn, "copro load/store", dsc);
5907
5908   if (debug_displaced)
5909     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
5910                         "load/store insn %.8lx\n", (unsigned long) insn);
5911
5912   dsc->modinsn[0] = insn & 0xfff0ffff;
5913
5914   install_copro_load_store (gdbarch, regs, dsc, bit (insn, 25), rn);
5915
5916   return 0;
5917 }
5918
5919 static int
5920 thumb2_copy_copro_load_store (struct gdbarch *gdbarch, uint16_t insn1,
5921                               uint16_t insn2, struct regcache *regs,
5922                               struct displaced_step_closure *dsc)
5923 {
5924   unsigned int rn = bits (insn1, 0, 3);
5925
5926   if (rn != ARM_PC_REGNUM)
5927     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
5928                                         "copro load/store", dsc);
5929
5930   if (debug_displaced)
5931     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
5932                         "load/store insn %.4x%.4x\n", insn1, insn2);
5933
5934   dsc->modinsn[0] = insn1 & 0xfff0;
5935   dsc->modinsn[1] = insn2;
5936   dsc->numinsns = 2;
5937
5938   /* This function is called for copying instruction LDC/LDC2/VLDR, which
5939      doesn't support writeback, so pass 0.  */
5940   install_copro_load_store (gdbarch, regs, dsc, 0, rn);
5941
5942   return 0;
5943 }
5944
5945 /* Clean up branch instructions (actually perform the branch, by setting
5946    PC).  */
5947
5948 static void
5949 cleanup_branch (struct gdbarch *gdbarch, struct regcache *regs,
5950                 struct displaced_step_closure *dsc)
5951 {
5952   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
5953   int branch_taken = condition_true (dsc->u.branch.cond, status);
5954   enum pc_write_style write_pc = dsc->u.branch.exchange
5955                                  ? BX_WRITE_PC : BRANCH_WRITE_PC;
5956
5957   if (!branch_taken)
5958     return;
5959
5960   if (dsc->u.branch.link)
5961     {
5962       /* The value of LR should be the next insn of current one.  In order
5963        not to confuse logic hanlding later insn `bx lr', if current insn mode
5964        is Thumb, the bit 0 of LR value should be set to 1.  */
5965       ULONGEST next_insn_addr = dsc->insn_addr + dsc->insn_size;
5966
5967       if (dsc->is_thumb)
5968         next_insn_addr |= 0x1;
5969
5970       displaced_write_reg (regs, dsc, ARM_LR_REGNUM, next_insn_addr,
5971                            CANNOT_WRITE_PC);
5972     }
5973
5974   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, dsc->u.branch.dest, write_pc);
5975 }
5976
5977 /* Copy B/BL/BLX instructions with immediate destinations.  */
5978
5979 static void
5980 install_b_bl_blx (struct gdbarch *gdbarch, struct regcache *regs,
5981                   struct displaced_step_closure *dsc,
5982                   unsigned int cond, int exchange, int link, long offset)
5983 {
5984   /* Implement "BL<cond> <label>" as:
5985
5986      Preparation: cond <- instruction condition
5987      Insn: mov r0, r0  (nop)
5988      Cleanup: if (condition true) { r14 <- pc; pc <- label }.
5989
5990      B<cond> similar, but don't set r14 in cleanup.  */
5991
5992   dsc->u.branch.cond = cond;
5993   dsc->u.branch.link = link;
5994   dsc->u.branch.exchange = exchange;
5995
5996   dsc->u.branch.dest = dsc->insn_addr;
5997   if (link && exchange)
5998     /* For BLX, offset is computed from the Align (PC, 4).  */
5999     dsc->u.branch.dest = dsc->u.branch.dest & 0xfffffffc;
6000
6001   if (dsc->is_thumb)
6002     dsc->u.branch.dest += 4 + offset;
6003   else
6004     dsc->u.branch.dest += 8 + offset;
6005
6006   dsc->cleanup = &cleanup_branch;
6007 }
6008 static int
6009 arm_copy_b_bl_blx (struct gdbarch *gdbarch, uint32_t insn,
6010                    struct regcache *regs, struct displaced_step_closure *dsc)
6011 {
6012   unsigned int cond = bits (insn, 28, 31);
6013   int exchange = (cond == 0xf);
6014   int link = exchange || bit (insn, 24);
6015   long offset;
6016
6017   if (debug_displaced)
6018     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s immediate insn "
6019                         "%.8lx\n", (exchange) ? "blx" : (link) ? "bl" : "b",
6020                         (unsigned long) insn);
6021   if (exchange)
6022     /* For BLX, set bit 0 of the destination.  The cleanup_branch function will
6023        then arrange the switch into Thumb mode.  */
6024     offset = (bits (insn, 0, 23) << 2) | (bit (insn, 24) << 1) | 1;
6025   else
6026     offset = bits (insn, 0, 23) << 2;
6027
6028   if (bit (offset, 25))
6029     offset = offset | ~0x3ffffff;
6030
6031   dsc->modinsn[0] = ARM_NOP;
6032
6033   install_b_bl_blx (gdbarch, regs, dsc, cond, exchange, link, offset);
6034   return 0;
6035 }
6036
6037 static int
6038 thumb2_copy_b_bl_blx (struct gdbarch *gdbarch, uint16_t insn1,
6039                       uint16_t insn2, struct regcache *regs,
6040                       struct displaced_step_closure *dsc)
6041 {
6042   int link = bit (insn2, 14);
6043   int exchange = link && !bit (insn2, 12);
6044   int cond = INST_AL;
6045   long offset = 0;
6046   int j1 = bit (insn2, 13);
6047   int j2 = bit (insn2, 11);
6048   int s = sbits (insn1, 10, 10);
6049   int i1 = !(j1 ^ bit (insn1, 10));
6050   int i2 = !(j2 ^ bit (insn1, 10));
6051
6052   if (!link && !exchange) /* B */
6053     {
6054       offset = (bits (insn2, 0, 10) << 1);
6055       if (bit (insn2, 12)) /* Encoding T4 */
6056         {
6057           offset |= (bits (insn1, 0, 9) << 12)
6058             | (i2 << 22)
6059             | (i1 << 23)
6060             | (s << 24);
6061           cond = INST_AL;
6062         }
6063       else /* Encoding T3 */
6064         {
6065           offset |= (bits (insn1, 0, 5) << 12)
6066             | (j1 << 18)
6067             | (j2 << 19)
6068             | (s << 20);
6069           cond = bits (insn1, 6, 9);
6070         }
6071     }
6072   else
6073     {
6074       offset = (bits (insn1, 0, 9) << 12);
6075       offset |= ((i2 << 22) | (i1 << 23) | (s << 24));
6076       offset |= exchange ?
6077         (bits (insn2, 1, 10) << 2) : (bits (insn2, 0, 10) << 1);
6078     }
6079
6080   if (debug_displaced)
6081     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s insn "
6082                         "%.4x %.4x with offset %.8lx\n",
6083                         link ? (exchange) ? "blx" : "bl" : "b",
6084                         insn1, insn2, offset);
6085
6086   dsc->modinsn[0] = THUMB_NOP;
6087
6088   install_b_bl_blx (gdbarch, regs, dsc, cond, exchange, link, offset);
6089   return 0;
6090 }
6091
6092 /* Copy B Thumb instructions.  */
6093 static int
6094 thumb_copy_b (struct gdbarch *gdbarch, unsigned short insn,
6095               struct displaced_step_closure *dsc)
6096 {
6097   unsigned int cond = 0;
6098   int offset = 0;
6099   unsigned short bit_12_15 = bits (insn, 12, 15);
6100   CORE_ADDR from = dsc->insn_addr;
6101
6102   if (bit_12_15 == 0xd)
6103     {
6104       /* offset = SignExtend (imm8:0, 32) */
6105       offset = sbits ((insn << 1), 0, 8);
6106       cond = bits (insn, 8, 11);
6107     }
6108   else if (bit_12_15 == 0xe) /* Encoding T2 */
6109     {
6110       offset = sbits ((insn << 1), 0, 11);
6111       cond = INST_AL;
6112     }
6113
6114   if (debug_displaced)
6115     fprintf_unfiltered (gdb_stdlog,
6116                         "displaced: copying b immediate insn %.4x "
6117                         "with offset %d\n", insn, offset);
6118
6119   dsc->u.branch.cond = cond;
6120   dsc->u.branch.link = 0;
6121   dsc->u.branch.exchange = 0;
6122   dsc->u.branch.dest = from + 4 + offset;
6123
6124   dsc->modinsn[0] = THUMB_NOP;
6125
6126   dsc->cleanup = &cleanup_branch;
6127
6128   return 0;
6129 }
6130
6131 /* Copy BX/BLX with register-specified destinations.  */
6132
6133 static void
6134 install_bx_blx_reg (struct gdbarch *gdbarch, struct regcache *regs,
6135                     struct displaced_step_closure *dsc, int link,
6136                     unsigned int cond, unsigned int rm)
6137 {
6138   /* Implement {BX,BLX}<cond> <reg>" as:
6139
6140      Preparation: cond <- instruction condition
6141      Insn: mov r0, r0 (nop)
6142      Cleanup: if (condition true) { r14 <- pc; pc <- dest; }.
6143
6144      Don't set r14 in cleanup for BX.  */
6145
6146   dsc->u.branch.dest = displaced_read_reg (regs, dsc, rm);
6147
6148   dsc->u.branch.cond = cond;
6149   dsc->u.branch.link = link;
6150
6151   dsc->u.branch.exchange = 1;
6152
6153   dsc->cleanup = &cleanup_branch;
6154 }
6155
6156 static int
6157 arm_copy_bx_blx_reg (struct gdbarch *gdbarch, uint32_t insn,
6158                      struct regcache *regs, struct displaced_step_closure *dsc)
6159 {
6160   unsigned int cond = bits (insn, 28, 31);
6161   /* BX:  x12xxx1x
6162      BLX: x12xxx3x.  */
6163   int link = bit (insn, 5);
6164   unsigned int rm = bits (insn, 0, 3);
6165
6166   if (debug_displaced)
6167     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx",
6168                         (unsigned long) insn);
6169
6170   dsc->modinsn[0] = ARM_NOP;
6171
6172   install_bx_blx_reg (gdbarch, regs, dsc, link, cond, rm);
6173   return 0;
6174 }
6175
6176 static int
6177 thumb_copy_bx_blx_reg (struct gdbarch *gdbarch, uint16_t insn,
6178                        struct regcache *regs,
6179                        struct displaced_step_closure *dsc)
6180 {
6181   int link = bit (insn, 7);
6182   unsigned int rm = bits (insn, 3, 6);
6183
6184   if (debug_displaced)
6185     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x",
6186                         (unsigned short) insn);
6187
6188   dsc->modinsn[0] = THUMB_NOP;
6189
6190   install_bx_blx_reg (gdbarch, regs, dsc, link, INST_AL, rm);
6191
6192   return 0;
6193 }
6194
6195
6196 /* Copy/cleanup arithmetic/logic instruction with immediate RHS.  */
6197
6198 static void
6199 cleanup_alu_imm (struct gdbarch *gdbarch,
6200                  struct regcache *regs, struct displaced_step_closure *dsc)
6201 {
6202   ULONGEST rd_val = displaced_read_reg (regs, dsc, 0);
6203   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6204   displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6205   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6206 }
6207
6208 static int
6209 arm_copy_alu_imm (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6210                   struct displaced_step_closure *dsc)
6211 {
6212   unsigned int rn = bits (insn, 16, 19);
6213   unsigned int rd = bits (insn, 12, 15);
6214   unsigned int op = bits (insn, 21, 24);
6215   int is_mov = (op == 0xd);
6216   ULONGEST rd_val, rn_val;
6217
6218   if (!insn_references_pc (insn, 0x000ff000ul))
6219     return arm_copy_unmodified (gdbarch, insn, "ALU immediate", dsc);
6220
6221   if (debug_displaced)
6222     fprintf_unfiltered (gdb_stdlog, "displaced: copying immediate %s insn "
6223                         "%.8lx\n", is_mov ? "move" : "ALU",
6224                         (unsigned long) insn);
6225
6226   /* Instruction is of form:
6227
6228      <op><cond> rd, [rn,] #imm
6229
6230      Rewrite as:
6231
6232      Preparation: tmp1, tmp2 <- r0, r1;
6233                   r0, r1 <- rd, rn
6234      Insn: <op><cond> r0, r1, #imm
6235      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
6236   */
6237
6238   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6239   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6240   rn_val = displaced_read_reg (regs, dsc, rn);
6241   rd_val = displaced_read_reg (regs, dsc, rd);
6242   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6243   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6244   dsc->rd = rd;
6245
6246   if (is_mov)
6247     dsc->modinsn[0] = insn & 0xfff00fff;
6248   else
6249     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x10000;
6250
6251   dsc->cleanup = &cleanup_alu_imm;
6252
6253   return 0;
6254 }
6255
6256 static int
6257 thumb2_copy_alu_imm (struct gdbarch *gdbarch, uint16_t insn1,
6258                      uint16_t insn2, struct regcache *regs,
6259                      struct displaced_step_closure *dsc)
6260 {
6261   unsigned int op = bits (insn1, 5, 8);
6262   unsigned int rn, rm, rd;
6263   ULONGEST rd_val, rn_val;
6264
6265   rn = bits (insn1, 0, 3); /* Rn */
6266   rm = bits (insn2, 0, 3); /* Rm */
6267   rd = bits (insn2, 8, 11); /* Rd */
6268
6269   /* This routine is only called for instruction MOV.  */
6270   gdb_assert (op == 0x2 && rn == 0xf);
6271
6272   if (rm != ARM_PC_REGNUM && rd != ARM_PC_REGNUM)
6273     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "ALU imm", dsc);
6274
6275   if (debug_displaced)
6276     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.4x%.4x\n",
6277                         "ALU", insn1, insn2);
6278
6279   /* Instruction is of form:
6280
6281      <op><cond> rd, [rn,] #imm
6282
6283      Rewrite as:
6284
6285      Preparation: tmp1, tmp2 <- r0, r1;
6286                   r0, r1 <- rd, rn
6287      Insn: <op><cond> r0, r1, #imm
6288      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
6289   */
6290
6291   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6292   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6293   rn_val = displaced_read_reg (regs, dsc, rn);
6294   rd_val = displaced_read_reg (regs, dsc, rd);
6295   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6296   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6297   dsc->rd = rd;
6298
6299   dsc->modinsn[0] = insn1;
6300   dsc->modinsn[1] = ((insn2 & 0xf0f0) | 0x1);
6301   dsc->numinsns = 2;
6302
6303   dsc->cleanup = &cleanup_alu_imm;
6304
6305   return 0;
6306 }
6307
6308 /* Copy/cleanup arithmetic/logic insns with register RHS.  */
6309
6310 static void
6311 cleanup_alu_reg (struct gdbarch *gdbarch,
6312                  struct regcache *regs, struct displaced_step_closure *dsc)
6313 {
6314   ULONGEST rd_val;
6315   int i;
6316
6317   rd_val = displaced_read_reg (regs, dsc, 0);
6318
6319   for (i = 0; i < 3; i++)
6320     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
6321
6322   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6323 }
6324
6325 static void
6326 install_alu_reg (struct gdbarch *gdbarch, struct regcache *regs,
6327                  struct displaced_step_closure *dsc,
6328                  unsigned int rd, unsigned int rn, unsigned int rm)
6329 {
6330   ULONGEST rd_val, rn_val, rm_val;
6331
6332   /* Instruction is of form:
6333
6334      <op><cond> rd, [rn,] rm [, <shift>]
6335
6336      Rewrite as:
6337
6338      Preparation: tmp1, tmp2, tmp3 <- r0, r1, r2;
6339                   r0, r1, r2 <- rd, rn, rm
6340      Insn: <op><cond> r0, r1, r2 [, <shift>]
6341      Cleanup: rd <- r0; r0, r1, r2 <- tmp1, tmp2, tmp3
6342   */
6343
6344   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6345   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6346   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6347   rd_val = displaced_read_reg (regs, dsc, rd);
6348   rn_val = displaced_read_reg (regs, dsc, rn);
6349   rm_val = displaced_read_reg (regs, dsc, rm);
6350   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6351   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6352   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
6353   dsc->rd = rd;
6354
6355   dsc->cleanup = &cleanup_alu_reg;
6356 }
6357
6358 static int
6359 arm_copy_alu_reg (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6360                   struct displaced_step_closure *dsc)
6361 {
6362   unsigned int op = bits (insn, 21, 24);
6363   int is_mov = (op == 0xd);
6364
6365   if (!insn_references_pc (insn, 0x000ff00ful))
6366     return arm_copy_unmodified (gdbarch, insn, "ALU reg", dsc);
6367
6368   if (debug_displaced)
6369     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.8lx\n",
6370                         is_mov ? "move" : "ALU", (unsigned long) insn);
6371
6372   if (is_mov)
6373     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x2;
6374   else
6375     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x10002;
6376
6377   install_alu_reg (gdbarch, regs, dsc, bits (insn, 12, 15), bits (insn, 16, 19),
6378                    bits (insn, 0, 3));
6379   return 0;
6380 }
6381
6382 static int
6383 thumb_copy_alu_reg (struct gdbarch *gdbarch, uint16_t insn,
6384                     struct regcache *regs,
6385                     struct displaced_step_closure *dsc)
6386 {
6387   unsigned rn, rm, rd;
6388
6389   rd = bits (insn, 3, 6);
6390   rn = (bit (insn, 7) << 3) | bits (insn, 0, 2);
6391   rm = 2;
6392
6393   if (rd != ARM_PC_REGNUM && rn != ARM_PC_REGNUM)
6394     return thumb_copy_unmodified_16bit (gdbarch, insn, "ALU reg", dsc);
6395
6396   if (debug_displaced)
6397     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.4x\n",
6398                         "ALU", (unsigned short) insn);
6399
6400   dsc->modinsn[0] = ((insn & 0xff00) | 0x08);
6401
6402   install_alu_reg (gdbarch, regs, dsc, rd, rn, rm);
6403
6404   return 0;
6405 }
6406
6407 /* Cleanup/copy arithmetic/logic insns with shifted register RHS.  */
6408
6409 static void
6410 cleanup_alu_shifted_reg (struct gdbarch *gdbarch,
6411                          struct regcache *regs,
6412                          struct displaced_step_closure *dsc)
6413 {
6414   ULONGEST rd_val = displaced_read_reg (regs, dsc, 0);
6415   int i;
6416
6417   for (i = 0; i < 4; i++)
6418     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
6419
6420   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6421 }
6422
6423 static void
6424 install_alu_shifted_reg (struct gdbarch *gdbarch, struct regcache *regs,
6425                          struct displaced_step_closure *dsc,
6426                          unsigned int rd, unsigned int rn, unsigned int rm,
6427                          unsigned rs)
6428 {
6429   int i;
6430   ULONGEST rd_val, rn_val, rm_val, rs_val;
6431
6432   /* Instruction is of form:
6433
6434      <op><cond> rd, [rn,] rm, <shift> rs
6435
6436      Rewrite as:
6437
6438      Preparation: tmp1, tmp2, tmp3, tmp4 <- r0, r1, r2, r3
6439                   r0, r1, r2, r3 <- rd, rn, rm, rs
6440      Insn: <op><cond> r0, r1, r2, <shift> r3
6441      Cleanup: tmp5 <- r0
6442               r0, r1, r2, r3 <- tmp1, tmp2, tmp3, tmp4
6443               rd <- tmp5
6444   */
6445
6446   for (i = 0; i < 4; i++)
6447     dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
6448
6449   rd_val = displaced_read_reg (regs, dsc, rd);
6450   rn_val = displaced_read_reg (regs, dsc, rn);
6451   rm_val = displaced_read_reg (regs, dsc, rm);
6452   rs_val = displaced_read_reg (regs, dsc, rs);
6453   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6454   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6455   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
6456   displaced_write_reg (regs, dsc, 3, rs_val, CANNOT_WRITE_PC);
6457   dsc->rd = rd;
6458   dsc->cleanup = &cleanup_alu_shifted_reg;
6459 }
6460
6461 static int
6462 arm_copy_alu_shifted_reg (struct gdbarch *gdbarch, uint32_t insn,
6463                           struct regcache *regs,
6464                           struct displaced_step_closure *dsc)
6465 {
6466   unsigned int op = bits (insn, 21, 24);
6467   int is_mov = (op == 0xd);
6468   unsigned int rd, rn, rm, rs;
6469
6470   if (!insn_references_pc (insn, 0x000fff0ful))
6471     return arm_copy_unmodified (gdbarch, insn, "ALU shifted reg", dsc);
6472
6473   if (debug_displaced)
6474     fprintf_unfiltered (gdb_stdlog, "displaced: copying shifted reg %s insn "
6475                         "%.8lx\n", is_mov ? "move" : "ALU",
6476                         (unsigned long) insn);
6477
6478   rn = bits (insn, 16, 19);
6479   rm = bits (insn, 0, 3);
6480   rs = bits (insn, 8, 11);
6481   rd = bits (insn, 12, 15);
6482
6483   if (is_mov)
6484     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x302;
6485   else
6486     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x10302;
6487
6488   install_alu_shifted_reg (gdbarch, regs, dsc, rd, rn, rm, rs);
6489
6490   return 0;
6491 }
6492
6493 /* Clean up load instructions.  */
6494
6495 static void
6496 cleanup_load (struct gdbarch *gdbarch, struct regcache *regs,
6497               struct displaced_step_closure *dsc)
6498 {
6499   ULONGEST rt_val, rt_val2 = 0, rn_val;
6500
6501   rt_val = displaced_read_reg (regs, dsc, 0);
6502   if (dsc->u.ldst.xfersize == 8)
6503     rt_val2 = displaced_read_reg (regs, dsc, 1);
6504   rn_val = displaced_read_reg (regs, dsc, 2);
6505
6506   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6507   if (dsc->u.ldst.xfersize > 4)
6508     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6509   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
6510   if (!dsc->u.ldst.immed)
6511     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
6512
6513   /* Handle register writeback.  */
6514   if (dsc->u.ldst.writeback)
6515     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
6516   /* Put result in right place.  */
6517   displaced_write_reg (regs, dsc, dsc->rd, rt_val, LOAD_WRITE_PC);
6518   if (dsc->u.ldst.xfersize == 8)
6519     displaced_write_reg (regs, dsc, dsc->rd + 1, rt_val2, LOAD_WRITE_PC);
6520 }
6521
6522 /* Clean up store instructions.  */
6523
6524 static void
6525 cleanup_store (struct gdbarch *gdbarch, struct regcache *regs,
6526                struct displaced_step_closure *dsc)
6527 {
6528   ULONGEST rn_val = displaced_read_reg (regs, dsc, 2);
6529
6530   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6531   if (dsc->u.ldst.xfersize > 4)
6532     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6533   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
6534   if (!dsc->u.ldst.immed)
6535     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
6536   if (!dsc->u.ldst.restore_r4)
6537     displaced_write_reg (regs, dsc, 4, dsc->tmp[4], CANNOT_WRITE_PC);
6538
6539   /* Writeback.  */
6540   if (dsc->u.ldst.writeback)
6541     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
6542 }
6543
6544 /* Copy "extra" load/store instructions.  These are halfword/doubleword
6545    transfers, which have a different encoding to byte/word transfers.  */
6546
6547 static int
6548 arm_copy_extra_ld_st (struct gdbarch *gdbarch, uint32_t insn, int unpriveleged,
6549                       struct regcache *regs, struct displaced_step_closure *dsc)
6550 {
6551   unsigned int op1 = bits (insn, 20, 24);
6552   unsigned int op2 = bits (insn, 5, 6);
6553   unsigned int rt = bits (insn, 12, 15);
6554   unsigned int rn = bits (insn, 16, 19);
6555   unsigned int rm = bits (insn, 0, 3);
6556   char load[12]     = {0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1};
6557   char bytesize[12] = {2, 2, 2, 2, 8, 1, 8, 1, 8, 2, 8, 2};
6558   int immed = (op1 & 0x4) != 0;
6559   int opcode;
6560   ULONGEST rt_val, rt_val2 = 0, rn_val, rm_val = 0;
6561
6562   if (!insn_references_pc (insn, 0x000ff00ful))
6563     return arm_copy_unmodified (gdbarch, insn, "extra load/store", dsc);
6564
6565   if (debug_displaced)
6566     fprintf_unfiltered (gdb_stdlog, "displaced: copying %sextra load/store "
6567                         "insn %.8lx\n", unpriveleged ? "unpriveleged " : "",
6568                         (unsigned long) insn);
6569
6570   opcode = ((op2 << 2) | (op1 & 0x1) | ((op1 & 0x4) >> 1)) - 4;
6571
6572   if (opcode < 0)
6573     internal_error (__FILE__, __LINE__,
6574                     _("copy_extra_ld_st: instruction decode error"));
6575
6576   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6577   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6578   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6579   if (!immed)
6580     dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6581
6582   rt_val = displaced_read_reg (regs, dsc, rt);
6583   if (bytesize[opcode] == 8)
6584     rt_val2 = displaced_read_reg (regs, dsc, rt + 1);
6585   rn_val = displaced_read_reg (regs, dsc, rn);
6586   if (!immed)
6587     rm_val = displaced_read_reg (regs, dsc, rm);
6588
6589   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
6590   if (bytesize[opcode] == 8)
6591     displaced_write_reg (regs, dsc, 1, rt_val2, CANNOT_WRITE_PC);
6592   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
6593   if (!immed)
6594     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
6595
6596   dsc->rd = rt;
6597   dsc->u.ldst.xfersize = bytesize[opcode];
6598   dsc->u.ldst.rn = rn;
6599   dsc->u.ldst.immed = immed;
6600   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
6601   dsc->u.ldst.restore_r4 = 0;
6602
6603   if (immed)
6604     /* {ldr,str}<width><cond> rt, [rt2,] [rn, #imm]
6605         ->
6606        {ldr,str}<width><cond> r0, [r1,] [r2, #imm].  */
6607     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
6608   else
6609     /* {ldr,str}<width><cond> rt, [rt2,] [rn, +/-rm]
6610         ->
6611        {ldr,str}<width><cond> r0, [r1,] [r2, +/-r3].  */
6612     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
6613
6614   dsc->cleanup = load[opcode] ? &cleanup_load : &cleanup_store;
6615
6616   return 0;
6617 }
6618
6619 /* Copy byte/half word/word loads and stores.  */
6620
6621 static void
6622 install_load_store (struct gdbarch *gdbarch, struct regcache *regs,
6623                     struct displaced_step_closure *dsc, int load,
6624                     int immed, int writeback, int size, int usermode,
6625                     int rt, int rm, int rn)
6626 {
6627   ULONGEST rt_val, rn_val, rm_val = 0;
6628
6629   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6630   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6631   if (!immed)
6632     dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6633   if (!load)
6634     dsc->tmp[4] = displaced_read_reg (regs, dsc, 4);
6635
6636   rt_val = displaced_read_reg (regs, dsc, rt);
6637   rn_val = displaced_read_reg (regs, dsc, rn);
6638   if (!immed)
6639     rm_val = displaced_read_reg (regs, dsc, rm);
6640
6641   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
6642   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
6643   if (!immed)
6644     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
6645   dsc->rd = rt;
6646   dsc->u.ldst.xfersize = size;
6647   dsc->u.ldst.rn = rn;
6648   dsc->u.ldst.immed = immed;
6649   dsc->u.ldst.writeback = writeback;
6650
6651   /* To write PC we can do:
6652
6653      Before this sequence of instructions:
6654      r0 is the PC value got from displaced_read_reg, so r0 = from + 8;
6655      r2 is the Rn value got from dispalced_read_reg.
6656
6657      Insn1: push {pc} Write address of STR instruction + offset on stack
6658      Insn2: pop  {r4} Read it back from stack, r4 = addr(Insn1) + offset
6659      Insn3: sub r4, r4, pc   r4 = addr(Insn1) + offset - pc
6660                                 = addr(Insn1) + offset - addr(Insn3) - 8
6661                                 = offset - 16
6662      Insn4: add r4, r4, #8   r4 = offset - 8
6663      Insn5: add r0, r0, r4   r0 = from + 8 + offset - 8
6664                                 = from + offset
6665      Insn6: str r0, [r2, #imm] (or str r0, [r2, r3])
6666
6667      Otherwise we don't know what value to write for PC, since the offset is
6668      architecture-dependent (sometimes PC+8, sometimes PC+12).  More details
6669      of this can be found in Section "Saving from r15" in
6670      http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204g/Cihbjifh.html */
6671
6672   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
6673 }
6674
6675
6676 static int
6677 thumb2_copy_load_literal (struct gdbarch *gdbarch, uint16_t insn1,
6678                           uint16_t insn2, struct regcache *regs,
6679                           struct displaced_step_closure *dsc, int size)
6680 {
6681   unsigned int u_bit = bit (insn1, 7);
6682   unsigned int rt = bits (insn2, 12, 15);
6683   int imm12 = bits (insn2, 0, 11);
6684   ULONGEST pc_val;
6685
6686   if (debug_displaced)
6687     fprintf_unfiltered (gdb_stdlog,
6688                         "displaced: copying ldr pc (0x%x) R%d %c imm12 %.4x\n",
6689                         (unsigned int) dsc->insn_addr, rt, u_bit ? '+' : '-',
6690                         imm12);
6691
6692   if (!u_bit)
6693     imm12 = -1 * imm12;
6694
6695   /* Rewrite instruction LDR Rt imm12 into:
6696
6697      Prepare: tmp[0] <- r0, tmp[1] <- r2, tmp[2] <- r3, r2 <- pc, r3 <- imm12
6698
6699      LDR R0, R2, R3,
6700
6701      Cleanup: rt <- r0, r0 <- tmp[0], r2 <- tmp[1], r3 <- tmp[2].  */
6702
6703
6704   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6705   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6706   dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6707
6708   pc_val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
6709
6710   pc_val = pc_val & 0xfffffffc;
6711
6712   displaced_write_reg (regs, dsc, 2, pc_val, CANNOT_WRITE_PC);
6713   displaced_write_reg (regs, dsc, 3, imm12, CANNOT_WRITE_PC);
6714
6715   dsc->rd = rt;
6716
6717   dsc->u.ldst.xfersize = size;
6718   dsc->u.ldst.immed = 0;
6719   dsc->u.ldst.writeback = 0;
6720   dsc->u.ldst.restore_r4 = 0;
6721
6722   /* LDR R0, R2, R3 */
6723   dsc->modinsn[0] = 0xf852;
6724   dsc->modinsn[1] = 0x3;
6725   dsc->numinsns = 2;
6726
6727   dsc->cleanup = &cleanup_load;
6728
6729   return 0;
6730 }
6731
6732 static int
6733 thumb2_copy_load_reg_imm (struct gdbarch *gdbarch, uint16_t insn1,
6734                           uint16_t insn2, struct regcache *regs,
6735                           struct displaced_step_closure *dsc,
6736                           int writeback, int immed)
6737 {
6738   unsigned int rt = bits (insn2, 12, 15);
6739   unsigned int rn = bits (insn1, 0, 3);
6740   unsigned int rm = bits (insn2, 0, 3);  /* Only valid if !immed.  */
6741   /* In LDR (register), there is also a register Rm, which is not allowed to
6742      be PC, so we don't have to check it.  */
6743
6744   if (rt != ARM_PC_REGNUM && rn != ARM_PC_REGNUM)
6745     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "load",
6746                                         dsc);
6747
6748   if (debug_displaced)
6749     fprintf_unfiltered (gdb_stdlog,
6750                         "displaced: copying ldr r%d [r%d] insn %.4x%.4x\n",
6751                          rt, rn, insn1, insn2);
6752
6753   install_load_store (gdbarch, regs, dsc, 1, immed, writeback, 4,
6754                       0, rt, rm, rn);
6755
6756   dsc->u.ldst.restore_r4 = 0;
6757
6758   if (immed)
6759     /* ldr[b]<cond> rt, [rn, #imm], etc.
6760        ->
6761        ldr[b]<cond> r0, [r2, #imm].  */
6762     {
6763       dsc->modinsn[0] = (insn1 & 0xfff0) | 0x2;
6764       dsc->modinsn[1] = insn2 & 0x0fff;
6765     }
6766   else
6767     /* ldr[b]<cond> rt, [rn, rm], etc.
6768        ->
6769        ldr[b]<cond> r0, [r2, r3].  */
6770     {
6771       dsc->modinsn[0] = (insn1 & 0xfff0) | 0x2;
6772       dsc->modinsn[1] = (insn2 & 0x0ff0) | 0x3;
6773     }
6774
6775   dsc->numinsns = 2;
6776
6777   return 0;
6778 }
6779
6780
6781 static int
6782 arm_copy_ldr_str_ldrb_strb (struct gdbarch *gdbarch, uint32_t insn,
6783                             struct regcache *regs,
6784                             struct displaced_step_closure *dsc,
6785                             int load, int size, int usermode)
6786 {
6787   int immed = !bit (insn, 25);
6788   int writeback = (bit (insn, 24) == 0 || bit (insn, 21) != 0);
6789   unsigned int rt = bits (insn, 12, 15);
6790   unsigned int rn = bits (insn, 16, 19);
6791   unsigned int rm = bits (insn, 0, 3);  /* Only valid if !immed.  */
6792
6793   if (!insn_references_pc (insn, 0x000ff00ful))
6794     return arm_copy_unmodified (gdbarch, insn, "load/store", dsc);
6795
6796   if (debug_displaced)
6797     fprintf_unfiltered (gdb_stdlog,
6798                         "displaced: copying %s%s r%d [r%d] insn %.8lx\n",
6799                         load ? (size == 1 ? "ldrb" : "ldr")
6800                              : (size == 1 ? "strb" : "str"), usermode ? "t" : "",
6801                         rt, rn,
6802                         (unsigned long) insn);
6803
6804   install_load_store (gdbarch, regs, dsc, load, immed, writeback, size,
6805                       usermode, rt, rm, rn);
6806
6807   if (load || rt != ARM_PC_REGNUM)
6808     {
6809       dsc->u.ldst.restore_r4 = 0;
6810
6811       if (immed)
6812         /* {ldr,str}[b]<cond> rt, [rn, #imm], etc.
6813            ->
6814            {ldr,str}[b]<cond> r0, [r2, #imm].  */
6815         dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
6816       else
6817         /* {ldr,str}[b]<cond> rt, [rn, rm], etc.
6818            ->
6819            {ldr,str}[b]<cond> r0, [r2, r3].  */
6820         dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
6821     }
6822   else
6823     {
6824       /* We need to use r4 as scratch.  Make sure it's restored afterwards.  */
6825       dsc->u.ldst.restore_r4 = 1;
6826       dsc->modinsn[0] = 0xe92d8000;  /* push {pc} */
6827       dsc->modinsn[1] = 0xe8bd0010;  /* pop  {r4} */
6828       dsc->modinsn[2] = 0xe044400f;  /* sub r4, r4, pc.  */
6829       dsc->modinsn[3] = 0xe2844008;  /* add r4, r4, #8.  */
6830       dsc->modinsn[4] = 0xe0800004;  /* add r0, r0, r4.  */
6831
6832       /* As above.  */
6833       if (immed)
6834         dsc->modinsn[5] = (insn & 0xfff00fff) | 0x20000;
6835       else
6836         dsc->modinsn[5] = (insn & 0xfff00ff0) | 0x20003;
6837
6838       dsc->numinsns = 6;
6839     }
6840
6841   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
6842
6843   return 0;
6844 }
6845
6846 /* Cleanup LDM instructions with fully-populated register list.  This is an
6847    unfortunate corner case: it's impossible to implement correctly by modifying
6848    the instruction.  The issue is as follows: we have an instruction,
6849
6850    ldm rN, {r0-r15}
6851
6852    which we must rewrite to avoid loading PC.  A possible solution would be to
6853    do the load in two halves, something like (with suitable cleanup
6854    afterwards):
6855
6856    mov r8, rN
6857    ldm[id][ab] r8!, {r0-r7}
6858    str r7, <temp>
6859    ldm[id][ab] r8, {r7-r14}
6860    <bkpt>
6861
6862    but at present there's no suitable place for <temp>, since the scratch space
6863    is overwritten before the cleanup routine is called.  For now, we simply
6864    emulate the instruction.  */
6865
6866 static void
6867 cleanup_block_load_all (struct gdbarch *gdbarch, struct regcache *regs,
6868                         struct displaced_step_closure *dsc)
6869 {
6870   int inc = dsc->u.block.increment;
6871   int bump_before = dsc->u.block.before ? (inc ? 4 : -4) : 0;
6872   int bump_after = dsc->u.block.before ? 0 : (inc ? 4 : -4);
6873   uint32_t regmask = dsc->u.block.regmask;
6874   int regno = inc ? 0 : 15;
6875   CORE_ADDR xfer_addr = dsc->u.block.xfer_addr;
6876   int exception_return = dsc->u.block.load && dsc->u.block.user
6877                          && (regmask & 0x8000) != 0;
6878   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6879   int do_transfer = condition_true (dsc->u.block.cond, status);
6880   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6881
6882   if (!do_transfer)
6883     return;
6884
6885   /* If the instruction is ldm rN, {...pc}^, I don't think there's anything
6886      sensible we can do here.  Complain loudly.  */
6887   if (exception_return)
6888     error (_("Cannot single-step exception return"));
6889
6890   /* We don't handle any stores here for now.  */
6891   gdb_assert (dsc->u.block.load != 0);
6892
6893   if (debug_displaced)
6894     fprintf_unfiltered (gdb_stdlog, "displaced: emulating block transfer: "
6895                         "%s %s %s\n", dsc->u.block.load ? "ldm" : "stm",
6896                         dsc->u.block.increment ? "inc" : "dec",
6897                         dsc->u.block.before ? "before" : "after");
6898
6899   while (regmask)
6900     {
6901       uint32_t memword;
6902
6903       if (inc)
6904         while (regno <= ARM_PC_REGNUM && (regmask & (1 << regno)) == 0)
6905           regno++;
6906       else
6907         while (regno >= 0 && (regmask & (1 << regno)) == 0)
6908           regno--;
6909
6910       xfer_addr += bump_before;
6911
6912       memword = read_memory_unsigned_integer (xfer_addr, 4, byte_order);
6913       displaced_write_reg (regs, dsc, regno, memword, LOAD_WRITE_PC);
6914
6915       xfer_addr += bump_after;
6916
6917       regmask &= ~(1 << regno);
6918     }
6919
6920   if (dsc->u.block.writeback)
6921     displaced_write_reg (regs, dsc, dsc->u.block.rn, xfer_addr,
6922                          CANNOT_WRITE_PC);
6923 }
6924
6925 /* Clean up an STM which included the PC in the register list.  */
6926
6927 static void
6928 cleanup_block_store_pc (struct gdbarch *gdbarch, struct regcache *regs,
6929                         struct displaced_step_closure *dsc)
6930 {
6931   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6932   int store_executed = condition_true (dsc->u.block.cond, status);
6933   CORE_ADDR pc_stored_at, transferred_regs = bitcount (dsc->u.block.regmask);
6934   CORE_ADDR stm_insn_addr;
6935   uint32_t pc_val;
6936   long offset;
6937   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6938
6939   /* If condition code fails, there's nothing else to do.  */
6940   if (!store_executed)
6941     return;
6942
6943   if (dsc->u.block.increment)
6944     {
6945       pc_stored_at = dsc->u.block.xfer_addr + 4 * transferred_regs;
6946
6947       if (dsc->u.block.before)
6948          pc_stored_at += 4;
6949     }
6950   else
6951     {
6952       pc_stored_at = dsc->u.block.xfer_addr;
6953
6954       if (dsc->u.block.before)
6955          pc_stored_at -= 4;
6956     }
6957
6958   pc_val = read_memory_unsigned_integer (pc_stored_at, 4, byte_order);
6959   stm_insn_addr = dsc->scratch_base;
6960   offset = pc_val - stm_insn_addr;
6961
6962   if (debug_displaced)
6963     fprintf_unfiltered (gdb_stdlog, "displaced: detected PC offset %.8lx for "
6964                         "STM instruction\n", offset);
6965
6966   /* Rewrite the stored PC to the proper value for the non-displaced original
6967      instruction.  */
6968   write_memory_unsigned_integer (pc_stored_at, 4, byte_order,
6969                                  dsc->insn_addr + offset);
6970 }
6971
6972 /* Clean up an LDM which includes the PC in the register list.  We clumped all
6973    the registers in the transferred list into a contiguous range r0...rX (to
6974    avoid loading PC directly and losing control of the debugged program), so we
6975    must undo that here.  */
6976
6977 static void
6978 cleanup_block_load_pc (struct gdbarch *gdbarch,
6979                        struct regcache *regs,
6980                        struct displaced_step_closure *dsc)
6981 {
6982   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6983   int load_executed = condition_true (dsc->u.block.cond, status);
6984   unsigned int mask = dsc->u.block.regmask, write_reg = ARM_PC_REGNUM;
6985   unsigned int regs_loaded = bitcount (mask);
6986   unsigned int num_to_shuffle = regs_loaded, clobbered;
6987
6988   /* The method employed here will fail if the register list is fully populated
6989      (we need to avoid loading PC directly).  */
6990   gdb_assert (num_to_shuffle < 16);
6991
6992   if (!load_executed)
6993     return;
6994
6995   clobbered = (1 << num_to_shuffle) - 1;
6996
6997   while (num_to_shuffle > 0)
6998     {
6999       if ((mask & (1 << write_reg)) != 0)
7000         {
7001           unsigned int read_reg = num_to_shuffle - 1;
7002
7003           if (read_reg != write_reg)
7004             {
7005               ULONGEST rval = displaced_read_reg (regs, dsc, read_reg);
7006               displaced_write_reg (regs, dsc, write_reg, rval, LOAD_WRITE_PC);
7007               if (debug_displaced)
7008                 fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: move "
7009                                     "loaded register r%d to r%d\n"), read_reg,
7010                                     write_reg);
7011             }
7012           else if (debug_displaced)
7013             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: register "
7014                                 "r%d already in the right place\n"),
7015                                 write_reg);
7016
7017           clobbered &= ~(1 << write_reg);
7018
7019           num_to_shuffle--;
7020         }
7021
7022       write_reg--;
7023     }
7024
7025   /* Restore any registers we scribbled over.  */
7026   for (write_reg = 0; clobbered != 0; write_reg++)
7027     {
7028       if ((clobbered & (1 << write_reg)) != 0)
7029         {
7030           displaced_write_reg (regs, dsc, write_reg, dsc->tmp[write_reg],
7031                                CANNOT_WRITE_PC);
7032           if (debug_displaced)
7033             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: restored "
7034                                 "clobbered register r%d\n"), write_reg);
7035           clobbered &= ~(1 << write_reg);
7036         }
7037     }
7038
7039   /* Perform register writeback manually.  */
7040   if (dsc->u.block.writeback)
7041     {
7042       ULONGEST new_rn_val = dsc->u.block.xfer_addr;
7043
7044       if (dsc->u.block.increment)
7045         new_rn_val += regs_loaded * 4;
7046       else
7047         new_rn_val -= regs_loaded * 4;
7048
7049       displaced_write_reg (regs, dsc, dsc->u.block.rn, new_rn_val,
7050                            CANNOT_WRITE_PC);
7051     }
7052 }
7053
7054 /* Handle ldm/stm, apart from some tricky cases which are unlikely to occur
7055    in user-level code (in particular exception return, ldm rn, {...pc}^).  */
7056
7057 static int
7058 arm_copy_block_xfer (struct gdbarch *gdbarch, uint32_t insn,
7059                      struct regcache *regs,
7060                      struct displaced_step_closure *dsc)
7061 {
7062   int load = bit (insn, 20);
7063   int user = bit (insn, 22);
7064   int increment = bit (insn, 23);
7065   int before = bit (insn, 24);
7066   int writeback = bit (insn, 21);
7067   int rn = bits (insn, 16, 19);
7068
7069   /* Block transfers which don't mention PC can be run directly
7070      out-of-line.  */
7071   if (rn != ARM_PC_REGNUM && (insn & 0x8000) == 0)
7072     return arm_copy_unmodified (gdbarch, insn, "ldm/stm", dsc);
7073
7074   if (rn == ARM_PC_REGNUM)
7075     {
7076       warning (_("displaced: Unpredictable LDM or STM with "
7077                  "base register r15"));
7078       return arm_copy_unmodified (gdbarch, insn, "unpredictable ldm/stm", dsc);
7079     }
7080
7081   if (debug_displaced)
7082     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
7083                         "%.8lx\n", (unsigned long) insn);
7084
7085   dsc->u.block.xfer_addr = displaced_read_reg (regs, dsc, rn);
7086   dsc->u.block.rn = rn;
7087
7088   dsc->u.block.load = load;
7089   dsc->u.block.user = user;
7090   dsc->u.block.increment = increment;
7091   dsc->u.block.before = before;
7092   dsc->u.block.writeback = writeback;
7093   dsc->u.block.cond = bits (insn, 28, 31);
7094
7095   dsc->u.block.regmask = insn & 0xffff;
7096
7097   if (load)
7098     {
7099       if ((insn & 0xffff) == 0xffff)
7100         {
7101           /* LDM with a fully-populated register list.  This case is
7102              particularly tricky.  Implement for now by fully emulating the
7103              instruction (which might not behave perfectly in all cases, but
7104              these instructions should be rare enough for that not to matter
7105              too much).  */
7106           dsc->modinsn[0] = ARM_NOP;
7107
7108           dsc->cleanup = &cleanup_block_load_all;
7109         }
7110       else
7111         {
7112           /* LDM of a list of registers which includes PC.  Implement by
7113              rewriting the list of registers to be transferred into a
7114              contiguous chunk r0...rX before doing the transfer, then shuffling
7115              registers into the correct places in the cleanup routine.  */
7116           unsigned int regmask = insn & 0xffff;
7117           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
7118           unsigned int to = 0, from = 0, i, new_rn;
7119
7120           for (i = 0; i < num_in_list; i++)
7121             dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
7122
7123           /* Writeback makes things complicated.  We need to avoid clobbering
7124              the base register with one of the registers in our modified
7125              register list, but just using a different register can't work in
7126              all cases, e.g.:
7127
7128                ldm r14!, {r0-r13,pc}
7129
7130              which would need to be rewritten as:
7131
7132                ldm rN!, {r0-r14}
7133
7134              but that can't work, because there's no free register for N.
7135
7136              Solve this by turning off the writeback bit, and emulating
7137              writeback manually in the cleanup routine.  */
7138
7139           if (writeback)
7140             insn &= ~(1 << 21);
7141
7142           new_regmask = (1 << num_in_list) - 1;
7143
7144           if (debug_displaced)
7145             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
7146                                 "{..., pc}: original reg list %.4x, modified "
7147                                 "list %.4x\n"), rn, writeback ? "!" : "",
7148                                 (int) insn & 0xffff, new_regmask);
7149
7150           dsc->modinsn[0] = (insn & ~0xffff) | (new_regmask & 0xffff);
7151
7152           dsc->cleanup = &cleanup_block_load_pc;
7153         }
7154     }
7155   else
7156     {
7157       /* STM of a list of registers which includes PC.  Run the instruction
7158          as-is, but out of line: this will store the wrong value for the PC,
7159          so we must manually fix up the memory in the cleanup routine.
7160          Doing things this way has the advantage that we can auto-detect
7161          the offset of the PC write (which is architecture-dependent) in
7162          the cleanup routine.  */
7163       dsc->modinsn[0] = insn;
7164
7165       dsc->cleanup = &cleanup_block_store_pc;
7166     }
7167
7168   return 0;
7169 }
7170
7171 static int
7172 thumb2_copy_block_xfer (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
7173                         struct regcache *regs,
7174                         struct displaced_step_closure *dsc)
7175 {
7176   int rn = bits (insn1, 0, 3);
7177   int load = bit (insn1, 4);
7178   int writeback = bit (insn1, 5);
7179
7180   /* Block transfers which don't mention PC can be run directly
7181      out-of-line.  */
7182   if (rn != ARM_PC_REGNUM && (insn2 & 0x8000) == 0)
7183     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "ldm/stm", dsc);
7184
7185   if (rn == ARM_PC_REGNUM)
7186     {
7187       warning (_("displaced: Unpredictable LDM or STM with "
7188                  "base register r15"));
7189       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7190                                           "unpredictable ldm/stm", dsc);
7191     }
7192
7193   if (debug_displaced)
7194     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
7195                         "%.4x%.4x\n", insn1, insn2);
7196
7197   /* Clear bit 13, since it should be always zero.  */
7198   dsc->u.block.regmask = (insn2 & 0xdfff);
7199   dsc->u.block.rn = rn;
7200
7201   dsc->u.block.load = load;
7202   dsc->u.block.user = 0;
7203   dsc->u.block.increment = bit (insn1, 7);
7204   dsc->u.block.before = bit (insn1, 8);
7205   dsc->u.block.writeback = writeback;
7206   dsc->u.block.cond = INST_AL;
7207   dsc->u.block.xfer_addr = displaced_read_reg (regs, dsc, rn);
7208
7209   if (load)
7210     {
7211       if (dsc->u.block.regmask == 0xffff)
7212         {
7213           /* This branch is impossible to happen.  */
7214           gdb_assert (0);
7215         }
7216       else
7217         {
7218           unsigned int regmask = dsc->u.block.regmask;
7219           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
7220           unsigned int to = 0, from = 0, i, new_rn;
7221
7222           for (i = 0; i < num_in_list; i++)
7223             dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
7224
7225           if (writeback)
7226             insn1 &= ~(1 << 5);
7227
7228           new_regmask = (1 << num_in_list) - 1;
7229
7230           if (debug_displaced)
7231             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
7232                                 "{..., pc}: original reg list %.4x, modified "
7233                                 "list %.4x\n"), rn, writeback ? "!" : "",
7234                                 (int) dsc->u.block.regmask, new_regmask);
7235
7236           dsc->modinsn[0] = insn1;
7237           dsc->modinsn[1] = (new_regmask & 0xffff);
7238           dsc->numinsns = 2;
7239
7240           dsc->cleanup = &cleanup_block_load_pc;
7241         }
7242     }
7243   else
7244     {
7245       dsc->modinsn[0] = insn1;
7246       dsc->modinsn[1] = insn2;
7247       dsc->numinsns = 2;
7248       dsc->cleanup = &cleanup_block_store_pc;
7249     }
7250   return 0;
7251 }
7252
7253 /* Cleanup/copy SVC (SWI) instructions.  These two functions are overridden
7254    for Linux, where some SVC instructions must be treated specially.  */
7255
7256 static void
7257 cleanup_svc (struct gdbarch *gdbarch, struct regcache *regs,
7258              struct displaced_step_closure *dsc)
7259 {
7260   CORE_ADDR resume_addr = dsc->insn_addr + dsc->insn_size;
7261
7262   if (debug_displaced)
7263     fprintf_unfiltered (gdb_stdlog, "displaced: cleanup for svc, resume at "
7264                         "%.8lx\n", (unsigned long) resume_addr);
7265
7266   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, resume_addr, BRANCH_WRITE_PC);
7267 }
7268
7269
7270 /* Common copy routine for svc instruciton.  */
7271
7272 static int
7273 install_svc (struct gdbarch *gdbarch, struct regcache *regs,
7274              struct displaced_step_closure *dsc)
7275 {
7276   /* Preparation: none.
7277      Insn: unmodified svc.
7278      Cleanup: pc <- insn_addr + insn_size.  */
7279
7280   /* Pretend we wrote to the PC, so cleanup doesn't set PC to the next
7281      instruction.  */
7282   dsc->wrote_to_pc = 1;
7283
7284   /* Allow OS-specific code to override SVC handling.  */
7285   if (dsc->u.svc.copy_svc_os)
7286     return dsc->u.svc.copy_svc_os (gdbarch, regs, dsc);
7287   else
7288     {
7289       dsc->cleanup = &cleanup_svc;
7290       return 0;
7291     }
7292 }
7293
7294 static int
7295 arm_copy_svc (struct gdbarch *gdbarch, uint32_t insn,
7296               struct regcache *regs, struct displaced_step_closure *dsc)
7297 {
7298
7299   if (debug_displaced)
7300     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.8lx\n",
7301                         (unsigned long) insn);
7302
7303   dsc->modinsn[0] = insn;
7304
7305   return install_svc (gdbarch, regs, dsc);
7306 }
7307
7308 static int
7309 thumb_copy_svc (struct gdbarch *gdbarch, uint16_t insn,
7310                 struct regcache *regs, struct displaced_step_closure *dsc)
7311 {
7312
7313   if (debug_displaced)
7314     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.4x\n",
7315                         insn);
7316
7317   dsc->modinsn[0] = insn;
7318
7319   return install_svc (gdbarch, regs, dsc);
7320 }
7321
7322 /* Copy undefined instructions.  */
7323
7324 static int
7325 arm_copy_undef (struct gdbarch *gdbarch, uint32_t insn,
7326                 struct displaced_step_closure *dsc)
7327 {
7328   if (debug_displaced)
7329     fprintf_unfiltered (gdb_stdlog,
7330                         "displaced: copying undefined insn %.8lx\n",
7331                         (unsigned long) insn);
7332
7333   dsc->modinsn[0] = insn;
7334
7335   return 0;
7336 }
7337
7338 static int
7339 thumb_32bit_copy_undef (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
7340                        struct displaced_step_closure *dsc)
7341 {
7342
7343   if (debug_displaced)
7344     fprintf_unfiltered (gdb_stdlog, "displaced: copying undefined insn "
7345                        "%.4x %.4x\n", (unsigned short) insn1,
7346                        (unsigned short) insn2);
7347
7348   dsc->modinsn[0] = insn1;
7349   dsc->modinsn[1] = insn2;
7350   dsc->numinsns = 2;
7351
7352   return 0;
7353 }
7354
7355 /* Copy unpredictable instructions.  */
7356
7357 static int
7358 arm_copy_unpred (struct gdbarch *gdbarch, uint32_t insn,
7359                  struct displaced_step_closure *dsc)
7360 {
7361   if (debug_displaced)
7362     fprintf_unfiltered (gdb_stdlog, "displaced: copying unpredictable insn "
7363                         "%.8lx\n", (unsigned long) insn);
7364
7365   dsc->modinsn[0] = insn;
7366
7367   return 0;
7368 }
7369
7370 /* The decode_* functions are instruction decoding helpers.  They mostly follow
7371    the presentation in the ARM ARM.  */
7372
7373 static int
7374 arm_decode_misc_memhint_neon (struct gdbarch *gdbarch, uint32_t insn,
7375                               struct regcache *regs,
7376                               struct displaced_step_closure *dsc)
7377 {
7378   unsigned int op1 = bits (insn, 20, 26), op2 = bits (insn, 4, 7);
7379   unsigned int rn = bits (insn, 16, 19);
7380
7381   if (op1 == 0x10 && (op2 & 0x2) == 0x0 && (rn & 0xe) == 0x0)
7382     return arm_copy_unmodified (gdbarch, insn, "cps", dsc);
7383   else if (op1 == 0x10 && op2 == 0x0 && (rn & 0xe) == 0x1)
7384     return arm_copy_unmodified (gdbarch, insn, "setend", dsc);
7385   else if ((op1 & 0x60) == 0x20)
7386     return arm_copy_unmodified (gdbarch, insn, "neon dataproc", dsc);
7387   else if ((op1 & 0x71) == 0x40)
7388     return arm_copy_unmodified (gdbarch, insn, "neon elt/struct load/store",
7389                                 dsc);
7390   else if ((op1 & 0x77) == 0x41)
7391     return arm_copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
7392   else if ((op1 & 0x77) == 0x45)
7393     return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pli.  */
7394   else if ((op1 & 0x77) == 0x51)
7395     {
7396       if (rn != 0xf)
7397         return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
7398       else
7399         return arm_copy_unpred (gdbarch, insn, dsc);
7400     }
7401   else if ((op1 & 0x77) == 0x55)
7402     return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
7403   else if (op1 == 0x57)
7404     switch (op2)
7405       {
7406       case 0x1: return arm_copy_unmodified (gdbarch, insn, "clrex", dsc);
7407       case 0x4: return arm_copy_unmodified (gdbarch, insn, "dsb", dsc);
7408       case 0x5: return arm_copy_unmodified (gdbarch, insn, "dmb", dsc);
7409       case 0x6: return arm_copy_unmodified (gdbarch, insn, "isb", dsc);
7410       default: return arm_copy_unpred (gdbarch, insn, dsc);
7411       }
7412   else if ((op1 & 0x63) == 0x43)
7413     return arm_copy_unpred (gdbarch, insn, dsc);
7414   else if ((op2 & 0x1) == 0x0)
7415     switch (op1 & ~0x80)
7416       {
7417       case 0x61:
7418         return arm_copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
7419       case 0x65:
7420         return arm_copy_preload_reg (gdbarch, insn, regs, dsc);  /* pli reg.  */
7421       case 0x71: case 0x75:
7422         /* pld/pldw reg.  */
7423         return arm_copy_preload_reg (gdbarch, insn, regs, dsc);
7424       case 0x63: case 0x67: case 0x73: case 0x77:
7425         return arm_copy_unpred (gdbarch, insn, dsc);
7426       default:
7427         return arm_copy_undef (gdbarch, insn, dsc);
7428       }
7429   else
7430     return arm_copy_undef (gdbarch, insn, dsc);  /* Probably unreachable.  */
7431 }
7432
7433 static int
7434 arm_decode_unconditional (struct gdbarch *gdbarch, uint32_t insn,
7435                           struct regcache *regs,
7436                           struct displaced_step_closure *dsc)
7437 {
7438   if (bit (insn, 27) == 0)
7439     return arm_decode_misc_memhint_neon (gdbarch, insn, regs, dsc);
7440   /* Switch on bits: 0bxxxxx321xxx0xxxxxxxxxxxxxxxxxxxx.  */
7441   else switch (((insn & 0x7000000) >> 23) | ((insn & 0x100000) >> 20))
7442     {
7443     case 0x0: case 0x2:
7444       return arm_copy_unmodified (gdbarch, insn, "srs", dsc);
7445
7446     case 0x1: case 0x3:
7447       return arm_copy_unmodified (gdbarch, insn, "rfe", dsc);
7448
7449     case 0x4: case 0x5: case 0x6: case 0x7:
7450       return arm_copy_b_bl_blx (gdbarch, insn, regs, dsc);
7451
7452     case 0x8:
7453       switch ((insn & 0xe00000) >> 21)
7454         {
7455         case 0x1: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7:
7456           /* stc/stc2.  */
7457           return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7458
7459         case 0x2:
7460           return arm_copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
7461
7462         default:
7463           return arm_copy_undef (gdbarch, insn, dsc);
7464         }
7465
7466     case 0x9:
7467       {
7468          int rn_f = (bits (insn, 16, 19) == 0xf);
7469         switch ((insn & 0xe00000) >> 21)
7470           {
7471           case 0x1: case 0x3:
7472             /* ldc/ldc2 imm (undefined for rn == pc).  */
7473             return rn_f ? arm_copy_undef (gdbarch, insn, dsc)
7474                         : arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7475
7476           case 0x2:
7477             return arm_copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
7478
7479           case 0x4: case 0x5: case 0x6: case 0x7:
7480             /* ldc/ldc2 lit (undefined for rn != pc).  */
7481             return rn_f ? arm_copy_copro_load_store (gdbarch, insn, regs, dsc)
7482                         : arm_copy_undef (gdbarch, insn, dsc);
7483
7484           default:
7485             return arm_copy_undef (gdbarch, insn, dsc);
7486           }
7487       }
7488
7489     case 0xa:
7490       return arm_copy_unmodified (gdbarch, insn, "stc/stc2", dsc);
7491
7492     case 0xb:
7493       if (bits (insn, 16, 19) == 0xf)
7494         /* ldc/ldc2 lit.  */
7495         return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7496       else
7497         return arm_copy_undef (gdbarch, insn, dsc);
7498
7499     case 0xc:
7500       if (bit (insn, 4))
7501         return arm_copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
7502       else
7503         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7504
7505     case 0xd:
7506       if (bit (insn, 4))
7507         return arm_copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
7508       else
7509         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7510
7511     default:
7512       return arm_copy_undef (gdbarch, insn, dsc);
7513     }
7514 }
7515
7516 /* Decode miscellaneous instructions in dp/misc encoding space.  */
7517
7518 static int
7519 arm_decode_miscellaneous (struct gdbarch *gdbarch, uint32_t insn,
7520                           struct regcache *regs,
7521                           struct displaced_step_closure *dsc)
7522 {
7523   unsigned int op2 = bits (insn, 4, 6);
7524   unsigned int op = bits (insn, 21, 22);
7525   unsigned int op1 = bits (insn, 16, 19);
7526
7527   switch (op2)
7528     {
7529     case 0x0:
7530       return arm_copy_unmodified (gdbarch, insn, "mrs/msr", dsc);
7531
7532     case 0x1:
7533       if (op == 0x1)  /* bx.  */
7534         return arm_copy_bx_blx_reg (gdbarch, insn, regs, dsc);
7535       else if (op == 0x3)
7536         return arm_copy_unmodified (gdbarch, insn, "clz", dsc);
7537       else
7538         return arm_copy_undef (gdbarch, insn, dsc);
7539
7540     case 0x2:
7541       if (op == 0x1)
7542         /* Not really supported.  */
7543         return arm_copy_unmodified (gdbarch, insn, "bxj", dsc);
7544       else
7545         return arm_copy_undef (gdbarch, insn, dsc);
7546
7547     case 0x3:
7548       if (op == 0x1)
7549         return arm_copy_bx_blx_reg (gdbarch, insn,
7550                                 regs, dsc);  /* blx register.  */
7551       else
7552         return arm_copy_undef (gdbarch, insn, dsc);
7553
7554     case 0x5:
7555       return arm_copy_unmodified (gdbarch, insn, "saturating add/sub", dsc);
7556
7557     case 0x7:
7558       if (op == 0x1)
7559         return arm_copy_unmodified (gdbarch, insn, "bkpt", dsc);
7560       else if (op == 0x3)
7561         /* Not really supported.  */
7562         return arm_copy_unmodified (gdbarch, insn, "smc", dsc);
7563
7564     default:
7565       return arm_copy_undef (gdbarch, insn, dsc);
7566     }
7567 }
7568
7569 static int
7570 arm_decode_dp_misc (struct gdbarch *gdbarch, uint32_t insn,
7571                     struct regcache *regs,
7572                     struct displaced_step_closure *dsc)
7573 {
7574   if (bit (insn, 25))
7575     switch (bits (insn, 20, 24))
7576       {
7577       case 0x10:
7578         return arm_copy_unmodified (gdbarch, insn, "movw", dsc);
7579
7580       case 0x14:
7581         return arm_copy_unmodified (gdbarch, insn, "movt", dsc);
7582
7583       case 0x12: case 0x16:
7584         return arm_copy_unmodified (gdbarch, insn, "msr imm", dsc);
7585
7586       default:
7587         return arm_copy_alu_imm (gdbarch, insn, regs, dsc);
7588       }
7589   else
7590     {
7591       uint32_t op1 = bits (insn, 20, 24), op2 = bits (insn, 4, 7);
7592
7593       if ((op1 & 0x19) != 0x10 && (op2 & 0x1) == 0x0)
7594         return arm_copy_alu_reg (gdbarch, insn, regs, dsc);
7595       else if ((op1 & 0x19) != 0x10 && (op2 & 0x9) == 0x1)
7596         return arm_copy_alu_shifted_reg (gdbarch, insn, regs, dsc);
7597       else if ((op1 & 0x19) == 0x10 && (op2 & 0x8) == 0x0)
7598         return arm_decode_miscellaneous (gdbarch, insn, regs, dsc);
7599       else if ((op1 & 0x19) == 0x10 && (op2 & 0x9) == 0x8)
7600         return arm_copy_unmodified (gdbarch, insn, "halfword mul/mla", dsc);
7601       else if ((op1 & 0x10) == 0x00 && op2 == 0x9)
7602         return arm_copy_unmodified (gdbarch, insn, "mul/mla", dsc);
7603       else if ((op1 & 0x10) == 0x10 && op2 == 0x9)
7604         return arm_copy_unmodified (gdbarch, insn, "synch", dsc);
7605       else if (op2 == 0xb || (op2 & 0xd) == 0xd)
7606         /* 2nd arg means "unpriveleged".  */
7607         return arm_copy_extra_ld_st (gdbarch, insn, (op1 & 0x12) == 0x02, regs,
7608                                      dsc);
7609     }
7610
7611   /* Should be unreachable.  */
7612   return 1;
7613 }
7614
7615 static int
7616 arm_decode_ld_st_word_ubyte (struct gdbarch *gdbarch, uint32_t insn,
7617                              struct regcache *regs,
7618                              struct displaced_step_closure *dsc)
7619 {
7620   int a = bit (insn, 25), b = bit (insn, 4);
7621   uint32_t op1 = bits (insn, 20, 24);
7622   int rn_f = bits (insn, 16, 19) == 0xf;
7623
7624   if ((!a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02)
7625       || (a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02 && !b))
7626     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 4, 0);
7627   else if ((!a && (op1 & 0x17) == 0x02)
7628             || (a && (op1 & 0x17) == 0x02 && !b))
7629     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 4, 1);
7630   else if ((!a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03)
7631             || (a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03 && !b))
7632     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 4, 0);
7633   else if ((!a && (op1 & 0x17) == 0x03)
7634            || (a && (op1 & 0x17) == 0x03 && !b))
7635     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 4, 1);
7636   else if ((!a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06)
7637             || (a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06 && !b))
7638     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 0);
7639   else if ((!a && (op1 & 0x17) == 0x06)
7640            || (a && (op1 & 0x17) == 0x06 && !b))
7641     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 1);
7642   else if ((!a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07)
7643            || (a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07 && !b))
7644     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 0);
7645   else if ((!a && (op1 & 0x17) == 0x07)
7646            || (a && (op1 & 0x17) == 0x07 && !b))
7647     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 1);
7648
7649   /* Should be unreachable.  */
7650   return 1;
7651 }
7652
7653 static int
7654 arm_decode_media (struct gdbarch *gdbarch, uint32_t insn,
7655                   struct displaced_step_closure *dsc)
7656 {
7657   switch (bits (insn, 20, 24))
7658     {
7659     case 0x00: case 0x01: case 0x02: case 0x03:
7660       return arm_copy_unmodified (gdbarch, insn, "parallel add/sub signed", dsc);
7661
7662     case 0x04: case 0x05: case 0x06: case 0x07:
7663       return arm_copy_unmodified (gdbarch, insn, "parallel add/sub unsigned", dsc);
7664
7665     case 0x08: case 0x09: case 0x0a: case 0x0b:
7666     case 0x0c: case 0x0d: case 0x0e: case 0x0f:
7667       return arm_copy_unmodified (gdbarch, insn,
7668                               "decode/pack/unpack/saturate/reverse", dsc);
7669
7670     case 0x18:
7671       if (bits (insn, 5, 7) == 0)  /* op2.  */
7672          {
7673           if (bits (insn, 12, 15) == 0xf)
7674             return arm_copy_unmodified (gdbarch, insn, "usad8", dsc);
7675           else
7676             return arm_copy_unmodified (gdbarch, insn, "usada8", dsc);
7677         }
7678       else
7679          return arm_copy_undef (gdbarch, insn, dsc);
7680
7681     case 0x1a: case 0x1b:
7682       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
7683         return arm_copy_unmodified (gdbarch, insn, "sbfx", dsc);
7684       else
7685         return arm_copy_undef (gdbarch, insn, dsc);
7686
7687     case 0x1c: case 0x1d:
7688       if (bits (insn, 5, 6) == 0x0)  /* op2[1:0].  */
7689          {
7690           if (bits (insn, 0, 3) == 0xf)
7691             return arm_copy_unmodified (gdbarch, insn, "bfc", dsc);
7692           else
7693             return arm_copy_unmodified (gdbarch, insn, "bfi", dsc);
7694         }
7695       else
7696         return arm_copy_undef (gdbarch, insn, dsc);
7697
7698     case 0x1e: case 0x1f:
7699       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
7700         return arm_copy_unmodified (gdbarch, insn, "ubfx", dsc);
7701       else
7702         return arm_copy_undef (gdbarch, insn, dsc);
7703     }
7704
7705   /* Should be unreachable.  */
7706   return 1;
7707 }
7708
7709 static int
7710 arm_decode_b_bl_ldmstm (struct gdbarch *gdbarch, int32_t insn,
7711                         struct regcache *regs,
7712                         struct displaced_step_closure *dsc)
7713 {
7714   if (bit (insn, 25))
7715     return arm_copy_b_bl_blx (gdbarch, insn, regs, dsc);
7716   else
7717     return arm_copy_block_xfer (gdbarch, insn, regs, dsc);
7718 }
7719
7720 static int
7721 arm_decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint32_t insn,
7722                           struct regcache *regs,
7723                           struct displaced_step_closure *dsc)
7724 {
7725   unsigned int opcode = bits (insn, 20, 24);
7726
7727   switch (opcode)
7728     {
7729     case 0x04: case 0x05:  /* VFP/Neon mrrc/mcrr.  */
7730       return arm_copy_unmodified (gdbarch, insn, "vfp/neon mrrc/mcrr", dsc);
7731
7732     case 0x08: case 0x0a: case 0x0c: case 0x0e:
7733     case 0x12: case 0x16:
7734       return arm_copy_unmodified (gdbarch, insn, "vfp/neon vstm/vpush", dsc);
7735
7736     case 0x09: case 0x0b: case 0x0d: case 0x0f:
7737     case 0x13: case 0x17:
7738       return arm_copy_unmodified (gdbarch, insn, "vfp/neon vldm/vpop", dsc);
7739
7740     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
7741     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
7742       /* Note: no writeback for these instructions.  Bit 25 will always be
7743          zero though (via caller), so the following works OK.  */
7744       return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7745     }
7746
7747   /* Should be unreachable.  */
7748   return 1;
7749 }
7750
7751 /* Decode shifted register instructions.  */
7752
7753 static int
7754 thumb2_decode_dp_shift_reg (struct gdbarch *gdbarch, uint16_t insn1,
7755                             uint16_t insn2,  struct regcache *regs,
7756                             struct displaced_step_closure *dsc)
7757 {
7758   /* PC is only allowed to be used in instruction MOV.  */
7759
7760   unsigned int op = bits (insn1, 5, 8);
7761   unsigned int rn = bits (insn1, 0, 3);
7762
7763   if (op == 0x2 && rn == 0xf) /* MOV */
7764     return thumb2_copy_alu_imm (gdbarch, insn1, insn2, regs, dsc);
7765   else
7766     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7767                                         "dp (shift reg)", dsc);
7768 }
7769
7770
7771 /* Decode extension register load/store.  Exactly the same as
7772    arm_decode_ext_reg_ld_st.  */
7773
7774 static int
7775 thumb2_decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint16_t insn1,
7776                              uint16_t insn2,  struct regcache *regs,
7777                              struct displaced_step_closure *dsc)
7778 {
7779   unsigned int opcode = bits (insn1, 4, 8);
7780
7781   switch (opcode)
7782     {
7783     case 0x04: case 0x05:
7784       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7785                                           "vfp/neon vmov", dsc);
7786
7787     case 0x08: case 0x0c: /* 01x00 */
7788     case 0x0a: case 0x0e: /* 01x10 */
7789     case 0x12: case 0x16: /* 10x10 */
7790       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7791                                           "vfp/neon vstm/vpush", dsc);
7792
7793     case 0x09: case 0x0d: /* 01x01 */
7794     case 0x0b: case 0x0f: /* 01x11 */
7795     case 0x13: case 0x17: /* 10x11 */
7796       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7797                                           "vfp/neon vldm/vpop", dsc);
7798
7799     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
7800       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7801                                           "vstr", dsc);
7802     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
7803       return thumb2_copy_copro_load_store (gdbarch, insn1, insn2, regs, dsc);
7804     }
7805
7806   /* Should be unreachable.  */
7807   return 1;
7808 }
7809
7810 static int
7811 arm_decode_svc_copro (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
7812                       struct regcache *regs, struct displaced_step_closure *dsc)
7813 {
7814   unsigned int op1 = bits (insn, 20, 25);
7815   int op = bit (insn, 4);
7816   unsigned int coproc = bits (insn, 8, 11);
7817   unsigned int rn = bits (insn, 16, 19);
7818
7819   if ((op1 & 0x20) == 0x00 && (op1 & 0x3a) != 0x00 && (coproc & 0xe) == 0xa)
7820     return arm_decode_ext_reg_ld_st (gdbarch, insn, regs, dsc);
7821   else if ((op1 & 0x21) == 0x00 && (op1 & 0x3a) != 0x00
7822            && (coproc & 0xe) != 0xa)
7823     /* stc/stc2.  */
7824     return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7825   else if ((op1 & 0x21) == 0x01 && (op1 & 0x3a) != 0x00
7826            && (coproc & 0xe) != 0xa)
7827     /* ldc/ldc2 imm/lit.  */
7828     return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7829   else if ((op1 & 0x3e) == 0x00)
7830     return arm_copy_undef (gdbarch, insn, dsc);
7831   else if ((op1 & 0x3e) == 0x04 && (coproc & 0xe) == 0xa)
7832     return arm_copy_unmodified (gdbarch, insn, "neon 64bit xfer", dsc);
7833   else if (op1 == 0x04 && (coproc & 0xe) != 0xa)
7834     return arm_copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
7835   else if (op1 == 0x05 && (coproc & 0xe) != 0xa)
7836     return arm_copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
7837   else if ((op1 & 0x30) == 0x20 && !op)
7838     {
7839       if ((coproc & 0xe) == 0xa)
7840         return arm_copy_unmodified (gdbarch, insn, "vfp dataproc", dsc);
7841       else
7842         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7843     }
7844   else if ((op1 & 0x30) == 0x20 && op)
7845     return arm_copy_unmodified (gdbarch, insn, "neon 8/16/32 bit xfer", dsc);
7846   else if ((op1 & 0x31) == 0x20 && op && (coproc & 0xe) != 0xa)
7847     return arm_copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
7848   else if ((op1 & 0x31) == 0x21 && op && (coproc & 0xe) != 0xa)
7849     return arm_copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
7850   else if ((op1 & 0x30) == 0x30)
7851     return arm_copy_svc (gdbarch, insn, regs, dsc);
7852   else
7853     return arm_copy_undef (gdbarch, insn, dsc);  /* Possibly unreachable.  */
7854 }
7855
7856 static int
7857 thumb2_decode_svc_copro (struct gdbarch *gdbarch, uint16_t insn1,
7858                          uint16_t insn2, struct regcache *regs,
7859                          struct displaced_step_closure *dsc)
7860 {
7861   unsigned int coproc = bits (insn2, 8, 11);
7862   unsigned int op1 = bits (insn1, 4, 9);
7863   unsigned int bit_5_8 = bits (insn1, 5, 8);
7864   unsigned int bit_9 = bit (insn1, 9);
7865   unsigned int bit_4 = bit (insn1, 4);
7866   unsigned int rn = bits (insn1, 0, 3);
7867
7868   if (bit_9 == 0)
7869     {
7870       if (bit_5_8 == 2)
7871         return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7872                                             "neon 64bit xfer/mrrc/mrrc2/mcrr/mcrr2",
7873                                             dsc);
7874       else if (bit_5_8 == 0) /* UNDEFINED.  */
7875         return thumb_32bit_copy_undef (gdbarch, insn1, insn2, dsc);
7876       else
7877         {
7878            /*coproc is 101x.  SIMD/VFP, ext registers load/store.  */
7879           if ((coproc & 0xe) == 0xa)
7880             return thumb2_decode_ext_reg_ld_st (gdbarch, insn1, insn2, regs,
7881                                                 dsc);
7882           else /* coproc is not 101x.  */
7883             {
7884               if (bit_4 == 0) /* STC/STC2.  */
7885                 return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7886                                                     "stc/stc2", dsc);
7887               else /* LDC/LDC2 {literal, immeidate}.  */
7888                 return thumb2_copy_copro_load_store (gdbarch, insn1, insn2,
7889                                                      regs, dsc);
7890             }
7891         }
7892     }
7893   else
7894     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "coproc", dsc);
7895
7896   return 0;
7897 }
7898
7899 static void
7900 install_pc_relative (struct gdbarch *gdbarch, struct regcache *regs,
7901                      struct displaced_step_closure *dsc, int rd)
7902 {
7903   /* ADR Rd, #imm
7904
7905      Rewrite as:
7906
7907      Preparation: Rd <- PC
7908      Insn: ADD Rd, #imm
7909      Cleanup: Null.
7910   */
7911
7912   /* Rd <- PC */
7913   int val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
7914   displaced_write_reg (regs, dsc, rd, val, CANNOT_WRITE_PC);
7915 }
7916
7917 static int
7918 thumb_copy_pc_relative_16bit (struct gdbarch *gdbarch, struct regcache *regs,
7919                               struct displaced_step_closure *dsc,
7920                               int rd, unsigned int imm)
7921 {
7922
7923   /* Encoding T2: ADDS Rd, #imm */
7924   dsc->modinsn[0] = (0x3000 | (rd << 8) | imm);
7925
7926   install_pc_relative (gdbarch, regs, dsc, rd);
7927
7928   return 0;
7929 }
7930
7931 static int
7932 thumb_decode_pc_relative_16bit (struct gdbarch *gdbarch, uint16_t insn,
7933                                 struct regcache *regs,
7934                                 struct displaced_step_closure *dsc)
7935 {
7936   unsigned int rd = bits (insn, 8, 10);
7937   unsigned int imm8 = bits (insn, 0, 7);
7938
7939   if (debug_displaced)
7940     fprintf_unfiltered (gdb_stdlog,
7941                         "displaced: copying thumb adr r%d, #%d insn %.4x\n",
7942                         rd, imm8, insn);
7943
7944   return thumb_copy_pc_relative_16bit (gdbarch, regs, dsc, rd, imm8);
7945 }
7946
7947 static int
7948 thumb_copy_pc_relative_32bit (struct gdbarch *gdbarch, uint16_t insn1,
7949                               uint16_t insn2, struct regcache *regs,
7950                               struct displaced_step_closure *dsc)
7951 {
7952   unsigned int rd = bits (insn2, 8, 11);
7953   /* Since immediate has the same encoding in ADR ADD and SUB, so we simply
7954      extract raw immediate encoding rather than computing immediate.  When
7955      generating ADD or SUB instruction, we can simply perform OR operation to
7956      set immediate into ADD.  */
7957   unsigned int imm_3_8 = insn2 & 0x70ff;
7958   unsigned int imm_i = insn1 & 0x0400; /* Clear all bits except bit 10.  */
7959
7960   if (debug_displaced)
7961     fprintf_unfiltered (gdb_stdlog,
7962                         "displaced: copying thumb adr r%d, #%d:%d insn %.4x%.4x\n",
7963                         rd, imm_i, imm_3_8, insn1, insn2);
7964
7965   if (bit (insn1, 7)) /* Encoding T2 */
7966     {
7967       /* Encoding T3: SUB Rd, Rd, #imm */
7968       dsc->modinsn[0] = (0xf1a0 | rd | imm_i);
7969       dsc->modinsn[1] = ((rd << 8) | imm_3_8);
7970     }
7971   else /* Encoding T3 */
7972     {
7973       /* Encoding T3: ADD Rd, Rd, #imm */
7974       dsc->modinsn[0] = (0xf100 | rd | imm_i);
7975       dsc->modinsn[1] = ((rd << 8) | imm_3_8);
7976     }
7977   dsc->numinsns = 2;
7978
7979   install_pc_relative (gdbarch, regs, dsc, rd);
7980
7981   return 0;
7982 }
7983
7984 static int
7985 thumb_copy_16bit_ldr_literal (struct gdbarch *gdbarch, unsigned short insn1,
7986                               struct regcache *regs,
7987                               struct displaced_step_closure *dsc)
7988 {
7989   unsigned int rt = bits (insn1, 8, 10);
7990   unsigned int pc;
7991   int imm8 = (bits (insn1, 0, 7) << 2);
7992   CORE_ADDR from = dsc->insn_addr;
7993
7994   /* LDR Rd, #imm8
7995
7996      Rwrite as:
7997
7998      Preparation: tmp0 <- R0, tmp2 <- R2, tmp3 <- R3, R2 <- PC, R3 <- #imm8;
7999
8000      Insn: LDR R0, [R2, R3];
8001      Cleanup: R2 <- tmp2, R3 <- tmp3, Rd <- R0, R0 <- tmp0 */
8002
8003   if (debug_displaced)
8004     fprintf_unfiltered (gdb_stdlog,
8005                         "displaced: copying thumb ldr r%d [pc #%d]\n"
8006                         , rt, imm8);
8007
8008   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
8009   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
8010   dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
8011   pc = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
8012   /* The assembler calculates the required value of the offset from the
8013      Align(PC,4) value of this instruction to the label.  */
8014   pc = pc & 0xfffffffc;
8015
8016   displaced_write_reg (regs, dsc, 2, pc, CANNOT_WRITE_PC);
8017   displaced_write_reg (regs, dsc, 3, imm8, CANNOT_WRITE_PC);
8018
8019   dsc->rd = rt;
8020   dsc->u.ldst.xfersize = 4;
8021   dsc->u.ldst.rn = 0;
8022   dsc->u.ldst.immed = 0;
8023   dsc->u.ldst.writeback = 0;
8024   dsc->u.ldst.restore_r4 = 0;
8025
8026   dsc->modinsn[0] = 0x58d0; /* ldr r0, [r2, r3]*/
8027
8028   dsc->cleanup = &cleanup_load;
8029
8030   return 0;
8031 }
8032
8033 /* Copy Thumb cbnz/cbz insruction.  */
8034
8035 static int
8036 thumb_copy_cbnz_cbz (struct gdbarch *gdbarch, uint16_t insn1,
8037                      struct regcache *regs,
8038                      struct displaced_step_closure *dsc)
8039 {
8040   int non_zero = bit (insn1, 11);
8041   unsigned int imm5 = (bit (insn1, 9) << 6) | (bits (insn1, 3, 7) << 1);
8042   CORE_ADDR from = dsc->insn_addr;
8043   int rn = bits (insn1, 0, 2);
8044   int rn_val = displaced_read_reg (regs, dsc, rn);
8045
8046   dsc->u.branch.cond = (rn_val && non_zero) || (!rn_val && !non_zero);
8047   /* CBNZ and CBZ do not affect the condition flags.  If condition is true,
8048      set it INST_AL, so cleanup_branch will know branch is taken, otherwise,
8049      condition is false, let it be, cleanup_branch will do nothing.  */
8050   if (dsc->u.branch.cond)
8051     {
8052       dsc->u.branch.cond = INST_AL;
8053       dsc->u.branch.dest = from + 4 + imm5;
8054     }
8055   else
8056       dsc->u.branch.dest = from + 2;
8057
8058   dsc->u.branch.link = 0;
8059   dsc->u.branch.exchange = 0;
8060
8061   if (debug_displaced)
8062     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s [r%d = 0x%x]"
8063                         " insn %.4x to %.8lx\n", non_zero ? "cbnz" : "cbz",
8064                         rn, rn_val, insn1, dsc->u.branch.dest);
8065
8066   dsc->modinsn[0] = THUMB_NOP;
8067
8068   dsc->cleanup = &cleanup_branch;
8069   return 0;
8070 }
8071
8072 /* Copy Table Branch Byte/Halfword */
8073 static int
8074 thumb2_copy_table_branch (struct gdbarch *gdbarch, uint16_t insn1,
8075                           uint16_t insn2, struct regcache *regs,
8076                           struct displaced_step_closure *dsc)
8077 {
8078   ULONGEST rn_val, rm_val;
8079   int is_tbh = bit (insn2, 4);
8080   CORE_ADDR halfwords = 0;
8081   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
8082
8083   rn_val = displaced_read_reg (regs, dsc, bits (insn1, 0, 3));
8084   rm_val = displaced_read_reg (regs, dsc, bits (insn2, 0, 3));
8085
8086   if (is_tbh)
8087     {
8088       gdb_byte buf[2];
8089
8090       target_read_memory (rn_val + 2 * rm_val, buf, 2);
8091       halfwords = extract_unsigned_integer (buf, 2, byte_order);
8092     }
8093   else
8094     {
8095       gdb_byte buf[1];
8096
8097       target_read_memory (rn_val + rm_val, buf, 1);
8098       halfwords = extract_unsigned_integer (buf, 1, byte_order);
8099     }
8100
8101   if (debug_displaced)
8102     fprintf_unfiltered (gdb_stdlog, "displaced: %s base 0x%x offset 0x%x"
8103                         " offset 0x%x\n", is_tbh ? "tbh" : "tbb",
8104                         (unsigned int) rn_val, (unsigned int) rm_val,
8105                         (unsigned int) halfwords);
8106
8107   dsc->u.branch.cond = INST_AL;
8108   dsc->u.branch.link = 0;
8109   dsc->u.branch.exchange = 0;
8110   dsc->u.branch.dest = dsc->insn_addr + 4 + 2 * halfwords;
8111
8112   dsc->cleanup = &cleanup_branch;
8113
8114   return 0;
8115 }
8116
8117 static void
8118 cleanup_pop_pc_16bit_all (struct gdbarch *gdbarch, struct regcache *regs,
8119                           struct displaced_step_closure *dsc)
8120 {
8121   /* PC <- r7 */
8122   int val = displaced_read_reg (regs, dsc, 7);
8123   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, val, BX_WRITE_PC);
8124
8125   /* r7 <- r8 */
8126   val = displaced_read_reg (regs, dsc, 8);
8127   displaced_write_reg (regs, dsc, 7, val, CANNOT_WRITE_PC);
8128
8129   /* r8 <- tmp[0] */
8130   displaced_write_reg (regs, dsc, 8, dsc->tmp[0], CANNOT_WRITE_PC);
8131
8132 }
8133
8134 static int
8135 thumb_copy_pop_pc_16bit (struct gdbarch *gdbarch, unsigned short insn1,
8136                          struct regcache *regs,
8137                          struct displaced_step_closure *dsc)
8138 {
8139   dsc->u.block.regmask = insn1 & 0x00ff;
8140
8141   /* Rewrite instruction: POP {rX, rY, ...,rZ, PC}
8142      to :
8143
8144      (1) register list is full, that is, r0-r7 are used.
8145      Prepare: tmp[0] <- r8
8146
8147      POP {r0, r1, ...., r6, r7}; remove PC from reglist
8148      MOV r8, r7; Move value of r7 to r8;
8149      POP {r7}; Store PC value into r7.
8150
8151      Cleanup: PC <- r7, r7 <- r8, r8 <-tmp[0]
8152
8153      (2) register list is not full, supposing there are N registers in
8154      register list (except PC, 0 <= N <= 7).
8155      Prepare: for each i, 0 - N, tmp[i] <- ri.
8156
8157      POP {r0, r1, ...., rN};
8158
8159      Cleanup: Set registers in original reglist from r0 - rN.  Restore r0 - rN
8160      from tmp[] properly.
8161   */
8162   if (debug_displaced)
8163     fprintf_unfiltered (gdb_stdlog,
8164                         "displaced: copying thumb pop {%.8x, pc} insn %.4x\n",
8165                         dsc->u.block.regmask, insn1);
8166
8167   if (dsc->u.block.regmask == 0xff)
8168     {
8169       dsc->tmp[0] = displaced_read_reg (regs, dsc, 8);
8170
8171       dsc->modinsn[0] = (insn1 & 0xfeff); /* POP {r0,r1,...,r6, r7} */
8172       dsc->modinsn[1] = 0x46b8; /* MOV r8, r7 */
8173       dsc->modinsn[2] = 0xbc80; /* POP {r7} */
8174
8175       dsc->numinsns = 3;
8176       dsc->cleanup = &cleanup_pop_pc_16bit_all;
8177     }
8178   else
8179     {
8180       unsigned int num_in_list = bitcount (dsc->u.block.regmask);
8181       unsigned int new_regmask, bit = 1;
8182       unsigned int to = 0, from = 0, i, new_rn;
8183
8184       for (i = 0; i < num_in_list + 1; i++)
8185         dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
8186
8187       new_regmask = (1 << (num_in_list + 1)) - 1;
8188
8189       if (debug_displaced)
8190         fprintf_unfiltered (gdb_stdlog, _("displaced: POP "
8191                                           "{..., pc}: original reg list %.4x,"
8192                                           " modified list %.4x\n"),
8193                             (int) dsc->u.block.regmask, new_regmask);
8194
8195       dsc->u.block.regmask |= 0x8000;
8196       dsc->u.block.writeback = 0;
8197       dsc->u.block.cond = INST_AL;
8198
8199       dsc->modinsn[0] = (insn1 & ~0x1ff) | (new_regmask & 0xff);
8200
8201       dsc->cleanup = &cleanup_block_load_pc;
8202     }
8203
8204   return 0;
8205 }
8206
8207 static void
8208 thumb_process_displaced_16bit_insn (struct gdbarch *gdbarch, uint16_t insn1,
8209                                     struct regcache *regs,
8210                                     struct displaced_step_closure *dsc)
8211 {
8212   unsigned short op_bit_12_15 = bits (insn1, 12, 15);
8213   unsigned short op_bit_10_11 = bits (insn1, 10, 11);
8214   int err = 0;
8215
8216   /* 16-bit thumb instructions.  */
8217   switch (op_bit_12_15)
8218     {
8219       /* Shift (imme), add, subtract, move and compare.  */
8220     case 0: case 1: case 2: case 3:
8221       err = thumb_copy_unmodified_16bit (gdbarch, insn1,
8222                                          "shift/add/sub/mov/cmp",
8223                                          dsc);
8224       break;
8225     case 4:
8226       switch (op_bit_10_11)
8227         {
8228         case 0: /* Data-processing */
8229           err = thumb_copy_unmodified_16bit (gdbarch, insn1,
8230                                              "data-processing",
8231                                              dsc);
8232           break;
8233         case 1: /* Special data instructions and branch and exchange.  */
8234           {
8235             unsigned short op = bits (insn1, 7, 9);
8236             if (op == 6 || op == 7) /* BX or BLX */
8237               err = thumb_copy_bx_blx_reg (gdbarch, insn1, regs, dsc);
8238             else if (bits (insn1, 6, 7) != 0) /* ADD/MOV/CMP high registers.  */
8239               err = thumb_copy_alu_reg (gdbarch, insn1, regs, dsc);
8240             else
8241               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "special data",
8242                                                  dsc);
8243           }
8244           break;
8245         default: /* LDR (literal) */
8246           err = thumb_copy_16bit_ldr_literal (gdbarch, insn1, regs, dsc);
8247         }
8248       break;
8249     case 5: case 6: case 7: case 8: case 9: /* Load/Store single data item */
8250       err = thumb_copy_unmodified_16bit (gdbarch, insn1, "ldr/str", dsc);
8251       break;
8252     case 10:
8253       if (op_bit_10_11 < 2) /* Generate PC-relative address */
8254         err = thumb_decode_pc_relative_16bit (gdbarch, insn1, regs, dsc);
8255       else /* Generate SP-relative address */
8256         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "sp-relative", dsc);
8257       break;
8258     case 11: /* Misc 16-bit instructions */
8259       {
8260         switch (bits (insn1, 8, 11))
8261           {
8262           case 1: case 3:  case 9: case 11: /* CBNZ, CBZ */
8263             err = thumb_copy_cbnz_cbz (gdbarch, insn1, regs, dsc);
8264             break;
8265           case 12: case 13: /* POP */
8266             if (bit (insn1, 8)) /* PC is in register list.  */
8267               err = thumb_copy_pop_pc_16bit (gdbarch, insn1, regs, dsc);
8268             else
8269               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "pop", dsc);
8270             break;
8271           case 15: /* If-Then, and hints */
8272             if (bits (insn1, 0, 3))
8273               /* If-Then makes up to four following instructions conditional.
8274                  IT instruction itself is not conditional, so handle it as a
8275                  common unmodified instruction.  */
8276               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "If-Then",
8277                                                  dsc);
8278             else
8279               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "hints", dsc);
8280             break;
8281           default:
8282             err = thumb_copy_unmodified_16bit (gdbarch, insn1, "misc", dsc);
8283           }
8284       }
8285       break;
8286     case 12:
8287       if (op_bit_10_11 < 2) /* Store multiple registers */
8288         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "stm", dsc);
8289       else /* Load multiple registers */
8290         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "ldm", dsc);
8291       break;
8292     case 13: /* Conditional branch and supervisor call */
8293       if (bits (insn1, 9, 11) != 7) /* conditional branch */
8294         err = thumb_copy_b (gdbarch, insn1, dsc);
8295       else
8296         err = thumb_copy_svc (gdbarch, insn1, regs, dsc);
8297       break;
8298     case 14: /* Unconditional branch */
8299       err = thumb_copy_b (gdbarch, insn1, dsc);
8300       break;
8301     default:
8302       err = 1;
8303     }
8304
8305   if (err)
8306     internal_error (__FILE__, __LINE__,
8307                     _("thumb_process_displaced_16bit_insn: Instruction decode error"));
8308 }
8309
8310 static int
8311 decode_thumb_32bit_ld_mem_hints (struct gdbarch *gdbarch,
8312                                  uint16_t insn1, uint16_t insn2,
8313                                  struct regcache *regs,
8314                                  struct displaced_step_closure *dsc)
8315 {
8316   int rt = bits (insn2, 12, 15);
8317   int rn = bits (insn1, 0, 3);
8318   int op1 = bits (insn1, 7, 8);
8319   int err = 0;
8320
8321   switch (bits (insn1, 5, 6))
8322     {
8323     case 0: /* Load byte and memory hints */
8324       if (rt == 0xf) /* PLD/PLI */
8325         {
8326           if (rn == 0xf)
8327             /* PLD literal or Encoding T3 of PLI(immediate, literal).  */
8328             return thumb2_copy_preload (gdbarch, insn1, insn2, regs, dsc);
8329           else
8330             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8331                                                 "pli/pld", dsc);
8332         }
8333       else
8334         {
8335           if (rn == 0xf) /* LDRB/LDRSB (literal) */
8336             return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc,
8337                                              1);
8338           else
8339             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8340                                                 "ldrb{reg, immediate}/ldrbt",
8341                                                 dsc);
8342         }
8343
8344       break;
8345     case 1: /* Load halfword and memory hints.  */
8346       if (rt == 0xf) /* PLD{W} and Unalloc memory hint.  */
8347         return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8348                                             "pld/unalloc memhint", dsc);
8349       else
8350         {
8351           if (rn == 0xf)
8352             return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc,
8353                                              2);
8354           else
8355             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8356                                                 "ldrh/ldrht", dsc);
8357         }
8358       break;
8359     case 2: /* Load word */
8360       {
8361         int insn2_bit_8_11 = bits (insn2, 8, 11);
8362
8363         if (rn == 0xf)
8364           return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc, 4);
8365         else if (op1 == 0x1) /* Encoding T3 */
8366           return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs, dsc,
8367                                            0, 1);
8368         else /* op1 == 0x0 */
8369           {
8370             if (insn2_bit_8_11 == 0xc || (insn2_bit_8_11 & 0x9) == 0x9)
8371               /* LDR (immediate) */
8372               return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs,
8373                                                dsc, bit (insn2, 8), 1);
8374             else if (insn2_bit_8_11 == 0xe) /* LDRT */
8375               return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8376                                                   "ldrt", dsc);
8377             else
8378               /* LDR (register) */
8379               return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs,
8380                                                dsc, 0, 0);
8381           }
8382         break;
8383       }
8384     default:
8385       return thumb_32bit_copy_undef (gdbarch, insn1, insn2, dsc);
8386       break;
8387     }
8388   return 0;
8389 }
8390
8391 static void
8392 thumb_process_displaced_32bit_insn (struct gdbarch *gdbarch, uint16_t insn1,
8393                                     uint16_t insn2, struct regcache *regs,
8394                                     struct displaced_step_closure *dsc)
8395 {
8396   int err = 0;
8397   unsigned short op = bit (insn2, 15);
8398   unsigned int op1 = bits (insn1, 11, 12);
8399
8400   switch (op1)
8401     {
8402     case 1:
8403       {
8404         switch (bits (insn1, 9, 10))
8405           {
8406           case 0:
8407             if (bit (insn1, 6))
8408               {
8409                 /* Load/store {dual, execlusive}, table branch.  */
8410                 if (bits (insn1, 7, 8) == 1 && bits (insn1, 4, 5) == 1
8411                     && bits (insn2, 5, 7) == 0)
8412                   err = thumb2_copy_table_branch (gdbarch, insn1, insn2, regs,
8413                                                   dsc);
8414                 else
8415                   /* PC is not allowed to use in load/store {dual, exclusive}
8416                      instructions.  */
8417                   err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8418                                                      "load/store dual/ex", dsc);
8419               }
8420             else /* load/store multiple */
8421               {
8422                 switch (bits (insn1, 7, 8))
8423                   {
8424                   case 0: case 3: /* SRS, RFE */
8425                     err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8426                                                        "srs/rfe", dsc);
8427                     break;
8428                   case 1: case 2: /* LDM/STM/PUSH/POP */
8429                     err = thumb2_copy_block_xfer (gdbarch, insn1, insn2, regs, dsc);
8430                     break;
8431                   }
8432               }
8433             break;
8434
8435           case 1:
8436             /* Data-processing (shift register).  */
8437             err = thumb2_decode_dp_shift_reg (gdbarch, insn1, insn2, regs,
8438                                               dsc);
8439             break;
8440           default: /* Coprocessor instructions.  */
8441             err = thumb2_decode_svc_copro (gdbarch, insn1, insn2, regs, dsc);
8442             break;
8443           }
8444       break;
8445       }
8446     case 2: /* op1 = 2 */
8447       if (op) /* Branch and misc control.  */
8448         {
8449           if (bit (insn2, 14)  /* BLX/BL */
8450               || bit (insn2, 12) /* Unconditional branch */
8451               || (bits (insn1, 7, 9) != 0x7)) /* Conditional branch */
8452             err = thumb2_copy_b_bl_blx (gdbarch, insn1, insn2, regs, dsc);
8453           else
8454             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8455                                                "misc ctrl", dsc);
8456         }
8457       else
8458         {
8459           if (bit (insn1, 9)) /* Data processing (plain binary imm).  */
8460             {
8461               int op = bits (insn1, 4, 8);
8462               int rn = bits (insn1, 0, 3);
8463               if ((op == 0 || op == 0xa) && rn == 0xf)
8464                 err = thumb_copy_pc_relative_32bit (gdbarch, insn1, insn2,
8465                                                     regs, dsc);
8466               else
8467                 err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8468                                                    "dp/pb", dsc);
8469             }
8470           else /* Data processing (modified immeidate) */
8471             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8472                                                "dp/mi", dsc);
8473         }
8474       break;
8475     case 3: /* op1 = 3 */
8476       switch (bits (insn1, 9, 10))
8477         {
8478         case 0:
8479           if (bit (insn1, 4))
8480             err = decode_thumb_32bit_ld_mem_hints (gdbarch, insn1, insn2,
8481                                                    regs, dsc);
8482           else /* NEON Load/Store and Store single data item */
8483             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8484                                                "neon elt/struct load/store",
8485                                                dsc);
8486           break;
8487         case 1: /* op1 = 3, bits (9, 10) == 1 */
8488           switch (bits (insn1, 7, 8))
8489             {
8490             case 0: case 1: /* Data processing (register) */
8491               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8492                                                  "dp(reg)", dsc);
8493               break;
8494             case 2: /* Multiply and absolute difference */
8495               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8496                                                  "mul/mua/diff", dsc);
8497               break;
8498             case 3: /* Long multiply and divide */
8499               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8500                                                  "lmul/lmua", dsc);
8501               break;
8502             }
8503           break;
8504         default: /* Coprocessor instructions */
8505           err = thumb2_decode_svc_copro (gdbarch, insn1, insn2, regs, dsc);
8506           break;
8507         }
8508       break;
8509     default:
8510       err = 1;
8511     }
8512
8513   if (err)
8514     internal_error (__FILE__, __LINE__,
8515                     _("thumb_process_displaced_32bit_insn: Instruction decode error"));
8516
8517 }
8518
8519 static void
8520 thumb_process_displaced_insn (struct gdbarch *gdbarch, CORE_ADDR from,
8521                               CORE_ADDR to, struct regcache *regs,
8522                               struct displaced_step_closure *dsc)
8523 {
8524   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8525   uint16_t insn1
8526     = read_memory_unsigned_integer (from, 2, byte_order_for_code);
8527
8528   if (debug_displaced)
8529     fprintf_unfiltered (gdb_stdlog, "displaced: process thumb insn %.4x "
8530                         "at %.8lx\n", insn1, (unsigned long) from);
8531
8532   dsc->is_thumb = 1;
8533   dsc->insn_size = thumb_insn_size (insn1);
8534   if (thumb_insn_size (insn1) == 4)
8535     {
8536       uint16_t insn2
8537         = read_memory_unsigned_integer (from + 2, 2, byte_order_for_code);
8538       thumb_process_displaced_32bit_insn (gdbarch, insn1, insn2, regs, dsc);
8539     }
8540   else
8541     thumb_process_displaced_16bit_insn (gdbarch, insn1, regs, dsc);
8542 }
8543
8544 void
8545 arm_process_displaced_insn (struct gdbarch *gdbarch, CORE_ADDR from,
8546                             CORE_ADDR to, struct regcache *regs,
8547                             struct displaced_step_closure *dsc)
8548 {
8549   int err = 0;
8550   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8551   uint32_t insn;
8552
8553   /* Most displaced instructions use a 1-instruction scratch space, so set this
8554      here and override below if/when necessary.  */
8555   dsc->numinsns = 1;
8556   dsc->insn_addr = from;
8557   dsc->scratch_base = to;
8558   dsc->cleanup = NULL;
8559   dsc->wrote_to_pc = 0;
8560
8561   if (!displaced_in_arm_mode (regs))
8562     return thumb_process_displaced_insn (gdbarch, from, to, regs, dsc);
8563
8564   dsc->is_thumb = 0;
8565   dsc->insn_size = 4;
8566   insn = read_memory_unsigned_integer (from, 4, byte_order_for_code);
8567   if (debug_displaced)
8568     fprintf_unfiltered (gdb_stdlog, "displaced: stepping insn %.8lx "
8569                         "at %.8lx\n", (unsigned long) insn,
8570                         (unsigned long) from);
8571
8572   if ((insn & 0xf0000000) == 0xf0000000)
8573     err = arm_decode_unconditional (gdbarch, insn, regs, dsc);
8574   else switch (((insn & 0x10) >> 4) | ((insn & 0xe000000) >> 24))
8575     {
8576     case 0x0: case 0x1: case 0x2: case 0x3:
8577       err = arm_decode_dp_misc (gdbarch, insn, regs, dsc);
8578       break;
8579
8580     case 0x4: case 0x5: case 0x6:
8581       err = arm_decode_ld_st_word_ubyte (gdbarch, insn, regs, dsc);
8582       break;
8583
8584     case 0x7:
8585       err = arm_decode_media (gdbarch, insn, dsc);
8586       break;
8587
8588     case 0x8: case 0x9: case 0xa: case 0xb:
8589       err = arm_decode_b_bl_ldmstm (gdbarch, insn, regs, dsc);
8590       break;
8591
8592     case 0xc: case 0xd: case 0xe: case 0xf:
8593       err = arm_decode_svc_copro (gdbarch, insn, to, regs, dsc);
8594       break;
8595     }
8596
8597   if (err)
8598     internal_error (__FILE__, __LINE__,
8599                     _("arm_process_displaced_insn: Instruction decode error"));
8600 }
8601
8602 /* Actually set up the scratch space for a displaced instruction.  */
8603
8604 void
8605 arm_displaced_init_closure (struct gdbarch *gdbarch, CORE_ADDR from,
8606                             CORE_ADDR to, struct displaced_step_closure *dsc)
8607 {
8608   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8609   unsigned int i, len, offset;
8610   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8611   int size = dsc->is_thumb? 2 : 4;
8612   const gdb_byte *bkp_insn;
8613
8614   offset = 0;
8615   /* Poke modified instruction(s).  */
8616   for (i = 0; i < dsc->numinsns; i++)
8617     {
8618       if (debug_displaced)
8619         {
8620           fprintf_unfiltered (gdb_stdlog, "displaced: writing insn ");
8621           if (size == 4)
8622             fprintf_unfiltered (gdb_stdlog, "%.8lx",
8623                                 dsc->modinsn[i]);
8624           else if (size == 2)
8625             fprintf_unfiltered (gdb_stdlog, "%.4x",
8626                                 (unsigned short)dsc->modinsn[i]);
8627
8628           fprintf_unfiltered (gdb_stdlog, " at %.8lx\n",
8629                               (unsigned long) to + offset);
8630
8631         }
8632       write_memory_unsigned_integer (to + offset, size,
8633                                      byte_order_for_code,
8634                                      dsc->modinsn[i]);
8635       offset += size;
8636     }
8637
8638   /* Choose the correct breakpoint instruction.  */
8639   if (dsc->is_thumb)
8640     {
8641       bkp_insn = tdep->thumb_breakpoint;
8642       len = tdep->thumb_breakpoint_size;
8643     }
8644   else
8645     {
8646       bkp_insn = tdep->arm_breakpoint;
8647       len = tdep->arm_breakpoint_size;
8648     }
8649
8650   /* Put breakpoint afterwards.  */
8651   write_memory (to + offset, bkp_insn, len);
8652
8653   if (debug_displaced)
8654     fprintf_unfiltered (gdb_stdlog, "displaced: copy %s->%s: ",
8655                         paddress (gdbarch, from), paddress (gdbarch, to));
8656 }
8657
8658 /* Entry point for copying an instruction into scratch space for displaced
8659    stepping.  */
8660
8661 struct displaced_step_closure *
8662 arm_displaced_step_copy_insn (struct gdbarch *gdbarch,
8663                               CORE_ADDR from, CORE_ADDR to,
8664                               struct regcache *regs)
8665 {
8666   struct displaced_step_closure *dsc
8667     = xmalloc (sizeof (struct displaced_step_closure));
8668   arm_process_displaced_insn (gdbarch, from, to, regs, dsc);
8669   arm_displaced_init_closure (gdbarch, from, to, dsc);
8670
8671   return dsc;
8672 }
8673
8674 /* Entry point for cleaning things up after a displaced instruction has been
8675    single-stepped.  */
8676
8677 void
8678 arm_displaced_step_fixup (struct gdbarch *gdbarch,
8679                           struct displaced_step_closure *dsc,
8680                           CORE_ADDR from, CORE_ADDR to,
8681                           struct regcache *regs)
8682 {
8683   if (dsc->cleanup)
8684     dsc->cleanup (gdbarch, regs, dsc);
8685
8686   if (!dsc->wrote_to_pc)
8687     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
8688                                     dsc->insn_addr + dsc->insn_size);
8689
8690 }
8691
8692 #include "bfd-in2.h"
8693 #include "libcoff.h"
8694
8695 static int
8696 gdb_print_insn_arm (bfd_vma memaddr, disassemble_info *info)
8697 {
8698   struct gdbarch *gdbarch = info->application_data;
8699
8700   if (arm_pc_is_thumb (gdbarch, memaddr))
8701     {
8702       static asymbol *asym;
8703       static combined_entry_type ce;
8704       static struct coff_symbol_struct csym;
8705       static struct bfd fake_bfd;
8706       static bfd_target fake_target;
8707
8708       if (csym.native == NULL)
8709         {
8710           /* Create a fake symbol vector containing a Thumb symbol.
8711              This is solely so that the code in print_insn_little_arm() 
8712              and print_insn_big_arm() in opcodes/arm-dis.c will detect
8713              the presence of a Thumb symbol and switch to decoding
8714              Thumb instructions.  */
8715
8716           fake_target.flavour = bfd_target_coff_flavour;
8717           fake_bfd.xvec = &fake_target;
8718           ce.u.syment.n_sclass = C_THUMBEXTFUNC;
8719           csym.native = &ce;
8720           csym.symbol.the_bfd = &fake_bfd;
8721           csym.symbol.name = "fake";
8722           asym = (asymbol *) & csym;
8723         }
8724
8725       memaddr = UNMAKE_THUMB_ADDR (memaddr);
8726       info->symbols = &asym;
8727     }
8728   else
8729     info->symbols = NULL;
8730
8731   if (info->endian == BFD_ENDIAN_BIG)
8732     return print_insn_big_arm (memaddr, info);
8733   else
8734     return print_insn_little_arm (memaddr, info);
8735 }
8736
8737 /* The following define instruction sequences that will cause ARM
8738    cpu's to take an undefined instruction trap.  These are used to
8739    signal a breakpoint to GDB.
8740    
8741    The newer ARMv4T cpu's are capable of operating in ARM or Thumb
8742    modes.  A different instruction is required for each mode.  The ARM
8743    cpu's can also be big or little endian.  Thus four different
8744    instructions are needed to support all cases.
8745    
8746    Note: ARMv4 defines several new instructions that will take the
8747    undefined instruction trap.  ARM7TDMI is nominally ARMv4T, but does
8748    not in fact add the new instructions.  The new undefined
8749    instructions in ARMv4 are all instructions that had no defined
8750    behaviour in earlier chips.  There is no guarantee that they will
8751    raise an exception, but may be treated as NOP's.  In practice, it
8752    may only safe to rely on instructions matching:
8753    
8754    3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 
8755    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
8756    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
8757    
8758    Even this may only true if the condition predicate is true.  The
8759    following use a condition predicate of ALWAYS so it is always TRUE.
8760    
8761    There are other ways of forcing a breakpoint.  GNU/Linux, RISC iX,
8762    and NetBSD all use a software interrupt rather than an undefined
8763    instruction to force a trap.  This can be handled by by the
8764    abi-specific code during establishment of the gdbarch vector.  */
8765
8766 #define ARM_LE_BREAKPOINT {0xFE,0xDE,0xFF,0xE7}
8767 #define ARM_BE_BREAKPOINT {0xE7,0xFF,0xDE,0xFE}
8768 #define THUMB_LE_BREAKPOINT {0xbe,0xbe}
8769 #define THUMB_BE_BREAKPOINT {0xbe,0xbe}
8770
8771 static const gdb_byte arm_default_arm_le_breakpoint[] = ARM_LE_BREAKPOINT;
8772 static const gdb_byte arm_default_arm_be_breakpoint[] = ARM_BE_BREAKPOINT;
8773 static const gdb_byte arm_default_thumb_le_breakpoint[] = THUMB_LE_BREAKPOINT;
8774 static const gdb_byte arm_default_thumb_be_breakpoint[] = THUMB_BE_BREAKPOINT;
8775
8776 /* Determine the type and size of breakpoint to insert at PCPTR.  Uses
8777    the program counter value to determine whether a 16-bit or 32-bit
8778    breakpoint should be used.  It returns a pointer to a string of
8779    bytes that encode a breakpoint instruction, stores the length of
8780    the string to *lenptr, and adjusts the program counter (if
8781    necessary) to point to the actual memory location where the
8782    breakpoint should be inserted.  */
8783
8784 static const unsigned char *
8785 arm_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr, int *lenptr)
8786 {
8787   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8788   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8789
8790   if (arm_pc_is_thumb (gdbarch, *pcptr))
8791     {
8792       *pcptr = UNMAKE_THUMB_ADDR (*pcptr);
8793
8794       /* If we have a separate 32-bit breakpoint instruction for Thumb-2,
8795          check whether we are replacing a 32-bit instruction.  */
8796       if (tdep->thumb2_breakpoint != NULL)
8797         {
8798           gdb_byte buf[2];
8799           if (target_read_memory (*pcptr, buf, 2) == 0)
8800             {
8801               unsigned short inst1;
8802               inst1 = extract_unsigned_integer (buf, 2, byte_order_for_code);
8803               if (thumb_insn_size (inst1) == 4)
8804                 {
8805                   *lenptr = tdep->thumb2_breakpoint_size;
8806                   return tdep->thumb2_breakpoint;
8807                 }
8808             }
8809         }
8810
8811       *lenptr = tdep->thumb_breakpoint_size;
8812       return tdep->thumb_breakpoint;
8813     }
8814   else
8815     {
8816       *lenptr = tdep->arm_breakpoint_size;
8817       return tdep->arm_breakpoint;
8818     }
8819 }
8820
8821 static void
8822 arm_remote_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
8823                                int *kindptr)
8824 {
8825   arm_breakpoint_from_pc (gdbarch, pcptr, kindptr);
8826
8827   if (arm_pc_is_thumb (gdbarch, *pcptr) && *kindptr == 4)
8828     /* The documented magic value for a 32-bit Thumb-2 breakpoint, so
8829        that this is not confused with a 32-bit ARM breakpoint.  */
8830     *kindptr = 3;
8831 }
8832
8833 /* Extract from an array REGBUF containing the (raw) register state a
8834    function return value of type TYPE, and copy that, in virtual
8835    format, into VALBUF.  */
8836
8837 static void
8838 arm_extract_return_value (struct type *type, struct regcache *regs,
8839                           gdb_byte *valbuf)
8840 {
8841   struct gdbarch *gdbarch = get_regcache_arch (regs);
8842   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
8843
8844   if (TYPE_CODE_FLT == TYPE_CODE (type))
8845     {
8846       switch (gdbarch_tdep (gdbarch)->fp_model)
8847         {
8848         case ARM_FLOAT_FPA:
8849           {
8850             /* The value is in register F0 in internal format.  We need to
8851                extract the raw value and then convert it to the desired
8852                internal type.  */
8853             bfd_byte tmpbuf[FP_REGISTER_SIZE];
8854
8855             regcache_cooked_read (regs, ARM_F0_REGNUM, tmpbuf);
8856             convert_from_extended (floatformat_from_type (type), tmpbuf,
8857                                    valbuf, gdbarch_byte_order (gdbarch));
8858           }
8859           break;
8860
8861         case ARM_FLOAT_SOFT_FPA:
8862         case ARM_FLOAT_SOFT_VFP:
8863           /* ARM_FLOAT_VFP can arise if this is a variadic function so
8864              not using the VFP ABI code.  */
8865         case ARM_FLOAT_VFP:
8866           regcache_cooked_read (regs, ARM_A1_REGNUM, valbuf);
8867           if (TYPE_LENGTH (type) > 4)
8868             regcache_cooked_read (regs, ARM_A1_REGNUM + 1,
8869                                   valbuf + INT_REGISTER_SIZE);
8870           break;
8871
8872         default:
8873           internal_error (__FILE__, __LINE__,
8874                           _("arm_extract_return_value: "
8875                             "Floating point model not supported"));
8876           break;
8877         }
8878     }
8879   else if (TYPE_CODE (type) == TYPE_CODE_INT
8880            || TYPE_CODE (type) == TYPE_CODE_CHAR
8881            || TYPE_CODE (type) == TYPE_CODE_BOOL
8882            || TYPE_CODE (type) == TYPE_CODE_PTR
8883            || TYPE_CODE (type) == TYPE_CODE_REF
8884            || TYPE_CODE (type) == TYPE_CODE_ENUM)
8885     {
8886       /* If the type is a plain integer, then the access is
8887          straight-forward.  Otherwise we have to play around a bit
8888          more.  */
8889       int len = TYPE_LENGTH (type);
8890       int regno = ARM_A1_REGNUM;
8891       ULONGEST tmp;
8892
8893       while (len > 0)
8894         {
8895           /* By using store_unsigned_integer we avoid having to do
8896              anything special for small big-endian values.  */
8897           regcache_cooked_read_unsigned (regs, regno++, &tmp);
8898           store_unsigned_integer (valbuf, 
8899                                   (len > INT_REGISTER_SIZE
8900                                    ? INT_REGISTER_SIZE : len),
8901                                   byte_order, tmp);
8902           len -= INT_REGISTER_SIZE;
8903           valbuf += INT_REGISTER_SIZE;
8904         }
8905     }
8906   else
8907     {
8908       /* For a structure or union the behaviour is as if the value had
8909          been stored to word-aligned memory and then loaded into 
8910          registers with 32-bit load instruction(s).  */
8911       int len = TYPE_LENGTH (type);
8912       int regno = ARM_A1_REGNUM;
8913       bfd_byte tmpbuf[INT_REGISTER_SIZE];
8914
8915       while (len > 0)
8916         {
8917           regcache_cooked_read (regs, regno++, tmpbuf);
8918           memcpy (valbuf, tmpbuf,
8919                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
8920           len -= INT_REGISTER_SIZE;
8921           valbuf += INT_REGISTER_SIZE;
8922         }
8923     }
8924 }
8925
8926
8927 /* Will a function return an aggregate type in memory or in a
8928    register?  Return 0 if an aggregate type can be returned in a
8929    register, 1 if it must be returned in memory.  */
8930
8931 static int
8932 arm_return_in_memory (struct gdbarch *gdbarch, struct type *type)
8933 {
8934   int nRc;
8935   enum type_code code;
8936
8937   CHECK_TYPEDEF (type);
8938
8939   /* In the ARM ABI, "integer" like aggregate types are returned in
8940      registers.  For an aggregate type to be integer like, its size
8941      must be less than or equal to INT_REGISTER_SIZE and the
8942      offset of each addressable subfield must be zero.  Note that bit
8943      fields are not addressable, and all addressable subfields of
8944      unions always start at offset zero.
8945
8946      This function is based on the behaviour of GCC 2.95.1.
8947      See: gcc/arm.c: arm_return_in_memory() for details.
8948
8949      Note: All versions of GCC before GCC 2.95.2 do not set up the
8950      parameters correctly for a function returning the following
8951      structure: struct { float f;}; This should be returned in memory,
8952      not a register.  Richard Earnshaw sent me a patch, but I do not
8953      know of any way to detect if a function like the above has been
8954      compiled with the correct calling convention.  */
8955
8956   /* All aggregate types that won't fit in a register must be returned
8957      in memory.  */
8958   if (TYPE_LENGTH (type) > INT_REGISTER_SIZE)
8959     {
8960       return 1;
8961     }
8962
8963   /* The AAPCS says all aggregates not larger than a word are returned
8964      in a register.  */
8965   if (gdbarch_tdep (gdbarch)->arm_abi != ARM_ABI_APCS)
8966     return 0;
8967
8968   /* The only aggregate types that can be returned in a register are
8969      structs and unions.  Arrays must be returned in memory.  */
8970   code = TYPE_CODE (type);
8971   if ((TYPE_CODE_STRUCT != code) && (TYPE_CODE_UNION != code))
8972     {
8973       return 1;
8974     }
8975
8976   /* Assume all other aggregate types can be returned in a register.
8977      Run a check for structures, unions and arrays.  */
8978   nRc = 0;
8979
8980   if ((TYPE_CODE_STRUCT == code) || (TYPE_CODE_UNION == code))
8981     {
8982       int i;
8983       /* Need to check if this struct/union is "integer" like.  For
8984          this to be true, its size must be less than or equal to
8985          INT_REGISTER_SIZE and the offset of each addressable
8986          subfield must be zero.  Note that bit fields are not
8987          addressable, and unions always start at offset zero.  If any
8988          of the subfields is a floating point type, the struct/union
8989          cannot be an integer type.  */
8990
8991       /* For each field in the object, check:
8992          1) Is it FP? --> yes, nRc = 1;
8993          2) Is it addressable (bitpos != 0) and
8994          not packed (bitsize == 0)?
8995          --> yes, nRc = 1  
8996        */
8997
8998       for (i = 0; i < TYPE_NFIELDS (type); i++)
8999         {
9000           enum type_code field_type_code;
9001           field_type_code = TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type,
9002                                                                        i)));
9003
9004           /* Is it a floating point type field?  */
9005           if (field_type_code == TYPE_CODE_FLT)
9006             {
9007               nRc = 1;
9008               break;
9009             }
9010
9011           /* If bitpos != 0, then we have to care about it.  */
9012           if (TYPE_FIELD_BITPOS (type, i) != 0)
9013             {
9014               /* Bitfields are not addressable.  If the field bitsize is 
9015                  zero, then the field is not packed.  Hence it cannot be
9016                  a bitfield or any other packed type.  */
9017               if (TYPE_FIELD_BITSIZE (type, i) == 0)
9018                 {
9019                   nRc = 1;
9020                   break;
9021                 }
9022             }
9023         }
9024     }
9025
9026   return nRc;
9027 }
9028
9029 /* Write into appropriate registers a function return value of type
9030    TYPE, given in virtual format.  */
9031
9032 static void
9033 arm_store_return_value (struct type *type, struct regcache *regs,
9034                         const gdb_byte *valbuf)
9035 {
9036   struct gdbarch *gdbarch = get_regcache_arch (regs);
9037   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
9038
9039   if (TYPE_CODE (type) == TYPE_CODE_FLT)
9040     {
9041       gdb_byte buf[MAX_REGISTER_SIZE];
9042
9043       switch (gdbarch_tdep (gdbarch)->fp_model)
9044         {
9045         case ARM_FLOAT_FPA:
9046
9047           convert_to_extended (floatformat_from_type (type), buf, valbuf,
9048                                gdbarch_byte_order (gdbarch));
9049           regcache_cooked_write (regs, ARM_F0_REGNUM, buf);
9050           break;
9051
9052         case ARM_FLOAT_SOFT_FPA:
9053         case ARM_FLOAT_SOFT_VFP:
9054           /* ARM_FLOAT_VFP can arise if this is a variadic function so
9055              not using the VFP ABI code.  */
9056         case ARM_FLOAT_VFP:
9057           regcache_cooked_write (regs, ARM_A1_REGNUM, valbuf);
9058           if (TYPE_LENGTH (type) > 4)
9059             regcache_cooked_write (regs, ARM_A1_REGNUM + 1, 
9060                                    valbuf + INT_REGISTER_SIZE);
9061           break;
9062
9063         default:
9064           internal_error (__FILE__, __LINE__,
9065                           _("arm_store_return_value: Floating "
9066                             "point model not supported"));
9067           break;
9068         }
9069     }
9070   else if (TYPE_CODE (type) == TYPE_CODE_INT
9071            || TYPE_CODE (type) == TYPE_CODE_CHAR
9072            || TYPE_CODE (type) == TYPE_CODE_BOOL
9073            || TYPE_CODE (type) == TYPE_CODE_PTR
9074            || TYPE_CODE (type) == TYPE_CODE_REF
9075            || TYPE_CODE (type) == TYPE_CODE_ENUM)
9076     {
9077       if (TYPE_LENGTH (type) <= 4)
9078         {
9079           /* Values of one word or less are zero/sign-extended and
9080              returned in r0.  */
9081           bfd_byte tmpbuf[INT_REGISTER_SIZE];
9082           LONGEST val = unpack_long (type, valbuf);
9083
9084           store_signed_integer (tmpbuf, INT_REGISTER_SIZE, byte_order, val);
9085           regcache_cooked_write (regs, ARM_A1_REGNUM, tmpbuf);
9086         }
9087       else
9088         {
9089           /* Integral values greater than one word are stored in consecutive
9090              registers starting with r0.  This will always be a multiple of
9091              the regiser size.  */
9092           int len = TYPE_LENGTH (type);
9093           int regno = ARM_A1_REGNUM;
9094
9095           while (len > 0)
9096             {
9097               regcache_cooked_write (regs, regno++, valbuf);
9098               len -= INT_REGISTER_SIZE;
9099               valbuf += INT_REGISTER_SIZE;
9100             }
9101         }
9102     }
9103   else
9104     {
9105       /* For a structure or union the behaviour is as if the value had
9106          been stored to word-aligned memory and then loaded into 
9107          registers with 32-bit load instruction(s).  */
9108       int len = TYPE_LENGTH (type);
9109       int regno = ARM_A1_REGNUM;
9110       bfd_byte tmpbuf[INT_REGISTER_SIZE];
9111
9112       while (len > 0)
9113         {
9114           memcpy (tmpbuf, valbuf,
9115                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
9116           regcache_cooked_write (regs, regno++, tmpbuf);
9117           len -= INT_REGISTER_SIZE;
9118           valbuf += INT_REGISTER_SIZE;
9119         }
9120     }
9121 }
9122
9123
9124 /* Handle function return values.  */
9125
9126 static enum return_value_convention
9127 arm_return_value (struct gdbarch *gdbarch, struct value *function,
9128                   struct type *valtype, struct regcache *regcache,
9129                   gdb_byte *readbuf, const gdb_byte *writebuf)
9130 {
9131   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
9132   struct type *func_type = function ? value_type (function) : NULL;
9133   enum arm_vfp_cprc_base_type vfp_base_type;
9134   int vfp_base_count;
9135
9136   if (arm_vfp_abi_for_function (gdbarch, func_type)
9137       && arm_vfp_call_candidate (valtype, &vfp_base_type, &vfp_base_count))
9138     {
9139       int reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
9140       int unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
9141       int i;
9142       for (i = 0; i < vfp_base_count; i++)
9143         {
9144           if (reg_char == 'q')
9145             {
9146               if (writebuf)
9147                 arm_neon_quad_write (gdbarch, regcache, i,
9148                                      writebuf + i * unit_length);
9149
9150               if (readbuf)
9151                 arm_neon_quad_read (gdbarch, regcache, i,
9152                                     readbuf + i * unit_length);
9153             }
9154           else
9155             {
9156               char name_buf[4];
9157               int regnum;
9158
9159               xsnprintf (name_buf, sizeof (name_buf), "%c%d", reg_char, i);
9160               regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9161                                                     strlen (name_buf));
9162               if (writebuf)
9163                 regcache_cooked_write (regcache, regnum,
9164                                        writebuf + i * unit_length);
9165               if (readbuf)
9166                 regcache_cooked_read (regcache, regnum,
9167                                       readbuf + i * unit_length);
9168             }
9169         }
9170       return RETURN_VALUE_REGISTER_CONVENTION;
9171     }
9172
9173   if (TYPE_CODE (valtype) == TYPE_CODE_STRUCT
9174       || TYPE_CODE (valtype) == TYPE_CODE_UNION
9175       || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
9176     {
9177       if (tdep->struct_return == pcc_struct_return
9178           || arm_return_in_memory (gdbarch, valtype))
9179         return RETURN_VALUE_STRUCT_CONVENTION;
9180     }
9181
9182   /* AAPCS returns complex types longer than a register in memory.  */
9183   if (tdep->arm_abi != ARM_ABI_APCS
9184       && TYPE_CODE (valtype) == TYPE_CODE_COMPLEX
9185       && TYPE_LENGTH (valtype) > INT_REGISTER_SIZE)
9186     return RETURN_VALUE_STRUCT_CONVENTION;
9187
9188   if (writebuf)
9189     arm_store_return_value (valtype, regcache, writebuf);
9190
9191   if (readbuf)
9192     arm_extract_return_value (valtype, regcache, readbuf);
9193
9194   return RETURN_VALUE_REGISTER_CONVENTION;
9195 }
9196
9197
9198 static int
9199 arm_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
9200 {
9201   struct gdbarch *gdbarch = get_frame_arch (frame);
9202   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
9203   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
9204   CORE_ADDR jb_addr;
9205   gdb_byte buf[INT_REGISTER_SIZE];
9206   
9207   jb_addr = get_frame_register_unsigned (frame, ARM_A1_REGNUM);
9208
9209   if (target_read_memory (jb_addr + tdep->jb_pc * tdep->jb_elt_size, buf,
9210                           INT_REGISTER_SIZE))
9211     return 0;
9212
9213   *pc = extract_unsigned_integer (buf, INT_REGISTER_SIZE, byte_order);
9214   return 1;
9215 }
9216
9217 /* Recognize GCC and GNU ld's trampolines.  If we are in a trampoline,
9218    return the target PC.  Otherwise return 0.  */
9219
9220 CORE_ADDR
9221 arm_skip_stub (struct frame_info *frame, CORE_ADDR pc)
9222 {
9223   const char *name;
9224   int namelen;
9225   CORE_ADDR start_addr;
9226
9227   /* Find the starting address and name of the function containing the PC.  */
9228   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
9229     return 0;
9230
9231   /* If PC is in a Thumb call or return stub, return the address of the
9232      target PC, which is in a register.  The thunk functions are called
9233      _call_via_xx, where x is the register name.  The possible names
9234      are r0-r9, sl, fp, ip, sp, and lr.  ARM RealView has similar
9235      functions, named __ARM_call_via_r[0-7].  */
9236   if (strncmp (name, "_call_via_", 10) == 0
9237       || strncmp (name, "__ARM_call_via_", strlen ("__ARM_call_via_")) == 0)
9238     {
9239       /* Use the name suffix to determine which register contains the
9240          target PC.  */
9241       static char *table[15] =
9242       {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
9243        "r8", "r9", "sl", "fp", "ip", "sp", "lr"
9244       };
9245       int regno;
9246       int offset = strlen (name) - 2;
9247
9248       for (regno = 0; regno <= 14; regno++)
9249         if (strcmp (&name[offset], table[regno]) == 0)
9250           return get_frame_register_unsigned (frame, regno);
9251     }
9252
9253   /* GNU ld generates __foo_from_arm or __foo_from_thumb for
9254      non-interworking calls to foo.  We could decode the stubs
9255      to find the target but it's easier to use the symbol table.  */
9256   namelen = strlen (name);
9257   if (name[0] == '_' && name[1] == '_'
9258       && ((namelen > 2 + strlen ("_from_thumb")
9259            && strncmp (name + namelen - strlen ("_from_thumb"), "_from_thumb",
9260                        strlen ("_from_thumb")) == 0)
9261           || (namelen > 2 + strlen ("_from_arm")
9262               && strncmp (name + namelen - strlen ("_from_arm"), "_from_arm",
9263                           strlen ("_from_arm")) == 0)))
9264     {
9265       char *target_name;
9266       int target_len = namelen - 2;
9267       struct bound_minimal_symbol minsym;
9268       struct objfile *objfile;
9269       struct obj_section *sec;
9270
9271       if (name[namelen - 1] == 'b')
9272         target_len -= strlen ("_from_thumb");
9273       else
9274         target_len -= strlen ("_from_arm");
9275
9276       target_name = alloca (target_len + 1);
9277       memcpy (target_name, name + 2, target_len);
9278       target_name[target_len] = '\0';
9279
9280       sec = find_pc_section (pc);
9281       objfile = (sec == NULL) ? NULL : sec->objfile;
9282       minsym = lookup_minimal_symbol (target_name, NULL, objfile);
9283       if (minsym.minsym != NULL)
9284         return BMSYMBOL_VALUE_ADDRESS (minsym);
9285       else
9286         return 0;
9287     }
9288
9289   return 0;                     /* not a stub */
9290 }
9291
9292 static void
9293 set_arm_command (char *args, int from_tty)
9294 {
9295   printf_unfiltered (_("\
9296 \"set arm\" must be followed by an apporpriate subcommand.\n"));
9297   help_list (setarmcmdlist, "set arm ", all_commands, gdb_stdout);
9298 }
9299
9300 static void
9301 show_arm_command (char *args, int from_tty)
9302 {
9303   cmd_show_list (showarmcmdlist, from_tty, "");
9304 }
9305
9306 static void
9307 arm_update_current_architecture (void)
9308 {
9309   struct gdbarch_info info;
9310
9311   /* If the current architecture is not ARM, we have nothing to do.  */
9312   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_arm)
9313     return;
9314
9315   /* Update the architecture.  */
9316   gdbarch_info_init (&info);
9317
9318   if (!gdbarch_update_p (info))
9319     internal_error (__FILE__, __LINE__, _("could not update architecture"));
9320 }
9321
9322 static void
9323 set_fp_model_sfunc (char *args, int from_tty,
9324                     struct cmd_list_element *c)
9325 {
9326   enum arm_float_model fp_model;
9327
9328   for (fp_model = ARM_FLOAT_AUTO; fp_model != ARM_FLOAT_LAST; fp_model++)
9329     if (strcmp (current_fp_model, fp_model_strings[fp_model]) == 0)
9330       {
9331         arm_fp_model = fp_model;
9332         break;
9333       }
9334
9335   if (fp_model == ARM_FLOAT_LAST)
9336     internal_error (__FILE__, __LINE__, _("Invalid fp model accepted: %s."),
9337                     current_fp_model);
9338
9339   arm_update_current_architecture ();
9340 }
9341
9342 static void
9343 show_fp_model (struct ui_file *file, int from_tty,
9344                struct cmd_list_element *c, const char *value)
9345 {
9346   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9347
9348   if (arm_fp_model == ARM_FLOAT_AUTO
9349       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_arm)
9350     fprintf_filtered (file, _("\
9351 The current ARM floating point model is \"auto\" (currently \"%s\").\n"),
9352                       fp_model_strings[tdep->fp_model]);
9353   else
9354     fprintf_filtered (file, _("\
9355 The current ARM floating point model is \"%s\".\n"),
9356                       fp_model_strings[arm_fp_model]);
9357 }
9358
9359 static void
9360 arm_set_abi (char *args, int from_tty,
9361              struct cmd_list_element *c)
9362 {
9363   enum arm_abi_kind arm_abi;
9364
9365   for (arm_abi = ARM_ABI_AUTO; arm_abi != ARM_ABI_LAST; arm_abi++)
9366     if (strcmp (arm_abi_string, arm_abi_strings[arm_abi]) == 0)
9367       {
9368         arm_abi_global = arm_abi;
9369         break;
9370       }
9371
9372   if (arm_abi == ARM_ABI_LAST)
9373     internal_error (__FILE__, __LINE__, _("Invalid ABI accepted: %s."),
9374                     arm_abi_string);
9375
9376   arm_update_current_architecture ();
9377 }
9378
9379 static void
9380 arm_show_abi (struct ui_file *file, int from_tty,
9381              struct cmd_list_element *c, const char *value)
9382 {
9383   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9384
9385   if (arm_abi_global == ARM_ABI_AUTO
9386       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_arm)
9387     fprintf_filtered (file, _("\
9388 The current ARM ABI is \"auto\" (currently \"%s\").\n"),
9389                       arm_abi_strings[tdep->arm_abi]);
9390   else
9391     fprintf_filtered (file, _("The current ARM ABI is \"%s\".\n"),
9392                       arm_abi_string);
9393 }
9394
9395 static void
9396 arm_show_fallback_mode (struct ui_file *file, int from_tty,
9397                         struct cmd_list_element *c, const char *value)
9398 {
9399   fprintf_filtered (file,
9400                     _("The current execution mode assumed "
9401                       "(when symbols are unavailable) is \"%s\".\n"),
9402                     arm_fallback_mode_string);
9403 }
9404
9405 static void
9406 arm_show_force_mode (struct ui_file *file, int from_tty,
9407                      struct cmd_list_element *c, const char *value)
9408 {
9409   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9410
9411   fprintf_filtered (file,
9412                     _("The current execution mode assumed "
9413                       "(even when symbols are available) is \"%s\".\n"),
9414                     arm_force_mode_string);
9415 }
9416
9417 /* If the user changes the register disassembly style used for info
9418    register and other commands, we have to also switch the style used
9419    in opcodes for disassembly output.  This function is run in the "set
9420    arm disassembly" command, and does that.  */
9421
9422 static void
9423 set_disassembly_style_sfunc (char *args, int from_tty,
9424                               struct cmd_list_element *c)
9425 {
9426   set_disassembly_style ();
9427 }
9428 \f
9429 /* Return the ARM register name corresponding to register I.  */
9430 static const char *
9431 arm_register_name (struct gdbarch *gdbarch, int i)
9432 {
9433   const int num_regs = gdbarch_num_regs (gdbarch);
9434
9435   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
9436       && i >= num_regs && i < num_regs + 32)
9437     {
9438       static const char *const vfp_pseudo_names[] = {
9439         "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
9440         "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
9441         "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
9442         "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
9443       };
9444
9445       return vfp_pseudo_names[i - num_regs];
9446     }
9447
9448   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
9449       && i >= num_regs + 32 && i < num_regs + 32 + 16)
9450     {
9451       static const char *const neon_pseudo_names[] = {
9452         "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
9453         "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15",
9454       };
9455
9456       return neon_pseudo_names[i - num_regs - 32];
9457     }
9458
9459   if (i >= ARRAY_SIZE (arm_register_names))
9460     /* These registers are only supported on targets which supply
9461        an XML description.  */
9462     return "";
9463
9464   return arm_register_names[i];
9465 }
9466
9467 static void
9468 set_disassembly_style (void)
9469 {
9470   int current;
9471
9472   /* Find the style that the user wants.  */
9473   for (current = 0; current < num_disassembly_options; current++)
9474     if (disassembly_style == valid_disassembly_styles[current])
9475       break;
9476   gdb_assert (current < num_disassembly_options);
9477
9478   /* Synchronize the disassembler.  */
9479   set_arm_regname_option (current);
9480 }
9481
9482 /* Test whether the coff symbol specific value corresponds to a Thumb
9483    function.  */
9484
9485 static int
9486 coff_sym_is_thumb (int val)
9487 {
9488   return (val == C_THUMBEXT
9489           || val == C_THUMBSTAT
9490           || val == C_THUMBEXTFUNC
9491           || val == C_THUMBSTATFUNC
9492           || val == C_THUMBLABEL);
9493 }
9494
9495 /* arm_coff_make_msymbol_special()
9496    arm_elf_make_msymbol_special()
9497    
9498    These functions test whether the COFF or ELF symbol corresponds to
9499    an address in thumb code, and set a "special" bit in a minimal
9500    symbol to indicate that it does.  */
9501    
9502 static void
9503 arm_elf_make_msymbol_special(asymbol *sym, struct minimal_symbol *msym)
9504 {
9505   if (ARM_SYM_BRANCH_TYPE (&((elf_symbol_type *)sym)->internal_elf_sym)
9506       == ST_BRANCH_TO_THUMB)
9507     MSYMBOL_SET_SPECIAL (msym);
9508 }
9509
9510 static void
9511 arm_coff_make_msymbol_special(int val, struct minimal_symbol *msym)
9512 {
9513   if (coff_sym_is_thumb (val))
9514     MSYMBOL_SET_SPECIAL (msym);
9515 }
9516
9517 static void
9518 arm_objfile_data_free (struct objfile *objfile, void *arg)
9519 {
9520   struct arm_per_objfile *data = arg;
9521   unsigned int i;
9522
9523   for (i = 0; i < objfile->obfd->section_count; i++)
9524     VEC_free (arm_mapping_symbol_s, data->section_maps[i]);
9525 }
9526
9527 static void
9528 arm_record_special_symbol (struct gdbarch *gdbarch, struct objfile *objfile,
9529                            asymbol *sym)
9530 {
9531   const char *name = bfd_asymbol_name (sym);
9532   struct arm_per_objfile *data;
9533   VEC(arm_mapping_symbol_s) **map_p;
9534   struct arm_mapping_symbol new_map_sym;
9535
9536   gdb_assert (name[0] == '$');
9537   if (name[1] != 'a' && name[1] != 't' && name[1] != 'd')
9538     return;
9539
9540   data = objfile_data (objfile, arm_objfile_data_key);
9541   if (data == NULL)
9542     {
9543       data = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9544                              struct arm_per_objfile);
9545       set_objfile_data (objfile, arm_objfile_data_key, data);
9546       data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
9547                                            objfile->obfd->section_count,
9548                                            VEC(arm_mapping_symbol_s) *);
9549     }
9550   map_p = &data->section_maps[bfd_get_section (sym)->index];
9551
9552   new_map_sym.value = sym->value;
9553   new_map_sym.type = name[1];
9554
9555   /* Assume that most mapping symbols appear in order of increasing
9556      value.  If they were randomly distributed, it would be faster to
9557      always push here and then sort at first use.  */
9558   if (!VEC_empty (arm_mapping_symbol_s, *map_p))
9559     {
9560       struct arm_mapping_symbol *prev_map_sym;
9561
9562       prev_map_sym = VEC_last (arm_mapping_symbol_s, *map_p);
9563       if (prev_map_sym->value >= sym->value)
9564         {
9565           unsigned int idx;
9566           idx = VEC_lower_bound (arm_mapping_symbol_s, *map_p, &new_map_sym,
9567                                  arm_compare_mapping_symbols);
9568           VEC_safe_insert (arm_mapping_symbol_s, *map_p, idx, &new_map_sym);
9569           return;
9570         }
9571     }
9572
9573   VEC_safe_push (arm_mapping_symbol_s, *map_p, &new_map_sym);
9574 }
9575
9576 static void
9577 arm_write_pc (struct regcache *regcache, CORE_ADDR pc)
9578 {
9579   struct gdbarch *gdbarch = get_regcache_arch (regcache);
9580   regcache_cooked_write_unsigned (regcache, ARM_PC_REGNUM, pc);
9581
9582   /* If necessary, set the T bit.  */
9583   if (arm_apcs_32)
9584     {
9585       ULONGEST val, t_bit;
9586       regcache_cooked_read_unsigned (regcache, ARM_PS_REGNUM, &val);
9587       t_bit = arm_psr_thumb_bit (gdbarch);
9588       if (arm_pc_is_thumb (gdbarch, pc))
9589         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
9590                                         val | t_bit);
9591       else
9592         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
9593                                         val & ~t_bit);
9594     }
9595 }
9596
9597 /* Read the contents of a NEON quad register, by reading from two
9598    double registers.  This is used to implement the quad pseudo
9599    registers, and for argument passing in case the quad registers are
9600    missing; vectors are passed in quad registers when using the VFP
9601    ABI, even if a NEON unit is not present.  REGNUM is the index of
9602    the quad register, in [0, 15].  */
9603
9604 static enum register_status
9605 arm_neon_quad_read (struct gdbarch *gdbarch, struct regcache *regcache,
9606                     int regnum, gdb_byte *buf)
9607 {
9608   char name_buf[4];
9609   gdb_byte reg_buf[8];
9610   int offset, double_regnum;
9611   enum register_status status;
9612
9613   xsnprintf (name_buf, sizeof (name_buf), "d%d", regnum << 1);
9614   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9615                                                strlen (name_buf));
9616
9617   /* d0 is always the least significant half of q0.  */
9618   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9619     offset = 8;
9620   else
9621     offset = 0;
9622
9623   status = regcache_raw_read (regcache, double_regnum, reg_buf);
9624   if (status != REG_VALID)
9625     return status;
9626   memcpy (buf + offset, reg_buf, 8);
9627
9628   offset = 8 - offset;
9629   status = regcache_raw_read (regcache, double_regnum + 1, reg_buf);
9630   if (status != REG_VALID)
9631     return status;
9632   memcpy (buf + offset, reg_buf, 8);
9633
9634   return REG_VALID;
9635 }
9636
9637 static enum register_status
9638 arm_pseudo_read (struct gdbarch *gdbarch, struct regcache *regcache,
9639                  int regnum, gdb_byte *buf)
9640 {
9641   const int num_regs = gdbarch_num_regs (gdbarch);
9642   char name_buf[4];
9643   gdb_byte reg_buf[8];
9644   int offset, double_regnum;
9645
9646   gdb_assert (regnum >= num_regs);
9647   regnum -= num_regs;
9648
9649   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
9650     /* Quad-precision register.  */
9651     return arm_neon_quad_read (gdbarch, regcache, regnum - 32, buf);
9652   else
9653     {
9654       enum register_status status;
9655
9656       /* Single-precision register.  */
9657       gdb_assert (regnum < 32);
9658
9659       /* s0 is always the least significant half of d0.  */
9660       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9661         offset = (regnum & 1) ? 0 : 4;
9662       else
9663         offset = (regnum & 1) ? 4 : 0;
9664
9665       xsnprintf (name_buf, sizeof (name_buf), "d%d", regnum >> 1);
9666       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9667                                                    strlen (name_buf));
9668
9669       status = regcache_raw_read (regcache, double_regnum, reg_buf);
9670       if (status == REG_VALID)
9671         memcpy (buf, reg_buf + offset, 4);
9672       return status;
9673     }
9674 }
9675
9676 /* Store the contents of BUF to a NEON quad register, by writing to
9677    two double registers.  This is used to implement the quad pseudo
9678    registers, and for argument passing in case the quad registers are
9679    missing; vectors are passed in quad registers when using the VFP
9680    ABI, even if a NEON unit is not present.  REGNUM is the index
9681    of the quad register, in [0, 15].  */
9682
9683 static void
9684 arm_neon_quad_write (struct gdbarch *gdbarch, struct regcache *regcache,
9685                      int regnum, const gdb_byte *buf)
9686 {
9687   char name_buf[4];
9688   int offset, double_regnum;
9689
9690   xsnprintf (name_buf, sizeof (name_buf), "d%d", regnum << 1);
9691   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9692                                                strlen (name_buf));
9693
9694   /* d0 is always the least significant half of q0.  */
9695   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9696     offset = 8;
9697   else
9698     offset = 0;
9699
9700   regcache_raw_write (regcache, double_regnum, buf + offset);
9701   offset = 8 - offset;
9702   regcache_raw_write (regcache, double_regnum + 1, buf + offset);
9703 }
9704
9705 static void
9706 arm_pseudo_write (struct gdbarch *gdbarch, struct regcache *regcache,
9707                   int regnum, const gdb_byte *buf)
9708 {
9709   const int num_regs = gdbarch_num_regs (gdbarch);
9710   char name_buf[4];
9711   gdb_byte reg_buf[8];
9712   int offset, double_regnum;
9713
9714   gdb_assert (regnum >= num_regs);
9715   regnum -= num_regs;
9716
9717   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
9718     /* Quad-precision register.  */
9719     arm_neon_quad_write (gdbarch, regcache, regnum - 32, buf);
9720   else
9721     {
9722       /* Single-precision register.  */
9723       gdb_assert (regnum < 32);
9724
9725       /* s0 is always the least significant half of d0.  */
9726       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9727         offset = (regnum & 1) ? 0 : 4;
9728       else
9729         offset = (regnum & 1) ? 4 : 0;
9730
9731       xsnprintf (name_buf, sizeof (name_buf), "d%d", regnum >> 1);
9732       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9733                                                    strlen (name_buf));
9734
9735       regcache_raw_read (regcache, double_regnum, reg_buf);
9736       memcpy (reg_buf + offset, buf, 4);
9737       regcache_raw_write (regcache, double_regnum, reg_buf);
9738     }
9739 }
9740
9741 static struct value *
9742 value_of_arm_user_reg (struct frame_info *frame, const void *baton)
9743 {
9744   const int *reg_p = baton;
9745   return value_of_register (*reg_p, frame);
9746 }
9747 \f
9748 static enum gdb_osabi
9749 arm_elf_osabi_sniffer (bfd *abfd)
9750 {
9751   unsigned int elfosabi;
9752   enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
9753
9754   elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI];
9755
9756   if (elfosabi == ELFOSABI_ARM)
9757     /* GNU tools use this value.  Check note sections in this case,
9758        as well.  */
9759     bfd_map_over_sections (abfd,
9760                            generic_elf_osabi_sniff_abi_tag_sections, 
9761                            &osabi);
9762
9763   /* Anything else will be handled by the generic ELF sniffer.  */
9764   return osabi;
9765 }
9766
9767 static int
9768 arm_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
9769                           struct reggroup *group)
9770 {
9771   /* FPS register's type is INT, but belongs to float_reggroup.  Beside
9772      this, FPS register belongs to save_regroup, restore_reggroup, and
9773      all_reggroup, of course.  */
9774   if (regnum == ARM_FPS_REGNUM)
9775     return (group == float_reggroup
9776             || group == save_reggroup
9777             || group == restore_reggroup
9778             || group == all_reggroup);
9779   else
9780     return default_register_reggroup_p (gdbarch, regnum, group);
9781 }
9782
9783 \f
9784 /* For backward-compatibility we allow two 'g' packet lengths with
9785    the remote protocol depending on whether FPA registers are
9786    supplied.  M-profile targets do not have FPA registers, but some
9787    stubs already exist in the wild which use a 'g' packet which
9788    supplies them albeit with dummy values.  The packet format which
9789    includes FPA registers should be considered deprecated for
9790    M-profile targets.  */
9791
9792 static void
9793 arm_register_g_packet_guesses (struct gdbarch *gdbarch)
9794 {
9795   if (gdbarch_tdep (gdbarch)->is_m)
9796     {
9797       /* If we know from the executable this is an M-profile target,
9798          cater for remote targets whose register set layout is the
9799          same as the FPA layout.  */
9800       register_remote_g_packet_guess (gdbarch,
9801                                       /* r0-r12,sp,lr,pc; f0-f7; fps,xpsr */
9802                                       (16 * INT_REGISTER_SIZE)
9803                                       + (8 * FP_REGISTER_SIZE)
9804                                       + (2 * INT_REGISTER_SIZE),
9805                                       tdesc_arm_with_m_fpa_layout);
9806
9807       /* The regular M-profile layout.  */
9808       register_remote_g_packet_guess (gdbarch,
9809                                       /* r0-r12,sp,lr,pc; xpsr */
9810                                       (16 * INT_REGISTER_SIZE)
9811                                       + INT_REGISTER_SIZE,
9812                                       tdesc_arm_with_m);
9813
9814       /* M-profile plus M4F VFP.  */
9815       register_remote_g_packet_guess (gdbarch,
9816                                       /* r0-r12,sp,lr,pc; d0-d15; fpscr,xpsr */
9817                                       (16 * INT_REGISTER_SIZE)
9818                                       + (16 * VFP_REGISTER_SIZE)
9819                                       + (2 * INT_REGISTER_SIZE),
9820                                       tdesc_arm_with_m_vfp_d16);
9821     }
9822
9823   /* Otherwise we don't have a useful guess.  */
9824 }
9825
9826 \f
9827 /* Initialize the current architecture based on INFO.  If possible,
9828    re-use an architecture from ARCHES, which is a list of
9829    architectures already created during this debugging session.
9830
9831    Called e.g. at program startup, when reading a core file, and when
9832    reading a binary file.  */
9833
9834 static struct gdbarch *
9835 arm_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
9836 {
9837   struct gdbarch_tdep *tdep;
9838   struct gdbarch *gdbarch;
9839   struct gdbarch_list *best_arch;
9840   enum arm_abi_kind arm_abi = arm_abi_global;
9841   enum arm_float_model fp_model = arm_fp_model;
9842   struct tdesc_arch_data *tdesc_data = NULL;
9843   int i, is_m = 0;
9844   int have_vfp_registers = 0, have_vfp_pseudos = 0, have_neon_pseudos = 0;
9845   int have_neon = 0;
9846   int have_fpa_registers = 1;
9847   const struct target_desc *tdesc = info.target_desc;
9848
9849   /* If we have an object to base this architecture on, try to determine
9850      its ABI.  */
9851
9852   if (arm_abi == ARM_ABI_AUTO && info.abfd != NULL)
9853     {
9854       int ei_osabi, e_flags;
9855
9856       switch (bfd_get_flavour (info.abfd))
9857         {
9858         case bfd_target_aout_flavour:
9859           /* Assume it's an old APCS-style ABI.  */
9860           arm_abi = ARM_ABI_APCS;
9861           break;
9862
9863         case bfd_target_coff_flavour:
9864           /* Assume it's an old APCS-style ABI.  */
9865           /* XXX WinCE?  */
9866           arm_abi = ARM_ABI_APCS;
9867           break;
9868
9869         case bfd_target_elf_flavour:
9870           ei_osabi = elf_elfheader (info.abfd)->e_ident[EI_OSABI];
9871           e_flags = elf_elfheader (info.abfd)->e_flags;
9872
9873           if (ei_osabi == ELFOSABI_ARM)
9874             {
9875               /* GNU tools used to use this value, but do not for EABI
9876                  objects.  There's nowhere to tag an EABI version
9877                  anyway, so assume APCS.  */
9878               arm_abi = ARM_ABI_APCS;
9879             }
9880           else if (ei_osabi == ELFOSABI_NONE)
9881             {
9882               int eabi_ver = EF_ARM_EABI_VERSION (e_flags);
9883               int attr_arch, attr_profile;
9884
9885               switch (eabi_ver)
9886                 {
9887                 case EF_ARM_EABI_UNKNOWN:
9888                   /* Assume GNU tools.  */
9889                   arm_abi = ARM_ABI_APCS;
9890                   break;
9891
9892                 case EF_ARM_EABI_VER4:
9893                 case EF_ARM_EABI_VER5:
9894                   arm_abi = ARM_ABI_AAPCS;
9895                   /* EABI binaries default to VFP float ordering.
9896                      They may also contain build attributes that can
9897                      be used to identify if the VFP argument-passing
9898                      ABI is in use.  */
9899                   if (fp_model == ARM_FLOAT_AUTO)
9900                     {
9901 #ifdef HAVE_ELF
9902                       switch (bfd_elf_get_obj_attr_int (info.abfd,
9903                                                         OBJ_ATTR_PROC,
9904                                                         Tag_ABI_VFP_args))
9905                         {
9906                         case 0:
9907                           /* "The user intended FP parameter/result
9908                              passing to conform to AAPCS, base
9909                              variant".  */
9910                           fp_model = ARM_FLOAT_SOFT_VFP;
9911                           break;
9912                         case 1:
9913                           /* "The user intended FP parameter/result
9914                              passing to conform to AAPCS, VFP
9915                              variant".  */
9916                           fp_model = ARM_FLOAT_VFP;
9917                           break;
9918                         case 2:
9919                           /* "The user intended FP parameter/result
9920                              passing to conform to tool chain-specific
9921                              conventions" - we don't know any such
9922                              conventions, so leave it as "auto".  */
9923                           break;
9924                         default:
9925                           /* Attribute value not mentioned in the
9926                              October 2008 ABI, so leave it as
9927                              "auto".  */
9928                           break;
9929                         }
9930 #else
9931                       fp_model = ARM_FLOAT_SOFT_VFP;
9932 #endif
9933                     }
9934                   break;
9935
9936                 default:
9937                   /* Leave it as "auto".  */
9938                   warning (_("unknown ARM EABI version 0x%x"), eabi_ver);
9939                   break;
9940                 }
9941
9942 #ifdef HAVE_ELF
9943               /* Detect M-profile programs.  This only works if the
9944                  executable file includes build attributes; GCC does
9945                  copy them to the executable, but e.g. RealView does
9946                  not.  */
9947               attr_arch = bfd_elf_get_obj_attr_int (info.abfd, OBJ_ATTR_PROC,
9948                                                     Tag_CPU_arch);
9949               attr_profile = bfd_elf_get_obj_attr_int (info.abfd,
9950                                                        OBJ_ATTR_PROC,
9951                                                        Tag_CPU_arch_profile);
9952               /* GCC specifies the profile for v6-M; RealView only
9953                  specifies the profile for architectures starting with
9954                  V7 (as opposed to architectures with a tag
9955                  numerically greater than TAG_CPU_ARCH_V7).  */
9956               if (!tdesc_has_registers (tdesc)
9957                   && (attr_arch == TAG_CPU_ARCH_V6_M
9958                       || attr_arch == TAG_CPU_ARCH_V6S_M
9959                       || attr_profile == 'M'))
9960                 is_m = 1;
9961 #endif
9962             }
9963
9964           if (fp_model == ARM_FLOAT_AUTO)
9965             {
9966               int e_flags = elf_elfheader (info.abfd)->e_flags;
9967
9968               switch (e_flags & (EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT))
9969                 {
9970                 case 0:
9971                   /* Leave it as "auto".  Strictly speaking this case
9972                      means FPA, but almost nobody uses that now, and
9973                      many toolchains fail to set the appropriate bits
9974                      for the floating-point model they use.  */
9975                   break;
9976                 case EF_ARM_SOFT_FLOAT:
9977                   fp_model = ARM_FLOAT_SOFT_FPA;
9978                   break;
9979                 case EF_ARM_VFP_FLOAT:
9980                   fp_model = ARM_FLOAT_VFP;
9981                   break;
9982                 case EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT:
9983                   fp_model = ARM_FLOAT_SOFT_VFP;
9984                   break;
9985                 }
9986             }
9987
9988           if (e_flags & EF_ARM_BE8)
9989             info.byte_order_for_code = BFD_ENDIAN_LITTLE;
9990
9991           break;
9992
9993         default:
9994           /* Leave it as "auto".  */
9995           break;
9996         }
9997     }
9998
9999   /* Check any target description for validity.  */
10000   if (tdesc_has_registers (tdesc))
10001     {
10002       /* For most registers we require GDB's default names; but also allow
10003          the numeric names for sp / lr / pc, as a convenience.  */
10004       static const char *const arm_sp_names[] = { "r13", "sp", NULL };
10005       static const char *const arm_lr_names[] = { "r14", "lr", NULL };
10006       static const char *const arm_pc_names[] = { "r15", "pc", NULL };
10007
10008       const struct tdesc_feature *feature;
10009       int valid_p;
10010
10011       feature = tdesc_find_feature (tdesc,
10012                                     "org.gnu.gdb.arm.core");
10013       if (feature == NULL)
10014         {
10015           feature = tdesc_find_feature (tdesc,
10016                                         "org.gnu.gdb.arm.m-profile");
10017           if (feature == NULL)
10018             return NULL;
10019           else
10020             is_m = 1;
10021         }
10022
10023       tdesc_data = tdesc_data_alloc ();
10024
10025       valid_p = 1;
10026       for (i = 0; i < ARM_SP_REGNUM; i++)
10027         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
10028                                             arm_register_names[i]);
10029       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10030                                                   ARM_SP_REGNUM,
10031                                                   arm_sp_names);
10032       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10033                                                   ARM_LR_REGNUM,
10034                                                   arm_lr_names);
10035       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10036                                                   ARM_PC_REGNUM,
10037                                                   arm_pc_names);
10038       if (is_m)
10039         valid_p &= tdesc_numbered_register (feature, tdesc_data,
10040                                             ARM_PS_REGNUM, "xpsr");
10041       else
10042         valid_p &= tdesc_numbered_register (feature, tdesc_data,
10043                                             ARM_PS_REGNUM, "cpsr");
10044
10045       if (!valid_p)
10046         {
10047           tdesc_data_cleanup (tdesc_data);
10048           return NULL;
10049         }
10050
10051       feature = tdesc_find_feature (tdesc,
10052                                     "org.gnu.gdb.arm.fpa");
10053       if (feature != NULL)
10054         {
10055           valid_p = 1;
10056           for (i = ARM_F0_REGNUM; i <= ARM_FPS_REGNUM; i++)
10057             valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
10058                                                 arm_register_names[i]);
10059           if (!valid_p)
10060             {
10061               tdesc_data_cleanup (tdesc_data);
10062               return NULL;
10063             }
10064         }
10065       else
10066         have_fpa_registers = 0;
10067
10068       feature = tdesc_find_feature (tdesc,
10069                                     "org.gnu.gdb.xscale.iwmmxt");
10070       if (feature != NULL)
10071         {
10072           static const char *const iwmmxt_names[] = {
10073             "wR0", "wR1", "wR2", "wR3", "wR4", "wR5", "wR6", "wR7",
10074             "wR8", "wR9", "wR10", "wR11", "wR12", "wR13", "wR14", "wR15",
10075             "wCID", "wCon", "wCSSF", "wCASF", "", "", "", "",
10076             "wCGR0", "wCGR1", "wCGR2", "wCGR3", "", "", "", "",
10077           };
10078
10079           valid_p = 1;
10080           for (i = ARM_WR0_REGNUM; i <= ARM_WR15_REGNUM; i++)
10081             valid_p
10082               &= tdesc_numbered_register (feature, tdesc_data, i,
10083                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
10084
10085           /* Check for the control registers, but do not fail if they
10086              are missing.  */
10087           for (i = ARM_WC0_REGNUM; i <= ARM_WCASF_REGNUM; i++)
10088             tdesc_numbered_register (feature, tdesc_data, i,
10089                                      iwmmxt_names[i - ARM_WR0_REGNUM]);
10090
10091           for (i = ARM_WCGR0_REGNUM; i <= ARM_WCGR3_REGNUM; i++)
10092             valid_p
10093               &= tdesc_numbered_register (feature, tdesc_data, i,
10094                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
10095
10096           if (!valid_p)
10097             {
10098               tdesc_data_cleanup (tdesc_data);
10099               return NULL;
10100             }
10101         }
10102
10103       /* If we have a VFP unit, check whether the single precision registers
10104          are present.  If not, then we will synthesize them as pseudo
10105          registers.  */
10106       feature = tdesc_find_feature (tdesc,
10107                                     "org.gnu.gdb.arm.vfp");
10108       if (feature != NULL)
10109         {
10110           static const char *const vfp_double_names[] = {
10111             "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
10112             "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
10113             "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
10114             "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
10115           };
10116
10117           /* Require the double precision registers.  There must be either
10118              16 or 32.  */
10119           valid_p = 1;
10120           for (i = 0; i < 32; i++)
10121             {
10122               valid_p &= tdesc_numbered_register (feature, tdesc_data,
10123                                                   ARM_D0_REGNUM + i,
10124                                                   vfp_double_names[i]);
10125               if (!valid_p)
10126                 break;
10127             }
10128           if (!valid_p && i == 16)
10129             valid_p = 1;
10130
10131           /* Also require FPSCR.  */
10132           valid_p &= tdesc_numbered_register (feature, tdesc_data,
10133                                               ARM_FPSCR_REGNUM, "fpscr");
10134           if (!valid_p)
10135             {
10136               tdesc_data_cleanup (tdesc_data);
10137               return NULL;
10138             }
10139
10140           if (tdesc_unnumbered_register (feature, "s0") == 0)
10141             have_vfp_pseudos = 1;
10142
10143           have_vfp_registers = 1;
10144
10145           /* If we have VFP, also check for NEON.  The architecture allows
10146              NEON without VFP (integer vector operations only), but GDB
10147              does not support that.  */
10148           feature = tdesc_find_feature (tdesc,
10149                                         "org.gnu.gdb.arm.neon");
10150           if (feature != NULL)
10151             {
10152               /* NEON requires 32 double-precision registers.  */
10153               if (i != 32)
10154                 {
10155                   tdesc_data_cleanup (tdesc_data);
10156                   return NULL;
10157                 }
10158
10159               /* If there are quad registers defined by the stub, use
10160                  their type; otherwise (normally) provide them with
10161                  the default type.  */
10162               if (tdesc_unnumbered_register (feature, "q0") == 0)
10163                 have_neon_pseudos = 1;
10164
10165               have_neon = 1;
10166             }
10167         }
10168     }
10169
10170   /* If there is already a candidate, use it.  */
10171   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
10172        best_arch != NULL;
10173        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
10174     {
10175       if (arm_abi != ARM_ABI_AUTO
10176           && arm_abi != gdbarch_tdep (best_arch->gdbarch)->arm_abi)
10177         continue;
10178
10179       if (fp_model != ARM_FLOAT_AUTO
10180           && fp_model != gdbarch_tdep (best_arch->gdbarch)->fp_model)
10181         continue;
10182
10183       /* There are various other properties in tdep that we do not
10184          need to check here: those derived from a target description,
10185          since gdbarches with a different target description are
10186          automatically disqualified.  */
10187
10188       /* Do check is_m, though, since it might come from the binary.  */
10189       if (is_m != gdbarch_tdep (best_arch->gdbarch)->is_m)
10190         continue;
10191
10192       /* Found a match.  */
10193       break;
10194     }
10195
10196   if (best_arch != NULL)
10197     {
10198       if (tdesc_data != NULL)
10199         tdesc_data_cleanup (tdesc_data);
10200       return best_arch->gdbarch;
10201     }
10202
10203   tdep = xcalloc (1, sizeof (struct gdbarch_tdep));
10204   gdbarch = gdbarch_alloc (&info, tdep);
10205
10206   /* Record additional information about the architecture we are defining.
10207      These are gdbarch discriminators, like the OSABI.  */
10208   tdep->arm_abi = arm_abi;
10209   tdep->fp_model = fp_model;
10210   tdep->is_m = is_m;
10211   tdep->have_fpa_registers = have_fpa_registers;
10212   tdep->have_vfp_registers = have_vfp_registers;
10213   tdep->have_vfp_pseudos = have_vfp_pseudos;
10214   tdep->have_neon_pseudos = have_neon_pseudos;
10215   tdep->have_neon = have_neon;
10216
10217   arm_register_g_packet_guesses (gdbarch);
10218
10219   /* Breakpoints.  */
10220   switch (info.byte_order_for_code)
10221     {
10222     case BFD_ENDIAN_BIG:
10223       tdep->arm_breakpoint = arm_default_arm_be_breakpoint;
10224       tdep->arm_breakpoint_size = sizeof (arm_default_arm_be_breakpoint);
10225       tdep->thumb_breakpoint = arm_default_thumb_be_breakpoint;
10226       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_be_breakpoint);
10227
10228       break;
10229
10230     case BFD_ENDIAN_LITTLE:
10231       tdep->arm_breakpoint = arm_default_arm_le_breakpoint;
10232       tdep->arm_breakpoint_size = sizeof (arm_default_arm_le_breakpoint);
10233       tdep->thumb_breakpoint = arm_default_thumb_le_breakpoint;
10234       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_le_breakpoint);
10235
10236       break;
10237
10238     default:
10239       internal_error (__FILE__, __LINE__,
10240                       _("arm_gdbarch_init: bad byte order for float format"));
10241     }
10242
10243   /* On ARM targets char defaults to unsigned.  */
10244   set_gdbarch_char_signed (gdbarch, 0);
10245
10246   /* Note: for displaced stepping, this includes the breakpoint, and one word
10247      of additional scratch space.  This setting isn't used for anything beside
10248      displaced stepping at present.  */
10249   set_gdbarch_max_insn_length (gdbarch, 4 * DISPLACED_MODIFIED_INSNS);
10250
10251   /* This should be low enough for everything.  */
10252   tdep->lowest_pc = 0x20;
10253   tdep->jb_pc = -1;     /* Longjump support not enabled by default.  */
10254
10255   /* The default, for both APCS and AAPCS, is to return small
10256      structures in registers.  */
10257   tdep->struct_return = reg_struct_return;
10258
10259   set_gdbarch_push_dummy_call (gdbarch, arm_push_dummy_call);
10260   set_gdbarch_frame_align (gdbarch, arm_frame_align);
10261
10262   set_gdbarch_write_pc (gdbarch, arm_write_pc);
10263
10264   /* Frame handling.  */
10265   set_gdbarch_dummy_id (gdbarch, arm_dummy_id);
10266   set_gdbarch_unwind_pc (gdbarch, arm_unwind_pc);
10267   set_gdbarch_unwind_sp (gdbarch, arm_unwind_sp);
10268
10269   frame_base_set_default (gdbarch, &arm_normal_base);
10270
10271   /* Address manipulation.  */
10272   set_gdbarch_addr_bits_remove (gdbarch, arm_addr_bits_remove);
10273
10274   /* Advance PC across function entry code.  */
10275   set_gdbarch_skip_prologue (gdbarch, arm_skip_prologue);
10276
10277   /* Detect whether PC is in function epilogue.  */
10278   set_gdbarch_in_function_epilogue_p (gdbarch, arm_in_function_epilogue_p);
10279
10280   /* Skip trampolines.  */
10281   set_gdbarch_skip_trampoline_code (gdbarch, arm_skip_stub);
10282
10283   /* The stack grows downward.  */
10284   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
10285
10286   /* Breakpoint manipulation.  */
10287   set_gdbarch_breakpoint_from_pc (gdbarch, arm_breakpoint_from_pc);
10288   set_gdbarch_remote_breakpoint_from_pc (gdbarch,
10289                                          arm_remote_breakpoint_from_pc);
10290
10291   /* Information about registers, etc.  */
10292   set_gdbarch_sp_regnum (gdbarch, ARM_SP_REGNUM);
10293   set_gdbarch_pc_regnum (gdbarch, ARM_PC_REGNUM);
10294   set_gdbarch_num_regs (gdbarch, ARM_NUM_REGS);
10295   set_gdbarch_register_type (gdbarch, arm_register_type);
10296   set_gdbarch_register_reggroup_p (gdbarch, arm_register_reggroup_p);
10297
10298   /* This "info float" is FPA-specific.  Use the generic version if we
10299      do not have FPA.  */
10300   if (gdbarch_tdep (gdbarch)->have_fpa_registers)
10301     set_gdbarch_print_float_info (gdbarch, arm_print_float_info);
10302
10303   /* Internal <-> external register number maps.  */
10304   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, arm_dwarf_reg_to_regnum);
10305   set_gdbarch_register_sim_regno (gdbarch, arm_register_sim_regno);
10306
10307   set_gdbarch_register_name (gdbarch, arm_register_name);
10308
10309   /* Returning results.  */
10310   set_gdbarch_return_value (gdbarch, arm_return_value);
10311
10312   /* Disassembly.  */
10313   set_gdbarch_print_insn (gdbarch, gdb_print_insn_arm);
10314
10315   /* Minsymbol frobbing.  */
10316   set_gdbarch_elf_make_msymbol_special (gdbarch, arm_elf_make_msymbol_special);
10317   set_gdbarch_coff_make_msymbol_special (gdbarch,
10318                                          arm_coff_make_msymbol_special);
10319   set_gdbarch_record_special_symbol (gdbarch, arm_record_special_symbol);
10320
10321   /* Thumb-2 IT block support.  */
10322   set_gdbarch_adjust_breakpoint_address (gdbarch,
10323                                          arm_adjust_breakpoint_address);
10324
10325   /* Virtual tables.  */
10326   set_gdbarch_vbit_in_delta (gdbarch, 1);
10327
10328   /* Hook in the ABI-specific overrides, if they have been registered.  */
10329   gdbarch_init_osabi (info, gdbarch);
10330
10331   dwarf2_frame_set_init_reg (gdbarch, arm_dwarf2_frame_init_reg);
10332
10333   /* Add some default predicates.  */
10334   if (is_m)
10335     frame_unwind_append_unwinder (gdbarch, &arm_m_exception_unwind);
10336   frame_unwind_append_unwinder (gdbarch, &arm_stub_unwind);
10337   dwarf2_append_unwinders (gdbarch);
10338   frame_unwind_append_unwinder (gdbarch, &arm_exidx_unwind);
10339   frame_unwind_append_unwinder (gdbarch, &arm_prologue_unwind);
10340
10341   /* Now we have tuned the configuration, set a few final things,
10342      based on what the OS ABI has told us.  */
10343
10344   /* If the ABI is not otherwise marked, assume the old GNU APCS.  EABI
10345      binaries are always marked.  */
10346   if (tdep->arm_abi == ARM_ABI_AUTO)
10347     tdep->arm_abi = ARM_ABI_APCS;
10348
10349   /* Watchpoints are not steppable.  */
10350   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
10351
10352   /* We used to default to FPA for generic ARM, but almost nobody
10353      uses that now, and we now provide a way for the user to force
10354      the model.  So default to the most useful variant.  */
10355   if (tdep->fp_model == ARM_FLOAT_AUTO)
10356     tdep->fp_model = ARM_FLOAT_SOFT_FPA;
10357
10358   if (tdep->jb_pc >= 0)
10359     set_gdbarch_get_longjmp_target (gdbarch, arm_get_longjmp_target);
10360
10361   /* Floating point sizes and format.  */
10362   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
10363   if (tdep->fp_model == ARM_FLOAT_SOFT_FPA || tdep->fp_model == ARM_FLOAT_FPA)
10364     {
10365       set_gdbarch_double_format
10366         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
10367       set_gdbarch_long_double_format
10368         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
10369     }
10370   else
10371     {
10372       set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
10373       set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double);
10374     }
10375
10376   if (have_vfp_pseudos)
10377     {
10378       /* NOTE: These are the only pseudo registers used by
10379          the ARM target at the moment.  If more are added, a
10380          little more care in numbering will be needed.  */
10381
10382       int num_pseudos = 32;
10383       if (have_neon_pseudos)
10384         num_pseudos += 16;
10385       set_gdbarch_num_pseudo_regs (gdbarch, num_pseudos);
10386       set_gdbarch_pseudo_register_read (gdbarch, arm_pseudo_read);
10387       set_gdbarch_pseudo_register_write (gdbarch, arm_pseudo_write);
10388     }
10389
10390   if (tdesc_data)
10391     {
10392       set_tdesc_pseudo_register_name (gdbarch, arm_register_name);
10393
10394       tdesc_use_registers (gdbarch, tdesc, tdesc_data);
10395
10396       /* Override tdesc_register_type to adjust the types of VFP
10397          registers for NEON.  */
10398       set_gdbarch_register_type (gdbarch, arm_register_type);
10399     }
10400
10401   /* Add standard register aliases.  We add aliases even for those
10402      nanes which are used by the current architecture - it's simpler,
10403      and does no harm, since nothing ever lists user registers.  */
10404   for (i = 0; i < ARRAY_SIZE (arm_register_aliases); i++)
10405     user_reg_add (gdbarch, arm_register_aliases[i].name,
10406                   value_of_arm_user_reg, &arm_register_aliases[i].regnum);
10407
10408   return gdbarch;
10409 }
10410
10411 static void
10412 arm_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
10413 {
10414   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
10415
10416   if (tdep == NULL)
10417     return;
10418
10419   fprintf_unfiltered (file, _("arm_dump_tdep: Lowest pc = 0x%lx"),
10420                       (unsigned long) tdep->lowest_pc);
10421 }
10422
10423 extern initialize_file_ftype _initialize_arm_tdep; /* -Wmissing-prototypes */
10424
10425 void
10426 _initialize_arm_tdep (void)
10427 {
10428   struct ui_file *stb;
10429   long length;
10430   struct cmd_list_element *new_set, *new_show;
10431   const char *setname;
10432   const char *setdesc;
10433   const char *const *regnames;
10434   int numregs, i, j;
10435   static char *helptext;
10436   char regdesc[1024], *rdptr = regdesc;
10437   size_t rest = sizeof (regdesc);
10438
10439   gdbarch_register (bfd_arch_arm, arm_gdbarch_init, arm_dump_tdep);
10440
10441   arm_objfile_data_key
10442     = register_objfile_data_with_cleanup (NULL, arm_objfile_data_free);
10443
10444   /* Add ourselves to objfile event chain.  */
10445   observer_attach_new_objfile (arm_exidx_new_objfile);
10446   arm_exidx_data_key
10447     = register_objfile_data_with_cleanup (NULL, arm_exidx_data_free);
10448
10449   /* Register an ELF OS ABI sniffer for ARM binaries.  */
10450   gdbarch_register_osabi_sniffer (bfd_arch_arm,
10451                                   bfd_target_elf_flavour,
10452                                   arm_elf_osabi_sniffer);
10453
10454   /* Initialize the standard target descriptions.  */
10455   initialize_tdesc_arm_with_m ();
10456   initialize_tdesc_arm_with_m_fpa_layout ();
10457   initialize_tdesc_arm_with_m_vfp_d16 ();
10458   initialize_tdesc_arm_with_iwmmxt ();
10459   initialize_tdesc_arm_with_vfpv2 ();
10460   initialize_tdesc_arm_with_vfpv3 ();
10461   initialize_tdesc_arm_with_neon ();
10462
10463   /* Get the number of possible sets of register names defined in opcodes.  */
10464   num_disassembly_options = get_arm_regname_num_options ();
10465
10466   /* Add root prefix command for all "set arm"/"show arm" commands.  */
10467   add_prefix_cmd ("arm", no_class, set_arm_command,
10468                   _("Various ARM-specific commands."),
10469                   &setarmcmdlist, "set arm ", 0, &setlist);
10470
10471   add_prefix_cmd ("arm", no_class, show_arm_command,
10472                   _("Various ARM-specific commands."),
10473                   &showarmcmdlist, "show arm ", 0, &showlist);
10474
10475   /* Sync the opcode insn printer with our register viewer.  */
10476   parse_arm_disassembler_option ("reg-names-std");
10477
10478   /* Initialize the array that will be passed to
10479      add_setshow_enum_cmd().  */
10480   valid_disassembly_styles
10481     = xmalloc ((num_disassembly_options + 1) * sizeof (char *));
10482   for (i = 0; i < num_disassembly_options; i++)
10483     {
10484       numregs = get_arm_regnames (i, &setname, &setdesc, &regnames);
10485       valid_disassembly_styles[i] = setname;
10486       length = snprintf (rdptr, rest, "%s - %s\n", setname, setdesc);
10487       rdptr += length;
10488       rest -= length;
10489       /* When we find the default names, tell the disassembler to use
10490          them.  */
10491       if (!strcmp (setname, "std"))
10492         {
10493           disassembly_style = setname;
10494           set_arm_regname_option (i);
10495         }
10496     }
10497   /* Mark the end of valid options.  */
10498   valid_disassembly_styles[num_disassembly_options] = NULL;
10499
10500   /* Create the help text.  */
10501   stb = mem_fileopen ();
10502   fprintf_unfiltered (stb, "%s%s%s",
10503                       _("The valid values are:\n"),
10504                       regdesc,
10505                       _("The default is \"std\"."));
10506   helptext = ui_file_xstrdup (stb, NULL);
10507   ui_file_delete (stb);
10508
10509   add_setshow_enum_cmd("disassembler", no_class,
10510                        valid_disassembly_styles, &disassembly_style,
10511                        _("Set the disassembly style."),
10512                        _("Show the disassembly style."),
10513                        helptext,
10514                        set_disassembly_style_sfunc,
10515                        NULL, /* FIXME: i18n: The disassembly style is
10516                                 \"%s\".  */
10517                        &setarmcmdlist, &showarmcmdlist);
10518
10519   add_setshow_boolean_cmd ("apcs32", no_class, &arm_apcs_32,
10520                            _("Set usage of ARM 32-bit mode."),
10521                            _("Show usage of ARM 32-bit mode."),
10522                            _("When off, a 26-bit PC will be used."),
10523                            NULL,
10524                            NULL, /* FIXME: i18n: Usage of ARM 32-bit
10525                                     mode is %s.  */
10526                            &setarmcmdlist, &showarmcmdlist);
10527
10528   /* Add a command to allow the user to force the FPU model.  */
10529   add_setshow_enum_cmd ("fpu", no_class, fp_model_strings, &current_fp_model,
10530                         _("Set the floating point type."),
10531                         _("Show the floating point type."),
10532                         _("auto - Determine the FP typefrom the OS-ABI.\n\
10533 softfpa - Software FP, mixed-endian doubles on little-endian ARMs.\n\
10534 fpa - FPA co-processor (GCC compiled).\n\
10535 softvfp - Software FP with pure-endian doubles.\n\
10536 vfp - VFP co-processor."),
10537                         set_fp_model_sfunc, show_fp_model,
10538                         &setarmcmdlist, &showarmcmdlist);
10539
10540   /* Add a command to allow the user to force the ABI.  */
10541   add_setshow_enum_cmd ("abi", class_support, arm_abi_strings, &arm_abi_string,
10542                         _("Set the ABI."),
10543                         _("Show the ABI."),
10544                         NULL, arm_set_abi, arm_show_abi,
10545                         &setarmcmdlist, &showarmcmdlist);
10546
10547   /* Add two commands to allow the user to force the assumed
10548      execution mode.  */
10549   add_setshow_enum_cmd ("fallback-mode", class_support,
10550                         arm_mode_strings, &arm_fallback_mode_string,
10551                         _("Set the mode assumed when symbols are unavailable."),
10552                         _("Show the mode assumed when symbols are unavailable."),
10553                         NULL, NULL, arm_show_fallback_mode,
10554                         &setarmcmdlist, &showarmcmdlist);
10555   add_setshow_enum_cmd ("force-mode", class_support,
10556                         arm_mode_strings, &arm_force_mode_string,
10557                         _("Set the mode assumed even when symbols are available."),
10558                         _("Show the mode assumed even when symbols are available."),
10559                         NULL, NULL, arm_show_force_mode,
10560                         &setarmcmdlist, &showarmcmdlist);
10561
10562   /* Debugging flag.  */
10563   add_setshow_boolean_cmd ("arm", class_maintenance, &arm_debug,
10564                            _("Set ARM debugging."),
10565                            _("Show ARM debugging."),
10566                            _("When on, arm-specific debugging is enabled."),
10567                            NULL,
10568                            NULL, /* FIXME: i18n: "ARM debugging is %s.  */
10569                            &setdebuglist, &showdebuglist);
10570 }
10571
10572 /* ARM-reversible process record data structures.  */
10573
10574 #define ARM_INSN_SIZE_BYTES 4    
10575 #define THUMB_INSN_SIZE_BYTES 2
10576 #define THUMB2_INSN_SIZE_BYTES 4
10577
10578
10579 #define INSN_S_L_BIT_NUM 20
10580
10581 #define REG_ALLOC(REGS, LENGTH, RECORD_BUF) \
10582         do  \
10583           { \
10584             unsigned int reg_len = LENGTH; \
10585             if (reg_len) \
10586               { \
10587                 REGS = XNEWVEC (uint32_t, reg_len); \
10588                 memcpy(&REGS[0], &RECORD_BUF[0], sizeof(uint32_t)*LENGTH); \
10589               } \
10590           } \
10591         while (0)
10592
10593 #define MEM_ALLOC(MEMS, LENGTH, RECORD_BUF) \
10594         do  \
10595           { \
10596             unsigned int mem_len = LENGTH; \
10597             if (mem_len) \
10598             { \
10599               MEMS =  XNEWVEC (struct arm_mem_r, mem_len);  \
10600               memcpy(&MEMS->len, &RECORD_BUF[0], \
10601                      sizeof(struct arm_mem_r) * LENGTH); \
10602             } \
10603           } \
10604           while (0)
10605
10606 /* Checks whether insn is already recorded or yet to be decoded. (boolean expression).  */
10607 #define INSN_RECORDED(ARM_RECORD) \
10608         (0 != (ARM_RECORD)->reg_rec_count || 0 != (ARM_RECORD)->mem_rec_count)
10609
10610 /* ARM memory record structure.  */
10611 struct arm_mem_r
10612 {
10613   uint32_t len;    /* Record length.  */
10614   uint32_t addr;   /* Memory address.  */
10615 };
10616
10617 /* ARM instruction record contains opcode of current insn
10618    and execution state (before entry to decode_insn()),
10619    contains list of to-be-modified registers and
10620    memory blocks (on return from decode_insn()).  */
10621
10622 typedef struct insn_decode_record_t
10623 {
10624   struct gdbarch *gdbarch;
10625   struct regcache *regcache;
10626   CORE_ADDR this_addr;          /* Address of the insn being decoded.  */
10627   uint32_t arm_insn;            /* Should accommodate thumb.  */
10628   uint32_t cond;                /* Condition code.  */
10629   uint32_t opcode;              /* Insn opcode.  */
10630   uint32_t decode;              /* Insn decode bits.  */
10631   uint32_t mem_rec_count;       /* No of mem records.  */
10632   uint32_t reg_rec_count;       /* No of reg records.  */
10633   uint32_t *arm_regs;           /* Registers to be saved for this record.  */
10634   struct arm_mem_r *arm_mems;   /* Memory to be saved for this record.  */
10635 } insn_decode_record;
10636
10637
10638 /* Checks ARM SBZ and SBO mandatory fields.  */
10639
10640 static int
10641 sbo_sbz (uint32_t insn, uint32_t bit_num, uint32_t len, uint32_t sbo)
10642 {
10643   uint32_t ones = bits (insn, bit_num - 1, (bit_num -1) + (len - 1));
10644
10645   if (!len)
10646     return 1;
10647
10648   if (!sbo)
10649     ones = ~ones;
10650
10651   while (ones)
10652     {
10653       if (!(ones & sbo))
10654         {
10655           return 0;
10656         }
10657       ones = ones >> 1;
10658     }
10659   return 1;
10660 }
10661
10662 enum arm_record_result
10663 {
10664   ARM_RECORD_SUCCESS = 0,
10665   ARM_RECORD_FAILURE = 1
10666 };
10667
10668 typedef enum
10669 {
10670   ARM_RECORD_STRH=1,
10671   ARM_RECORD_STRD
10672 } arm_record_strx_t;
10673
10674 typedef enum
10675 {
10676   ARM_RECORD=1,
10677   THUMB_RECORD,
10678   THUMB2_RECORD
10679 } record_type_t;
10680
10681
10682 static int
10683 arm_record_strx (insn_decode_record *arm_insn_r, uint32_t *record_buf, 
10684                  uint32_t *record_buf_mem, arm_record_strx_t str_type)
10685 {
10686
10687   struct regcache *reg_cache = arm_insn_r->regcache;
10688   ULONGEST u_regval[2]= {0};
10689
10690   uint32_t reg_src1 = 0, reg_src2 = 0;
10691   uint32_t immed_high = 0, immed_low = 0,offset_8 = 0, tgt_mem_addr = 0;
10692   uint32_t opcode1 = 0;
10693
10694   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
10695   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
10696   opcode1 = bits (arm_insn_r->arm_insn, 20, 24);
10697
10698
10699   if (14 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
10700     {
10701       /* 1) Handle misc store, immediate offset.  */
10702       immed_low = bits (arm_insn_r->arm_insn, 0, 3);
10703       immed_high = bits (arm_insn_r->arm_insn, 8, 11);
10704       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
10705       regcache_raw_read_unsigned (reg_cache, reg_src1,
10706                                   &u_regval[0]);
10707       if (ARM_PC_REGNUM == reg_src1)
10708         {
10709           /* If R15 was used as Rn, hence current PC+8.  */
10710           u_regval[0] = u_regval[0] + 8;
10711         }
10712       offset_8 = (immed_high << 4) | immed_low;
10713       /* Calculate target store address.  */
10714       if (14 == arm_insn_r->opcode)
10715         {
10716           tgt_mem_addr = u_regval[0] + offset_8;
10717         }
10718       else
10719         {
10720           tgt_mem_addr = u_regval[0] - offset_8;
10721         }
10722       if (ARM_RECORD_STRH == str_type)
10723         {
10724           record_buf_mem[0] = 2;
10725           record_buf_mem[1] = tgt_mem_addr;
10726           arm_insn_r->mem_rec_count = 1;
10727         }
10728       else if (ARM_RECORD_STRD == str_type)
10729         {
10730           record_buf_mem[0] = 4;
10731           record_buf_mem[1] = tgt_mem_addr;
10732           record_buf_mem[2] = 4;
10733           record_buf_mem[3] = tgt_mem_addr + 4;
10734           arm_insn_r->mem_rec_count = 2;
10735         }
10736     }
10737   else if (12 == arm_insn_r->opcode || 8 == arm_insn_r->opcode)
10738     {
10739       /* 2) Store, register offset.  */
10740       /* Get Rm.  */
10741       reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
10742       /* Get Rn.  */
10743       reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
10744       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10745       regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
10746       if (15 == reg_src2)
10747         {
10748           /* If R15 was used as Rn, hence current PC+8.  */
10749           u_regval[0] = u_regval[0] + 8;
10750         }
10751       /* Calculate target store address, Rn +/- Rm, register offset.  */
10752       if (12 == arm_insn_r->opcode)
10753         {
10754           tgt_mem_addr = u_regval[0] + u_regval[1];
10755         }
10756       else
10757         {
10758           tgt_mem_addr = u_regval[1] - u_regval[0];
10759         }
10760       if (ARM_RECORD_STRH == str_type)
10761         {
10762           record_buf_mem[0] = 2;
10763           record_buf_mem[1] = tgt_mem_addr;
10764           arm_insn_r->mem_rec_count = 1;
10765         }
10766       else if (ARM_RECORD_STRD == str_type)
10767         {
10768           record_buf_mem[0] = 4;
10769           record_buf_mem[1] = tgt_mem_addr;
10770           record_buf_mem[2] = 4;
10771           record_buf_mem[3] = tgt_mem_addr + 4;
10772           arm_insn_r->mem_rec_count = 2;
10773         }
10774     }
10775   else if (11 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
10776            || 2 == arm_insn_r->opcode  || 6 == arm_insn_r->opcode)
10777     {
10778       /* 3) Store, immediate pre-indexed.  */
10779       /* 5) Store, immediate post-indexed.  */
10780       immed_low = bits (arm_insn_r->arm_insn, 0, 3);
10781       immed_high = bits (arm_insn_r->arm_insn, 8, 11);
10782       offset_8 = (immed_high << 4) | immed_low;
10783       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
10784       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10785       /* Calculate target store address, Rn +/- Rm, register offset.  */
10786       if (15 == arm_insn_r->opcode || 6 == arm_insn_r->opcode)
10787         {
10788           tgt_mem_addr = u_regval[0] + offset_8;
10789         }
10790       else
10791         {
10792           tgt_mem_addr = u_regval[0] - offset_8;
10793         }
10794       if (ARM_RECORD_STRH == str_type)
10795         {
10796           record_buf_mem[0] = 2;
10797           record_buf_mem[1] = tgt_mem_addr;
10798           arm_insn_r->mem_rec_count = 1;
10799         }
10800       else if (ARM_RECORD_STRD == str_type)
10801         {
10802           record_buf_mem[0] = 4;
10803           record_buf_mem[1] = tgt_mem_addr;
10804           record_buf_mem[2] = 4;
10805           record_buf_mem[3] = tgt_mem_addr + 4;
10806           arm_insn_r->mem_rec_count = 2;
10807         }
10808       /* Record Rn also as it changes.  */
10809       *(record_buf) = bits (arm_insn_r->arm_insn, 16, 19);
10810       arm_insn_r->reg_rec_count = 1;
10811     }
10812   else if (9 == arm_insn_r->opcode || 13 == arm_insn_r->opcode
10813            || 0 == arm_insn_r->opcode || 4 == arm_insn_r->opcode)
10814     {
10815       /* 4) Store, register pre-indexed.  */
10816       /* 6) Store, register post -indexed.  */
10817       reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
10818       reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
10819       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10820       regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
10821       /* Calculate target store address, Rn +/- Rm, register offset.  */
10822       if (13 == arm_insn_r->opcode || 4 == arm_insn_r->opcode)
10823         {
10824           tgt_mem_addr = u_regval[0] + u_regval[1];
10825         }
10826       else
10827         {
10828           tgt_mem_addr = u_regval[1] - u_regval[0];
10829         }
10830       if (ARM_RECORD_STRH == str_type)
10831         {
10832           record_buf_mem[0] = 2;
10833           record_buf_mem[1] = tgt_mem_addr;
10834           arm_insn_r->mem_rec_count = 1;
10835         }
10836       else if (ARM_RECORD_STRD == str_type)
10837         {
10838           record_buf_mem[0] = 4;
10839           record_buf_mem[1] = tgt_mem_addr;
10840           record_buf_mem[2] = 4;
10841           record_buf_mem[3] = tgt_mem_addr + 4;
10842           arm_insn_r->mem_rec_count = 2;
10843         }
10844       /* Record Rn also as it changes.  */
10845       *(record_buf) = bits (arm_insn_r->arm_insn, 16, 19);
10846       arm_insn_r->reg_rec_count = 1;
10847     }
10848   return 0;
10849 }
10850
10851 /* Handling ARM extension space insns.  */
10852
10853 static int
10854 arm_record_extension_space (insn_decode_record *arm_insn_r)
10855 {
10856   uint32_t ret = 0;  /* Return value: -1:record failure ;  0:success  */
10857   uint32_t opcode1 = 0, opcode2 = 0, insn_op1 = 0;
10858   uint32_t record_buf[8], record_buf_mem[8];
10859   uint32_t reg_src1 = 0;
10860   uint32_t immed_high = 0, immed_low = 0,offset_8 = 0, tgt_mem_addr = 0;
10861   struct regcache *reg_cache = arm_insn_r->regcache;
10862   ULONGEST u_regval = 0;
10863
10864   gdb_assert (!INSN_RECORDED(arm_insn_r));
10865   /* Handle unconditional insn extension space.  */
10866
10867   opcode1 = bits (arm_insn_r->arm_insn, 20, 27);
10868   opcode2 = bits (arm_insn_r->arm_insn, 4, 7);
10869   if (arm_insn_r->cond)
10870     {
10871       /* PLD has no affect on architectural state, it just affects
10872          the caches.  */
10873       if (5 == ((opcode1 & 0xE0) >> 5))
10874         {
10875           /* BLX(1) */
10876           record_buf[0] = ARM_PS_REGNUM;
10877           record_buf[1] = ARM_LR_REGNUM;
10878           arm_insn_r->reg_rec_count = 2;
10879         }
10880       /* STC2, LDC2, MCR2, MRC2, CDP2: <TBD>, co-processor insn.  */
10881     }
10882
10883
10884   opcode1 = bits (arm_insn_r->arm_insn, 25, 27);
10885   if (3 == opcode1 && bit (arm_insn_r->arm_insn, 4))
10886     {
10887       ret = -1;
10888       /* Undefined instruction on ARM V5; need to handle if later 
10889          versions define it.  */
10890     }
10891
10892   opcode1 = bits (arm_insn_r->arm_insn, 24, 27);
10893   opcode2 = bits (arm_insn_r->arm_insn, 4, 7);
10894   insn_op1 = bits (arm_insn_r->arm_insn, 20, 23);
10895
10896   /* Handle arithmetic insn extension space.  */
10897   if (!opcode1 && 9 == opcode2 && 1 != arm_insn_r->cond
10898       && !INSN_RECORDED(arm_insn_r))
10899     {
10900       /* Handle MLA(S) and MUL(S).  */
10901       if (0 <= insn_op1 && 3 >= insn_op1)
10902       {
10903         record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10904         record_buf[1] = ARM_PS_REGNUM;
10905         arm_insn_r->reg_rec_count = 2;
10906       }
10907       else if (4 <= insn_op1 && 15 >= insn_op1)
10908       {
10909         /* Handle SMLAL(S), SMULL(S), UMLAL(S), UMULL(S).  */
10910         record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
10911         record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
10912         record_buf[2] = ARM_PS_REGNUM;
10913         arm_insn_r->reg_rec_count = 3;
10914       }
10915     }
10916
10917   opcode1 = bits (arm_insn_r->arm_insn, 26, 27);
10918   opcode2 = bits (arm_insn_r->arm_insn, 23, 24);
10919   insn_op1 = bits (arm_insn_r->arm_insn, 21, 22);
10920
10921   /* Handle control insn extension space.  */
10922
10923   if (!opcode1 && 2 == opcode2 && !bit (arm_insn_r->arm_insn, 20)
10924       && 1 != arm_insn_r->cond && !INSN_RECORDED(arm_insn_r))
10925     {
10926       if (!bit (arm_insn_r->arm_insn,25))
10927         {
10928           if (!bits (arm_insn_r->arm_insn, 4, 7))
10929             {
10930               if ((0 == insn_op1) || (2 == insn_op1))
10931                 {
10932                   /* MRS.  */
10933                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10934                   arm_insn_r->reg_rec_count = 1;
10935                 }
10936               else if (1 == insn_op1)
10937                 {
10938                   /* CSPR is going to be changed.  */
10939                   record_buf[0] = ARM_PS_REGNUM;
10940                   arm_insn_r->reg_rec_count = 1;
10941                 }
10942               else if (3 == insn_op1)
10943                 {
10944                   /* SPSR is going to be changed.  */
10945                   /* We need to get SPSR value, which is yet to be done.  */
10946                   printf_unfiltered (_("Process record does not support "
10947                                      "instruction  0x%0x at address %s.\n"),
10948                                      arm_insn_r->arm_insn,
10949                                      paddress (arm_insn_r->gdbarch, 
10950                                      arm_insn_r->this_addr));
10951                   return -1;
10952                 }
10953             }
10954           else if (1 == bits (arm_insn_r->arm_insn, 4, 7))
10955             {
10956               if (1 == insn_op1)
10957                 {
10958                   /* BX.  */
10959                   record_buf[0] = ARM_PS_REGNUM;
10960                   arm_insn_r->reg_rec_count = 1;
10961                 }
10962               else if (3 == insn_op1)
10963                 {
10964                   /* CLZ.  */
10965                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10966                   arm_insn_r->reg_rec_count = 1;
10967                 }
10968             }
10969           else if (3 == bits (arm_insn_r->arm_insn, 4, 7))
10970             {
10971               /* BLX.  */
10972               record_buf[0] = ARM_PS_REGNUM;
10973               record_buf[1] = ARM_LR_REGNUM;
10974               arm_insn_r->reg_rec_count = 2;
10975             }
10976           else if (5 == bits (arm_insn_r->arm_insn, 4, 7))
10977             {
10978               /* QADD, QSUB, QDADD, QDSUB */
10979               record_buf[0] = ARM_PS_REGNUM;
10980               record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
10981               arm_insn_r->reg_rec_count = 2;
10982             }
10983           else if (7 == bits (arm_insn_r->arm_insn, 4, 7))
10984             {
10985               /* BKPT.  */
10986               record_buf[0] = ARM_PS_REGNUM;
10987               record_buf[1] = ARM_LR_REGNUM;
10988               arm_insn_r->reg_rec_count = 2;
10989
10990               /* Save SPSR also;how?  */
10991               printf_unfiltered (_("Process record does not support "
10992                                   "instruction 0x%0x at address %s.\n"),
10993                                   arm_insn_r->arm_insn,
10994                   paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
10995               return -1;
10996             }
10997           else if(8 == bits (arm_insn_r->arm_insn, 4, 7) 
10998                   || 10 == bits (arm_insn_r->arm_insn, 4, 7)
10999                   || 12 == bits (arm_insn_r->arm_insn, 4, 7)
11000                   || 14 == bits (arm_insn_r->arm_insn, 4, 7)
11001                  )
11002             {
11003               if (0 == insn_op1 || 1 == insn_op1)
11004                 {
11005                   /* SMLA<x><y>, SMLAW<y>, SMULW<y>.  */
11006                   /* We dont do optimization for SMULW<y> where we
11007                      need only Rd.  */
11008                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11009                   record_buf[1] = ARM_PS_REGNUM;
11010                   arm_insn_r->reg_rec_count = 2;
11011                 }
11012               else if (2 == insn_op1)
11013                 {
11014                   /* SMLAL<x><y>.  */
11015                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11016                   record_buf[1] = bits (arm_insn_r->arm_insn, 16, 19);
11017                   arm_insn_r->reg_rec_count = 2;
11018                 }
11019               else if (3 == insn_op1)
11020                 {
11021                   /* SMUL<x><y>.  */
11022                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11023                   arm_insn_r->reg_rec_count = 1;
11024                 }
11025             }
11026         }
11027       else
11028         {
11029           /* MSR : immediate form.  */
11030           if (1 == insn_op1)
11031             {
11032               /* CSPR is going to be changed.  */
11033               record_buf[0] = ARM_PS_REGNUM;
11034               arm_insn_r->reg_rec_count = 1;
11035             }
11036           else if (3 == insn_op1)
11037             {
11038               /* SPSR is going to be changed.  */
11039               /* we need to get SPSR value, which is yet to be done  */
11040               printf_unfiltered (_("Process record does not support "
11041                                    "instruction 0x%0x at address %s.\n"),
11042                                     arm_insn_r->arm_insn,
11043                                     paddress (arm_insn_r->gdbarch, 
11044                                     arm_insn_r->this_addr));
11045               return -1;
11046             }
11047         }
11048     }
11049
11050   opcode1 = bits (arm_insn_r->arm_insn, 25, 27);
11051   opcode2 = bits (arm_insn_r->arm_insn, 20, 24);
11052   insn_op1 = bits (arm_insn_r->arm_insn, 5, 6);
11053
11054   /* Handle load/store insn extension space.  */
11055
11056   if (!opcode1 && bit (arm_insn_r->arm_insn, 7) 
11057       && bit (arm_insn_r->arm_insn, 4) && 1 != arm_insn_r->cond
11058       && !INSN_RECORDED(arm_insn_r))
11059     {
11060       /* SWP/SWPB.  */
11061       if (0 == insn_op1)
11062         {
11063           /* These insn, changes register and memory as well.  */
11064           /* SWP or SWPB insn.  */
11065           /* Get memory address given by Rn.  */
11066           reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11067           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
11068           /* SWP insn ?, swaps word.  */
11069           if (8 == arm_insn_r->opcode)
11070             {
11071               record_buf_mem[0] = 4;
11072             }
11073           else
11074             {
11075               /* SWPB insn, swaps only byte.  */
11076               record_buf_mem[0] = 1;
11077             }
11078           record_buf_mem[1] = u_regval;
11079           arm_insn_r->mem_rec_count = 1;
11080           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11081           arm_insn_r->reg_rec_count = 1;
11082         }
11083       else if (1 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11084         {
11085           /* STRH.  */
11086           arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11087                           ARM_RECORD_STRH);
11088         }
11089       else if (2 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11090         {
11091           /* LDRD.  */
11092           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11093           record_buf[1] = record_buf[0] + 1;
11094           arm_insn_r->reg_rec_count = 2;
11095         }
11096       else if (3 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11097         {
11098           /* STRD.  */
11099           arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11100                         ARM_RECORD_STRD);
11101         }
11102       else if (bit (arm_insn_r->arm_insn, 20) && insn_op1 <= 3)
11103         {
11104           /* LDRH, LDRSB, LDRSH.  */
11105           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11106           arm_insn_r->reg_rec_count = 1;
11107         }
11108
11109     }
11110
11111   opcode1 = bits (arm_insn_r->arm_insn, 23, 27);
11112   if (24 == opcode1 && bit (arm_insn_r->arm_insn, 21)
11113       && !INSN_RECORDED(arm_insn_r))
11114     {
11115       ret = -1;
11116       /* Handle coprocessor insn extension space.  */
11117     }
11118
11119   /* To be done for ARMv5 and later; as of now we return -1.  */
11120   if (-1 == ret)
11121     printf_unfiltered (_("Process record does not support instruction x%0x "
11122                          "at address %s.\n"),arm_insn_r->arm_insn,
11123                          paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11124
11125
11126   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11127   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11128
11129   return ret;
11130 }
11131
11132 /* Handling opcode 000 insns.  */
11133
11134 static int
11135 arm_record_data_proc_misc_ld_str (insn_decode_record *arm_insn_r)
11136 {
11137   struct regcache *reg_cache = arm_insn_r->regcache;
11138   uint32_t record_buf[8], record_buf_mem[8];
11139   ULONGEST u_regval[2] = {0};
11140
11141   uint32_t reg_src1 = 0, reg_src2 = 0, reg_dest = 0;
11142   uint32_t immed_high = 0, immed_low = 0, offset_8 = 0, tgt_mem_addr = 0;
11143   uint32_t opcode1 = 0;
11144
11145   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11146   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11147   opcode1 = bits (arm_insn_r->arm_insn, 20, 24);
11148
11149   /* Data processing insn /multiply insn.  */
11150   if (9 == arm_insn_r->decode
11151       && ((4 <= arm_insn_r->opcode && 7 >= arm_insn_r->opcode)
11152       ||  (0 == arm_insn_r->opcode || 1 == arm_insn_r->opcode)))
11153     {
11154       /* Handle multiply instructions.  */
11155       /* MLA, MUL, SMLAL, SMULL, UMLAL, UMULL.  */
11156         if (0 == arm_insn_r->opcode || 1 == arm_insn_r->opcode)
11157           {
11158             /* Handle MLA and MUL.  */
11159             record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
11160             record_buf[1] = ARM_PS_REGNUM;
11161             arm_insn_r->reg_rec_count = 2;
11162           }
11163         else if (4 <= arm_insn_r->opcode && 7 >= arm_insn_r->opcode)
11164           {
11165             /* Handle SMLAL, SMULL, UMLAL, UMULL.  */
11166             record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
11167             record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
11168             record_buf[2] = ARM_PS_REGNUM;
11169             arm_insn_r->reg_rec_count = 3;
11170           }
11171     }
11172   else if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM)
11173            && (11 == arm_insn_r->decode || 13 == arm_insn_r->decode))
11174     {
11175       /* Handle misc load insns, as 20th bit  (L = 1).  */
11176       /* LDR insn has a capability to do branching, if
11177          MOV LR, PC is precceded by LDR insn having Rn as R15
11178          in that case, it emulates branch and link insn, and hence we 
11179          need to save CSPR and PC as well. I am not sure this is right
11180          place; as opcode = 010 LDR insn make this happen, if R15 was
11181          used.  */
11182       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11183       if (15 != reg_dest)
11184         {
11185           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11186           arm_insn_r->reg_rec_count = 1;
11187         }
11188       else
11189         {
11190           record_buf[0] = reg_dest;
11191           record_buf[1] = ARM_PS_REGNUM;
11192           arm_insn_r->reg_rec_count = 2;
11193         }
11194     }
11195   else if ((9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode)
11196            && sbo_sbz (arm_insn_r->arm_insn, 5, 12, 0)
11197            && sbo_sbz (arm_insn_r->arm_insn, 13, 4, 1)
11198            && 2 == bits (arm_insn_r->arm_insn, 20, 21))
11199     {
11200       /* Handle MSR insn.  */
11201       if (9 == arm_insn_r->opcode)
11202         {
11203           /* CSPR is going to be changed.  */
11204           record_buf[0] = ARM_PS_REGNUM;
11205           arm_insn_r->reg_rec_count = 1;
11206         }
11207       else
11208         {
11209           /* SPSR is going to be changed.  */
11210           /* How to read SPSR value?  */
11211           printf_unfiltered (_("Process record does not support instruction "
11212                             "0x%0x at address %s.\n"),
11213                             arm_insn_r->arm_insn,
11214                         paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11215           return -1;
11216         }
11217     }
11218   else if (9 == arm_insn_r->decode
11219            && (8 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
11220            && !bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11221     {
11222       /* Handling SWP, SWPB.  */
11223       /* These insn, changes register and memory as well.  */
11224       /* SWP or SWPB insn.  */
11225
11226       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11227       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11228       /* SWP insn ?, swaps word.  */
11229       if (8 == arm_insn_r->opcode)
11230         {
11231           record_buf_mem[0] = 4;
11232         }
11233         else
11234         {
11235           /* SWPB insn, swaps only byte.  */
11236           record_buf_mem[0] = 1;
11237         }
11238       record_buf_mem[1] = u_regval[0];
11239       arm_insn_r->mem_rec_count = 1;
11240       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11241       arm_insn_r->reg_rec_count = 1;
11242     }
11243   else if (3 == arm_insn_r->decode && 0x12 == opcode1
11244            && sbo_sbz (arm_insn_r->arm_insn, 9, 12, 1))
11245     {
11246       /* Handle BLX, branch and link/exchange.  */
11247       if (9 == arm_insn_r->opcode)
11248       {
11249         /* Branch is chosen by setting T bit of CSPR, bitp[0] of Rm,
11250            and R14 stores the return address.  */
11251         record_buf[0] = ARM_PS_REGNUM;
11252         record_buf[1] = ARM_LR_REGNUM;
11253         arm_insn_r->reg_rec_count = 2;
11254       }
11255     }
11256   else if (7 == arm_insn_r->decode && 0x12 == opcode1)
11257     {
11258       /* Handle enhanced software breakpoint insn, BKPT.  */
11259       /* CPSR is changed to be executed in ARM state,  disabling normal
11260          interrupts, entering abort mode.  */
11261       /* According to high vector configuration PC is set.  */
11262       /* user hit breakpoint and type reverse, in
11263          that case, we need to go back with previous CPSR and
11264          Program Counter.  */
11265       record_buf[0] = ARM_PS_REGNUM;
11266       record_buf[1] = ARM_LR_REGNUM;
11267       arm_insn_r->reg_rec_count = 2;
11268
11269       /* Save SPSR also; how?  */
11270       printf_unfiltered (_("Process record does not support instruction "
11271                            "0x%0x at address %s.\n"),arm_insn_r->arm_insn,
11272                            paddress (arm_insn_r->gdbarch, 
11273                            arm_insn_r->this_addr));
11274       return -1;
11275     }
11276   else if (11 == arm_insn_r->decode
11277            && !bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11278   {
11279     /* Handle enhanced store insns and DSP insns (e.g. LDRD).  */
11280
11281     /* Handle str(x) insn */
11282     arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11283                     ARM_RECORD_STRH);
11284   }
11285   else if (1 == arm_insn_r->decode && 0x12 == opcode1
11286            && sbo_sbz (arm_insn_r->arm_insn, 9, 12, 1))
11287     {
11288       /* Handle BX, branch and link/exchange.  */
11289       /* Branch is chosen by setting T bit of CSPR, bitp[0] of Rm.  */
11290       record_buf[0] = ARM_PS_REGNUM;
11291       arm_insn_r->reg_rec_count = 1;
11292     }
11293   else if (1 == arm_insn_r->decode && 0x16 == opcode1
11294            && sbo_sbz (arm_insn_r->arm_insn, 9, 4, 1)
11295            && sbo_sbz (arm_insn_r->arm_insn, 17, 4, 1))
11296     {
11297       /* Count leading zeros: CLZ.  */
11298       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11299       arm_insn_r->reg_rec_count = 1;
11300     }
11301   else if (!bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM)
11302            && (8 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
11303            && sbo_sbz (arm_insn_r->arm_insn, 17, 4, 1)
11304            && sbo_sbz (arm_insn_r->arm_insn, 1, 12, 0)
11305           )
11306     {
11307       /* Handle MRS insn.  */
11308       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11309       arm_insn_r->reg_rec_count = 1;
11310     }
11311   else if (arm_insn_r->opcode <= 15)
11312     {
11313       /* Normal data processing insns.  */
11314       /* Out of 11 shifter operands mode, all the insn modifies destination
11315          register, which is specified by 13-16 decode.  */
11316       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11317       record_buf[1] = ARM_PS_REGNUM;
11318       arm_insn_r->reg_rec_count = 2;
11319     }
11320   else
11321     {
11322       return -1;
11323     }
11324
11325   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11326   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11327   return 0;
11328 }
11329
11330 /* Handling opcode 001 insns.  */
11331
11332 static int
11333 arm_record_data_proc_imm (insn_decode_record *arm_insn_r)
11334 {
11335   uint32_t record_buf[8], record_buf_mem[8];
11336
11337   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11338   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11339
11340   if ((9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode)
11341       && 2 == bits (arm_insn_r->arm_insn, 20, 21)
11342       && sbo_sbz (arm_insn_r->arm_insn, 13, 4, 1)
11343      )
11344     {
11345       /* Handle MSR insn.  */
11346       if (9 == arm_insn_r->opcode)
11347         {
11348           /* CSPR is going to be changed.  */
11349           record_buf[0] = ARM_PS_REGNUM;
11350           arm_insn_r->reg_rec_count = 1;
11351         }
11352       else
11353         {
11354           /* SPSR is going to be changed.  */
11355         }
11356     }
11357   else if (arm_insn_r->opcode <= 15)
11358     {
11359       /* Normal data processing insns.  */
11360       /* Out of 11 shifter operands mode, all the insn modifies destination
11361          register, which is specified by 13-16 decode.  */
11362       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11363       record_buf[1] = ARM_PS_REGNUM;
11364       arm_insn_r->reg_rec_count = 2;
11365     }
11366   else
11367     {
11368       return -1;
11369     }
11370
11371   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11372   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11373   return 0;
11374 }
11375
11376 /* Handling opcode 010 insns.  */
11377
11378 static int
11379 arm_record_ld_st_imm_offset (insn_decode_record *arm_insn_r)
11380 {
11381   struct regcache *reg_cache = arm_insn_r->regcache;
11382
11383   uint32_t reg_src1 = 0 , reg_dest = 0;
11384   uint32_t offset_12 = 0, tgt_mem_addr = 0;
11385   uint32_t record_buf[8], record_buf_mem[8];
11386
11387   ULONGEST u_regval = 0;
11388
11389   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11390   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11391
11392   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11393     {
11394       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11395       /* LDR insn has a capability to do branching, if
11396          MOV LR, PC is precedded by LDR insn having Rn as R15
11397          in that case, it emulates branch and link insn, and hence we
11398          need to save CSPR and PC as well.  */
11399       if (ARM_PC_REGNUM != reg_dest)
11400         {
11401           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11402           arm_insn_r->reg_rec_count = 1;
11403         }
11404       else
11405         {
11406           record_buf[0] = reg_dest;
11407           record_buf[1] = ARM_PS_REGNUM;
11408           arm_insn_r->reg_rec_count = 2;
11409         }
11410     }
11411   else
11412     {
11413       /* Store, immediate offset, immediate pre-indexed,
11414          immediate post-indexed.  */
11415       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11416       offset_12 = bits (arm_insn_r->arm_insn, 0, 11);
11417       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
11418       /* U == 1 */
11419       if (bit (arm_insn_r->arm_insn, 23))
11420         {
11421           tgt_mem_addr = u_regval + offset_12;
11422         }
11423       else
11424         {
11425           tgt_mem_addr = u_regval - offset_12;
11426         }
11427
11428       switch (arm_insn_r->opcode)
11429         {
11430           /* STR.  */
11431           case 8:
11432           case 12:
11433           /* STR.  */
11434           case 9:
11435           case 13:
11436           /* STRT.  */    
11437           case 1:
11438           case 5:
11439           /* STR.  */    
11440           case 4:
11441           case 0:
11442             record_buf_mem[0] = 4;
11443           break;
11444
11445           /* STRB.  */
11446           case 10:
11447           case 14:
11448           /* STRB.  */    
11449           case 11:
11450           case 15:
11451           /* STRBT.  */    
11452           case 3:
11453           case 7:
11454           /* STRB.  */    
11455           case 2:
11456           case 6:
11457             record_buf_mem[0] = 1;
11458           break;
11459
11460           default:
11461             gdb_assert_not_reached ("no decoding pattern found");
11462           break;
11463         }
11464       record_buf_mem[1] = tgt_mem_addr;
11465       arm_insn_r->mem_rec_count = 1;
11466
11467       if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11468           || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11469           || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11470           || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11471           || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11472           || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11473          )
11474         {
11475           /* We are handling pre-indexed mode; post-indexed mode;
11476              where Rn is going to be changed.  */
11477           record_buf[0] = reg_src1;
11478           arm_insn_r->reg_rec_count = 1;
11479         }
11480     }
11481
11482   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11483   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11484   return 0;
11485 }
11486
11487 /* Handling opcode 011 insns.  */
11488
11489 static int
11490 arm_record_ld_st_reg_offset (insn_decode_record *arm_insn_r)
11491 {
11492   struct regcache *reg_cache = arm_insn_r->regcache;
11493
11494   uint32_t shift_imm = 0;
11495   uint32_t reg_src1 = 0, reg_src2 = 0, reg_dest = 0;
11496   uint32_t offset_12 = 0, tgt_mem_addr = 0;
11497   uint32_t record_buf[8], record_buf_mem[8];
11498
11499   LONGEST s_word;
11500   ULONGEST u_regval[2];
11501
11502   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11503   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11504
11505   /* Handle enhanced store insns and LDRD DSP insn,
11506      order begins according to addressing modes for store insns
11507      STRH insn.  */
11508
11509   /* LDR or STR?  */
11510   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11511     {
11512       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11513       /* LDR insn has a capability to do branching, if
11514          MOV LR, PC is precedded by LDR insn having Rn as R15
11515          in that case, it emulates branch and link insn, and hence we
11516          need to save CSPR and PC as well.  */
11517       if (15 != reg_dest)
11518         {
11519           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11520           arm_insn_r->reg_rec_count = 1;
11521         }
11522       else
11523         {
11524           record_buf[0] = reg_dest;
11525           record_buf[1] = ARM_PS_REGNUM;
11526           arm_insn_r->reg_rec_count = 2;
11527         }
11528     }
11529   else
11530     {
11531       if (! bits (arm_insn_r->arm_insn, 4, 11))
11532         {
11533           /* Store insn, register offset and register pre-indexed,
11534              register post-indexed.  */
11535           /* Get Rm.  */
11536           reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
11537           /* Get Rn.  */
11538           reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
11539           regcache_raw_read_unsigned (reg_cache, reg_src1
11540                                       , &u_regval[0]);
11541           regcache_raw_read_unsigned (reg_cache, reg_src2
11542                                       , &u_regval[1]);
11543           if (15 == reg_src2)
11544             {
11545               /* If R15 was used as Rn, hence current PC+8.  */
11546               /* Pre-indexed mode doesnt reach here ; illegal insn.  */
11547                 u_regval[0] = u_regval[0] + 8;
11548             }
11549           /* Calculate target store address, Rn +/- Rm, register offset.  */
11550           /* U == 1.  */
11551           if (bit (arm_insn_r->arm_insn, 23))
11552             {
11553               tgt_mem_addr = u_regval[0] + u_regval[1];
11554             }
11555           else
11556             {
11557               tgt_mem_addr = u_regval[1] - u_regval[0];
11558             }
11559
11560           switch (arm_insn_r->opcode)
11561             {
11562               /* STR.  */
11563               case 8:
11564               case 12:
11565               /* STR.  */    
11566               case 9:
11567               case 13:
11568               /* STRT.  */
11569               case 1:
11570               case 5:
11571               /* STR.  */
11572               case 0:
11573               case 4:
11574                 record_buf_mem[0] = 4;
11575               break;
11576
11577               /* STRB.  */
11578               case 10:
11579               case 14:
11580               /* STRB.  */
11581               case 11:
11582               case 15:
11583               /* STRBT.  */    
11584               case 3:
11585               case 7:
11586               /* STRB.  */
11587               case 2:
11588               case 6:
11589                 record_buf_mem[0] = 1;
11590               break;
11591
11592               default:
11593                 gdb_assert_not_reached ("no decoding pattern found");
11594               break;
11595             }
11596           record_buf_mem[1] = tgt_mem_addr;
11597           arm_insn_r->mem_rec_count = 1;
11598
11599           if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11600               || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11601               || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11602               || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11603               || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11604               || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11605              )
11606             {
11607               /* Rn is going to be changed in pre-indexed mode and
11608                  post-indexed mode as well.  */
11609               record_buf[0] = reg_src2;
11610               arm_insn_r->reg_rec_count = 1;
11611             }
11612         }
11613       else
11614         {
11615           /* Store insn, scaled register offset; scaled pre-indexed.  */
11616           offset_12 = bits (arm_insn_r->arm_insn, 5, 6);
11617           /* Get Rm.  */
11618           reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
11619           /* Get Rn.  */
11620           reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
11621           /* Get shift_imm.  */
11622           shift_imm = bits (arm_insn_r->arm_insn, 7, 11);
11623           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11624           regcache_raw_read_signed (reg_cache, reg_src1, &s_word);
11625           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
11626           /* Offset_12 used as shift.  */
11627           switch (offset_12)
11628             {
11629               case 0:
11630                 /* Offset_12 used as index.  */
11631                 offset_12 = u_regval[0] << shift_imm;
11632               break;
11633
11634               case 1:
11635                 offset_12 = (!shift_imm)?0:u_regval[0] >> shift_imm;
11636               break;
11637
11638               case 2:
11639                 if (!shift_imm)
11640                   {
11641                     if (bit (u_regval[0], 31))
11642                       {
11643                         offset_12 = 0xFFFFFFFF;
11644                       }
11645                     else
11646                       {
11647                         offset_12 = 0;
11648                       }
11649                   }
11650                 else
11651                   {
11652                     /* This is arithmetic shift.  */
11653                     offset_12 = s_word >> shift_imm;
11654                   }
11655                 break;
11656
11657               case 3:
11658                 if (!shift_imm)
11659                   {
11660                     regcache_raw_read_unsigned (reg_cache, ARM_PS_REGNUM,
11661                                                 &u_regval[1]);
11662                     /* Get C flag value and shift it by 31.  */
11663                     offset_12 = (((bit (u_regval[1], 29)) << 31) \
11664                                   | (u_regval[0]) >> 1);
11665                   }
11666                 else
11667                   {
11668                     offset_12 = (u_regval[0] >> shift_imm) \
11669                                 | (u_regval[0] <<
11670                                 (sizeof(uint32_t) - shift_imm));
11671                   }
11672               break;
11673
11674               default:
11675                 gdb_assert_not_reached ("no decoding pattern found");
11676               break;
11677             }
11678
11679           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
11680           /* bit U set.  */
11681           if (bit (arm_insn_r->arm_insn, 23))
11682             {
11683               tgt_mem_addr = u_regval[1] + offset_12;
11684             }
11685           else
11686             {
11687               tgt_mem_addr = u_regval[1] - offset_12;
11688             }
11689
11690           switch (arm_insn_r->opcode)
11691             {
11692               /* STR.  */
11693               case 8:
11694               case 12:
11695               /* STR.  */    
11696               case 9:
11697               case 13:
11698               /* STRT.  */
11699               case 1:
11700               case 5:
11701               /* STR.  */
11702               case 0:
11703               case 4:
11704                 record_buf_mem[0] = 4;
11705               break;
11706
11707               /* STRB.  */
11708               case 10:
11709               case 14:
11710               /* STRB.  */
11711               case 11:
11712               case 15:
11713               /* STRBT.  */    
11714               case 3:
11715               case 7:
11716               /* STRB.  */
11717               case 2:
11718               case 6:
11719                 record_buf_mem[0] = 1;
11720               break;
11721
11722               default:
11723                 gdb_assert_not_reached ("no decoding pattern found");
11724               break;
11725             }
11726           record_buf_mem[1] = tgt_mem_addr;
11727           arm_insn_r->mem_rec_count = 1;
11728
11729           if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11730               || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11731               || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11732               || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11733               || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11734               || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11735              )
11736             {
11737               /* Rn is going to be changed in register scaled pre-indexed
11738                  mode,and scaled post indexed mode.  */
11739               record_buf[0] = reg_src2;
11740               arm_insn_r->reg_rec_count = 1;
11741             }
11742         }
11743     }
11744
11745   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11746   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11747   return 0;
11748 }
11749
11750 /* Handling opcode 100 insns.  */
11751
11752 static int
11753 arm_record_ld_st_multiple (insn_decode_record *arm_insn_r)
11754 {
11755   struct regcache *reg_cache = arm_insn_r->regcache;
11756
11757   uint32_t register_list[16] = {0}, register_count = 0, register_bits = 0;
11758   uint32_t reg_src1 = 0, addr_mode = 0, no_of_regs = 0;
11759   uint32_t start_address = 0, index = 0;
11760   uint32_t record_buf[24], record_buf_mem[48];
11761
11762   ULONGEST u_regval[2] = {0};
11763
11764   /* This mode is exclusively for load and store multiple.  */
11765   /* Handle incremenrt after/before and decrment after.before mode;
11766      Rn is changing depending on W bit, but as of now we store Rn too
11767      without optimization.  */
11768
11769   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11770     {
11771       /* LDM  (1,2,3) where LDM  (3) changes CPSR too.  */
11772
11773       if (bit (arm_insn_r->arm_insn, 20) && !bit (arm_insn_r->arm_insn, 22))
11774         {
11775           register_bits = bits (arm_insn_r->arm_insn, 0, 15);
11776           no_of_regs = 15;
11777         }
11778       else
11779         {
11780           register_bits = bits (arm_insn_r->arm_insn, 0, 14);
11781           no_of_regs = 14;
11782         }
11783       /* Get Rn.  */
11784       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11785       while (register_bits)
11786       {
11787         if (register_bits & 0x00000001)
11788           record_buf[index++] = register_count;
11789         register_bits = register_bits >> 1;
11790         register_count++;
11791       }
11792
11793         /* Extra space for Base Register and CPSR; wihtout optimization.  */
11794         record_buf[index++] = reg_src1;
11795         record_buf[index++] = ARM_PS_REGNUM;
11796         arm_insn_r->reg_rec_count = index;
11797     }
11798   else
11799     {
11800       /* It handles both STM(1) and STM(2).  */
11801       addr_mode = bits (arm_insn_r->arm_insn, 23, 24);    
11802
11803       register_bits = bits (arm_insn_r->arm_insn, 0, 15);
11804       /* Get Rn.  */
11805       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11806       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11807       while (register_bits)
11808         {
11809           if (register_bits & 0x00000001)
11810             register_count++;
11811           register_bits = register_bits >> 1;
11812         }
11813
11814       switch (addr_mode)
11815         {
11816           /* Decrement after.  */
11817           case 0:                          
11818             start_address = (u_regval[0]) - (register_count * 4) + 4;
11819             arm_insn_r->mem_rec_count = register_count;
11820             while (register_count)
11821               {
11822                 record_buf_mem[(register_count * 2) - 1] = start_address;
11823                 record_buf_mem[(register_count * 2) - 2] = 4;
11824                 start_address = start_address + 4;
11825                 register_count--;
11826               }
11827           break;    
11828
11829           /* Increment after.  */
11830           case 1:
11831             start_address = u_regval[0];
11832             arm_insn_r->mem_rec_count = register_count;
11833             while (register_count)
11834               {
11835                 record_buf_mem[(register_count * 2) - 1] = start_address;
11836                 record_buf_mem[(register_count * 2) - 2] = 4;
11837                 start_address = start_address + 4;
11838                 register_count--;
11839               }
11840           break;    
11841
11842           /* Decrement before.  */
11843           case 2:
11844
11845             start_address = (u_regval[0]) - (register_count * 4);
11846             arm_insn_r->mem_rec_count = register_count;
11847             while (register_count)
11848               {
11849                 record_buf_mem[(register_count * 2) - 1] = start_address;
11850                 record_buf_mem[(register_count * 2) - 2] = 4;
11851                 start_address = start_address + 4;
11852                 register_count--;
11853               }
11854           break;    
11855
11856           /* Increment before.  */
11857           case 3:
11858             start_address = u_regval[0] + 4;
11859             arm_insn_r->mem_rec_count = register_count;
11860             while (register_count)
11861               {
11862                 record_buf_mem[(register_count * 2) - 1] = start_address;
11863                 record_buf_mem[(register_count * 2) - 2] = 4;
11864                 start_address = start_address + 4;
11865                 register_count--;
11866               }
11867           break;    
11868
11869           default:
11870             gdb_assert_not_reached ("no decoding pattern found");
11871           break;    
11872         }
11873
11874       /* Base register also changes; based on condition and W bit.  */
11875       /* We save it anyway without optimization.  */
11876       record_buf[0] = reg_src1;
11877       arm_insn_r->reg_rec_count = 1;
11878     }
11879
11880   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11881   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11882   return 0;
11883 }
11884
11885 /* Handling opcode 101 insns.  */
11886
11887 static int
11888 arm_record_b_bl (insn_decode_record *arm_insn_r)
11889 {
11890   uint32_t record_buf[8];
11891
11892   /* Handle B, BL, BLX(1) insns.  */
11893   /* B simply branches so we do nothing here.  */
11894   /* Note: BLX(1) doesnt fall here but instead it falls into
11895      extension space.  */
11896   if (bit (arm_insn_r->arm_insn, 24))
11897   {
11898     record_buf[0] = ARM_LR_REGNUM;
11899     arm_insn_r->reg_rec_count = 1;
11900   }
11901
11902   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11903
11904   return 0;
11905 }
11906
11907 /* Handling opcode 110 insns.  */
11908
11909 static int
11910 arm_record_unsupported_insn (insn_decode_record *arm_insn_r)
11911 {
11912   printf_unfiltered (_("Process record does not support instruction "
11913                     "0x%0x at address %s.\n"),arm_insn_r->arm_insn,
11914                     paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11915
11916   return -1;
11917 }
11918
11919 /* Handling opcode 111 insns.  */
11920
11921 static int
11922 arm_record_coproc_data_proc (insn_decode_record *arm_insn_r)
11923 {
11924   struct gdbarch_tdep *tdep = gdbarch_tdep (arm_insn_r->gdbarch);
11925   struct regcache *reg_cache = arm_insn_r->regcache;
11926   uint32_t ret = 0; /* function return value: -1:record failure ;  0:success  */
11927   ULONGEST u_regval = 0;
11928
11929   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 24, 27);
11930
11931   /* Handle arm SWI/SVC system call instructions.  */
11932   if (15 == arm_insn_r->opcode)
11933     {
11934       if (tdep->arm_syscall_record != NULL)
11935         {
11936           ULONGEST svc_operand, svc_number;
11937
11938           svc_operand = (0x00ffffff & arm_insn_r->arm_insn);
11939
11940           if (svc_operand)  /* OABI.  */
11941             svc_number = svc_operand - 0x900000;
11942           else /* EABI.  */
11943             regcache_raw_read_unsigned (reg_cache, 7, &svc_number);
11944
11945           ret = tdep->arm_syscall_record (reg_cache, svc_number);
11946         }
11947       else
11948         {
11949           printf_unfiltered (_("no syscall record support\n"));
11950           ret = -1;
11951         }
11952     }
11953   else
11954     {
11955       arm_record_unsupported_insn (arm_insn_r);
11956       ret = -1;
11957     }
11958
11959   return ret;
11960 }
11961
11962 /* Handling opcode 000 insns.  */
11963
11964 static int
11965 thumb_record_shift_add_sub (insn_decode_record *thumb_insn_r)
11966 {
11967   uint32_t record_buf[8];
11968   uint32_t reg_src1 = 0;
11969
11970   reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
11971
11972   record_buf[0] = ARM_PS_REGNUM;
11973   record_buf[1] = reg_src1;
11974   thumb_insn_r->reg_rec_count = 2;
11975
11976   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
11977
11978   return 0;
11979 }
11980
11981
11982 /* Handling opcode 001 insns.  */
11983
11984 static int
11985 thumb_record_add_sub_cmp_mov (insn_decode_record *thumb_insn_r)
11986 {
11987   uint32_t record_buf[8];
11988   uint32_t reg_src1 = 0;
11989
11990   reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
11991
11992   record_buf[0] = ARM_PS_REGNUM;
11993   record_buf[1] = reg_src1;
11994   thumb_insn_r->reg_rec_count = 2;
11995
11996   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
11997
11998   return 0;
11999 }
12000
12001 /* Handling opcode 010 insns.  */
12002
12003 static int
12004 thumb_record_ld_st_reg_offset (insn_decode_record *thumb_insn_r)
12005 {
12006   struct regcache *reg_cache =  thumb_insn_r->regcache;
12007   uint32_t record_buf[8], record_buf_mem[8];
12008
12009   uint32_t reg_src1 = 0, reg_src2 = 0;
12010   uint32_t opcode1 = 0, opcode2 = 0, opcode3 = 0;
12011
12012   ULONGEST u_regval[2] = {0};
12013
12014   opcode1 = bits (thumb_insn_r->arm_insn, 10, 12);
12015
12016   if (bit (thumb_insn_r->arm_insn, 12))
12017     {
12018       /* Handle load/store register offset.  */
12019       opcode2 = bits (thumb_insn_r->arm_insn, 9, 10);
12020       if (opcode2 >= 12 && opcode2 <= 15)
12021         {
12022           /* LDR(2), LDRB(2) , LDRH(2), LDRSB, LDRSH.  */
12023           reg_src1 = bits (thumb_insn_r->arm_insn,0, 2);
12024           record_buf[0] = reg_src1;
12025           thumb_insn_r->reg_rec_count = 1;
12026         }
12027       else if (opcode2 >= 8 && opcode2 <= 10)
12028         {
12029           /* STR(2), STRB(2), STRH(2) .  */
12030           reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12031           reg_src2 = bits (thumb_insn_r->arm_insn, 6, 8);
12032           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
12033           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
12034           if (8 == opcode2)
12035             record_buf_mem[0] = 4;    /* STR (2).  */
12036           else if (10 == opcode2)
12037             record_buf_mem[0] = 1;    /*  STRB (2).  */
12038           else if (9 == opcode2)
12039             record_buf_mem[0] = 2;    /* STRH (2).  */
12040           record_buf_mem[1] = u_regval[0] + u_regval[1];
12041           thumb_insn_r->mem_rec_count = 1;
12042         }
12043     }
12044   else if (bit (thumb_insn_r->arm_insn, 11))
12045     {
12046       /* Handle load from literal pool.  */
12047       /* LDR(3).  */
12048       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12049       record_buf[0] = reg_src1;
12050       thumb_insn_r->reg_rec_count = 1;
12051     }
12052   else if (opcode1)
12053     {
12054       opcode2 = bits (thumb_insn_r->arm_insn, 8, 9);
12055       opcode3 = bits (thumb_insn_r->arm_insn, 0, 2);
12056       if ((3 == opcode2) && (!opcode3))
12057         {
12058           /* Branch with exchange.  */
12059           record_buf[0] = ARM_PS_REGNUM;
12060           thumb_insn_r->reg_rec_count = 1;
12061         }
12062       else
12063         {
12064           /* Format 8; special data processing insns.  */
12065           reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12066           record_buf[0] = ARM_PS_REGNUM;
12067           record_buf[1] = reg_src1;
12068           thumb_insn_r->reg_rec_count = 2;
12069         }
12070     }
12071   else
12072     {
12073       /* Format 5; data processing insns.  */
12074       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12075       if (bit (thumb_insn_r->arm_insn, 7))
12076         {
12077           reg_src1 = reg_src1 + 8;
12078         }
12079       record_buf[0] = ARM_PS_REGNUM;
12080       record_buf[1] = reg_src1;
12081       thumb_insn_r->reg_rec_count = 2;
12082     }
12083
12084   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12085   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12086              record_buf_mem);
12087
12088   return 0;
12089 }
12090
12091 /* Handling opcode 001 insns.  */
12092
12093 static int
12094 thumb_record_ld_st_imm_offset (insn_decode_record *thumb_insn_r)
12095 {
12096   struct regcache *reg_cache = thumb_insn_r->regcache;
12097   uint32_t record_buf[8], record_buf_mem[8];
12098
12099   uint32_t reg_src1 = 0;
12100   uint32_t opcode = 0, immed_5 = 0;
12101
12102   ULONGEST u_regval = 0;
12103
12104   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12105
12106   if (opcode)
12107     {
12108       /* LDR(1).  */
12109       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12110       record_buf[0] = reg_src1;
12111       thumb_insn_r->reg_rec_count = 1;
12112     }
12113   else
12114     {
12115       /* STR(1).  */
12116       reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12117       immed_5 = bits (thumb_insn_r->arm_insn, 6, 10);
12118       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12119       record_buf_mem[0] = 4;
12120       record_buf_mem[1] = u_regval + (immed_5 * 4);
12121       thumb_insn_r->mem_rec_count = 1;
12122     }
12123
12124   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12125   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count, 
12126              record_buf_mem);
12127
12128   return 0;
12129 }
12130
12131 /* Handling opcode 100 insns.  */
12132
12133 static int
12134 thumb_record_ld_st_stack (insn_decode_record *thumb_insn_r)
12135 {
12136   struct regcache *reg_cache = thumb_insn_r->regcache;
12137   uint32_t record_buf[8], record_buf_mem[8];
12138
12139   uint32_t reg_src1 = 0;
12140   uint32_t opcode = 0, immed_8 = 0, immed_5 = 0;
12141
12142   ULONGEST u_regval = 0;
12143
12144   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12145
12146   if (3 == opcode)
12147     {
12148       /* LDR(4).  */
12149       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12150       record_buf[0] = reg_src1;
12151       thumb_insn_r->reg_rec_count = 1;
12152     }
12153   else if (1 == opcode)
12154     {
12155       /* LDRH(1).  */
12156       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12157       record_buf[0] = reg_src1;
12158       thumb_insn_r->reg_rec_count = 1;
12159     }
12160   else if (2 == opcode)
12161     {
12162       /* STR(3).  */
12163       immed_8 = bits (thumb_insn_r->arm_insn, 0, 7);
12164       regcache_raw_read_unsigned (reg_cache, ARM_SP_REGNUM, &u_regval);
12165       record_buf_mem[0] = 4;
12166       record_buf_mem[1] = u_regval + (immed_8 * 4);
12167       thumb_insn_r->mem_rec_count = 1;
12168     }
12169   else if (0 == opcode)
12170     {
12171       /* STRH(1).  */
12172       immed_5 = bits (thumb_insn_r->arm_insn, 6, 10);
12173       reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12174       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12175       record_buf_mem[0] = 2;
12176       record_buf_mem[1] = u_regval + (immed_5 * 2);
12177       thumb_insn_r->mem_rec_count = 1;
12178     }
12179
12180   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12181   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12182              record_buf_mem);
12183
12184   return 0;
12185 }
12186
12187 /* Handling opcode 101 insns.  */
12188
12189 static int
12190 thumb_record_misc (insn_decode_record *thumb_insn_r)
12191 {
12192   struct regcache *reg_cache = thumb_insn_r->regcache;
12193
12194   uint32_t opcode = 0, opcode1 = 0, opcode2 = 0;
12195   uint32_t register_bits = 0, register_count = 0;
12196   uint32_t register_list[8] = {0}, index = 0, start_address = 0;
12197   uint32_t record_buf[24], record_buf_mem[48];
12198   uint32_t reg_src1;
12199
12200   ULONGEST u_regval = 0;
12201
12202   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12203   opcode1 = bits (thumb_insn_r->arm_insn, 8, 12);
12204   opcode2 = bits (thumb_insn_r->arm_insn, 9, 12);
12205
12206   if (14 == opcode2)
12207     {
12208       /* POP.  */
12209       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12210       while (register_bits)
12211       {
12212         if (register_bits & 0x00000001)
12213           record_buf[index++] = register_count;
12214         register_bits = register_bits >> 1;
12215         register_count++;
12216       }
12217       record_buf[index++] = ARM_PS_REGNUM;
12218       record_buf[index++] = ARM_SP_REGNUM;
12219       thumb_insn_r->reg_rec_count = index;
12220     }
12221   else if (10 == opcode2)
12222     {
12223       /* PUSH.  */
12224       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12225       regcache_raw_read_unsigned (reg_cache, ARM_SP_REGNUM, &u_regval);
12226       while (register_bits)
12227         {
12228           if (register_bits & 0x00000001)
12229             register_count++;
12230           register_bits = register_bits >> 1;
12231         }
12232       start_address = u_regval -  \
12233                   (4 * (bit (thumb_insn_r->arm_insn, 8) + register_count));
12234       thumb_insn_r->mem_rec_count = register_count;
12235       while (register_count)
12236         {
12237           record_buf_mem[(register_count * 2) - 1] = start_address;
12238           record_buf_mem[(register_count * 2) - 2] = 4;
12239           start_address = start_address + 4;
12240           register_count--;
12241         }
12242       record_buf[0] = ARM_SP_REGNUM;
12243       thumb_insn_r->reg_rec_count = 1;
12244     }
12245   else if (0x1E == opcode1)
12246     {
12247       /* BKPT insn.  */
12248       /* Handle enhanced software breakpoint insn, BKPT.  */
12249       /* CPSR is changed to be executed in ARM state,  disabling normal
12250          interrupts, entering abort mode.  */
12251       /* According to high vector configuration PC is set.  */
12252       /* User hits breakpoint and type reverse, in that case, we need to go back with 
12253       previous CPSR and Program Counter.  */
12254       record_buf[0] = ARM_PS_REGNUM;
12255       record_buf[1] = ARM_LR_REGNUM;
12256       thumb_insn_r->reg_rec_count = 2;
12257       /* We need to save SPSR value, which is not yet done.  */
12258       printf_unfiltered (_("Process record does not support instruction "
12259                            "0x%0x at address %s.\n"),
12260                            thumb_insn_r->arm_insn,
12261                            paddress (thumb_insn_r->gdbarch,
12262                            thumb_insn_r->this_addr));
12263       return -1;
12264     }
12265   else if ((0 == opcode) || (1 == opcode))
12266     {
12267       /* ADD(5), ADD(6).  */
12268       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12269       record_buf[0] = reg_src1;
12270       thumb_insn_r->reg_rec_count = 1;
12271     }
12272   else if (2 == opcode)
12273     {
12274       /* ADD(7), SUB(4).  */
12275       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12276       record_buf[0] = ARM_SP_REGNUM;
12277       thumb_insn_r->reg_rec_count = 1;
12278     }
12279
12280   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12281   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12282              record_buf_mem);
12283
12284   return 0;
12285 }
12286
12287 /* Handling opcode 110 insns.  */
12288
12289 static int
12290 thumb_record_ldm_stm_swi (insn_decode_record *thumb_insn_r)                
12291 {
12292   struct gdbarch_tdep *tdep = gdbarch_tdep (thumb_insn_r->gdbarch);
12293   struct regcache *reg_cache = thumb_insn_r->regcache;
12294
12295   uint32_t ret = 0; /* function return value: -1:record failure ;  0:success  */
12296   uint32_t reg_src1 = 0;
12297   uint32_t opcode1 = 0, opcode2 = 0, register_bits = 0, register_count = 0;
12298   uint32_t register_list[8] = {0}, index = 0, start_address = 0;
12299   uint32_t record_buf[24], record_buf_mem[48];
12300
12301   ULONGEST u_regval = 0;
12302
12303   opcode1 = bits (thumb_insn_r->arm_insn, 8, 12);
12304   opcode2 = bits (thumb_insn_r->arm_insn, 11, 12);
12305
12306   if (1 == opcode2)
12307     {
12308
12309       /* LDMIA.  */
12310       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12311       /* Get Rn.  */
12312       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12313       while (register_bits)
12314         {
12315           if (register_bits & 0x00000001)
12316             record_buf[index++] = register_count;
12317           register_bits = register_bits >> 1;
12318           register_count++;
12319         }
12320       record_buf[index++] = reg_src1;
12321       thumb_insn_r->reg_rec_count = index;
12322     }
12323   else if (0 == opcode2)
12324     {
12325       /* It handles both STMIA.  */
12326       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12327       /* Get Rn.  */
12328       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12329       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12330       while (register_bits)
12331         {
12332           if (register_bits & 0x00000001)
12333             register_count++;
12334           register_bits = register_bits >> 1;
12335         }
12336       start_address = u_regval;
12337       thumb_insn_r->mem_rec_count = register_count;
12338       while (register_count)
12339         {
12340           record_buf_mem[(register_count * 2) - 1] = start_address;
12341           record_buf_mem[(register_count * 2) - 2] = 4;
12342           start_address = start_address + 4;
12343           register_count--;
12344         }
12345     }
12346   else if (0x1F == opcode1)
12347     {
12348         /* Handle arm syscall insn.  */
12349         if (tdep->arm_syscall_record != NULL)
12350           {
12351             regcache_raw_read_unsigned (reg_cache, 7, &u_regval);
12352             ret = tdep->arm_syscall_record (reg_cache, u_regval);
12353           }
12354         else
12355           {
12356             printf_unfiltered (_("no syscall record support\n"));
12357             return -1;
12358           }
12359     }
12360
12361   /* B (1), conditional branch is automatically taken care in process_record,
12362     as PC is saved there.  */
12363
12364   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12365   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12366              record_buf_mem);
12367
12368   return ret;
12369 }
12370
12371 /* Handling opcode 111 insns.  */
12372
12373 static int
12374 thumb_record_branch (insn_decode_record *thumb_insn_r)
12375 {
12376   uint32_t record_buf[8];
12377   uint32_t bits_h = 0;
12378
12379   bits_h = bits (thumb_insn_r->arm_insn, 11, 12);
12380
12381   if (2 == bits_h || 3 == bits_h)
12382     {
12383       /* BL */
12384       record_buf[0] = ARM_LR_REGNUM;
12385       thumb_insn_r->reg_rec_count = 1;
12386     }
12387   else if (1 == bits_h)
12388     {
12389       /* BLX(1). */
12390       record_buf[0] = ARM_PS_REGNUM;
12391       record_buf[1] = ARM_LR_REGNUM;
12392       thumb_insn_r->reg_rec_count = 2;
12393     }
12394
12395   /* B(2) is automatically taken care in process_record, as PC is 
12396      saved there.  */
12397
12398   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12399
12400   return 0;     
12401 }
12402
12403 /* Handler for thumb2 load/store multiple instructions.  */
12404
12405 static int
12406 thumb2_record_ld_st_multiple (insn_decode_record *thumb2_insn_r)
12407 {
12408   struct regcache *reg_cache = thumb2_insn_r->regcache;
12409
12410   uint32_t reg_rn, op;
12411   uint32_t register_bits = 0, register_count = 0;
12412   uint32_t index = 0, start_address = 0;
12413   uint32_t record_buf[24], record_buf_mem[48];
12414
12415   ULONGEST u_regval = 0;
12416
12417   reg_rn = bits (thumb2_insn_r->arm_insn, 16, 19);
12418   op = bits (thumb2_insn_r->arm_insn, 23, 24);
12419
12420   if (0 == op || 3 == op)
12421     {
12422       if (bit (thumb2_insn_r->arm_insn, INSN_S_L_BIT_NUM))
12423         {
12424           /* Handle RFE instruction.  */
12425           record_buf[0] = ARM_PS_REGNUM;
12426           thumb2_insn_r->reg_rec_count = 1;
12427         }
12428       else
12429         {
12430           /* Handle SRS instruction after reading banked SP.  */
12431           return arm_record_unsupported_insn (thumb2_insn_r);
12432         }
12433     }
12434   else if (1 == op || 2 == op)
12435     {
12436       if (bit (thumb2_insn_r->arm_insn, INSN_S_L_BIT_NUM))
12437         {
12438           /* Handle LDM/LDMIA/LDMFD and LDMDB/LDMEA instructions.  */
12439           register_bits = bits (thumb2_insn_r->arm_insn, 0, 15);
12440           while (register_bits)
12441             {
12442               if (register_bits & 0x00000001)
12443                 record_buf[index++] = register_count;
12444
12445               register_count++;
12446               register_bits = register_bits >> 1;
12447             }
12448           record_buf[index++] = reg_rn;
12449           record_buf[index++] = ARM_PS_REGNUM;
12450           thumb2_insn_r->reg_rec_count = index;
12451         }
12452       else
12453         {
12454           /* Handle STM/STMIA/STMEA and STMDB/STMFD.  */
12455           register_bits = bits (thumb2_insn_r->arm_insn, 0, 15);
12456           regcache_raw_read_unsigned (reg_cache, reg_rn, &u_regval);
12457           while (register_bits)
12458             {
12459               if (register_bits & 0x00000001)
12460                 register_count++;
12461
12462               register_bits = register_bits >> 1;
12463             }
12464
12465           if (1 == op)
12466             {
12467               /* Start address calculation for LDMDB/LDMEA.  */
12468               start_address = u_regval;
12469             }
12470           else if (2 == op)
12471             {
12472               /* Start address calculation for LDMDB/LDMEA.  */
12473               start_address = u_regval - register_count * 4;
12474             }
12475
12476           thumb2_insn_r->mem_rec_count = register_count;
12477           while (register_count)
12478             {
12479               record_buf_mem[register_count * 2 - 1] = start_address;
12480               record_buf_mem[register_count * 2 - 2] = 4;
12481               start_address = start_address + 4;
12482               register_count--;
12483             }
12484           record_buf[0] = reg_rn;
12485           record_buf[1] = ARM_PS_REGNUM;
12486           thumb2_insn_r->reg_rec_count = 2;
12487         }
12488     }
12489
12490   MEM_ALLOC (thumb2_insn_r->arm_mems, thumb2_insn_r->mem_rec_count,
12491             record_buf_mem);
12492   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12493             record_buf);
12494   return ARM_RECORD_SUCCESS;
12495 }
12496
12497 /* Handler for thumb2 load/store (dual/exclusive) and table branch
12498    instructions.  */
12499
12500 static int
12501 thumb2_record_ld_st_dual_ex_tbb (insn_decode_record *thumb2_insn_r)
12502 {
12503   struct regcache *reg_cache = thumb2_insn_r->regcache;
12504
12505   uint32_t reg_rd, reg_rn, offset_imm;
12506   uint32_t reg_dest1, reg_dest2;
12507   uint32_t address, offset_addr;
12508   uint32_t record_buf[8], record_buf_mem[8];
12509   uint32_t op1, op2, op3;
12510   LONGEST s_word;
12511
12512   ULONGEST u_regval[2];
12513
12514   op1 = bits (thumb2_insn_r->arm_insn, 23, 24);
12515   op2 = bits (thumb2_insn_r->arm_insn, 20, 21);
12516   op3 = bits (thumb2_insn_r->arm_insn, 4, 7);
12517
12518   if (bit (thumb2_insn_r->arm_insn, INSN_S_L_BIT_NUM))
12519     {
12520       if(!(1 == op1 && 1 == op2 && (0 == op3 || 1 == op3)))
12521         {
12522           reg_dest1 = bits (thumb2_insn_r->arm_insn, 12, 15);
12523           record_buf[0] = reg_dest1;
12524           record_buf[1] = ARM_PS_REGNUM;
12525           thumb2_insn_r->reg_rec_count = 2;
12526         }
12527
12528       if (3 == op2 || (op1 & 2) || (1 == op1 && 1 == op2 && 7 == op3))
12529         {
12530           reg_dest2 = bits (thumb2_insn_r->arm_insn, 8, 11);
12531           record_buf[2] = reg_dest2;
12532           thumb2_insn_r->reg_rec_count = 3;
12533         }
12534     }
12535   else
12536     {
12537       reg_rn = bits (thumb2_insn_r->arm_insn, 16, 19);
12538       regcache_raw_read_unsigned (reg_cache, reg_rn, &u_regval[0]);
12539
12540       if (0 == op1 && 0 == op2)
12541         {
12542           /* Handle STREX.  */
12543           offset_imm = bits (thumb2_insn_r->arm_insn, 0, 7);
12544           address = u_regval[0] + (offset_imm * 4);
12545           record_buf_mem[0] = 4;
12546           record_buf_mem[1] = address;
12547           thumb2_insn_r->mem_rec_count = 1;
12548           reg_rd = bits (thumb2_insn_r->arm_insn, 0, 3);
12549           record_buf[0] = reg_rd;
12550           thumb2_insn_r->reg_rec_count = 1;
12551         }
12552       else if (1 == op1 && 0 == op2)
12553         {
12554           reg_rd = bits (thumb2_insn_r->arm_insn, 0, 3);
12555           record_buf[0] = reg_rd;
12556           thumb2_insn_r->reg_rec_count = 1;
12557           address = u_regval[0];
12558           record_buf_mem[1] = address;
12559
12560           if (4 == op3)
12561             {
12562               /* Handle STREXB.  */
12563               record_buf_mem[0] = 1;
12564               thumb2_insn_r->mem_rec_count = 1;
12565             }
12566           else if (5 == op3)
12567             {
12568               /* Handle STREXH.  */
12569               record_buf_mem[0] = 2 ;
12570               thumb2_insn_r->mem_rec_count = 1;
12571             }
12572           else if (7 == op3)
12573             {
12574               /* Handle STREXD.  */
12575               address = u_regval[0];
12576               record_buf_mem[0] = 4;
12577               record_buf_mem[2] = 4;
12578               record_buf_mem[3] = address + 4;
12579               thumb2_insn_r->mem_rec_count = 2;
12580             }
12581         }
12582       else
12583         {
12584           offset_imm = bits (thumb2_insn_r->arm_insn, 0, 7);
12585
12586           if (bit (thumb2_insn_r->arm_insn, 24))
12587             {
12588               if (bit (thumb2_insn_r->arm_insn, 23))
12589                 offset_addr = u_regval[0] + (offset_imm * 4);
12590               else
12591                 offset_addr = u_regval[0] - (offset_imm * 4);
12592
12593               address = offset_addr;
12594             }
12595           else
12596             address = u_regval[0];
12597
12598           record_buf_mem[0] = 4;
12599           record_buf_mem[1] = address;
12600           record_buf_mem[2] = 4;
12601           record_buf_mem[3] = address + 4;
12602           thumb2_insn_r->mem_rec_count = 2;
12603           record_buf[0] = reg_rn;
12604           thumb2_insn_r->reg_rec_count = 1;
12605         }
12606     }
12607
12608   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12609             record_buf);
12610   MEM_ALLOC (thumb2_insn_r->arm_mems, thumb2_insn_r->mem_rec_count,
12611             record_buf_mem);
12612   return ARM_RECORD_SUCCESS;
12613 }
12614
12615 /* Handler for thumb2 data processing (shift register and modified immediate)
12616    instructions.  */
12617
12618 static int
12619 thumb2_record_data_proc_sreg_mimm (insn_decode_record *thumb2_insn_r)
12620 {
12621   uint32_t reg_rd, op;
12622   uint32_t record_buf[8];
12623
12624   op = bits (thumb2_insn_r->arm_insn, 21, 24);
12625   reg_rd = bits (thumb2_insn_r->arm_insn, 8, 11);
12626
12627   if ((0 == op || 4 == op || 8 == op || 13 == op) && 15 == reg_rd)
12628     {
12629       record_buf[0] = ARM_PS_REGNUM;
12630       thumb2_insn_r->reg_rec_count = 1;
12631     }
12632   else
12633     {
12634       record_buf[0] = reg_rd;
12635       record_buf[1] = ARM_PS_REGNUM;
12636       thumb2_insn_r->reg_rec_count = 2;
12637     }
12638
12639   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12640             record_buf);
12641   return ARM_RECORD_SUCCESS;
12642 }
12643
12644 /* Generic handler for thumb2 instructions which effect destination and PS
12645    registers.  */
12646
12647 static int
12648 thumb2_record_ps_dest_generic (insn_decode_record *thumb2_insn_r)
12649 {
12650   uint32_t reg_rd;
12651   uint32_t record_buf[8];
12652
12653   reg_rd = bits (thumb2_insn_r->arm_insn, 8, 11);
12654
12655   record_buf[0] = reg_rd;
12656   record_buf[1] = ARM_PS_REGNUM;
12657   thumb2_insn_r->reg_rec_count = 2;
12658
12659   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12660             record_buf);
12661   return ARM_RECORD_SUCCESS;
12662 }
12663
12664 /* Handler for thumb2 branch and miscellaneous control instructions.  */
12665
12666 static int
12667 thumb2_record_branch_misc_cntrl (insn_decode_record *thumb2_insn_r)
12668 {
12669   uint32_t op, op1, op2;
12670   uint32_t record_buf[8];
12671
12672   op = bits (thumb2_insn_r->arm_insn, 20, 26);
12673   op1 = bits (thumb2_insn_r->arm_insn, 12, 14);
12674   op2 = bits (thumb2_insn_r->arm_insn, 8, 11);
12675
12676   /* Handle MSR insn.  */
12677   if (!(op1 & 0x2) && 0x38 == op)
12678     {
12679       if (!(op2 & 0x3))
12680         {
12681           /* CPSR is going to be changed.  */
12682           record_buf[0] = ARM_PS_REGNUM;
12683           thumb2_insn_r->reg_rec_count = 1;
12684         }
12685       else
12686         {
12687           arm_record_unsupported_insn(thumb2_insn_r);
12688           return -1;
12689         }
12690     }
12691   else if (4 == (op1 & 0x5) || 5 == (op1 & 0x5))
12692     {
12693       /* BLX.  */
12694       record_buf[0] = ARM_PS_REGNUM;
12695       record_buf[1] = ARM_LR_REGNUM;
12696       thumb2_insn_r->reg_rec_count = 2;
12697     }
12698
12699   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12700             record_buf);
12701   return ARM_RECORD_SUCCESS;
12702 }
12703
12704 /* Handler for thumb2 store single data item instructions.  */
12705
12706 static int
12707 thumb2_record_str_single_data (insn_decode_record *thumb2_insn_r)
12708 {
12709   struct regcache *reg_cache = thumb2_insn_r->regcache;
12710
12711   uint32_t reg_rn, reg_rm, offset_imm, shift_imm;
12712   uint32_t address, offset_addr;
12713   uint32_t record_buf[8], record_buf_mem[8];
12714   uint32_t op1, op2;
12715
12716   ULONGEST u_regval[2];
12717
12718   op1 = bits (thumb2_insn_r->arm_insn, 21, 23);
12719   op2 = bits (thumb2_insn_r->arm_insn, 6, 11);
12720   reg_rn = bits (thumb2_insn_r->arm_insn, 16, 19);
12721   regcache_raw_read_unsigned (reg_cache, reg_rn, &u_regval[0]);
12722
12723   if (bit (thumb2_insn_r->arm_insn, 23))
12724     {
12725       /* T2 encoding.  */
12726       offset_imm = bits (thumb2_insn_r->arm_insn, 0, 11);
12727       offset_addr = u_regval[0] + offset_imm;
12728       address = offset_addr;
12729     }
12730   else
12731     {
12732       /* T3 encoding.  */
12733       if ((0 == op1 || 1 == op1 || 2 == op1) && !(op2 & 0x20))
12734         {
12735           /* Handle STRB (register).  */
12736           reg_rm = bits (thumb2_insn_r->arm_insn, 0, 3);
12737           regcache_raw_read_unsigned (reg_cache, reg_rm, &u_regval[1]);
12738           shift_imm = bits (thumb2_insn_r->arm_insn, 4, 5);
12739           offset_addr = u_regval[1] << shift_imm;
12740           address = u_regval[0] + offset_addr;
12741         }
12742       else
12743         {
12744           offset_imm = bits (thumb2_insn_r->arm_insn, 0, 7);
12745           if (bit (thumb2_insn_r->arm_insn, 10))
12746             {
12747               if (bit (thumb2_insn_r->arm_insn, 9))
12748                 offset_addr = u_regval[0] + offset_imm;
12749               else
12750                 offset_addr = u_regval[0] - offset_imm;
12751
12752               address = offset_addr;
12753             }
12754           else
12755             address = u_regval[0];
12756         }
12757     }
12758
12759   switch (op1)
12760     {
12761       /* Store byte instructions.  */
12762       case 4:
12763       case 0:
12764         record_buf_mem[0] = 1;
12765         break;
12766       /* Store half word instructions.  */
12767       case 1:
12768       case 5:
12769         record_buf_mem[0] = 2;
12770         break;
12771       /* Store word instructions.  */
12772       case 2:
12773       case 6:
12774         record_buf_mem[0] = 4;
12775         break;
12776
12777       default:
12778         gdb_assert_not_reached ("no decoding pattern found");
12779         break;
12780     }
12781
12782   record_buf_mem[1] = address;
12783   thumb2_insn_r->mem_rec_count = 1;
12784   record_buf[0] = reg_rn;
12785   thumb2_insn_r->reg_rec_count = 1;
12786
12787   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12788             record_buf);
12789   MEM_ALLOC (thumb2_insn_r->arm_mems, thumb2_insn_r->mem_rec_count,
12790             record_buf_mem);
12791   return ARM_RECORD_SUCCESS;
12792 }
12793
12794 /* Handler for thumb2 load memory hints instructions.  */
12795
12796 static int
12797 thumb2_record_ld_mem_hints (insn_decode_record *thumb2_insn_r)
12798 {
12799   uint32_t record_buf[8];
12800   uint32_t reg_rt, reg_rn;
12801
12802   reg_rt = bits (thumb2_insn_r->arm_insn, 12, 15);
12803   reg_rn = bits (thumb2_insn_r->arm_insn, 16, 19);
12804
12805   if (ARM_PC_REGNUM != reg_rt)
12806     {
12807       record_buf[0] = reg_rt;
12808       record_buf[1] = reg_rn;
12809       record_buf[2] = ARM_PS_REGNUM;
12810       thumb2_insn_r->reg_rec_count = 3;
12811
12812       REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12813                 record_buf);
12814       return ARM_RECORD_SUCCESS;
12815     }
12816
12817   return ARM_RECORD_FAILURE;
12818 }
12819
12820 /* Handler for thumb2 load word instructions.  */
12821
12822 static int
12823 thumb2_record_ld_word (insn_decode_record *thumb2_insn_r)
12824 {
12825   uint32_t opcode1 = 0, opcode2 = 0;
12826   uint32_t record_buf[8];
12827
12828   record_buf[0] = bits (thumb2_insn_r->arm_insn, 12, 15);
12829   record_buf[1] = ARM_PS_REGNUM;
12830   thumb2_insn_r->reg_rec_count = 2;
12831
12832   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12833             record_buf);
12834   return ARM_RECORD_SUCCESS;
12835 }
12836
12837 /* Handler for thumb2 long multiply, long multiply accumulate, and
12838    divide instructions.  */
12839
12840 static int
12841 thumb2_record_lmul_lmla_div (insn_decode_record *thumb2_insn_r)
12842 {
12843   uint32_t opcode1 = 0, opcode2 = 0;
12844   uint32_t record_buf[8];
12845   uint32_t reg_src1 = 0;
12846
12847   opcode1 = bits (thumb2_insn_r->arm_insn, 20, 22);
12848   opcode2 = bits (thumb2_insn_r->arm_insn, 4, 7);
12849
12850   if (0 == opcode1 || 2 == opcode1 || (opcode1 >= 4 && opcode1 <= 6))
12851     {
12852       /* Handle SMULL, UMULL, SMULAL.  */
12853       /* Handle SMLAL(S), SMULL(S), UMLAL(S), UMULL(S).  */
12854       record_buf[0] = bits (thumb2_insn_r->arm_insn, 16, 19);
12855       record_buf[1] = bits (thumb2_insn_r->arm_insn, 12, 15);
12856       record_buf[2] = ARM_PS_REGNUM;
12857       thumb2_insn_r->reg_rec_count = 3;
12858     }
12859   else if (1 == opcode1 || 3 == opcode2)
12860     {
12861       /* Handle SDIV and UDIV.  */
12862       record_buf[0] = bits (thumb2_insn_r->arm_insn, 16, 19);
12863       record_buf[1] = bits (thumb2_insn_r->arm_insn, 12, 15);
12864       record_buf[2] = ARM_PS_REGNUM;
12865       thumb2_insn_r->reg_rec_count = 3;
12866     }
12867   else
12868     return ARM_RECORD_FAILURE;
12869
12870   REG_ALLOC (thumb2_insn_r->arm_regs, thumb2_insn_r->reg_rec_count,
12871             record_buf);
12872   return ARM_RECORD_SUCCESS;
12873 }
12874
12875 /* Decodes thumb2 instruction type and invokes its record handler.  */
12876
12877 static unsigned int
12878 thumb2_record_decode_insn_handler (insn_decode_record *thumb2_insn_r)
12879 {
12880   uint32_t op, op1, op2;
12881
12882   op = bit (thumb2_insn_r->arm_insn, 15);
12883   op1 = bits (thumb2_insn_r->arm_insn, 27, 28);
12884   op2 = bits (thumb2_insn_r->arm_insn, 20, 26);
12885
12886   if (op1 == 0x01)
12887     {
12888       if (!(op2 & 0x64 ))
12889         {
12890           /* Load/store multiple instruction.  */
12891           return thumb2_record_ld_st_multiple (thumb2_insn_r);
12892         }
12893       else if (!((op2 & 0x64) ^ 0x04))
12894         {
12895           /* Load/store (dual/exclusive) and table branch instruction.  */
12896           return thumb2_record_ld_st_dual_ex_tbb (thumb2_insn_r);
12897         }
12898       else if (!((op2 & 0x20) ^ 0x20))
12899         {
12900           /* Data-processing (shifted register).  */
12901           return thumb2_record_data_proc_sreg_mimm (thumb2_insn_r);
12902         }
12903       else if (op2 & 0x40)
12904         {
12905           /* Co-processor instructions.  */
12906           arm_record_unsupported_insn (thumb2_insn_r);
12907         }
12908     }
12909   else if (op1 == 0x02)
12910     {
12911       if (op)
12912         {
12913           /* Branches and miscellaneous control instructions.  */
12914           return thumb2_record_branch_misc_cntrl (thumb2_insn_r);
12915         }
12916       else if (op2 & 0x20)
12917         {
12918           /* Data-processing (plain binary immediate) instruction.  */
12919           return thumb2_record_ps_dest_generic (thumb2_insn_r);
12920         }
12921       else
12922         {
12923           /* Data-processing (modified immediate).  */
12924           return thumb2_record_data_proc_sreg_mimm (thumb2_insn_r);
12925         }
12926     }
12927   else if (op1 == 0x03)
12928     {
12929       if (!(op2 & 0x71 ))
12930         {
12931           /* Store single data item.  */
12932           return thumb2_record_str_single_data (thumb2_insn_r);
12933         }
12934       else if (!((op2 & 0x71) ^ 0x10))
12935         {
12936           /* Advanced SIMD or structure load/store instructions.  */
12937           return arm_record_unsupported_insn (thumb2_insn_r);
12938         }
12939       else if (!((op2 & 0x67) ^ 0x01))
12940         {
12941           /* Load byte, memory hints instruction.  */
12942           return thumb2_record_ld_mem_hints (thumb2_insn_r);
12943         }
12944       else if (!((op2 & 0x67) ^ 0x03))
12945         {
12946           /* Load halfword, memory hints instruction.  */
12947           return thumb2_record_ld_mem_hints (thumb2_insn_r);
12948         }
12949       else if (!((op2 & 0x67) ^ 0x05))
12950         {
12951           /* Load word instruction.  */
12952           return thumb2_record_ld_word (thumb2_insn_r);
12953         }
12954       else if (!((op2 & 0x70) ^ 0x20))
12955         {
12956           /* Data-processing (register) instruction.  */
12957           return thumb2_record_ps_dest_generic (thumb2_insn_r);
12958         }
12959       else if (!((op2 & 0x78) ^ 0x30))
12960         {
12961           /* Multiply, multiply accumulate, abs diff instruction.  */
12962           return thumb2_record_ps_dest_generic (thumb2_insn_r);
12963         }
12964       else if (!((op2 & 0x78) ^ 0x38))
12965         {
12966           /* Long multiply, long multiply accumulate, and divide.  */
12967           return thumb2_record_lmul_lmla_div (thumb2_insn_r);
12968         }
12969       else if (op2 & 0x40)
12970         {
12971           /* Co-processor instructions.  */
12972           return arm_record_unsupported_insn (thumb2_insn_r);
12973         }
12974    }
12975
12976   return -1;
12977 }
12978
12979 /* Extracts arm/thumb/thumb2 insn depending on the size, and returns 0 on success 
12980 and positive val on fauilure.  */
12981
12982 static int
12983 extract_arm_insn (insn_decode_record *insn_record, uint32_t insn_size)
12984 {
12985   gdb_byte buf[insn_size];
12986
12987   memset (&buf[0], 0, insn_size);
12988   
12989   if (target_read_memory (insn_record->this_addr, &buf[0], insn_size))
12990     return 1;
12991   insn_record->arm_insn = (uint32_t) extract_unsigned_integer (&buf[0],
12992                            insn_size, 
12993                            gdbarch_byte_order (insn_record->gdbarch));
12994   return 0;
12995 }
12996
12997 typedef int (*sti_arm_hdl_fp_t) (insn_decode_record*);
12998
12999 /* Decode arm/thumb insn depending on condition cods and opcodes; and
13000    dispatch it.  */
13001
13002 static int
13003 decode_insn (insn_decode_record *arm_record, record_type_t record_type,
13004                 uint32_t insn_size)
13005 {
13006
13007   /* (Starting from numerical 0); bits 25, 26, 27 decodes type of arm instruction.  */
13008   static const sti_arm_hdl_fp_t const arm_handle_insn[8] =                    
13009   {
13010     arm_record_data_proc_misc_ld_str,   /* 000.  */
13011     arm_record_data_proc_imm,           /* 001.  */
13012     arm_record_ld_st_imm_offset,        /* 010.  */
13013     arm_record_ld_st_reg_offset,        /* 011.  */
13014     arm_record_ld_st_multiple,          /* 100.  */
13015     arm_record_b_bl,                    /* 101.  */
13016     arm_record_unsupported_insn,        /* 110.  */
13017     arm_record_coproc_data_proc         /* 111.  */
13018   };
13019
13020   /* (Starting from numerical 0); bits 13,14,15 decodes type of thumb instruction.  */
13021   static const sti_arm_hdl_fp_t const thumb_handle_insn[8] =
13022   { \
13023     thumb_record_shift_add_sub,        /* 000.  */
13024     thumb_record_add_sub_cmp_mov,      /* 001.  */
13025     thumb_record_ld_st_reg_offset,     /* 010.  */
13026     thumb_record_ld_st_imm_offset,     /* 011.  */
13027     thumb_record_ld_st_stack,          /* 100.  */
13028     thumb_record_misc,                 /* 101.  */
13029     thumb_record_ldm_stm_swi,          /* 110.  */
13030     thumb_record_branch                /* 111.  */
13031   };
13032
13033   uint32_t ret = 0;    /* return value: negative:failure   0:success.  */
13034   uint32_t insn_id = 0;
13035
13036   if (extract_arm_insn (arm_record, insn_size))
13037     {
13038       if (record_debug)
13039         {
13040           printf_unfiltered (_("Process record: error reading memory at "
13041                               "addr %s len = %d.\n"),
13042           paddress (arm_record->gdbarch, arm_record->this_addr), insn_size);        
13043         }
13044       return -1;
13045     }
13046   else if (ARM_RECORD == record_type)
13047     {
13048       arm_record->cond = bits (arm_record->arm_insn, 28, 31);
13049       insn_id = bits (arm_record->arm_insn, 25, 27);
13050       ret = arm_record_extension_space (arm_record);
13051       /* If this insn has fallen into extension space 
13052          then we need not decode it anymore.  */
13053       if (ret != -1 && !INSN_RECORDED(arm_record))
13054         {
13055           ret = arm_handle_insn[insn_id] (arm_record);
13056         }
13057     }
13058   else if (THUMB_RECORD == record_type)
13059     {
13060       /* As thumb does not have condition codes, we set negative.  */
13061       arm_record->cond = -1;
13062       insn_id = bits (arm_record->arm_insn, 13, 15);
13063       ret = thumb_handle_insn[insn_id] (arm_record);
13064     }
13065   else if (THUMB2_RECORD == record_type)
13066     {
13067       /* As thumb does not have condition codes, we set negative.  */
13068       arm_record->cond = -1;
13069
13070       /* Swap first half of 32bit thumb instruction with second half.  */
13071       arm_record->arm_insn
13072         = (arm_record->arm_insn >> 16) | (arm_record->arm_insn << 16);
13073
13074       insn_id = thumb2_record_decode_insn_handler (arm_record);
13075
13076       if (insn_id != ARM_RECORD_SUCCESS)
13077         {
13078           arm_record_unsupported_insn (arm_record);
13079           ret = -1;
13080         }
13081     }
13082   else
13083     {
13084       /* Throw assertion.  */
13085       gdb_assert_not_reached ("not a valid instruction, could not decode");
13086     }
13087
13088   return ret;
13089 }
13090
13091
13092 /* Cleans up local record registers and memory allocations.  */
13093
13094 static void 
13095 deallocate_reg_mem (insn_decode_record *record)
13096 {
13097   xfree (record->arm_regs);
13098   xfree (record->arm_mems);    
13099 }
13100
13101
13102 /* Parse the current instruction and record the values of the registers and    
13103    memory that will be changed in current instruction to record_arch_list".
13104    Return -1 if something is wrong.  */
13105
13106 int
13107 arm_process_record (struct gdbarch *gdbarch, struct regcache *regcache, 
13108                         CORE_ADDR insn_addr)
13109 {
13110
13111   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
13112   uint32_t no_of_rec = 0;
13113   uint32_t ret = 0;  /* return value: -1:record failure ;  0:success  */
13114   ULONGEST t_bit = 0, insn_id = 0;
13115
13116   ULONGEST u_regval = 0;
13117
13118   insn_decode_record arm_record;
13119
13120   memset (&arm_record, 0, sizeof (insn_decode_record));
13121   arm_record.regcache = regcache;
13122   arm_record.this_addr = insn_addr;
13123   arm_record.gdbarch = gdbarch;
13124
13125
13126   if (record_debug > 1)
13127     {
13128       fprintf_unfiltered (gdb_stdlog, "Process record: arm_process_record "
13129                                       "addr = %s\n",
13130       paddress (gdbarch, arm_record.this_addr));
13131     }
13132
13133   if (extract_arm_insn (&arm_record, 2))
13134     {
13135       if (record_debug)
13136         {
13137           printf_unfiltered (_("Process record: error reading memory at "
13138                              "addr %s len = %d.\n"),
13139                              paddress (arm_record.gdbarch, 
13140                              arm_record.this_addr), 2);
13141         }
13142       return -1;
13143     }
13144
13145   /* Check the insn, whether it is thumb or arm one.  */
13146
13147   t_bit = arm_psr_thumb_bit (arm_record.gdbarch);
13148   regcache_raw_read_unsigned (arm_record.regcache, ARM_PS_REGNUM, &u_regval);
13149
13150
13151   if (!(u_regval & t_bit))
13152     {
13153       /* We are decoding arm insn.  */
13154       ret = decode_insn (&arm_record, ARM_RECORD, ARM_INSN_SIZE_BYTES);
13155     }
13156   else
13157     {
13158       insn_id = bits (arm_record.arm_insn, 11, 15);
13159       /* is it thumb2 insn?  */
13160       if ((0x1D == insn_id) || (0x1E == insn_id) || (0x1F == insn_id))
13161         {
13162           ret = decode_insn (&arm_record, THUMB2_RECORD, 
13163                              THUMB2_INSN_SIZE_BYTES);
13164         }
13165       else
13166         {
13167           /* We are decoding thumb insn.  */
13168           ret = decode_insn (&arm_record, THUMB_RECORD, THUMB_INSN_SIZE_BYTES);
13169         }
13170     }
13171
13172   if (0 == ret)
13173     {
13174       /* Record registers.  */
13175       record_full_arch_list_add_reg (arm_record.regcache, ARM_PC_REGNUM);
13176       if (arm_record.arm_regs)
13177         {
13178           for (no_of_rec = 0; no_of_rec < arm_record.reg_rec_count; no_of_rec++)
13179             {
13180               if (record_full_arch_list_add_reg
13181                   (arm_record.regcache , arm_record.arm_regs[no_of_rec]))
13182               ret = -1;
13183             }
13184         }
13185       /* Record memories.  */
13186       if (arm_record.arm_mems)
13187         {
13188           for (no_of_rec = 0; no_of_rec < arm_record.mem_rec_count; no_of_rec++)
13189             {
13190               if (record_full_arch_list_add_mem
13191                   ((CORE_ADDR)arm_record.arm_mems[no_of_rec].addr,
13192                    arm_record.arm_mems[no_of_rec].len))
13193                 ret = -1;
13194             }
13195         }
13196
13197       if (record_full_arch_list_add_end ())
13198         ret = -1;
13199     }
13200
13201
13202   deallocate_reg_mem (&arm_record);
13203
13204   return ret;
13205 }
13206