gdb/
[external/binutils.git] / gdb / arm-tdep.c
1 /* Common target dependent code for GDB on ARM systems.
2
3    Copyright (C) 1988-1989, 1991-1993, 1995-1996, 1998-2012 Free
4    Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22
23 #include <ctype.h>              /* XXX for isupper ().  */
24
25 #include "frame.h"
26 #include "inferior.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include "gdb_string.h"
30 #include "dis-asm.h"            /* For register styles.  */
31 #include "regcache.h"
32 #include "reggroups.h"
33 #include "doublest.h"
34 #include "value.h"
35 #include "arch-utils.h"
36 #include "osabi.h"
37 #include "frame-unwind.h"
38 #include "frame-base.h"
39 #include "trad-frame.h"
40 #include "objfiles.h"
41 #include "dwarf2-frame.h"
42 #include "gdbtypes.h"
43 #include "prologue-value.h"
44 #include "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
61 #include "features/arm-with-m.c"
62 #include "features/arm-with-m-fpa-layout.c"
63 #include "features/arm-with-m-vfp-d16.c"
64 #include "features/arm-with-iwmmxt.c"
65 #include "features/arm-with-vfpv2.c"
66 #include "features/arm-with-vfpv3.c"
67 #include "features/arm-with-neon.c"
68
69 static int arm_debug;
70
71 /* Macros for setting and testing a bit in a minimal symbol that marks
72    it as Thumb function.  The MSB of the minimal symbol's "info" field
73    is used for this purpose.
74
75    MSYMBOL_SET_SPECIAL  Actually sets the "special" bit.
76    MSYMBOL_IS_SPECIAL   Tests the "special" bit in a minimal symbol.  */
77
78 #define MSYMBOL_SET_SPECIAL(msym)                               \
79         MSYMBOL_TARGET_FLAG_1 (msym) = 1
80
81 #define MSYMBOL_IS_SPECIAL(msym)                                \
82         MSYMBOL_TARGET_FLAG_1 (msym)
83
84 /* Per-objfile data used for mapping symbols.  */
85 static const struct objfile_data *arm_objfile_data_key;
86
87 struct arm_mapping_symbol
88 {
89   bfd_vma value;
90   char type;
91 };
92 typedef struct arm_mapping_symbol arm_mapping_symbol_s;
93 DEF_VEC_O(arm_mapping_symbol_s);
94
95 struct arm_per_objfile
96 {
97   VEC(arm_mapping_symbol_s) **section_maps;
98 };
99
100 /* The list of available "set arm ..." and "show arm ..." commands.  */
101 static struct cmd_list_element *setarmcmdlist = NULL;
102 static struct cmd_list_element *showarmcmdlist = NULL;
103
104 /* The type of floating-point to use.  Keep this in sync with enum
105    arm_float_model, and the help string in _initialize_arm_tdep.  */
106 static const char *const fp_model_strings[] =
107 {
108   "auto",
109   "softfpa",
110   "fpa",
111   "softvfp",
112   "vfp",
113   NULL
114 };
115
116 /* A variable that can be configured by the user.  */
117 static enum arm_float_model arm_fp_model = ARM_FLOAT_AUTO;
118 static const char *current_fp_model = "auto";
119
120 /* The ABI to use.  Keep this in sync with arm_abi_kind.  */
121 static const char *const arm_abi_strings[] =
122 {
123   "auto",
124   "APCS",
125   "AAPCS",
126   NULL
127 };
128
129 /* A variable that can be configured by the user.  */
130 static enum arm_abi_kind arm_abi_global = ARM_ABI_AUTO;
131 static const char *arm_abi_string = "auto";
132
133 /* The execution mode to assume.  */
134 static const char *const arm_mode_strings[] =
135   {
136     "auto",
137     "arm",
138     "thumb",
139     NULL
140   };
141
142 static const char *arm_fallback_mode_string = "auto";
143 static const char *arm_force_mode_string = "auto";
144
145 /* Internal override of the execution mode.  -1 means no override,
146    0 means override to ARM mode, 1 means override to Thumb mode.
147    The effect is the same as if arm_force_mode has been set by the
148    user (except the internal override has precedence over a user's
149    arm_force_mode override).  */
150 static int arm_override_mode = -1;
151
152 /* Number of different reg name sets (options).  */
153 static int num_disassembly_options;
154
155 /* The standard register names, and all the valid aliases for them.  Note
156    that `fp', `sp' and `pc' are not added in this alias list, because they
157    have been added as builtin user registers in
158    std-regs.c:_initialize_frame_reg.  */
159 static const struct
160 {
161   const char *name;
162   int regnum;
163 } arm_register_aliases[] = {
164   /* Basic register numbers.  */
165   { "r0", 0 },
166   { "r1", 1 },
167   { "r2", 2 },
168   { "r3", 3 },
169   { "r4", 4 },
170   { "r5", 5 },
171   { "r6", 6 },
172   { "r7", 7 },
173   { "r8", 8 },
174   { "r9", 9 },
175   { "r10", 10 },
176   { "r11", 11 },
177   { "r12", 12 },
178   { "r13", 13 },
179   { "r14", 14 },
180   { "r15", 15 },
181   /* Synonyms (argument and variable registers).  */
182   { "a1", 0 },
183   { "a2", 1 },
184   { "a3", 2 },
185   { "a4", 3 },
186   { "v1", 4 },
187   { "v2", 5 },
188   { "v3", 6 },
189   { "v4", 7 },
190   { "v5", 8 },
191   { "v6", 9 },
192   { "v7", 10 },
193   { "v8", 11 },
194   /* Other platform-specific names for r9.  */
195   { "sb", 9 },
196   { "tr", 9 },
197   /* Special names.  */
198   { "ip", 12 },
199   { "lr", 14 },
200   /* Names used by GCC (not listed in the ARM EABI).  */
201   { "sl", 10 },
202   /* A special name from the older ATPCS.  */
203   { "wr", 7 },
204 };
205
206 static const char *const arm_register_names[] =
207 {"r0",  "r1",  "r2",  "r3",     /*  0  1  2  3 */
208  "r4",  "r5",  "r6",  "r7",     /*  4  5  6  7 */
209  "r8",  "r9",  "r10", "r11",    /*  8  9 10 11 */
210  "r12", "sp",  "lr",  "pc",     /* 12 13 14 15 */
211  "f0",  "f1",  "f2",  "f3",     /* 16 17 18 19 */
212  "f4",  "f5",  "f6",  "f7",     /* 20 21 22 23 */
213  "fps", "cpsr" };               /* 24 25       */
214
215 /* Valid register name styles.  */
216 static const char **valid_disassembly_styles;
217
218 /* Disassembly style to use. Default to "std" register names.  */
219 static const char *disassembly_style;
220
221 /* This is used to keep the bfd arch_info in sync with the disassembly
222    style.  */
223 static void set_disassembly_style_sfunc(char *, int,
224                                          struct cmd_list_element *);
225 static void set_disassembly_style (void);
226
227 static void convert_from_extended (const struct floatformat *, const void *,
228                                    void *, int);
229 static void convert_to_extended (const struct floatformat *, void *,
230                                  const void *, int);
231
232 static enum register_status arm_neon_quad_read (struct gdbarch *gdbarch,
233                                                 struct regcache *regcache,
234                                                 int regnum, gdb_byte *buf);
235 static void arm_neon_quad_write (struct gdbarch *gdbarch,
236                                  struct regcache *regcache,
237                                  int regnum, const gdb_byte *buf);
238
239 static int thumb_insn_size (unsigned short inst1);
240
241 struct arm_prologue_cache
242 {
243   /* The stack pointer at the time this frame was created; i.e. the
244      caller's stack pointer when this function was called.  It is used
245      to identify this frame.  */
246   CORE_ADDR prev_sp;
247
248   /* The frame base for this frame is just prev_sp - frame size.
249      FRAMESIZE is the distance from the frame pointer to the
250      initial stack pointer.  */
251
252   int framesize;
253
254   /* The register used to hold the frame pointer for this frame.  */
255   int framereg;
256
257   /* Saved register offsets.  */
258   struct trad_frame_saved_reg *saved_regs;
259 };
260
261 static CORE_ADDR arm_analyze_prologue (struct gdbarch *gdbarch,
262                                        CORE_ADDR prologue_start,
263                                        CORE_ADDR prologue_end,
264                                        struct arm_prologue_cache *cache);
265
266 /* Architecture version for displaced stepping.  This effects the behaviour of
267    certain instructions, and really should not be hard-wired.  */
268
269 #define DISPLACED_STEPPING_ARCH_VERSION         5
270
271 /* Addresses for calling Thumb functions have the bit 0 set.
272    Here are some macros to test, set, or clear bit 0 of addresses.  */
273 #define IS_THUMB_ADDR(addr)     ((addr) & 1)
274 #define MAKE_THUMB_ADDR(addr)   ((addr) | 1)
275 #define UNMAKE_THUMB_ADDR(addr) ((addr) & ~1)
276
277 /* Set to true if the 32-bit mode is in use.  */
278
279 int arm_apcs_32 = 1;
280
281 /* Return the bit mask in ARM_PS_REGNUM that indicates Thumb mode.  */
282
283 int
284 arm_psr_thumb_bit (struct gdbarch *gdbarch)
285 {
286   if (gdbarch_tdep (gdbarch)->is_m)
287     return XPSR_T;
288   else
289     return CPSR_T;
290 }
291
292 /* Determine if FRAME is executing in Thumb mode.  */
293
294 int
295 arm_frame_is_thumb (struct frame_info *frame)
296 {
297   CORE_ADDR cpsr;
298   ULONGEST t_bit = arm_psr_thumb_bit (get_frame_arch (frame));
299
300   /* Every ARM frame unwinder can unwind the T bit of the CPSR, either
301      directly (from a signal frame or dummy frame) or by interpreting
302      the saved LR (from a prologue or DWARF frame).  So consult it and
303      trust the unwinders.  */
304   cpsr = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
305
306   return (cpsr & t_bit) != 0;
307 }
308
309 /* Callback for VEC_lower_bound.  */
310
311 static inline int
312 arm_compare_mapping_symbols (const struct arm_mapping_symbol *lhs,
313                              const struct arm_mapping_symbol *rhs)
314 {
315   return lhs->value < rhs->value;
316 }
317
318 /* Search for the mapping symbol covering MEMADDR.  If one is found,
319    return its type.  Otherwise, return 0.  If START is non-NULL,
320    set *START to the location of the mapping symbol.  */
321
322 static char
323 arm_find_mapping_symbol (CORE_ADDR memaddr, CORE_ADDR *start)
324 {
325   struct obj_section *sec;
326
327   /* If there are mapping symbols, consult them.  */
328   sec = find_pc_section (memaddr);
329   if (sec != NULL)
330     {
331       struct arm_per_objfile *data;
332       VEC(arm_mapping_symbol_s) *map;
333       struct arm_mapping_symbol map_key = { memaddr - obj_section_addr (sec),
334                                             0 };
335       unsigned int idx;
336
337       data = objfile_data (sec->objfile, arm_objfile_data_key);
338       if (data != NULL)
339         {
340           map = data->section_maps[sec->the_bfd_section->index];
341           if (!VEC_empty (arm_mapping_symbol_s, map))
342             {
343               struct arm_mapping_symbol *map_sym;
344
345               idx = VEC_lower_bound (arm_mapping_symbol_s, map, &map_key,
346                                      arm_compare_mapping_symbols);
347
348               /* VEC_lower_bound finds the earliest ordered insertion
349                  point.  If the following symbol starts at this exact
350                  address, we use that; otherwise, the preceding
351                  mapping symbol covers this address.  */
352               if (idx < VEC_length (arm_mapping_symbol_s, map))
353                 {
354                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx);
355                   if (map_sym->value == map_key.value)
356                     {
357                       if (start)
358                         *start = map_sym->value + obj_section_addr (sec);
359                       return map_sym->type;
360                     }
361                 }
362
363               if (idx > 0)
364                 {
365                   map_sym = VEC_index (arm_mapping_symbol_s, map, idx - 1);
366                   if (start)
367                     *start = map_sym->value + obj_section_addr (sec);
368                   return map_sym->type;
369                 }
370             }
371         }
372     }
373
374   return 0;
375 }
376
377 /* Determine if the program counter specified in MEMADDR is in a Thumb
378    function.  This function should be called for addresses unrelated to
379    any executing frame; otherwise, prefer arm_frame_is_thumb.  */
380
381 int
382 arm_pc_is_thumb (struct gdbarch *gdbarch, CORE_ADDR memaddr)
383 {
384   struct minimal_symbol *sym;
385   char type;
386   struct displaced_step_closure* dsc
387     = get_displaced_step_closure_by_addr(memaddr);
388
389   /* If checking the mode of displaced instruction in copy area, the mode
390      should be determined by instruction on the original address.  */
391   if (dsc)
392     {
393       if (debug_displaced)
394         fprintf_unfiltered (gdb_stdlog,
395                             "displaced: check mode of %.8lx instead of %.8lx\n",
396                             (unsigned long) dsc->insn_addr,
397                             (unsigned long) memaddr);
398       memaddr = dsc->insn_addr;
399     }
400
401   /* If bit 0 of the address is set, assume this is a Thumb address.  */
402   if (IS_THUMB_ADDR (memaddr))
403     return 1;
404
405   /* Respect internal mode override if active.  */
406   if (arm_override_mode != -1)
407     return arm_override_mode;
408
409   /* If the user wants to override the symbol table, let him.  */
410   if (strcmp (arm_force_mode_string, "arm") == 0)
411     return 0;
412   if (strcmp (arm_force_mode_string, "thumb") == 0)
413     return 1;
414
415   /* ARM v6-M and v7-M are always in Thumb mode.  */
416   if (gdbarch_tdep (gdbarch)->is_m)
417     return 1;
418
419   /* If there are mapping symbols, consult them.  */
420   type = arm_find_mapping_symbol (memaddr, NULL);
421   if (type)
422     return type == 't';
423
424   /* Thumb functions have a "special" bit set in minimal symbols.  */
425   sym = lookup_minimal_symbol_by_pc (memaddr);
426   if (sym)
427     return (MSYMBOL_IS_SPECIAL (sym));
428
429   /* If the user wants to override the fallback mode, let them.  */
430   if (strcmp (arm_fallback_mode_string, "arm") == 0)
431     return 0;
432   if (strcmp (arm_fallback_mode_string, "thumb") == 0)
433     return 1;
434
435   /* If we couldn't find any symbol, but we're talking to a running
436      target, then trust the current value of $cpsr.  This lets
437      "display/i $pc" always show the correct mode (though if there is
438      a symbol table we will not reach here, so it still may not be
439      displayed in the mode it will be executed).  */
440   if (target_has_registers)
441     return arm_frame_is_thumb (get_current_frame ());
442
443   /* Otherwise we're out of luck; we assume ARM.  */
444   return 0;
445 }
446
447 /* Remove useless bits from addresses in a running program.  */
448 static CORE_ADDR
449 arm_addr_bits_remove (struct gdbarch *gdbarch, CORE_ADDR val)
450 {
451   /* On M-profile devices, do not strip the low bit from EXC_RETURN
452      (the magic exception return address).  */
453   if (gdbarch_tdep (gdbarch)->is_m
454       && (val & 0xfffffff0) == 0xfffffff0)
455     return val;
456
457   if (arm_apcs_32)
458     return UNMAKE_THUMB_ADDR (val);
459   else
460     return (val & 0x03fffffc);
461 }
462
463 /* When reading symbols, we need to zap the low bit of the address,
464    which may be set to 1 for Thumb functions.  */
465 static CORE_ADDR
466 arm_smash_text_address (struct gdbarch *gdbarch, CORE_ADDR val)
467 {
468   return val & ~1;
469 }
470
471 /* Return 1 if PC is the start of a compiler helper function which
472    can be safely ignored during prologue skipping.  IS_THUMB is true
473    if the function is known to be a Thumb function due to the way it
474    is being called.  */
475 static int
476 skip_prologue_function (struct gdbarch *gdbarch, CORE_ADDR pc, int is_thumb)
477 {
478   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
479   struct minimal_symbol *msym;
480
481   msym = lookup_minimal_symbol_by_pc (pc);
482   if (msym != NULL
483       && SYMBOL_VALUE_ADDRESS (msym) == pc
484       && SYMBOL_LINKAGE_NAME (msym) != NULL)
485     {
486       const char *name = SYMBOL_LINKAGE_NAME (msym);
487
488       /* The GNU linker's Thumb call stub to foo is named
489          __foo_from_thumb.  */
490       if (strstr (name, "_from_thumb") != NULL)
491         name += 2;
492
493       /* On soft-float targets, __truncdfsf2 is called to convert promoted
494          arguments to their argument types in non-prototyped
495          functions.  */
496       if (strncmp (name, "__truncdfsf2", strlen ("__truncdfsf2")) == 0)
497         return 1;
498       if (strncmp (name, "__aeabi_d2f", strlen ("__aeabi_d2f")) == 0)
499         return 1;
500
501       /* Internal functions related to thread-local storage.  */
502       if (strncmp (name, "__tls_get_addr", strlen ("__tls_get_addr")) == 0)
503         return 1;
504       if (strncmp (name, "__aeabi_read_tp", strlen ("__aeabi_read_tp")) == 0)
505         return 1;
506     }
507   else
508     {
509       /* If we run against a stripped glibc, we may be unable to identify
510          special functions by name.  Check for one important case,
511          __aeabi_read_tp, by comparing the *code* against the default
512          implementation (this is hand-written ARM assembler in glibc).  */
513
514       if (!is_thumb
515           && read_memory_unsigned_integer (pc, 4, byte_order_for_code)
516              == 0xe3e00a0f /* mov r0, #0xffff0fff */
517           && read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code)
518              == 0xe240f01f) /* sub pc, r0, #31 */
519         return 1;
520     }
521
522   return 0;
523 }
524
525 /* Support routines for instruction parsing.  */
526 #define submask(x) ((1L << ((x) + 1)) - 1)
527 #define bit(obj,st) (((obj) >> (st)) & 1)
528 #define bits(obj,st,fn) (((obj) >> (st)) & submask ((fn) - (st)))
529 #define sbits(obj,st,fn) \
530   ((long) (bits(obj,st,fn) | ((long) bit(obj,fn) * ~ submask (fn - st))))
531 #define BranchDest(addr,instr) \
532   ((CORE_ADDR) (((long) (addr)) + 8 + (sbits (instr, 0, 23) << 2)))
533
534 /* Extract the immediate from instruction movw/movt of encoding T.  INSN1 is
535    the first 16-bit of instruction, and INSN2 is the second 16-bit of
536    instruction.  */
537 #define EXTRACT_MOVW_MOVT_IMM_T(insn1, insn2) \
538   ((bits ((insn1), 0, 3) << 12)               \
539    | (bits ((insn1), 10, 10) << 11)           \
540    | (bits ((insn2), 12, 14) << 8)            \
541    | bits ((insn2), 0, 7))
542
543 /* Extract the immediate from instruction movw/movt of encoding A.  INSN is
544    the 32-bit instruction.  */
545 #define EXTRACT_MOVW_MOVT_IMM_A(insn) \
546   ((bits ((insn), 16, 19) << 12) \
547    | bits ((insn), 0, 11))
548
549 /* Decode immediate value; implements ThumbExpandImmediate pseudo-op.  */
550
551 static unsigned int
552 thumb_expand_immediate (unsigned int imm)
553 {
554   unsigned int count = imm >> 7;
555
556   if (count < 8)
557     switch (count / 2)
558       {
559       case 0:
560         return imm & 0xff;
561       case 1:
562         return (imm & 0xff) | ((imm & 0xff) << 16);
563       case 2:
564         return ((imm & 0xff) << 8) | ((imm & 0xff) << 24);
565       case 3:
566         return (imm & 0xff) | ((imm & 0xff) << 8)
567                 | ((imm & 0xff) << 16) | ((imm & 0xff) << 24);
568       }
569
570   return (0x80 | (imm & 0x7f)) << (32 - count);
571 }
572
573 /* Return 1 if the 16-bit Thumb instruction INST might change
574    control flow, 0 otherwise.  */
575
576 static int
577 thumb_instruction_changes_pc (unsigned short inst)
578 {
579   if ((inst & 0xff00) == 0xbd00)        /* pop {rlist, pc} */
580     return 1;
581
582   if ((inst & 0xf000) == 0xd000)        /* conditional branch */
583     return 1;
584
585   if ((inst & 0xf800) == 0xe000)        /* unconditional branch */
586     return 1;
587
588   if ((inst & 0xff00) == 0x4700)        /* bx REG, blx REG */
589     return 1;
590
591   if ((inst & 0xff87) == 0x4687)        /* mov pc, REG */
592     return 1;
593
594   if ((inst & 0xf500) == 0xb100)        /* CBNZ or CBZ.  */
595     return 1;
596
597   return 0;
598 }
599
600 /* Return 1 if the 32-bit Thumb instruction in INST1 and INST2
601    might change control flow, 0 otherwise.  */
602
603 static int
604 thumb2_instruction_changes_pc (unsigned short inst1, unsigned short inst2)
605 {
606   if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
607     {
608       /* Branches and miscellaneous control instructions.  */
609
610       if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
611         {
612           /* B, BL, BLX.  */
613           return 1;
614         }
615       else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
616         {
617           /* SUBS PC, LR, #imm8.  */
618           return 1;
619         }
620       else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
621         {
622           /* Conditional branch.  */
623           return 1;
624         }
625
626       return 0;
627     }
628
629   if ((inst1 & 0xfe50) == 0xe810)
630     {
631       /* Load multiple or RFE.  */
632
633       if (bit (inst1, 7) && !bit (inst1, 8))
634         {
635           /* LDMIA or POP */
636           if (bit (inst2, 15))
637             return 1;
638         }
639       else if (!bit (inst1, 7) && bit (inst1, 8))
640         {
641           /* LDMDB */
642           if (bit (inst2, 15))
643             return 1;
644         }
645       else if (bit (inst1, 7) && bit (inst1, 8))
646         {
647           /* RFEIA */
648           return 1;
649         }
650       else if (!bit (inst1, 7) && !bit (inst1, 8))
651         {
652           /* RFEDB */
653           return 1;
654         }
655
656       return 0;
657     }
658
659   if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
660     {
661       /* MOV PC or MOVS PC.  */
662       return 1;
663     }
664
665   if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
666     {
667       /* LDR PC.  */
668       if (bits (inst1, 0, 3) == 15)
669         return 1;
670       if (bit (inst1, 7))
671         return 1;
672       if (bit (inst2, 11))
673         return 1;
674       if ((inst2 & 0x0fc0) == 0x0000)
675         return 1;       
676
677       return 0;
678     }
679
680   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
681     {
682       /* TBB.  */
683       return 1;
684     }
685
686   if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
687     {
688       /* TBH.  */
689       return 1;
690     }
691
692   return 0;
693 }
694
695 /* Analyze a Thumb prologue, looking for a recognizable stack frame
696    and frame pointer.  Scan until we encounter a store that could
697    clobber the stack frame unexpectedly, or an unknown instruction.
698    Return the last address which is definitely safe to skip for an
699    initial breakpoint.  */
700
701 static CORE_ADDR
702 thumb_analyze_prologue (struct gdbarch *gdbarch,
703                         CORE_ADDR start, CORE_ADDR limit,
704                         struct arm_prologue_cache *cache)
705 {
706   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
707   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
708   int i;
709   pv_t regs[16];
710   struct pv_area *stack;
711   struct cleanup *back_to;
712   CORE_ADDR offset;
713   CORE_ADDR unrecognized_pc = 0;
714
715   for (i = 0; i < 16; i++)
716     regs[i] = pv_register (i, 0);
717   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
718   back_to = make_cleanup_free_pv_area (stack);
719
720   while (start < limit)
721     {
722       unsigned short insn;
723
724       insn = read_memory_unsigned_integer (start, 2, byte_order_for_code);
725
726       if ((insn & 0xfe00) == 0xb400)            /* push { rlist } */
727         {
728           int regno;
729           int mask;
730
731           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
732             break;
733
734           /* Bits 0-7 contain a mask for registers R0-R7.  Bit 8 says
735              whether to save LR (R14).  */
736           mask = (insn & 0xff) | ((insn & 0x100) << 6);
737
738           /* Calculate offsets of saved R0-R7 and LR.  */
739           for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
740             if (mask & (1 << regno))
741               {
742                 regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
743                                                        -4);
744                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
745               }
746         }
747       else if ((insn & 0xff00) == 0xb000)       /* add sp, #simm  OR  
748                                                    sub sp, #simm */
749         {
750           offset = (insn & 0x7f) << 2;          /* get scaled offset */
751           if (insn & 0x80)                      /* Check for SUB.  */
752             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
753                                                    -offset);
754           else
755             regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM],
756                                                    offset);
757         }
758       else if ((insn & 0xf800) == 0xa800)       /* add Rd, sp, #imm */
759         regs[bits (insn, 8, 10)] = pv_add_constant (regs[ARM_SP_REGNUM],
760                                                     (insn & 0xff) << 2);
761       else if ((insn & 0xfe00) == 0x1c00        /* add Rd, Rn, #imm */
762                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
763         regs[bits (insn, 0, 2)] = pv_add_constant (regs[bits (insn, 3, 5)],
764                                                    bits (insn, 6, 8));
765       else if ((insn & 0xf800) == 0x3000        /* add Rd, #imm */
766                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
767         regs[bits (insn, 8, 10)] = pv_add_constant (regs[bits (insn, 8, 10)],
768                                                     bits (insn, 0, 7));
769       else if ((insn & 0xfe00) == 0x1800        /* add Rd, Rn, Rm */
770                && pv_is_register (regs[bits (insn, 6, 8)], ARM_SP_REGNUM)
771                && pv_is_constant (regs[bits (insn, 3, 5)]))
772         regs[bits (insn, 0, 2)] = pv_add (regs[bits (insn, 3, 5)],
773                                           regs[bits (insn, 6, 8)]);
774       else if ((insn & 0xff00) == 0x4400        /* add Rd, Rm */
775                && pv_is_constant (regs[bits (insn, 3, 6)]))
776         {
777           int rd = (bit (insn, 7) << 3) + bits (insn, 0, 2);
778           int rm = bits (insn, 3, 6);
779           regs[rd] = pv_add (regs[rd], regs[rm]);
780         }
781       else if ((insn & 0xff00) == 0x4600)       /* mov hi, lo or mov lo, hi */
782         {
783           int dst_reg = (insn & 0x7) + ((insn & 0x80) >> 4);
784           int src_reg = (insn & 0x78) >> 3;
785           regs[dst_reg] = regs[src_reg];
786         }
787       else if ((insn & 0xf800) == 0x9000)       /* str rd, [sp, #off] */
788         {
789           /* Handle stores to the stack.  Normally pushes are used,
790              but with GCC -mtpcs-frame, there may be other stores
791              in the prologue to create the frame.  */
792           int regno = (insn >> 8) & 0x7;
793           pv_t addr;
794
795           offset = (insn & 0xff) << 2;
796           addr = pv_add_constant (regs[ARM_SP_REGNUM], offset);
797
798           if (pv_area_store_would_trash (stack, addr))
799             break;
800
801           pv_area_store (stack, addr, 4, regs[regno]);
802         }
803       else if ((insn & 0xf800) == 0x6000)       /* str rd, [rn, #off] */
804         {
805           int rd = bits (insn, 0, 2);
806           int rn = bits (insn, 3, 5);
807           pv_t addr;
808
809           offset = bits (insn, 6, 10) << 2;
810           addr = pv_add_constant (regs[rn], offset);
811
812           if (pv_area_store_would_trash (stack, addr))
813             break;
814
815           pv_area_store (stack, addr, 4, regs[rd]);
816         }
817       else if (((insn & 0xf800) == 0x7000       /* strb Rd, [Rn, #off] */
818                 || (insn & 0xf800) == 0x8000)   /* strh Rd, [Rn, #off] */
819                && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM))
820         /* Ignore stores of argument registers to the stack.  */
821         ;
822       else if ((insn & 0xf800) == 0xc800        /* ldmia Rn!, { registers } */
823                && pv_is_register (regs[bits (insn, 8, 10)], ARM_SP_REGNUM))
824         /* Ignore block loads from the stack, potentially copying
825            parameters from memory.  */
826         ;
827       else if ((insn & 0xf800) == 0x9800        /* ldr Rd, [Rn, #immed] */
828                || ((insn & 0xf800) == 0x6800    /* ldr Rd, [sp, #immed] */
829                    && pv_is_register (regs[bits (insn, 3, 5)], ARM_SP_REGNUM)))
830         /* Similarly ignore single loads from the stack.  */
831         ;
832       else if ((insn & 0xffc0) == 0x0000        /* lsls Rd, Rm, #0 */
833                || (insn & 0xffc0) == 0x1c00)    /* add Rd, Rn, #0 */
834         /* Skip register copies, i.e. saves to another register
835            instead of the stack.  */
836         ;
837       else if ((insn & 0xf800) == 0x2000)       /* movs Rd, #imm */
838         /* Recognize constant loads; even with small stacks these are necessary
839            on Thumb.  */
840         regs[bits (insn, 8, 10)] = pv_constant (bits (insn, 0, 7));
841       else if ((insn & 0xf800) == 0x4800)       /* ldr Rd, [pc, #imm] */
842         {
843           /* Constant pool loads, for the same reason.  */
844           unsigned int constant;
845           CORE_ADDR loc;
846
847           loc = start + 4 + bits (insn, 0, 7) * 4;
848           constant = read_memory_unsigned_integer (loc, 4, byte_order);
849           regs[bits (insn, 8, 10)] = pv_constant (constant);
850         }
851       else if (thumb_insn_size (insn) == 4) /* 32-bit Thumb-2 instructions.  */
852         {
853           unsigned short inst2;
854
855           inst2 = read_memory_unsigned_integer (start + 2, 2,
856                                                 byte_order_for_code);
857
858           if ((insn & 0xf800) == 0xf000 && (inst2 & 0xe800) == 0xe800)
859             {
860               /* BL, BLX.  Allow some special function calls when
861                  skipping the prologue; GCC generates these before
862                  storing arguments to the stack.  */
863               CORE_ADDR nextpc;
864               int j1, j2, imm1, imm2;
865
866               imm1 = sbits (insn, 0, 10);
867               imm2 = bits (inst2, 0, 10);
868               j1 = bit (inst2, 13);
869               j2 = bit (inst2, 11);
870
871               offset = ((imm1 << 12) + (imm2 << 1));
872               offset ^= ((!j2) << 22) | ((!j1) << 23);
873
874               nextpc = start + 4 + offset;
875               /* For BLX make sure to clear the low bits.  */
876               if (bit (inst2, 12) == 0)
877                 nextpc = nextpc & 0xfffffffc;
878
879               if (!skip_prologue_function (gdbarch, nextpc,
880                                            bit (inst2, 12) != 0))
881                 break;
882             }
883
884           else if ((insn & 0xffd0) == 0xe900    /* stmdb Rn{!},
885                                                    { registers } */
886                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
887             {
888               pv_t addr = regs[bits (insn, 0, 3)];
889               int regno;
890
891               if (pv_area_store_would_trash (stack, addr))
892                 break;
893
894               /* Calculate offsets of saved registers.  */
895               for (regno = ARM_LR_REGNUM; regno >= 0; regno--)
896                 if (inst2 & (1 << regno))
897                   {
898                     addr = pv_add_constant (addr, -4);
899                     pv_area_store (stack, addr, 4, regs[regno]);
900                   }
901
902               if (insn & 0x0020)
903                 regs[bits (insn, 0, 3)] = addr;
904             }
905
906           else if ((insn & 0xff50) == 0xe940    /* strd Rt, Rt2,
907                                                    [Rn, #+/-imm]{!} */
908                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
909             {
910               int regno1 = bits (inst2, 12, 15);
911               int regno2 = bits (inst2, 8, 11);
912               pv_t addr = regs[bits (insn, 0, 3)];
913
914               offset = inst2 & 0xff;
915               if (insn & 0x0080)
916                 addr = pv_add_constant (addr, offset);
917               else
918                 addr = pv_add_constant (addr, -offset);
919
920               if (pv_area_store_would_trash (stack, addr))
921                 break;
922
923               pv_area_store (stack, addr, 4, regs[regno1]);
924               pv_area_store (stack, pv_add_constant (addr, 4),
925                              4, regs[regno2]);
926
927               if (insn & 0x0020)
928                 regs[bits (insn, 0, 3)] = addr;
929             }
930
931           else if ((insn & 0xfff0) == 0xf8c0    /* str Rt,[Rn,+/-#imm]{!} */
932                    && (inst2 & 0x0c00) == 0x0c00
933                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
934             {
935               int regno = bits (inst2, 12, 15);
936               pv_t addr = regs[bits (insn, 0, 3)];
937
938               offset = inst2 & 0xff;
939               if (inst2 & 0x0200)
940                 addr = pv_add_constant (addr, offset);
941               else
942                 addr = pv_add_constant (addr, -offset);
943
944               if (pv_area_store_would_trash (stack, addr))
945                 break;
946
947               pv_area_store (stack, addr, 4, regs[regno]);
948
949               if (inst2 & 0x0100)
950                 regs[bits (insn, 0, 3)] = addr;
951             }
952
953           else if ((insn & 0xfff0) == 0xf8c0    /* str.w Rt,[Rn,#imm] */
954                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
955             {
956               int regno = bits (inst2, 12, 15);
957               pv_t addr;
958
959               offset = inst2 & 0xfff;
960               addr = pv_add_constant (regs[bits (insn, 0, 3)], offset);
961
962               if (pv_area_store_would_trash (stack, addr))
963                 break;
964
965               pv_area_store (stack, addr, 4, regs[regno]);
966             }
967
968           else if ((insn & 0xffd0) == 0xf880    /* str{bh}.w Rt,[Rn,#imm] */
969                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
970             /* Ignore stores of argument registers to the stack.  */
971             ;
972
973           else if ((insn & 0xffd0) == 0xf800    /* str{bh} Rt,[Rn,#+/-imm] */
974                    && (inst2 & 0x0d00) == 0x0c00
975                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
976             /* Ignore stores of argument registers to the stack.  */
977             ;
978
979           else if ((insn & 0xffd0) == 0xe890    /* ldmia Rn[!],
980                                                    { registers } */
981                    && (inst2 & 0x8000) == 0x0000
982                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
983             /* Ignore block loads from the stack, potentially copying
984                parameters from memory.  */
985             ;
986
987           else if ((insn & 0xffb0) == 0xe950    /* ldrd Rt, Rt2,
988                                                    [Rn, #+/-imm] */
989                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
990             /* Similarly ignore dual loads from the stack.  */
991             ;
992
993           else if ((insn & 0xfff0) == 0xf850    /* ldr Rt,[Rn,#+/-imm] */
994                    && (inst2 & 0x0d00) == 0x0c00
995                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
996             /* Similarly ignore single loads from the stack.  */
997             ;
998
999           else if ((insn & 0xfff0) == 0xf8d0    /* ldr.w Rt,[Rn,#imm] */
1000                    && pv_is_register (regs[bits (insn, 0, 3)], ARM_SP_REGNUM))
1001             /* Similarly ignore single loads from the stack.  */
1002             ;
1003
1004           else if ((insn & 0xfbf0) == 0xf100    /* add.w Rd, Rn, #imm */
1005                    && (inst2 & 0x8000) == 0x0000)
1006             {
1007               unsigned int imm = ((bits (insn, 10, 10) << 11)
1008                                   | (bits (inst2, 12, 14) << 8)
1009                                   | bits (inst2, 0, 7));
1010
1011               regs[bits (inst2, 8, 11)]
1012                 = pv_add_constant (regs[bits (insn, 0, 3)],
1013                                    thumb_expand_immediate (imm));
1014             }
1015
1016           else if ((insn & 0xfbf0) == 0xf200    /* addw Rd, Rn, #imm */
1017                    && (inst2 & 0x8000) == 0x0000)
1018             {
1019               unsigned int imm = ((bits (insn, 10, 10) << 11)
1020                                   | (bits (inst2, 12, 14) << 8)
1021                                   | bits (inst2, 0, 7));
1022
1023               regs[bits (inst2, 8, 11)]
1024                 = pv_add_constant (regs[bits (insn, 0, 3)], imm);
1025             }
1026
1027           else if ((insn & 0xfbf0) == 0xf1a0    /* sub.w Rd, Rn, #imm */
1028                    && (inst2 & 0x8000) == 0x0000)
1029             {
1030               unsigned int imm = ((bits (insn, 10, 10) << 11)
1031                                   | (bits (inst2, 12, 14) << 8)
1032                                   | bits (inst2, 0, 7));
1033
1034               regs[bits (inst2, 8, 11)]
1035                 = pv_add_constant (regs[bits (insn, 0, 3)],
1036                                    - (CORE_ADDR) thumb_expand_immediate (imm));
1037             }
1038
1039           else if ((insn & 0xfbf0) == 0xf2a0    /* subw Rd, Rn, #imm */
1040                    && (inst2 & 0x8000) == 0x0000)
1041             {
1042               unsigned int imm = ((bits (insn, 10, 10) << 11)
1043                                   | (bits (inst2, 12, 14) << 8)
1044                                   | bits (inst2, 0, 7));
1045
1046               regs[bits (inst2, 8, 11)]
1047                 = pv_add_constant (regs[bits (insn, 0, 3)], - (CORE_ADDR) imm);
1048             }
1049
1050           else if ((insn & 0xfbff) == 0xf04f)   /* mov.w Rd, #const */
1051             {
1052               unsigned int imm = ((bits (insn, 10, 10) << 11)
1053                                   | (bits (inst2, 12, 14) << 8)
1054                                   | bits (inst2, 0, 7));
1055
1056               regs[bits (inst2, 8, 11)]
1057                 = pv_constant (thumb_expand_immediate (imm));
1058             }
1059
1060           else if ((insn & 0xfbf0) == 0xf240)   /* movw Rd, #const */
1061             {
1062               unsigned int imm
1063                 = EXTRACT_MOVW_MOVT_IMM_T (insn, inst2);
1064
1065               regs[bits (inst2, 8, 11)] = pv_constant (imm);
1066             }
1067
1068           else if (insn == 0xea5f               /* mov.w Rd,Rm */
1069                    && (inst2 & 0xf0f0) == 0)
1070             {
1071               int dst_reg = (inst2 & 0x0f00) >> 8;
1072               int src_reg = inst2 & 0xf;
1073               regs[dst_reg] = regs[src_reg];
1074             }
1075
1076           else if ((insn & 0xff7f) == 0xf85f)   /* ldr.w Rt,<label> */
1077             {
1078               /* Constant pool loads.  */
1079               unsigned int constant;
1080               CORE_ADDR loc;
1081
1082               offset = bits (insn, 0, 11);
1083               if (insn & 0x0080)
1084                 loc = start + 4 + offset;
1085               else
1086                 loc = start + 4 - offset;
1087
1088               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1089               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1090             }
1091
1092           else if ((insn & 0xff7f) == 0xe95f)   /* ldrd Rt,Rt2,<label> */
1093             {
1094               /* Constant pool loads.  */
1095               unsigned int constant;
1096               CORE_ADDR loc;
1097
1098               offset = bits (insn, 0, 7) << 2;
1099               if (insn & 0x0080)
1100                 loc = start + 4 + offset;
1101               else
1102                 loc = start + 4 - offset;
1103
1104               constant = read_memory_unsigned_integer (loc, 4, byte_order);
1105               regs[bits (inst2, 12, 15)] = pv_constant (constant);
1106
1107               constant = read_memory_unsigned_integer (loc + 4, 4, byte_order);
1108               regs[bits (inst2, 8, 11)] = pv_constant (constant);
1109             }
1110
1111           else if (thumb2_instruction_changes_pc (insn, inst2))
1112             {
1113               /* Don't scan past anything that might change control flow.  */
1114               break;
1115             }
1116           else
1117             {
1118               /* The optimizer might shove anything into the prologue,
1119                  so we just skip what we don't recognize.  */
1120               unrecognized_pc = start;
1121             }
1122
1123           start += 2;
1124         }
1125       else if (thumb_instruction_changes_pc (insn))
1126         {
1127           /* Don't scan past anything that might change control flow.  */
1128           break;
1129         }
1130       else
1131         {
1132           /* The optimizer might shove anything into the prologue,
1133              so we just skip what we don't recognize.  */
1134           unrecognized_pc = start;
1135         }
1136
1137       start += 2;
1138     }
1139
1140   if (arm_debug)
1141     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1142                         paddress (gdbarch, start));
1143
1144   if (unrecognized_pc == 0)
1145     unrecognized_pc = start;
1146
1147   if (cache == NULL)
1148     {
1149       do_cleanups (back_to);
1150       return unrecognized_pc;
1151     }
1152
1153   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1154     {
1155       /* Frame pointer is fp.  Frame size is constant.  */
1156       cache->framereg = ARM_FP_REGNUM;
1157       cache->framesize = -regs[ARM_FP_REGNUM].k;
1158     }
1159   else if (pv_is_register (regs[THUMB_FP_REGNUM], ARM_SP_REGNUM))
1160     {
1161       /* Frame pointer is r7.  Frame size is constant.  */
1162       cache->framereg = THUMB_FP_REGNUM;
1163       cache->framesize = -regs[THUMB_FP_REGNUM].k;
1164     }
1165   else
1166     {
1167       /* Try the stack pointer... this is a bit desperate.  */
1168       cache->framereg = ARM_SP_REGNUM;
1169       cache->framesize = -regs[ARM_SP_REGNUM].k;
1170     }
1171
1172   for (i = 0; i < 16; i++)
1173     if (pv_area_find_reg (stack, gdbarch, i, &offset))
1174       cache->saved_regs[i].addr = offset;
1175
1176   do_cleanups (back_to);
1177   return unrecognized_pc;
1178 }
1179
1180
1181 /* Try to analyze the instructions starting from PC, which load symbol
1182    __stack_chk_guard.  Return the address of instruction after loading this
1183    symbol, set the dest register number to *BASEREG, and set the size of
1184    instructions for loading symbol in OFFSET.  Return 0 if instructions are
1185    not recognized.  */
1186
1187 static CORE_ADDR
1188 arm_analyze_load_stack_chk_guard(CORE_ADDR pc, struct gdbarch *gdbarch,
1189                                  unsigned int *destreg, int *offset)
1190 {
1191   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1192   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1193   unsigned int low, high, address;
1194
1195   address = 0;
1196   if (is_thumb)
1197     {
1198       unsigned short insn1
1199         = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
1200
1201       if ((insn1 & 0xf800) == 0x4800) /* ldr Rd, #immed */
1202         {
1203           *destreg = bits (insn1, 8, 10);
1204           *offset = 2;
1205           address = bits (insn1, 0, 7);
1206         }
1207       else if ((insn1 & 0xfbf0) == 0xf240) /* movw Rd, #const */
1208         {
1209           unsigned short insn2
1210             = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
1211
1212           low = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1213
1214           insn1
1215             = read_memory_unsigned_integer (pc + 4, 2, byte_order_for_code);
1216           insn2
1217             = read_memory_unsigned_integer (pc + 6, 2, byte_order_for_code);
1218
1219           /* movt Rd, #const */
1220           if ((insn1 & 0xfbc0) == 0xf2c0)
1221             {
1222               high = EXTRACT_MOVW_MOVT_IMM_T (insn1, insn2);
1223               *destreg = bits (insn2, 8, 11);
1224               *offset = 8;
1225               address = (high << 16 | low);
1226             }
1227         }
1228     }
1229   else
1230     {
1231       unsigned int insn
1232         = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
1233
1234       if ((insn & 0x0e5f0000) == 0x041f0000) /* ldr Rd, #immed */
1235         {
1236           address = bits (insn, 0, 11);
1237           *destreg = bits (insn, 12, 15);
1238           *offset = 4;
1239         }
1240       else if ((insn & 0x0ff00000) == 0x03000000) /* movw Rd, #const */
1241         {
1242           low = EXTRACT_MOVW_MOVT_IMM_A (insn);
1243
1244           insn
1245             = read_memory_unsigned_integer (pc + 4, 4, byte_order_for_code);
1246
1247           if ((insn & 0x0ff00000) == 0x03400000) /* movt Rd, #const */
1248             {
1249               high = EXTRACT_MOVW_MOVT_IMM_A (insn);
1250               *destreg = bits (insn, 12, 15);
1251               *offset = 8;
1252               address = (high << 16 | low);
1253             }
1254         }
1255     }
1256
1257   return address;
1258 }
1259
1260 /* Try to skip a sequence of instructions used for stack protector.  If PC
1261    points to the first instruction of this sequence, return the address of
1262    first instruction after this sequence, otherwise, return original PC.
1263
1264    On arm, this sequence of instructions is composed of mainly three steps,
1265      Step 1: load symbol __stack_chk_guard,
1266      Step 2: load from address of __stack_chk_guard,
1267      Step 3: store it to somewhere else.
1268
1269    Usually, instructions on step 2 and step 3 are the same on various ARM
1270    architectures.  On step 2, it is one instruction 'ldr Rx, [Rn, #0]', and
1271    on step 3, it is also one instruction 'str Rx, [r7, #immd]'.  However,
1272    instructions in step 1 vary from different ARM architectures.  On ARMv7,
1273    they are,
1274
1275         movw    Rn, #:lower16:__stack_chk_guard
1276         movt    Rn, #:upper16:__stack_chk_guard
1277
1278    On ARMv5t, it is,
1279
1280         ldr     Rn, .Label
1281         ....
1282         .Lable:
1283         .word   __stack_chk_guard
1284
1285    Since ldr/str is a very popular instruction, we can't use them as
1286    'fingerprint' or 'signature' of stack protector sequence.  Here we choose
1287    sequence {movw/movt, ldr}/ldr/str plus symbol __stack_chk_guard, if not
1288    stripped, as the 'fingerprint' of a stack protector cdoe sequence.  */
1289
1290 static CORE_ADDR
1291 arm_skip_stack_protector(CORE_ADDR pc, struct gdbarch *gdbarch)
1292 {
1293   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1294   unsigned int basereg;
1295   struct minimal_symbol *stack_chk_guard;
1296   int offset;
1297   int is_thumb = arm_pc_is_thumb (gdbarch, pc);
1298   CORE_ADDR addr;
1299
1300   /* Try to parse the instructions in Step 1.  */
1301   addr = arm_analyze_load_stack_chk_guard (pc, gdbarch,
1302                                            &basereg, &offset);
1303   if (!addr)
1304     return pc;
1305
1306   stack_chk_guard = lookup_minimal_symbol_by_pc (addr);
1307   /* If name of symbol doesn't start with '__stack_chk_guard', this
1308      instruction sequence is not for stack protector.  If symbol is
1309      removed, we conservatively think this sequence is for stack protector.  */
1310   if (stack_chk_guard
1311       && strncmp (SYMBOL_LINKAGE_NAME (stack_chk_guard), "__stack_chk_guard",
1312                   strlen ("__stack_chk_guard")) != 0)
1313    return pc;
1314
1315   if (is_thumb)
1316     {
1317       unsigned int destreg;
1318       unsigned short insn
1319         = read_memory_unsigned_integer (pc + offset, 2, byte_order_for_code);
1320
1321       /* Step 2: ldr Rd, [Rn, #immed], encoding T1.  */
1322       if ((insn & 0xf800) != 0x6800)
1323         return pc;
1324       if (bits (insn, 3, 5) != basereg)
1325         return pc;
1326       destreg = bits (insn, 0, 2);
1327
1328       insn = read_memory_unsigned_integer (pc + offset + 2, 2,
1329                                            byte_order_for_code);
1330       /* Step 3: str Rd, [Rn, #immed], encoding T1.  */
1331       if ((insn & 0xf800) != 0x6000)
1332         return pc;
1333       if (destreg != bits (insn, 0, 2))
1334         return pc;
1335     }
1336   else
1337     {
1338       unsigned int destreg;
1339       unsigned int insn
1340         = read_memory_unsigned_integer (pc + offset, 4, byte_order_for_code);
1341
1342       /* Step 2: ldr Rd, [Rn, #immed], encoding A1.  */
1343       if ((insn & 0x0e500000) != 0x04100000)
1344         return pc;
1345       if (bits (insn, 16, 19) != basereg)
1346         return pc;
1347       destreg = bits (insn, 12, 15);
1348       /* Step 3: str Rd, [Rn, #immed], encoding A1.  */
1349       insn = read_memory_unsigned_integer (pc + offset + 4,
1350                                            4, byte_order_for_code);
1351       if ((insn & 0x0e500000) != 0x04000000)
1352         return pc;
1353       if (bits (insn, 12, 15) != destreg)
1354         return pc;
1355     }
1356   /* The size of total two instructions ldr/str is 4 on Thumb-2, while 8
1357      on arm.  */
1358   if (is_thumb)
1359     return pc + offset + 4;
1360   else
1361     return pc + offset + 8;
1362 }
1363
1364 /* Advance the PC across any function entry prologue instructions to
1365    reach some "real" code.
1366
1367    The APCS (ARM Procedure Call Standard) defines the following
1368    prologue:
1369
1370    mov          ip, sp
1371    [stmfd       sp!, {a1,a2,a3,a4}]
1372    stmfd        sp!, {...,fp,ip,lr,pc}
1373    [stfe        f7, [sp, #-12]!]
1374    [stfe        f6, [sp, #-12]!]
1375    [stfe        f5, [sp, #-12]!]
1376    [stfe        f4, [sp, #-12]!]
1377    sub fp, ip, #nn @@ nn == 20 or 4 depending on second insn.  */
1378
1379 static CORE_ADDR
1380 arm_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1381 {
1382   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1383   unsigned long inst;
1384   CORE_ADDR skip_pc;
1385   CORE_ADDR func_addr, limit_pc;
1386
1387   /* See if we can determine the end of the prologue via the symbol table.
1388      If so, then return either PC, or the PC after the prologue, whichever
1389      is greater.  */
1390   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1391     {
1392       CORE_ADDR post_prologue_pc
1393         = skip_prologue_using_sal (gdbarch, func_addr);
1394       struct symtab *s = find_pc_symtab (func_addr);
1395
1396       if (post_prologue_pc)
1397         post_prologue_pc
1398           = arm_skip_stack_protector (post_prologue_pc, gdbarch);
1399
1400
1401       /* GCC always emits a line note before the prologue and another
1402          one after, even if the two are at the same address or on the
1403          same line.  Take advantage of this so that we do not need to
1404          know every instruction that might appear in the prologue.  We
1405          will have producer information for most binaries; if it is
1406          missing (e.g. for -gstabs), assuming the GNU tools.  */
1407       if (post_prologue_pc
1408           && (s == NULL
1409               || s->producer == NULL
1410               || strncmp (s->producer, "GNU ", sizeof ("GNU ") - 1) == 0 
1411               || strncmp (s->producer, "clang ", sizeof ("clang ") - 1) == 0))
1412         return post_prologue_pc;
1413
1414       if (post_prologue_pc != 0)
1415         {
1416           CORE_ADDR analyzed_limit;
1417
1418           /* For non-GCC compilers, make sure the entire line is an
1419              acceptable prologue; GDB will round this function's
1420              return value up to the end of the following line so we
1421              can not skip just part of a line (and we do not want to).
1422
1423              RealView does not treat the prologue specially, but does
1424              associate prologue code with the opening brace; so this
1425              lets us skip the first line if we think it is the opening
1426              brace.  */
1427           if (arm_pc_is_thumb (gdbarch, func_addr))
1428             analyzed_limit = thumb_analyze_prologue (gdbarch, func_addr,
1429                                                      post_prologue_pc, NULL);
1430           else
1431             analyzed_limit = arm_analyze_prologue (gdbarch, func_addr,
1432                                                    post_prologue_pc, NULL);
1433
1434           if (analyzed_limit != post_prologue_pc)
1435             return func_addr;
1436
1437           return post_prologue_pc;
1438         }
1439     }
1440
1441   /* Can't determine prologue from the symbol table, need to examine
1442      instructions.  */
1443
1444   /* Find an upper limit on the function prologue using the debug
1445      information.  If the debug information could not be used to provide
1446      that bound, then use an arbitrary large number as the upper bound.  */
1447   /* Like arm_scan_prologue, stop no later than pc + 64.  */
1448   limit_pc = skip_prologue_using_sal (gdbarch, pc);
1449   if (limit_pc == 0)
1450     limit_pc = pc + 64;          /* Magic.  */
1451
1452
1453   /* Check if this is Thumb code.  */
1454   if (arm_pc_is_thumb (gdbarch, pc))
1455     return thumb_analyze_prologue (gdbarch, pc, limit_pc, NULL);
1456
1457   for (skip_pc = pc; skip_pc < limit_pc; skip_pc += 4)
1458     {
1459       inst = read_memory_unsigned_integer (skip_pc, 4, byte_order_for_code);
1460
1461       /* "mov ip, sp" is no longer a required part of the prologue.  */
1462       if (inst == 0xe1a0c00d)                   /* mov ip, sp */
1463         continue;
1464
1465       if ((inst & 0xfffff000) == 0xe28dc000)    /* add ip, sp #n */
1466         continue;
1467
1468       if ((inst & 0xfffff000) == 0xe24dc000)    /* sub ip, sp #n */
1469         continue;
1470
1471       /* Some prologues begin with "str lr, [sp, #-4]!".  */
1472       if (inst == 0xe52de004)                   /* str lr, [sp, #-4]! */
1473         continue;
1474
1475       if ((inst & 0xfffffff0) == 0xe92d0000)    /* stmfd sp!,{a1,a2,a3,a4} */
1476         continue;
1477
1478       if ((inst & 0xfffff800) == 0xe92dd800)    /* stmfd sp!,{fp,ip,lr,pc} */
1479         continue;
1480
1481       /* Any insns after this point may float into the code, if it makes
1482          for better instruction scheduling, so we skip them only if we
1483          find them, but still consider the function to be frame-ful.  */
1484
1485       /* We may have either one sfmfd instruction here, or several stfe
1486          insns, depending on the version of floating point code we
1487          support.  */
1488       if ((inst & 0xffbf0fff) == 0xec2d0200)    /* sfmfd fn, <cnt>, [sp]! */
1489         continue;
1490
1491       if ((inst & 0xffff8fff) == 0xed6d0103)    /* stfe fn, [sp, #-12]! */
1492         continue;
1493
1494       if ((inst & 0xfffff000) == 0xe24cb000)    /* sub fp, ip, #nn */
1495         continue;
1496
1497       if ((inst & 0xfffff000) == 0xe24dd000)    /* sub sp, sp, #nn */
1498         continue;
1499
1500       if ((inst & 0xffffc000) == 0xe54b0000     /* strb r(0123),[r11,#-nn] */
1501           || (inst & 0xffffc0f0) == 0xe14b00b0  /* strh r(0123),[r11,#-nn] */
1502           || (inst & 0xffffc000) == 0xe50b0000) /* str  r(0123),[r11,#-nn] */
1503         continue;
1504
1505       if ((inst & 0xffffc000) == 0xe5cd0000     /* strb r(0123),[sp,#nn] */
1506           || (inst & 0xffffc0f0) == 0xe1cd00b0  /* strh r(0123),[sp,#nn] */
1507           || (inst & 0xffffc000) == 0xe58d0000) /* str  r(0123),[sp,#nn] */
1508         continue;
1509
1510       /* Un-recognized instruction; stop scanning.  */
1511       break;
1512     }
1513
1514   return skip_pc;               /* End of prologue.  */
1515 }
1516
1517 /* *INDENT-OFF* */
1518 /* Function: thumb_scan_prologue (helper function for arm_scan_prologue)
1519    This function decodes a Thumb function prologue to determine:
1520      1) the size of the stack frame
1521      2) which registers are saved on it
1522      3) the offsets of saved regs
1523      4) the offset from the stack pointer to the frame pointer
1524
1525    A typical Thumb function prologue would create this stack frame
1526    (offsets relative to FP)
1527      old SP ->  24  stack parameters
1528                 20  LR
1529                 16  R7
1530      R7 ->       0  local variables (16 bytes)
1531      SP ->     -12  additional stack space (12 bytes)
1532    The frame size would thus be 36 bytes, and the frame offset would be
1533    12 bytes.  The frame register is R7.
1534    
1535    The comments for thumb_skip_prolog() describe the algorithm we use
1536    to detect the end of the prolog.  */
1537 /* *INDENT-ON* */
1538
1539 static void
1540 thumb_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR prev_pc,
1541                      CORE_ADDR block_addr, struct arm_prologue_cache *cache)
1542 {
1543   CORE_ADDR prologue_start;
1544   CORE_ADDR prologue_end;
1545
1546   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1547                                 &prologue_end))
1548     {
1549       /* See comment in arm_scan_prologue for an explanation of
1550          this heuristics.  */
1551       if (prologue_end > prologue_start + 64)
1552         {
1553           prologue_end = prologue_start + 64;
1554         }
1555     }
1556   else
1557     /* We're in the boondocks: we have no idea where the start of the
1558        function is.  */
1559     return;
1560
1561   prologue_end = min (prologue_end, prev_pc);
1562
1563   thumb_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
1564 }
1565
1566 /* Return 1 if THIS_INSTR might change control flow, 0 otherwise.  */
1567
1568 static int
1569 arm_instruction_changes_pc (uint32_t this_instr)
1570 {
1571   if (bits (this_instr, 28, 31) == INST_NV)
1572     /* Unconditional instructions.  */
1573     switch (bits (this_instr, 24, 27))
1574       {
1575       case 0xa:
1576       case 0xb:
1577         /* Branch with Link and change to Thumb.  */
1578         return 1;
1579       case 0xc:
1580       case 0xd:
1581       case 0xe:
1582         /* Coprocessor register transfer.  */
1583         if (bits (this_instr, 12, 15) == 15)
1584           error (_("Invalid update to pc in instruction"));
1585         return 0;
1586       default:
1587         return 0;
1588       }
1589   else
1590     switch (bits (this_instr, 25, 27))
1591       {
1592       case 0x0:
1593         if (bits (this_instr, 23, 24) == 2 && bit (this_instr, 20) == 0)
1594           {
1595             /* Multiplies and extra load/stores.  */
1596             if (bit (this_instr, 4) == 1 && bit (this_instr, 7) == 1)
1597               /* Neither multiplies nor extension load/stores are allowed
1598                  to modify PC.  */
1599               return 0;
1600
1601             /* Otherwise, miscellaneous instructions.  */
1602
1603             /* BX <reg>, BXJ <reg>, BLX <reg> */
1604             if (bits (this_instr, 4, 27) == 0x12fff1
1605                 || bits (this_instr, 4, 27) == 0x12fff2
1606                 || bits (this_instr, 4, 27) == 0x12fff3)
1607               return 1;
1608
1609             /* Other miscellaneous instructions are unpredictable if they
1610                modify PC.  */
1611             return 0;
1612           }
1613         /* Data processing instruction.  Fall through.  */
1614
1615       case 0x1:
1616         if (bits (this_instr, 12, 15) == 15)
1617           return 1;
1618         else
1619           return 0;
1620
1621       case 0x2:
1622       case 0x3:
1623         /* Media instructions and architecturally undefined instructions.  */
1624         if (bits (this_instr, 25, 27) == 3 && bit (this_instr, 4) == 1)
1625           return 0;
1626
1627         /* Stores.  */
1628         if (bit (this_instr, 20) == 0)
1629           return 0;
1630
1631         /* Loads.  */
1632         if (bits (this_instr, 12, 15) == ARM_PC_REGNUM)
1633           return 1;
1634         else
1635           return 0;
1636
1637       case 0x4:
1638         /* Load/store multiple.  */
1639         if (bit (this_instr, 20) == 1 && bit (this_instr, 15) == 1)
1640           return 1;
1641         else
1642           return 0;
1643
1644       case 0x5:
1645         /* Branch and branch with link.  */
1646         return 1;
1647
1648       case 0x6:
1649       case 0x7:
1650         /* Coprocessor transfers or SWIs can not affect PC.  */
1651         return 0;
1652
1653       default:
1654         internal_error (__FILE__, __LINE__, _("bad value in switch"));
1655       }
1656 }
1657
1658 /* Analyze an ARM mode prologue starting at PROLOGUE_START and
1659    continuing no further than PROLOGUE_END.  If CACHE is non-NULL,
1660    fill it in.  Return the first address not recognized as a prologue
1661    instruction.
1662
1663    We recognize all the instructions typically found in ARM prologues,
1664    plus harmless instructions which can be skipped (either for analysis
1665    purposes, or a more restrictive set that can be skipped when finding
1666    the end of the prologue).  */
1667
1668 static CORE_ADDR
1669 arm_analyze_prologue (struct gdbarch *gdbarch,
1670                       CORE_ADDR prologue_start, CORE_ADDR prologue_end,
1671                       struct arm_prologue_cache *cache)
1672 {
1673   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1674   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
1675   int regno;
1676   CORE_ADDR offset, current_pc;
1677   pv_t regs[ARM_FPS_REGNUM];
1678   struct pv_area *stack;
1679   struct cleanup *back_to;
1680   int framereg, framesize;
1681   CORE_ADDR unrecognized_pc = 0;
1682
1683   /* Search the prologue looking for instructions that set up the
1684      frame pointer, adjust the stack pointer, and save registers.
1685
1686      Be careful, however, and if it doesn't look like a prologue,
1687      don't try to scan it.  If, for instance, a frameless function
1688      begins with stmfd sp!, then we will tell ourselves there is
1689      a frame, which will confuse stack traceback, as well as "finish" 
1690      and other operations that rely on a knowledge of the stack
1691      traceback.  */
1692
1693   for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1694     regs[regno] = pv_register (regno, 0);
1695   stack = make_pv_area (ARM_SP_REGNUM, gdbarch_addr_bit (gdbarch));
1696   back_to = make_cleanup_free_pv_area (stack);
1697
1698   for (current_pc = prologue_start;
1699        current_pc < prologue_end;
1700        current_pc += 4)
1701     {
1702       unsigned int insn
1703         = read_memory_unsigned_integer (current_pc, 4, byte_order_for_code);
1704
1705       if (insn == 0xe1a0c00d)           /* mov ip, sp */
1706         {
1707           regs[ARM_IP_REGNUM] = regs[ARM_SP_REGNUM];
1708           continue;
1709         }
1710       else if ((insn & 0xfff00000) == 0xe2800000        /* add Rd, Rn, #n */
1711                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1712         {
1713           unsigned imm = insn & 0xff;                   /* immediate value */
1714           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1715           int rd = bits (insn, 12, 15);
1716           imm = (imm >> rot) | (imm << (32 - rot));
1717           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], imm);
1718           continue;
1719         }
1720       else if ((insn & 0xfff00000) == 0xe2400000        /* sub Rd, Rn, #n */
1721                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1722         {
1723           unsigned imm = insn & 0xff;                   /* immediate value */
1724           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1725           int rd = bits (insn, 12, 15);
1726           imm = (imm >> rot) | (imm << (32 - rot));
1727           regs[rd] = pv_add_constant (regs[bits (insn, 16, 19)], -imm);
1728           continue;
1729         }
1730       else if ((insn & 0xffff0fff) == 0xe52d0004)       /* str Rd,
1731                                                            [sp, #-4]! */
1732         {
1733           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1734             break;
1735           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1736           pv_area_store (stack, regs[ARM_SP_REGNUM], 4,
1737                          regs[bits (insn, 12, 15)]);
1738           continue;
1739         }
1740       else if ((insn & 0xffff0000) == 0xe92d0000)
1741         /* stmfd sp!, {..., fp, ip, lr, pc}
1742            or
1743            stmfd sp!, {a1, a2, a3, a4}  */
1744         {
1745           int mask = insn & 0xffff;
1746
1747           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1748             break;
1749
1750           /* Calculate offsets of saved registers.  */
1751           for (regno = ARM_PC_REGNUM; regno >= 0; regno--)
1752             if (mask & (1 << regno))
1753               {
1754                 regs[ARM_SP_REGNUM]
1755                   = pv_add_constant (regs[ARM_SP_REGNUM], -4);
1756                 pv_area_store (stack, regs[ARM_SP_REGNUM], 4, regs[regno]);
1757               }
1758         }
1759       else if ((insn & 0xffff0000) == 0xe54b0000        /* strb rx,[r11,#-n] */
1760                || (insn & 0xffff00f0) == 0xe14b00b0     /* strh rx,[r11,#-n] */
1761                || (insn & 0xffffc000) == 0xe50b0000)    /* str  rx,[r11,#-n] */
1762         {
1763           /* No need to add this to saved_regs -- it's just an arg reg.  */
1764           continue;
1765         }
1766       else if ((insn & 0xffff0000) == 0xe5cd0000        /* strb rx,[sp,#n] */
1767                || (insn & 0xffff00f0) == 0xe1cd00b0     /* strh rx,[sp,#n] */
1768                || (insn & 0xffffc000) == 0xe58d0000)    /* str  rx,[sp,#n] */
1769         {
1770           /* No need to add this to saved_regs -- it's just an arg reg.  */
1771           continue;
1772         }
1773       else if ((insn & 0xfff00000) == 0xe8800000        /* stm Rn,
1774                                                            { registers } */
1775                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1776         {
1777           /* No need to add this to saved_regs -- it's just arg regs.  */
1778           continue;
1779         }
1780       else if ((insn & 0xfffff000) == 0xe24cb000)       /* sub fp, ip #n */
1781         {
1782           unsigned imm = insn & 0xff;                   /* immediate value */
1783           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1784           imm = (imm >> rot) | (imm << (32 - rot));
1785           regs[ARM_FP_REGNUM] = pv_add_constant (regs[ARM_IP_REGNUM], -imm);
1786         }
1787       else if ((insn & 0xfffff000) == 0xe24dd000)       /* sub sp, sp #n */
1788         {
1789           unsigned imm = insn & 0xff;                   /* immediate value */
1790           unsigned rot = (insn & 0xf00) >> 7;           /* rotate amount */
1791           imm = (imm >> rot) | (imm << (32 - rot));
1792           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -imm);
1793         }
1794       else if ((insn & 0xffff7fff) == 0xed6d0103        /* stfe f?,
1795                                                            [sp, -#c]! */
1796                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1797         {
1798           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1799             break;
1800
1801           regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1802           regno = ARM_F0_REGNUM + ((insn >> 12) & 0x07);
1803           pv_area_store (stack, regs[ARM_SP_REGNUM], 12, regs[regno]);
1804         }
1805       else if ((insn & 0xffbf0fff) == 0xec2d0200        /* sfmfd f0, 4,
1806                                                            [sp!] */
1807                && gdbarch_tdep (gdbarch)->have_fpa_registers)
1808         {
1809           int n_saved_fp_regs;
1810           unsigned int fp_start_reg, fp_bound_reg;
1811
1812           if (pv_area_store_would_trash (stack, regs[ARM_SP_REGNUM]))
1813             break;
1814
1815           if ((insn & 0x800) == 0x800)          /* N0 is set */
1816             {
1817               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1818                 n_saved_fp_regs = 3;
1819               else
1820                 n_saved_fp_regs = 1;
1821             }
1822           else
1823             {
1824               if ((insn & 0x40000) == 0x40000)  /* N1 is set */
1825                 n_saved_fp_regs = 2;
1826               else
1827                 n_saved_fp_regs = 4;
1828             }
1829
1830           fp_start_reg = ARM_F0_REGNUM + ((insn >> 12) & 0x7);
1831           fp_bound_reg = fp_start_reg + n_saved_fp_regs;
1832           for (; fp_start_reg < fp_bound_reg; fp_start_reg++)
1833             {
1834               regs[ARM_SP_REGNUM] = pv_add_constant (regs[ARM_SP_REGNUM], -12);
1835               pv_area_store (stack, regs[ARM_SP_REGNUM], 12,
1836                              regs[fp_start_reg++]);
1837             }
1838         }
1839       else if ((insn & 0xff000000) == 0xeb000000 && cache == NULL) /* bl */
1840         {
1841           /* Allow some special function calls when skipping the
1842              prologue; GCC generates these before storing arguments to
1843              the stack.  */
1844           CORE_ADDR dest = BranchDest (current_pc, insn);
1845
1846           if (skip_prologue_function (gdbarch, dest, 0))
1847             continue;
1848           else
1849             break;
1850         }
1851       else if ((insn & 0xf0000000) != 0xe0000000)
1852         break;                  /* Condition not true, exit early.  */
1853       else if (arm_instruction_changes_pc (insn))
1854         /* Don't scan past anything that might change control flow.  */
1855         break;
1856       else if ((insn & 0xfe500000) == 0xe8100000        /* ldm */
1857                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1858         /* Ignore block loads from the stack, potentially copying
1859            parameters from memory.  */
1860         continue;
1861       else if ((insn & 0xfc500000) == 0xe4100000
1862                && pv_is_register (regs[bits (insn, 16, 19)], ARM_SP_REGNUM))
1863         /* Similarly ignore single loads from the stack.  */
1864         continue;
1865       else if ((insn & 0xffff0ff0) == 0xe1a00000)
1866         /* MOV Rd, Rm.  Skip register copies, i.e. saves to another
1867            register instead of the stack.  */
1868         continue;
1869       else
1870         {
1871           /* The optimizer might shove anything into the prologue,
1872              so we just skip what we don't recognize.  */
1873           unrecognized_pc = current_pc;
1874           continue;
1875         }
1876     }
1877
1878   if (unrecognized_pc == 0)
1879     unrecognized_pc = current_pc;
1880
1881   /* The frame size is just the distance from the frame register
1882      to the original stack pointer.  */
1883   if (pv_is_register (regs[ARM_FP_REGNUM], ARM_SP_REGNUM))
1884     {
1885       /* Frame pointer is fp.  */
1886       framereg = ARM_FP_REGNUM;
1887       framesize = -regs[ARM_FP_REGNUM].k;
1888     }
1889   else
1890     {
1891       /* Try the stack pointer... this is a bit desperate.  */
1892       framereg = ARM_SP_REGNUM;
1893       framesize = -regs[ARM_SP_REGNUM].k;
1894     }
1895
1896   if (cache)
1897     {
1898       cache->framereg = framereg;
1899       cache->framesize = framesize;
1900
1901       for (regno = 0; regno < ARM_FPS_REGNUM; regno++)
1902         if (pv_area_find_reg (stack, gdbarch, regno, &offset))
1903           cache->saved_regs[regno].addr = offset;
1904     }
1905
1906   if (arm_debug)
1907     fprintf_unfiltered (gdb_stdlog, "Prologue scan stopped at %s\n",
1908                         paddress (gdbarch, unrecognized_pc));
1909
1910   do_cleanups (back_to);
1911   return unrecognized_pc;
1912 }
1913
1914 static void
1915 arm_scan_prologue (struct frame_info *this_frame,
1916                    struct arm_prologue_cache *cache)
1917 {
1918   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1919   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1920   int regno;
1921   CORE_ADDR prologue_start, prologue_end, current_pc;
1922   CORE_ADDR prev_pc = get_frame_pc (this_frame);
1923   CORE_ADDR block_addr = get_frame_address_in_block (this_frame);
1924   pv_t regs[ARM_FPS_REGNUM];
1925   struct pv_area *stack;
1926   struct cleanup *back_to;
1927   CORE_ADDR offset;
1928
1929   /* Assume there is no frame until proven otherwise.  */
1930   cache->framereg = ARM_SP_REGNUM;
1931   cache->framesize = 0;
1932
1933   /* Check for Thumb prologue.  */
1934   if (arm_frame_is_thumb (this_frame))
1935     {
1936       thumb_scan_prologue (gdbarch, prev_pc, block_addr, cache);
1937       return;
1938     }
1939
1940   /* Find the function prologue.  If we can't find the function in
1941      the symbol table, peek in the stack frame to find the PC.  */
1942   if (find_pc_partial_function (block_addr, NULL, &prologue_start,
1943                                 &prologue_end))
1944     {
1945       /* One way to find the end of the prologue (which works well
1946          for unoptimized code) is to do the following:
1947
1948             struct symtab_and_line sal = find_pc_line (prologue_start, 0);
1949
1950             if (sal.line == 0)
1951               prologue_end = prev_pc;
1952             else if (sal.end < prologue_end)
1953               prologue_end = sal.end;
1954
1955          This mechanism is very accurate so long as the optimizer
1956          doesn't move any instructions from the function body into the
1957          prologue.  If this happens, sal.end will be the last
1958          instruction in the first hunk of prologue code just before
1959          the first instruction that the scheduler has moved from
1960          the body to the prologue.
1961
1962          In order to make sure that we scan all of the prologue
1963          instructions, we use a slightly less accurate mechanism which
1964          may scan more than necessary.  To help compensate for this
1965          lack of accuracy, the prologue scanning loop below contains
1966          several clauses which'll cause the loop to terminate early if
1967          an implausible prologue instruction is encountered.
1968
1969          The expression
1970
1971               prologue_start + 64
1972
1973          is a suitable endpoint since it accounts for the largest
1974          possible prologue plus up to five instructions inserted by
1975          the scheduler.  */
1976
1977       if (prologue_end > prologue_start + 64)
1978         {
1979           prologue_end = prologue_start + 64;   /* See above.  */
1980         }
1981     }
1982   else
1983     {
1984       /* We have no symbol information.  Our only option is to assume this
1985          function has a standard stack frame and the normal frame register.
1986          Then, we can find the value of our frame pointer on entrance to
1987          the callee (or at the present moment if this is the innermost frame).
1988          The value stored there should be the address of the stmfd + 8.  */
1989       CORE_ADDR frame_loc;
1990       LONGEST return_value;
1991
1992       frame_loc = get_frame_register_unsigned (this_frame, ARM_FP_REGNUM);
1993       if (!safe_read_memory_integer (frame_loc, 4, byte_order, &return_value))
1994         return;
1995       else
1996         {
1997           prologue_start = gdbarch_addr_bits_remove
1998                              (gdbarch, return_value) - 8;
1999           prologue_end = prologue_start + 64;   /* See above.  */
2000         }
2001     }
2002
2003   if (prev_pc < prologue_end)
2004     prologue_end = prev_pc;
2005
2006   arm_analyze_prologue (gdbarch, prologue_start, prologue_end, cache);
2007 }
2008
2009 static struct arm_prologue_cache *
2010 arm_make_prologue_cache (struct frame_info *this_frame)
2011 {
2012   int reg;
2013   struct arm_prologue_cache *cache;
2014   CORE_ADDR unwound_fp;
2015
2016   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2017   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2018
2019   arm_scan_prologue (this_frame, cache);
2020
2021   unwound_fp = get_frame_register_unsigned (this_frame, cache->framereg);
2022   if (unwound_fp == 0)
2023     return cache;
2024
2025   cache->prev_sp = unwound_fp + cache->framesize;
2026
2027   /* Calculate actual addresses of saved registers using offsets
2028      determined by arm_scan_prologue.  */
2029   for (reg = 0; reg < gdbarch_num_regs (get_frame_arch (this_frame)); reg++)
2030     if (trad_frame_addr_p (cache->saved_regs, reg))
2031       cache->saved_regs[reg].addr += cache->prev_sp;
2032
2033   return cache;
2034 }
2035
2036 /* Our frame ID for a normal frame is the current function's starting PC
2037    and the caller's SP when we were called.  */
2038
2039 static void
2040 arm_prologue_this_id (struct frame_info *this_frame,
2041                       void **this_cache,
2042                       struct frame_id *this_id)
2043 {
2044   struct arm_prologue_cache *cache;
2045   struct frame_id id;
2046   CORE_ADDR pc, func;
2047
2048   if (*this_cache == NULL)
2049     *this_cache = arm_make_prologue_cache (this_frame);
2050   cache = *this_cache;
2051
2052   /* This is meant to halt the backtrace at "_start".  */
2053   pc = get_frame_pc (this_frame);
2054   if (pc <= gdbarch_tdep (get_frame_arch (this_frame))->lowest_pc)
2055     return;
2056
2057   /* If we've hit a wall, stop.  */
2058   if (cache->prev_sp == 0)
2059     return;
2060
2061   /* Use function start address as part of the frame ID.  If we cannot
2062      identify the start address (due to missing symbol information),
2063      fall back to just using the current PC.  */
2064   func = get_frame_func (this_frame);
2065   if (!func)
2066     func = pc;
2067
2068   id = frame_id_build (cache->prev_sp, func);
2069   *this_id = id;
2070 }
2071
2072 static struct value *
2073 arm_prologue_prev_register (struct frame_info *this_frame,
2074                             void **this_cache,
2075                             int prev_regnum)
2076 {
2077   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2078   struct arm_prologue_cache *cache;
2079
2080   if (*this_cache == NULL)
2081     *this_cache = arm_make_prologue_cache (this_frame);
2082   cache = *this_cache;
2083
2084   /* If we are asked to unwind the PC, then we need to return the LR
2085      instead.  The prologue may save PC, but it will point into this
2086      frame's prologue, not the next frame's resume location.  Also
2087      strip the saved T bit.  A valid LR may have the low bit set, but
2088      a valid PC never does.  */
2089   if (prev_regnum == ARM_PC_REGNUM)
2090     {
2091       CORE_ADDR lr;
2092
2093       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2094       return frame_unwind_got_constant (this_frame, prev_regnum,
2095                                         arm_addr_bits_remove (gdbarch, lr));
2096     }
2097
2098   /* SP is generally not saved to the stack, but this frame is
2099      identified by the next frame's stack pointer at the time of the call.
2100      The value was already reconstructed into PREV_SP.  */
2101   if (prev_regnum == ARM_SP_REGNUM)
2102     return frame_unwind_got_constant (this_frame, prev_regnum, cache->prev_sp);
2103
2104   /* The CPSR may have been changed by the call instruction and by the
2105      called function.  The only bit we can reconstruct is the T bit,
2106      by checking the low bit of LR as of the call.  This is a reliable
2107      indicator of Thumb-ness except for some ARM v4T pre-interworking
2108      Thumb code, which could get away with a clear low bit as long as
2109      the called function did not use bx.  Guess that all other
2110      bits are unchanged; the condition flags are presumably lost,
2111      but the processor status is likely valid.  */
2112   if (prev_regnum == ARM_PS_REGNUM)
2113     {
2114       CORE_ADDR lr, cpsr;
2115       ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
2116
2117       cpsr = get_frame_register_unsigned (this_frame, prev_regnum);
2118       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
2119       if (IS_THUMB_ADDR (lr))
2120         cpsr |= t_bit;
2121       else
2122         cpsr &= ~t_bit;
2123       return frame_unwind_got_constant (this_frame, prev_regnum, cpsr);
2124     }
2125
2126   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
2127                                        prev_regnum);
2128 }
2129
2130 struct frame_unwind arm_prologue_unwind = {
2131   NORMAL_FRAME,
2132   default_frame_unwind_stop_reason,
2133   arm_prologue_this_id,
2134   arm_prologue_prev_register,
2135   NULL,
2136   default_frame_sniffer
2137 };
2138
2139 /* Maintain a list of ARM exception table entries per objfile, similar to the
2140    list of mapping symbols.  We only cache entries for standard ARM-defined
2141    personality routines; the cache will contain only the frame unwinding
2142    instructions associated with the entry (not the descriptors).  */
2143
2144 static const struct objfile_data *arm_exidx_data_key;
2145
2146 struct arm_exidx_entry
2147 {
2148   bfd_vma addr;
2149   gdb_byte *entry;
2150 };
2151 typedef struct arm_exidx_entry arm_exidx_entry_s;
2152 DEF_VEC_O(arm_exidx_entry_s);
2153
2154 struct arm_exidx_data
2155 {
2156   VEC(arm_exidx_entry_s) **section_maps;
2157 };
2158
2159 static void
2160 arm_exidx_data_free (struct objfile *objfile, void *arg)
2161 {
2162   struct arm_exidx_data *data = arg;
2163   unsigned int i;
2164
2165   for (i = 0; i < objfile->obfd->section_count; i++)
2166     VEC_free (arm_exidx_entry_s, data->section_maps[i]);
2167 }
2168
2169 static inline int
2170 arm_compare_exidx_entries (const struct arm_exidx_entry *lhs,
2171                            const struct arm_exidx_entry *rhs)
2172 {
2173   return lhs->addr < rhs->addr;
2174 }
2175
2176 static struct obj_section *
2177 arm_obj_section_from_vma (struct objfile *objfile, bfd_vma vma)
2178 {
2179   struct obj_section *osect;
2180
2181   ALL_OBJFILE_OSECTIONS (objfile, osect)
2182     if (bfd_get_section_flags (objfile->obfd,
2183                                osect->the_bfd_section) & SEC_ALLOC)
2184       {
2185         bfd_vma start, size;
2186         start = bfd_get_section_vma (objfile->obfd, osect->the_bfd_section);
2187         size = bfd_get_section_size (osect->the_bfd_section);
2188
2189         if (start <= vma && vma < start + size)
2190           return osect;
2191       }
2192
2193   return NULL;
2194 }
2195
2196 /* Parse contents of exception table and exception index sections
2197    of OBJFILE, and fill in the exception table entry cache.
2198
2199    For each entry that refers to a standard ARM-defined personality
2200    routine, extract the frame unwinding instructions (from either
2201    the index or the table section).  The unwinding instructions
2202    are normalized by:
2203     - extracting them from the rest of the table data
2204     - converting to host endianness
2205     - appending the implicit 0xb0 ("Finish") code
2206
2207    The extracted and normalized instructions are stored for later
2208    retrieval by the arm_find_exidx_entry routine.  */
2209  
2210 static void
2211 arm_exidx_new_objfile (struct objfile *objfile)
2212 {
2213   struct cleanup *cleanups;
2214   struct arm_exidx_data *data;
2215   asection *exidx, *extab;
2216   bfd_vma exidx_vma = 0, extab_vma = 0;
2217   bfd_size_type exidx_size = 0, extab_size = 0;
2218   gdb_byte *exidx_data = NULL, *extab_data = NULL;
2219   LONGEST i;
2220
2221   /* If we've already touched this file, do nothing.  */
2222   if (!objfile || objfile_data (objfile, arm_exidx_data_key) != NULL)
2223     return;
2224   cleanups = make_cleanup (null_cleanup, NULL);
2225
2226   /* Read contents of exception table and index.  */
2227   exidx = bfd_get_section_by_name (objfile->obfd, ".ARM.exidx");
2228   if (exidx)
2229     {
2230       exidx_vma = bfd_section_vma (objfile->obfd, exidx);
2231       exidx_size = bfd_get_section_size (exidx);
2232       exidx_data = xmalloc (exidx_size);
2233       make_cleanup (xfree, exidx_data);
2234
2235       if (!bfd_get_section_contents (objfile->obfd, exidx,
2236                                      exidx_data, 0, exidx_size))
2237         {
2238           do_cleanups (cleanups);
2239           return;
2240         }
2241     }
2242
2243   extab = bfd_get_section_by_name (objfile->obfd, ".ARM.extab");
2244   if (extab)
2245     {
2246       extab_vma = bfd_section_vma (objfile->obfd, extab);
2247       extab_size = bfd_get_section_size (extab);
2248       extab_data = xmalloc (extab_size);
2249       make_cleanup (xfree, extab_data);
2250
2251       if (!bfd_get_section_contents (objfile->obfd, extab,
2252                                      extab_data, 0, extab_size))
2253         {
2254           do_cleanups (cleanups);
2255           return;
2256         }
2257     }
2258
2259   /* Allocate exception table data structure.  */
2260   data = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct arm_exidx_data);
2261   set_objfile_data (objfile, arm_exidx_data_key, data);
2262   data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
2263                                        objfile->obfd->section_count,
2264                                        VEC(arm_exidx_entry_s) *);
2265
2266   /* Fill in exception table.  */
2267   for (i = 0; i < exidx_size / 8; i++)
2268     {
2269       struct arm_exidx_entry new_exidx_entry;
2270       bfd_vma idx = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8);
2271       bfd_vma val = bfd_h_get_32 (objfile->obfd, exidx_data + i * 8 + 4);
2272       bfd_vma addr = 0, word = 0;
2273       int n_bytes = 0, n_words = 0;
2274       struct obj_section *sec;
2275       gdb_byte *entry = NULL;
2276
2277       /* Extract address of start of function.  */
2278       idx = ((idx & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2279       idx += exidx_vma + i * 8;
2280
2281       /* Find section containing function and compute section offset.  */
2282       sec = arm_obj_section_from_vma (objfile, idx);
2283       if (sec == NULL)
2284         continue;
2285       idx -= bfd_get_section_vma (objfile->obfd, sec->the_bfd_section);
2286
2287       /* Determine address of exception table entry.  */
2288       if (val == 1)
2289         {
2290           /* EXIDX_CANTUNWIND -- no exception table entry present.  */
2291         }
2292       else if ((val & 0xff000000) == 0x80000000)
2293         {
2294           /* Exception table entry embedded in .ARM.exidx
2295              -- must be short form.  */
2296           word = val;
2297           n_bytes = 3;
2298         }
2299       else if (!(val & 0x80000000))
2300         {
2301           /* Exception table entry in .ARM.extab.  */
2302           addr = ((val & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2303           addr += exidx_vma + i * 8 + 4;
2304
2305           if (addr >= extab_vma && addr + 4 <= extab_vma + extab_size)
2306             {
2307               word = bfd_h_get_32 (objfile->obfd,
2308                                    extab_data + addr - extab_vma);
2309               addr += 4;
2310
2311               if ((word & 0xff000000) == 0x80000000)
2312                 {
2313                   /* Short form.  */
2314                   n_bytes = 3;
2315                 }
2316               else if ((word & 0xff000000) == 0x81000000
2317                        || (word & 0xff000000) == 0x82000000)
2318                 {
2319                   /* Long form.  */
2320                   n_bytes = 2;
2321                   n_words = ((word >> 16) & 0xff);
2322                 }
2323               else if (!(word & 0x80000000))
2324                 {
2325                   bfd_vma pers;
2326                   struct obj_section *pers_sec;
2327                   int gnu_personality = 0;
2328
2329                   /* Custom personality routine.  */
2330                   pers = ((word & 0x7fffffff) ^ 0x40000000) - 0x40000000;
2331                   pers = UNMAKE_THUMB_ADDR (pers + addr - 4);
2332
2333                   /* Check whether we've got one of the variants of the
2334                      GNU personality routines.  */
2335                   pers_sec = arm_obj_section_from_vma (objfile, pers);
2336                   if (pers_sec)
2337                     {
2338                       static const char *personality[] = 
2339                         {
2340                           "__gcc_personality_v0",
2341                           "__gxx_personality_v0",
2342                           "__gcj_personality_v0",
2343                           "__gnu_objc_personality_v0",
2344                           NULL
2345                         };
2346
2347                       CORE_ADDR pc = pers + obj_section_offset (pers_sec);
2348                       int k;
2349
2350                       for (k = 0; personality[k]; k++)
2351                         if (lookup_minimal_symbol_by_pc_name
2352                               (pc, personality[k], objfile))
2353                           {
2354                             gnu_personality = 1;
2355                             break;
2356                           }
2357                     }
2358
2359                   /* If so, the next word contains a word count in the high
2360                      byte, followed by the same unwind instructions as the
2361                      pre-defined forms.  */
2362                   if (gnu_personality
2363                       && addr + 4 <= extab_vma + extab_size)
2364                     {
2365                       word = bfd_h_get_32 (objfile->obfd,
2366                                            extab_data + addr - extab_vma);
2367                       addr += 4;
2368                       n_bytes = 3;
2369                       n_words = ((word >> 24) & 0xff);
2370                     }
2371                 }
2372             }
2373         }
2374
2375       /* Sanity check address.  */
2376       if (n_words)
2377         if (addr < extab_vma || addr + 4 * n_words > extab_vma + extab_size)
2378           n_words = n_bytes = 0;
2379
2380       /* The unwind instructions reside in WORD (only the N_BYTES least
2381          significant bytes are valid), followed by N_WORDS words in the
2382          extab section starting at ADDR.  */
2383       if (n_bytes || n_words)
2384         {
2385           gdb_byte *p = entry = obstack_alloc (&objfile->objfile_obstack,
2386                                                n_bytes + n_words * 4 + 1);
2387
2388           while (n_bytes--)
2389             *p++ = (gdb_byte) ((word >> (8 * n_bytes)) & 0xff);
2390
2391           while (n_words--)
2392             {
2393               word = bfd_h_get_32 (objfile->obfd,
2394                                    extab_data + addr - extab_vma);
2395               addr += 4;
2396
2397               *p++ = (gdb_byte) ((word >> 24) & 0xff);
2398               *p++ = (gdb_byte) ((word >> 16) & 0xff);
2399               *p++ = (gdb_byte) ((word >> 8) & 0xff);
2400               *p++ = (gdb_byte) (word & 0xff);
2401             }
2402
2403           /* Implied "Finish" to terminate the list.  */
2404           *p++ = 0xb0;
2405         }
2406
2407       /* Push entry onto vector.  They are guaranteed to always
2408          appear in order of increasing addresses.  */
2409       new_exidx_entry.addr = idx;
2410       new_exidx_entry.entry = entry;
2411       VEC_safe_push (arm_exidx_entry_s,
2412                      data->section_maps[sec->the_bfd_section->index],
2413                      &new_exidx_entry);
2414     }
2415
2416   do_cleanups (cleanups);
2417 }
2418
2419 /* Search for the exception table entry covering MEMADDR.  If one is found,
2420    return a pointer to its data.  Otherwise, return 0.  If START is non-NULL,
2421    set *START to the start of the region covered by this entry.  */
2422
2423 static gdb_byte *
2424 arm_find_exidx_entry (CORE_ADDR memaddr, CORE_ADDR *start)
2425 {
2426   struct obj_section *sec;
2427
2428   sec = find_pc_section (memaddr);
2429   if (sec != NULL)
2430     {
2431       struct arm_exidx_data *data;
2432       VEC(arm_exidx_entry_s) *map;
2433       struct arm_exidx_entry map_key = { memaddr - obj_section_addr (sec), 0 };
2434       unsigned int idx;
2435
2436       data = objfile_data (sec->objfile, arm_exidx_data_key);
2437       if (data != NULL)
2438         {
2439           map = data->section_maps[sec->the_bfd_section->index];
2440           if (!VEC_empty (arm_exidx_entry_s, map))
2441             {
2442               struct arm_exidx_entry *map_sym;
2443
2444               idx = VEC_lower_bound (arm_exidx_entry_s, map, &map_key,
2445                                      arm_compare_exidx_entries);
2446
2447               /* VEC_lower_bound finds the earliest ordered insertion
2448                  point.  If the following symbol starts at this exact
2449                  address, we use that; otherwise, the preceding
2450                  exception table entry covers this address.  */
2451               if (idx < VEC_length (arm_exidx_entry_s, map))
2452                 {
2453                   map_sym = VEC_index (arm_exidx_entry_s, map, idx);
2454                   if (map_sym->addr == map_key.addr)
2455                     {
2456                       if (start)
2457                         *start = map_sym->addr + obj_section_addr (sec);
2458                       return map_sym->entry;
2459                     }
2460                 }
2461
2462               if (idx > 0)
2463                 {
2464                   map_sym = VEC_index (arm_exidx_entry_s, map, idx - 1);
2465                   if (start)
2466                     *start = map_sym->addr + obj_section_addr (sec);
2467                   return map_sym->entry;
2468                 }
2469             }
2470         }
2471     }
2472
2473   return NULL;
2474 }
2475
2476 /* Given the current frame THIS_FRAME, and its associated frame unwinding
2477    instruction list from the ARM exception table entry ENTRY, allocate and
2478    return a prologue cache structure describing how to unwind this frame.
2479
2480    Return NULL if the unwinding instruction list contains a "spare",
2481    "reserved" or "refuse to unwind" instruction as defined in section
2482    "9.3 Frame unwinding instructions" of the "Exception Handling ABI
2483    for the ARM Architecture" document.  */
2484
2485 static struct arm_prologue_cache *
2486 arm_exidx_fill_cache (struct frame_info *this_frame, gdb_byte *entry)
2487 {
2488   CORE_ADDR vsp = 0;
2489   int vsp_valid = 0;
2490
2491   struct arm_prologue_cache *cache;
2492   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2493   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2494
2495   for (;;)
2496     {
2497       gdb_byte insn;
2498
2499       /* Whenever we reload SP, we actually have to retrieve its
2500          actual value in the current frame.  */
2501       if (!vsp_valid)
2502         {
2503           if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2504             {
2505               int reg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2506               vsp = get_frame_register_unsigned (this_frame, reg);
2507             }
2508           else
2509             {
2510               CORE_ADDR addr = cache->saved_regs[ARM_SP_REGNUM].addr;
2511               vsp = get_frame_memory_unsigned (this_frame, addr, 4);
2512             }
2513
2514           vsp_valid = 1;
2515         }
2516
2517       /* Decode next unwind instruction.  */
2518       insn = *entry++;
2519
2520       if ((insn & 0xc0) == 0)
2521         {
2522           int offset = insn & 0x3f;
2523           vsp += (offset << 2) + 4;
2524         }
2525       else if ((insn & 0xc0) == 0x40)
2526         {
2527           int offset = insn & 0x3f;
2528           vsp -= (offset << 2) + 4;
2529         }
2530       else if ((insn & 0xf0) == 0x80)
2531         {
2532           int mask = ((insn & 0xf) << 8) | *entry++;
2533           int i;
2534
2535           /* The special case of an all-zero mask identifies
2536              "Refuse to unwind".  We return NULL to fall back
2537              to the prologue analyzer.  */
2538           if (mask == 0)
2539             return NULL;
2540
2541           /* Pop registers r4..r15 under mask.  */
2542           for (i = 0; i < 12; i++)
2543             if (mask & (1 << i))
2544               {
2545                 cache->saved_regs[4 + i].addr = vsp;
2546                 vsp += 4;
2547               }
2548
2549           /* Special-case popping SP -- we need to reload vsp.  */
2550           if (mask & (1 << (ARM_SP_REGNUM - 4)))
2551             vsp_valid = 0;
2552         }
2553       else if ((insn & 0xf0) == 0x90)
2554         {
2555           int reg = insn & 0xf;
2556
2557           /* Reserved cases.  */
2558           if (reg == ARM_SP_REGNUM || reg == ARM_PC_REGNUM)
2559             return NULL;
2560
2561           /* Set SP from another register and mark VSP for reload.  */
2562           cache->saved_regs[ARM_SP_REGNUM] = cache->saved_regs[reg];
2563           vsp_valid = 0;
2564         }
2565       else if ((insn & 0xf0) == 0xa0)
2566         {
2567           int count = insn & 0x7;
2568           int pop_lr = (insn & 0x8) != 0;
2569           int i;
2570
2571           /* Pop r4..r[4+count].  */
2572           for (i = 0; i <= count; i++)
2573             {
2574               cache->saved_regs[4 + i].addr = vsp;
2575               vsp += 4;
2576             }
2577
2578           /* If indicated by flag, pop LR as well.  */
2579           if (pop_lr)
2580             {
2581               cache->saved_regs[ARM_LR_REGNUM].addr = vsp;
2582               vsp += 4;
2583             }
2584         }
2585       else if (insn == 0xb0)
2586         {
2587           /* We could only have updated PC by popping into it; if so, it
2588              will show up as address.  Otherwise, copy LR into PC.  */
2589           if (!trad_frame_addr_p (cache->saved_regs, ARM_PC_REGNUM))
2590             cache->saved_regs[ARM_PC_REGNUM]
2591               = cache->saved_regs[ARM_LR_REGNUM];
2592
2593           /* We're done.  */
2594           break;
2595         }
2596       else if (insn == 0xb1)
2597         {
2598           int mask = *entry++;
2599           int i;
2600
2601           /* All-zero mask and mask >= 16 is "spare".  */
2602           if (mask == 0 || mask >= 16)
2603             return NULL;
2604
2605           /* Pop r0..r3 under mask.  */
2606           for (i = 0; i < 4; i++)
2607             if (mask & (1 << i))
2608               {
2609                 cache->saved_regs[i].addr = vsp;
2610                 vsp += 4;
2611               }
2612         }
2613       else if (insn == 0xb2)
2614         {
2615           ULONGEST offset = 0;
2616           unsigned shift = 0;
2617
2618           do
2619             {
2620               offset |= (*entry & 0x7f) << shift;
2621               shift += 7;
2622             }
2623           while (*entry++ & 0x80);
2624
2625           vsp += 0x204 + (offset << 2);
2626         }
2627       else if (insn == 0xb3)
2628         {
2629           int start = *entry >> 4;
2630           int count = (*entry++) & 0xf;
2631           int i;
2632
2633           /* Only registers D0..D15 are valid here.  */
2634           if (start + count >= 16)
2635             return NULL;
2636
2637           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2638           for (i = 0; i <= count; i++)
2639             {
2640               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2641               vsp += 8;
2642             }
2643
2644           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2645           vsp += 4;
2646         }
2647       else if ((insn & 0xf8) == 0xb8)
2648         {
2649           int count = insn & 0x7;
2650           int i;
2651
2652           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2653           for (i = 0; i <= count; i++)
2654             {
2655               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2656               vsp += 8;
2657             }
2658
2659           /* Add an extra 4 bytes for FSTMFDX-style stack.  */
2660           vsp += 4;
2661         }
2662       else if (insn == 0xc6)
2663         {
2664           int start = *entry >> 4;
2665           int count = (*entry++) & 0xf;
2666           int i;
2667
2668           /* Only registers WR0..WR15 are valid.  */
2669           if (start + count >= 16)
2670             return NULL;
2671
2672           /* Pop iwmmx registers WR[start]..WR[start+count].  */
2673           for (i = 0; i <= count; i++)
2674             {
2675               cache->saved_regs[ARM_WR0_REGNUM + start + i].addr = vsp;
2676               vsp += 8;
2677             }
2678         }
2679       else if (insn == 0xc7)
2680         {
2681           int mask = *entry++;
2682           int i;
2683
2684           /* All-zero mask and mask >= 16 is "spare".  */
2685           if (mask == 0 || mask >= 16)
2686             return NULL;
2687
2688           /* Pop iwmmx general-purpose registers WCGR0..WCGR3 under mask.  */
2689           for (i = 0; i < 4; i++)
2690             if (mask & (1 << i))
2691               {
2692                 cache->saved_regs[ARM_WCGR0_REGNUM + i].addr = vsp;
2693                 vsp += 4;
2694               }
2695         }
2696       else if ((insn & 0xf8) == 0xc0)
2697         {
2698           int count = insn & 0x7;
2699           int i;
2700
2701           /* Pop iwmmx registers WR[10]..WR[10+count].  */
2702           for (i = 0; i <= count; i++)
2703             {
2704               cache->saved_regs[ARM_WR0_REGNUM + 10 + i].addr = vsp;
2705               vsp += 8;
2706             }
2707         }
2708       else if (insn == 0xc8)
2709         {
2710           int start = *entry >> 4;
2711           int count = (*entry++) & 0xf;
2712           int i;
2713
2714           /* Only registers D0..D31 are valid.  */
2715           if (start + count >= 16)
2716             return NULL;
2717
2718           /* Pop VFP double-precision registers
2719              D[16+start]..D[16+start+count].  */
2720           for (i = 0; i <= count; i++)
2721             {
2722               cache->saved_regs[ARM_D0_REGNUM + 16 + start + i].addr = vsp;
2723               vsp += 8;
2724             }
2725         }
2726       else if (insn == 0xc9)
2727         {
2728           int start = *entry >> 4;
2729           int count = (*entry++) & 0xf;
2730           int i;
2731
2732           /* Pop VFP double-precision registers D[start]..D[start+count].  */
2733           for (i = 0; i <= count; i++)
2734             {
2735               cache->saved_regs[ARM_D0_REGNUM + start + i].addr = vsp;
2736               vsp += 8;
2737             }
2738         }
2739       else if ((insn & 0xf8) == 0xd0)
2740         {
2741           int count = insn & 0x7;
2742           int i;
2743
2744           /* Pop VFP double-precision registers D[8]..D[8+count].  */
2745           for (i = 0; i <= count; i++)
2746             {
2747               cache->saved_regs[ARM_D0_REGNUM + 8 + i].addr = vsp;
2748               vsp += 8;
2749             }
2750         }
2751       else
2752         {
2753           /* Everything else is "spare".  */
2754           return NULL;
2755         }
2756     }
2757
2758   /* If we restore SP from a register, assume this was the frame register.
2759      Otherwise just fall back to SP as frame register.  */
2760   if (trad_frame_realreg_p (cache->saved_regs, ARM_SP_REGNUM))
2761     cache->framereg = cache->saved_regs[ARM_SP_REGNUM].realreg;
2762   else
2763     cache->framereg = ARM_SP_REGNUM;
2764
2765   /* Determine offset to previous frame.  */
2766   cache->framesize
2767     = vsp - get_frame_register_unsigned (this_frame, cache->framereg);
2768
2769   /* We already got the previous SP.  */
2770   cache->prev_sp = vsp;
2771
2772   return cache;
2773 }
2774
2775 /* Unwinding via ARM exception table entries.  Note that the sniffer
2776    already computes a filled-in prologue cache, which is then used
2777    with the same arm_prologue_this_id and arm_prologue_prev_register
2778    routines also used for prologue-parsing based unwinding.  */
2779
2780 static int
2781 arm_exidx_unwind_sniffer (const struct frame_unwind *self,
2782                           struct frame_info *this_frame,
2783                           void **this_prologue_cache)
2784 {
2785   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2786   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
2787   CORE_ADDR addr_in_block, exidx_region, func_start;
2788   struct arm_prologue_cache *cache;
2789   gdb_byte *entry;
2790
2791   /* See if we have an ARM exception table entry covering this address.  */
2792   addr_in_block = get_frame_address_in_block (this_frame);
2793   entry = arm_find_exidx_entry (addr_in_block, &exidx_region);
2794   if (!entry)
2795     return 0;
2796
2797   /* The ARM exception table does not describe unwind information
2798      for arbitrary PC values, but is guaranteed to be correct only
2799      at call sites.  We have to decide here whether we want to use
2800      ARM exception table information for this frame, or fall back
2801      to using prologue parsing.  (Note that if we have DWARF CFI,
2802      this sniffer isn't even called -- CFI is always preferred.)
2803
2804      Before we make this decision, however, we check whether we
2805      actually have *symbol* information for the current frame.
2806      If not, prologue parsing would not work anyway, so we might
2807      as well use the exception table and hope for the best.  */
2808   if (find_pc_partial_function (addr_in_block, NULL, &func_start, NULL))
2809     {
2810       int exc_valid = 0;
2811
2812       /* If the next frame is "normal", we are at a call site in this
2813          frame, so exception information is guaranteed to be valid.  */
2814       if (get_next_frame (this_frame)
2815           && get_frame_type (get_next_frame (this_frame)) == NORMAL_FRAME)
2816         exc_valid = 1;
2817
2818       /* We also assume exception information is valid if we're currently
2819          blocked in a system call.  The system library is supposed to
2820          ensure this, so that e.g. pthread cancellation works.  */
2821       if (arm_frame_is_thumb (this_frame))
2822         {
2823           LONGEST insn;
2824
2825           if (safe_read_memory_integer (get_frame_pc (this_frame) - 2, 2,
2826                                         byte_order_for_code, &insn)
2827               && (insn & 0xff00) == 0xdf00 /* svc */)
2828             exc_valid = 1;
2829         }
2830       else
2831         {
2832           LONGEST insn;
2833
2834           if (safe_read_memory_integer (get_frame_pc (this_frame) - 4, 4,
2835                                         byte_order_for_code, &insn)
2836               && (insn & 0x0f000000) == 0x0f000000 /* svc */)
2837             exc_valid = 1;
2838         }
2839         
2840       /* Bail out if we don't know that exception information is valid.  */
2841       if (!exc_valid)
2842         return 0;
2843
2844      /* The ARM exception index does not mark the *end* of the region
2845         covered by the entry, and some functions will not have any entry.
2846         To correctly recognize the end of the covered region, the linker
2847         should have inserted dummy records with a CANTUNWIND marker.
2848
2849         Unfortunately, current versions of GNU ld do not reliably do
2850         this, and thus we may have found an incorrect entry above.
2851         As a (temporary) sanity check, we only use the entry if it
2852         lies *within* the bounds of the function.  Note that this check
2853         might reject perfectly valid entries that just happen to cover
2854         multiple functions; therefore this check ought to be removed
2855         once the linker is fixed.  */
2856       if (func_start > exidx_region)
2857         return 0;
2858     }
2859
2860   /* Decode the list of unwinding instructions into a prologue cache.
2861      Note that this may fail due to e.g. a "refuse to unwind" code.  */
2862   cache = arm_exidx_fill_cache (this_frame, entry);
2863   if (!cache)
2864     return 0;
2865
2866   *this_prologue_cache = cache;
2867   return 1;
2868 }
2869
2870 struct frame_unwind arm_exidx_unwind = {
2871   NORMAL_FRAME,
2872   default_frame_unwind_stop_reason,
2873   arm_prologue_this_id,
2874   arm_prologue_prev_register,
2875   NULL,
2876   arm_exidx_unwind_sniffer
2877 };
2878
2879 static struct arm_prologue_cache *
2880 arm_make_stub_cache (struct frame_info *this_frame)
2881 {
2882   struct arm_prologue_cache *cache;
2883
2884   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2885   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2886
2887   cache->prev_sp = get_frame_register_unsigned (this_frame, ARM_SP_REGNUM);
2888
2889   return cache;
2890 }
2891
2892 /* Our frame ID for a stub frame is the current SP and LR.  */
2893
2894 static void
2895 arm_stub_this_id (struct frame_info *this_frame,
2896                   void **this_cache,
2897                   struct frame_id *this_id)
2898 {
2899   struct arm_prologue_cache *cache;
2900
2901   if (*this_cache == NULL)
2902     *this_cache = arm_make_stub_cache (this_frame);
2903   cache = *this_cache;
2904
2905   *this_id = frame_id_build (cache->prev_sp, get_frame_pc (this_frame));
2906 }
2907
2908 static int
2909 arm_stub_unwind_sniffer (const struct frame_unwind *self,
2910                          struct frame_info *this_frame,
2911                          void **this_prologue_cache)
2912 {
2913   CORE_ADDR addr_in_block;
2914   char dummy[4];
2915
2916   addr_in_block = get_frame_address_in_block (this_frame);
2917   if (in_plt_section (addr_in_block, NULL)
2918       /* We also use the stub winder if the target memory is unreadable
2919          to avoid having the prologue unwinder trying to read it.  */
2920       || target_read_memory (get_frame_pc (this_frame), dummy, 4) != 0)
2921     return 1;
2922
2923   return 0;
2924 }
2925
2926 struct frame_unwind arm_stub_unwind = {
2927   NORMAL_FRAME,
2928   default_frame_unwind_stop_reason,
2929   arm_stub_this_id,
2930   arm_prologue_prev_register,
2931   NULL,
2932   arm_stub_unwind_sniffer
2933 };
2934
2935 /* Put here the code to store, into CACHE->saved_regs, the addresses
2936    of the saved registers of frame described by THIS_FRAME.  CACHE is
2937    returned.  */
2938
2939 static struct arm_prologue_cache *
2940 arm_m_exception_cache (struct frame_info *this_frame)
2941 {
2942   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2943   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2944   struct arm_prologue_cache *cache;
2945   CORE_ADDR unwound_sp;
2946   LONGEST xpsr;
2947
2948   cache = FRAME_OBSTACK_ZALLOC (struct arm_prologue_cache);
2949   cache->saved_regs = trad_frame_alloc_saved_regs (this_frame);
2950
2951   unwound_sp = get_frame_register_unsigned (this_frame,
2952                                             ARM_SP_REGNUM);
2953
2954   /* The hardware saves eight 32-bit words, comprising xPSR,
2955      ReturnAddress, LR (R14), R12, R3, R2, R1, R0.  See details in
2956      "B1.5.6 Exception entry behavior" in
2957      "ARMv7-M Architecture Reference Manual".  */
2958   cache->saved_regs[0].addr = unwound_sp;
2959   cache->saved_regs[1].addr = unwound_sp + 4;
2960   cache->saved_regs[2].addr = unwound_sp + 8;
2961   cache->saved_regs[3].addr = unwound_sp + 12;
2962   cache->saved_regs[12].addr = unwound_sp + 16;
2963   cache->saved_regs[14].addr = unwound_sp + 20;
2964   cache->saved_regs[15].addr = unwound_sp + 24;
2965   cache->saved_regs[ARM_PS_REGNUM].addr = unwound_sp + 28;
2966
2967   /* If bit 9 of the saved xPSR is set, then there is a four-byte
2968      aligner between the top of the 32-byte stack frame and the
2969      previous context's stack pointer.  */
2970   cache->prev_sp = unwound_sp + 32;
2971   if (safe_read_memory_integer (unwound_sp + 28, 4, byte_order, &xpsr)
2972       && (xpsr & (1 << 9)) != 0)
2973     cache->prev_sp += 4;
2974
2975   return cache;
2976 }
2977
2978 /* Implementation of function hook 'this_id' in
2979    'struct frame_uwnind'.  */
2980
2981 static void
2982 arm_m_exception_this_id (struct frame_info *this_frame,
2983                          void **this_cache,
2984                          struct frame_id *this_id)
2985 {
2986   struct arm_prologue_cache *cache;
2987
2988   if (*this_cache == NULL)
2989     *this_cache = arm_m_exception_cache (this_frame);
2990   cache = *this_cache;
2991
2992   /* Our frame ID for a stub frame is the current SP and LR.  */
2993   *this_id = frame_id_build (cache->prev_sp,
2994                              get_frame_pc (this_frame));
2995 }
2996
2997 /* Implementation of function hook 'prev_register' in
2998    'struct frame_uwnind'.  */
2999
3000 static struct value *
3001 arm_m_exception_prev_register (struct frame_info *this_frame,
3002                                void **this_cache,
3003                                int prev_regnum)
3004 {
3005   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3006   struct arm_prologue_cache *cache;
3007
3008   if (*this_cache == NULL)
3009     *this_cache = arm_m_exception_cache (this_frame);
3010   cache = *this_cache;
3011
3012   /* The value was already reconstructed into PREV_SP.  */
3013   if (prev_regnum == ARM_SP_REGNUM)
3014     return frame_unwind_got_constant (this_frame, prev_regnum,
3015                                       cache->prev_sp);
3016
3017   return trad_frame_get_prev_register (this_frame, cache->saved_regs,
3018                                        prev_regnum);
3019 }
3020
3021 /* Implementation of function hook 'sniffer' in
3022    'struct frame_uwnind'.  */
3023
3024 static int
3025 arm_m_exception_unwind_sniffer (const struct frame_unwind *self,
3026                                 struct frame_info *this_frame,
3027                                 void **this_prologue_cache)
3028 {
3029   CORE_ADDR this_pc = get_frame_pc (this_frame);
3030
3031   /* No need to check is_m; this sniffer is only registered for
3032      M-profile architectures.  */
3033
3034   /* Exception frames return to one of these magic PCs.  Other values
3035      are not defined as of v7-M.  See details in "B1.5.8 Exception
3036      return behavior" in "ARMv7-M Architecture Reference Manual".  */
3037   if (this_pc == 0xfffffff1 || this_pc == 0xfffffff9
3038       || this_pc == 0xfffffffd)
3039     return 1;
3040
3041   return 0;
3042 }
3043
3044 /* Frame unwinder for M-profile exceptions.  */
3045
3046 struct frame_unwind arm_m_exception_unwind =
3047 {
3048   SIGTRAMP_FRAME,
3049   default_frame_unwind_stop_reason,
3050   arm_m_exception_this_id,
3051   arm_m_exception_prev_register,
3052   NULL,
3053   arm_m_exception_unwind_sniffer
3054 };
3055
3056 static CORE_ADDR
3057 arm_normal_frame_base (struct frame_info *this_frame, void **this_cache)
3058 {
3059   struct arm_prologue_cache *cache;
3060
3061   if (*this_cache == NULL)
3062     *this_cache = arm_make_prologue_cache (this_frame);
3063   cache = *this_cache;
3064
3065   return cache->prev_sp - cache->framesize;
3066 }
3067
3068 struct frame_base arm_normal_base = {
3069   &arm_prologue_unwind,
3070   arm_normal_frame_base,
3071   arm_normal_frame_base,
3072   arm_normal_frame_base
3073 };
3074
3075 /* Assuming THIS_FRAME is a dummy, return the frame ID of that
3076    dummy frame.  The frame ID's base needs to match the TOS value
3077    saved by save_dummy_frame_tos() and returned from
3078    arm_push_dummy_call, and the PC needs to match the dummy frame's
3079    breakpoint.  */
3080
3081 static struct frame_id
3082 arm_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
3083 {
3084   return frame_id_build (get_frame_register_unsigned (this_frame,
3085                                                       ARM_SP_REGNUM),
3086                          get_frame_pc (this_frame));
3087 }
3088
3089 /* Given THIS_FRAME, find the previous frame's resume PC (which will
3090    be used to construct the previous frame's ID, after looking up the
3091    containing function).  */
3092
3093 static CORE_ADDR
3094 arm_unwind_pc (struct gdbarch *gdbarch, struct frame_info *this_frame)
3095 {
3096   CORE_ADDR pc;
3097   pc = frame_unwind_register_unsigned (this_frame, ARM_PC_REGNUM);
3098   return arm_addr_bits_remove (gdbarch, pc);
3099 }
3100
3101 static CORE_ADDR
3102 arm_unwind_sp (struct gdbarch *gdbarch, struct frame_info *this_frame)
3103 {
3104   return frame_unwind_register_unsigned (this_frame, ARM_SP_REGNUM);
3105 }
3106
3107 static struct value *
3108 arm_dwarf2_prev_register (struct frame_info *this_frame, void **this_cache,
3109                           int regnum)
3110 {
3111   struct gdbarch * gdbarch = get_frame_arch (this_frame);
3112   CORE_ADDR lr, cpsr;
3113   ULONGEST t_bit = arm_psr_thumb_bit (gdbarch);
3114
3115   switch (regnum)
3116     {
3117     case ARM_PC_REGNUM:
3118       /* The PC is normally copied from the return column, which
3119          describes saves of LR.  However, that version may have an
3120          extra bit set to indicate Thumb state.  The bit is not
3121          part of the PC.  */
3122       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3123       return frame_unwind_got_constant (this_frame, regnum,
3124                                         arm_addr_bits_remove (gdbarch, lr));
3125
3126     case ARM_PS_REGNUM:
3127       /* Reconstruct the T bit; see arm_prologue_prev_register for details.  */
3128       cpsr = get_frame_register_unsigned (this_frame, regnum);
3129       lr = frame_unwind_register_unsigned (this_frame, ARM_LR_REGNUM);
3130       if (IS_THUMB_ADDR (lr))
3131         cpsr |= t_bit;
3132       else
3133         cpsr &= ~t_bit;
3134       return frame_unwind_got_constant (this_frame, regnum, cpsr);
3135
3136     default:
3137       internal_error (__FILE__, __LINE__,
3138                       _("Unexpected register %d"), regnum);
3139     }
3140 }
3141
3142 static void
3143 arm_dwarf2_frame_init_reg (struct gdbarch *gdbarch, int regnum,
3144                            struct dwarf2_frame_state_reg *reg,
3145                            struct frame_info *this_frame)
3146 {
3147   switch (regnum)
3148     {
3149     case ARM_PC_REGNUM:
3150     case ARM_PS_REGNUM:
3151       reg->how = DWARF2_FRAME_REG_FN;
3152       reg->loc.fn = arm_dwarf2_prev_register;
3153       break;
3154     case ARM_SP_REGNUM:
3155       reg->how = DWARF2_FRAME_REG_CFA;
3156       break;
3157     }
3158 }
3159
3160 /* Return true if we are in the function's epilogue, i.e. after the
3161    instruction that destroyed the function's stack frame.  */
3162
3163 static int
3164 thumb_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3165 {
3166   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3167   unsigned int insn, insn2;
3168   int found_return = 0, found_stack_adjust = 0;
3169   CORE_ADDR func_start, func_end;
3170   CORE_ADDR scan_pc;
3171   gdb_byte buf[4];
3172
3173   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3174     return 0;
3175
3176   /* The epilogue is a sequence of instructions along the following lines:
3177
3178     - add stack frame size to SP or FP
3179     - [if frame pointer used] restore SP from FP
3180     - restore registers from SP [may include PC]
3181     - a return-type instruction [if PC wasn't already restored]
3182
3183     In a first pass, we scan forward from the current PC and verify the
3184     instructions we find as compatible with this sequence, ending in a
3185     return instruction.
3186
3187     However, this is not sufficient to distinguish indirect function calls
3188     within a function from indirect tail calls in the epilogue in some cases.
3189     Therefore, if we didn't already find any SP-changing instruction during
3190     forward scan, we add a backward scanning heuristic to ensure we actually
3191     are in the epilogue.  */
3192
3193   scan_pc = pc;
3194   while (scan_pc < func_end && !found_return)
3195     {
3196       if (target_read_memory (scan_pc, buf, 2))
3197         break;
3198
3199       scan_pc += 2;
3200       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3201
3202       if ((insn & 0xff80) == 0x4700)  /* bx <Rm> */
3203         found_return = 1;
3204       else if (insn == 0x46f7)  /* mov pc, lr */
3205         found_return = 1;
3206       else if (insn == 0x46bd)  /* mov sp, r7 */
3207         found_stack_adjust = 1;
3208       else if ((insn & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3209         found_stack_adjust = 1;
3210       else if ((insn & 0xfe00) == 0xbc00)  /* pop <registers> */
3211         {
3212           found_stack_adjust = 1;
3213           if (insn & 0x0100)  /* <registers> include PC.  */
3214             found_return = 1;
3215         }
3216       else if (thumb_insn_size (insn) == 4)  /* 32-bit Thumb-2 instruction */
3217         {
3218           if (target_read_memory (scan_pc, buf, 2))
3219             break;
3220
3221           scan_pc += 2;
3222           insn2 = extract_unsigned_integer (buf, 2, byte_order_for_code);
3223
3224           if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3225             {
3226               found_stack_adjust = 1;
3227               if (insn2 & 0x8000)  /* <registers> include PC.  */
3228                 found_return = 1;
3229             }
3230           else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3231                    && (insn2 & 0x0fff) == 0x0b04)
3232             {
3233               found_stack_adjust = 1;
3234               if ((insn2 & 0xf000) == 0xf000) /* <Rt> is PC.  */
3235                 found_return = 1;
3236             }
3237           else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3238                    && (insn2 & 0x0e00) == 0x0a00)
3239             found_stack_adjust = 1;
3240           else
3241             break;
3242         }
3243       else
3244         break;
3245     }
3246
3247   if (!found_return)
3248     return 0;
3249
3250   /* Since any instruction in the epilogue sequence, with the possible
3251      exception of return itself, updates the stack pointer, we need to
3252      scan backwards for at most one instruction.  Try either a 16-bit or
3253      a 32-bit instruction.  This is just a heuristic, so we do not worry
3254      too much about false positives.  */
3255
3256   if (!found_stack_adjust)
3257     {
3258       if (pc - 4 < func_start)
3259         return 0;
3260       if (target_read_memory (pc - 4, buf, 4))
3261         return 0;
3262
3263       insn = extract_unsigned_integer (buf, 2, byte_order_for_code);
3264       insn2 = extract_unsigned_integer (buf + 2, 2, byte_order_for_code);
3265
3266       if (insn2 == 0x46bd)  /* mov sp, r7 */
3267         found_stack_adjust = 1;
3268       else if ((insn2 & 0xff00) == 0xb000)  /* add sp, imm or sub sp, imm  */
3269         found_stack_adjust = 1;
3270       else if ((insn2 & 0xff00) == 0xbc00)  /* pop <registers> without PC */
3271         found_stack_adjust = 1;
3272       else if (insn == 0xe8bd)  /* ldm.w sp!, <registers> */
3273         found_stack_adjust = 1;
3274       else if (insn == 0xf85d  /* ldr.w <Rt>, [sp], #4 */
3275                && (insn2 & 0x0fff) == 0x0b04)
3276         found_stack_adjust = 1;
3277       else if ((insn & 0xffbf) == 0xecbd  /* vldm sp!, <list> */
3278                && (insn2 & 0x0e00) == 0x0a00)
3279         found_stack_adjust = 1;
3280     }
3281
3282   return found_stack_adjust;
3283 }
3284
3285 /* Return true if we are in the function's epilogue, i.e. after the
3286    instruction that destroyed the function's stack frame.  */
3287
3288 static int
3289 arm_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
3290 {
3291   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
3292   unsigned int insn;
3293   int found_return, found_stack_adjust;
3294   CORE_ADDR func_start, func_end;
3295
3296   if (arm_pc_is_thumb (gdbarch, pc))
3297     return thumb_in_function_epilogue_p (gdbarch, pc);
3298
3299   if (!find_pc_partial_function (pc, NULL, &func_start, &func_end))
3300     return 0;
3301
3302   /* We are in the epilogue if the previous instruction was a stack
3303      adjustment and the next instruction is a possible return (bx, mov
3304      pc, or pop).  We could have to scan backwards to find the stack
3305      adjustment, or forwards to find the return, but this is a decent
3306      approximation.  First scan forwards.  */
3307
3308   found_return = 0;
3309   insn = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
3310   if (bits (insn, 28, 31) != INST_NV)
3311     {
3312       if ((insn & 0x0ffffff0) == 0x012fff10)
3313         /* BX.  */
3314         found_return = 1;
3315       else if ((insn & 0x0ffffff0) == 0x01a0f000)
3316         /* MOV PC.  */
3317         found_return = 1;
3318       else if ((insn & 0x0fff0000) == 0x08bd0000
3319           && (insn & 0x0000c000) != 0)
3320         /* POP (LDMIA), including PC or LR.  */
3321         found_return = 1;
3322     }
3323
3324   if (!found_return)
3325     return 0;
3326
3327   /* Scan backwards.  This is just a heuristic, so do not worry about
3328      false positives from mode changes.  */
3329
3330   if (pc < func_start + 4)
3331     return 0;
3332
3333   found_stack_adjust = 0;
3334   insn = read_memory_unsigned_integer (pc - 4, 4, byte_order_for_code);
3335   if (bits (insn, 28, 31) != INST_NV)
3336     {
3337       if ((insn & 0x0df0f000) == 0x0080d000)
3338         /* ADD SP (register or immediate).  */
3339         found_stack_adjust = 1;
3340       else if ((insn & 0x0df0f000) == 0x0040d000)
3341         /* SUB SP (register or immediate).  */
3342         found_stack_adjust = 1;
3343       else if ((insn & 0x0ffffff0) == 0x01a0d000)
3344         /* MOV SP.  */
3345         found_stack_adjust = 1;
3346       else if ((insn & 0x0fff0000) == 0x08bd0000)
3347         /* POP (LDMIA).  */
3348         found_stack_adjust = 1;
3349       else if ((insn & 0x0fff0000) == 0x049d0000)
3350         /* POP of a single register.  */
3351         found_stack_adjust = 1;
3352     }
3353
3354   if (found_stack_adjust)
3355     return 1;
3356
3357   return 0;
3358 }
3359
3360
3361 /* When arguments must be pushed onto the stack, they go on in reverse
3362    order.  The code below implements a FILO (stack) to do this.  */
3363
3364 struct stack_item
3365 {
3366   int len;
3367   struct stack_item *prev;
3368   void *data;
3369 };
3370
3371 static struct stack_item *
3372 push_stack_item (struct stack_item *prev, const void *contents, int len)
3373 {
3374   struct stack_item *si;
3375   si = xmalloc (sizeof (struct stack_item));
3376   si->data = xmalloc (len);
3377   si->len = len;
3378   si->prev = prev;
3379   memcpy (si->data, contents, len);
3380   return si;
3381 }
3382
3383 static struct stack_item *
3384 pop_stack_item (struct stack_item *si)
3385 {
3386   struct stack_item *dead = si;
3387   si = si->prev;
3388   xfree (dead->data);
3389   xfree (dead);
3390   return si;
3391 }
3392
3393
3394 /* Return the alignment (in bytes) of the given type.  */
3395
3396 static int
3397 arm_type_align (struct type *t)
3398 {
3399   int n;
3400   int align;
3401   int falign;
3402
3403   t = check_typedef (t);
3404   switch (TYPE_CODE (t))
3405     {
3406     default:
3407       /* Should never happen.  */
3408       internal_error (__FILE__, __LINE__, _("unknown type alignment"));
3409       return 4;
3410
3411     case TYPE_CODE_PTR:
3412     case TYPE_CODE_ENUM:
3413     case TYPE_CODE_INT:
3414     case TYPE_CODE_FLT:
3415     case TYPE_CODE_SET:
3416     case TYPE_CODE_RANGE:
3417     case TYPE_CODE_REF:
3418     case TYPE_CODE_CHAR:
3419     case TYPE_CODE_BOOL:
3420       return TYPE_LENGTH (t);
3421
3422     case TYPE_CODE_ARRAY:
3423     case TYPE_CODE_COMPLEX:
3424       /* TODO: What about vector types?  */
3425       return arm_type_align (TYPE_TARGET_TYPE (t));
3426
3427     case TYPE_CODE_STRUCT:
3428     case TYPE_CODE_UNION:
3429       align = 1;
3430       for (n = 0; n < TYPE_NFIELDS (t); n++)
3431         {
3432           falign = arm_type_align (TYPE_FIELD_TYPE (t, n));
3433           if (falign > align)
3434             align = falign;
3435         }
3436       return align;
3437     }
3438 }
3439
3440 /* Possible base types for a candidate for passing and returning in
3441    VFP registers.  */
3442
3443 enum arm_vfp_cprc_base_type
3444 {
3445   VFP_CPRC_UNKNOWN,
3446   VFP_CPRC_SINGLE,
3447   VFP_CPRC_DOUBLE,
3448   VFP_CPRC_VEC64,
3449   VFP_CPRC_VEC128
3450 };
3451
3452 /* The length of one element of base type B.  */
3453
3454 static unsigned
3455 arm_vfp_cprc_unit_length (enum arm_vfp_cprc_base_type b)
3456 {
3457   switch (b)
3458     {
3459     case VFP_CPRC_SINGLE:
3460       return 4;
3461     case VFP_CPRC_DOUBLE:
3462       return 8;
3463     case VFP_CPRC_VEC64:
3464       return 8;
3465     case VFP_CPRC_VEC128:
3466       return 16;
3467     default:
3468       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3469                       (int) b);
3470     }
3471 }
3472
3473 /* The character ('s', 'd' or 'q') for the type of VFP register used
3474    for passing base type B.  */
3475
3476 static int
3477 arm_vfp_cprc_reg_char (enum arm_vfp_cprc_base_type b)
3478 {
3479   switch (b)
3480     {
3481     case VFP_CPRC_SINGLE:
3482       return 's';
3483     case VFP_CPRC_DOUBLE:
3484       return 'd';
3485     case VFP_CPRC_VEC64:
3486       return 'd';
3487     case VFP_CPRC_VEC128:
3488       return 'q';
3489     default:
3490       internal_error (__FILE__, __LINE__, _("Invalid VFP CPRC type: %d."),
3491                       (int) b);
3492     }
3493 }
3494
3495 /* Determine whether T may be part of a candidate for passing and
3496    returning in VFP registers, ignoring the limit on the total number
3497    of components.  If *BASE_TYPE is VFP_CPRC_UNKNOWN, set it to the
3498    classification of the first valid component found; if it is not
3499    VFP_CPRC_UNKNOWN, all components must have the same classification
3500    as *BASE_TYPE.  If it is found that T contains a type not permitted
3501    for passing and returning in VFP registers, a type differently
3502    classified from *BASE_TYPE, or two types differently classified
3503    from each other, return -1, otherwise return the total number of
3504    base-type elements found (possibly 0 in an empty structure or
3505    array).  Vectors and complex types are not currently supported,
3506    matching the generic AAPCS support.  */
3507
3508 static int
3509 arm_vfp_cprc_sub_candidate (struct type *t,
3510                             enum arm_vfp_cprc_base_type *base_type)
3511 {
3512   t = check_typedef (t);
3513   switch (TYPE_CODE (t))
3514     {
3515     case TYPE_CODE_FLT:
3516       switch (TYPE_LENGTH (t))
3517         {
3518         case 4:
3519           if (*base_type == VFP_CPRC_UNKNOWN)
3520             *base_type = VFP_CPRC_SINGLE;
3521           else if (*base_type != VFP_CPRC_SINGLE)
3522             return -1;
3523           return 1;
3524
3525         case 8:
3526           if (*base_type == VFP_CPRC_UNKNOWN)
3527             *base_type = VFP_CPRC_DOUBLE;
3528           else if (*base_type != VFP_CPRC_DOUBLE)
3529             return -1;
3530           return 1;
3531
3532         default:
3533           return -1;
3534         }
3535       break;
3536
3537     case TYPE_CODE_ARRAY:
3538       {
3539         int count;
3540         unsigned unitlen;
3541         count = arm_vfp_cprc_sub_candidate (TYPE_TARGET_TYPE (t), base_type);
3542         if (count == -1)
3543           return -1;
3544         if (TYPE_LENGTH (t) == 0)
3545           {
3546             gdb_assert (count == 0);
3547             return 0;
3548           }
3549         else if (count == 0)
3550           return -1;
3551         unitlen = arm_vfp_cprc_unit_length (*base_type);
3552         gdb_assert ((TYPE_LENGTH (t) % unitlen) == 0);
3553         return TYPE_LENGTH (t) / unitlen;
3554       }
3555       break;
3556
3557     case TYPE_CODE_STRUCT:
3558       {
3559         int count = 0;
3560         unsigned unitlen;
3561         int i;
3562         for (i = 0; i < TYPE_NFIELDS (t); i++)
3563           {
3564             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3565                                                         base_type);
3566             if (sub_count == -1)
3567               return -1;
3568             count += sub_count;
3569           }
3570         if (TYPE_LENGTH (t) == 0)
3571           {
3572             gdb_assert (count == 0);
3573             return 0;
3574           }
3575         else if (count == 0)
3576           return -1;
3577         unitlen = arm_vfp_cprc_unit_length (*base_type);
3578         if (TYPE_LENGTH (t) != unitlen * count)
3579           return -1;
3580         return count;
3581       }
3582
3583     case TYPE_CODE_UNION:
3584       {
3585         int count = 0;
3586         unsigned unitlen;
3587         int i;
3588         for (i = 0; i < TYPE_NFIELDS (t); i++)
3589           {
3590             int sub_count = arm_vfp_cprc_sub_candidate (TYPE_FIELD_TYPE (t, i),
3591                                                         base_type);
3592             if (sub_count == -1)
3593               return -1;
3594             count = (count > sub_count ? count : sub_count);
3595           }
3596         if (TYPE_LENGTH (t) == 0)
3597           {
3598             gdb_assert (count == 0);
3599             return 0;
3600           }
3601         else if (count == 0)
3602           return -1;
3603         unitlen = arm_vfp_cprc_unit_length (*base_type);
3604         if (TYPE_LENGTH (t) != unitlen * count)
3605           return -1;
3606         return count;
3607       }
3608
3609     default:
3610       break;
3611     }
3612
3613   return -1;
3614 }
3615
3616 /* Determine whether T is a VFP co-processor register candidate (CPRC)
3617    if passed to or returned from a non-variadic function with the VFP
3618    ABI in effect.  Return 1 if it is, 0 otherwise.  If it is, set
3619    *BASE_TYPE to the base type for T and *COUNT to the number of
3620    elements of that base type before returning.  */
3621
3622 static int
3623 arm_vfp_call_candidate (struct type *t, enum arm_vfp_cprc_base_type *base_type,
3624                         int *count)
3625 {
3626   enum arm_vfp_cprc_base_type b = VFP_CPRC_UNKNOWN;
3627   int c = arm_vfp_cprc_sub_candidate (t, &b);
3628   if (c <= 0 || c > 4)
3629     return 0;
3630   *base_type = b;
3631   *count = c;
3632   return 1;
3633 }
3634
3635 /* Return 1 if the VFP ABI should be used for passing arguments to and
3636    returning values from a function of type FUNC_TYPE, 0
3637    otherwise.  */
3638
3639 static int
3640 arm_vfp_abi_for_function (struct gdbarch *gdbarch, struct type *func_type)
3641 {
3642   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3643   /* Variadic functions always use the base ABI.  Assume that functions
3644      without debug info are not variadic.  */
3645   if (func_type && TYPE_VARARGS (check_typedef (func_type)))
3646     return 0;
3647   /* The VFP ABI is only supported as a variant of AAPCS.  */
3648   if (tdep->arm_abi != ARM_ABI_AAPCS)
3649     return 0;
3650   return gdbarch_tdep (gdbarch)->fp_model == ARM_FLOAT_VFP;
3651 }
3652
3653 /* We currently only support passing parameters in integer registers, which
3654    conforms with GCC's default model, and VFP argument passing following
3655    the VFP variant of AAPCS.  Several other variants exist and
3656    we should probably support some of them based on the selected ABI.  */
3657
3658 static CORE_ADDR
3659 arm_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
3660                      struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
3661                      struct value **args, CORE_ADDR sp, int struct_return,
3662                      CORE_ADDR struct_addr)
3663 {
3664   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3665   int argnum;
3666   int argreg;
3667   int nstack;
3668   struct stack_item *si = NULL;
3669   int use_vfp_abi;
3670   struct type *ftype;
3671   unsigned vfp_regs_free = (1 << 16) - 1;
3672
3673   /* Determine the type of this function and whether the VFP ABI
3674      applies.  */
3675   ftype = check_typedef (value_type (function));
3676   if (TYPE_CODE (ftype) == TYPE_CODE_PTR)
3677     ftype = check_typedef (TYPE_TARGET_TYPE (ftype));
3678   use_vfp_abi = arm_vfp_abi_for_function (gdbarch, ftype);
3679
3680   /* Set the return address.  For the ARM, the return breakpoint is
3681      always at BP_ADDR.  */
3682   if (arm_pc_is_thumb (gdbarch, bp_addr))
3683     bp_addr |= 1;
3684   regcache_cooked_write_unsigned (regcache, ARM_LR_REGNUM, bp_addr);
3685
3686   /* Walk through the list of args and determine how large a temporary
3687      stack is required.  Need to take care here as structs may be
3688      passed on the stack, and we have to push them.  */
3689   nstack = 0;
3690
3691   argreg = ARM_A1_REGNUM;
3692   nstack = 0;
3693
3694   /* The struct_return pointer occupies the first parameter
3695      passing register.  */
3696   if (struct_return)
3697     {
3698       if (arm_debug)
3699         fprintf_unfiltered (gdb_stdlog, "struct return in %s = %s\n",
3700                             gdbarch_register_name (gdbarch, argreg),
3701                             paddress (gdbarch, struct_addr));
3702       regcache_cooked_write_unsigned (regcache, argreg, struct_addr);
3703       argreg++;
3704     }
3705
3706   for (argnum = 0; argnum < nargs; argnum++)
3707     {
3708       int len;
3709       struct type *arg_type;
3710       struct type *target_type;
3711       enum type_code typecode;
3712       const bfd_byte *val;
3713       int align;
3714       enum arm_vfp_cprc_base_type vfp_base_type;
3715       int vfp_base_count;
3716       int may_use_core_reg = 1;
3717
3718       arg_type = check_typedef (value_type (args[argnum]));
3719       len = TYPE_LENGTH (arg_type);
3720       target_type = TYPE_TARGET_TYPE (arg_type);
3721       typecode = TYPE_CODE (arg_type);
3722       val = value_contents (args[argnum]);
3723
3724       align = arm_type_align (arg_type);
3725       /* Round alignment up to a whole number of words.  */
3726       align = (align + INT_REGISTER_SIZE - 1) & ~(INT_REGISTER_SIZE - 1);
3727       /* Different ABIs have different maximum alignments.  */
3728       if (gdbarch_tdep (gdbarch)->arm_abi == ARM_ABI_APCS)
3729         {
3730           /* The APCS ABI only requires word alignment.  */
3731           align = INT_REGISTER_SIZE;
3732         }
3733       else
3734         {
3735           /* The AAPCS requires at most doubleword alignment.  */
3736           if (align > INT_REGISTER_SIZE * 2)
3737             align = INT_REGISTER_SIZE * 2;
3738         }
3739
3740       if (use_vfp_abi
3741           && arm_vfp_call_candidate (arg_type, &vfp_base_type,
3742                                      &vfp_base_count))
3743         {
3744           int regno;
3745           int unit_length;
3746           int shift;
3747           unsigned mask;
3748
3749           /* Because this is a CPRC it cannot go in a core register or
3750              cause a core register to be skipped for alignment.
3751              Either it goes in VFP registers and the rest of this loop
3752              iteration is skipped for this argument, or it goes on the
3753              stack (and the stack alignment code is correct for this
3754              case).  */
3755           may_use_core_reg = 0;
3756
3757           unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
3758           shift = unit_length / 4;
3759           mask = (1 << (shift * vfp_base_count)) - 1;
3760           for (regno = 0; regno < 16; regno += shift)
3761             if (((vfp_regs_free >> regno) & mask) == mask)
3762               break;
3763
3764           if (regno < 16)
3765             {
3766               int reg_char;
3767               int reg_scaled;
3768               int i;
3769
3770               vfp_regs_free &= ~(mask << regno);
3771               reg_scaled = regno / shift;
3772               reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
3773               for (i = 0; i < vfp_base_count; i++)
3774                 {
3775                   char name_buf[4];
3776                   int regnum;
3777                   if (reg_char == 'q')
3778                     arm_neon_quad_write (gdbarch, regcache, reg_scaled + i,
3779                                          val + i * unit_length);
3780                   else
3781                     {
3782                       sprintf (name_buf, "%c%d", reg_char, reg_scaled + i);
3783                       regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
3784                                                             strlen (name_buf));
3785                       regcache_cooked_write (regcache, regnum,
3786                                              val + i * unit_length);
3787                     }
3788                 }
3789               continue;
3790             }
3791           else
3792             {
3793               /* This CPRC could not go in VFP registers, so all VFP
3794                  registers are now marked as used.  */
3795               vfp_regs_free = 0;
3796             }
3797         }
3798
3799       /* Push stack padding for dowubleword alignment.  */
3800       if (nstack & (align - 1))
3801         {
3802           si = push_stack_item (si, val, INT_REGISTER_SIZE);
3803           nstack += INT_REGISTER_SIZE;
3804         }
3805       
3806       /* Doubleword aligned quantities must go in even register pairs.  */
3807       if (may_use_core_reg
3808           && argreg <= ARM_LAST_ARG_REGNUM
3809           && align > INT_REGISTER_SIZE
3810           && argreg & 1)
3811         argreg++;
3812
3813       /* If the argument is a pointer to a function, and it is a
3814          Thumb function, create a LOCAL copy of the value and set
3815          the THUMB bit in it.  */
3816       if (TYPE_CODE_PTR == typecode
3817           && target_type != NULL
3818           && TYPE_CODE_FUNC == TYPE_CODE (check_typedef (target_type)))
3819         {
3820           CORE_ADDR regval = extract_unsigned_integer (val, len, byte_order);
3821           if (arm_pc_is_thumb (gdbarch, regval))
3822             {
3823               bfd_byte *copy = alloca (len);
3824               store_unsigned_integer (copy, len, byte_order,
3825                                       MAKE_THUMB_ADDR (regval));
3826               val = copy;
3827             }
3828         }
3829
3830       /* Copy the argument to general registers or the stack in
3831          register-sized pieces.  Large arguments are split between
3832          registers and stack.  */
3833       while (len > 0)
3834         {
3835           int partial_len = len < INT_REGISTER_SIZE ? len : INT_REGISTER_SIZE;
3836
3837           if (may_use_core_reg && argreg <= ARM_LAST_ARG_REGNUM)
3838             {
3839               /* The argument is being passed in a general purpose
3840                  register.  */
3841               CORE_ADDR regval
3842                 = extract_unsigned_integer (val, partial_len, byte_order);
3843               if (byte_order == BFD_ENDIAN_BIG)
3844                 regval <<= (INT_REGISTER_SIZE - partial_len) * 8;
3845               if (arm_debug)
3846                 fprintf_unfiltered (gdb_stdlog, "arg %d in %s = 0x%s\n",
3847                                     argnum,
3848                                     gdbarch_register_name
3849                                       (gdbarch, argreg),
3850                                     phex (regval, INT_REGISTER_SIZE));
3851               regcache_cooked_write_unsigned (regcache, argreg, regval);
3852               argreg++;
3853             }
3854           else
3855             {
3856               /* Push the arguments onto the stack.  */
3857               if (arm_debug)
3858                 fprintf_unfiltered (gdb_stdlog, "arg %d @ sp + %d\n",
3859                                     argnum, nstack);
3860               si = push_stack_item (si, val, INT_REGISTER_SIZE);
3861               nstack += INT_REGISTER_SIZE;
3862             }
3863               
3864           len -= partial_len;
3865           val += partial_len;
3866         }
3867     }
3868   /* If we have an odd number of words to push, then decrement the stack
3869      by one word now, so first stack argument will be dword aligned.  */
3870   if (nstack & 4)
3871     sp -= 4;
3872
3873   while (si)
3874     {
3875       sp -= si->len;
3876       write_memory (sp, si->data, si->len);
3877       si = pop_stack_item (si);
3878     }
3879
3880   /* Finally, update teh SP register.  */
3881   regcache_cooked_write_unsigned (regcache, ARM_SP_REGNUM, sp);
3882
3883   return sp;
3884 }
3885
3886
3887 /* Always align the frame to an 8-byte boundary.  This is required on
3888    some platforms and harmless on the rest.  */
3889
3890 static CORE_ADDR
3891 arm_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
3892 {
3893   /* Align the stack to eight bytes.  */
3894   return sp & ~ (CORE_ADDR) 7;
3895 }
3896
3897 static void
3898 print_fpu_flags (int flags)
3899 {
3900   if (flags & (1 << 0))
3901     fputs ("IVO ", stdout);
3902   if (flags & (1 << 1))
3903     fputs ("DVZ ", stdout);
3904   if (flags & (1 << 2))
3905     fputs ("OFL ", stdout);
3906   if (flags & (1 << 3))
3907     fputs ("UFL ", stdout);
3908   if (flags & (1 << 4))
3909     fputs ("INX ", stdout);
3910   putchar ('\n');
3911 }
3912
3913 /* Print interesting information about the floating point processor
3914    (if present) or emulator.  */
3915 static void
3916 arm_print_float_info (struct gdbarch *gdbarch, struct ui_file *file,
3917                       struct frame_info *frame, const char *args)
3918 {
3919   unsigned long status = get_frame_register_unsigned (frame, ARM_FPS_REGNUM);
3920   int type;
3921
3922   type = (status >> 24) & 127;
3923   if (status & (1 << 31))
3924     printf (_("Hardware FPU type %d\n"), type);
3925   else
3926     printf (_("Software FPU type %d\n"), type);
3927   /* i18n: [floating point unit] mask */
3928   fputs (_("mask: "), stdout);
3929   print_fpu_flags (status >> 16);
3930   /* i18n: [floating point unit] flags */
3931   fputs (_("flags: "), stdout);
3932   print_fpu_flags (status);
3933 }
3934
3935 /* Construct the ARM extended floating point type.  */
3936 static struct type *
3937 arm_ext_type (struct gdbarch *gdbarch)
3938 {
3939   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3940
3941   if (!tdep->arm_ext_type)
3942     tdep->arm_ext_type
3943       = arch_float_type (gdbarch, -1, "builtin_type_arm_ext",
3944                          floatformats_arm_ext);
3945
3946   return tdep->arm_ext_type;
3947 }
3948
3949 static struct type *
3950 arm_neon_double_type (struct gdbarch *gdbarch)
3951 {
3952   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3953
3954   if (tdep->neon_double_type == NULL)
3955     {
3956       struct type *t, *elem;
3957
3958       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_d",
3959                                TYPE_CODE_UNION);
3960       elem = builtin_type (gdbarch)->builtin_uint8;
3961       append_composite_type_field (t, "u8", init_vector_type (elem, 8));
3962       elem = builtin_type (gdbarch)->builtin_uint16;
3963       append_composite_type_field (t, "u16", init_vector_type (elem, 4));
3964       elem = builtin_type (gdbarch)->builtin_uint32;
3965       append_composite_type_field (t, "u32", init_vector_type (elem, 2));
3966       elem = builtin_type (gdbarch)->builtin_uint64;
3967       append_composite_type_field (t, "u64", elem);
3968       elem = builtin_type (gdbarch)->builtin_float;
3969       append_composite_type_field (t, "f32", init_vector_type (elem, 2));
3970       elem = builtin_type (gdbarch)->builtin_double;
3971       append_composite_type_field (t, "f64", elem);
3972
3973       TYPE_VECTOR (t) = 1;
3974       TYPE_NAME (t) = "neon_d";
3975       tdep->neon_double_type = t;
3976     }
3977
3978   return tdep->neon_double_type;
3979 }
3980
3981 /* FIXME: The vector types are not correctly ordered on big-endian
3982    targets.  Just as s0 is the low bits of d0, d0[0] is also the low
3983    bits of d0 - regardless of what unit size is being held in d0.  So
3984    the offset of the first uint8 in d0 is 7, but the offset of the
3985    first float is 4.  This code works as-is for little-endian
3986    targets.  */
3987
3988 static struct type *
3989 arm_neon_quad_type (struct gdbarch *gdbarch)
3990 {
3991   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
3992
3993   if (tdep->neon_quad_type == NULL)
3994     {
3995       struct type *t, *elem;
3996
3997       t = arch_composite_type (gdbarch, "__gdb_builtin_type_neon_q",
3998                                TYPE_CODE_UNION);
3999       elem = builtin_type (gdbarch)->builtin_uint8;
4000       append_composite_type_field (t, "u8", init_vector_type (elem, 16));
4001       elem = builtin_type (gdbarch)->builtin_uint16;
4002       append_composite_type_field (t, "u16", init_vector_type (elem, 8));
4003       elem = builtin_type (gdbarch)->builtin_uint32;
4004       append_composite_type_field (t, "u32", init_vector_type (elem, 4));
4005       elem = builtin_type (gdbarch)->builtin_uint64;
4006       append_composite_type_field (t, "u64", init_vector_type (elem, 2));
4007       elem = builtin_type (gdbarch)->builtin_float;
4008       append_composite_type_field (t, "f32", init_vector_type (elem, 4));
4009       elem = builtin_type (gdbarch)->builtin_double;
4010       append_composite_type_field (t, "f64", init_vector_type (elem, 2));
4011
4012       TYPE_VECTOR (t) = 1;
4013       TYPE_NAME (t) = "neon_q";
4014       tdep->neon_quad_type = t;
4015     }
4016
4017   return tdep->neon_quad_type;
4018 }
4019
4020 /* Return the GDB type object for the "standard" data type of data in
4021    register N.  */
4022
4023 static struct type *
4024 arm_register_type (struct gdbarch *gdbarch, int regnum)
4025 {
4026   int num_regs = gdbarch_num_regs (gdbarch);
4027
4028   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
4029       && regnum >= num_regs && regnum < num_regs + 32)
4030     return builtin_type (gdbarch)->builtin_float;
4031
4032   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
4033       && regnum >= num_regs + 32 && regnum < num_regs + 32 + 16)
4034     return arm_neon_quad_type (gdbarch);
4035
4036   /* If the target description has register information, we are only
4037      in this function so that we can override the types of
4038      double-precision registers for NEON.  */
4039   if (tdesc_has_registers (gdbarch_target_desc (gdbarch)))
4040     {
4041       struct type *t = tdesc_register_type (gdbarch, regnum);
4042
4043       if (regnum >= ARM_D0_REGNUM && regnum < ARM_D0_REGNUM + 32
4044           && TYPE_CODE (t) == TYPE_CODE_FLT
4045           && gdbarch_tdep (gdbarch)->have_neon)
4046         return arm_neon_double_type (gdbarch);
4047       else
4048         return t;
4049     }
4050
4051   if (regnum >= ARM_F0_REGNUM && regnum < ARM_F0_REGNUM + NUM_FREGS)
4052     {
4053       if (!gdbarch_tdep (gdbarch)->have_fpa_registers)
4054         return builtin_type (gdbarch)->builtin_void;
4055
4056       return arm_ext_type (gdbarch);
4057     }
4058   else if (regnum == ARM_SP_REGNUM)
4059     return builtin_type (gdbarch)->builtin_data_ptr;
4060   else if (regnum == ARM_PC_REGNUM)
4061     return builtin_type (gdbarch)->builtin_func_ptr;
4062   else if (regnum >= ARRAY_SIZE (arm_register_names))
4063     /* These registers are only supported on targets which supply
4064        an XML description.  */
4065     return builtin_type (gdbarch)->builtin_int0;
4066   else
4067     return builtin_type (gdbarch)->builtin_uint32;
4068 }
4069
4070 /* Map a DWARF register REGNUM onto the appropriate GDB register
4071    number.  */
4072
4073 static int
4074 arm_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
4075 {
4076   /* Core integer regs.  */
4077   if (reg >= 0 && reg <= 15)
4078     return reg;
4079
4080   /* Legacy FPA encoding.  These were once used in a way which
4081      overlapped with VFP register numbering, so their use is
4082      discouraged, but GDB doesn't support the ARM toolchain
4083      which used them for VFP.  */
4084   if (reg >= 16 && reg <= 23)
4085     return ARM_F0_REGNUM + reg - 16;
4086
4087   /* New assignments for the FPA registers.  */
4088   if (reg >= 96 && reg <= 103)
4089     return ARM_F0_REGNUM + reg - 96;
4090
4091   /* WMMX register assignments.  */
4092   if (reg >= 104 && reg <= 111)
4093     return ARM_WCGR0_REGNUM + reg - 104;
4094
4095   if (reg >= 112 && reg <= 127)
4096     return ARM_WR0_REGNUM + reg - 112;
4097
4098   if (reg >= 192 && reg <= 199)
4099     return ARM_WC0_REGNUM + reg - 192;
4100
4101   /* VFP v2 registers.  A double precision value is actually
4102      in d1 rather than s2, but the ABI only defines numbering
4103      for the single precision registers.  This will "just work"
4104      in GDB for little endian targets (we'll read eight bytes,
4105      starting in s0 and then progressing to s1), but will be
4106      reversed on big endian targets with VFP.  This won't
4107      be a problem for the new Neon quad registers; you're supposed
4108      to use DW_OP_piece for those.  */
4109   if (reg >= 64 && reg <= 95)
4110     {
4111       char name_buf[4];
4112
4113       sprintf (name_buf, "s%d", reg - 64);
4114       return user_reg_map_name_to_regnum (gdbarch, name_buf,
4115                                           strlen (name_buf));
4116     }
4117
4118   /* VFP v3 / Neon registers.  This range is also used for VFP v2
4119      registers, except that it now describes d0 instead of s0.  */
4120   if (reg >= 256 && reg <= 287)
4121     {
4122       char name_buf[4];
4123
4124       sprintf (name_buf, "d%d", reg - 256);
4125       return user_reg_map_name_to_regnum (gdbarch, name_buf,
4126                                           strlen (name_buf));
4127     }
4128
4129   return -1;
4130 }
4131
4132 /* Map GDB internal REGNUM onto the Arm simulator register numbers.  */
4133 static int
4134 arm_register_sim_regno (struct gdbarch *gdbarch, int regnum)
4135 {
4136   int reg = regnum;
4137   gdb_assert (reg >= 0 && reg < gdbarch_num_regs (gdbarch));
4138
4139   if (regnum >= ARM_WR0_REGNUM && regnum <= ARM_WR15_REGNUM)
4140     return regnum - ARM_WR0_REGNUM + SIM_ARM_IWMMXT_COP0R0_REGNUM;
4141
4142   if (regnum >= ARM_WC0_REGNUM && regnum <= ARM_WC7_REGNUM)
4143     return regnum - ARM_WC0_REGNUM + SIM_ARM_IWMMXT_COP1R0_REGNUM;
4144
4145   if (regnum >= ARM_WCGR0_REGNUM && regnum <= ARM_WCGR7_REGNUM)
4146     return regnum - ARM_WCGR0_REGNUM + SIM_ARM_IWMMXT_COP1R8_REGNUM;
4147
4148   if (reg < NUM_GREGS)
4149     return SIM_ARM_R0_REGNUM + reg;
4150   reg -= NUM_GREGS;
4151
4152   if (reg < NUM_FREGS)
4153     return SIM_ARM_FP0_REGNUM + reg;
4154   reg -= NUM_FREGS;
4155
4156   if (reg < NUM_SREGS)
4157     return SIM_ARM_FPS_REGNUM + reg;
4158   reg -= NUM_SREGS;
4159
4160   internal_error (__FILE__, __LINE__, _("Bad REGNUM %d"), regnum);
4161 }
4162
4163 /* NOTE: cagney/2001-08-20: Both convert_from_extended() and
4164    convert_to_extended() use floatformat_arm_ext_littlebyte_bigword.
4165    It is thought that this is is the floating-point register format on
4166    little-endian systems.  */
4167
4168 static void
4169 convert_from_extended (const struct floatformat *fmt, const void *ptr,
4170                        void *dbl, int endianess)
4171 {
4172   DOUBLEST d;
4173
4174   if (endianess == BFD_ENDIAN_BIG)
4175     floatformat_to_doublest (&floatformat_arm_ext_big, ptr, &d);
4176   else
4177     floatformat_to_doublest (&floatformat_arm_ext_littlebyte_bigword,
4178                              ptr, &d);
4179   floatformat_from_doublest (fmt, &d, dbl);
4180 }
4181
4182 static void
4183 convert_to_extended (const struct floatformat *fmt, void *dbl, const void *ptr,
4184                      int endianess)
4185 {
4186   DOUBLEST d;
4187
4188   floatformat_to_doublest (fmt, ptr, &d);
4189   if (endianess == BFD_ENDIAN_BIG)
4190     floatformat_from_doublest (&floatformat_arm_ext_big, &d, dbl);
4191   else
4192     floatformat_from_doublest (&floatformat_arm_ext_littlebyte_bigword,
4193                                &d, dbl);
4194 }
4195
4196 static int
4197 condition_true (unsigned long cond, unsigned long status_reg)
4198 {
4199   if (cond == INST_AL || cond == INST_NV)
4200     return 1;
4201
4202   switch (cond)
4203     {
4204     case INST_EQ:
4205       return ((status_reg & FLAG_Z) != 0);
4206     case INST_NE:
4207       return ((status_reg & FLAG_Z) == 0);
4208     case INST_CS:
4209       return ((status_reg & FLAG_C) != 0);
4210     case INST_CC:
4211       return ((status_reg & FLAG_C) == 0);
4212     case INST_MI:
4213       return ((status_reg & FLAG_N) != 0);
4214     case INST_PL:
4215       return ((status_reg & FLAG_N) == 0);
4216     case INST_VS:
4217       return ((status_reg & FLAG_V) != 0);
4218     case INST_VC:
4219       return ((status_reg & FLAG_V) == 0);
4220     case INST_HI:
4221       return ((status_reg & (FLAG_C | FLAG_Z)) == FLAG_C);
4222     case INST_LS:
4223       return ((status_reg & (FLAG_C | FLAG_Z)) != FLAG_C);
4224     case INST_GE:
4225       return (((status_reg & FLAG_N) == 0) == ((status_reg & FLAG_V) == 0));
4226     case INST_LT:
4227       return (((status_reg & FLAG_N) == 0) != ((status_reg & FLAG_V) == 0));
4228     case INST_GT:
4229       return (((status_reg & FLAG_Z) == 0)
4230               && (((status_reg & FLAG_N) == 0)
4231                   == ((status_reg & FLAG_V) == 0)));
4232     case INST_LE:
4233       return (((status_reg & FLAG_Z) != 0)
4234               || (((status_reg & FLAG_N) == 0)
4235                   != ((status_reg & FLAG_V) == 0)));
4236     }
4237   return 1;
4238 }
4239
4240 static unsigned long
4241 shifted_reg_val (struct frame_info *frame, unsigned long inst, int carry,
4242                  unsigned long pc_val, unsigned long status_reg)
4243 {
4244   unsigned long res, shift;
4245   int rm = bits (inst, 0, 3);
4246   unsigned long shifttype = bits (inst, 5, 6);
4247
4248   if (bit (inst, 4))
4249     {
4250       int rs = bits (inst, 8, 11);
4251       shift = (rs == 15 ? pc_val + 8
4252                         : get_frame_register_unsigned (frame, rs)) & 0xFF;
4253     }
4254   else
4255     shift = bits (inst, 7, 11);
4256
4257   res = (rm == ARM_PC_REGNUM
4258          ? (pc_val + (bit (inst, 4) ? 12 : 8))
4259          : get_frame_register_unsigned (frame, rm));
4260
4261   switch (shifttype)
4262     {
4263     case 0:                     /* LSL */
4264       res = shift >= 32 ? 0 : res << shift;
4265       break;
4266
4267     case 1:                     /* LSR */
4268       res = shift >= 32 ? 0 : res >> shift;
4269       break;
4270
4271     case 2:                     /* ASR */
4272       if (shift >= 32)
4273         shift = 31;
4274       res = ((res & 0x80000000L)
4275              ? ~((~res) >> shift) : res >> shift);
4276       break;
4277
4278     case 3:                     /* ROR/RRX */
4279       shift &= 31;
4280       if (shift == 0)
4281         res = (res >> 1) | (carry ? 0x80000000L : 0);
4282       else
4283         res = (res >> shift) | (res << (32 - shift));
4284       break;
4285     }
4286
4287   return res & 0xffffffff;
4288 }
4289
4290 /* Return number of 1-bits in VAL.  */
4291
4292 static int
4293 bitcount (unsigned long val)
4294 {
4295   int nbits;
4296   for (nbits = 0; val != 0; nbits++)
4297     val &= val - 1;             /* Delete rightmost 1-bit in val.  */
4298   return nbits;
4299 }
4300
4301 /* Return the size in bytes of the complete Thumb instruction whose
4302    first halfword is INST1.  */
4303
4304 static int
4305 thumb_insn_size (unsigned short inst1)
4306 {
4307   if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
4308     return 4;
4309   else
4310     return 2;
4311 }
4312
4313 static int
4314 thumb_advance_itstate (unsigned int itstate)
4315 {
4316   /* Preserve IT[7:5], the first three bits of the condition.  Shift
4317      the upcoming condition flags left by one bit.  */
4318   itstate = (itstate & 0xe0) | ((itstate << 1) & 0x1f);
4319
4320   /* If we have finished the IT block, clear the state.  */
4321   if ((itstate & 0x0f) == 0)
4322     itstate = 0;
4323
4324   return itstate;
4325 }
4326
4327 /* Find the next PC after the current instruction executes.  In some
4328    cases we can not statically determine the answer (see the IT state
4329    handling in this function); in that case, a breakpoint may be
4330    inserted in addition to the returned PC, which will be used to set
4331    another breakpoint by our caller.  */
4332
4333 static CORE_ADDR
4334 thumb_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc)
4335 {
4336   struct gdbarch *gdbarch = get_frame_arch (frame);
4337   struct address_space *aspace = get_frame_address_space (frame);
4338   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4339   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4340   unsigned long pc_val = ((unsigned long) pc) + 4;      /* PC after prefetch */
4341   unsigned short inst1;
4342   CORE_ADDR nextpc = pc + 2;            /* Default is next instruction.  */
4343   unsigned long offset;
4344   ULONGEST status, itstate;
4345
4346   nextpc = MAKE_THUMB_ADDR (nextpc);
4347   pc_val = MAKE_THUMB_ADDR (pc_val);
4348
4349   inst1 = read_memory_unsigned_integer (pc, 2, byte_order_for_code);
4350
4351   /* Thumb-2 conditional execution support.  There are eight bits in
4352      the CPSR which describe conditional execution state.  Once
4353      reconstructed (they're in a funny order), the low five bits
4354      describe the low bit of the condition for each instruction and
4355      how many instructions remain.  The high three bits describe the
4356      base condition.  One of the low four bits will be set if an IT
4357      block is active.  These bits read as zero on earlier
4358      processors.  */
4359   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4360   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
4361
4362   /* If-Then handling.  On GNU/Linux, where this routine is used, we
4363      use an undefined instruction as a breakpoint.  Unlike BKPT, IT
4364      can disable execution of the undefined instruction.  So we might
4365      miss the breakpoint if we set it on a skipped conditional
4366      instruction.  Because conditional instructions can change the
4367      flags, affecting the execution of further instructions, we may
4368      need to set two breakpoints.  */
4369
4370   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint != NULL)
4371     {
4372       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
4373         {
4374           /* An IT instruction.  Because this instruction does not
4375              modify the flags, we can accurately predict the next
4376              executed instruction.  */
4377           itstate = inst1 & 0x00ff;
4378           pc += thumb_insn_size (inst1);
4379
4380           while (itstate != 0 && ! condition_true (itstate >> 4, status))
4381             {
4382               inst1 = read_memory_unsigned_integer (pc, 2,
4383                                                     byte_order_for_code);
4384               pc += thumb_insn_size (inst1);
4385               itstate = thumb_advance_itstate (itstate);
4386             }
4387
4388           return MAKE_THUMB_ADDR (pc);
4389         }
4390       else if (itstate != 0)
4391         {
4392           /* We are in a conditional block.  Check the condition.  */
4393           if (! condition_true (itstate >> 4, status))
4394             {
4395               /* Advance to the next executed instruction.  */
4396               pc += thumb_insn_size (inst1);
4397               itstate = thumb_advance_itstate (itstate);
4398
4399               while (itstate != 0 && ! condition_true (itstate >> 4, status))
4400                 {
4401                   inst1 = read_memory_unsigned_integer (pc, 2, 
4402                                                         byte_order_for_code);
4403                   pc += thumb_insn_size (inst1);
4404                   itstate = thumb_advance_itstate (itstate);
4405                 }
4406
4407               return MAKE_THUMB_ADDR (pc);
4408             }
4409           else if ((itstate & 0x0f) == 0x08)
4410             {
4411               /* This is the last instruction of the conditional
4412                  block, and it is executed.  We can handle it normally
4413                  because the following instruction is not conditional,
4414                  and we must handle it normally because it is
4415                  permitted to branch.  Fall through.  */
4416             }
4417           else
4418             {
4419               int cond_negated;
4420
4421               /* There are conditional instructions after this one.
4422                  If this instruction modifies the flags, then we can
4423                  not predict what the next executed instruction will
4424                  be.  Fortunately, this instruction is architecturally
4425                  forbidden to branch; we know it will fall through.
4426                  Start by skipping past it.  */
4427               pc += thumb_insn_size (inst1);
4428               itstate = thumb_advance_itstate (itstate);
4429
4430               /* Set a breakpoint on the following instruction.  */
4431               gdb_assert ((itstate & 0x0f) != 0);
4432               arm_insert_single_step_breakpoint (gdbarch, aspace,
4433                                                  MAKE_THUMB_ADDR (pc));
4434               cond_negated = (itstate >> 4) & 1;
4435
4436               /* Skip all following instructions with the same
4437                  condition.  If there is a later instruction in the IT
4438                  block with the opposite condition, set the other
4439                  breakpoint there.  If not, then set a breakpoint on
4440                  the instruction after the IT block.  */
4441               do
4442                 {
4443                   inst1 = read_memory_unsigned_integer (pc, 2,
4444                                                         byte_order_for_code);
4445                   pc += thumb_insn_size (inst1);
4446                   itstate = thumb_advance_itstate (itstate);
4447                 }
4448               while (itstate != 0 && ((itstate >> 4) & 1) == cond_negated);
4449
4450               return MAKE_THUMB_ADDR (pc);
4451             }
4452         }
4453     }
4454   else if (itstate & 0x0f)
4455     {
4456       /* We are in a conditional block.  Check the condition.  */
4457       int cond = itstate >> 4;
4458
4459       if (! condition_true (cond, status))
4460         /* Advance to the next instruction.  All the 32-bit
4461            instructions share a common prefix.  */
4462         return MAKE_THUMB_ADDR (pc + thumb_insn_size (inst1));
4463
4464       /* Otherwise, handle the instruction normally.  */
4465     }
4466
4467   if ((inst1 & 0xff00) == 0xbd00)       /* pop {rlist, pc} */
4468     {
4469       CORE_ADDR sp;
4470
4471       /* Fetch the saved PC from the stack.  It's stored above
4472          all of the other registers.  */
4473       offset = bitcount (bits (inst1, 0, 7)) * INT_REGISTER_SIZE;
4474       sp = get_frame_register_unsigned (frame, ARM_SP_REGNUM);
4475       nextpc = read_memory_unsigned_integer (sp + offset, 4, byte_order);
4476     }
4477   else if ((inst1 & 0xf000) == 0xd000)  /* conditional branch */
4478     {
4479       unsigned long cond = bits (inst1, 8, 11);
4480       if (cond == 0x0f)  /* 0x0f = SWI */
4481         {
4482           struct gdbarch_tdep *tdep;
4483           tdep = gdbarch_tdep (gdbarch);
4484
4485           if (tdep->syscall_next_pc != NULL)
4486             nextpc = tdep->syscall_next_pc (frame);
4487
4488         }
4489       else if (cond != 0x0f && condition_true (cond, status))
4490         nextpc = pc_val + (sbits (inst1, 0, 7) << 1);
4491     }
4492   else if ((inst1 & 0xf800) == 0xe000)  /* unconditional branch */
4493     {
4494       nextpc = pc_val + (sbits (inst1, 0, 10) << 1);
4495     }
4496   else if (thumb_insn_size (inst1) == 4) /* 32-bit instruction */
4497     {
4498       unsigned short inst2;
4499       inst2 = read_memory_unsigned_integer (pc + 2, 2, byte_order_for_code);
4500
4501       /* Default to the next instruction.  */
4502       nextpc = pc + 4;
4503       nextpc = MAKE_THUMB_ADDR (nextpc);
4504
4505       if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
4506         {
4507           /* Branches and miscellaneous control instructions.  */
4508
4509           if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
4510             {
4511               /* B, BL, BLX.  */
4512               int j1, j2, imm1, imm2;
4513
4514               imm1 = sbits (inst1, 0, 10);
4515               imm2 = bits (inst2, 0, 10);
4516               j1 = bit (inst2, 13);
4517               j2 = bit (inst2, 11);
4518
4519               offset = ((imm1 << 12) + (imm2 << 1));
4520               offset ^= ((!j2) << 22) | ((!j1) << 23);
4521
4522               nextpc = pc_val + offset;
4523               /* For BLX make sure to clear the low bits.  */
4524               if (bit (inst2, 12) == 0)
4525                 nextpc = nextpc & 0xfffffffc;
4526             }
4527           else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
4528             {
4529               /* SUBS PC, LR, #imm8.  */
4530               nextpc = get_frame_register_unsigned (frame, ARM_LR_REGNUM);
4531               nextpc -= inst2 & 0x00ff;
4532             }
4533           else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
4534             {
4535               /* Conditional branch.  */
4536               if (condition_true (bits (inst1, 6, 9), status))
4537                 {
4538                   int sign, j1, j2, imm1, imm2;
4539
4540                   sign = sbits (inst1, 10, 10);
4541                   imm1 = bits (inst1, 0, 5);
4542                   imm2 = bits (inst2, 0, 10);
4543                   j1 = bit (inst2, 13);
4544                   j2 = bit (inst2, 11);
4545
4546                   offset = (sign << 20) + (j2 << 19) + (j1 << 18);
4547                   offset += (imm1 << 12) + (imm2 << 1);
4548
4549                   nextpc = pc_val + offset;
4550                 }
4551             }
4552         }
4553       else if ((inst1 & 0xfe50) == 0xe810)
4554         {
4555           /* Load multiple or RFE.  */
4556           int rn, offset, load_pc = 1;
4557
4558           rn = bits (inst1, 0, 3);
4559           if (bit (inst1, 7) && !bit (inst1, 8))
4560             {
4561               /* LDMIA or POP */
4562               if (!bit (inst2, 15))
4563                 load_pc = 0;
4564               offset = bitcount (inst2) * 4 - 4;
4565             }
4566           else if (!bit (inst1, 7) && bit (inst1, 8))
4567             {
4568               /* LDMDB */
4569               if (!bit (inst2, 15))
4570                 load_pc = 0;
4571               offset = -4;
4572             }
4573           else if (bit (inst1, 7) && bit (inst1, 8))
4574             {
4575               /* RFEIA */
4576               offset = 0;
4577             }
4578           else if (!bit (inst1, 7) && !bit (inst1, 8))
4579             {
4580               /* RFEDB */
4581               offset = -8;
4582             }
4583           else
4584             load_pc = 0;
4585
4586           if (load_pc)
4587             {
4588               CORE_ADDR addr = get_frame_register_unsigned (frame, rn);
4589               nextpc = get_frame_memory_unsigned (frame, addr + offset, 4);
4590             }
4591         }
4592       else if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
4593         {
4594           /* MOV PC or MOVS PC.  */
4595           nextpc = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4596           nextpc = MAKE_THUMB_ADDR (nextpc);
4597         }
4598       else if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
4599         {
4600           /* LDR PC.  */
4601           CORE_ADDR base;
4602           int rn, load_pc = 1;
4603
4604           rn = bits (inst1, 0, 3);
4605           base = get_frame_register_unsigned (frame, rn);
4606           if (rn == ARM_PC_REGNUM)
4607             {
4608               base = (base + 4) & ~(CORE_ADDR) 0x3;
4609               if (bit (inst1, 7))
4610                 base += bits (inst2, 0, 11);
4611               else
4612                 base -= bits (inst2, 0, 11);
4613             }
4614           else if (bit (inst1, 7))
4615             base += bits (inst2, 0, 11);
4616           else if (bit (inst2, 11))
4617             {
4618               if (bit (inst2, 10))
4619                 {
4620                   if (bit (inst2, 9))
4621                     base += bits (inst2, 0, 7);
4622                   else
4623                     base -= bits (inst2, 0, 7);
4624                 }
4625             }
4626           else if ((inst2 & 0x0fc0) == 0x0000)
4627             {
4628               int shift = bits (inst2, 4, 5), rm = bits (inst2, 0, 3);
4629               base += get_frame_register_unsigned (frame, rm) << shift;
4630             }
4631           else
4632             /* Reserved.  */
4633             load_pc = 0;
4634
4635           if (load_pc)
4636             nextpc = get_frame_memory_unsigned (frame, base, 4);
4637         }
4638       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
4639         {
4640           /* TBB.  */
4641           CORE_ADDR tbl_reg, table, offset, length;
4642
4643           tbl_reg = bits (inst1, 0, 3);
4644           if (tbl_reg == 0x0f)
4645             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4646           else
4647             table = get_frame_register_unsigned (frame, tbl_reg);
4648
4649           offset = get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4650           length = 2 * get_frame_memory_unsigned (frame, table + offset, 1);
4651           nextpc = pc_val + length;
4652         }
4653       else if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
4654         {
4655           /* TBH.  */
4656           CORE_ADDR tbl_reg, table, offset, length;
4657
4658           tbl_reg = bits (inst1, 0, 3);
4659           if (tbl_reg == 0x0f)
4660             table = pc + 4;  /* Regcache copy of PC isn't right yet.  */
4661           else
4662             table = get_frame_register_unsigned (frame, tbl_reg);
4663
4664           offset = 2 * get_frame_register_unsigned (frame, bits (inst2, 0, 3));
4665           length = 2 * get_frame_memory_unsigned (frame, table + offset, 2);
4666           nextpc = pc_val + length;
4667         }
4668     }
4669   else if ((inst1 & 0xff00) == 0x4700)  /* bx REG, blx REG */
4670     {
4671       if (bits (inst1, 3, 6) == 0x0f)
4672         nextpc = UNMAKE_THUMB_ADDR (pc_val);
4673       else
4674         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4675     }
4676   else if ((inst1 & 0xff87) == 0x4687)  /* mov pc, REG */
4677     {
4678       if (bits (inst1, 3, 6) == 0x0f)
4679         nextpc = pc_val;
4680       else
4681         nextpc = get_frame_register_unsigned (frame, bits (inst1, 3, 6));
4682
4683       nextpc = MAKE_THUMB_ADDR (nextpc);
4684     }
4685   else if ((inst1 & 0xf500) == 0xb100)
4686     {
4687       /* CBNZ or CBZ.  */
4688       int imm = (bit (inst1, 9) << 6) + (bits (inst1, 3, 7) << 1);
4689       ULONGEST reg = get_frame_register_unsigned (frame, bits (inst1, 0, 2));
4690
4691       if (bit (inst1, 11) && reg != 0)
4692         nextpc = pc_val + imm;
4693       else if (!bit (inst1, 11) && reg == 0)
4694         nextpc = pc_val + imm;
4695     }
4696   return nextpc;
4697 }
4698
4699 /* Get the raw next address.  PC is the current program counter, in 
4700    FRAME, which is assumed to be executing in ARM mode.
4701
4702    The value returned has the execution state of the next instruction 
4703    encoded in it.  Use IS_THUMB_ADDR () to see whether the instruction is
4704    in Thumb-State, and gdbarch_addr_bits_remove () to get the plain memory
4705    address.  */
4706
4707 static CORE_ADDR
4708 arm_get_next_pc_raw (struct frame_info *frame, CORE_ADDR pc)
4709 {
4710   struct gdbarch *gdbarch = get_frame_arch (frame);
4711   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
4712   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
4713   unsigned long pc_val;
4714   unsigned long this_instr;
4715   unsigned long status;
4716   CORE_ADDR nextpc;
4717
4718   pc_val = (unsigned long) pc;
4719   this_instr = read_memory_unsigned_integer (pc, 4, byte_order_for_code);
4720
4721   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
4722   nextpc = (CORE_ADDR) (pc_val + 4);    /* Default case */
4723
4724   if (bits (this_instr, 28, 31) == INST_NV)
4725     switch (bits (this_instr, 24, 27))
4726       {
4727       case 0xa:
4728       case 0xb:
4729         {
4730           /* Branch with Link and change to Thumb.  */
4731           nextpc = BranchDest (pc, this_instr);
4732           nextpc |= bit (this_instr, 24) << 1;
4733           nextpc = MAKE_THUMB_ADDR (nextpc);
4734           break;
4735         }
4736       case 0xc:
4737       case 0xd:
4738       case 0xe:
4739         /* Coprocessor register transfer.  */
4740         if (bits (this_instr, 12, 15) == 15)
4741           error (_("Invalid update to pc in instruction"));
4742         break;
4743       }
4744   else if (condition_true (bits (this_instr, 28, 31), status))
4745     {
4746       switch (bits (this_instr, 24, 27))
4747         {
4748         case 0x0:
4749         case 0x1:                       /* data processing */
4750         case 0x2:
4751         case 0x3:
4752           {
4753             unsigned long operand1, operand2, result = 0;
4754             unsigned long rn;
4755             int c;
4756
4757             if (bits (this_instr, 12, 15) != 15)
4758               break;
4759
4760             if (bits (this_instr, 22, 25) == 0
4761                 && bits (this_instr, 4, 7) == 9)        /* multiply */
4762               error (_("Invalid update to pc in instruction"));
4763
4764             /* BX <reg>, BLX <reg> */
4765             if (bits (this_instr, 4, 27) == 0x12fff1
4766                 || bits (this_instr, 4, 27) == 0x12fff3)
4767               {
4768                 rn = bits (this_instr, 0, 3);
4769                 nextpc = ((rn == ARM_PC_REGNUM)
4770                           ? (pc_val + 8)
4771                           : get_frame_register_unsigned (frame, rn));
4772
4773                 return nextpc;
4774               }
4775
4776             /* Multiply into PC.  */
4777             c = (status & FLAG_C) ? 1 : 0;
4778             rn = bits (this_instr, 16, 19);
4779             operand1 = ((rn == ARM_PC_REGNUM)
4780                         ? (pc_val + 8)
4781                         : get_frame_register_unsigned (frame, rn));
4782
4783             if (bit (this_instr, 25))
4784               {
4785                 unsigned long immval = bits (this_instr, 0, 7);
4786                 unsigned long rotate = 2 * bits (this_instr, 8, 11);
4787                 operand2 = ((immval >> rotate) | (immval << (32 - rotate)))
4788                   & 0xffffffff;
4789               }
4790             else                /* operand 2 is a shifted register.  */
4791               operand2 = shifted_reg_val (frame, this_instr, c,
4792                                           pc_val, status);
4793
4794             switch (bits (this_instr, 21, 24))
4795               {
4796               case 0x0: /*and */
4797                 result = operand1 & operand2;
4798                 break;
4799
4800               case 0x1: /*eor */
4801                 result = operand1 ^ operand2;
4802                 break;
4803
4804               case 0x2: /*sub */
4805                 result = operand1 - operand2;
4806                 break;
4807
4808               case 0x3: /*rsb */
4809                 result = operand2 - operand1;
4810                 break;
4811
4812               case 0x4: /*add */
4813                 result = operand1 + operand2;
4814                 break;
4815
4816               case 0x5: /*adc */
4817                 result = operand1 + operand2 + c;
4818                 break;
4819
4820               case 0x6: /*sbc */
4821                 result = operand1 - operand2 + c;
4822                 break;
4823
4824               case 0x7: /*rsc */
4825                 result = operand2 - operand1 + c;
4826                 break;
4827
4828               case 0x8:
4829               case 0x9:
4830               case 0xa:
4831               case 0xb: /* tst, teq, cmp, cmn */
4832                 result = (unsigned long) nextpc;
4833                 break;
4834
4835               case 0xc: /*orr */
4836                 result = operand1 | operand2;
4837                 break;
4838
4839               case 0xd: /*mov */
4840                 /* Always step into a function.  */
4841                 result = operand2;
4842                 break;
4843
4844               case 0xe: /*bic */
4845                 result = operand1 & ~operand2;
4846                 break;
4847
4848               case 0xf: /*mvn */
4849                 result = ~operand2;
4850                 break;
4851               }
4852
4853             /* In 26-bit APCS the bottom two bits of the result are 
4854                ignored, and we always end up in ARM state.  */
4855             if (!arm_apcs_32)
4856               nextpc = arm_addr_bits_remove (gdbarch, result);
4857             else
4858               nextpc = result;
4859
4860             break;
4861           }
4862
4863         case 0x4:
4864         case 0x5:               /* data transfer */
4865         case 0x6:
4866         case 0x7:
4867           if (bit (this_instr, 20))
4868             {
4869               /* load */
4870               if (bits (this_instr, 12, 15) == 15)
4871                 {
4872                   /* rd == pc */
4873                   unsigned long rn;
4874                   unsigned long base;
4875
4876                   if (bit (this_instr, 22))
4877                     error (_("Invalid update to pc in instruction"));
4878
4879                   /* byte write to PC */
4880                   rn = bits (this_instr, 16, 19);
4881                   base = ((rn == ARM_PC_REGNUM)
4882                           ? (pc_val + 8)
4883                           : get_frame_register_unsigned (frame, rn));
4884
4885                   if (bit (this_instr, 24))
4886                     {
4887                       /* pre-indexed */
4888                       int c = (status & FLAG_C) ? 1 : 0;
4889                       unsigned long offset =
4890                       (bit (this_instr, 25)
4891                        ? shifted_reg_val (frame, this_instr, c, pc_val, status)
4892                        : bits (this_instr, 0, 11));
4893
4894                       if (bit (this_instr, 23))
4895                         base += offset;
4896                       else
4897                         base -= offset;
4898                     }
4899                   nextpc =
4900                     (CORE_ADDR) read_memory_unsigned_integer ((CORE_ADDR) base,
4901                                                               4, byte_order);
4902                 }
4903             }
4904           break;
4905
4906         case 0x8:
4907         case 0x9:               /* block transfer */
4908           if (bit (this_instr, 20))
4909             {
4910               /* LDM */
4911               if (bit (this_instr, 15))
4912                 {
4913                   /* loading pc */
4914                   int offset = 0;
4915                   unsigned long rn_val
4916                     = get_frame_register_unsigned (frame,
4917                                                    bits (this_instr, 16, 19));
4918
4919                   if (bit (this_instr, 23))
4920                     {
4921                       /* up */
4922                       unsigned long reglist = bits (this_instr, 0, 14);
4923                       offset = bitcount (reglist) * 4;
4924                       if (bit (this_instr, 24))         /* pre */
4925                         offset += 4;
4926                     }
4927                   else if (bit (this_instr, 24))
4928                     offset = -4;
4929
4930                   nextpc =
4931                     (CORE_ADDR) read_memory_unsigned_integer ((CORE_ADDR)
4932                                                               (rn_val + offset),
4933                                                               4, byte_order);
4934                 }
4935             }
4936           break;
4937
4938         case 0xb:               /* branch & link */
4939         case 0xa:               /* branch */
4940           {
4941             nextpc = BranchDest (pc, this_instr);
4942             break;
4943           }
4944
4945         case 0xc:
4946         case 0xd:
4947         case 0xe:               /* coproc ops */
4948           break;
4949         case 0xf:               /* SWI */
4950           {
4951             struct gdbarch_tdep *tdep;
4952             tdep = gdbarch_tdep (gdbarch);
4953
4954             if (tdep->syscall_next_pc != NULL)
4955               nextpc = tdep->syscall_next_pc (frame);
4956
4957           }
4958           break;
4959
4960         default:
4961           fprintf_filtered (gdb_stderr, _("Bad bit-field extraction\n"));
4962           return (pc);
4963         }
4964     }
4965
4966   return nextpc;
4967 }
4968
4969 /* Determine next PC after current instruction executes.  Will call either
4970    arm_get_next_pc_raw or thumb_get_next_pc_raw.  Error out if infinite
4971    loop is detected.  */
4972
4973 CORE_ADDR
4974 arm_get_next_pc (struct frame_info *frame, CORE_ADDR pc)
4975 {
4976   CORE_ADDR nextpc;
4977
4978   if (arm_frame_is_thumb (frame))
4979     {
4980       nextpc = thumb_get_next_pc_raw (frame, pc);
4981       if (nextpc == MAKE_THUMB_ADDR (pc))
4982         error (_("Infinite loop detected"));
4983     }
4984   else
4985     {
4986       nextpc = arm_get_next_pc_raw (frame, pc);
4987       if (nextpc == pc)
4988         error (_("Infinite loop detected"));
4989     }
4990
4991   return nextpc;
4992 }
4993
4994 /* Like insert_single_step_breakpoint, but make sure we use a breakpoint
4995    of the appropriate mode (as encoded in the PC value), even if this
4996    differs from what would be expected according to the symbol tables.  */
4997
4998 void
4999 arm_insert_single_step_breakpoint (struct gdbarch *gdbarch,
5000                                    struct address_space *aspace,
5001                                    CORE_ADDR pc)
5002 {
5003   struct cleanup *old_chain
5004     = make_cleanup_restore_integer (&arm_override_mode);
5005
5006   arm_override_mode = IS_THUMB_ADDR (pc);
5007   pc = gdbarch_addr_bits_remove (gdbarch, pc);
5008
5009   insert_single_step_breakpoint (gdbarch, aspace, pc);
5010
5011   do_cleanups (old_chain);
5012 }
5013
5014 /* Checks for an atomic sequence of instructions beginning with a LDREX{,B,H,D}
5015    instruction and ending with a STREX{,B,H,D} instruction.  If such a sequence
5016    is found, attempt to step through it.  A breakpoint is placed at the end of
5017    the sequence.  */
5018
5019 static int
5020 thumb_deal_with_atomic_sequence_raw (struct frame_info *frame)
5021 {
5022   struct gdbarch *gdbarch = get_frame_arch (frame);
5023   struct address_space *aspace = get_frame_address_space (frame);
5024   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
5025   CORE_ADDR pc = get_frame_pc (frame);
5026   CORE_ADDR breaks[2] = {-1, -1};
5027   CORE_ADDR loc = pc;
5028   unsigned short insn1, insn2;
5029   int insn_count;
5030   int index;
5031   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
5032   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
5033   ULONGEST status, itstate;
5034
5035   /* We currently do not support atomic sequences within an IT block.  */
5036   status = get_frame_register_unsigned (frame, ARM_PS_REGNUM);
5037   itstate = ((status >> 8) & 0xfc) | ((status >> 25) & 0x3);
5038   if (itstate & 0x0f)
5039     return 0;
5040
5041   /* Assume all atomic sequences start with a ldrex{,b,h,d} instruction.  */
5042   insn1 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5043   loc += 2;
5044   if (thumb_insn_size (insn1) != 4)
5045     return 0;
5046
5047   insn2 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5048   loc += 2;
5049   if (!((insn1 & 0xfff0) == 0xe850
5050         || ((insn1 & 0xfff0) == 0xe8d0 && (insn2 & 0x00c0) == 0x0040)))
5051     return 0;
5052
5053   /* Assume that no atomic sequence is longer than "atomic_sequence_length"
5054      instructions.  */
5055   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
5056     {
5057       insn1 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5058       loc += 2;
5059
5060       if (thumb_insn_size (insn1) != 4)
5061         {
5062           /* Assume that there is at most one conditional branch in the
5063              atomic sequence.  If a conditional branch is found, put a
5064              breakpoint in its destination address.  */
5065           if ((insn1 & 0xf000) == 0xd000 && bits (insn1, 8, 11) != 0x0f)
5066             {
5067               if (last_breakpoint > 0)
5068                 return 0; /* More than one conditional branch found,
5069                              fallback to the standard code.  */
5070
5071               breaks[1] = loc + 2 + (sbits (insn1, 0, 7) << 1);
5072               last_breakpoint++;
5073             }
5074
5075           /* We do not support atomic sequences that use any *other*
5076              instructions but conditional branches to change the PC.
5077              Fall back to standard code to avoid losing control of
5078              execution.  */
5079           else if (thumb_instruction_changes_pc (insn1))
5080             return 0;
5081         }
5082       else
5083         {
5084           insn2 = read_memory_unsigned_integer (loc, 2, byte_order_for_code);
5085           loc += 2;
5086
5087           /* Assume that there is at most one conditional branch in the
5088              atomic sequence.  If a conditional branch is found, put a
5089              breakpoint in its destination address.  */
5090           if ((insn1 & 0xf800) == 0xf000
5091               && (insn2 & 0xd000) == 0x8000
5092               && (insn1 & 0x0380) != 0x0380)
5093             {
5094               int sign, j1, j2, imm1, imm2;
5095               unsigned int offset;
5096
5097               sign = sbits (insn1, 10, 10);
5098               imm1 = bits (insn1, 0, 5);
5099               imm2 = bits (insn2, 0, 10);
5100               j1 = bit (insn2, 13);
5101               j2 = bit (insn2, 11);
5102
5103               offset = (sign << 20) + (j2 << 19) + (j1 << 18);
5104               offset += (imm1 << 12) + (imm2 << 1);
5105
5106               if (last_breakpoint > 0)
5107                 return 0; /* More than one conditional branch found,
5108                              fallback to the standard code.  */
5109
5110               breaks[1] = loc + offset;
5111               last_breakpoint++;
5112             }
5113
5114           /* We do not support atomic sequences that use any *other*
5115              instructions but conditional branches to change the PC.
5116              Fall back to standard code to avoid losing control of
5117              execution.  */
5118           else if (thumb2_instruction_changes_pc (insn1, insn2))
5119             return 0;
5120
5121           /* If we find a strex{,b,h,d}, we're done.  */
5122           if ((insn1 & 0xfff0) == 0xe840
5123               || ((insn1 & 0xfff0) == 0xe8c0 && (insn2 & 0x00c0) == 0x0040))
5124             break;
5125         }
5126     }
5127
5128   /* If we didn't find the strex{,b,h,d}, we cannot handle the sequence.  */
5129   if (insn_count == atomic_sequence_length)
5130     return 0;
5131
5132   /* Insert a breakpoint right after the end of the atomic sequence.  */
5133   breaks[0] = loc;
5134
5135   /* Check for duplicated breakpoints.  Check also for a breakpoint
5136      placed (branch instruction's destination) anywhere in sequence.  */
5137   if (last_breakpoint
5138       && (breaks[1] == breaks[0]
5139           || (breaks[1] >= pc && breaks[1] < loc)))
5140     last_breakpoint = 0;
5141
5142   /* Effectively inserts the breakpoints.  */
5143   for (index = 0; index <= last_breakpoint; index++)
5144     arm_insert_single_step_breakpoint (gdbarch, aspace,
5145                                        MAKE_THUMB_ADDR (breaks[index]));
5146
5147   return 1;
5148 }
5149
5150 static int
5151 arm_deal_with_atomic_sequence_raw (struct frame_info *frame)
5152 {
5153   struct gdbarch *gdbarch = get_frame_arch (frame);
5154   struct address_space *aspace = get_frame_address_space (frame);
5155   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
5156   CORE_ADDR pc = get_frame_pc (frame);
5157   CORE_ADDR breaks[2] = {-1, -1};
5158   CORE_ADDR loc = pc;
5159   unsigned int insn;
5160   int insn_count;
5161   int index;
5162   int last_breakpoint = 0; /* Defaults to 0 (no breakpoints placed).  */
5163   const int atomic_sequence_length = 16; /* Instruction sequence length.  */
5164
5165   /* Assume all atomic sequences start with a ldrex{,b,h,d} instruction.
5166      Note that we do not currently support conditionally executed atomic
5167      instructions.  */
5168   insn = read_memory_unsigned_integer (loc, 4, byte_order_for_code);
5169   loc += 4;
5170   if ((insn & 0xff9000f0) != 0xe1900090)
5171     return 0;
5172
5173   /* Assume that no atomic sequence is longer than "atomic_sequence_length"
5174      instructions.  */
5175   for (insn_count = 0; insn_count < atomic_sequence_length; ++insn_count)
5176     {
5177       insn = read_memory_unsigned_integer (loc, 4, byte_order_for_code);
5178       loc += 4;
5179
5180       /* Assume that there is at most one conditional branch in the atomic
5181          sequence.  If a conditional branch is found, put a breakpoint in
5182          its destination address.  */
5183       if (bits (insn, 24, 27) == 0xa)
5184         {
5185           if (last_breakpoint > 0)
5186             return 0; /* More than one conditional branch found, fallback
5187                          to the standard single-step code.  */
5188
5189           breaks[1] = BranchDest (loc - 4, insn);
5190           last_breakpoint++;
5191         }
5192
5193       /* We do not support atomic sequences that use any *other* instructions
5194          but conditional branches to change the PC.  Fall back to standard
5195          code to avoid losing control of execution.  */
5196       else if (arm_instruction_changes_pc (insn))
5197         return 0;
5198
5199       /* If we find a strex{,b,h,d}, we're done.  */
5200       if ((insn & 0xff9000f0) == 0xe1800090)
5201         break;
5202     }
5203
5204   /* If we didn't find the strex{,b,h,d}, we cannot handle the sequence.  */
5205   if (insn_count == atomic_sequence_length)
5206     return 0;
5207
5208   /* Insert a breakpoint right after the end of the atomic sequence.  */
5209   breaks[0] = loc;
5210
5211   /* Check for duplicated breakpoints.  Check also for a breakpoint
5212      placed (branch instruction's destination) anywhere in sequence.  */
5213   if (last_breakpoint
5214       && (breaks[1] == breaks[0]
5215           || (breaks[1] >= pc && breaks[1] < loc)))
5216     last_breakpoint = 0;
5217
5218   /* Effectively inserts the breakpoints.  */
5219   for (index = 0; index <= last_breakpoint; index++)
5220     arm_insert_single_step_breakpoint (gdbarch, aspace, breaks[index]);
5221
5222   return 1;
5223 }
5224
5225 int
5226 arm_deal_with_atomic_sequence (struct frame_info *frame)
5227 {
5228   if (arm_frame_is_thumb (frame))
5229     return thumb_deal_with_atomic_sequence_raw (frame);
5230   else
5231     return arm_deal_with_atomic_sequence_raw (frame);
5232 }
5233
5234 /* single_step() is called just before we want to resume the inferior,
5235    if we want to single-step it but there is no hardware or kernel
5236    single-step support.  We find the target of the coming instruction
5237    and breakpoint it.  */
5238
5239 int
5240 arm_software_single_step (struct frame_info *frame)
5241 {
5242   struct gdbarch *gdbarch = get_frame_arch (frame);
5243   struct address_space *aspace = get_frame_address_space (frame);
5244   CORE_ADDR next_pc;
5245
5246   if (arm_deal_with_atomic_sequence (frame))
5247     return 1;
5248
5249   next_pc = arm_get_next_pc (frame, get_frame_pc (frame));
5250   arm_insert_single_step_breakpoint (gdbarch, aspace, next_pc);
5251
5252   return 1;
5253 }
5254
5255 /* Given BUF, which is OLD_LEN bytes ending at ENDADDR, expand
5256    the buffer to be NEW_LEN bytes ending at ENDADDR.  Return
5257    NULL if an error occurs.  BUF is freed.  */
5258
5259 static gdb_byte *
5260 extend_buffer_earlier (gdb_byte *buf, CORE_ADDR endaddr,
5261                        int old_len, int new_len)
5262 {
5263   gdb_byte *new_buf;
5264   int bytes_to_read = new_len - old_len;
5265
5266   new_buf = xmalloc (new_len);
5267   memcpy (new_buf + bytes_to_read, buf, old_len);
5268   xfree (buf);
5269   if (target_read_memory (endaddr - new_len, new_buf, bytes_to_read) != 0)
5270     {
5271       xfree (new_buf);
5272       return NULL;
5273     }
5274   return new_buf;
5275 }
5276
5277 /* An IT block is at most the 2-byte IT instruction followed by
5278    four 4-byte instructions.  The furthest back we must search to
5279    find an IT block that affects the current instruction is thus
5280    2 + 3 * 4 == 14 bytes.  */
5281 #define MAX_IT_BLOCK_PREFIX 14
5282
5283 /* Use a quick scan if there are more than this many bytes of
5284    code.  */
5285 #define IT_SCAN_THRESHOLD 32
5286
5287 /* Adjust a breakpoint's address to move breakpoints out of IT blocks.
5288    A breakpoint in an IT block may not be hit, depending on the
5289    condition flags.  */
5290 static CORE_ADDR
5291 arm_adjust_breakpoint_address (struct gdbarch *gdbarch, CORE_ADDR bpaddr)
5292 {
5293   gdb_byte *buf;
5294   char map_type;
5295   CORE_ADDR boundary, func_start;
5296   int buf_len;
5297   enum bfd_endian order = gdbarch_byte_order_for_code (gdbarch);
5298   int i, any, last_it, last_it_count;
5299
5300   /* If we are using BKPT breakpoints, none of this is necessary.  */
5301   if (gdbarch_tdep (gdbarch)->thumb2_breakpoint == NULL)
5302     return bpaddr;
5303
5304   /* ARM mode does not have this problem.  */
5305   if (!arm_pc_is_thumb (gdbarch, bpaddr))
5306     return bpaddr;
5307
5308   /* We are setting a breakpoint in Thumb code that could potentially
5309      contain an IT block.  The first step is to find how much Thumb
5310      code there is; we do not need to read outside of known Thumb
5311      sequences.  */
5312   map_type = arm_find_mapping_symbol (bpaddr, &boundary);
5313   if (map_type == 0)
5314     /* Thumb-2 code must have mapping symbols to have a chance.  */
5315     return bpaddr;
5316
5317   bpaddr = gdbarch_addr_bits_remove (gdbarch, bpaddr);
5318
5319   if (find_pc_partial_function (bpaddr, NULL, &func_start, NULL)
5320       && func_start > boundary)
5321     boundary = func_start;
5322
5323   /* Search for a candidate IT instruction.  We have to do some fancy
5324      footwork to distinguish a real IT instruction from the second
5325      half of a 32-bit instruction, but there is no need for that if
5326      there's no candidate.  */
5327   buf_len = min (bpaddr - boundary, MAX_IT_BLOCK_PREFIX);
5328   if (buf_len == 0)
5329     /* No room for an IT instruction.  */
5330     return bpaddr;
5331
5332   buf = xmalloc (buf_len);
5333   if (target_read_memory (bpaddr - buf_len, buf, buf_len) != 0)
5334     return bpaddr;
5335   any = 0;
5336   for (i = 0; i < buf_len; i += 2)
5337     {
5338       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5339       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
5340         {
5341           any = 1;
5342           break;
5343         }
5344     }
5345   if (any == 0)
5346     {
5347       xfree (buf);
5348       return bpaddr;
5349     }
5350
5351   /* OK, the code bytes before this instruction contain at least one
5352      halfword which resembles an IT instruction.  We know that it's
5353      Thumb code, but there are still two possibilities.  Either the
5354      halfword really is an IT instruction, or it is the second half of
5355      a 32-bit Thumb instruction.  The only way we can tell is to
5356      scan forwards from a known instruction boundary.  */
5357   if (bpaddr - boundary > IT_SCAN_THRESHOLD)
5358     {
5359       int definite;
5360
5361       /* There's a lot of code before this instruction.  Start with an
5362          optimistic search; it's easy to recognize halfwords that can
5363          not be the start of a 32-bit instruction, and use that to
5364          lock on to the instruction boundaries.  */
5365       buf = extend_buffer_earlier (buf, bpaddr, buf_len, IT_SCAN_THRESHOLD);
5366       if (buf == NULL)
5367         return bpaddr;
5368       buf_len = IT_SCAN_THRESHOLD;
5369
5370       definite = 0;
5371       for (i = 0; i < buf_len - sizeof (buf) && ! definite; i += 2)
5372         {
5373           unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5374           if (thumb_insn_size (inst1) == 2)
5375             {
5376               definite = 1;
5377               break;
5378             }
5379         }
5380
5381       /* At this point, if DEFINITE, BUF[I] is the first place we
5382          are sure that we know the instruction boundaries, and it is far
5383          enough from BPADDR that we could not miss an IT instruction
5384          affecting BPADDR.  If ! DEFINITE, give up - start from a
5385          known boundary.  */
5386       if (! definite)
5387         {
5388           buf = extend_buffer_earlier (buf, bpaddr, buf_len,
5389                                        bpaddr - boundary);
5390           if (buf == NULL)
5391             return bpaddr;
5392           buf_len = bpaddr - boundary;
5393           i = 0;
5394         }
5395     }
5396   else
5397     {
5398       buf = extend_buffer_earlier (buf, bpaddr, buf_len, bpaddr - boundary);
5399       if (buf == NULL)
5400         return bpaddr;
5401       buf_len = bpaddr - boundary;
5402       i = 0;
5403     }
5404
5405   /* Scan forwards.  Find the last IT instruction before BPADDR.  */
5406   last_it = -1;
5407   last_it_count = 0;
5408   while (i < buf_len)
5409     {
5410       unsigned short inst1 = extract_unsigned_integer (&buf[i], 2, order);
5411       last_it_count--;
5412       if ((inst1 & 0xff00) == 0xbf00 && (inst1 & 0x000f) != 0)
5413         {
5414           last_it = i;
5415           if (inst1 & 0x0001)
5416             last_it_count = 4;
5417           else if (inst1 & 0x0002)
5418             last_it_count = 3;
5419           else if (inst1 & 0x0004)
5420             last_it_count = 2;
5421           else
5422             last_it_count = 1;
5423         }
5424       i += thumb_insn_size (inst1);
5425     }
5426
5427   xfree (buf);
5428
5429   if (last_it == -1)
5430     /* There wasn't really an IT instruction after all.  */
5431     return bpaddr;
5432
5433   if (last_it_count < 1)
5434     /* It was too far away.  */
5435     return bpaddr;
5436
5437   /* This really is a trouble spot.  Move the breakpoint to the IT
5438      instruction.  */
5439   return bpaddr - buf_len + last_it;
5440 }
5441
5442 /* ARM displaced stepping support.
5443
5444    Generally ARM displaced stepping works as follows:
5445
5446    1. When an instruction is to be single-stepped, it is first decoded by
5447       arm_process_displaced_insn (called from arm_displaced_step_copy_insn).
5448       Depending on the type of instruction, it is then copied to a scratch
5449       location, possibly in a modified form.  The copy_* set of functions
5450       performs such modification, as necessary.  A breakpoint is placed after
5451       the modified instruction in the scratch space to return control to GDB.
5452       Note in particular that instructions which modify the PC will no longer
5453       do so after modification.
5454
5455    2. The instruction is single-stepped, by setting the PC to the scratch
5456       location address, and resuming.  Control returns to GDB when the
5457       breakpoint is hit.
5458
5459    3. A cleanup function (cleanup_*) is called corresponding to the copy_*
5460       function used for the current instruction.  This function's job is to
5461       put the CPU/memory state back to what it would have been if the
5462       instruction had been executed unmodified in its original location.  */
5463
5464 /* NOP instruction (mov r0, r0).  */
5465 #define ARM_NOP                         0xe1a00000
5466 #define THUMB_NOP 0x4600
5467
5468 /* Helper for register reads for displaced stepping.  In particular, this
5469    returns the PC as it would be seen by the instruction at its original
5470    location.  */
5471
5472 ULONGEST
5473 displaced_read_reg (struct regcache *regs, struct displaced_step_closure *dsc,
5474                     int regno)
5475 {
5476   ULONGEST ret;
5477   CORE_ADDR from = dsc->insn_addr;
5478
5479   if (regno == ARM_PC_REGNUM)
5480     {
5481       /* Compute pipeline offset:
5482          - When executing an ARM instruction, PC reads as the address of the
5483          current instruction plus 8.
5484          - When executing a Thumb instruction, PC reads as the address of the
5485          current instruction plus 4.  */
5486
5487       if (!dsc->is_thumb)
5488         from += 8;
5489       else
5490         from += 4;
5491
5492       if (debug_displaced)
5493         fprintf_unfiltered (gdb_stdlog, "displaced: read pc value %.8lx\n",
5494                             (unsigned long) from);
5495       return (ULONGEST) from;
5496     }
5497   else
5498     {
5499       regcache_cooked_read_unsigned (regs, regno, &ret);
5500       if (debug_displaced)
5501         fprintf_unfiltered (gdb_stdlog, "displaced: read r%d value %.8lx\n",
5502                             regno, (unsigned long) ret);
5503       return ret;
5504     }
5505 }
5506
5507 static int
5508 displaced_in_arm_mode (struct regcache *regs)
5509 {
5510   ULONGEST ps;
5511   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5512
5513   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5514
5515   return (ps & t_bit) == 0;
5516 }
5517
5518 /* Write to the PC as from a branch instruction.  */
5519
5520 static void
5521 branch_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5522                  ULONGEST val)
5523 {
5524   if (!dsc->is_thumb)
5525     /* Note: If bits 0/1 are set, this branch would be unpredictable for
5526        architecture versions < 6.  */
5527     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5528                                     val & ~(ULONGEST) 0x3);
5529   else
5530     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
5531                                     val & ~(ULONGEST) 0x1);
5532 }
5533
5534 /* Write to the PC as from a branch-exchange instruction.  */
5535
5536 static void
5537 bx_write_pc (struct regcache *regs, ULONGEST val)
5538 {
5539   ULONGEST ps;
5540   ULONGEST t_bit = arm_psr_thumb_bit (get_regcache_arch (regs));
5541
5542   regcache_cooked_read_unsigned (regs, ARM_PS_REGNUM, &ps);
5543
5544   if ((val & 1) == 1)
5545     {
5546       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps | t_bit);
5547       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffe);
5548     }
5549   else if ((val & 2) == 0)
5550     {
5551       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5552       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val);
5553     }
5554   else
5555     {
5556       /* Unpredictable behaviour.  Try to do something sensible (switch to ARM
5557           mode, align dest to 4 bytes).  */
5558       warning (_("Single-stepping BX to non-word-aligned ARM instruction."));
5559       regcache_cooked_write_unsigned (regs, ARM_PS_REGNUM, ps & ~t_bit);
5560       regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM, val & 0xfffffffc);
5561     }
5562 }
5563
5564 /* Write to the PC as if from a load instruction.  */
5565
5566 static void
5567 load_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5568                ULONGEST val)
5569 {
5570   if (DISPLACED_STEPPING_ARCH_VERSION >= 5)
5571     bx_write_pc (regs, val);
5572   else
5573     branch_write_pc (regs, dsc, val);
5574 }
5575
5576 /* Write to the PC as if from an ALU instruction.  */
5577
5578 static void
5579 alu_write_pc (struct regcache *regs, struct displaced_step_closure *dsc,
5580               ULONGEST val)
5581 {
5582   if (DISPLACED_STEPPING_ARCH_VERSION >= 7 && !dsc->is_thumb)
5583     bx_write_pc (regs, val);
5584   else
5585     branch_write_pc (regs, dsc, val);
5586 }
5587
5588 /* Helper for writing to registers for displaced stepping.  Writing to the PC
5589    has a varying effects depending on the instruction which does the write:
5590    this is controlled by the WRITE_PC argument.  */
5591
5592 void
5593 displaced_write_reg (struct regcache *regs, struct displaced_step_closure *dsc,
5594                      int regno, ULONGEST val, enum pc_write_style write_pc)
5595 {
5596   if (regno == ARM_PC_REGNUM)
5597     {
5598       if (debug_displaced)
5599         fprintf_unfiltered (gdb_stdlog, "displaced: writing pc %.8lx\n",
5600                             (unsigned long) val);
5601       switch (write_pc)
5602         {
5603         case BRANCH_WRITE_PC:
5604           branch_write_pc (regs, dsc, val);
5605           break;
5606
5607         case BX_WRITE_PC:
5608           bx_write_pc (regs, val);
5609           break;
5610
5611         case LOAD_WRITE_PC:
5612           load_write_pc (regs, dsc, val);
5613           break;
5614
5615         case ALU_WRITE_PC:
5616           alu_write_pc (regs, dsc, val);
5617           break;
5618
5619         case CANNOT_WRITE_PC:
5620           warning (_("Instruction wrote to PC in an unexpected way when "
5621                      "single-stepping"));
5622           break;
5623
5624         default:
5625           internal_error (__FILE__, __LINE__,
5626                           _("Invalid argument to displaced_write_reg"));
5627         }
5628
5629       dsc->wrote_to_pc = 1;
5630     }
5631   else
5632     {
5633       if (debug_displaced)
5634         fprintf_unfiltered (gdb_stdlog, "displaced: writing r%d value %.8lx\n",
5635                             regno, (unsigned long) val);
5636       regcache_cooked_write_unsigned (regs, regno, val);
5637     }
5638 }
5639
5640 /* This function is used to concisely determine if an instruction INSN
5641    references PC.  Register fields of interest in INSN should have the
5642    corresponding fields of BITMASK set to 0b1111.  The function
5643    returns return 1 if any of these fields in INSN reference the PC
5644    (also 0b1111, r15), else it returns 0.  */
5645
5646 static int
5647 insn_references_pc (uint32_t insn, uint32_t bitmask)
5648 {
5649   uint32_t lowbit = 1;
5650
5651   while (bitmask != 0)
5652     {
5653       uint32_t mask;
5654
5655       for (; lowbit && (bitmask & lowbit) == 0; lowbit <<= 1)
5656         ;
5657
5658       if (!lowbit)
5659         break;
5660
5661       mask = lowbit * 0xf;
5662
5663       if ((insn & mask) == mask)
5664         return 1;
5665
5666       bitmask &= ~mask;
5667     }
5668
5669   return 0;
5670 }
5671
5672 /* The simplest copy function.  Many instructions have the same effect no
5673    matter what address they are executed at: in those cases, use this.  */
5674
5675 static int
5676 arm_copy_unmodified (struct gdbarch *gdbarch, uint32_t insn,
5677                      const char *iname, struct displaced_step_closure *dsc)
5678 {
5679   if (debug_displaced)
5680     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx, "
5681                         "opcode/class '%s' unmodified\n", (unsigned long) insn,
5682                         iname);
5683
5684   dsc->modinsn[0] = insn;
5685
5686   return 0;
5687 }
5688
5689 static int
5690 thumb_copy_unmodified_32bit (struct gdbarch *gdbarch, uint16_t insn1,
5691                              uint16_t insn2, const char *iname,
5692                              struct displaced_step_closure *dsc)
5693 {
5694   if (debug_displaced)
5695     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x %.4x, "
5696                         "opcode/class '%s' unmodified\n", insn1, insn2,
5697                         iname);
5698
5699   dsc->modinsn[0] = insn1;
5700   dsc->modinsn[1] = insn2;
5701   dsc->numinsns = 2;
5702
5703   return 0;
5704 }
5705
5706 /* Copy 16-bit Thumb(Thumb and 16-bit Thumb-2) instruction without any
5707    modification.  */
5708 static int
5709 thumb_copy_unmodified_16bit (struct gdbarch *gdbarch, unsigned int insn,
5710                              const char *iname,
5711                              struct displaced_step_closure *dsc)
5712 {
5713   if (debug_displaced)
5714     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x, "
5715                         "opcode/class '%s' unmodified\n", insn,
5716                         iname);
5717
5718   dsc->modinsn[0] = insn;
5719
5720   return 0;
5721 }
5722
5723 /* Preload instructions with immediate offset.  */
5724
5725 static void
5726 cleanup_preload (struct gdbarch *gdbarch,
5727                  struct regcache *regs, struct displaced_step_closure *dsc)
5728 {
5729   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5730   if (!dsc->u.preload.immed)
5731     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
5732 }
5733
5734 static void
5735 install_preload (struct gdbarch *gdbarch, struct regcache *regs,
5736                  struct displaced_step_closure *dsc, unsigned int rn)
5737 {
5738   ULONGEST rn_val;
5739   /* Preload instructions:
5740
5741      {pli/pld} [rn, #+/-imm]
5742      ->
5743      {pli/pld} [r0, #+/-imm].  */
5744
5745   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5746   rn_val = displaced_read_reg (regs, dsc, rn);
5747   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5748   dsc->u.preload.immed = 1;
5749
5750   dsc->cleanup = &cleanup_preload;
5751 }
5752
5753 static int
5754 arm_copy_preload (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
5755                   struct displaced_step_closure *dsc)
5756 {
5757   unsigned int rn = bits (insn, 16, 19);
5758
5759   if (!insn_references_pc (insn, 0x000f0000ul))
5760     return arm_copy_unmodified (gdbarch, insn, "preload", dsc);
5761
5762   if (debug_displaced)
5763     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5764                         (unsigned long) insn);
5765
5766   dsc->modinsn[0] = insn & 0xfff0ffff;
5767
5768   install_preload (gdbarch, regs, dsc, rn);
5769
5770   return 0;
5771 }
5772
5773 static int
5774 thumb2_copy_preload (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
5775                      struct regcache *regs, struct displaced_step_closure *dsc)
5776 {
5777   unsigned int rn = bits (insn1, 0, 3);
5778   unsigned int u_bit = bit (insn1, 7);
5779   int imm12 = bits (insn2, 0, 11);
5780   ULONGEST pc_val;
5781
5782   if (rn != ARM_PC_REGNUM)
5783     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "preload", dsc);
5784
5785   /* PC is only allowed to use in PLI (immediate,literal) Encoding T3, and
5786      PLD (literal) Encoding T1.  */
5787   if (debug_displaced)
5788     fprintf_unfiltered (gdb_stdlog,
5789                         "displaced: copying pld/pli pc (0x%x) %c imm12 %.4x\n",
5790                         (unsigned int) dsc->insn_addr, u_bit ? '+' : '-',
5791                         imm12);
5792
5793   if (!u_bit)
5794     imm12 = -1 * imm12;
5795
5796   /* Rewrite instruction {pli/pld} PC imm12 into:
5797      Prepare: tmp[0] <- r0, tmp[1] <- r1, r0 <- pc, r1 <- imm12
5798
5799      {pli/pld} [r0, r1]
5800
5801      Cleanup: r0 <- tmp[0], r1 <- tmp[1].  */
5802
5803   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5804   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
5805
5806   pc_val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
5807
5808   displaced_write_reg (regs, dsc, 0, pc_val, CANNOT_WRITE_PC);
5809   displaced_write_reg (regs, dsc, 1, imm12, CANNOT_WRITE_PC);
5810   dsc->u.preload.immed = 0;
5811
5812   /* {pli/pld} [r0, r1] */
5813   dsc->modinsn[0] = insn1 & 0xfff0;
5814   dsc->modinsn[1] = 0xf001;
5815   dsc->numinsns = 2;
5816
5817   dsc->cleanup = &cleanup_preload;
5818   return 0;
5819 }
5820
5821 /* Preload instructions with register offset.  */
5822
5823 static void
5824 install_preload_reg(struct gdbarch *gdbarch, struct regcache *regs,
5825                     struct displaced_step_closure *dsc, unsigned int rn,
5826                     unsigned int rm)
5827 {
5828   ULONGEST rn_val, rm_val;
5829
5830   /* Preload register-offset instructions:
5831
5832      {pli/pld} [rn, rm {, shift}]
5833      ->
5834      {pli/pld} [r0, r1 {, shift}].  */
5835
5836   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5837   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
5838   rn_val = displaced_read_reg (regs, dsc, rn);
5839   rm_val = displaced_read_reg (regs, dsc, rm);
5840   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5841   displaced_write_reg (regs, dsc, 1, rm_val, CANNOT_WRITE_PC);
5842   dsc->u.preload.immed = 0;
5843
5844   dsc->cleanup = &cleanup_preload;
5845 }
5846
5847 static int
5848 arm_copy_preload_reg (struct gdbarch *gdbarch, uint32_t insn,
5849                       struct regcache *regs,
5850                       struct displaced_step_closure *dsc)
5851 {
5852   unsigned int rn = bits (insn, 16, 19);
5853   unsigned int rm = bits (insn, 0, 3);
5854
5855
5856   if (!insn_references_pc (insn, 0x000f000ful))
5857     return arm_copy_unmodified (gdbarch, insn, "preload reg", dsc);
5858
5859   if (debug_displaced)
5860     fprintf_unfiltered (gdb_stdlog, "displaced: copying preload insn %.8lx\n",
5861                         (unsigned long) insn);
5862
5863   dsc->modinsn[0] = (insn & 0xfff0fff0) | 0x1;
5864
5865   install_preload_reg (gdbarch, regs, dsc, rn, rm);
5866   return 0;
5867 }
5868
5869 /* Copy/cleanup coprocessor load and store instructions.  */
5870
5871 static void
5872 cleanup_copro_load_store (struct gdbarch *gdbarch,
5873                           struct regcache *regs,
5874                           struct displaced_step_closure *dsc)
5875 {
5876   ULONGEST rn_val = displaced_read_reg (regs, dsc, 0);
5877
5878   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
5879
5880   if (dsc->u.ldst.writeback)
5881     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, LOAD_WRITE_PC);
5882 }
5883
5884 static void
5885 install_copro_load_store (struct gdbarch *gdbarch, struct regcache *regs,
5886                           struct displaced_step_closure *dsc,
5887                           int writeback, unsigned int rn)
5888 {
5889   ULONGEST rn_val;
5890
5891   /* Coprocessor load/store instructions:
5892
5893      {stc/stc2} [<Rn>, #+/-imm]  (and other immediate addressing modes)
5894      ->
5895      {stc/stc2} [r0, #+/-imm].
5896
5897      ldc/ldc2 are handled identically.  */
5898
5899   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
5900   rn_val = displaced_read_reg (regs, dsc, rn);
5901   /* PC should be 4-byte aligned.  */
5902   rn_val = rn_val & 0xfffffffc;
5903   displaced_write_reg (regs, dsc, 0, rn_val, CANNOT_WRITE_PC);
5904
5905   dsc->u.ldst.writeback = writeback;
5906   dsc->u.ldst.rn = rn;
5907
5908   dsc->cleanup = &cleanup_copro_load_store;
5909 }
5910
5911 static int
5912 arm_copy_copro_load_store (struct gdbarch *gdbarch, uint32_t insn,
5913                            struct regcache *regs,
5914                            struct displaced_step_closure *dsc)
5915 {
5916   unsigned int rn = bits (insn, 16, 19);
5917
5918   if (!insn_references_pc (insn, 0x000f0000ul))
5919     return arm_copy_unmodified (gdbarch, insn, "copro load/store", dsc);
5920
5921   if (debug_displaced)
5922     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
5923                         "load/store insn %.8lx\n", (unsigned long) insn);
5924
5925   dsc->modinsn[0] = insn & 0xfff0ffff;
5926
5927   install_copro_load_store (gdbarch, regs, dsc, bit (insn, 25), rn);
5928
5929   return 0;
5930 }
5931
5932 static int
5933 thumb2_copy_copro_load_store (struct gdbarch *gdbarch, uint16_t insn1,
5934                               uint16_t insn2, struct regcache *regs,
5935                               struct displaced_step_closure *dsc)
5936 {
5937   unsigned int rn = bits (insn1, 0, 3);
5938
5939   if (rn != ARM_PC_REGNUM)
5940     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
5941                                         "copro load/store", dsc);
5942
5943   if (debug_displaced)
5944     fprintf_unfiltered (gdb_stdlog, "displaced: copying coprocessor "
5945                         "load/store insn %.4x%.4x\n", insn1, insn2);
5946
5947   dsc->modinsn[0] = insn1 & 0xfff0;
5948   dsc->modinsn[1] = insn2;
5949   dsc->numinsns = 2;
5950
5951   /* This function is called for copying instruction LDC/LDC2/VLDR, which
5952      doesn't support writeback, so pass 0.  */
5953   install_copro_load_store (gdbarch, regs, dsc, 0, rn);
5954
5955   return 0;
5956 }
5957
5958 /* Clean up branch instructions (actually perform the branch, by setting
5959    PC).  */
5960
5961 static void
5962 cleanup_branch (struct gdbarch *gdbarch, struct regcache *regs,
5963                 struct displaced_step_closure *dsc)
5964 {
5965   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
5966   int branch_taken = condition_true (dsc->u.branch.cond, status);
5967   enum pc_write_style write_pc = dsc->u.branch.exchange
5968                                  ? BX_WRITE_PC : BRANCH_WRITE_PC;
5969
5970   if (!branch_taken)
5971     return;
5972
5973   if (dsc->u.branch.link)
5974     {
5975       /* The value of LR should be the next insn of current one.  In order
5976        not to confuse logic hanlding later insn `bx lr', if current insn mode
5977        is Thumb, the bit 0 of LR value should be set to 1.  */
5978       ULONGEST next_insn_addr = dsc->insn_addr + dsc->insn_size;
5979
5980       if (dsc->is_thumb)
5981         next_insn_addr |= 0x1;
5982
5983       displaced_write_reg (regs, dsc, ARM_LR_REGNUM, next_insn_addr,
5984                            CANNOT_WRITE_PC);
5985     }
5986
5987   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, dsc->u.branch.dest, write_pc);
5988 }
5989
5990 /* Copy B/BL/BLX instructions with immediate destinations.  */
5991
5992 static void
5993 install_b_bl_blx (struct gdbarch *gdbarch, struct regcache *regs,
5994                   struct displaced_step_closure *dsc,
5995                   unsigned int cond, int exchange, int link, long offset)
5996 {
5997   /* Implement "BL<cond> <label>" as:
5998
5999      Preparation: cond <- instruction condition
6000      Insn: mov r0, r0  (nop)
6001      Cleanup: if (condition true) { r14 <- pc; pc <- label }.
6002
6003      B<cond> similar, but don't set r14 in cleanup.  */
6004
6005   dsc->u.branch.cond = cond;
6006   dsc->u.branch.link = link;
6007   dsc->u.branch.exchange = exchange;
6008
6009   dsc->u.branch.dest = dsc->insn_addr;
6010   if (link && exchange)
6011     /* For BLX, offset is computed from the Align (PC, 4).  */
6012     dsc->u.branch.dest = dsc->u.branch.dest & 0xfffffffc;
6013
6014   if (dsc->is_thumb)
6015     dsc->u.branch.dest += 4 + offset;
6016   else
6017     dsc->u.branch.dest += 8 + offset;
6018
6019   dsc->cleanup = &cleanup_branch;
6020 }
6021 static int
6022 arm_copy_b_bl_blx (struct gdbarch *gdbarch, uint32_t insn,
6023                    struct regcache *regs, struct displaced_step_closure *dsc)
6024 {
6025   unsigned int cond = bits (insn, 28, 31);
6026   int exchange = (cond == 0xf);
6027   int link = exchange || bit (insn, 24);
6028   long offset;
6029
6030   if (debug_displaced)
6031     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s immediate insn "
6032                         "%.8lx\n", (exchange) ? "blx" : (link) ? "bl" : "b",
6033                         (unsigned long) insn);
6034   if (exchange)
6035     /* For BLX, set bit 0 of the destination.  The cleanup_branch function will
6036        then arrange the switch into Thumb mode.  */
6037     offset = (bits (insn, 0, 23) << 2) | (bit (insn, 24) << 1) | 1;
6038   else
6039     offset = bits (insn, 0, 23) << 2;
6040
6041   if (bit (offset, 25))
6042     offset = offset | ~0x3ffffff;
6043
6044   dsc->modinsn[0] = ARM_NOP;
6045
6046   install_b_bl_blx (gdbarch, regs, dsc, cond, exchange, link, offset);
6047   return 0;
6048 }
6049
6050 static int
6051 thumb2_copy_b_bl_blx (struct gdbarch *gdbarch, uint16_t insn1,
6052                       uint16_t insn2, struct regcache *regs,
6053                       struct displaced_step_closure *dsc)
6054 {
6055   int link = bit (insn2, 14);
6056   int exchange = link && !bit (insn2, 12);
6057   int cond = INST_AL;
6058   long offset = 0;
6059   int j1 = bit (insn2, 13);
6060   int j2 = bit (insn2, 11);
6061   int s = sbits (insn1, 10, 10);
6062   int i1 = !(j1 ^ bit (insn1, 10));
6063   int i2 = !(j2 ^ bit (insn1, 10));
6064
6065   if (!link && !exchange) /* B */
6066     {
6067       offset = (bits (insn2, 0, 10) << 1);
6068       if (bit (insn2, 12)) /* Encoding T4 */
6069         {
6070           offset |= (bits (insn1, 0, 9) << 12)
6071             | (i2 << 22)
6072             | (i1 << 23)
6073             | (s << 24);
6074           cond = INST_AL;
6075         }
6076       else /* Encoding T3 */
6077         {
6078           offset |= (bits (insn1, 0, 5) << 12)
6079             | (j1 << 18)
6080             | (j2 << 19)
6081             | (s << 20);
6082           cond = bits (insn1, 6, 9);
6083         }
6084     }
6085   else
6086     {
6087       offset = (bits (insn1, 0, 9) << 12);
6088       offset |= ((i2 << 22) | (i1 << 23) | (s << 24));
6089       offset |= exchange ?
6090         (bits (insn2, 1, 10) << 2) : (bits (insn2, 0, 10) << 1);
6091     }
6092
6093   if (debug_displaced)
6094     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s insn "
6095                         "%.4x %.4x with offset %.8lx\n",
6096                         link ? (exchange) ? "blx" : "bl" : "b",
6097                         insn1, insn2, offset);
6098
6099   dsc->modinsn[0] = THUMB_NOP;
6100
6101   install_b_bl_blx (gdbarch, regs, dsc, cond, exchange, link, offset);
6102   return 0;
6103 }
6104
6105 /* Copy B Thumb instructions.  */
6106 static int
6107 thumb_copy_b (struct gdbarch *gdbarch, unsigned short insn,
6108               struct displaced_step_closure *dsc)
6109 {
6110   unsigned int cond = 0;
6111   int offset = 0;
6112   unsigned short bit_12_15 = bits (insn, 12, 15);
6113   CORE_ADDR from = dsc->insn_addr;
6114
6115   if (bit_12_15 == 0xd)
6116     {
6117       /* offset = SignExtend (imm8:0, 32) */
6118       offset = sbits ((insn << 1), 0, 8);
6119       cond = bits (insn, 8, 11);
6120     }
6121   else if (bit_12_15 == 0xe) /* Encoding T2 */
6122     {
6123       offset = sbits ((insn << 1), 0, 11);
6124       cond = INST_AL;
6125     }
6126
6127   if (debug_displaced)
6128     fprintf_unfiltered (gdb_stdlog,
6129                         "displaced: copying b immediate insn %.4x "
6130                         "with offset %d\n", insn, offset);
6131
6132   dsc->u.branch.cond = cond;
6133   dsc->u.branch.link = 0;
6134   dsc->u.branch.exchange = 0;
6135   dsc->u.branch.dest = from + 4 + offset;
6136
6137   dsc->modinsn[0] = THUMB_NOP;
6138
6139   dsc->cleanup = &cleanup_branch;
6140
6141   return 0;
6142 }
6143
6144 /* Copy BX/BLX with register-specified destinations.  */
6145
6146 static void
6147 install_bx_blx_reg (struct gdbarch *gdbarch, struct regcache *regs,
6148                     struct displaced_step_closure *dsc, int link,
6149                     unsigned int cond, unsigned int rm)
6150 {
6151   /* Implement {BX,BLX}<cond> <reg>" as:
6152
6153      Preparation: cond <- instruction condition
6154      Insn: mov r0, r0 (nop)
6155      Cleanup: if (condition true) { r14 <- pc; pc <- dest; }.
6156
6157      Don't set r14 in cleanup for BX.  */
6158
6159   dsc->u.branch.dest = displaced_read_reg (regs, dsc, rm);
6160
6161   dsc->u.branch.cond = cond;
6162   dsc->u.branch.link = link;
6163
6164   dsc->u.branch.exchange = 1;
6165
6166   dsc->cleanup = &cleanup_branch;
6167 }
6168
6169 static int
6170 arm_copy_bx_blx_reg (struct gdbarch *gdbarch, uint32_t insn,
6171                      struct regcache *regs, struct displaced_step_closure *dsc)
6172 {
6173   unsigned int cond = bits (insn, 28, 31);
6174   /* BX:  x12xxx1x
6175      BLX: x12xxx3x.  */
6176   int link = bit (insn, 5);
6177   unsigned int rm = bits (insn, 0, 3);
6178
6179   if (debug_displaced)
6180     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.8lx",
6181                         (unsigned long) insn);
6182
6183   dsc->modinsn[0] = ARM_NOP;
6184
6185   install_bx_blx_reg (gdbarch, regs, dsc, link, cond, rm);
6186   return 0;
6187 }
6188
6189 static int
6190 thumb_copy_bx_blx_reg (struct gdbarch *gdbarch, uint16_t insn,
6191                        struct regcache *regs,
6192                        struct displaced_step_closure *dsc)
6193 {
6194   int link = bit (insn, 7);
6195   unsigned int rm = bits (insn, 3, 6);
6196
6197   if (debug_displaced)
6198     fprintf_unfiltered (gdb_stdlog, "displaced: copying insn %.4x",
6199                         (unsigned short) insn);
6200
6201   dsc->modinsn[0] = THUMB_NOP;
6202
6203   install_bx_blx_reg (gdbarch, regs, dsc, link, INST_AL, rm);
6204
6205   return 0;
6206 }
6207
6208
6209 /* Copy/cleanup arithmetic/logic instruction with immediate RHS.  */
6210
6211 static void
6212 cleanup_alu_imm (struct gdbarch *gdbarch,
6213                  struct regcache *regs, struct displaced_step_closure *dsc)
6214 {
6215   ULONGEST rd_val = displaced_read_reg (regs, dsc, 0);
6216   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6217   displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6218   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6219 }
6220
6221 static int
6222 arm_copy_alu_imm (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6223                   struct displaced_step_closure *dsc)
6224 {
6225   unsigned int rn = bits (insn, 16, 19);
6226   unsigned int rd = bits (insn, 12, 15);
6227   unsigned int op = bits (insn, 21, 24);
6228   int is_mov = (op == 0xd);
6229   ULONGEST rd_val, rn_val;
6230
6231   if (!insn_references_pc (insn, 0x000ff000ul))
6232     return arm_copy_unmodified (gdbarch, insn, "ALU immediate", dsc);
6233
6234   if (debug_displaced)
6235     fprintf_unfiltered (gdb_stdlog, "displaced: copying immediate %s insn "
6236                         "%.8lx\n", is_mov ? "move" : "ALU",
6237                         (unsigned long) insn);
6238
6239   /* Instruction is of form:
6240
6241      <op><cond> rd, [rn,] #imm
6242
6243      Rewrite as:
6244
6245      Preparation: tmp1, tmp2 <- r0, r1;
6246                   r0, r1 <- rd, rn
6247      Insn: <op><cond> r0, r1, #imm
6248      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
6249   */
6250
6251   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6252   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6253   rn_val = displaced_read_reg (regs, dsc, rn);
6254   rd_val = displaced_read_reg (regs, dsc, rd);
6255   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6256   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6257   dsc->rd = rd;
6258
6259   if (is_mov)
6260     dsc->modinsn[0] = insn & 0xfff00fff;
6261   else
6262     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x10000;
6263
6264   dsc->cleanup = &cleanup_alu_imm;
6265
6266   return 0;
6267 }
6268
6269 static int
6270 thumb2_copy_alu_imm (struct gdbarch *gdbarch, uint16_t insn1,
6271                      uint16_t insn2, struct regcache *regs,
6272                      struct displaced_step_closure *dsc)
6273 {
6274   unsigned int op = bits (insn1, 5, 8);
6275   unsigned int rn, rm, rd;
6276   ULONGEST rd_val, rn_val;
6277
6278   rn = bits (insn1, 0, 3); /* Rn */
6279   rm = bits (insn2, 0, 3); /* Rm */
6280   rd = bits (insn2, 8, 11); /* Rd */
6281
6282   /* This routine is only called for instruction MOV.  */
6283   gdb_assert (op == 0x2 && rn == 0xf);
6284
6285   if (rm != ARM_PC_REGNUM && rd != ARM_PC_REGNUM)
6286     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "ALU imm", dsc);
6287
6288   if (debug_displaced)
6289     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.4x%.4x\n",
6290                         "ALU", insn1, insn2);
6291
6292   /* Instruction is of form:
6293
6294      <op><cond> rd, [rn,] #imm
6295
6296      Rewrite as:
6297
6298      Preparation: tmp1, tmp2 <- r0, r1;
6299                   r0, r1 <- rd, rn
6300      Insn: <op><cond> r0, r1, #imm
6301      Cleanup: rd <- r0; r0 <- tmp1; r1 <- tmp2
6302   */
6303
6304   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6305   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6306   rn_val = displaced_read_reg (regs, dsc, rn);
6307   rd_val = displaced_read_reg (regs, dsc, rd);
6308   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6309   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6310   dsc->rd = rd;
6311
6312   dsc->modinsn[0] = insn1;
6313   dsc->modinsn[1] = ((insn2 & 0xf0f0) | 0x1);
6314   dsc->numinsns = 2;
6315
6316   dsc->cleanup = &cleanup_alu_imm;
6317
6318   return 0;
6319 }
6320
6321 /* Copy/cleanup arithmetic/logic insns with register RHS.  */
6322
6323 static void
6324 cleanup_alu_reg (struct gdbarch *gdbarch,
6325                  struct regcache *regs, struct displaced_step_closure *dsc)
6326 {
6327   ULONGEST rd_val;
6328   int i;
6329
6330   rd_val = displaced_read_reg (regs, dsc, 0);
6331
6332   for (i = 0; i < 3; i++)
6333     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
6334
6335   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6336 }
6337
6338 static void
6339 install_alu_reg (struct gdbarch *gdbarch, struct regcache *regs,
6340                  struct displaced_step_closure *dsc,
6341                  unsigned int rd, unsigned int rn, unsigned int rm)
6342 {
6343   ULONGEST rd_val, rn_val, rm_val;
6344
6345   /* Instruction is of form:
6346
6347      <op><cond> rd, [rn,] rm [, <shift>]
6348
6349      Rewrite as:
6350
6351      Preparation: tmp1, tmp2, tmp3 <- r0, r1, r2;
6352                   r0, r1, r2 <- rd, rn, rm
6353      Insn: <op><cond> r0, r1, r2 [, <shift>]
6354      Cleanup: rd <- r0; r0, r1, r2 <- tmp1, tmp2, tmp3
6355   */
6356
6357   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6358   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6359   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6360   rd_val = displaced_read_reg (regs, dsc, rd);
6361   rn_val = displaced_read_reg (regs, dsc, rn);
6362   rm_val = displaced_read_reg (regs, dsc, rm);
6363   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6364   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6365   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
6366   dsc->rd = rd;
6367
6368   dsc->cleanup = &cleanup_alu_reg;
6369 }
6370
6371 static int
6372 arm_copy_alu_reg (struct gdbarch *gdbarch, uint32_t insn, struct regcache *regs,
6373                   struct displaced_step_closure *dsc)
6374 {
6375   unsigned int op = bits (insn, 21, 24);
6376   int is_mov = (op == 0xd);
6377
6378   if (!insn_references_pc (insn, 0x000ff00ful))
6379     return arm_copy_unmodified (gdbarch, insn, "ALU reg", dsc);
6380
6381   if (debug_displaced)
6382     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.8lx\n",
6383                         is_mov ? "move" : "ALU", (unsigned long) insn);
6384
6385   if (is_mov)
6386     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x2;
6387   else
6388     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x10002;
6389
6390   install_alu_reg (gdbarch, regs, dsc, bits (insn, 12, 15), bits (insn, 16, 19),
6391                    bits (insn, 0, 3));
6392   return 0;
6393 }
6394
6395 static int
6396 thumb_copy_alu_reg (struct gdbarch *gdbarch, uint16_t insn,
6397                     struct regcache *regs,
6398                     struct displaced_step_closure *dsc)
6399 {
6400   unsigned rn, rm, rd;
6401
6402   rd = bits (insn, 3, 6);
6403   rn = (bit (insn, 7) << 3) | bits (insn, 0, 2);
6404   rm = 2;
6405
6406   if (rd != ARM_PC_REGNUM && rn != ARM_PC_REGNUM)
6407     return thumb_copy_unmodified_16bit (gdbarch, insn, "ALU reg", dsc);
6408
6409   if (debug_displaced)
6410     fprintf_unfiltered (gdb_stdlog, "displaced: copying reg %s insn %.4x\n",
6411                         "ALU", (unsigned short) insn);
6412
6413   dsc->modinsn[0] = ((insn & 0xff00) | 0x08);
6414
6415   install_alu_reg (gdbarch, regs, dsc, rd, rn, rm);
6416
6417   return 0;
6418 }
6419
6420 /* Cleanup/copy arithmetic/logic insns with shifted register RHS.  */
6421
6422 static void
6423 cleanup_alu_shifted_reg (struct gdbarch *gdbarch,
6424                          struct regcache *regs,
6425                          struct displaced_step_closure *dsc)
6426 {
6427   ULONGEST rd_val = displaced_read_reg (regs, dsc, 0);
6428   int i;
6429
6430   for (i = 0; i < 4; i++)
6431     displaced_write_reg (regs, dsc, i, dsc->tmp[i], CANNOT_WRITE_PC);
6432
6433   displaced_write_reg (regs, dsc, dsc->rd, rd_val, ALU_WRITE_PC);
6434 }
6435
6436 static void
6437 install_alu_shifted_reg (struct gdbarch *gdbarch, struct regcache *regs,
6438                          struct displaced_step_closure *dsc,
6439                          unsigned int rd, unsigned int rn, unsigned int rm,
6440                          unsigned rs)
6441 {
6442   int i;
6443   ULONGEST rd_val, rn_val, rm_val, rs_val;
6444
6445   /* Instruction is of form:
6446
6447      <op><cond> rd, [rn,] rm, <shift> rs
6448
6449      Rewrite as:
6450
6451      Preparation: tmp1, tmp2, tmp3, tmp4 <- r0, r1, r2, r3
6452                   r0, r1, r2, r3 <- rd, rn, rm, rs
6453      Insn: <op><cond> r0, r1, r2, <shift> r3
6454      Cleanup: tmp5 <- r0
6455               r0, r1, r2, r3 <- tmp1, tmp2, tmp3, tmp4
6456               rd <- tmp5
6457   */
6458
6459   for (i = 0; i < 4; i++)
6460     dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
6461
6462   rd_val = displaced_read_reg (regs, dsc, rd);
6463   rn_val = displaced_read_reg (regs, dsc, rn);
6464   rm_val = displaced_read_reg (regs, dsc, rm);
6465   rs_val = displaced_read_reg (regs, dsc, rs);
6466   displaced_write_reg (regs, dsc, 0, rd_val, CANNOT_WRITE_PC);
6467   displaced_write_reg (regs, dsc, 1, rn_val, CANNOT_WRITE_PC);
6468   displaced_write_reg (regs, dsc, 2, rm_val, CANNOT_WRITE_PC);
6469   displaced_write_reg (regs, dsc, 3, rs_val, CANNOT_WRITE_PC);
6470   dsc->rd = rd;
6471   dsc->cleanup = &cleanup_alu_shifted_reg;
6472 }
6473
6474 static int
6475 arm_copy_alu_shifted_reg (struct gdbarch *gdbarch, uint32_t insn,
6476                           struct regcache *regs,
6477                           struct displaced_step_closure *dsc)
6478 {
6479   unsigned int op = bits (insn, 21, 24);
6480   int is_mov = (op == 0xd);
6481   unsigned int rd, rn, rm, rs;
6482
6483   if (!insn_references_pc (insn, 0x000fff0ful))
6484     return arm_copy_unmodified (gdbarch, insn, "ALU shifted reg", dsc);
6485
6486   if (debug_displaced)
6487     fprintf_unfiltered (gdb_stdlog, "displaced: copying shifted reg %s insn "
6488                         "%.8lx\n", is_mov ? "move" : "ALU",
6489                         (unsigned long) insn);
6490
6491   rn = bits (insn, 16, 19);
6492   rm = bits (insn, 0, 3);
6493   rs = bits (insn, 8, 11);
6494   rd = bits (insn, 12, 15);
6495
6496   if (is_mov)
6497     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x302;
6498   else
6499     dsc->modinsn[0] = (insn & 0xfff000f0) | 0x10302;
6500
6501   install_alu_shifted_reg (gdbarch, regs, dsc, rd, rn, rm, rs);
6502
6503   return 0;
6504 }
6505
6506 /* Clean up load instructions.  */
6507
6508 static void
6509 cleanup_load (struct gdbarch *gdbarch, struct regcache *regs,
6510               struct displaced_step_closure *dsc)
6511 {
6512   ULONGEST rt_val, rt_val2 = 0, rn_val;
6513
6514   rt_val = displaced_read_reg (regs, dsc, 0);
6515   if (dsc->u.ldst.xfersize == 8)
6516     rt_val2 = displaced_read_reg (regs, dsc, 1);
6517   rn_val = displaced_read_reg (regs, dsc, 2);
6518
6519   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6520   if (dsc->u.ldst.xfersize > 4)
6521     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6522   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
6523   if (!dsc->u.ldst.immed)
6524     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
6525
6526   /* Handle register writeback.  */
6527   if (dsc->u.ldst.writeback)
6528     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
6529   /* Put result in right place.  */
6530   displaced_write_reg (regs, dsc, dsc->rd, rt_val, LOAD_WRITE_PC);
6531   if (dsc->u.ldst.xfersize == 8)
6532     displaced_write_reg (regs, dsc, dsc->rd + 1, rt_val2, LOAD_WRITE_PC);
6533 }
6534
6535 /* Clean up store instructions.  */
6536
6537 static void
6538 cleanup_store (struct gdbarch *gdbarch, struct regcache *regs,
6539                struct displaced_step_closure *dsc)
6540 {
6541   ULONGEST rn_val = displaced_read_reg (regs, dsc, 2);
6542
6543   displaced_write_reg (regs, dsc, 0, dsc->tmp[0], CANNOT_WRITE_PC);
6544   if (dsc->u.ldst.xfersize > 4)
6545     displaced_write_reg (regs, dsc, 1, dsc->tmp[1], CANNOT_WRITE_PC);
6546   displaced_write_reg (regs, dsc, 2, dsc->tmp[2], CANNOT_WRITE_PC);
6547   if (!dsc->u.ldst.immed)
6548     displaced_write_reg (regs, dsc, 3, dsc->tmp[3], CANNOT_WRITE_PC);
6549   if (!dsc->u.ldst.restore_r4)
6550     displaced_write_reg (regs, dsc, 4, dsc->tmp[4], CANNOT_WRITE_PC);
6551
6552   /* Writeback.  */
6553   if (dsc->u.ldst.writeback)
6554     displaced_write_reg (regs, dsc, dsc->u.ldst.rn, rn_val, CANNOT_WRITE_PC);
6555 }
6556
6557 /* Copy "extra" load/store instructions.  These are halfword/doubleword
6558    transfers, which have a different encoding to byte/word transfers.  */
6559
6560 static int
6561 arm_copy_extra_ld_st (struct gdbarch *gdbarch, uint32_t insn, int unpriveleged,
6562                       struct regcache *regs, struct displaced_step_closure *dsc)
6563 {
6564   unsigned int op1 = bits (insn, 20, 24);
6565   unsigned int op2 = bits (insn, 5, 6);
6566   unsigned int rt = bits (insn, 12, 15);
6567   unsigned int rn = bits (insn, 16, 19);
6568   unsigned int rm = bits (insn, 0, 3);
6569   char load[12]     = {0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1};
6570   char bytesize[12] = {2, 2, 2, 2, 8, 1, 8, 1, 8, 2, 8, 2};
6571   int immed = (op1 & 0x4) != 0;
6572   int opcode;
6573   ULONGEST rt_val, rt_val2 = 0, rn_val, rm_val = 0;
6574
6575   if (!insn_references_pc (insn, 0x000ff00ful))
6576     return arm_copy_unmodified (gdbarch, insn, "extra load/store", dsc);
6577
6578   if (debug_displaced)
6579     fprintf_unfiltered (gdb_stdlog, "displaced: copying %sextra load/store "
6580                         "insn %.8lx\n", unpriveleged ? "unpriveleged " : "",
6581                         (unsigned long) insn);
6582
6583   opcode = ((op2 << 2) | (op1 & 0x1) | ((op1 & 0x4) >> 1)) - 4;
6584
6585   if (opcode < 0)
6586     internal_error (__FILE__, __LINE__,
6587                     _("copy_extra_ld_st: instruction decode error"));
6588
6589   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6590   dsc->tmp[1] = displaced_read_reg (regs, dsc, 1);
6591   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6592   if (!immed)
6593     dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6594
6595   rt_val = displaced_read_reg (regs, dsc, rt);
6596   if (bytesize[opcode] == 8)
6597     rt_val2 = displaced_read_reg (regs, dsc, rt + 1);
6598   rn_val = displaced_read_reg (regs, dsc, rn);
6599   if (!immed)
6600     rm_val = displaced_read_reg (regs, dsc, rm);
6601
6602   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
6603   if (bytesize[opcode] == 8)
6604     displaced_write_reg (regs, dsc, 1, rt_val2, CANNOT_WRITE_PC);
6605   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
6606   if (!immed)
6607     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
6608
6609   dsc->rd = rt;
6610   dsc->u.ldst.xfersize = bytesize[opcode];
6611   dsc->u.ldst.rn = rn;
6612   dsc->u.ldst.immed = immed;
6613   dsc->u.ldst.writeback = bit (insn, 24) == 0 || bit (insn, 21) != 0;
6614   dsc->u.ldst.restore_r4 = 0;
6615
6616   if (immed)
6617     /* {ldr,str}<width><cond> rt, [rt2,] [rn, #imm]
6618         ->
6619        {ldr,str}<width><cond> r0, [r1,] [r2, #imm].  */
6620     dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
6621   else
6622     /* {ldr,str}<width><cond> rt, [rt2,] [rn, +/-rm]
6623         ->
6624        {ldr,str}<width><cond> r0, [r1,] [r2, +/-r3].  */
6625     dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
6626
6627   dsc->cleanup = load[opcode] ? &cleanup_load : &cleanup_store;
6628
6629   return 0;
6630 }
6631
6632 /* Copy byte/half word/word loads and stores.  */
6633
6634 static void
6635 install_load_store (struct gdbarch *gdbarch, struct regcache *regs,
6636                     struct displaced_step_closure *dsc, int load,
6637                     int immed, int writeback, int size, int usermode,
6638                     int rt, int rm, int rn)
6639 {
6640   ULONGEST rt_val, rn_val, rm_val = 0;
6641
6642   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6643   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6644   if (!immed)
6645     dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6646   if (!load)
6647     dsc->tmp[4] = displaced_read_reg (regs, dsc, 4);
6648
6649   rt_val = displaced_read_reg (regs, dsc, rt);
6650   rn_val = displaced_read_reg (regs, dsc, rn);
6651   if (!immed)
6652     rm_val = displaced_read_reg (regs, dsc, rm);
6653
6654   displaced_write_reg (regs, dsc, 0, rt_val, CANNOT_WRITE_PC);
6655   displaced_write_reg (regs, dsc, 2, rn_val, CANNOT_WRITE_PC);
6656   if (!immed)
6657     displaced_write_reg (regs, dsc, 3, rm_val, CANNOT_WRITE_PC);
6658   dsc->rd = rt;
6659   dsc->u.ldst.xfersize = size;
6660   dsc->u.ldst.rn = rn;
6661   dsc->u.ldst.immed = immed;
6662   dsc->u.ldst.writeback = writeback;
6663
6664   /* To write PC we can do:
6665
6666      Before this sequence of instructions:
6667      r0 is the PC value got from displaced_read_reg, so r0 = from + 8;
6668      r2 is the Rn value got from dispalced_read_reg.
6669
6670      Insn1: push {pc} Write address of STR instruction + offset on stack
6671      Insn2: pop  {r4} Read it back from stack, r4 = addr(Insn1) + offset
6672      Insn3: sub r4, r4, pc   r4 = addr(Insn1) + offset - pc
6673                                 = addr(Insn1) + offset - addr(Insn3) - 8
6674                                 = offset - 16
6675      Insn4: add r4, r4, #8   r4 = offset - 8
6676      Insn5: add r0, r0, r4   r0 = from + 8 + offset - 8
6677                                 = from + offset
6678      Insn6: str r0, [r2, #imm] (or str r0, [r2, r3])
6679
6680      Otherwise we don't know what value to write for PC, since the offset is
6681      architecture-dependent (sometimes PC+8, sometimes PC+12).  More details
6682      of this can be found in Section "Saving from r15" in
6683      http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204g/Cihbjifh.html */
6684
6685   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
6686 }
6687
6688
6689 static int
6690 thumb2_copy_load_literal (struct gdbarch *gdbarch, uint16_t insn1,
6691                           uint16_t insn2, struct regcache *regs,
6692                           struct displaced_step_closure *dsc, int size)
6693 {
6694   unsigned int u_bit = bit (insn1, 7);
6695   unsigned int rt = bits (insn2, 12, 15);
6696   int imm12 = bits (insn2, 0, 11);
6697   ULONGEST pc_val;
6698
6699   if (debug_displaced)
6700     fprintf_unfiltered (gdb_stdlog,
6701                         "displaced: copying ldr pc (0x%x) R%d %c imm12 %.4x\n",
6702                         (unsigned int) dsc->insn_addr, rt, u_bit ? '+' : '-',
6703                         imm12);
6704
6705   if (!u_bit)
6706     imm12 = -1 * imm12;
6707
6708   /* Rewrite instruction LDR Rt imm12 into:
6709
6710      Prepare: tmp[0] <- r0, tmp[1] <- r2, tmp[2] <- r3, r2 <- pc, r3 <- imm12
6711
6712      LDR R0, R2, R3,
6713
6714      Cleanup: rt <- r0, r0 <- tmp[0], r2 <- tmp[1], r3 <- tmp[2].  */
6715
6716
6717   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
6718   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
6719   dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
6720
6721   pc_val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
6722
6723   pc_val = pc_val & 0xfffffffc;
6724
6725   displaced_write_reg (regs, dsc, 2, pc_val, CANNOT_WRITE_PC);
6726   displaced_write_reg (regs, dsc, 3, imm12, CANNOT_WRITE_PC);
6727
6728   dsc->rd = rt;
6729
6730   dsc->u.ldst.xfersize = size;
6731   dsc->u.ldst.immed = 0;
6732   dsc->u.ldst.writeback = 0;
6733   dsc->u.ldst.restore_r4 = 0;
6734
6735   /* LDR R0, R2, R3 */
6736   dsc->modinsn[0] = 0xf852;
6737   dsc->modinsn[1] = 0x3;
6738   dsc->numinsns = 2;
6739
6740   dsc->cleanup = &cleanup_load;
6741
6742   return 0;
6743 }
6744
6745 static int
6746 thumb2_copy_load_reg_imm (struct gdbarch *gdbarch, uint16_t insn1,
6747                           uint16_t insn2, struct regcache *regs,
6748                           struct displaced_step_closure *dsc,
6749                           int writeback, int immed)
6750 {
6751   unsigned int rt = bits (insn2, 12, 15);
6752   unsigned int rn = bits (insn1, 0, 3);
6753   unsigned int rm = bits (insn2, 0, 3);  /* Only valid if !immed.  */
6754   /* In LDR (register), there is also a register Rm, which is not allowed to
6755      be PC, so we don't have to check it.  */
6756
6757   if (rt != ARM_PC_REGNUM && rn != ARM_PC_REGNUM)
6758     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "load",
6759                                         dsc);
6760
6761   if (debug_displaced)
6762     fprintf_unfiltered (gdb_stdlog,
6763                         "displaced: copying ldr r%d [r%d] insn %.4x%.4x\n",
6764                          rt, rn, insn1, insn2);
6765
6766   install_load_store (gdbarch, regs, dsc, 1, immed, writeback, 4,
6767                       0, rt, rm, rn);
6768
6769   dsc->u.ldst.restore_r4 = 0;
6770
6771   if (immed)
6772     /* ldr[b]<cond> rt, [rn, #imm], etc.
6773        ->
6774        ldr[b]<cond> r0, [r2, #imm].  */
6775     {
6776       dsc->modinsn[0] = (insn1 & 0xfff0) | 0x2;
6777       dsc->modinsn[1] = insn2 & 0x0fff;
6778     }
6779   else
6780     /* ldr[b]<cond> rt, [rn, rm], etc.
6781        ->
6782        ldr[b]<cond> r0, [r2, r3].  */
6783     {
6784       dsc->modinsn[0] = (insn1 & 0xfff0) | 0x2;
6785       dsc->modinsn[1] = (insn2 & 0x0ff0) | 0x3;
6786     }
6787
6788   dsc->numinsns = 2;
6789
6790   return 0;
6791 }
6792
6793
6794 static int
6795 arm_copy_ldr_str_ldrb_strb (struct gdbarch *gdbarch, uint32_t insn,
6796                             struct regcache *regs,
6797                             struct displaced_step_closure *dsc,
6798                             int load, int size, int usermode)
6799 {
6800   int immed = !bit (insn, 25);
6801   int writeback = (bit (insn, 24) == 0 || bit (insn, 21) != 0);
6802   unsigned int rt = bits (insn, 12, 15);
6803   unsigned int rn = bits (insn, 16, 19);
6804   unsigned int rm = bits (insn, 0, 3);  /* Only valid if !immed.  */
6805
6806   if (!insn_references_pc (insn, 0x000ff00ful))
6807     return arm_copy_unmodified (gdbarch, insn, "load/store", dsc);
6808
6809   if (debug_displaced)
6810     fprintf_unfiltered (gdb_stdlog,
6811                         "displaced: copying %s%s r%d [r%d] insn %.8lx\n",
6812                         load ? (size == 1 ? "ldrb" : "ldr")
6813                              : (size == 1 ? "strb" : "str"), usermode ? "t" : "",
6814                         rt, rn,
6815                         (unsigned long) insn);
6816
6817   install_load_store (gdbarch, regs, dsc, load, immed, writeback, size,
6818                       usermode, rt, rm, rn);
6819
6820   if (load || rt != ARM_PC_REGNUM)
6821     {
6822       dsc->u.ldst.restore_r4 = 0;
6823
6824       if (immed)
6825         /* {ldr,str}[b]<cond> rt, [rn, #imm], etc.
6826            ->
6827            {ldr,str}[b]<cond> r0, [r2, #imm].  */
6828         dsc->modinsn[0] = (insn & 0xfff00fff) | 0x20000;
6829       else
6830         /* {ldr,str}[b]<cond> rt, [rn, rm], etc.
6831            ->
6832            {ldr,str}[b]<cond> r0, [r2, r3].  */
6833         dsc->modinsn[0] = (insn & 0xfff00ff0) | 0x20003;
6834     }
6835   else
6836     {
6837       /* We need to use r4 as scratch.  Make sure it's restored afterwards.  */
6838       dsc->u.ldst.restore_r4 = 1;
6839       dsc->modinsn[0] = 0xe92d8000;  /* push {pc} */
6840       dsc->modinsn[1] = 0xe8bd0010;  /* pop  {r4} */
6841       dsc->modinsn[2] = 0xe044400f;  /* sub r4, r4, pc.  */
6842       dsc->modinsn[3] = 0xe2844008;  /* add r4, r4, #8.  */
6843       dsc->modinsn[4] = 0xe0800004;  /* add r0, r0, r4.  */
6844
6845       /* As above.  */
6846       if (immed)
6847         dsc->modinsn[5] = (insn & 0xfff00fff) | 0x20000;
6848       else
6849         dsc->modinsn[5] = (insn & 0xfff00ff0) | 0x20003;
6850
6851       dsc->numinsns = 6;
6852     }
6853
6854   dsc->cleanup = load ? &cleanup_load : &cleanup_store;
6855
6856   return 0;
6857 }
6858
6859 /* Cleanup LDM instructions with fully-populated register list.  This is an
6860    unfortunate corner case: it's impossible to implement correctly by modifying
6861    the instruction.  The issue is as follows: we have an instruction,
6862
6863    ldm rN, {r0-r15}
6864
6865    which we must rewrite to avoid loading PC.  A possible solution would be to
6866    do the load in two halves, something like (with suitable cleanup
6867    afterwards):
6868
6869    mov r8, rN
6870    ldm[id][ab] r8!, {r0-r7}
6871    str r7, <temp>
6872    ldm[id][ab] r8, {r7-r14}
6873    <bkpt>
6874
6875    but at present there's no suitable place for <temp>, since the scratch space
6876    is overwritten before the cleanup routine is called.  For now, we simply
6877    emulate the instruction.  */
6878
6879 static void
6880 cleanup_block_load_all (struct gdbarch *gdbarch, struct regcache *regs,
6881                         struct displaced_step_closure *dsc)
6882 {
6883   int inc = dsc->u.block.increment;
6884   int bump_before = dsc->u.block.before ? (inc ? 4 : -4) : 0;
6885   int bump_after = dsc->u.block.before ? 0 : (inc ? 4 : -4);
6886   uint32_t regmask = dsc->u.block.regmask;
6887   int regno = inc ? 0 : 15;
6888   CORE_ADDR xfer_addr = dsc->u.block.xfer_addr;
6889   int exception_return = dsc->u.block.load && dsc->u.block.user
6890                          && (regmask & 0x8000) != 0;
6891   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6892   int do_transfer = condition_true (dsc->u.block.cond, status);
6893   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6894
6895   if (!do_transfer)
6896     return;
6897
6898   /* If the instruction is ldm rN, {...pc}^, I don't think there's anything
6899      sensible we can do here.  Complain loudly.  */
6900   if (exception_return)
6901     error (_("Cannot single-step exception return"));
6902
6903   /* We don't handle any stores here for now.  */
6904   gdb_assert (dsc->u.block.load != 0);
6905
6906   if (debug_displaced)
6907     fprintf_unfiltered (gdb_stdlog, "displaced: emulating block transfer: "
6908                         "%s %s %s\n", dsc->u.block.load ? "ldm" : "stm",
6909                         dsc->u.block.increment ? "inc" : "dec",
6910                         dsc->u.block.before ? "before" : "after");
6911
6912   while (regmask)
6913     {
6914       uint32_t memword;
6915
6916       if (inc)
6917         while (regno <= ARM_PC_REGNUM && (regmask & (1 << regno)) == 0)
6918           regno++;
6919       else
6920         while (regno >= 0 && (regmask & (1 << regno)) == 0)
6921           regno--;
6922
6923       xfer_addr += bump_before;
6924
6925       memword = read_memory_unsigned_integer (xfer_addr, 4, byte_order);
6926       displaced_write_reg (regs, dsc, regno, memword, LOAD_WRITE_PC);
6927
6928       xfer_addr += bump_after;
6929
6930       regmask &= ~(1 << regno);
6931     }
6932
6933   if (dsc->u.block.writeback)
6934     displaced_write_reg (regs, dsc, dsc->u.block.rn, xfer_addr,
6935                          CANNOT_WRITE_PC);
6936 }
6937
6938 /* Clean up an STM which included the PC in the register list.  */
6939
6940 static void
6941 cleanup_block_store_pc (struct gdbarch *gdbarch, struct regcache *regs,
6942                         struct displaced_step_closure *dsc)
6943 {
6944   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6945   int store_executed = condition_true (dsc->u.block.cond, status);
6946   CORE_ADDR pc_stored_at, transferred_regs = bitcount (dsc->u.block.regmask);
6947   CORE_ADDR stm_insn_addr;
6948   uint32_t pc_val;
6949   long offset;
6950   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
6951
6952   /* If condition code fails, there's nothing else to do.  */
6953   if (!store_executed)
6954     return;
6955
6956   if (dsc->u.block.increment)
6957     {
6958       pc_stored_at = dsc->u.block.xfer_addr + 4 * transferred_regs;
6959
6960       if (dsc->u.block.before)
6961          pc_stored_at += 4;
6962     }
6963   else
6964     {
6965       pc_stored_at = dsc->u.block.xfer_addr;
6966
6967       if (dsc->u.block.before)
6968          pc_stored_at -= 4;
6969     }
6970
6971   pc_val = read_memory_unsigned_integer (pc_stored_at, 4, byte_order);
6972   stm_insn_addr = dsc->scratch_base;
6973   offset = pc_val - stm_insn_addr;
6974
6975   if (debug_displaced)
6976     fprintf_unfiltered (gdb_stdlog, "displaced: detected PC offset %.8lx for "
6977                         "STM instruction\n", offset);
6978
6979   /* Rewrite the stored PC to the proper value for the non-displaced original
6980      instruction.  */
6981   write_memory_unsigned_integer (pc_stored_at, 4, byte_order,
6982                                  dsc->insn_addr + offset);
6983 }
6984
6985 /* Clean up an LDM which includes the PC in the register list.  We clumped all
6986    the registers in the transferred list into a contiguous range r0...rX (to
6987    avoid loading PC directly and losing control of the debugged program), so we
6988    must undo that here.  */
6989
6990 static void
6991 cleanup_block_load_pc (struct gdbarch *gdbarch,
6992                        struct regcache *regs,
6993                        struct displaced_step_closure *dsc)
6994 {
6995   uint32_t status = displaced_read_reg (regs, dsc, ARM_PS_REGNUM);
6996   int load_executed = condition_true (dsc->u.block.cond, status);
6997   unsigned int mask = dsc->u.block.regmask, write_reg = ARM_PC_REGNUM;
6998   unsigned int regs_loaded = bitcount (mask);
6999   unsigned int num_to_shuffle = regs_loaded, clobbered;
7000
7001   /* The method employed here will fail if the register list is fully populated
7002      (we need to avoid loading PC directly).  */
7003   gdb_assert (num_to_shuffle < 16);
7004
7005   if (!load_executed)
7006     return;
7007
7008   clobbered = (1 << num_to_shuffle) - 1;
7009
7010   while (num_to_shuffle > 0)
7011     {
7012       if ((mask & (1 << write_reg)) != 0)
7013         {
7014           unsigned int read_reg = num_to_shuffle - 1;
7015
7016           if (read_reg != write_reg)
7017             {
7018               ULONGEST rval = displaced_read_reg (regs, dsc, read_reg);
7019               displaced_write_reg (regs, dsc, write_reg, rval, LOAD_WRITE_PC);
7020               if (debug_displaced)
7021                 fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: move "
7022                                     "loaded register r%d to r%d\n"), read_reg,
7023                                     write_reg);
7024             }
7025           else if (debug_displaced)
7026             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: register "
7027                                 "r%d already in the right place\n"),
7028                                 write_reg);
7029
7030           clobbered &= ~(1 << write_reg);
7031
7032           num_to_shuffle--;
7033         }
7034
7035       write_reg--;
7036     }
7037
7038   /* Restore any registers we scribbled over.  */
7039   for (write_reg = 0; clobbered != 0; write_reg++)
7040     {
7041       if ((clobbered & (1 << write_reg)) != 0)
7042         {
7043           displaced_write_reg (regs, dsc, write_reg, dsc->tmp[write_reg],
7044                                CANNOT_WRITE_PC);
7045           if (debug_displaced)
7046             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM: restored "
7047                                 "clobbered register r%d\n"), write_reg);
7048           clobbered &= ~(1 << write_reg);
7049         }
7050     }
7051
7052   /* Perform register writeback manually.  */
7053   if (dsc->u.block.writeback)
7054     {
7055       ULONGEST new_rn_val = dsc->u.block.xfer_addr;
7056
7057       if (dsc->u.block.increment)
7058         new_rn_val += regs_loaded * 4;
7059       else
7060         new_rn_val -= regs_loaded * 4;
7061
7062       displaced_write_reg (regs, dsc, dsc->u.block.rn, new_rn_val,
7063                            CANNOT_WRITE_PC);
7064     }
7065 }
7066
7067 /* Handle ldm/stm, apart from some tricky cases which are unlikely to occur
7068    in user-level code (in particular exception return, ldm rn, {...pc}^).  */
7069
7070 static int
7071 arm_copy_block_xfer (struct gdbarch *gdbarch, uint32_t insn,
7072                      struct regcache *regs,
7073                      struct displaced_step_closure *dsc)
7074 {
7075   int load = bit (insn, 20);
7076   int user = bit (insn, 22);
7077   int increment = bit (insn, 23);
7078   int before = bit (insn, 24);
7079   int writeback = bit (insn, 21);
7080   int rn = bits (insn, 16, 19);
7081
7082   /* Block transfers which don't mention PC can be run directly
7083      out-of-line.  */
7084   if (rn != ARM_PC_REGNUM && (insn & 0x8000) == 0)
7085     return arm_copy_unmodified (gdbarch, insn, "ldm/stm", dsc);
7086
7087   if (rn == ARM_PC_REGNUM)
7088     {
7089       warning (_("displaced: Unpredictable LDM or STM with "
7090                  "base register r15"));
7091       return arm_copy_unmodified (gdbarch, insn, "unpredictable ldm/stm", dsc);
7092     }
7093
7094   if (debug_displaced)
7095     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
7096                         "%.8lx\n", (unsigned long) insn);
7097
7098   dsc->u.block.xfer_addr = displaced_read_reg (regs, dsc, rn);
7099   dsc->u.block.rn = rn;
7100
7101   dsc->u.block.load = load;
7102   dsc->u.block.user = user;
7103   dsc->u.block.increment = increment;
7104   dsc->u.block.before = before;
7105   dsc->u.block.writeback = writeback;
7106   dsc->u.block.cond = bits (insn, 28, 31);
7107
7108   dsc->u.block.regmask = insn & 0xffff;
7109
7110   if (load)
7111     {
7112       if ((insn & 0xffff) == 0xffff)
7113         {
7114           /* LDM with a fully-populated register list.  This case is
7115              particularly tricky.  Implement for now by fully emulating the
7116              instruction (which might not behave perfectly in all cases, but
7117              these instructions should be rare enough for that not to matter
7118              too much).  */
7119           dsc->modinsn[0] = ARM_NOP;
7120
7121           dsc->cleanup = &cleanup_block_load_all;
7122         }
7123       else
7124         {
7125           /* LDM of a list of registers which includes PC.  Implement by
7126              rewriting the list of registers to be transferred into a
7127              contiguous chunk r0...rX before doing the transfer, then shuffling
7128              registers into the correct places in the cleanup routine.  */
7129           unsigned int regmask = insn & 0xffff;
7130           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
7131           unsigned int to = 0, from = 0, i, new_rn;
7132
7133           for (i = 0; i < num_in_list; i++)
7134             dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
7135
7136           /* Writeback makes things complicated.  We need to avoid clobbering
7137              the base register with one of the registers in our modified
7138              register list, but just using a different register can't work in
7139              all cases, e.g.:
7140
7141                ldm r14!, {r0-r13,pc}
7142
7143              which would need to be rewritten as:
7144
7145                ldm rN!, {r0-r14}
7146
7147              but that can't work, because there's no free register for N.
7148
7149              Solve this by turning off the writeback bit, and emulating
7150              writeback manually in the cleanup routine.  */
7151
7152           if (writeback)
7153             insn &= ~(1 << 21);
7154
7155           new_regmask = (1 << num_in_list) - 1;
7156
7157           if (debug_displaced)
7158             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
7159                                 "{..., pc}: original reg list %.4x, modified "
7160                                 "list %.4x\n"), rn, writeback ? "!" : "",
7161                                 (int) insn & 0xffff, new_regmask);
7162
7163           dsc->modinsn[0] = (insn & ~0xffff) | (new_regmask & 0xffff);
7164
7165           dsc->cleanup = &cleanup_block_load_pc;
7166         }
7167     }
7168   else
7169     {
7170       /* STM of a list of registers which includes PC.  Run the instruction
7171          as-is, but out of line: this will store the wrong value for the PC,
7172          so we must manually fix up the memory in the cleanup routine.
7173          Doing things this way has the advantage that we can auto-detect
7174          the offset of the PC write (which is architecture-dependent) in
7175          the cleanup routine.  */
7176       dsc->modinsn[0] = insn;
7177
7178       dsc->cleanup = &cleanup_block_store_pc;
7179     }
7180
7181   return 0;
7182 }
7183
7184 static int
7185 thumb2_copy_block_xfer (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
7186                         struct regcache *regs,
7187                         struct displaced_step_closure *dsc)
7188 {
7189   int rn = bits (insn1, 0, 3);
7190   int load = bit (insn1, 4);
7191   int writeback = bit (insn1, 5);
7192
7193   /* Block transfers which don't mention PC can be run directly
7194      out-of-line.  */
7195   if (rn != ARM_PC_REGNUM && (insn2 & 0x8000) == 0)
7196     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "ldm/stm", dsc);
7197
7198   if (rn == ARM_PC_REGNUM)
7199     {
7200       warning (_("displaced: Unpredictable LDM or STM with "
7201                  "base register r15"));
7202       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7203                                           "unpredictable ldm/stm", dsc);
7204     }
7205
7206   if (debug_displaced)
7207     fprintf_unfiltered (gdb_stdlog, "displaced: copying block transfer insn "
7208                         "%.4x%.4x\n", insn1, insn2);
7209
7210   /* Clear bit 13, since it should be always zero.  */
7211   dsc->u.block.regmask = (insn2 & 0xdfff);
7212   dsc->u.block.rn = rn;
7213
7214   dsc->u.block.load = load;
7215   dsc->u.block.user = 0;
7216   dsc->u.block.increment = bit (insn1, 7);
7217   dsc->u.block.before = bit (insn1, 8);
7218   dsc->u.block.writeback = writeback;
7219   dsc->u.block.cond = INST_AL;
7220   dsc->u.block.xfer_addr = displaced_read_reg (regs, dsc, rn);
7221
7222   if (load)
7223     {
7224       if (dsc->u.block.regmask == 0xffff)
7225         {
7226           /* This branch is impossible to happen.  */
7227           gdb_assert (0);
7228         }
7229       else
7230         {
7231           unsigned int regmask = dsc->u.block.regmask;
7232           unsigned int num_in_list = bitcount (regmask), new_regmask, bit = 1;
7233           unsigned int to = 0, from = 0, i, new_rn;
7234
7235           for (i = 0; i < num_in_list; i++)
7236             dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
7237
7238           if (writeback)
7239             insn1 &= ~(1 << 5);
7240
7241           new_regmask = (1 << num_in_list) - 1;
7242
7243           if (debug_displaced)
7244             fprintf_unfiltered (gdb_stdlog, _("displaced: LDM r%d%s, "
7245                                 "{..., pc}: original reg list %.4x, modified "
7246                                 "list %.4x\n"), rn, writeback ? "!" : "",
7247                                 (int) dsc->u.block.regmask, new_regmask);
7248
7249           dsc->modinsn[0] = insn1;
7250           dsc->modinsn[1] = (new_regmask & 0xffff);
7251           dsc->numinsns = 2;
7252
7253           dsc->cleanup = &cleanup_block_load_pc;
7254         }
7255     }
7256   else
7257     {
7258       dsc->modinsn[0] = insn1;
7259       dsc->modinsn[1] = insn2;
7260       dsc->numinsns = 2;
7261       dsc->cleanup = &cleanup_block_store_pc;
7262     }
7263   return 0;
7264 }
7265
7266 /* Cleanup/copy SVC (SWI) instructions.  These two functions are overridden
7267    for Linux, where some SVC instructions must be treated specially.  */
7268
7269 static void
7270 cleanup_svc (struct gdbarch *gdbarch, struct regcache *regs,
7271              struct displaced_step_closure *dsc)
7272 {
7273   CORE_ADDR resume_addr = dsc->insn_addr + dsc->insn_size;
7274
7275   if (debug_displaced)
7276     fprintf_unfiltered (gdb_stdlog, "displaced: cleanup for svc, resume at "
7277                         "%.8lx\n", (unsigned long) resume_addr);
7278
7279   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, resume_addr, BRANCH_WRITE_PC);
7280 }
7281
7282
7283 /* Common copy routine for svc instruciton.  */
7284
7285 static int
7286 install_svc (struct gdbarch *gdbarch, struct regcache *regs,
7287              struct displaced_step_closure *dsc)
7288 {
7289   /* Preparation: none.
7290      Insn: unmodified svc.
7291      Cleanup: pc <- insn_addr + insn_size.  */
7292
7293   /* Pretend we wrote to the PC, so cleanup doesn't set PC to the next
7294      instruction.  */
7295   dsc->wrote_to_pc = 1;
7296
7297   /* Allow OS-specific code to override SVC handling.  */
7298   if (dsc->u.svc.copy_svc_os)
7299     return dsc->u.svc.copy_svc_os (gdbarch, regs, dsc);
7300   else
7301     {
7302       dsc->cleanup = &cleanup_svc;
7303       return 0;
7304     }
7305 }
7306
7307 static int
7308 arm_copy_svc (struct gdbarch *gdbarch, uint32_t insn,
7309               struct regcache *regs, struct displaced_step_closure *dsc)
7310 {
7311
7312   if (debug_displaced)
7313     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.8lx\n",
7314                         (unsigned long) insn);
7315
7316   dsc->modinsn[0] = insn;
7317
7318   return install_svc (gdbarch, regs, dsc);
7319 }
7320
7321 static int
7322 thumb_copy_svc (struct gdbarch *gdbarch, uint16_t insn,
7323                 struct regcache *regs, struct displaced_step_closure *dsc)
7324 {
7325
7326   if (debug_displaced)
7327     fprintf_unfiltered (gdb_stdlog, "displaced: copying svc insn %.4x\n",
7328                         insn);
7329
7330   dsc->modinsn[0] = insn;
7331
7332   return install_svc (gdbarch, regs, dsc);
7333 }
7334
7335 /* Copy undefined instructions.  */
7336
7337 static int
7338 arm_copy_undef (struct gdbarch *gdbarch, uint32_t insn,
7339                 struct displaced_step_closure *dsc)
7340 {
7341   if (debug_displaced)
7342     fprintf_unfiltered (gdb_stdlog,
7343                         "displaced: copying undefined insn %.8lx\n",
7344                         (unsigned long) insn);
7345
7346   dsc->modinsn[0] = insn;
7347
7348   return 0;
7349 }
7350
7351 static int
7352 thumb_32bit_copy_undef (struct gdbarch *gdbarch, uint16_t insn1, uint16_t insn2,
7353                        struct displaced_step_closure *dsc)
7354 {
7355
7356   if (debug_displaced)
7357     fprintf_unfiltered (gdb_stdlog, "displaced: copying undefined insn "
7358                        "%.4x %.4x\n", (unsigned short) insn1,
7359                        (unsigned short) insn2);
7360
7361   dsc->modinsn[0] = insn1;
7362   dsc->modinsn[1] = insn2;
7363   dsc->numinsns = 2;
7364
7365   return 0;
7366 }
7367
7368 /* Copy unpredictable instructions.  */
7369
7370 static int
7371 arm_copy_unpred (struct gdbarch *gdbarch, uint32_t insn,
7372                  struct displaced_step_closure *dsc)
7373 {
7374   if (debug_displaced)
7375     fprintf_unfiltered (gdb_stdlog, "displaced: copying unpredictable insn "
7376                         "%.8lx\n", (unsigned long) insn);
7377
7378   dsc->modinsn[0] = insn;
7379
7380   return 0;
7381 }
7382
7383 /* The decode_* functions are instruction decoding helpers.  They mostly follow
7384    the presentation in the ARM ARM.  */
7385
7386 static int
7387 arm_decode_misc_memhint_neon (struct gdbarch *gdbarch, uint32_t insn,
7388                               struct regcache *regs,
7389                               struct displaced_step_closure *dsc)
7390 {
7391   unsigned int op1 = bits (insn, 20, 26), op2 = bits (insn, 4, 7);
7392   unsigned int rn = bits (insn, 16, 19);
7393
7394   if (op1 == 0x10 && (op2 & 0x2) == 0x0 && (rn & 0xe) == 0x0)
7395     return arm_copy_unmodified (gdbarch, insn, "cps", dsc);
7396   else if (op1 == 0x10 && op2 == 0x0 && (rn & 0xe) == 0x1)
7397     return arm_copy_unmodified (gdbarch, insn, "setend", dsc);
7398   else if ((op1 & 0x60) == 0x20)
7399     return arm_copy_unmodified (gdbarch, insn, "neon dataproc", dsc);
7400   else if ((op1 & 0x71) == 0x40)
7401     return arm_copy_unmodified (gdbarch, insn, "neon elt/struct load/store",
7402                                 dsc);
7403   else if ((op1 & 0x77) == 0x41)
7404     return arm_copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
7405   else if ((op1 & 0x77) == 0x45)
7406     return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pli.  */
7407   else if ((op1 & 0x77) == 0x51)
7408     {
7409       if (rn != 0xf)
7410         return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
7411       else
7412         return arm_copy_unpred (gdbarch, insn, dsc);
7413     }
7414   else if ((op1 & 0x77) == 0x55)
7415     return arm_copy_preload (gdbarch, insn, regs, dsc);  /* pld/pldw.  */
7416   else if (op1 == 0x57)
7417     switch (op2)
7418       {
7419       case 0x1: return arm_copy_unmodified (gdbarch, insn, "clrex", dsc);
7420       case 0x4: return arm_copy_unmodified (gdbarch, insn, "dsb", dsc);
7421       case 0x5: return arm_copy_unmodified (gdbarch, insn, "dmb", dsc);
7422       case 0x6: return arm_copy_unmodified (gdbarch, insn, "isb", dsc);
7423       default: return arm_copy_unpred (gdbarch, insn, dsc);
7424       }
7425   else if ((op1 & 0x63) == 0x43)
7426     return arm_copy_unpred (gdbarch, insn, dsc);
7427   else if ((op2 & 0x1) == 0x0)
7428     switch (op1 & ~0x80)
7429       {
7430       case 0x61:
7431         return arm_copy_unmodified (gdbarch, insn, "unallocated mem hint", dsc);
7432       case 0x65:
7433         return arm_copy_preload_reg (gdbarch, insn, regs, dsc);  /* pli reg.  */
7434       case 0x71: case 0x75:
7435         /* pld/pldw reg.  */
7436         return arm_copy_preload_reg (gdbarch, insn, regs, dsc);
7437       case 0x63: case 0x67: case 0x73: case 0x77:
7438         return arm_copy_unpred (gdbarch, insn, dsc);
7439       default:
7440         return arm_copy_undef (gdbarch, insn, dsc);
7441       }
7442   else
7443     return arm_copy_undef (gdbarch, insn, dsc);  /* Probably unreachable.  */
7444 }
7445
7446 static int
7447 arm_decode_unconditional (struct gdbarch *gdbarch, uint32_t insn,
7448                           struct regcache *regs,
7449                           struct displaced_step_closure *dsc)
7450 {
7451   if (bit (insn, 27) == 0)
7452     return arm_decode_misc_memhint_neon (gdbarch, insn, regs, dsc);
7453   /* Switch on bits: 0bxxxxx321xxx0xxxxxxxxxxxxxxxxxxxx.  */
7454   else switch (((insn & 0x7000000) >> 23) | ((insn & 0x100000) >> 20))
7455     {
7456     case 0x0: case 0x2:
7457       return arm_copy_unmodified (gdbarch, insn, "srs", dsc);
7458
7459     case 0x1: case 0x3:
7460       return arm_copy_unmodified (gdbarch, insn, "rfe", dsc);
7461
7462     case 0x4: case 0x5: case 0x6: case 0x7:
7463       return arm_copy_b_bl_blx (gdbarch, insn, regs, dsc);
7464
7465     case 0x8:
7466       switch ((insn & 0xe00000) >> 21)
7467         {
7468         case 0x1: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7:
7469           /* stc/stc2.  */
7470           return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7471
7472         case 0x2:
7473           return arm_copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
7474
7475         default:
7476           return arm_copy_undef (gdbarch, insn, dsc);
7477         }
7478
7479     case 0x9:
7480       {
7481          int rn_f = (bits (insn, 16, 19) == 0xf);
7482         switch ((insn & 0xe00000) >> 21)
7483           {
7484           case 0x1: case 0x3:
7485             /* ldc/ldc2 imm (undefined for rn == pc).  */
7486             return rn_f ? arm_copy_undef (gdbarch, insn, dsc)
7487                         : arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7488
7489           case 0x2:
7490             return arm_copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
7491
7492           case 0x4: case 0x5: case 0x6: case 0x7:
7493             /* ldc/ldc2 lit (undefined for rn != pc).  */
7494             return rn_f ? arm_copy_copro_load_store (gdbarch, insn, regs, dsc)
7495                         : arm_copy_undef (gdbarch, insn, dsc);
7496
7497           default:
7498             return arm_copy_undef (gdbarch, insn, dsc);
7499           }
7500       }
7501
7502     case 0xa:
7503       return arm_copy_unmodified (gdbarch, insn, "stc/stc2", dsc);
7504
7505     case 0xb:
7506       if (bits (insn, 16, 19) == 0xf)
7507         /* ldc/ldc2 lit.  */
7508         return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7509       else
7510         return arm_copy_undef (gdbarch, insn, dsc);
7511
7512     case 0xc:
7513       if (bit (insn, 4))
7514         return arm_copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
7515       else
7516         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7517
7518     case 0xd:
7519       if (bit (insn, 4))
7520         return arm_copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
7521       else
7522         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7523
7524     default:
7525       return arm_copy_undef (gdbarch, insn, dsc);
7526     }
7527 }
7528
7529 /* Decode miscellaneous instructions in dp/misc encoding space.  */
7530
7531 static int
7532 arm_decode_miscellaneous (struct gdbarch *gdbarch, uint32_t insn,
7533                           struct regcache *regs,
7534                           struct displaced_step_closure *dsc)
7535 {
7536   unsigned int op2 = bits (insn, 4, 6);
7537   unsigned int op = bits (insn, 21, 22);
7538   unsigned int op1 = bits (insn, 16, 19);
7539
7540   switch (op2)
7541     {
7542     case 0x0:
7543       return arm_copy_unmodified (gdbarch, insn, "mrs/msr", dsc);
7544
7545     case 0x1:
7546       if (op == 0x1)  /* bx.  */
7547         return arm_copy_bx_blx_reg (gdbarch, insn, regs, dsc);
7548       else if (op == 0x3)
7549         return arm_copy_unmodified (gdbarch, insn, "clz", dsc);
7550       else
7551         return arm_copy_undef (gdbarch, insn, dsc);
7552
7553     case 0x2:
7554       if (op == 0x1)
7555         /* Not really supported.  */
7556         return arm_copy_unmodified (gdbarch, insn, "bxj", dsc);
7557       else
7558         return arm_copy_undef (gdbarch, insn, dsc);
7559
7560     case 0x3:
7561       if (op == 0x1)
7562         return arm_copy_bx_blx_reg (gdbarch, insn,
7563                                 regs, dsc);  /* blx register.  */
7564       else
7565         return arm_copy_undef (gdbarch, insn, dsc);
7566
7567     case 0x5:
7568       return arm_copy_unmodified (gdbarch, insn, "saturating add/sub", dsc);
7569
7570     case 0x7:
7571       if (op == 0x1)
7572         return arm_copy_unmodified (gdbarch, insn, "bkpt", dsc);
7573       else if (op == 0x3)
7574         /* Not really supported.  */
7575         return arm_copy_unmodified (gdbarch, insn, "smc", dsc);
7576
7577     default:
7578       return arm_copy_undef (gdbarch, insn, dsc);
7579     }
7580 }
7581
7582 static int
7583 arm_decode_dp_misc (struct gdbarch *gdbarch, uint32_t insn,
7584                     struct regcache *regs,
7585                     struct displaced_step_closure *dsc)
7586 {
7587   if (bit (insn, 25))
7588     switch (bits (insn, 20, 24))
7589       {
7590       case 0x10:
7591         return arm_copy_unmodified (gdbarch, insn, "movw", dsc);
7592
7593       case 0x14:
7594         return arm_copy_unmodified (gdbarch, insn, "movt", dsc);
7595
7596       case 0x12: case 0x16:
7597         return arm_copy_unmodified (gdbarch, insn, "msr imm", dsc);
7598
7599       default:
7600         return arm_copy_alu_imm (gdbarch, insn, regs, dsc);
7601       }
7602   else
7603     {
7604       uint32_t op1 = bits (insn, 20, 24), op2 = bits (insn, 4, 7);
7605
7606       if ((op1 & 0x19) != 0x10 && (op2 & 0x1) == 0x0)
7607         return arm_copy_alu_reg (gdbarch, insn, regs, dsc);
7608       else if ((op1 & 0x19) != 0x10 && (op2 & 0x9) == 0x1)
7609         return arm_copy_alu_shifted_reg (gdbarch, insn, regs, dsc);
7610       else if ((op1 & 0x19) == 0x10 && (op2 & 0x8) == 0x0)
7611         return arm_decode_miscellaneous (gdbarch, insn, regs, dsc);
7612       else if ((op1 & 0x19) == 0x10 && (op2 & 0x9) == 0x8)
7613         return arm_copy_unmodified (gdbarch, insn, "halfword mul/mla", dsc);
7614       else if ((op1 & 0x10) == 0x00 && op2 == 0x9)
7615         return arm_copy_unmodified (gdbarch, insn, "mul/mla", dsc);
7616       else if ((op1 & 0x10) == 0x10 && op2 == 0x9)
7617         return arm_copy_unmodified (gdbarch, insn, "synch", dsc);
7618       else if (op2 == 0xb || (op2 & 0xd) == 0xd)
7619         /* 2nd arg means "unpriveleged".  */
7620         return arm_copy_extra_ld_st (gdbarch, insn, (op1 & 0x12) == 0x02, regs,
7621                                      dsc);
7622     }
7623
7624   /* Should be unreachable.  */
7625   return 1;
7626 }
7627
7628 static int
7629 arm_decode_ld_st_word_ubyte (struct gdbarch *gdbarch, uint32_t insn,
7630                              struct regcache *regs,
7631                              struct displaced_step_closure *dsc)
7632 {
7633   int a = bit (insn, 25), b = bit (insn, 4);
7634   uint32_t op1 = bits (insn, 20, 24);
7635   int rn_f = bits (insn, 16, 19) == 0xf;
7636
7637   if ((!a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02)
7638       || (a && (op1 & 0x05) == 0x00 && (op1 & 0x17) != 0x02 && !b))
7639     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 4, 0);
7640   else if ((!a && (op1 & 0x17) == 0x02)
7641             || (a && (op1 & 0x17) == 0x02 && !b))
7642     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 4, 1);
7643   else if ((!a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03)
7644             || (a && (op1 & 0x05) == 0x01 && (op1 & 0x17) != 0x03 && !b))
7645     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 4, 0);
7646   else if ((!a && (op1 & 0x17) == 0x03)
7647            || (a && (op1 & 0x17) == 0x03 && !b))
7648     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 4, 1);
7649   else if ((!a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06)
7650             || (a && (op1 & 0x05) == 0x04 && (op1 & 0x17) != 0x06 && !b))
7651     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 0);
7652   else if ((!a && (op1 & 0x17) == 0x06)
7653            || (a && (op1 & 0x17) == 0x06 && !b))
7654     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 0, 1, 1);
7655   else if ((!a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07)
7656            || (a && (op1 & 0x05) == 0x05 && (op1 & 0x17) != 0x07 && !b))
7657     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 0);
7658   else if ((!a && (op1 & 0x17) == 0x07)
7659            || (a && (op1 & 0x17) == 0x07 && !b))
7660     return arm_copy_ldr_str_ldrb_strb (gdbarch, insn, regs, dsc, 1, 1, 1);
7661
7662   /* Should be unreachable.  */
7663   return 1;
7664 }
7665
7666 static int
7667 arm_decode_media (struct gdbarch *gdbarch, uint32_t insn,
7668                   struct displaced_step_closure *dsc)
7669 {
7670   switch (bits (insn, 20, 24))
7671     {
7672     case 0x00: case 0x01: case 0x02: case 0x03:
7673       return arm_copy_unmodified (gdbarch, insn, "parallel add/sub signed", dsc);
7674
7675     case 0x04: case 0x05: case 0x06: case 0x07:
7676       return arm_copy_unmodified (gdbarch, insn, "parallel add/sub unsigned", dsc);
7677
7678     case 0x08: case 0x09: case 0x0a: case 0x0b:
7679     case 0x0c: case 0x0d: case 0x0e: case 0x0f:
7680       return arm_copy_unmodified (gdbarch, insn,
7681                               "decode/pack/unpack/saturate/reverse", dsc);
7682
7683     case 0x18:
7684       if (bits (insn, 5, 7) == 0)  /* op2.  */
7685          {
7686           if (bits (insn, 12, 15) == 0xf)
7687             return arm_copy_unmodified (gdbarch, insn, "usad8", dsc);
7688           else
7689             return arm_copy_unmodified (gdbarch, insn, "usada8", dsc);
7690         }
7691       else
7692          return arm_copy_undef (gdbarch, insn, dsc);
7693
7694     case 0x1a: case 0x1b:
7695       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
7696         return arm_copy_unmodified (gdbarch, insn, "sbfx", dsc);
7697       else
7698         return arm_copy_undef (gdbarch, insn, dsc);
7699
7700     case 0x1c: case 0x1d:
7701       if (bits (insn, 5, 6) == 0x0)  /* op2[1:0].  */
7702          {
7703           if (bits (insn, 0, 3) == 0xf)
7704             return arm_copy_unmodified (gdbarch, insn, "bfc", dsc);
7705           else
7706             return arm_copy_unmodified (gdbarch, insn, "bfi", dsc);
7707         }
7708       else
7709         return arm_copy_undef (gdbarch, insn, dsc);
7710
7711     case 0x1e: case 0x1f:
7712       if (bits (insn, 5, 6) == 0x2)  /* op2[1:0].  */
7713         return arm_copy_unmodified (gdbarch, insn, "ubfx", dsc);
7714       else
7715         return arm_copy_undef (gdbarch, insn, dsc);
7716     }
7717
7718   /* Should be unreachable.  */
7719   return 1;
7720 }
7721
7722 static int
7723 arm_decode_b_bl_ldmstm (struct gdbarch *gdbarch, int32_t insn,
7724                         struct regcache *regs,
7725                         struct displaced_step_closure *dsc)
7726 {
7727   if (bit (insn, 25))
7728     return arm_copy_b_bl_blx (gdbarch, insn, regs, dsc);
7729   else
7730     return arm_copy_block_xfer (gdbarch, insn, regs, dsc);
7731 }
7732
7733 static int
7734 arm_decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint32_t insn,
7735                           struct regcache *regs,
7736                           struct displaced_step_closure *dsc)
7737 {
7738   unsigned int opcode = bits (insn, 20, 24);
7739
7740   switch (opcode)
7741     {
7742     case 0x04: case 0x05:  /* VFP/Neon mrrc/mcrr.  */
7743       return arm_copy_unmodified (gdbarch, insn, "vfp/neon mrrc/mcrr", dsc);
7744
7745     case 0x08: case 0x0a: case 0x0c: case 0x0e:
7746     case 0x12: case 0x16:
7747       return arm_copy_unmodified (gdbarch, insn, "vfp/neon vstm/vpush", dsc);
7748
7749     case 0x09: case 0x0b: case 0x0d: case 0x0f:
7750     case 0x13: case 0x17:
7751       return arm_copy_unmodified (gdbarch, insn, "vfp/neon vldm/vpop", dsc);
7752
7753     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
7754     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
7755       /* Note: no writeback for these instructions.  Bit 25 will always be
7756          zero though (via caller), so the following works OK.  */
7757       return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7758     }
7759
7760   /* Should be unreachable.  */
7761   return 1;
7762 }
7763
7764 /* Decode shifted register instructions.  */
7765
7766 static int
7767 thumb2_decode_dp_shift_reg (struct gdbarch *gdbarch, uint16_t insn1,
7768                             uint16_t insn2,  struct regcache *regs,
7769                             struct displaced_step_closure *dsc)
7770 {
7771   /* PC is only allowed to be used in instruction MOV.  */
7772
7773   unsigned int op = bits (insn1, 5, 8);
7774   unsigned int rn = bits (insn1, 0, 3);
7775
7776   if (op == 0x2 && rn == 0xf) /* MOV */
7777     return thumb2_copy_alu_imm (gdbarch, insn1, insn2, regs, dsc);
7778   else
7779     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7780                                         "dp (shift reg)", dsc);
7781 }
7782
7783
7784 /* Decode extension register load/store.  Exactly the same as
7785    arm_decode_ext_reg_ld_st.  */
7786
7787 static int
7788 thumb2_decode_ext_reg_ld_st (struct gdbarch *gdbarch, uint16_t insn1,
7789                              uint16_t insn2,  struct regcache *regs,
7790                              struct displaced_step_closure *dsc)
7791 {
7792   unsigned int opcode = bits (insn1, 4, 8);
7793
7794   switch (opcode)
7795     {
7796     case 0x04: case 0x05:
7797       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7798                                           "vfp/neon vmov", dsc);
7799
7800     case 0x08: case 0x0c: /* 01x00 */
7801     case 0x0a: case 0x0e: /* 01x10 */
7802     case 0x12: case 0x16: /* 10x10 */
7803       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7804                                           "vfp/neon vstm/vpush", dsc);
7805
7806     case 0x09: case 0x0d: /* 01x01 */
7807     case 0x0b: case 0x0f: /* 01x11 */
7808     case 0x13: case 0x17: /* 10x11 */
7809       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7810                                           "vfp/neon vldm/vpop", dsc);
7811
7812     case 0x10: case 0x14: case 0x18: case 0x1c:  /* vstr.  */
7813       return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7814                                           "vstr", dsc);
7815     case 0x11: case 0x15: case 0x19: case 0x1d:  /* vldr.  */
7816       return thumb2_copy_copro_load_store (gdbarch, insn1, insn2, regs, dsc);
7817     }
7818
7819   /* Should be unreachable.  */
7820   return 1;
7821 }
7822
7823 static int
7824 arm_decode_svc_copro (struct gdbarch *gdbarch, uint32_t insn, CORE_ADDR to,
7825                       struct regcache *regs, struct displaced_step_closure *dsc)
7826 {
7827   unsigned int op1 = bits (insn, 20, 25);
7828   int op = bit (insn, 4);
7829   unsigned int coproc = bits (insn, 8, 11);
7830   unsigned int rn = bits (insn, 16, 19);
7831
7832   if ((op1 & 0x20) == 0x00 && (op1 & 0x3a) != 0x00 && (coproc & 0xe) == 0xa)
7833     return arm_decode_ext_reg_ld_st (gdbarch, insn, regs, dsc);
7834   else if ((op1 & 0x21) == 0x00 && (op1 & 0x3a) != 0x00
7835            && (coproc & 0xe) != 0xa)
7836     /* stc/stc2.  */
7837     return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7838   else if ((op1 & 0x21) == 0x01 && (op1 & 0x3a) != 0x00
7839            && (coproc & 0xe) != 0xa)
7840     /* ldc/ldc2 imm/lit.  */
7841     return arm_copy_copro_load_store (gdbarch, insn, regs, dsc);
7842   else if ((op1 & 0x3e) == 0x00)
7843     return arm_copy_undef (gdbarch, insn, dsc);
7844   else if ((op1 & 0x3e) == 0x04 && (coproc & 0xe) == 0xa)
7845     return arm_copy_unmodified (gdbarch, insn, "neon 64bit xfer", dsc);
7846   else if (op1 == 0x04 && (coproc & 0xe) != 0xa)
7847     return arm_copy_unmodified (gdbarch, insn, "mcrr/mcrr2", dsc);
7848   else if (op1 == 0x05 && (coproc & 0xe) != 0xa)
7849     return arm_copy_unmodified (gdbarch, insn, "mrrc/mrrc2", dsc);
7850   else if ((op1 & 0x30) == 0x20 && !op)
7851     {
7852       if ((coproc & 0xe) == 0xa)
7853         return arm_copy_unmodified (gdbarch, insn, "vfp dataproc", dsc);
7854       else
7855         return arm_copy_unmodified (gdbarch, insn, "cdp/cdp2", dsc);
7856     }
7857   else if ((op1 & 0x30) == 0x20 && op)
7858     return arm_copy_unmodified (gdbarch, insn, "neon 8/16/32 bit xfer", dsc);
7859   else if ((op1 & 0x31) == 0x20 && op && (coproc & 0xe) != 0xa)
7860     return arm_copy_unmodified (gdbarch, insn, "mcr/mcr2", dsc);
7861   else if ((op1 & 0x31) == 0x21 && op && (coproc & 0xe) != 0xa)
7862     return arm_copy_unmodified (gdbarch, insn, "mrc/mrc2", dsc);
7863   else if ((op1 & 0x30) == 0x30)
7864     return arm_copy_svc (gdbarch, insn, regs, dsc);
7865   else
7866     return arm_copy_undef (gdbarch, insn, dsc);  /* Possibly unreachable.  */
7867 }
7868
7869 static int
7870 thumb2_decode_svc_copro (struct gdbarch *gdbarch, uint16_t insn1,
7871                          uint16_t insn2, struct regcache *regs,
7872                          struct displaced_step_closure *dsc)
7873 {
7874   unsigned int coproc = bits (insn2, 8, 11);
7875   unsigned int op1 = bits (insn1, 4, 9);
7876   unsigned int bit_5_8 = bits (insn1, 5, 8);
7877   unsigned int bit_9 = bit (insn1, 9);
7878   unsigned int bit_4 = bit (insn1, 4);
7879   unsigned int rn = bits (insn1, 0, 3);
7880
7881   if (bit_9 == 0)
7882     {
7883       if (bit_5_8 == 2)
7884         return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7885                                             "neon 64bit xfer/mrrc/mrrc2/mcrr/mcrr2",
7886                                             dsc);
7887       else if (bit_5_8 == 0) /* UNDEFINED.  */
7888         return thumb_32bit_copy_undef (gdbarch, insn1, insn2, dsc);
7889       else
7890         {
7891            /*coproc is 101x.  SIMD/VFP, ext registers load/store.  */
7892           if ((coproc & 0xe) == 0xa)
7893             return thumb2_decode_ext_reg_ld_st (gdbarch, insn1, insn2, regs,
7894                                                 dsc);
7895           else /* coproc is not 101x.  */
7896             {
7897               if (bit_4 == 0) /* STC/STC2.  */
7898                 return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
7899                                                     "stc/stc2", dsc);
7900               else /* LDC/LDC2 {literal, immeidate}.  */
7901                 return thumb2_copy_copro_load_store (gdbarch, insn1, insn2,
7902                                                      regs, dsc);
7903             }
7904         }
7905     }
7906   else
7907     return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2, "coproc", dsc);
7908
7909   return 0;
7910 }
7911
7912 static void
7913 install_pc_relative (struct gdbarch *gdbarch, struct regcache *regs,
7914                      struct displaced_step_closure *dsc, int rd)
7915 {
7916   /* ADR Rd, #imm
7917
7918      Rewrite as:
7919
7920      Preparation: Rd <- PC
7921      Insn: ADD Rd, #imm
7922      Cleanup: Null.
7923   */
7924
7925   /* Rd <- PC */
7926   int val = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
7927   displaced_write_reg (regs, dsc, rd, val, CANNOT_WRITE_PC);
7928 }
7929
7930 static int
7931 thumb_copy_pc_relative_16bit (struct gdbarch *gdbarch, struct regcache *regs,
7932                               struct displaced_step_closure *dsc,
7933                               int rd, unsigned int imm)
7934 {
7935
7936   /* Encoding T2: ADDS Rd, #imm */
7937   dsc->modinsn[0] = (0x3000 | (rd << 8) | imm);
7938
7939   install_pc_relative (gdbarch, regs, dsc, rd);
7940
7941   return 0;
7942 }
7943
7944 static int
7945 thumb_decode_pc_relative_16bit (struct gdbarch *gdbarch, uint16_t insn,
7946                                 struct regcache *regs,
7947                                 struct displaced_step_closure *dsc)
7948 {
7949   unsigned int rd = bits (insn, 8, 10);
7950   unsigned int imm8 = bits (insn, 0, 7);
7951
7952   if (debug_displaced)
7953     fprintf_unfiltered (gdb_stdlog,
7954                         "displaced: copying thumb adr r%d, #%d insn %.4x\n",
7955                         rd, imm8, insn);
7956
7957   return thumb_copy_pc_relative_16bit (gdbarch, regs, dsc, rd, imm8);
7958 }
7959
7960 static int
7961 thumb_copy_pc_relative_32bit (struct gdbarch *gdbarch, uint16_t insn1,
7962                               uint16_t insn2, struct regcache *regs,
7963                               struct displaced_step_closure *dsc)
7964 {
7965   unsigned int rd = bits (insn2, 8, 11);
7966   /* Since immediate has the same encoding in ADR ADD and SUB, so we simply
7967      extract raw immediate encoding rather than computing immediate.  When
7968      generating ADD or SUB instruction, we can simply perform OR operation to
7969      set immediate into ADD.  */
7970   unsigned int imm_3_8 = insn2 & 0x70ff;
7971   unsigned int imm_i = insn1 & 0x0400; /* Clear all bits except bit 10.  */
7972
7973   if (debug_displaced)
7974     fprintf_unfiltered (gdb_stdlog,
7975                         "displaced: copying thumb adr r%d, #%d:%d insn %.4x%.4x\n",
7976                         rd, imm_i, imm_3_8, insn1, insn2);
7977
7978   if (bit (insn1, 7)) /* Encoding T2 */
7979     {
7980       /* Encoding T3: SUB Rd, Rd, #imm */
7981       dsc->modinsn[0] = (0xf1a0 | rd | imm_i);
7982       dsc->modinsn[1] = ((rd << 8) | imm_3_8);
7983     }
7984   else /* Encoding T3 */
7985     {
7986       /* Encoding T3: ADD Rd, Rd, #imm */
7987       dsc->modinsn[0] = (0xf100 | rd | imm_i);
7988       dsc->modinsn[1] = ((rd << 8) | imm_3_8);
7989     }
7990   dsc->numinsns = 2;
7991
7992   install_pc_relative (gdbarch, regs, dsc, rd);
7993
7994   return 0;
7995 }
7996
7997 static int
7998 thumb_copy_16bit_ldr_literal (struct gdbarch *gdbarch, unsigned short insn1,
7999                               struct regcache *regs,
8000                               struct displaced_step_closure *dsc)
8001 {
8002   unsigned int rt = bits (insn1, 8, 10);
8003   unsigned int pc;
8004   int imm8 = (bits (insn1, 0, 7) << 2);
8005   CORE_ADDR from = dsc->insn_addr;
8006
8007   /* LDR Rd, #imm8
8008
8009      Rwrite as:
8010
8011      Preparation: tmp0 <- R0, tmp2 <- R2, tmp3 <- R3, R2 <- PC, R3 <- #imm8;
8012
8013      Insn: LDR R0, [R2, R3];
8014      Cleanup: R2 <- tmp2, R3 <- tmp3, Rd <- R0, R0 <- tmp0 */
8015
8016   if (debug_displaced)
8017     fprintf_unfiltered (gdb_stdlog,
8018                         "displaced: copying thumb ldr r%d [pc #%d]\n"
8019                         , rt, imm8);
8020
8021   dsc->tmp[0] = displaced_read_reg (regs, dsc, 0);
8022   dsc->tmp[2] = displaced_read_reg (regs, dsc, 2);
8023   dsc->tmp[3] = displaced_read_reg (regs, dsc, 3);
8024   pc = displaced_read_reg (regs, dsc, ARM_PC_REGNUM);
8025   /* The assembler calculates the required value of the offset from the
8026      Align(PC,4) value of this instruction to the label.  */
8027   pc = pc & 0xfffffffc;
8028
8029   displaced_write_reg (regs, dsc, 2, pc, CANNOT_WRITE_PC);
8030   displaced_write_reg (regs, dsc, 3, imm8, CANNOT_WRITE_PC);
8031
8032   dsc->rd = rt;
8033   dsc->u.ldst.xfersize = 4;
8034   dsc->u.ldst.rn = 0;
8035   dsc->u.ldst.immed = 0;
8036   dsc->u.ldst.writeback = 0;
8037   dsc->u.ldst.restore_r4 = 0;
8038
8039   dsc->modinsn[0] = 0x58d0; /* ldr r0, [r2, r3]*/
8040
8041   dsc->cleanup = &cleanup_load;
8042
8043   return 0;
8044 }
8045
8046 /* Copy Thumb cbnz/cbz insruction.  */
8047
8048 static int
8049 thumb_copy_cbnz_cbz (struct gdbarch *gdbarch, uint16_t insn1,
8050                      struct regcache *regs,
8051                      struct displaced_step_closure *dsc)
8052 {
8053   int non_zero = bit (insn1, 11);
8054   unsigned int imm5 = (bit (insn1, 9) << 6) | (bits (insn1, 3, 7) << 1);
8055   CORE_ADDR from = dsc->insn_addr;
8056   int rn = bits (insn1, 0, 2);
8057   int rn_val = displaced_read_reg (regs, dsc, rn);
8058
8059   dsc->u.branch.cond = (rn_val && non_zero) || (!rn_val && !non_zero);
8060   /* CBNZ and CBZ do not affect the condition flags.  If condition is true,
8061      set it INST_AL, so cleanup_branch will know branch is taken, otherwise,
8062      condition is false, let it be, cleanup_branch will do nothing.  */
8063   if (dsc->u.branch.cond)
8064     {
8065       dsc->u.branch.cond = INST_AL;
8066       dsc->u.branch.dest = from + 4 + imm5;
8067     }
8068   else
8069       dsc->u.branch.dest = from + 2;
8070
8071   dsc->u.branch.link = 0;
8072   dsc->u.branch.exchange = 0;
8073
8074   if (debug_displaced)
8075     fprintf_unfiltered (gdb_stdlog, "displaced: copying %s [r%d = 0x%x]"
8076                         " insn %.4x to %.8lx\n", non_zero ? "cbnz" : "cbz",
8077                         rn, rn_val, insn1, dsc->u.branch.dest);
8078
8079   dsc->modinsn[0] = THUMB_NOP;
8080
8081   dsc->cleanup = &cleanup_branch;
8082   return 0;
8083 }
8084
8085 /* Copy Table Branch Byte/Halfword */
8086 static int
8087 thumb2_copy_table_branch (struct gdbarch *gdbarch, uint16_t insn1,
8088                           uint16_t insn2, struct regcache *regs,
8089                           struct displaced_step_closure *dsc)
8090 {
8091   ULONGEST rn_val, rm_val;
8092   int is_tbh = bit (insn2, 4);
8093   CORE_ADDR halfwords = 0;
8094   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
8095
8096   rn_val = displaced_read_reg (regs, dsc, bits (insn1, 0, 3));
8097   rm_val = displaced_read_reg (regs, dsc, bits (insn2, 0, 3));
8098
8099   if (is_tbh)
8100     {
8101       gdb_byte buf[2];
8102
8103       target_read_memory (rn_val + 2 * rm_val, buf, 2);
8104       halfwords = extract_unsigned_integer (buf, 2, byte_order);
8105     }
8106   else
8107     {
8108       gdb_byte buf[1];
8109
8110       target_read_memory (rn_val + rm_val, buf, 1);
8111       halfwords = extract_unsigned_integer (buf, 1, byte_order);
8112     }
8113
8114   if (debug_displaced)
8115     fprintf_unfiltered (gdb_stdlog, "displaced: %s base 0x%x offset 0x%x"
8116                         " offset 0x%x\n", is_tbh ? "tbh" : "tbb",
8117                         (unsigned int) rn_val, (unsigned int) rm_val,
8118                         (unsigned int) halfwords);
8119
8120   dsc->u.branch.cond = INST_AL;
8121   dsc->u.branch.link = 0;
8122   dsc->u.branch.exchange = 0;
8123   dsc->u.branch.dest = dsc->insn_addr + 4 + 2 * halfwords;
8124
8125   dsc->cleanup = &cleanup_branch;
8126
8127   return 0;
8128 }
8129
8130 static void
8131 cleanup_pop_pc_16bit_all (struct gdbarch *gdbarch, struct regcache *regs,
8132                           struct displaced_step_closure *dsc)
8133 {
8134   /* PC <- r7 */
8135   int val = displaced_read_reg (regs, dsc, 7);
8136   displaced_write_reg (regs, dsc, ARM_PC_REGNUM, val, BX_WRITE_PC);
8137
8138   /* r7 <- r8 */
8139   val = displaced_read_reg (regs, dsc, 8);
8140   displaced_write_reg (regs, dsc, 7, val, CANNOT_WRITE_PC);
8141
8142   /* r8 <- tmp[0] */
8143   displaced_write_reg (regs, dsc, 8, dsc->tmp[0], CANNOT_WRITE_PC);
8144
8145 }
8146
8147 static int
8148 thumb_copy_pop_pc_16bit (struct gdbarch *gdbarch, unsigned short insn1,
8149                          struct regcache *regs,
8150                          struct displaced_step_closure *dsc)
8151 {
8152   dsc->u.block.regmask = insn1 & 0x00ff;
8153
8154   /* Rewrite instruction: POP {rX, rY, ...,rZ, PC}
8155      to :
8156
8157      (1) register list is full, that is, r0-r7 are used.
8158      Prepare: tmp[0] <- r8
8159
8160      POP {r0, r1, ...., r6, r7}; remove PC from reglist
8161      MOV r8, r7; Move value of r7 to r8;
8162      POP {r7}; Store PC value into r7.
8163
8164      Cleanup: PC <- r7, r7 <- r8, r8 <-tmp[0]
8165
8166      (2) register list is not full, supposing there are N registers in
8167      register list (except PC, 0 <= N <= 7).
8168      Prepare: for each i, 0 - N, tmp[i] <- ri.
8169
8170      POP {r0, r1, ...., rN};
8171
8172      Cleanup: Set registers in original reglist from r0 - rN.  Restore r0 - rN
8173      from tmp[] properly.
8174   */
8175   if (debug_displaced)
8176     fprintf_unfiltered (gdb_stdlog,
8177                         "displaced: copying thumb pop {%.8x, pc} insn %.4x\n",
8178                         dsc->u.block.regmask, insn1);
8179
8180   if (dsc->u.block.regmask == 0xff)
8181     {
8182       dsc->tmp[0] = displaced_read_reg (regs, dsc, 8);
8183
8184       dsc->modinsn[0] = (insn1 & 0xfeff); /* POP {r0,r1,...,r6, r7} */
8185       dsc->modinsn[1] = 0x46b8; /* MOV r8, r7 */
8186       dsc->modinsn[2] = 0xbc80; /* POP {r7} */
8187
8188       dsc->numinsns = 3;
8189       dsc->cleanup = &cleanup_pop_pc_16bit_all;
8190     }
8191   else
8192     {
8193       unsigned int num_in_list = bitcount (dsc->u.block.regmask);
8194       unsigned int new_regmask, bit = 1;
8195       unsigned int to = 0, from = 0, i, new_rn;
8196
8197       for (i = 0; i < num_in_list + 1; i++)
8198         dsc->tmp[i] = displaced_read_reg (regs, dsc, i);
8199
8200       new_regmask = (1 << (num_in_list + 1)) - 1;
8201
8202       if (debug_displaced)
8203         fprintf_unfiltered (gdb_stdlog, _("displaced: POP "
8204                                           "{..., pc}: original reg list %.4x,"
8205                                           " modified list %.4x\n"),
8206                             (int) dsc->u.block.regmask, new_regmask);
8207
8208       dsc->u.block.regmask |= 0x8000;
8209       dsc->u.block.writeback = 0;
8210       dsc->u.block.cond = INST_AL;
8211
8212       dsc->modinsn[0] = (insn1 & ~0x1ff) | (new_regmask & 0xff);
8213
8214       dsc->cleanup = &cleanup_block_load_pc;
8215     }
8216
8217   return 0;
8218 }
8219
8220 static void
8221 thumb_process_displaced_16bit_insn (struct gdbarch *gdbarch, uint16_t insn1,
8222                                     struct regcache *regs,
8223                                     struct displaced_step_closure *dsc)
8224 {
8225   unsigned short op_bit_12_15 = bits (insn1, 12, 15);
8226   unsigned short op_bit_10_11 = bits (insn1, 10, 11);
8227   int err = 0;
8228
8229   /* 16-bit thumb instructions.  */
8230   switch (op_bit_12_15)
8231     {
8232       /* Shift (imme), add, subtract, move and compare.  */
8233     case 0: case 1: case 2: case 3:
8234       err = thumb_copy_unmodified_16bit (gdbarch, insn1,
8235                                          "shift/add/sub/mov/cmp",
8236                                          dsc);
8237       break;
8238     case 4:
8239       switch (op_bit_10_11)
8240         {
8241         case 0: /* Data-processing */
8242           err = thumb_copy_unmodified_16bit (gdbarch, insn1,
8243                                              "data-processing",
8244                                              dsc);
8245           break;
8246         case 1: /* Special data instructions and branch and exchange.  */
8247           {
8248             unsigned short op = bits (insn1, 7, 9);
8249             if (op == 6 || op == 7) /* BX or BLX */
8250               err = thumb_copy_bx_blx_reg (gdbarch, insn1, regs, dsc);
8251             else if (bits (insn1, 6, 7) != 0) /* ADD/MOV/CMP high registers.  */
8252               err = thumb_copy_alu_reg (gdbarch, insn1, regs, dsc);
8253             else
8254               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "special data",
8255                                                  dsc);
8256           }
8257           break;
8258         default: /* LDR (literal) */
8259           err = thumb_copy_16bit_ldr_literal (gdbarch, insn1, regs, dsc);
8260         }
8261       break;
8262     case 5: case 6: case 7: case 8: case 9: /* Load/Store single data item */
8263       err = thumb_copy_unmodified_16bit (gdbarch, insn1, "ldr/str", dsc);
8264       break;
8265     case 10:
8266       if (op_bit_10_11 < 2) /* Generate PC-relative address */
8267         err = thumb_decode_pc_relative_16bit (gdbarch, insn1, regs, dsc);
8268       else /* Generate SP-relative address */
8269         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "sp-relative", dsc);
8270       break;
8271     case 11: /* Misc 16-bit instructions */
8272       {
8273         switch (bits (insn1, 8, 11))
8274           {
8275           case 1: case 3:  case 9: case 11: /* CBNZ, CBZ */
8276             err = thumb_copy_cbnz_cbz (gdbarch, insn1, regs, dsc);
8277             break;
8278           case 12: case 13: /* POP */
8279             if (bit (insn1, 8)) /* PC is in register list.  */
8280               err = thumb_copy_pop_pc_16bit (gdbarch, insn1, regs, dsc);
8281             else
8282               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "pop", dsc);
8283             break;
8284           case 15: /* If-Then, and hints */
8285             if (bits (insn1, 0, 3))
8286               /* If-Then makes up to four following instructions conditional.
8287                  IT instruction itself is not conditional, so handle it as a
8288                  common unmodified instruction.  */
8289               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "If-Then",
8290                                                  dsc);
8291             else
8292               err = thumb_copy_unmodified_16bit (gdbarch, insn1, "hints", dsc);
8293             break;
8294           default:
8295             err = thumb_copy_unmodified_16bit (gdbarch, insn1, "misc", dsc);
8296           }
8297       }
8298       break;
8299     case 12:
8300       if (op_bit_10_11 < 2) /* Store multiple registers */
8301         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "stm", dsc);
8302       else /* Load multiple registers */
8303         err = thumb_copy_unmodified_16bit (gdbarch, insn1, "ldm", dsc);
8304       break;
8305     case 13: /* Conditional branch and supervisor call */
8306       if (bits (insn1, 9, 11) != 7) /* conditional branch */
8307         err = thumb_copy_b (gdbarch, insn1, dsc);
8308       else
8309         err = thumb_copy_svc (gdbarch, insn1, regs, dsc);
8310       break;
8311     case 14: /* Unconditional branch */
8312       err = thumb_copy_b (gdbarch, insn1, dsc);
8313       break;
8314     default:
8315       err = 1;
8316     }
8317
8318   if (err)
8319     internal_error (__FILE__, __LINE__,
8320                     _("thumb_process_displaced_16bit_insn: Instruction decode error"));
8321 }
8322
8323 static int
8324 decode_thumb_32bit_ld_mem_hints (struct gdbarch *gdbarch,
8325                                  uint16_t insn1, uint16_t insn2,
8326                                  struct regcache *regs,
8327                                  struct displaced_step_closure *dsc)
8328 {
8329   int rt = bits (insn2, 12, 15);
8330   int rn = bits (insn1, 0, 3);
8331   int op1 = bits (insn1, 7, 8);
8332   int err = 0;
8333
8334   switch (bits (insn1, 5, 6))
8335     {
8336     case 0: /* Load byte and memory hints */
8337       if (rt == 0xf) /* PLD/PLI */
8338         {
8339           if (rn == 0xf)
8340             /* PLD literal or Encoding T3 of PLI(immediate, literal).  */
8341             return thumb2_copy_preload (gdbarch, insn1, insn2, regs, dsc);
8342           else
8343             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8344                                                 "pli/pld", dsc);
8345         }
8346       else
8347         {
8348           if (rn == 0xf) /* LDRB/LDRSB (literal) */
8349             return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc,
8350                                              1);
8351           else
8352             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8353                                                 "ldrb{reg, immediate}/ldrbt",
8354                                                 dsc);
8355         }
8356
8357       break;
8358     case 1: /* Load halfword and memory hints.  */
8359       if (rt == 0xf) /* PLD{W} and Unalloc memory hint.  */
8360         return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8361                                             "pld/unalloc memhint", dsc);
8362       else
8363         {
8364           if (rn == 0xf)
8365             return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc,
8366                                              2);
8367           else
8368             return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8369                                                 "ldrh/ldrht", dsc);
8370         }
8371       break;
8372     case 2: /* Load word */
8373       {
8374         int insn2_bit_8_11 = bits (insn2, 8, 11);
8375
8376         if (rn == 0xf)
8377           return thumb2_copy_load_literal (gdbarch, insn1, insn2, regs, dsc, 4);
8378         else if (op1 == 0x1) /* Encoding T3 */
8379           return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs, dsc,
8380                                            0, 1);
8381         else /* op1 == 0x0 */
8382           {
8383             if (insn2_bit_8_11 == 0xc || (insn2_bit_8_11 & 0x9) == 0x9)
8384               /* LDR (immediate) */
8385               return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs,
8386                                                dsc, bit (insn2, 8), 1);
8387             else if (insn2_bit_8_11 == 0xe) /* LDRT */
8388               return thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8389                                                   "ldrt", dsc);
8390             else
8391               /* LDR (register) */
8392               return thumb2_copy_load_reg_imm (gdbarch, insn1, insn2, regs,
8393                                                dsc, 0, 0);
8394           }
8395         break;
8396       }
8397     default:
8398       return thumb_32bit_copy_undef (gdbarch, insn1, insn2, dsc);
8399       break;
8400     }
8401   return 0;
8402 }
8403
8404 static void
8405 thumb_process_displaced_32bit_insn (struct gdbarch *gdbarch, uint16_t insn1,
8406                                     uint16_t insn2, struct regcache *regs,
8407                                     struct displaced_step_closure *dsc)
8408 {
8409   int err = 0;
8410   unsigned short op = bit (insn2, 15);
8411   unsigned int op1 = bits (insn1, 11, 12);
8412
8413   switch (op1)
8414     {
8415     case 1:
8416       {
8417         switch (bits (insn1, 9, 10))
8418           {
8419           case 0:
8420             if (bit (insn1, 6))
8421               {
8422                 /* Load/store {dual, execlusive}, table branch.  */
8423                 if (bits (insn1, 7, 8) == 1 && bits (insn1, 4, 5) == 1
8424                     && bits (insn2, 5, 7) == 0)
8425                   err = thumb2_copy_table_branch (gdbarch, insn1, insn2, regs,
8426                                                   dsc);
8427                 else
8428                   /* PC is not allowed to use in load/store {dual, exclusive}
8429                      instructions.  */
8430                   err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8431                                                      "load/store dual/ex", dsc);
8432               }
8433             else /* load/store multiple */
8434               {
8435                 switch (bits (insn1, 7, 8))
8436                   {
8437                   case 0: case 3: /* SRS, RFE */
8438                     err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8439                                                        "srs/rfe", dsc);
8440                     break;
8441                   case 1: case 2: /* LDM/STM/PUSH/POP */
8442                     err = thumb2_copy_block_xfer (gdbarch, insn1, insn2, regs, dsc);
8443                     break;
8444                   }
8445               }
8446             break;
8447
8448           case 1:
8449             /* Data-processing (shift register).  */
8450             err = thumb2_decode_dp_shift_reg (gdbarch, insn1, insn2, regs,
8451                                               dsc);
8452             break;
8453           default: /* Coprocessor instructions.  */
8454             err = thumb2_decode_svc_copro (gdbarch, insn1, insn2, regs, dsc);
8455             break;
8456           }
8457       break;
8458       }
8459     case 2: /* op1 = 2 */
8460       if (op) /* Branch and misc control.  */
8461         {
8462           if (bit (insn2, 14)  /* BLX/BL */
8463               || bit (insn2, 12) /* Unconditional branch */
8464               || (bits (insn1, 7, 9) != 0x7)) /* Conditional branch */
8465             err = thumb2_copy_b_bl_blx (gdbarch, insn1, insn2, regs, dsc);
8466           else
8467             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8468                                                "misc ctrl", dsc);
8469         }
8470       else
8471         {
8472           if (bit (insn1, 9)) /* Data processing (plain binary imm).  */
8473             {
8474               int op = bits (insn1, 4, 8);
8475               int rn = bits (insn1, 0, 3);
8476               if ((op == 0 || op == 0xa) && rn == 0xf)
8477                 err = thumb_copy_pc_relative_32bit (gdbarch, insn1, insn2,
8478                                                     regs, dsc);
8479               else
8480                 err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8481                                                    "dp/pb", dsc);
8482             }
8483           else /* Data processing (modified immeidate) */
8484             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8485                                                "dp/mi", dsc);
8486         }
8487       break;
8488     case 3: /* op1 = 3 */
8489       switch (bits (insn1, 9, 10))
8490         {
8491         case 0:
8492           if (bit (insn1, 4))
8493             err = decode_thumb_32bit_ld_mem_hints (gdbarch, insn1, insn2,
8494                                                    regs, dsc);
8495           else /* NEON Load/Store and Store single data item */
8496             err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8497                                                "neon elt/struct load/store",
8498                                                dsc);
8499           break;
8500         case 1: /* op1 = 3, bits (9, 10) == 1 */
8501           switch (bits (insn1, 7, 8))
8502             {
8503             case 0: case 1: /* Data processing (register) */
8504               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8505                                                  "dp(reg)", dsc);
8506               break;
8507             case 2: /* Multiply and absolute difference */
8508               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8509                                                  "mul/mua/diff", dsc);
8510               break;
8511             case 3: /* Long multiply and divide */
8512               err = thumb_copy_unmodified_32bit (gdbarch, insn1, insn2,
8513                                                  "lmul/lmua", dsc);
8514               break;
8515             }
8516           break;
8517         default: /* Coprocessor instructions */
8518           err = thumb2_decode_svc_copro (gdbarch, insn1, insn2, regs, dsc);
8519           break;
8520         }
8521       break;
8522     default:
8523       err = 1;
8524     }
8525
8526   if (err)
8527     internal_error (__FILE__, __LINE__,
8528                     _("thumb_process_displaced_32bit_insn: Instruction decode error"));
8529
8530 }
8531
8532 static void
8533 thumb_process_displaced_insn (struct gdbarch *gdbarch, CORE_ADDR from,
8534                               CORE_ADDR to, struct regcache *regs,
8535                               struct displaced_step_closure *dsc)
8536 {
8537   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8538   uint16_t insn1
8539     = read_memory_unsigned_integer (from, 2, byte_order_for_code);
8540
8541   if (debug_displaced)
8542     fprintf_unfiltered (gdb_stdlog, "displaced: process thumb insn %.4x "
8543                         "at %.8lx\n", insn1, (unsigned long) from);
8544
8545   dsc->is_thumb = 1;
8546   dsc->insn_size = thumb_insn_size (insn1);
8547   if (thumb_insn_size (insn1) == 4)
8548     {
8549       uint16_t insn2
8550         = read_memory_unsigned_integer (from + 2, 2, byte_order_for_code);
8551       thumb_process_displaced_32bit_insn (gdbarch, insn1, insn2, regs, dsc);
8552     }
8553   else
8554     thumb_process_displaced_16bit_insn (gdbarch, insn1, regs, dsc);
8555 }
8556
8557 void
8558 arm_process_displaced_insn (struct gdbarch *gdbarch, CORE_ADDR from,
8559                             CORE_ADDR to, struct regcache *regs,
8560                             struct displaced_step_closure *dsc)
8561 {
8562   int err = 0;
8563   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8564   uint32_t insn;
8565
8566   /* Most displaced instructions use a 1-instruction scratch space, so set this
8567      here and override below if/when necessary.  */
8568   dsc->numinsns = 1;
8569   dsc->insn_addr = from;
8570   dsc->scratch_base = to;
8571   dsc->cleanup = NULL;
8572   dsc->wrote_to_pc = 0;
8573
8574   if (!displaced_in_arm_mode (regs))
8575     return thumb_process_displaced_insn (gdbarch, from, to, regs, dsc);
8576
8577   dsc->is_thumb = 0;
8578   dsc->insn_size = 4;
8579   insn = read_memory_unsigned_integer (from, 4, byte_order_for_code);
8580   if (debug_displaced)
8581     fprintf_unfiltered (gdb_stdlog, "displaced: stepping insn %.8lx "
8582                         "at %.8lx\n", (unsigned long) insn,
8583                         (unsigned long) from);
8584
8585   if ((insn & 0xf0000000) == 0xf0000000)
8586     err = arm_decode_unconditional (gdbarch, insn, regs, dsc);
8587   else switch (((insn & 0x10) >> 4) | ((insn & 0xe000000) >> 24))
8588     {
8589     case 0x0: case 0x1: case 0x2: case 0x3:
8590       err = arm_decode_dp_misc (gdbarch, insn, regs, dsc);
8591       break;
8592
8593     case 0x4: case 0x5: case 0x6:
8594       err = arm_decode_ld_st_word_ubyte (gdbarch, insn, regs, dsc);
8595       break;
8596
8597     case 0x7:
8598       err = arm_decode_media (gdbarch, insn, dsc);
8599       break;
8600
8601     case 0x8: case 0x9: case 0xa: case 0xb:
8602       err = arm_decode_b_bl_ldmstm (gdbarch, insn, regs, dsc);
8603       break;
8604
8605     case 0xc: case 0xd: case 0xe: case 0xf:
8606       err = arm_decode_svc_copro (gdbarch, insn, to, regs, dsc);
8607       break;
8608     }
8609
8610   if (err)
8611     internal_error (__FILE__, __LINE__,
8612                     _("arm_process_displaced_insn: Instruction decode error"));
8613 }
8614
8615 /* Actually set up the scratch space for a displaced instruction.  */
8616
8617 void
8618 arm_displaced_init_closure (struct gdbarch *gdbarch, CORE_ADDR from,
8619                             CORE_ADDR to, struct displaced_step_closure *dsc)
8620 {
8621   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8622   unsigned int i, len, offset;
8623   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8624   int size = dsc->is_thumb? 2 : 4;
8625   const unsigned char *bkp_insn;
8626
8627   offset = 0;
8628   /* Poke modified instruction(s).  */
8629   for (i = 0; i < dsc->numinsns; i++)
8630     {
8631       if (debug_displaced)
8632         {
8633           fprintf_unfiltered (gdb_stdlog, "displaced: writing insn ");
8634           if (size == 4)
8635             fprintf_unfiltered (gdb_stdlog, "%.8lx",
8636                                 dsc->modinsn[i]);
8637           else if (size == 2)
8638             fprintf_unfiltered (gdb_stdlog, "%.4x",
8639                                 (unsigned short)dsc->modinsn[i]);
8640
8641           fprintf_unfiltered (gdb_stdlog, " at %.8lx\n",
8642                               (unsigned long) to + offset);
8643
8644         }
8645       write_memory_unsigned_integer (to + offset, size,
8646                                      byte_order_for_code,
8647                                      dsc->modinsn[i]);
8648       offset += size;
8649     }
8650
8651   /* Choose the correct breakpoint instruction.  */
8652   if (dsc->is_thumb)
8653     {
8654       bkp_insn = tdep->thumb_breakpoint;
8655       len = tdep->thumb_breakpoint_size;
8656     }
8657   else
8658     {
8659       bkp_insn = tdep->arm_breakpoint;
8660       len = tdep->arm_breakpoint_size;
8661     }
8662
8663   /* Put breakpoint afterwards.  */
8664   write_memory (to + offset, bkp_insn, len);
8665
8666   if (debug_displaced)
8667     fprintf_unfiltered (gdb_stdlog, "displaced: copy %s->%s: ",
8668                         paddress (gdbarch, from), paddress (gdbarch, to));
8669 }
8670
8671 /* Entry point for copying an instruction into scratch space for displaced
8672    stepping.  */
8673
8674 struct displaced_step_closure *
8675 arm_displaced_step_copy_insn (struct gdbarch *gdbarch,
8676                               CORE_ADDR from, CORE_ADDR to,
8677                               struct regcache *regs)
8678 {
8679   struct displaced_step_closure *dsc
8680     = xmalloc (sizeof (struct displaced_step_closure));
8681   arm_process_displaced_insn (gdbarch, from, to, regs, dsc);
8682   arm_displaced_init_closure (gdbarch, from, to, dsc);
8683
8684   return dsc;
8685 }
8686
8687 /* Entry point for cleaning things up after a displaced instruction has been
8688    single-stepped.  */
8689
8690 void
8691 arm_displaced_step_fixup (struct gdbarch *gdbarch,
8692                           struct displaced_step_closure *dsc,
8693                           CORE_ADDR from, CORE_ADDR to,
8694                           struct regcache *regs)
8695 {
8696   if (dsc->cleanup)
8697     dsc->cleanup (gdbarch, regs, dsc);
8698
8699   if (!dsc->wrote_to_pc)
8700     regcache_cooked_write_unsigned (regs, ARM_PC_REGNUM,
8701                                     dsc->insn_addr + dsc->insn_size);
8702
8703 }
8704
8705 #include "bfd-in2.h"
8706 #include "libcoff.h"
8707
8708 static int
8709 gdb_print_insn_arm (bfd_vma memaddr, disassemble_info *info)
8710 {
8711   struct gdbarch *gdbarch = info->application_data;
8712
8713   if (arm_pc_is_thumb (gdbarch, memaddr))
8714     {
8715       static asymbol *asym;
8716       static combined_entry_type ce;
8717       static struct coff_symbol_struct csym;
8718       static struct bfd fake_bfd;
8719       static bfd_target fake_target;
8720
8721       if (csym.native == NULL)
8722         {
8723           /* Create a fake symbol vector containing a Thumb symbol.
8724              This is solely so that the code in print_insn_little_arm() 
8725              and print_insn_big_arm() in opcodes/arm-dis.c will detect
8726              the presence of a Thumb symbol and switch to decoding
8727              Thumb instructions.  */
8728
8729           fake_target.flavour = bfd_target_coff_flavour;
8730           fake_bfd.xvec = &fake_target;
8731           ce.u.syment.n_sclass = C_THUMBEXTFUNC;
8732           csym.native = &ce;
8733           csym.symbol.the_bfd = &fake_bfd;
8734           csym.symbol.name = "fake";
8735           asym = (asymbol *) & csym;
8736         }
8737
8738       memaddr = UNMAKE_THUMB_ADDR (memaddr);
8739       info->symbols = &asym;
8740     }
8741   else
8742     info->symbols = NULL;
8743
8744   if (info->endian == BFD_ENDIAN_BIG)
8745     return print_insn_big_arm (memaddr, info);
8746   else
8747     return print_insn_little_arm (memaddr, info);
8748 }
8749
8750 /* The following define instruction sequences that will cause ARM
8751    cpu's to take an undefined instruction trap.  These are used to
8752    signal a breakpoint to GDB.
8753    
8754    The newer ARMv4T cpu's are capable of operating in ARM or Thumb
8755    modes.  A different instruction is required for each mode.  The ARM
8756    cpu's can also be big or little endian.  Thus four different
8757    instructions are needed to support all cases.
8758    
8759    Note: ARMv4 defines several new instructions that will take the
8760    undefined instruction trap.  ARM7TDMI is nominally ARMv4T, but does
8761    not in fact add the new instructions.  The new undefined
8762    instructions in ARMv4 are all instructions that had no defined
8763    behaviour in earlier chips.  There is no guarantee that they will
8764    raise an exception, but may be treated as NOP's.  In practice, it
8765    may only safe to rely on instructions matching:
8766    
8767    3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 
8768    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
8769    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
8770    
8771    Even this may only true if the condition predicate is true.  The
8772    following use a condition predicate of ALWAYS so it is always TRUE.
8773    
8774    There are other ways of forcing a breakpoint.  GNU/Linux, RISC iX,
8775    and NetBSD all use a software interrupt rather than an undefined
8776    instruction to force a trap.  This can be handled by by the
8777    abi-specific code during establishment of the gdbarch vector.  */
8778
8779 #define ARM_LE_BREAKPOINT {0xFE,0xDE,0xFF,0xE7}
8780 #define ARM_BE_BREAKPOINT {0xE7,0xFF,0xDE,0xFE}
8781 #define THUMB_LE_BREAKPOINT {0xbe,0xbe}
8782 #define THUMB_BE_BREAKPOINT {0xbe,0xbe}
8783
8784 static const char arm_default_arm_le_breakpoint[] = ARM_LE_BREAKPOINT;
8785 static const char arm_default_arm_be_breakpoint[] = ARM_BE_BREAKPOINT;
8786 static const char arm_default_thumb_le_breakpoint[] = THUMB_LE_BREAKPOINT;
8787 static const char arm_default_thumb_be_breakpoint[] = THUMB_BE_BREAKPOINT;
8788
8789 /* Determine the type and size of breakpoint to insert at PCPTR.  Uses
8790    the program counter value to determine whether a 16-bit or 32-bit
8791    breakpoint should be used.  It returns a pointer to a string of
8792    bytes that encode a breakpoint instruction, stores the length of
8793    the string to *lenptr, and adjusts the program counter (if
8794    necessary) to point to the actual memory location where the
8795    breakpoint should be inserted.  */
8796
8797 static const unsigned char *
8798 arm_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr, int *lenptr)
8799 {
8800   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
8801   enum bfd_endian byte_order_for_code = gdbarch_byte_order_for_code (gdbarch);
8802
8803   if (arm_pc_is_thumb (gdbarch, *pcptr))
8804     {
8805       *pcptr = UNMAKE_THUMB_ADDR (*pcptr);
8806
8807       /* If we have a separate 32-bit breakpoint instruction for Thumb-2,
8808          check whether we are replacing a 32-bit instruction.  */
8809       if (tdep->thumb2_breakpoint != NULL)
8810         {
8811           gdb_byte buf[2];
8812           if (target_read_memory (*pcptr, buf, 2) == 0)
8813             {
8814               unsigned short inst1;
8815               inst1 = extract_unsigned_integer (buf, 2, byte_order_for_code);
8816               if (thumb_insn_size (inst1) == 4)
8817                 {
8818                   *lenptr = tdep->thumb2_breakpoint_size;
8819                   return tdep->thumb2_breakpoint;
8820                 }
8821             }
8822         }
8823
8824       *lenptr = tdep->thumb_breakpoint_size;
8825       return tdep->thumb_breakpoint;
8826     }
8827   else
8828     {
8829       *lenptr = tdep->arm_breakpoint_size;
8830       return tdep->arm_breakpoint;
8831     }
8832 }
8833
8834 static void
8835 arm_remote_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr,
8836                                int *kindptr)
8837 {
8838   arm_breakpoint_from_pc (gdbarch, pcptr, kindptr);
8839
8840   if (arm_pc_is_thumb (gdbarch, *pcptr) && *kindptr == 4)
8841     /* The documented magic value for a 32-bit Thumb-2 breakpoint, so
8842        that this is not confused with a 32-bit ARM breakpoint.  */
8843     *kindptr = 3;
8844 }
8845
8846 /* Extract from an array REGBUF containing the (raw) register state a
8847    function return value of type TYPE, and copy that, in virtual
8848    format, into VALBUF.  */
8849
8850 static void
8851 arm_extract_return_value (struct type *type, struct regcache *regs,
8852                           gdb_byte *valbuf)
8853 {
8854   struct gdbarch *gdbarch = get_regcache_arch (regs);
8855   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
8856
8857   if (TYPE_CODE_FLT == TYPE_CODE (type))
8858     {
8859       switch (gdbarch_tdep (gdbarch)->fp_model)
8860         {
8861         case ARM_FLOAT_FPA:
8862           {
8863             /* The value is in register F0 in internal format.  We need to
8864                extract the raw value and then convert it to the desired
8865                internal type.  */
8866             bfd_byte tmpbuf[FP_REGISTER_SIZE];
8867
8868             regcache_cooked_read (regs, ARM_F0_REGNUM, tmpbuf);
8869             convert_from_extended (floatformat_from_type (type), tmpbuf,
8870                                    valbuf, gdbarch_byte_order (gdbarch));
8871           }
8872           break;
8873
8874         case ARM_FLOAT_SOFT_FPA:
8875         case ARM_FLOAT_SOFT_VFP:
8876           /* ARM_FLOAT_VFP can arise if this is a variadic function so
8877              not using the VFP ABI code.  */
8878         case ARM_FLOAT_VFP:
8879           regcache_cooked_read (regs, ARM_A1_REGNUM, valbuf);
8880           if (TYPE_LENGTH (type) > 4)
8881             regcache_cooked_read (regs, ARM_A1_REGNUM + 1,
8882                                   valbuf + INT_REGISTER_SIZE);
8883           break;
8884
8885         default:
8886           internal_error (__FILE__, __LINE__,
8887                           _("arm_extract_return_value: "
8888                             "Floating point model not supported"));
8889           break;
8890         }
8891     }
8892   else if (TYPE_CODE (type) == TYPE_CODE_INT
8893            || TYPE_CODE (type) == TYPE_CODE_CHAR
8894            || TYPE_CODE (type) == TYPE_CODE_BOOL
8895            || TYPE_CODE (type) == TYPE_CODE_PTR
8896            || TYPE_CODE (type) == TYPE_CODE_REF
8897            || TYPE_CODE (type) == TYPE_CODE_ENUM)
8898     {
8899       /* If the type is a plain integer, then the access is
8900          straight-forward.  Otherwise we have to play around a bit
8901          more.  */
8902       int len = TYPE_LENGTH (type);
8903       int regno = ARM_A1_REGNUM;
8904       ULONGEST tmp;
8905
8906       while (len > 0)
8907         {
8908           /* By using store_unsigned_integer we avoid having to do
8909              anything special for small big-endian values.  */
8910           regcache_cooked_read_unsigned (regs, regno++, &tmp);
8911           store_unsigned_integer (valbuf, 
8912                                   (len > INT_REGISTER_SIZE
8913                                    ? INT_REGISTER_SIZE : len),
8914                                   byte_order, tmp);
8915           len -= INT_REGISTER_SIZE;
8916           valbuf += INT_REGISTER_SIZE;
8917         }
8918     }
8919   else
8920     {
8921       /* For a structure or union the behaviour is as if the value had
8922          been stored to word-aligned memory and then loaded into 
8923          registers with 32-bit load instruction(s).  */
8924       int len = TYPE_LENGTH (type);
8925       int regno = ARM_A1_REGNUM;
8926       bfd_byte tmpbuf[INT_REGISTER_SIZE];
8927
8928       while (len > 0)
8929         {
8930           regcache_cooked_read (regs, regno++, tmpbuf);
8931           memcpy (valbuf, tmpbuf,
8932                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
8933           len -= INT_REGISTER_SIZE;
8934           valbuf += INT_REGISTER_SIZE;
8935         }
8936     }
8937 }
8938
8939
8940 /* Will a function return an aggregate type in memory or in a
8941    register?  Return 0 if an aggregate type can be returned in a
8942    register, 1 if it must be returned in memory.  */
8943
8944 static int
8945 arm_return_in_memory (struct gdbarch *gdbarch, struct type *type)
8946 {
8947   int nRc;
8948   enum type_code code;
8949
8950   CHECK_TYPEDEF (type);
8951
8952   /* In the ARM ABI, "integer" like aggregate types are returned in
8953      registers.  For an aggregate type to be integer like, its size
8954      must be less than or equal to INT_REGISTER_SIZE and the
8955      offset of each addressable subfield must be zero.  Note that bit
8956      fields are not addressable, and all addressable subfields of
8957      unions always start at offset zero.
8958
8959      This function is based on the behaviour of GCC 2.95.1.
8960      See: gcc/arm.c: arm_return_in_memory() for details.
8961
8962      Note: All versions of GCC before GCC 2.95.2 do not set up the
8963      parameters correctly for a function returning the following
8964      structure: struct { float f;}; This should be returned in memory,
8965      not a register.  Richard Earnshaw sent me a patch, but I do not
8966      know of any way to detect if a function like the above has been
8967      compiled with the correct calling convention.  */
8968
8969   /* All aggregate types that won't fit in a register must be returned
8970      in memory.  */
8971   if (TYPE_LENGTH (type) > INT_REGISTER_SIZE)
8972     {
8973       return 1;
8974     }
8975
8976   /* The AAPCS says all aggregates not larger than a word are returned
8977      in a register.  */
8978   if (gdbarch_tdep (gdbarch)->arm_abi != ARM_ABI_APCS)
8979     return 0;
8980
8981   /* The only aggregate types that can be returned in a register are
8982      structs and unions.  Arrays must be returned in memory.  */
8983   code = TYPE_CODE (type);
8984   if ((TYPE_CODE_STRUCT != code) && (TYPE_CODE_UNION != code))
8985     {
8986       return 1;
8987     }
8988
8989   /* Assume all other aggregate types can be returned in a register.
8990      Run a check for structures, unions and arrays.  */
8991   nRc = 0;
8992
8993   if ((TYPE_CODE_STRUCT == code) || (TYPE_CODE_UNION == code))
8994     {
8995       int i;
8996       /* Need to check if this struct/union is "integer" like.  For
8997          this to be true, its size must be less than or equal to
8998          INT_REGISTER_SIZE and the offset of each addressable
8999          subfield must be zero.  Note that bit fields are not
9000          addressable, and unions always start at offset zero.  If any
9001          of the subfields is a floating point type, the struct/union
9002          cannot be an integer type.  */
9003
9004       /* For each field in the object, check:
9005          1) Is it FP? --> yes, nRc = 1;
9006          2) Is it addressable (bitpos != 0) and
9007          not packed (bitsize == 0)?
9008          --> yes, nRc = 1  
9009        */
9010
9011       for (i = 0; i < TYPE_NFIELDS (type); i++)
9012         {
9013           enum type_code field_type_code;
9014           field_type_code = TYPE_CODE (check_typedef (TYPE_FIELD_TYPE (type,
9015                                                                        i)));
9016
9017           /* Is it a floating point type field?  */
9018           if (field_type_code == TYPE_CODE_FLT)
9019             {
9020               nRc = 1;
9021               break;
9022             }
9023
9024           /* If bitpos != 0, then we have to care about it.  */
9025           if (TYPE_FIELD_BITPOS (type, i) != 0)
9026             {
9027               /* Bitfields are not addressable.  If the field bitsize is 
9028                  zero, then the field is not packed.  Hence it cannot be
9029                  a bitfield or any other packed type.  */
9030               if (TYPE_FIELD_BITSIZE (type, i) == 0)
9031                 {
9032                   nRc = 1;
9033                   break;
9034                 }
9035             }
9036         }
9037     }
9038
9039   return nRc;
9040 }
9041
9042 /* Write into appropriate registers a function return value of type
9043    TYPE, given in virtual format.  */
9044
9045 static void
9046 arm_store_return_value (struct type *type, struct regcache *regs,
9047                         const gdb_byte *valbuf)
9048 {
9049   struct gdbarch *gdbarch = get_regcache_arch (regs);
9050   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
9051
9052   if (TYPE_CODE (type) == TYPE_CODE_FLT)
9053     {
9054       char buf[MAX_REGISTER_SIZE];
9055
9056       switch (gdbarch_tdep (gdbarch)->fp_model)
9057         {
9058         case ARM_FLOAT_FPA:
9059
9060           convert_to_extended (floatformat_from_type (type), buf, valbuf,
9061                                gdbarch_byte_order (gdbarch));
9062           regcache_cooked_write (regs, ARM_F0_REGNUM, buf);
9063           break;
9064
9065         case ARM_FLOAT_SOFT_FPA:
9066         case ARM_FLOAT_SOFT_VFP:
9067           /* ARM_FLOAT_VFP can arise if this is a variadic function so
9068              not using the VFP ABI code.  */
9069         case ARM_FLOAT_VFP:
9070           regcache_cooked_write (regs, ARM_A1_REGNUM, valbuf);
9071           if (TYPE_LENGTH (type) > 4)
9072             regcache_cooked_write (regs, ARM_A1_REGNUM + 1, 
9073                                    valbuf + INT_REGISTER_SIZE);
9074           break;
9075
9076         default:
9077           internal_error (__FILE__, __LINE__,
9078                           _("arm_store_return_value: Floating "
9079                             "point model not supported"));
9080           break;
9081         }
9082     }
9083   else if (TYPE_CODE (type) == TYPE_CODE_INT
9084            || TYPE_CODE (type) == TYPE_CODE_CHAR
9085            || TYPE_CODE (type) == TYPE_CODE_BOOL
9086            || TYPE_CODE (type) == TYPE_CODE_PTR
9087            || TYPE_CODE (type) == TYPE_CODE_REF
9088            || TYPE_CODE (type) == TYPE_CODE_ENUM)
9089     {
9090       if (TYPE_LENGTH (type) <= 4)
9091         {
9092           /* Values of one word or less are zero/sign-extended and
9093              returned in r0.  */
9094           bfd_byte tmpbuf[INT_REGISTER_SIZE];
9095           LONGEST val = unpack_long (type, valbuf);
9096
9097           store_signed_integer (tmpbuf, INT_REGISTER_SIZE, byte_order, val);
9098           regcache_cooked_write (regs, ARM_A1_REGNUM, tmpbuf);
9099         }
9100       else
9101         {
9102           /* Integral values greater than one word are stored in consecutive
9103              registers starting with r0.  This will always be a multiple of
9104              the regiser size.  */
9105           int len = TYPE_LENGTH (type);
9106           int regno = ARM_A1_REGNUM;
9107
9108           while (len > 0)
9109             {
9110               regcache_cooked_write (regs, regno++, valbuf);
9111               len -= INT_REGISTER_SIZE;
9112               valbuf += INT_REGISTER_SIZE;
9113             }
9114         }
9115     }
9116   else
9117     {
9118       /* For a structure or union the behaviour is as if the value had
9119          been stored to word-aligned memory and then loaded into 
9120          registers with 32-bit load instruction(s).  */
9121       int len = TYPE_LENGTH (type);
9122       int regno = ARM_A1_REGNUM;
9123       bfd_byte tmpbuf[INT_REGISTER_SIZE];
9124
9125       while (len > 0)
9126         {
9127           memcpy (tmpbuf, valbuf,
9128                   len > INT_REGISTER_SIZE ? INT_REGISTER_SIZE : len);
9129           regcache_cooked_write (regs, regno++, tmpbuf);
9130           len -= INT_REGISTER_SIZE;
9131           valbuf += INT_REGISTER_SIZE;
9132         }
9133     }
9134 }
9135
9136
9137 /* Handle function return values.  */
9138
9139 static enum return_value_convention
9140 arm_return_value (struct gdbarch *gdbarch, struct value *function,
9141                   struct type *valtype, struct regcache *regcache,
9142                   gdb_byte *readbuf, const gdb_byte *writebuf)
9143 {
9144   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
9145   struct type *func_type = function ? value_type (function) : NULL;
9146   enum arm_vfp_cprc_base_type vfp_base_type;
9147   int vfp_base_count;
9148
9149   if (arm_vfp_abi_for_function (gdbarch, func_type)
9150       && arm_vfp_call_candidate (valtype, &vfp_base_type, &vfp_base_count))
9151     {
9152       int reg_char = arm_vfp_cprc_reg_char (vfp_base_type);
9153       int unit_length = arm_vfp_cprc_unit_length (vfp_base_type);
9154       int i;
9155       for (i = 0; i < vfp_base_count; i++)
9156         {
9157           if (reg_char == 'q')
9158             {
9159               if (writebuf)
9160                 arm_neon_quad_write (gdbarch, regcache, i,
9161                                      writebuf + i * unit_length);
9162
9163               if (readbuf)
9164                 arm_neon_quad_read (gdbarch, regcache, i,
9165                                     readbuf + i * unit_length);
9166             }
9167           else
9168             {
9169               char name_buf[4];
9170               int regnum;
9171
9172               sprintf (name_buf, "%c%d", reg_char, i);
9173               regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9174                                                     strlen (name_buf));
9175               if (writebuf)
9176                 regcache_cooked_write (regcache, regnum,
9177                                        writebuf + i * unit_length);
9178               if (readbuf)
9179                 regcache_cooked_read (regcache, regnum,
9180                                       readbuf + i * unit_length);
9181             }
9182         }
9183       return RETURN_VALUE_REGISTER_CONVENTION;
9184     }
9185
9186   if (TYPE_CODE (valtype) == TYPE_CODE_STRUCT
9187       || TYPE_CODE (valtype) == TYPE_CODE_UNION
9188       || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
9189     {
9190       if (tdep->struct_return == pcc_struct_return
9191           || arm_return_in_memory (gdbarch, valtype))
9192         return RETURN_VALUE_STRUCT_CONVENTION;
9193     }
9194
9195   /* AAPCS returns complex types longer than a register in memory.  */
9196   if (tdep->arm_abi != ARM_ABI_APCS
9197       && TYPE_CODE (valtype) == TYPE_CODE_COMPLEX
9198       && TYPE_LENGTH (valtype) > INT_REGISTER_SIZE)
9199     return RETURN_VALUE_STRUCT_CONVENTION;
9200
9201   if (writebuf)
9202     arm_store_return_value (valtype, regcache, writebuf);
9203
9204   if (readbuf)
9205     arm_extract_return_value (valtype, regcache, readbuf);
9206
9207   return RETURN_VALUE_REGISTER_CONVENTION;
9208 }
9209
9210
9211 static int
9212 arm_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
9213 {
9214   struct gdbarch *gdbarch = get_frame_arch (frame);
9215   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
9216   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
9217   CORE_ADDR jb_addr;
9218   char buf[INT_REGISTER_SIZE];
9219   
9220   jb_addr = get_frame_register_unsigned (frame, ARM_A1_REGNUM);
9221
9222   if (target_read_memory (jb_addr + tdep->jb_pc * tdep->jb_elt_size, buf,
9223                           INT_REGISTER_SIZE))
9224     return 0;
9225
9226   *pc = extract_unsigned_integer (buf, INT_REGISTER_SIZE, byte_order);
9227   return 1;
9228 }
9229
9230 /* Recognize GCC and GNU ld's trampolines.  If we are in a trampoline,
9231    return the target PC.  Otherwise return 0.  */
9232
9233 CORE_ADDR
9234 arm_skip_stub (struct frame_info *frame, CORE_ADDR pc)
9235 {
9236   const char *name;
9237   int namelen;
9238   CORE_ADDR start_addr;
9239
9240   /* Find the starting address and name of the function containing the PC.  */
9241   if (find_pc_partial_function (pc, &name, &start_addr, NULL) == 0)
9242     return 0;
9243
9244   /* If PC is in a Thumb call or return stub, return the address of the
9245      target PC, which is in a register.  The thunk functions are called
9246      _call_via_xx, where x is the register name.  The possible names
9247      are r0-r9, sl, fp, ip, sp, and lr.  ARM RealView has similar
9248      functions, named __ARM_call_via_r[0-7].  */
9249   if (strncmp (name, "_call_via_", 10) == 0
9250       || strncmp (name, "__ARM_call_via_", strlen ("__ARM_call_via_")) == 0)
9251     {
9252       /* Use the name suffix to determine which register contains the
9253          target PC.  */
9254       static char *table[15] =
9255       {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
9256        "r8", "r9", "sl", "fp", "ip", "sp", "lr"
9257       };
9258       int regno;
9259       int offset = strlen (name) - 2;
9260
9261       for (regno = 0; regno <= 14; regno++)
9262         if (strcmp (&name[offset], table[regno]) == 0)
9263           return get_frame_register_unsigned (frame, regno);
9264     }
9265
9266   /* GNU ld generates __foo_from_arm or __foo_from_thumb for
9267      non-interworking calls to foo.  We could decode the stubs
9268      to find the target but it's easier to use the symbol table.  */
9269   namelen = strlen (name);
9270   if (name[0] == '_' && name[1] == '_'
9271       && ((namelen > 2 + strlen ("_from_thumb")
9272            && strncmp (name + namelen - strlen ("_from_thumb"), "_from_thumb",
9273                        strlen ("_from_thumb")) == 0)
9274           || (namelen > 2 + strlen ("_from_arm")
9275               && strncmp (name + namelen - strlen ("_from_arm"), "_from_arm",
9276                           strlen ("_from_arm")) == 0)))
9277     {
9278       char *target_name;
9279       int target_len = namelen - 2;
9280       struct minimal_symbol *minsym;
9281       struct objfile *objfile;
9282       struct obj_section *sec;
9283
9284       if (name[namelen - 1] == 'b')
9285         target_len -= strlen ("_from_thumb");
9286       else
9287         target_len -= strlen ("_from_arm");
9288
9289       target_name = alloca (target_len + 1);
9290       memcpy (target_name, name + 2, target_len);
9291       target_name[target_len] = '\0';
9292
9293       sec = find_pc_section (pc);
9294       objfile = (sec == NULL) ? NULL : sec->objfile;
9295       minsym = lookup_minimal_symbol (target_name, NULL, objfile);
9296       if (minsym != NULL)
9297         return SYMBOL_VALUE_ADDRESS (minsym);
9298       else
9299         return 0;
9300     }
9301
9302   return 0;                     /* not a stub */
9303 }
9304
9305 static void
9306 set_arm_command (char *args, int from_tty)
9307 {
9308   printf_unfiltered (_("\
9309 \"set arm\" must be followed by an apporpriate subcommand.\n"));
9310   help_list (setarmcmdlist, "set arm ", all_commands, gdb_stdout);
9311 }
9312
9313 static void
9314 show_arm_command (char *args, int from_tty)
9315 {
9316   cmd_show_list (showarmcmdlist, from_tty, "");
9317 }
9318
9319 static void
9320 arm_update_current_architecture (void)
9321 {
9322   struct gdbarch_info info;
9323
9324   /* If the current architecture is not ARM, we have nothing to do.  */
9325   if (gdbarch_bfd_arch_info (target_gdbarch ())->arch != bfd_arch_arm)
9326     return;
9327
9328   /* Update the architecture.  */
9329   gdbarch_info_init (&info);
9330
9331   if (!gdbarch_update_p (info))
9332     internal_error (__FILE__, __LINE__, _("could not update architecture"));
9333 }
9334
9335 static void
9336 set_fp_model_sfunc (char *args, int from_tty,
9337                     struct cmd_list_element *c)
9338 {
9339   enum arm_float_model fp_model;
9340
9341   for (fp_model = ARM_FLOAT_AUTO; fp_model != ARM_FLOAT_LAST; fp_model++)
9342     if (strcmp (current_fp_model, fp_model_strings[fp_model]) == 0)
9343       {
9344         arm_fp_model = fp_model;
9345         break;
9346       }
9347
9348   if (fp_model == ARM_FLOAT_LAST)
9349     internal_error (__FILE__, __LINE__, _("Invalid fp model accepted: %s."),
9350                     current_fp_model);
9351
9352   arm_update_current_architecture ();
9353 }
9354
9355 static void
9356 show_fp_model (struct ui_file *file, int from_tty,
9357                struct cmd_list_element *c, const char *value)
9358 {
9359   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9360
9361   if (arm_fp_model == ARM_FLOAT_AUTO
9362       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_arm)
9363     fprintf_filtered (file, _("\
9364 The current ARM floating point model is \"auto\" (currently \"%s\").\n"),
9365                       fp_model_strings[tdep->fp_model]);
9366   else
9367     fprintf_filtered (file, _("\
9368 The current ARM floating point model is \"%s\".\n"),
9369                       fp_model_strings[arm_fp_model]);
9370 }
9371
9372 static void
9373 arm_set_abi (char *args, int from_tty,
9374              struct cmd_list_element *c)
9375 {
9376   enum arm_abi_kind arm_abi;
9377
9378   for (arm_abi = ARM_ABI_AUTO; arm_abi != ARM_ABI_LAST; arm_abi++)
9379     if (strcmp (arm_abi_string, arm_abi_strings[arm_abi]) == 0)
9380       {
9381         arm_abi_global = arm_abi;
9382         break;
9383       }
9384
9385   if (arm_abi == ARM_ABI_LAST)
9386     internal_error (__FILE__, __LINE__, _("Invalid ABI accepted: %s."),
9387                     arm_abi_string);
9388
9389   arm_update_current_architecture ();
9390 }
9391
9392 static void
9393 arm_show_abi (struct ui_file *file, int from_tty,
9394              struct cmd_list_element *c, const char *value)
9395 {
9396   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9397
9398   if (arm_abi_global == ARM_ABI_AUTO
9399       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_arm)
9400     fprintf_filtered (file, _("\
9401 The current ARM ABI is \"auto\" (currently \"%s\").\n"),
9402                       arm_abi_strings[tdep->arm_abi]);
9403   else
9404     fprintf_filtered (file, _("The current ARM ABI is \"%s\".\n"),
9405                       arm_abi_string);
9406 }
9407
9408 static void
9409 arm_show_fallback_mode (struct ui_file *file, int from_tty,
9410                         struct cmd_list_element *c, const char *value)
9411 {
9412   fprintf_filtered (file,
9413                     _("The current execution mode assumed "
9414                       "(when symbols are unavailable) is \"%s\".\n"),
9415                     arm_fallback_mode_string);
9416 }
9417
9418 static void
9419 arm_show_force_mode (struct ui_file *file, int from_tty,
9420                      struct cmd_list_element *c, const char *value)
9421 {
9422   struct gdbarch_tdep *tdep = gdbarch_tdep (target_gdbarch ());
9423
9424   fprintf_filtered (file,
9425                     _("The current execution mode assumed "
9426                       "(even when symbols are available) is \"%s\".\n"),
9427                     arm_force_mode_string);
9428 }
9429
9430 /* If the user changes the register disassembly style used for info
9431    register and other commands, we have to also switch the style used
9432    in opcodes for disassembly output.  This function is run in the "set
9433    arm disassembly" command, and does that.  */
9434
9435 static void
9436 set_disassembly_style_sfunc (char *args, int from_tty,
9437                               struct cmd_list_element *c)
9438 {
9439   set_disassembly_style ();
9440 }
9441 \f
9442 /* Return the ARM register name corresponding to register I.  */
9443 static const char *
9444 arm_register_name (struct gdbarch *gdbarch, int i)
9445 {
9446   const int num_regs = gdbarch_num_regs (gdbarch);
9447
9448   if (gdbarch_tdep (gdbarch)->have_vfp_pseudos
9449       && i >= num_regs && i < num_regs + 32)
9450     {
9451       static const char *const vfp_pseudo_names[] = {
9452         "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
9453         "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
9454         "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
9455         "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
9456       };
9457
9458       return vfp_pseudo_names[i - num_regs];
9459     }
9460
9461   if (gdbarch_tdep (gdbarch)->have_neon_pseudos
9462       && i >= num_regs + 32 && i < num_regs + 32 + 16)
9463     {
9464       static const char *const neon_pseudo_names[] = {
9465         "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
9466         "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15",
9467       };
9468
9469       return neon_pseudo_names[i - num_regs - 32];
9470     }
9471
9472   if (i >= ARRAY_SIZE (arm_register_names))
9473     /* These registers are only supported on targets which supply
9474        an XML description.  */
9475     return "";
9476
9477   return arm_register_names[i];
9478 }
9479
9480 static void
9481 set_disassembly_style (void)
9482 {
9483   int current;
9484
9485   /* Find the style that the user wants.  */
9486   for (current = 0; current < num_disassembly_options; current++)
9487     if (disassembly_style == valid_disassembly_styles[current])
9488       break;
9489   gdb_assert (current < num_disassembly_options);
9490
9491   /* Synchronize the disassembler.  */
9492   set_arm_regname_option (current);
9493 }
9494
9495 /* Test whether the coff symbol specific value corresponds to a Thumb
9496    function.  */
9497
9498 static int
9499 coff_sym_is_thumb (int val)
9500 {
9501   return (val == C_THUMBEXT
9502           || val == C_THUMBSTAT
9503           || val == C_THUMBEXTFUNC
9504           || val == C_THUMBSTATFUNC
9505           || val == C_THUMBLABEL);
9506 }
9507
9508 /* arm_coff_make_msymbol_special()
9509    arm_elf_make_msymbol_special()
9510    
9511    These functions test whether the COFF or ELF symbol corresponds to
9512    an address in thumb code, and set a "special" bit in a minimal
9513    symbol to indicate that it does.  */
9514    
9515 static void
9516 arm_elf_make_msymbol_special(asymbol *sym, struct minimal_symbol *msym)
9517 {
9518   if (ARM_SYM_BRANCH_TYPE (&((elf_symbol_type *)sym)->internal_elf_sym)
9519       == ST_BRANCH_TO_THUMB)
9520     MSYMBOL_SET_SPECIAL (msym);
9521 }
9522
9523 static void
9524 arm_coff_make_msymbol_special(int val, struct minimal_symbol *msym)
9525 {
9526   if (coff_sym_is_thumb (val))
9527     MSYMBOL_SET_SPECIAL (msym);
9528 }
9529
9530 static void
9531 arm_objfile_data_free (struct objfile *objfile, void *arg)
9532 {
9533   struct arm_per_objfile *data = arg;
9534   unsigned int i;
9535
9536   for (i = 0; i < objfile->obfd->section_count; i++)
9537     VEC_free (arm_mapping_symbol_s, data->section_maps[i]);
9538 }
9539
9540 static void
9541 arm_record_special_symbol (struct gdbarch *gdbarch, struct objfile *objfile,
9542                            asymbol *sym)
9543 {
9544   const char *name = bfd_asymbol_name (sym);
9545   struct arm_per_objfile *data;
9546   VEC(arm_mapping_symbol_s) **map_p;
9547   struct arm_mapping_symbol new_map_sym;
9548
9549   gdb_assert (name[0] == '$');
9550   if (name[1] != 'a' && name[1] != 't' && name[1] != 'd')
9551     return;
9552
9553   data = objfile_data (objfile, arm_objfile_data_key);
9554   if (data == NULL)
9555     {
9556       data = OBSTACK_ZALLOC (&objfile->objfile_obstack,
9557                              struct arm_per_objfile);
9558       set_objfile_data (objfile, arm_objfile_data_key, data);
9559       data->section_maps = OBSTACK_CALLOC (&objfile->objfile_obstack,
9560                                            objfile->obfd->section_count,
9561                                            VEC(arm_mapping_symbol_s) *);
9562     }
9563   map_p = &data->section_maps[bfd_get_section (sym)->index];
9564
9565   new_map_sym.value = sym->value;
9566   new_map_sym.type = name[1];
9567
9568   /* Assume that most mapping symbols appear in order of increasing
9569      value.  If they were randomly distributed, it would be faster to
9570      always push here and then sort at first use.  */
9571   if (!VEC_empty (arm_mapping_symbol_s, *map_p))
9572     {
9573       struct arm_mapping_symbol *prev_map_sym;
9574
9575       prev_map_sym = VEC_last (arm_mapping_symbol_s, *map_p);
9576       if (prev_map_sym->value >= sym->value)
9577         {
9578           unsigned int idx;
9579           idx = VEC_lower_bound (arm_mapping_symbol_s, *map_p, &new_map_sym,
9580                                  arm_compare_mapping_symbols);
9581           VEC_safe_insert (arm_mapping_symbol_s, *map_p, idx, &new_map_sym);
9582           return;
9583         }
9584     }
9585
9586   VEC_safe_push (arm_mapping_symbol_s, *map_p, &new_map_sym);
9587 }
9588
9589 static void
9590 arm_write_pc (struct regcache *regcache, CORE_ADDR pc)
9591 {
9592   struct gdbarch *gdbarch = get_regcache_arch (regcache);
9593   regcache_cooked_write_unsigned (regcache, ARM_PC_REGNUM, pc);
9594
9595   /* If necessary, set the T bit.  */
9596   if (arm_apcs_32)
9597     {
9598       ULONGEST val, t_bit;
9599       regcache_cooked_read_unsigned (regcache, ARM_PS_REGNUM, &val);
9600       t_bit = arm_psr_thumb_bit (gdbarch);
9601       if (arm_pc_is_thumb (gdbarch, pc))
9602         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
9603                                         val | t_bit);
9604       else
9605         regcache_cooked_write_unsigned (regcache, ARM_PS_REGNUM,
9606                                         val & ~t_bit);
9607     }
9608 }
9609
9610 /* Read the contents of a NEON quad register, by reading from two
9611    double registers.  This is used to implement the quad pseudo
9612    registers, and for argument passing in case the quad registers are
9613    missing; vectors are passed in quad registers when using the VFP
9614    ABI, even if a NEON unit is not present.  REGNUM is the index of
9615    the quad register, in [0, 15].  */
9616
9617 static enum register_status
9618 arm_neon_quad_read (struct gdbarch *gdbarch, struct regcache *regcache,
9619                     int regnum, gdb_byte *buf)
9620 {
9621   char name_buf[4];
9622   gdb_byte reg_buf[8];
9623   int offset, double_regnum;
9624   enum register_status status;
9625
9626   sprintf (name_buf, "d%d", regnum << 1);
9627   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9628                                                strlen (name_buf));
9629
9630   /* d0 is always the least significant half of q0.  */
9631   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9632     offset = 8;
9633   else
9634     offset = 0;
9635
9636   status = regcache_raw_read (regcache, double_regnum, reg_buf);
9637   if (status != REG_VALID)
9638     return status;
9639   memcpy (buf + offset, reg_buf, 8);
9640
9641   offset = 8 - offset;
9642   status = regcache_raw_read (regcache, double_regnum + 1, reg_buf);
9643   if (status != REG_VALID)
9644     return status;
9645   memcpy (buf + offset, reg_buf, 8);
9646
9647   return REG_VALID;
9648 }
9649
9650 static enum register_status
9651 arm_pseudo_read (struct gdbarch *gdbarch, struct regcache *regcache,
9652                  int regnum, gdb_byte *buf)
9653 {
9654   const int num_regs = gdbarch_num_regs (gdbarch);
9655   char name_buf[4];
9656   gdb_byte reg_buf[8];
9657   int offset, double_regnum;
9658
9659   gdb_assert (regnum >= num_regs);
9660   regnum -= num_regs;
9661
9662   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
9663     /* Quad-precision register.  */
9664     return arm_neon_quad_read (gdbarch, regcache, regnum - 32, buf);
9665   else
9666     {
9667       enum register_status status;
9668
9669       /* Single-precision register.  */
9670       gdb_assert (regnum < 32);
9671
9672       /* s0 is always the least significant half of d0.  */
9673       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9674         offset = (regnum & 1) ? 0 : 4;
9675       else
9676         offset = (regnum & 1) ? 4 : 0;
9677
9678       sprintf (name_buf, "d%d", regnum >> 1);
9679       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9680                                                    strlen (name_buf));
9681
9682       status = regcache_raw_read (regcache, double_regnum, reg_buf);
9683       if (status == REG_VALID)
9684         memcpy (buf, reg_buf + offset, 4);
9685       return status;
9686     }
9687 }
9688
9689 /* Store the contents of BUF to a NEON quad register, by writing to
9690    two double registers.  This is used to implement the quad pseudo
9691    registers, and for argument passing in case the quad registers are
9692    missing; vectors are passed in quad registers when using the VFP
9693    ABI, even if a NEON unit is not present.  REGNUM is the index
9694    of the quad register, in [0, 15].  */
9695
9696 static void
9697 arm_neon_quad_write (struct gdbarch *gdbarch, struct regcache *regcache,
9698                      int regnum, const gdb_byte *buf)
9699 {
9700   char name_buf[4];
9701   int offset, double_regnum;
9702
9703   sprintf (name_buf, "d%d", regnum << 1);
9704   double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9705                                                strlen (name_buf));
9706
9707   /* d0 is always the least significant half of q0.  */
9708   if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9709     offset = 8;
9710   else
9711     offset = 0;
9712
9713   regcache_raw_write (regcache, double_regnum, buf + offset);
9714   offset = 8 - offset;
9715   regcache_raw_write (regcache, double_regnum + 1, buf + offset);
9716 }
9717
9718 static void
9719 arm_pseudo_write (struct gdbarch *gdbarch, struct regcache *regcache,
9720                   int regnum, const gdb_byte *buf)
9721 {
9722   const int num_regs = gdbarch_num_regs (gdbarch);
9723   char name_buf[4];
9724   gdb_byte reg_buf[8];
9725   int offset, double_regnum;
9726
9727   gdb_assert (regnum >= num_regs);
9728   regnum -= num_regs;
9729
9730   if (gdbarch_tdep (gdbarch)->have_neon_pseudos && regnum >= 32 && regnum < 48)
9731     /* Quad-precision register.  */
9732     arm_neon_quad_write (gdbarch, regcache, regnum - 32, buf);
9733   else
9734     {
9735       /* Single-precision register.  */
9736       gdb_assert (regnum < 32);
9737
9738       /* s0 is always the least significant half of d0.  */
9739       if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG)
9740         offset = (regnum & 1) ? 0 : 4;
9741       else
9742         offset = (regnum & 1) ? 4 : 0;
9743
9744       sprintf (name_buf, "d%d", regnum >> 1);
9745       double_regnum = user_reg_map_name_to_regnum (gdbarch, name_buf,
9746                                                    strlen (name_buf));
9747
9748       regcache_raw_read (regcache, double_regnum, reg_buf);
9749       memcpy (reg_buf + offset, buf, 4);
9750       regcache_raw_write (regcache, double_regnum, reg_buf);
9751     }
9752 }
9753
9754 static struct value *
9755 value_of_arm_user_reg (struct frame_info *frame, const void *baton)
9756 {
9757   const int *reg_p = baton;
9758   return value_of_register (*reg_p, frame);
9759 }
9760 \f
9761 static enum gdb_osabi
9762 arm_elf_osabi_sniffer (bfd *abfd)
9763 {
9764   unsigned int elfosabi;
9765   enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
9766
9767   elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI];
9768
9769   if (elfosabi == ELFOSABI_ARM)
9770     /* GNU tools use this value.  Check note sections in this case,
9771        as well.  */
9772     bfd_map_over_sections (abfd,
9773                            generic_elf_osabi_sniff_abi_tag_sections, 
9774                            &osabi);
9775
9776   /* Anything else will be handled by the generic ELF sniffer.  */
9777   return osabi;
9778 }
9779
9780 static int
9781 arm_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
9782                           struct reggroup *group)
9783 {
9784   /* FPS register's type is INT, but belongs to float_reggroup.  Beside
9785      this, FPS register belongs to save_regroup, restore_reggroup, and
9786      all_reggroup, of course.  */
9787   if (regnum == ARM_FPS_REGNUM)
9788     return (group == float_reggroup
9789             || group == save_reggroup
9790             || group == restore_reggroup
9791             || group == all_reggroup);
9792   else
9793     return default_register_reggroup_p (gdbarch, regnum, group);
9794 }
9795
9796 \f
9797 /* For backward-compatibility we allow two 'g' packet lengths with
9798    the remote protocol depending on whether FPA registers are
9799    supplied.  M-profile targets do not have FPA registers, but some
9800    stubs already exist in the wild which use a 'g' packet which
9801    supplies them albeit with dummy values.  The packet format which
9802    includes FPA registers should be considered deprecated for
9803    M-profile targets.  */
9804
9805 static void
9806 arm_register_g_packet_guesses (struct gdbarch *gdbarch)
9807 {
9808   if (gdbarch_tdep (gdbarch)->is_m)
9809     {
9810       /* If we know from the executable this is an M-profile target,
9811          cater for remote targets whose register set layout is the
9812          same as the FPA layout.  */
9813       register_remote_g_packet_guess (gdbarch,
9814                                       /* r0-r12,sp,lr,pc; f0-f7; fps,xpsr */
9815                                       (16 * INT_REGISTER_SIZE)
9816                                       + (8 * FP_REGISTER_SIZE)
9817                                       + (2 * INT_REGISTER_SIZE),
9818                                       tdesc_arm_with_m_fpa_layout);
9819
9820       /* The regular M-profile layout.  */
9821       register_remote_g_packet_guess (gdbarch,
9822                                       /* r0-r12,sp,lr,pc; xpsr */
9823                                       (16 * INT_REGISTER_SIZE)
9824                                       + INT_REGISTER_SIZE,
9825                                       tdesc_arm_with_m);
9826
9827       /* M-profile plus M4F VFP.  */
9828       register_remote_g_packet_guess (gdbarch,
9829                                       /* r0-r12,sp,lr,pc; d0-d15; fpscr,xpsr */
9830                                       (16 * INT_REGISTER_SIZE)
9831                                       + (16 * VFP_REGISTER_SIZE)
9832                                       + (2 * INT_REGISTER_SIZE),
9833                                       tdesc_arm_with_m_vfp_d16);
9834     }
9835
9836   /* Otherwise we don't have a useful guess.  */
9837 }
9838
9839 \f
9840 /* Initialize the current architecture based on INFO.  If possible,
9841    re-use an architecture from ARCHES, which is a list of
9842    architectures already created during this debugging session.
9843
9844    Called e.g. at program startup, when reading a core file, and when
9845    reading a binary file.  */
9846
9847 static struct gdbarch *
9848 arm_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
9849 {
9850   struct gdbarch_tdep *tdep;
9851   struct gdbarch *gdbarch;
9852   struct gdbarch_list *best_arch;
9853   enum arm_abi_kind arm_abi = arm_abi_global;
9854   enum arm_float_model fp_model = arm_fp_model;
9855   struct tdesc_arch_data *tdesc_data = NULL;
9856   int i, is_m = 0;
9857   int have_vfp_registers = 0, have_vfp_pseudos = 0, have_neon_pseudos = 0;
9858   int have_neon = 0;
9859   int have_fpa_registers = 1;
9860   const struct target_desc *tdesc = info.target_desc;
9861
9862   /* If we have an object to base this architecture on, try to determine
9863      its ABI.  */
9864
9865   if (arm_abi == ARM_ABI_AUTO && info.abfd != NULL)
9866     {
9867       int ei_osabi, e_flags;
9868
9869       switch (bfd_get_flavour (info.abfd))
9870         {
9871         case bfd_target_aout_flavour:
9872           /* Assume it's an old APCS-style ABI.  */
9873           arm_abi = ARM_ABI_APCS;
9874           break;
9875
9876         case bfd_target_coff_flavour:
9877           /* Assume it's an old APCS-style ABI.  */
9878           /* XXX WinCE?  */
9879           arm_abi = ARM_ABI_APCS;
9880           break;
9881
9882         case bfd_target_elf_flavour:
9883           ei_osabi = elf_elfheader (info.abfd)->e_ident[EI_OSABI];
9884           e_flags = elf_elfheader (info.abfd)->e_flags;
9885
9886           if (ei_osabi == ELFOSABI_ARM)
9887             {
9888               /* GNU tools used to use this value, but do not for EABI
9889                  objects.  There's nowhere to tag an EABI version
9890                  anyway, so assume APCS.  */
9891               arm_abi = ARM_ABI_APCS;
9892             }
9893           else if (ei_osabi == ELFOSABI_NONE)
9894             {
9895               int eabi_ver = EF_ARM_EABI_VERSION (e_flags);
9896               int attr_arch, attr_profile;
9897
9898               switch (eabi_ver)
9899                 {
9900                 case EF_ARM_EABI_UNKNOWN:
9901                   /* Assume GNU tools.  */
9902                   arm_abi = ARM_ABI_APCS;
9903                   break;
9904
9905                 case EF_ARM_EABI_VER4:
9906                 case EF_ARM_EABI_VER5:
9907                   arm_abi = ARM_ABI_AAPCS;
9908                   /* EABI binaries default to VFP float ordering.
9909                      They may also contain build attributes that can
9910                      be used to identify if the VFP argument-passing
9911                      ABI is in use.  */
9912                   if (fp_model == ARM_FLOAT_AUTO)
9913                     {
9914 #ifdef HAVE_ELF
9915                       switch (bfd_elf_get_obj_attr_int (info.abfd,
9916                                                         OBJ_ATTR_PROC,
9917                                                         Tag_ABI_VFP_args))
9918                         {
9919                         case 0:
9920                           /* "The user intended FP parameter/result
9921                              passing to conform to AAPCS, base
9922                              variant".  */
9923                           fp_model = ARM_FLOAT_SOFT_VFP;
9924                           break;
9925                         case 1:
9926                           /* "The user intended FP parameter/result
9927                              passing to conform to AAPCS, VFP
9928                              variant".  */
9929                           fp_model = ARM_FLOAT_VFP;
9930                           break;
9931                         case 2:
9932                           /* "The user intended FP parameter/result
9933                              passing to conform to tool chain-specific
9934                              conventions" - we don't know any such
9935                              conventions, so leave it as "auto".  */
9936                           break;
9937                         default:
9938                           /* Attribute value not mentioned in the
9939                              October 2008 ABI, so leave it as
9940                              "auto".  */
9941                           break;
9942                         }
9943 #else
9944                       fp_model = ARM_FLOAT_SOFT_VFP;
9945 #endif
9946                     }
9947                   break;
9948
9949                 default:
9950                   /* Leave it as "auto".  */
9951                   warning (_("unknown ARM EABI version 0x%x"), eabi_ver);
9952                   break;
9953                 }
9954
9955 #ifdef HAVE_ELF
9956               /* Detect M-profile programs.  This only works if the
9957                  executable file includes build attributes; GCC does
9958                  copy them to the executable, but e.g. RealView does
9959                  not.  */
9960               attr_arch = bfd_elf_get_obj_attr_int (info.abfd, OBJ_ATTR_PROC,
9961                                                     Tag_CPU_arch);
9962               attr_profile = bfd_elf_get_obj_attr_int (info.abfd,
9963                                                        OBJ_ATTR_PROC,
9964                                                        Tag_CPU_arch_profile);
9965               /* GCC specifies the profile for v6-M; RealView only
9966                  specifies the profile for architectures starting with
9967                  V7 (as opposed to architectures with a tag
9968                  numerically greater than TAG_CPU_ARCH_V7).  */
9969               if (!tdesc_has_registers (tdesc)
9970                   && (attr_arch == TAG_CPU_ARCH_V6_M
9971                       || attr_arch == TAG_CPU_ARCH_V6S_M
9972                       || attr_profile == 'M'))
9973                 is_m = 1;
9974 #endif
9975             }
9976
9977           if (fp_model == ARM_FLOAT_AUTO)
9978             {
9979               int e_flags = elf_elfheader (info.abfd)->e_flags;
9980
9981               switch (e_flags & (EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT))
9982                 {
9983                 case 0:
9984                   /* Leave it as "auto".  Strictly speaking this case
9985                      means FPA, but almost nobody uses that now, and
9986                      many toolchains fail to set the appropriate bits
9987                      for the floating-point model they use.  */
9988                   break;
9989                 case EF_ARM_SOFT_FLOAT:
9990                   fp_model = ARM_FLOAT_SOFT_FPA;
9991                   break;
9992                 case EF_ARM_VFP_FLOAT:
9993                   fp_model = ARM_FLOAT_VFP;
9994                   break;
9995                 case EF_ARM_SOFT_FLOAT | EF_ARM_VFP_FLOAT:
9996                   fp_model = ARM_FLOAT_SOFT_VFP;
9997                   break;
9998                 }
9999             }
10000
10001           if (e_flags & EF_ARM_BE8)
10002             info.byte_order_for_code = BFD_ENDIAN_LITTLE;
10003
10004           break;
10005
10006         default:
10007           /* Leave it as "auto".  */
10008           break;
10009         }
10010     }
10011
10012   /* Check any target description for validity.  */
10013   if (tdesc_has_registers (tdesc))
10014     {
10015       /* For most registers we require GDB's default names; but also allow
10016          the numeric names for sp / lr / pc, as a convenience.  */
10017       static const char *const arm_sp_names[] = { "r13", "sp", NULL };
10018       static const char *const arm_lr_names[] = { "r14", "lr", NULL };
10019       static const char *const arm_pc_names[] = { "r15", "pc", NULL };
10020
10021       const struct tdesc_feature *feature;
10022       int valid_p;
10023
10024       feature = tdesc_find_feature (tdesc,
10025                                     "org.gnu.gdb.arm.core");
10026       if (feature == NULL)
10027         {
10028           feature = tdesc_find_feature (tdesc,
10029                                         "org.gnu.gdb.arm.m-profile");
10030           if (feature == NULL)
10031             return NULL;
10032           else
10033             is_m = 1;
10034         }
10035
10036       tdesc_data = tdesc_data_alloc ();
10037
10038       valid_p = 1;
10039       for (i = 0; i < ARM_SP_REGNUM; i++)
10040         valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
10041                                             arm_register_names[i]);
10042       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10043                                                   ARM_SP_REGNUM,
10044                                                   arm_sp_names);
10045       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10046                                                   ARM_LR_REGNUM,
10047                                                   arm_lr_names);
10048       valid_p &= tdesc_numbered_register_choices (feature, tdesc_data,
10049                                                   ARM_PC_REGNUM,
10050                                                   arm_pc_names);
10051       if (is_m)
10052         valid_p &= tdesc_numbered_register (feature, tdesc_data,
10053                                             ARM_PS_REGNUM, "xpsr");
10054       else
10055         valid_p &= tdesc_numbered_register (feature, tdesc_data,
10056                                             ARM_PS_REGNUM, "cpsr");
10057
10058       if (!valid_p)
10059         {
10060           tdesc_data_cleanup (tdesc_data);
10061           return NULL;
10062         }
10063
10064       feature = tdesc_find_feature (tdesc,
10065                                     "org.gnu.gdb.arm.fpa");
10066       if (feature != NULL)
10067         {
10068           valid_p = 1;
10069           for (i = ARM_F0_REGNUM; i <= ARM_FPS_REGNUM; i++)
10070             valid_p &= tdesc_numbered_register (feature, tdesc_data, i,
10071                                                 arm_register_names[i]);
10072           if (!valid_p)
10073             {
10074               tdesc_data_cleanup (tdesc_data);
10075               return NULL;
10076             }
10077         }
10078       else
10079         have_fpa_registers = 0;
10080
10081       feature = tdesc_find_feature (tdesc,
10082                                     "org.gnu.gdb.xscale.iwmmxt");
10083       if (feature != NULL)
10084         {
10085           static const char *const iwmmxt_names[] = {
10086             "wR0", "wR1", "wR2", "wR3", "wR4", "wR5", "wR6", "wR7",
10087             "wR8", "wR9", "wR10", "wR11", "wR12", "wR13", "wR14", "wR15",
10088             "wCID", "wCon", "wCSSF", "wCASF", "", "", "", "",
10089             "wCGR0", "wCGR1", "wCGR2", "wCGR3", "", "", "", "",
10090           };
10091
10092           valid_p = 1;
10093           for (i = ARM_WR0_REGNUM; i <= ARM_WR15_REGNUM; i++)
10094             valid_p
10095               &= tdesc_numbered_register (feature, tdesc_data, i,
10096                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
10097
10098           /* Check for the control registers, but do not fail if they
10099              are missing.  */
10100           for (i = ARM_WC0_REGNUM; i <= ARM_WCASF_REGNUM; i++)
10101             tdesc_numbered_register (feature, tdesc_data, i,
10102                                      iwmmxt_names[i - ARM_WR0_REGNUM]);
10103
10104           for (i = ARM_WCGR0_REGNUM; i <= ARM_WCGR3_REGNUM; i++)
10105             valid_p
10106               &= tdesc_numbered_register (feature, tdesc_data, i,
10107                                           iwmmxt_names[i - ARM_WR0_REGNUM]);
10108
10109           if (!valid_p)
10110             {
10111               tdesc_data_cleanup (tdesc_data);
10112               return NULL;
10113             }
10114         }
10115
10116       /* If we have a VFP unit, check whether the single precision registers
10117          are present.  If not, then we will synthesize them as pseudo
10118          registers.  */
10119       feature = tdesc_find_feature (tdesc,
10120                                     "org.gnu.gdb.arm.vfp");
10121       if (feature != NULL)
10122         {
10123           static const char *const vfp_double_names[] = {
10124             "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
10125             "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
10126             "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
10127             "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
10128           };
10129
10130           /* Require the double precision registers.  There must be either
10131              16 or 32.  */
10132           valid_p = 1;
10133           for (i = 0; i < 32; i++)
10134             {
10135               valid_p &= tdesc_numbered_register (feature, tdesc_data,
10136                                                   ARM_D0_REGNUM + i,
10137                                                   vfp_double_names[i]);
10138               if (!valid_p)
10139                 break;
10140             }
10141           if (!valid_p && i == 16)
10142             valid_p = 1;
10143
10144           /* Also require FPSCR.  */
10145           valid_p &= tdesc_numbered_register (feature, tdesc_data,
10146                                               ARM_FPSCR_REGNUM, "fpscr");
10147           if (!valid_p)
10148             {
10149               tdesc_data_cleanup (tdesc_data);
10150               return NULL;
10151             }
10152
10153           if (tdesc_unnumbered_register (feature, "s0") == 0)
10154             have_vfp_pseudos = 1;
10155
10156           have_vfp_registers = 1;
10157
10158           /* If we have VFP, also check for NEON.  The architecture allows
10159              NEON without VFP (integer vector operations only), but GDB
10160              does not support that.  */
10161           feature = tdesc_find_feature (tdesc,
10162                                         "org.gnu.gdb.arm.neon");
10163           if (feature != NULL)
10164             {
10165               /* NEON requires 32 double-precision registers.  */
10166               if (i != 32)
10167                 {
10168                   tdesc_data_cleanup (tdesc_data);
10169                   return NULL;
10170                 }
10171
10172               /* If there are quad registers defined by the stub, use
10173                  their type; otherwise (normally) provide them with
10174                  the default type.  */
10175               if (tdesc_unnumbered_register (feature, "q0") == 0)
10176                 have_neon_pseudos = 1;
10177
10178               have_neon = 1;
10179             }
10180         }
10181     }
10182
10183   /* If there is already a candidate, use it.  */
10184   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
10185        best_arch != NULL;
10186        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
10187     {
10188       if (arm_abi != ARM_ABI_AUTO
10189           && arm_abi != gdbarch_tdep (best_arch->gdbarch)->arm_abi)
10190         continue;
10191
10192       if (fp_model != ARM_FLOAT_AUTO
10193           && fp_model != gdbarch_tdep (best_arch->gdbarch)->fp_model)
10194         continue;
10195
10196       /* There are various other properties in tdep that we do not
10197          need to check here: those derived from a target description,
10198          since gdbarches with a different target description are
10199          automatically disqualified.  */
10200
10201       /* Do check is_m, though, since it might come from the binary.  */
10202       if (is_m != gdbarch_tdep (best_arch->gdbarch)->is_m)
10203         continue;
10204
10205       /* Found a match.  */
10206       break;
10207     }
10208
10209   if (best_arch != NULL)
10210     {
10211       if (tdesc_data != NULL)
10212         tdesc_data_cleanup (tdesc_data);
10213       return best_arch->gdbarch;
10214     }
10215
10216   tdep = xcalloc (1, sizeof (struct gdbarch_tdep));
10217   gdbarch = gdbarch_alloc (&info, tdep);
10218
10219   /* Record additional information about the architecture we are defining.
10220      These are gdbarch discriminators, like the OSABI.  */
10221   tdep->arm_abi = arm_abi;
10222   tdep->fp_model = fp_model;
10223   tdep->is_m = is_m;
10224   tdep->have_fpa_registers = have_fpa_registers;
10225   tdep->have_vfp_registers = have_vfp_registers;
10226   tdep->have_vfp_pseudos = have_vfp_pseudos;
10227   tdep->have_neon_pseudos = have_neon_pseudos;
10228   tdep->have_neon = have_neon;
10229
10230   arm_register_g_packet_guesses (gdbarch);
10231
10232   /* Breakpoints.  */
10233   switch (info.byte_order_for_code)
10234     {
10235     case BFD_ENDIAN_BIG:
10236       tdep->arm_breakpoint = arm_default_arm_be_breakpoint;
10237       tdep->arm_breakpoint_size = sizeof (arm_default_arm_be_breakpoint);
10238       tdep->thumb_breakpoint = arm_default_thumb_be_breakpoint;
10239       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_be_breakpoint);
10240
10241       break;
10242
10243     case BFD_ENDIAN_LITTLE:
10244       tdep->arm_breakpoint = arm_default_arm_le_breakpoint;
10245       tdep->arm_breakpoint_size = sizeof (arm_default_arm_le_breakpoint);
10246       tdep->thumb_breakpoint = arm_default_thumb_le_breakpoint;
10247       tdep->thumb_breakpoint_size = sizeof (arm_default_thumb_le_breakpoint);
10248
10249       break;
10250
10251     default:
10252       internal_error (__FILE__, __LINE__,
10253                       _("arm_gdbarch_init: bad byte order for float format"));
10254     }
10255
10256   /* On ARM targets char defaults to unsigned.  */
10257   set_gdbarch_char_signed (gdbarch, 0);
10258
10259   /* Note: for displaced stepping, this includes the breakpoint, and one word
10260      of additional scratch space.  This setting isn't used for anything beside
10261      displaced stepping at present.  */
10262   set_gdbarch_max_insn_length (gdbarch, 4 * DISPLACED_MODIFIED_INSNS);
10263
10264   /* This should be low enough for everything.  */
10265   tdep->lowest_pc = 0x20;
10266   tdep->jb_pc = -1;     /* Longjump support not enabled by default.  */
10267
10268   /* The default, for both APCS and AAPCS, is to return small
10269      structures in registers.  */
10270   tdep->struct_return = reg_struct_return;
10271
10272   set_gdbarch_push_dummy_call (gdbarch, arm_push_dummy_call);
10273   set_gdbarch_frame_align (gdbarch, arm_frame_align);
10274
10275   set_gdbarch_write_pc (gdbarch, arm_write_pc);
10276
10277   /* Frame handling.  */
10278   set_gdbarch_dummy_id (gdbarch, arm_dummy_id);
10279   set_gdbarch_unwind_pc (gdbarch, arm_unwind_pc);
10280   set_gdbarch_unwind_sp (gdbarch, arm_unwind_sp);
10281
10282   frame_base_set_default (gdbarch, &arm_normal_base);
10283
10284   /* Address manipulation.  */
10285   set_gdbarch_smash_text_address (gdbarch, arm_smash_text_address);
10286   set_gdbarch_addr_bits_remove (gdbarch, arm_addr_bits_remove);
10287
10288   /* Advance PC across function entry code.  */
10289   set_gdbarch_skip_prologue (gdbarch, arm_skip_prologue);
10290
10291   /* Detect whether PC is in function epilogue.  */
10292   set_gdbarch_in_function_epilogue_p (gdbarch, arm_in_function_epilogue_p);
10293
10294   /* Skip trampolines.  */
10295   set_gdbarch_skip_trampoline_code (gdbarch, arm_skip_stub);
10296
10297   /* The stack grows downward.  */
10298   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
10299
10300   /* Breakpoint manipulation.  */
10301   set_gdbarch_breakpoint_from_pc (gdbarch, arm_breakpoint_from_pc);
10302   set_gdbarch_remote_breakpoint_from_pc (gdbarch,
10303                                          arm_remote_breakpoint_from_pc);
10304
10305   /* Information about registers, etc.  */
10306   set_gdbarch_sp_regnum (gdbarch, ARM_SP_REGNUM);
10307   set_gdbarch_pc_regnum (gdbarch, ARM_PC_REGNUM);
10308   set_gdbarch_num_regs (gdbarch, ARM_NUM_REGS);
10309   set_gdbarch_register_type (gdbarch, arm_register_type);
10310   set_gdbarch_register_reggroup_p (gdbarch, arm_register_reggroup_p);
10311
10312   /* This "info float" is FPA-specific.  Use the generic version if we
10313      do not have FPA.  */
10314   if (gdbarch_tdep (gdbarch)->have_fpa_registers)
10315     set_gdbarch_print_float_info (gdbarch, arm_print_float_info);
10316
10317   /* Internal <-> external register number maps.  */
10318   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, arm_dwarf_reg_to_regnum);
10319   set_gdbarch_register_sim_regno (gdbarch, arm_register_sim_regno);
10320
10321   set_gdbarch_register_name (gdbarch, arm_register_name);
10322
10323   /* Returning results.  */
10324   set_gdbarch_return_value (gdbarch, arm_return_value);
10325
10326   /* Disassembly.  */
10327   set_gdbarch_print_insn (gdbarch, gdb_print_insn_arm);
10328
10329   /* Minsymbol frobbing.  */
10330   set_gdbarch_elf_make_msymbol_special (gdbarch, arm_elf_make_msymbol_special);
10331   set_gdbarch_coff_make_msymbol_special (gdbarch,
10332                                          arm_coff_make_msymbol_special);
10333   set_gdbarch_record_special_symbol (gdbarch, arm_record_special_symbol);
10334
10335   /* Thumb-2 IT block support.  */
10336   set_gdbarch_adjust_breakpoint_address (gdbarch,
10337                                          arm_adjust_breakpoint_address);
10338
10339   /* Virtual tables.  */
10340   set_gdbarch_vbit_in_delta (gdbarch, 1);
10341
10342   /* Hook in the ABI-specific overrides, if they have been registered.  */
10343   gdbarch_init_osabi (info, gdbarch);
10344
10345   dwarf2_frame_set_init_reg (gdbarch, arm_dwarf2_frame_init_reg);
10346
10347   /* Add some default predicates.  */
10348   if (is_m)
10349     frame_unwind_append_unwinder (gdbarch, &arm_m_exception_unwind);
10350   frame_unwind_append_unwinder (gdbarch, &arm_stub_unwind);
10351   dwarf2_append_unwinders (gdbarch);
10352   frame_unwind_append_unwinder (gdbarch, &arm_exidx_unwind);
10353   frame_unwind_append_unwinder (gdbarch, &arm_prologue_unwind);
10354
10355   /* Now we have tuned the configuration, set a few final things,
10356      based on what the OS ABI has told us.  */
10357
10358   /* If the ABI is not otherwise marked, assume the old GNU APCS.  EABI
10359      binaries are always marked.  */
10360   if (tdep->arm_abi == ARM_ABI_AUTO)
10361     tdep->arm_abi = ARM_ABI_APCS;
10362
10363   /* Watchpoints are not steppable.  */
10364   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
10365
10366   /* We used to default to FPA for generic ARM, but almost nobody
10367      uses that now, and we now provide a way for the user to force
10368      the model.  So default to the most useful variant.  */
10369   if (tdep->fp_model == ARM_FLOAT_AUTO)
10370     tdep->fp_model = ARM_FLOAT_SOFT_FPA;
10371
10372   if (tdep->jb_pc >= 0)
10373     set_gdbarch_get_longjmp_target (gdbarch, arm_get_longjmp_target);
10374
10375   /* Floating point sizes and format.  */
10376   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
10377   if (tdep->fp_model == ARM_FLOAT_SOFT_FPA || tdep->fp_model == ARM_FLOAT_FPA)
10378     {
10379       set_gdbarch_double_format
10380         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
10381       set_gdbarch_long_double_format
10382         (gdbarch, floatformats_ieee_double_littlebyte_bigword);
10383     }
10384   else
10385     {
10386       set_gdbarch_double_format (gdbarch, floatformats_ieee_double);
10387       set_gdbarch_long_double_format (gdbarch, floatformats_ieee_double);
10388     }
10389
10390   if (have_vfp_pseudos)
10391     {
10392       /* NOTE: These are the only pseudo registers used by
10393          the ARM target at the moment.  If more are added, a
10394          little more care in numbering will be needed.  */
10395
10396       int num_pseudos = 32;
10397       if (have_neon_pseudos)
10398         num_pseudos += 16;
10399       set_gdbarch_num_pseudo_regs (gdbarch, num_pseudos);
10400       set_gdbarch_pseudo_register_read (gdbarch, arm_pseudo_read);
10401       set_gdbarch_pseudo_register_write (gdbarch, arm_pseudo_write);
10402     }
10403
10404   if (tdesc_data)
10405     {
10406       set_tdesc_pseudo_register_name (gdbarch, arm_register_name);
10407
10408       tdesc_use_registers (gdbarch, tdesc, tdesc_data);
10409
10410       /* Override tdesc_register_type to adjust the types of VFP
10411          registers for NEON.  */
10412       set_gdbarch_register_type (gdbarch, arm_register_type);
10413     }
10414
10415   /* Add standard register aliases.  We add aliases even for those
10416      nanes which are used by the current architecture - it's simpler,
10417      and does no harm, since nothing ever lists user registers.  */
10418   for (i = 0; i < ARRAY_SIZE (arm_register_aliases); i++)
10419     user_reg_add (gdbarch, arm_register_aliases[i].name,
10420                   value_of_arm_user_reg, &arm_register_aliases[i].regnum);
10421
10422   return gdbarch;
10423 }
10424
10425 static void
10426 arm_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
10427 {
10428   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
10429
10430   if (tdep == NULL)
10431     return;
10432
10433   fprintf_unfiltered (file, _("arm_dump_tdep: Lowest pc = 0x%lx"),
10434                       (unsigned long) tdep->lowest_pc);
10435 }
10436
10437 extern initialize_file_ftype _initialize_arm_tdep; /* -Wmissing-prototypes */
10438
10439 void
10440 _initialize_arm_tdep (void)
10441 {
10442   struct ui_file *stb;
10443   long length;
10444   struct cmd_list_element *new_set, *new_show;
10445   const char *setname;
10446   const char *setdesc;
10447   const char *const *regnames;
10448   int numregs, i, j;
10449   static char *helptext;
10450   char regdesc[1024], *rdptr = regdesc;
10451   size_t rest = sizeof (regdesc);
10452
10453   gdbarch_register (bfd_arch_arm, arm_gdbarch_init, arm_dump_tdep);
10454
10455   arm_objfile_data_key
10456     = register_objfile_data_with_cleanup (NULL, arm_objfile_data_free);
10457
10458   /* Add ourselves to objfile event chain.  */
10459   observer_attach_new_objfile (arm_exidx_new_objfile);
10460   arm_exidx_data_key
10461     = register_objfile_data_with_cleanup (NULL, arm_exidx_data_free);
10462
10463   /* Register an ELF OS ABI sniffer for ARM binaries.  */
10464   gdbarch_register_osabi_sniffer (bfd_arch_arm,
10465                                   bfd_target_elf_flavour,
10466                                   arm_elf_osabi_sniffer);
10467
10468   /* Initialize the standard target descriptions.  */
10469   initialize_tdesc_arm_with_m ();
10470   initialize_tdesc_arm_with_m_fpa_layout ();
10471   initialize_tdesc_arm_with_m_vfp_d16 ();
10472   initialize_tdesc_arm_with_iwmmxt ();
10473   initialize_tdesc_arm_with_vfpv2 ();
10474   initialize_tdesc_arm_with_vfpv3 ();
10475   initialize_tdesc_arm_with_neon ();
10476
10477   /* Get the number of possible sets of register names defined in opcodes.  */
10478   num_disassembly_options = get_arm_regname_num_options ();
10479
10480   /* Add root prefix command for all "set arm"/"show arm" commands.  */
10481   add_prefix_cmd ("arm", no_class, set_arm_command,
10482                   _("Various ARM-specific commands."),
10483                   &setarmcmdlist, "set arm ", 0, &setlist);
10484
10485   add_prefix_cmd ("arm", no_class, show_arm_command,
10486                   _("Various ARM-specific commands."),
10487                   &showarmcmdlist, "show arm ", 0, &showlist);
10488
10489   /* Sync the opcode insn printer with our register viewer.  */
10490   parse_arm_disassembler_option ("reg-names-std");
10491
10492   /* Initialize the array that will be passed to
10493      add_setshow_enum_cmd().  */
10494   valid_disassembly_styles
10495     = xmalloc ((num_disassembly_options + 1) * sizeof (char *));
10496   for (i = 0; i < num_disassembly_options; i++)
10497     {
10498       numregs = get_arm_regnames (i, &setname, &setdesc, &regnames);
10499       valid_disassembly_styles[i] = setname;
10500       length = snprintf (rdptr, rest, "%s - %s\n", setname, setdesc);
10501       rdptr += length;
10502       rest -= length;
10503       /* When we find the default names, tell the disassembler to use
10504          them.  */
10505       if (!strcmp (setname, "std"))
10506         {
10507           disassembly_style = setname;
10508           set_arm_regname_option (i);
10509         }
10510     }
10511   /* Mark the end of valid options.  */
10512   valid_disassembly_styles[num_disassembly_options] = NULL;
10513
10514   /* Create the help text.  */
10515   stb = mem_fileopen ();
10516   fprintf_unfiltered (stb, "%s%s%s",
10517                       _("The valid values are:\n"),
10518                       regdesc,
10519                       _("The default is \"std\"."));
10520   helptext = ui_file_xstrdup (stb, NULL);
10521   ui_file_delete (stb);
10522
10523   add_setshow_enum_cmd("disassembler", no_class,
10524                        valid_disassembly_styles, &disassembly_style,
10525                        _("Set the disassembly style."),
10526                        _("Show the disassembly style."),
10527                        helptext,
10528                        set_disassembly_style_sfunc,
10529                        NULL, /* FIXME: i18n: The disassembly style is
10530                                 \"%s\".  */
10531                        &setarmcmdlist, &showarmcmdlist);
10532
10533   add_setshow_boolean_cmd ("apcs32", no_class, &arm_apcs_32,
10534                            _("Set usage of ARM 32-bit mode."),
10535                            _("Show usage of ARM 32-bit mode."),
10536                            _("When off, a 26-bit PC will be used."),
10537                            NULL,
10538                            NULL, /* FIXME: i18n: Usage of ARM 32-bit
10539                                     mode is %s.  */
10540                            &setarmcmdlist, &showarmcmdlist);
10541
10542   /* Add a command to allow the user to force the FPU model.  */
10543   add_setshow_enum_cmd ("fpu", no_class, fp_model_strings, &current_fp_model,
10544                         _("Set the floating point type."),
10545                         _("Show the floating point type."),
10546                         _("auto - Determine the FP typefrom the OS-ABI.\n\
10547 softfpa - Software FP, mixed-endian doubles on little-endian ARMs.\n\
10548 fpa - FPA co-processor (GCC compiled).\n\
10549 softvfp - Software FP with pure-endian doubles.\n\
10550 vfp - VFP co-processor."),
10551                         set_fp_model_sfunc, show_fp_model,
10552                         &setarmcmdlist, &showarmcmdlist);
10553
10554   /* Add a command to allow the user to force the ABI.  */
10555   add_setshow_enum_cmd ("abi", class_support, arm_abi_strings, &arm_abi_string,
10556                         _("Set the ABI."),
10557                         _("Show the ABI."),
10558                         NULL, arm_set_abi, arm_show_abi,
10559                         &setarmcmdlist, &showarmcmdlist);
10560
10561   /* Add two commands to allow the user to force the assumed
10562      execution mode.  */
10563   add_setshow_enum_cmd ("fallback-mode", class_support,
10564                         arm_mode_strings, &arm_fallback_mode_string,
10565                         _("Set the mode assumed when symbols are unavailable."),
10566                         _("Show the mode assumed when symbols are unavailable."),
10567                         NULL, NULL, arm_show_fallback_mode,
10568                         &setarmcmdlist, &showarmcmdlist);
10569   add_setshow_enum_cmd ("force-mode", class_support,
10570                         arm_mode_strings, &arm_force_mode_string,
10571                         _("Set the mode assumed even when symbols are available."),
10572                         _("Show the mode assumed even when symbols are available."),
10573                         NULL, NULL, arm_show_force_mode,
10574                         &setarmcmdlist, &showarmcmdlist);
10575
10576   /* Debugging flag.  */
10577   add_setshow_boolean_cmd ("arm", class_maintenance, &arm_debug,
10578                            _("Set ARM debugging."),
10579                            _("Show ARM debugging."),
10580                            _("When on, arm-specific debugging is enabled."),
10581                            NULL,
10582                            NULL, /* FIXME: i18n: "ARM debugging is %s.  */
10583                            &setdebuglist, &showdebuglist);
10584 }
10585
10586 /* ARM-reversible process record data structures.  */
10587
10588 #define ARM_INSN_SIZE_BYTES 4    
10589 #define THUMB_INSN_SIZE_BYTES 2
10590 #define THUMB2_INSN_SIZE_BYTES 4
10591
10592
10593 #define INSN_S_L_BIT_NUM 20
10594
10595 #define REG_ALLOC(REGS, LENGTH, RECORD_BUF) \
10596         do  \
10597           { \
10598             unsigned int reg_len = LENGTH; \
10599             if (reg_len) \
10600               { \
10601                 REGS = XNEWVEC (uint32_t, reg_len); \
10602                 memcpy(&REGS[0], &RECORD_BUF[0], sizeof(uint32_t)*LENGTH); \
10603               } \
10604           } \
10605         while (0)
10606
10607 #define MEM_ALLOC(MEMS, LENGTH, RECORD_BUF) \
10608         do  \
10609           { \
10610             unsigned int mem_len = LENGTH; \
10611             if (mem_len) \
10612             { \
10613               MEMS =  XNEWVEC (struct arm_mem_r, mem_len);  \
10614               memcpy(&MEMS->len, &RECORD_BUF[0], \
10615                      sizeof(struct arm_mem_r) * LENGTH); \
10616             } \
10617           } \
10618           while (0)
10619
10620 /* Checks whether insn is already recorded or yet to be decoded. (boolean expression).  */
10621 #define INSN_RECORDED(ARM_RECORD) \
10622         (0 != (ARM_RECORD)->reg_rec_count || 0 != (ARM_RECORD)->mem_rec_count)
10623
10624 /* ARM memory record structure.  */
10625 struct arm_mem_r
10626 {
10627   uint32_t len;    /* Record length.  */
10628   CORE_ADDR addr;  /* Memory address.  */
10629 };
10630
10631 /* ARM instruction record contains opcode of current insn
10632    and execution state (before entry to decode_insn()),
10633    contains list of to-be-modified registers and
10634    memory blocks (on return from decode_insn()).  */
10635
10636 typedef struct insn_decode_record_t
10637 {
10638   struct gdbarch *gdbarch;
10639   struct regcache *regcache;
10640   CORE_ADDR this_addr;          /* Address of the insn being decoded.  */
10641   uint32_t arm_insn;            /* Should accommodate thumb.  */
10642   uint32_t cond;                /* Condition code.  */
10643   uint32_t opcode;              /* Insn opcode.  */
10644   uint32_t decode;              /* Insn decode bits.  */
10645   uint32_t mem_rec_count;       /* No of mem records.  */
10646   uint32_t reg_rec_count;       /* No of reg records.  */
10647   uint32_t *arm_regs;           /* Registers to be saved for this record.  */
10648   struct arm_mem_r *arm_mems;   /* Memory to be saved for this record.  */
10649 } insn_decode_record;
10650
10651
10652 /* Checks ARM SBZ and SBO mandatory fields.  */
10653
10654 static int
10655 sbo_sbz (uint32_t insn, uint32_t bit_num, uint32_t len, uint32_t sbo)
10656 {
10657   uint32_t ones = bits (insn, bit_num - 1, (bit_num -1) + (len - 1));
10658
10659   if (!len)
10660     return 1;
10661
10662   if (!sbo)
10663     ones = ~ones;
10664
10665   while (ones)
10666     {
10667       if (!(ones & sbo))
10668         {
10669           return 0;
10670         }
10671       ones = ones >> 1;
10672     }
10673   return 1;
10674 }
10675
10676 typedef enum
10677 {
10678   ARM_RECORD_STRH=1,
10679   ARM_RECORD_STRD
10680 } arm_record_strx_t;
10681
10682 typedef enum
10683 {
10684   ARM_RECORD=1,
10685   THUMB_RECORD,
10686   THUMB2_RECORD
10687 } record_type_t;
10688
10689
10690 static int
10691 arm_record_strx (insn_decode_record *arm_insn_r, uint32_t *record_buf, 
10692                  uint32_t *record_buf_mem, arm_record_strx_t str_type)
10693 {
10694
10695   struct regcache *reg_cache = arm_insn_r->regcache;
10696   ULONGEST u_regval[2]= {0};
10697
10698   uint32_t reg_src1 = 0, reg_src2 = 0;
10699   uint32_t immed_high = 0, immed_low = 0,offset_8 = 0, tgt_mem_addr = 0;
10700   uint32_t opcode1 = 0;
10701
10702   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
10703   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
10704   opcode1 = bits (arm_insn_r->arm_insn, 20, 24);
10705
10706
10707   if (14 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
10708     {
10709       /* 1) Handle misc store, immediate offset.  */
10710       immed_low = bits (arm_insn_r->arm_insn, 0, 3);
10711       immed_high = bits (arm_insn_r->arm_insn, 8, 11);
10712       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
10713       regcache_raw_read_unsigned (reg_cache, reg_src1,
10714                                   &u_regval[0]);
10715       if (ARM_PC_REGNUM == reg_src1)
10716         {
10717           /* If R15 was used as Rn, hence current PC+8.  */
10718           u_regval[0] = u_regval[0] + 8;
10719         }
10720       offset_8 = (immed_high << 4) | immed_low;
10721       /* Calculate target store address.  */
10722       if (14 == arm_insn_r->opcode)
10723         {
10724           tgt_mem_addr = u_regval[0] + offset_8;
10725         }
10726       else
10727         {
10728           tgt_mem_addr = u_regval[0] - offset_8;
10729         }
10730       if (ARM_RECORD_STRH == str_type)
10731         {
10732           record_buf_mem[0] = 2;
10733           record_buf_mem[1] = tgt_mem_addr;
10734           arm_insn_r->mem_rec_count = 1;
10735         }
10736       else if (ARM_RECORD_STRD == str_type)
10737         {
10738           record_buf_mem[0] = 4;
10739           record_buf_mem[1] = tgt_mem_addr;
10740           record_buf_mem[2] = 4;
10741           record_buf_mem[3] = tgt_mem_addr + 4;
10742           arm_insn_r->mem_rec_count = 2;
10743         }
10744     }
10745   else if (12 == arm_insn_r->opcode || 8 == arm_insn_r->opcode)
10746     {
10747       /* 2) Store, register offset.  */
10748       /* Get Rm.  */
10749       reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
10750       /* Get Rn.  */
10751       reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
10752       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10753       regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
10754       if (15 == reg_src2)
10755         {
10756           /* If R15 was used as Rn, hence current PC+8.  */
10757           u_regval[0] = u_regval[0] + 8;
10758         }
10759       /* Calculate target store address, Rn +/- Rm, register offset.  */
10760       if (12 == arm_insn_r->opcode)
10761         {
10762           tgt_mem_addr = u_regval[0] + u_regval[1];
10763         }
10764       else
10765         {
10766           tgt_mem_addr = u_regval[1] - u_regval[0];
10767         }
10768       if (ARM_RECORD_STRH == str_type)
10769         {
10770           record_buf_mem[0] = 2;
10771           record_buf_mem[1] = tgt_mem_addr;
10772           arm_insn_r->mem_rec_count = 1;
10773         }
10774       else if (ARM_RECORD_STRD == str_type)
10775         {
10776           record_buf_mem[0] = 4;
10777           record_buf_mem[1] = tgt_mem_addr;
10778           record_buf_mem[2] = 4;
10779           record_buf_mem[3] = tgt_mem_addr + 4;
10780           arm_insn_r->mem_rec_count = 2;
10781         }
10782     }
10783   else if (11 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
10784            || 2 == arm_insn_r->opcode  || 6 == arm_insn_r->opcode)
10785     {
10786       /* 3) Store, immediate pre-indexed.  */
10787       /* 5) Store, immediate post-indexed.  */
10788       immed_low = bits (arm_insn_r->arm_insn, 0, 3);
10789       immed_high = bits (arm_insn_r->arm_insn, 8, 11);
10790       offset_8 = (immed_high << 4) | immed_low;
10791       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
10792       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10793       /* Calculate target store address, Rn +/- Rm, register offset.  */
10794       if (15 == arm_insn_r->opcode || 6 == arm_insn_r->opcode)
10795         {
10796           tgt_mem_addr = u_regval[0] + offset_8;
10797         }
10798       else
10799         {
10800           tgt_mem_addr = u_regval[0] - offset_8;
10801         }
10802       if (ARM_RECORD_STRH == str_type)
10803         {
10804           record_buf_mem[0] = 2;
10805           record_buf_mem[1] = tgt_mem_addr;
10806           arm_insn_r->mem_rec_count = 1;
10807         }
10808       else if (ARM_RECORD_STRD == str_type)
10809         {
10810           record_buf_mem[0] = 4;
10811           record_buf_mem[1] = tgt_mem_addr;
10812           record_buf_mem[2] = 4;
10813           record_buf_mem[3] = tgt_mem_addr + 4;
10814           arm_insn_r->mem_rec_count = 2;
10815         }
10816       /* Record Rn also as it changes.  */
10817       *(record_buf) = bits (arm_insn_r->arm_insn, 16, 19);
10818       arm_insn_r->reg_rec_count = 1;
10819     }
10820   else if (9 == arm_insn_r->opcode || 13 == arm_insn_r->opcode
10821            || 0 == arm_insn_r->opcode || 4 == arm_insn_r->opcode)
10822     {
10823       /* 4) Store, register pre-indexed.  */
10824       /* 6) Store, register post -indexed.  */
10825       reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
10826       reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
10827       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
10828       regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
10829       /* Calculate target store address, Rn +/- Rm, register offset.  */
10830       if (13 == arm_insn_r->opcode || 4 == arm_insn_r->opcode)
10831         {
10832           tgt_mem_addr = u_regval[0] + u_regval[1];
10833         }
10834       else
10835         {
10836           tgt_mem_addr = u_regval[1] - u_regval[0];
10837         }
10838       if (ARM_RECORD_STRH == str_type)
10839         {
10840           record_buf_mem[0] = 2;
10841           record_buf_mem[1] = tgt_mem_addr;
10842           arm_insn_r->mem_rec_count = 1;
10843         }
10844       else if (ARM_RECORD_STRD == str_type)
10845         {
10846           record_buf_mem[0] = 4;
10847           record_buf_mem[1] = tgt_mem_addr;
10848           record_buf_mem[2] = 4;
10849           record_buf_mem[3] = tgt_mem_addr + 4;
10850           arm_insn_r->mem_rec_count = 2;
10851         }
10852       /* Record Rn also as it changes.  */
10853       *(record_buf) = bits (arm_insn_r->arm_insn, 16, 19);
10854       arm_insn_r->reg_rec_count = 1;
10855     }
10856   return 0;
10857 }
10858
10859 /* Handling ARM extension space insns.  */
10860
10861 static int
10862 arm_record_extension_space (insn_decode_record *arm_insn_r)
10863 {
10864   uint32_t ret = 0;  /* Return value: -1:record failure ;  0:success  */
10865   uint32_t opcode1 = 0, opcode2 = 0, insn_op1 = 0;
10866   uint32_t record_buf[8], record_buf_mem[8];
10867   uint32_t reg_src1 = 0;
10868   uint32_t immed_high = 0, immed_low = 0,offset_8 = 0, tgt_mem_addr = 0;
10869   struct regcache *reg_cache = arm_insn_r->regcache;
10870   ULONGEST u_regval = 0;
10871
10872   gdb_assert (!INSN_RECORDED(arm_insn_r));
10873   /* Handle unconditional insn extension space.  */
10874
10875   opcode1 = bits (arm_insn_r->arm_insn, 20, 27);
10876   opcode2 = bits (arm_insn_r->arm_insn, 4, 7);
10877   if (arm_insn_r->cond)
10878     {
10879       /* PLD has no affect on architectural state, it just affects
10880          the caches.  */
10881       if (5 == ((opcode1 & 0xE0) >> 5))
10882         {
10883           /* BLX(1) */
10884           record_buf[0] = ARM_PS_REGNUM;
10885           record_buf[1] = ARM_LR_REGNUM;
10886           arm_insn_r->reg_rec_count = 2;
10887         }
10888       /* STC2, LDC2, MCR2, MRC2, CDP2: <TBD>, co-processor insn.  */
10889     }
10890
10891
10892   opcode1 = bits (arm_insn_r->arm_insn, 25, 27);
10893   if (3 == opcode1 && bit (arm_insn_r->arm_insn, 4))
10894     {
10895       ret = -1;
10896       /* Undefined instruction on ARM V5; need to handle if later 
10897          versions define it.  */
10898     }
10899
10900   opcode1 = bits (arm_insn_r->arm_insn, 24, 27);
10901   opcode2 = bits (arm_insn_r->arm_insn, 4, 7);
10902   insn_op1 = bits (arm_insn_r->arm_insn, 20, 23);
10903
10904   /* Handle arithmetic insn extension space.  */
10905   if (!opcode1 && 9 == opcode2 && 1 != arm_insn_r->cond
10906       && !INSN_RECORDED(arm_insn_r))
10907     {
10908       /* Handle MLA(S) and MUL(S).  */
10909       if (0 <= insn_op1 && 3 >= insn_op1)
10910       {
10911         record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10912         record_buf[1] = ARM_PS_REGNUM;
10913         arm_insn_r->reg_rec_count = 2;
10914       }
10915       else if (4 <= insn_op1 && 15 >= insn_op1)
10916       {
10917         /* Handle SMLAL(S), SMULL(S), UMLAL(S), UMULL(S).  */
10918         record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
10919         record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
10920         record_buf[2] = ARM_PS_REGNUM;
10921         arm_insn_r->reg_rec_count = 3;
10922       }
10923     }
10924
10925   opcode1 = bits (arm_insn_r->arm_insn, 26, 27);
10926   opcode2 = bits (arm_insn_r->arm_insn, 23, 24);
10927   insn_op1 = bits (arm_insn_r->arm_insn, 21, 22);
10928
10929   /* Handle control insn extension space.  */
10930
10931   if (!opcode1 && 2 == opcode2 && !bit (arm_insn_r->arm_insn, 20)
10932       && 1 != arm_insn_r->cond && !INSN_RECORDED(arm_insn_r))
10933     {
10934       if (!bit (arm_insn_r->arm_insn,25))
10935         {
10936           if (!bits (arm_insn_r->arm_insn, 4, 7))
10937             {
10938               if ((0 == insn_op1) || (2 == insn_op1))
10939                 {
10940                   /* MRS.  */
10941                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10942                   arm_insn_r->reg_rec_count = 1;
10943                 }
10944               else if (1 == insn_op1)
10945                 {
10946                   /* CSPR is going to be changed.  */
10947                   record_buf[0] = ARM_PS_REGNUM;
10948                   arm_insn_r->reg_rec_count = 1;
10949                 }
10950               else if (3 == insn_op1)
10951                 {
10952                   /* SPSR is going to be changed.  */
10953                   /* We need to get SPSR value, which is yet to be done.  */
10954                   printf_unfiltered (_("Process record does not support "
10955                                      "instruction  0x%0x at address %s.\n"),
10956                                      arm_insn_r->arm_insn,
10957                                      paddress (arm_insn_r->gdbarch, 
10958                                      arm_insn_r->this_addr));
10959                   return -1;
10960                 }
10961             }
10962           else if (1 == bits (arm_insn_r->arm_insn, 4, 7))
10963             {
10964               if (1 == insn_op1)
10965                 {
10966                   /* BX.  */
10967                   record_buf[0] = ARM_PS_REGNUM;
10968                   arm_insn_r->reg_rec_count = 1;
10969                 }
10970               else if (3 == insn_op1)
10971                 {
10972                   /* CLZ.  */
10973                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
10974                   arm_insn_r->reg_rec_count = 1;
10975                 }
10976             }
10977           else if (3 == bits (arm_insn_r->arm_insn, 4, 7))
10978             {
10979               /* BLX.  */
10980               record_buf[0] = ARM_PS_REGNUM;
10981               record_buf[1] = ARM_LR_REGNUM;
10982               arm_insn_r->reg_rec_count = 2;
10983             }
10984           else if (5 == bits (arm_insn_r->arm_insn, 4, 7))
10985             {
10986               /* QADD, QSUB, QDADD, QDSUB */
10987               record_buf[0] = ARM_PS_REGNUM;
10988               record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
10989               arm_insn_r->reg_rec_count = 2;
10990             }
10991           else if (7 == bits (arm_insn_r->arm_insn, 4, 7))
10992             {
10993               /* BKPT.  */
10994               record_buf[0] = ARM_PS_REGNUM;
10995               record_buf[1] = ARM_LR_REGNUM;
10996               arm_insn_r->reg_rec_count = 2;
10997
10998               /* Save SPSR also;how?  */
10999               printf_unfiltered (_("Process record does not support "
11000                                   "instruction 0x%0x at address %s.\n"),
11001                                   arm_insn_r->arm_insn,
11002                   paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11003               return -1;
11004             }
11005           else if(8 == bits (arm_insn_r->arm_insn, 4, 7) 
11006                   || 10 == bits (arm_insn_r->arm_insn, 4, 7)
11007                   || 12 == bits (arm_insn_r->arm_insn, 4, 7)
11008                   || 14 == bits (arm_insn_r->arm_insn, 4, 7)
11009                  )
11010             {
11011               if (0 == insn_op1 || 1 == insn_op1)
11012                 {
11013                   /* SMLA<x><y>, SMLAW<y>, SMULW<y>.  */
11014                   /* We dont do optimization for SMULW<y> where we
11015                      need only Rd.  */
11016                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11017                   record_buf[1] = ARM_PS_REGNUM;
11018                   arm_insn_r->reg_rec_count = 2;
11019                 }
11020               else if (2 == insn_op1)
11021                 {
11022                   /* SMLAL<x><y>.  */
11023                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11024                   record_buf[1] = bits (arm_insn_r->arm_insn, 16, 19);
11025                   arm_insn_r->reg_rec_count = 2;
11026                 }
11027               else if (3 == insn_op1)
11028                 {
11029                   /* SMUL<x><y>.  */
11030                   record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11031                   arm_insn_r->reg_rec_count = 1;
11032                 }
11033             }
11034         }
11035       else
11036         {
11037           /* MSR : immediate form.  */
11038           if (1 == insn_op1)
11039             {
11040               /* CSPR is going to be changed.  */
11041               record_buf[0] = ARM_PS_REGNUM;
11042               arm_insn_r->reg_rec_count = 1;
11043             }
11044           else if (3 == insn_op1)
11045             {
11046               /* SPSR is going to be changed.  */
11047               /* we need to get SPSR value, which is yet to be done  */
11048               printf_unfiltered (_("Process record does not support "
11049                                    "instruction 0x%0x at address %s.\n"),
11050                                     arm_insn_r->arm_insn,
11051                                     paddress (arm_insn_r->gdbarch, 
11052                                     arm_insn_r->this_addr));
11053               return -1;
11054             }
11055         }
11056     }
11057
11058   opcode1 = bits (arm_insn_r->arm_insn, 25, 27);
11059   opcode2 = bits (arm_insn_r->arm_insn, 20, 24);
11060   insn_op1 = bits (arm_insn_r->arm_insn, 5, 6);
11061
11062   /* Handle load/store insn extension space.  */
11063
11064   if (!opcode1 && bit (arm_insn_r->arm_insn, 7) 
11065       && bit (arm_insn_r->arm_insn, 4) && 1 != arm_insn_r->cond
11066       && !INSN_RECORDED(arm_insn_r))
11067     {
11068       /* SWP/SWPB.  */
11069       if (0 == insn_op1)
11070         {
11071           /* These insn, changes register and memory as well.  */
11072           /* SWP or SWPB insn.  */
11073           /* Get memory address given by Rn.  */
11074           reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11075           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
11076           /* SWP insn ?, swaps word.  */
11077           if (8 == arm_insn_r->opcode)
11078             {
11079               record_buf_mem[0] = 4;
11080             }
11081           else
11082             {
11083               /* SWPB insn, swaps only byte.  */
11084               record_buf_mem[0] = 1;
11085             }
11086           record_buf_mem[1] = u_regval;
11087           arm_insn_r->mem_rec_count = 1;
11088           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11089           arm_insn_r->reg_rec_count = 1;
11090         }
11091       else if (1 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11092         {
11093           /* STRH.  */
11094           arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11095                           ARM_RECORD_STRH);
11096         }
11097       else if (2 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11098         {
11099           /* LDRD.  */
11100           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11101           record_buf[1] = record_buf[0] + 1;
11102           arm_insn_r->reg_rec_count = 2;
11103         }
11104       else if (3 == insn_op1 && !bit (arm_insn_r->arm_insn, 20))
11105         {
11106           /* STRD.  */
11107           arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11108                         ARM_RECORD_STRD);
11109         }
11110       else if (bit (arm_insn_r->arm_insn, 20) && insn_op1 <= 3)
11111         {
11112           /* LDRH, LDRSB, LDRSH.  */
11113           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11114           arm_insn_r->reg_rec_count = 1;
11115         }
11116
11117     }
11118
11119   opcode1 = bits (arm_insn_r->arm_insn, 23, 27);
11120   if (24 == opcode1 && bit (arm_insn_r->arm_insn, 21)
11121       && !INSN_RECORDED(arm_insn_r))
11122     {
11123       ret = -1;
11124       /* Handle coprocessor insn extension space.  */
11125     }
11126
11127   /* To be done for ARMv5 and later; as of now we return -1.  */
11128   if (-1 == ret)
11129     printf_unfiltered (_("Process record does not support instruction x%0x "
11130                          "at address %s.\n"),arm_insn_r->arm_insn,
11131                          paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11132
11133
11134   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11135   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11136
11137   return ret;
11138 }
11139
11140 /* Handling opcode 000 insns.  */
11141
11142 static int
11143 arm_record_data_proc_misc_ld_str (insn_decode_record *arm_insn_r)
11144 {
11145   struct regcache *reg_cache = arm_insn_r->regcache;
11146   uint32_t record_buf[8], record_buf_mem[8];
11147   ULONGEST u_regval[2] = {0};
11148
11149   uint32_t reg_src1 = 0, reg_src2 = 0, reg_dest = 0;
11150   uint32_t immed_high = 0, immed_low = 0, offset_8 = 0, tgt_mem_addr = 0;
11151   uint32_t opcode1 = 0;
11152
11153   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11154   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11155   opcode1 = bits (arm_insn_r->arm_insn, 20, 24);
11156
11157   /* Data processing insn /multiply insn.  */
11158   if (9 == arm_insn_r->decode
11159       && ((4 <= arm_insn_r->opcode && 7 >= arm_insn_r->opcode)
11160       ||  (0 == arm_insn_r->opcode || 1 == arm_insn_r->opcode)))
11161     {
11162       /* Handle multiply instructions.  */
11163       /* MLA, MUL, SMLAL, SMULL, UMLAL, UMULL.  */
11164         if (0 == arm_insn_r->opcode || 1 == arm_insn_r->opcode)
11165           {
11166             /* Handle MLA and MUL.  */
11167             record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
11168             record_buf[1] = ARM_PS_REGNUM;
11169             arm_insn_r->reg_rec_count = 2;
11170           }
11171         else if (4 <= arm_insn_r->opcode && 7 >= arm_insn_r->opcode)
11172           {
11173             /* Handle SMLAL, SMULL, UMLAL, UMULL.  */
11174             record_buf[0] = bits (arm_insn_r->arm_insn, 16, 19);
11175             record_buf[1] = bits (arm_insn_r->arm_insn, 12, 15);
11176             record_buf[2] = ARM_PS_REGNUM;
11177             arm_insn_r->reg_rec_count = 3;
11178           }
11179     }
11180   else if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM)
11181            && (11 == arm_insn_r->decode || 13 == arm_insn_r->decode))
11182     {
11183       /* Handle misc load insns, as 20th bit  (L = 1).  */
11184       /* LDR insn has a capability to do branching, if
11185          MOV LR, PC is precceded by LDR insn having Rn as R15
11186          in that case, it emulates branch and link insn, and hence we 
11187          need to save CSPR and PC as well. I am not sure this is right
11188          place; as opcode = 010 LDR insn make this happen, if R15 was
11189          used.  */
11190       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11191       if (15 != reg_dest)
11192         {
11193           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11194           arm_insn_r->reg_rec_count = 1;
11195         }
11196       else
11197         {
11198           record_buf[0] = reg_dest;
11199           record_buf[1] = ARM_PS_REGNUM;
11200           arm_insn_r->reg_rec_count = 2;
11201         }
11202     }
11203   else if ((9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode)
11204            && sbo_sbz (arm_insn_r->arm_insn, 5, 12, 0)
11205            && sbo_sbz (arm_insn_r->arm_insn, 13, 4, 1)
11206            && 2 == bits (arm_insn_r->arm_insn, 20, 21))
11207     {
11208       /* Handle MSR insn.  */
11209       if (9 == arm_insn_r->opcode)
11210         {
11211           /* CSPR is going to be changed.  */
11212           record_buf[0] = ARM_PS_REGNUM;
11213           arm_insn_r->reg_rec_count = 1;
11214         }
11215       else
11216         {
11217           /* SPSR is going to be changed.  */
11218           /* How to read SPSR value?  */
11219           printf_unfiltered (_("Process record does not support instruction "
11220                             "0x%0x at address %s.\n"),
11221                             arm_insn_r->arm_insn,
11222                         paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11223           return -1;
11224         }
11225     }
11226   else if (9 == arm_insn_r->decode
11227            && (8 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
11228            && !bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11229     {
11230       /* Handling SWP, SWPB.  */
11231       /* These insn, changes register and memory as well.  */
11232       /* SWP or SWPB insn.  */
11233
11234       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11235       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11236       /* SWP insn ?, swaps word.  */
11237       if (8 == arm_insn_r->opcode)
11238         {
11239           record_buf_mem[0] = 4;
11240         }
11241         else
11242         {
11243           /* SWPB insn, swaps only byte.  */
11244           record_buf_mem[0] = 1;
11245         }
11246       record_buf_mem[1] = u_regval[0];
11247       arm_insn_r->mem_rec_count = 1;
11248       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11249       arm_insn_r->reg_rec_count = 1;
11250     }
11251   else if (3 == arm_insn_r->decode && 0x12 == opcode1
11252            && sbo_sbz (arm_insn_r->arm_insn, 9, 12, 1))
11253     {
11254       /* Handle BLX, branch and link/exchange.  */
11255       if (9 == arm_insn_r->opcode)
11256       {
11257         /* Branch is chosen by setting T bit of CSPR, bitp[0] of Rm,
11258            and R14 stores the return address.  */
11259         record_buf[0] = ARM_PS_REGNUM;
11260         record_buf[1] = ARM_LR_REGNUM;
11261         arm_insn_r->reg_rec_count = 2;
11262       }
11263     }
11264   else if (7 == arm_insn_r->decode && 0x12 == opcode1)
11265     {
11266       /* Handle enhanced software breakpoint insn, BKPT.  */
11267       /* CPSR is changed to be executed in ARM state,  disabling normal
11268          interrupts, entering abort mode.  */
11269       /* According to high vector configuration PC is set.  */
11270       /* user hit breakpoint and type reverse, in
11271          that case, we need to go back with previous CPSR and
11272          Program Counter.  */
11273       record_buf[0] = ARM_PS_REGNUM;
11274       record_buf[1] = ARM_LR_REGNUM;
11275       arm_insn_r->reg_rec_count = 2;
11276
11277       /* Save SPSR also; how?  */
11278       printf_unfiltered (_("Process record does not support instruction "
11279                            "0x%0x at address %s.\n"),arm_insn_r->arm_insn,
11280                            paddress (arm_insn_r->gdbarch, 
11281                            arm_insn_r->this_addr));
11282       return -1;
11283     }
11284   else if (11 == arm_insn_r->decode
11285            && !bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11286   {
11287     /* Handle enhanced store insns and DSP insns (e.g. LDRD).  */
11288
11289     /* Handle str(x) insn */
11290     arm_record_strx(arm_insn_r, &record_buf[0], &record_buf_mem[0],
11291                     ARM_RECORD_STRH);
11292   }
11293   else if (1 == arm_insn_r->decode && 0x12 == opcode1
11294            && sbo_sbz (arm_insn_r->arm_insn, 9, 12, 1))
11295     {
11296       /* Handle BX, branch and link/exchange.  */
11297       /* Branch is chosen by setting T bit of CSPR, bitp[0] of Rm.  */
11298       record_buf[0] = ARM_PS_REGNUM;
11299       arm_insn_r->reg_rec_count = 1;
11300     }
11301   else if (1 == arm_insn_r->decode && 0x16 == opcode1
11302            && sbo_sbz (arm_insn_r->arm_insn, 9, 4, 1)
11303            && sbo_sbz (arm_insn_r->arm_insn, 17, 4, 1))
11304     {
11305       /* Count leading zeros: CLZ.  */
11306       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11307       arm_insn_r->reg_rec_count = 1;
11308     }
11309   else if (!bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM)
11310            && (8 == arm_insn_r->opcode || 10 == arm_insn_r->opcode)
11311            && sbo_sbz (arm_insn_r->arm_insn, 17, 4, 1)
11312            && sbo_sbz (arm_insn_r->arm_insn, 1, 12, 0)
11313           )
11314     {
11315       /* Handle MRS insn.  */
11316       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11317       arm_insn_r->reg_rec_count = 1;
11318     }
11319   else if (arm_insn_r->opcode <= 15)
11320     {
11321       /* Normal data processing insns.  */
11322       /* Out of 11 shifter operands mode, all the insn modifies destination
11323          register, which is specified by 13-16 decode.  */
11324       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11325       record_buf[1] = ARM_PS_REGNUM;
11326       arm_insn_r->reg_rec_count = 2;
11327     }
11328   else
11329     {
11330       return -1;
11331     }
11332
11333   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11334   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11335   return 0;
11336 }
11337
11338 /* Handling opcode 001 insns.  */
11339
11340 static int
11341 arm_record_data_proc_imm (insn_decode_record *arm_insn_r)
11342 {
11343   uint32_t record_buf[8], record_buf_mem[8];
11344
11345   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11346   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11347
11348   if ((9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode)
11349       && 2 == bits (arm_insn_r->arm_insn, 20, 21)
11350       && sbo_sbz (arm_insn_r->arm_insn, 13, 4, 1)
11351      )
11352     {
11353       /* Handle MSR insn.  */
11354       if (9 == arm_insn_r->opcode)
11355         {
11356           /* CSPR is going to be changed.  */
11357           record_buf[0] = ARM_PS_REGNUM;
11358           arm_insn_r->reg_rec_count = 1;
11359         }
11360       else
11361         {
11362           /* SPSR is going to be changed.  */
11363         }
11364     }
11365   else if (arm_insn_r->opcode <= 15)
11366     {
11367       /* Normal data processing insns.  */
11368       /* Out of 11 shifter operands mode, all the insn modifies destination
11369          register, which is specified by 13-16 decode.  */
11370       record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11371       record_buf[1] = ARM_PS_REGNUM;
11372       arm_insn_r->reg_rec_count = 2;
11373     }
11374   else
11375     {
11376       return -1;
11377     }
11378
11379   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11380   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11381   return 0;
11382 }
11383
11384 /* Handling opcode 010 insns.  */
11385
11386 static int
11387 arm_record_ld_st_imm_offset (insn_decode_record *arm_insn_r)
11388 {
11389   struct regcache *reg_cache = arm_insn_r->regcache;
11390
11391   uint32_t reg_src1 = 0 , reg_dest = 0;
11392   uint32_t offset_12 = 0, tgt_mem_addr = 0;
11393   uint32_t record_buf[8], record_buf_mem[8];
11394
11395   ULONGEST u_regval = 0;
11396
11397   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11398   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11399
11400   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11401     {
11402       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11403       /* LDR insn has a capability to do branching, if
11404          MOV LR, PC is precedded by LDR insn having Rn as R15
11405          in that case, it emulates branch and link insn, and hence we
11406          need to save CSPR and PC as well.  */
11407       if (ARM_PC_REGNUM != reg_dest)
11408         {
11409           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11410           arm_insn_r->reg_rec_count = 1;
11411         }
11412       else
11413         {
11414           record_buf[0] = reg_dest;
11415           record_buf[1] = ARM_PS_REGNUM;
11416           arm_insn_r->reg_rec_count = 2;
11417         }
11418     }
11419   else
11420     {
11421       /* Store, immediate offset, immediate pre-indexed,
11422          immediate post-indexed.  */
11423       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11424       offset_12 = bits (arm_insn_r->arm_insn, 0, 11);
11425       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
11426       /* U == 1 */
11427       if (bit (arm_insn_r->arm_insn, 23))
11428         {
11429           tgt_mem_addr = u_regval + offset_12;
11430         }
11431       else
11432         {
11433           tgt_mem_addr = u_regval - offset_12;
11434         }
11435
11436       switch (arm_insn_r->opcode)
11437         {
11438           /* STR.  */
11439           case 8:
11440           case 12:
11441           /* STR.  */
11442           case 9:
11443           case 13:
11444           /* STRT.  */    
11445           case 1:
11446           case 5:
11447           /* STR.  */    
11448           case 4:
11449           case 0:
11450             record_buf_mem[0] = 4;
11451           break;
11452
11453           /* STRB.  */
11454           case 10:
11455           case 14:
11456           /* STRB.  */    
11457           case 11:
11458           case 15:
11459           /* STRBT.  */    
11460           case 3:
11461           case 7:
11462           /* STRB.  */    
11463           case 2:
11464           case 6:
11465             record_buf_mem[0] = 1;
11466           break;
11467
11468           default:
11469             gdb_assert_not_reached ("no decoding pattern found");
11470           break;
11471         }
11472       record_buf_mem[1] = tgt_mem_addr;
11473       arm_insn_r->mem_rec_count = 1;
11474
11475       if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11476           || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11477           || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11478           || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11479           || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11480           || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11481          )
11482         {
11483           /* We are handling pre-indexed mode; post-indexed mode;
11484              where Rn is going to be changed.  */
11485           record_buf[0] = reg_src1;
11486           arm_insn_r->reg_rec_count = 1;
11487         }
11488     }
11489
11490   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11491   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11492   return 0;
11493 }
11494
11495 /* Handling opcode 011 insns.  */
11496
11497 static int
11498 arm_record_ld_st_reg_offset (insn_decode_record *arm_insn_r)
11499 {
11500   struct regcache *reg_cache = arm_insn_r->regcache;
11501
11502   uint32_t shift_imm = 0;
11503   uint32_t reg_src1 = 0, reg_src2 = 0, reg_dest = 0;
11504   uint32_t offset_12 = 0, tgt_mem_addr = 0;
11505   uint32_t record_buf[8], record_buf_mem[8];
11506
11507   LONGEST s_word;
11508   ULONGEST u_regval[2];
11509
11510   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 21, 24);
11511   arm_insn_r->decode = bits (arm_insn_r->arm_insn, 4, 7);
11512
11513   /* Handle enhanced store insns and LDRD DSP insn,
11514      order begins according to addressing modes for store insns
11515      STRH insn.  */
11516
11517   /* LDR or STR?  */
11518   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11519     {
11520       reg_dest = bits (arm_insn_r->arm_insn, 12, 15);
11521       /* LDR insn has a capability to do branching, if
11522          MOV LR, PC is precedded by LDR insn having Rn as R15
11523          in that case, it emulates branch and link insn, and hence we
11524          need to save CSPR and PC as well.  */
11525       if (15 != reg_dest)
11526         {
11527           record_buf[0] = bits (arm_insn_r->arm_insn, 12, 15);
11528           arm_insn_r->reg_rec_count = 1;
11529         }
11530       else
11531         {
11532           record_buf[0] = reg_dest;
11533           record_buf[1] = ARM_PS_REGNUM;
11534           arm_insn_r->reg_rec_count = 2;
11535         }
11536     }
11537   else
11538     {
11539       if (! bits (arm_insn_r->arm_insn, 4, 11))
11540         {
11541           /* Store insn, register offset and register pre-indexed,
11542              register post-indexed.  */
11543           /* Get Rm.  */
11544           reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
11545           /* Get Rn.  */
11546           reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
11547           regcache_raw_read_unsigned (reg_cache, reg_src1
11548                                       , &u_regval[0]);
11549           regcache_raw_read_unsigned (reg_cache, reg_src2
11550                                       , &u_regval[1]);
11551           if (15 == reg_src2)
11552             {
11553               /* If R15 was used as Rn, hence current PC+8.  */
11554               /* Pre-indexed mode doesnt reach here ; illegal insn.  */
11555                 u_regval[0] = u_regval[0] + 8;
11556             }
11557           /* Calculate target store address, Rn +/- Rm, register offset.  */
11558           /* U == 1.  */
11559           if (bit (arm_insn_r->arm_insn, 23))
11560             {
11561               tgt_mem_addr = u_regval[0] + u_regval[1];
11562             }
11563           else
11564             {
11565               tgt_mem_addr = u_regval[1] - u_regval[0];
11566             }
11567
11568           switch (arm_insn_r->opcode)
11569             {
11570               /* STR.  */
11571               case 8:
11572               case 12:
11573               /* STR.  */    
11574               case 9:
11575               case 13:
11576               /* STRT.  */
11577               case 1:
11578               case 5:
11579               /* STR.  */
11580               case 0:
11581               case 4:
11582                 record_buf_mem[0] = 4;
11583               break;
11584
11585               /* STRB.  */
11586               case 10:
11587               case 14:
11588               /* STRB.  */
11589               case 11:
11590               case 15:
11591               /* STRBT.  */    
11592               case 3:
11593               case 7:
11594               /* STRB.  */
11595               case 2:
11596               case 6:
11597                 record_buf_mem[0] = 1;
11598               break;
11599
11600               default:
11601                 gdb_assert_not_reached ("no decoding pattern found");
11602               break;
11603             }
11604           record_buf_mem[1] = tgt_mem_addr;
11605           arm_insn_r->mem_rec_count = 1;
11606
11607           if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11608               || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11609               || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11610               || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11611               || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11612               || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11613              )
11614             {
11615               /* Rn is going to be changed in pre-indexed mode and
11616                  post-indexed mode as well.  */
11617               record_buf[0] = reg_src2;
11618               arm_insn_r->reg_rec_count = 1;
11619             }
11620         }
11621       else
11622         {
11623           /* Store insn, scaled register offset; scaled pre-indexed.  */
11624           offset_12 = bits (arm_insn_r->arm_insn, 5, 6);
11625           /* Get Rm.  */
11626           reg_src1 = bits (arm_insn_r->arm_insn, 0, 3);
11627           /* Get Rn.  */
11628           reg_src2 = bits (arm_insn_r->arm_insn, 16, 19);
11629           /* Get shift_imm.  */
11630           shift_imm = bits (arm_insn_r->arm_insn, 7, 11);
11631           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11632           regcache_raw_read_signed (reg_cache, reg_src1, &s_word);
11633           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
11634           /* Offset_12 used as shift.  */
11635           switch (offset_12)
11636             {
11637               case 0:
11638                 /* Offset_12 used as index.  */
11639                 offset_12 = u_regval[0] << shift_imm;
11640               break;
11641
11642               case 1:
11643                 offset_12 = (!shift_imm)?0:u_regval[0] >> shift_imm;
11644               break;
11645
11646               case 2:
11647                 if (!shift_imm)
11648                   {
11649                     if (bit (u_regval[0], 31))
11650                       {
11651                         offset_12 = 0xFFFFFFFF;
11652                       }
11653                     else
11654                       {
11655                         offset_12 = 0;
11656                       }
11657                   }
11658                 else
11659                   {
11660                     /* This is arithmetic shift.  */
11661                     offset_12 = s_word >> shift_imm;
11662                   }
11663                 break;
11664
11665               case 3:
11666                 if (!shift_imm)
11667                   {
11668                     regcache_raw_read_unsigned (reg_cache, ARM_PS_REGNUM,
11669                                                 &u_regval[1]);
11670                     /* Get C flag value and shift it by 31.  */
11671                     offset_12 = (((bit (u_regval[1], 29)) << 31) \
11672                                   | (u_regval[0]) >> 1);
11673                   }
11674                 else
11675                   {
11676                     offset_12 = (u_regval[0] >> shift_imm) \
11677                                 | (u_regval[0] <<
11678                                 (sizeof(uint32_t) - shift_imm));
11679                   }
11680               break;
11681
11682               default:
11683                 gdb_assert_not_reached ("no decoding pattern found");
11684               break;
11685             }
11686
11687           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
11688           /* bit U set.  */
11689           if (bit (arm_insn_r->arm_insn, 23))
11690             {
11691               tgt_mem_addr = u_regval[1] + offset_12;
11692             }
11693           else
11694             {
11695               tgt_mem_addr = u_regval[1] - offset_12;
11696             }
11697
11698           switch (arm_insn_r->opcode)
11699             {
11700               /* STR.  */
11701               case 8:
11702               case 12:
11703               /* STR.  */    
11704               case 9:
11705               case 13:
11706               /* STRT.  */
11707               case 1:
11708               case 5:
11709               /* STR.  */
11710               case 0:
11711               case 4:
11712                 record_buf_mem[0] = 4;
11713               break;
11714
11715               /* STRB.  */
11716               case 10:
11717               case 14:
11718               /* STRB.  */
11719               case 11:
11720               case 15:
11721               /* STRBT.  */    
11722               case 3:
11723               case 7:
11724               /* STRB.  */
11725               case 2:
11726               case 6:
11727                 record_buf_mem[0] = 1;
11728               break;
11729
11730               default:
11731                 gdb_assert_not_reached ("no decoding pattern found");
11732               break;
11733             }
11734           record_buf_mem[1] = tgt_mem_addr;
11735           arm_insn_r->mem_rec_count = 1;
11736
11737           if (9 == arm_insn_r->opcode || 11 == arm_insn_r->opcode
11738               || 13 == arm_insn_r->opcode || 15 == arm_insn_r->opcode
11739               || 0 == arm_insn_r->opcode || 2 == arm_insn_r->opcode
11740               || 4 == arm_insn_r->opcode || 6 == arm_insn_r->opcode
11741               || 1 == arm_insn_r->opcode || 3 == arm_insn_r->opcode
11742               || 5 == arm_insn_r->opcode || 7 == arm_insn_r->opcode
11743              )
11744             {
11745               /* Rn is going to be changed in register scaled pre-indexed
11746                  mode,and scaled post indexed mode.  */
11747               record_buf[0] = reg_src2;
11748               arm_insn_r->reg_rec_count = 1;
11749             }
11750         }
11751     }
11752
11753   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11754   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11755   return 0;
11756 }
11757
11758 /* Handling opcode 100 insns.  */
11759
11760 static int
11761 arm_record_ld_st_multiple (insn_decode_record *arm_insn_r)
11762 {
11763   struct regcache *reg_cache = arm_insn_r->regcache;
11764
11765   uint32_t register_list[16] = {0}, register_count = 0, register_bits = 0;
11766   uint32_t reg_src1 = 0, addr_mode = 0, no_of_regs = 0;
11767   uint32_t start_address = 0, index = 0;
11768   uint32_t record_buf[24], record_buf_mem[48];
11769
11770   ULONGEST u_regval[2] = {0};
11771
11772   /* This mode is exclusively for load and store multiple.  */
11773   /* Handle incremenrt after/before and decrment after.before mode;
11774      Rn is changing depending on W bit, but as of now we store Rn too
11775      without optimization.  */
11776
11777   if (bit (arm_insn_r->arm_insn, INSN_S_L_BIT_NUM))
11778     {
11779       /* LDM  (1,2,3) where LDM  (3) changes CPSR too.  */
11780
11781       if (bit (arm_insn_r->arm_insn, 20) && !bit (arm_insn_r->arm_insn, 22))
11782         {
11783           register_bits = bits (arm_insn_r->arm_insn, 0, 15);
11784           no_of_regs = 15;
11785         }
11786       else
11787         {
11788           register_bits = bits (arm_insn_r->arm_insn, 0, 14);
11789           no_of_regs = 14;
11790         }
11791       /* Get Rn.  */
11792       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11793       while (register_bits)
11794       {
11795         if (register_bits & 0x00000001)
11796           register_list[register_count++] = 1;
11797         register_bits = register_bits >> 1;
11798       }
11799
11800         /* Extra space for Base Register and CPSR; wihtout optimization.  */
11801         record_buf[register_count] = reg_src1;
11802         record_buf[register_count + 1] = ARM_PS_REGNUM;
11803         arm_insn_r->reg_rec_count = register_count + 2;
11804
11805         for (register_count = 0; register_count < no_of_regs; register_count++)
11806           {
11807             if  (register_list[register_count])
11808               {
11809                 /* Register_count gives total no of registers
11810                 and dually working as reg number.  */
11811                 record_buf[index] = register_count;
11812                 index++;
11813               }
11814           }
11815
11816     }
11817   else
11818     {
11819       /* It handles both STM(1) and STM(2).  */
11820       addr_mode = bits (arm_insn_r->arm_insn, 23, 24);    
11821
11822       register_bits = bits (arm_insn_r->arm_insn, 0, 15);
11823       /* Get Rn.  */
11824       reg_src1 = bits (arm_insn_r->arm_insn, 16, 19);
11825       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
11826       while (register_bits)
11827         {
11828           if (register_bits & 0x00000001)
11829             register_count++;
11830           register_bits = register_bits >> 1;
11831         }
11832
11833       switch (addr_mode)
11834         {
11835           /* Decrement after.  */
11836           case 0:                          
11837             start_address = (u_regval[0]) - (register_count * 4) + 4;
11838             arm_insn_r->mem_rec_count = register_count;
11839             while (register_count)
11840               {
11841                 record_buf_mem[(register_count * 2) - 1] = start_address;
11842                 record_buf_mem[(register_count * 2) - 2] = 4;
11843                 start_address = start_address + 4;
11844                 register_count--;
11845               }
11846           break;    
11847
11848           /* Increment after.  */
11849           case 1:
11850             start_address = u_regval[0];
11851             arm_insn_r->mem_rec_count = register_count;
11852             while (register_count)
11853               {
11854                 record_buf_mem[(register_count * 2) - 1] = start_address;
11855                 record_buf_mem[(register_count * 2) - 2] = 4;
11856                 start_address = start_address + 4;
11857                 register_count--;
11858               }
11859           break;    
11860
11861           /* Decrement before.  */
11862           case 2:
11863
11864             start_address = (u_regval[0]) - (register_count * 4);
11865             arm_insn_r->mem_rec_count = register_count;
11866             while (register_count)
11867               {
11868                 record_buf_mem[(register_count * 2) - 1] = start_address;
11869                 record_buf_mem[(register_count * 2) - 2] = 4;
11870                 start_address = start_address + 4;
11871                 register_count--;
11872               }
11873           break;    
11874
11875           /* Increment before.  */
11876           case 3:
11877             start_address = u_regval[0] + 4;
11878             arm_insn_r->mem_rec_count = register_count;
11879             while (register_count)
11880               {
11881                 record_buf_mem[(register_count * 2) - 1] = start_address;
11882                 record_buf_mem[(register_count * 2) - 2] = 4;
11883                 start_address = start_address + 4;
11884                 register_count--;
11885               }
11886           break;    
11887
11888           default:
11889             gdb_assert_not_reached ("no decoding pattern found");
11890           break;    
11891         }
11892
11893       /* Base register also changes; based on condition and W bit.  */
11894       /* We save it anyway without optimization.  */
11895       record_buf[0] = reg_src1;
11896       arm_insn_r->reg_rec_count = 1;
11897     }
11898
11899   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11900   MEM_ALLOC (arm_insn_r->arm_mems, arm_insn_r->mem_rec_count, record_buf_mem);
11901   return 0;
11902 }
11903
11904 /* Handling opcode 101 insns.  */
11905
11906 static int
11907 arm_record_b_bl (insn_decode_record *arm_insn_r)
11908 {
11909   uint32_t record_buf[8];
11910
11911   /* Handle B, BL, BLX(1) insns.  */
11912   /* B simply branches so we do nothing here.  */
11913   /* Note: BLX(1) doesnt fall here but instead it falls into
11914      extension space.  */
11915   if (bit (arm_insn_r->arm_insn, 24))
11916   {
11917     record_buf[0] = ARM_LR_REGNUM;
11918     arm_insn_r->reg_rec_count = 1;
11919   }
11920
11921   REG_ALLOC (arm_insn_r->arm_regs, arm_insn_r->reg_rec_count, record_buf);
11922
11923   return 0;
11924 }
11925
11926 /* Handling opcode 110 insns.  */
11927
11928 static int
11929 arm_record_coproc (insn_decode_record *arm_insn_r)
11930 {
11931   printf_unfiltered (_("Process record does not support instruction "
11932                     "0x%0x at address %s.\n"),arm_insn_r->arm_insn,
11933                     paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11934
11935   return -1;
11936 }
11937
11938 /* Handling opcode 111 insns.  */
11939
11940 static int
11941 arm_record_coproc_data_proc (insn_decode_record *arm_insn_r)
11942 {
11943   struct gdbarch_tdep *tdep = gdbarch_tdep (arm_insn_r->gdbarch);
11944   struct regcache *reg_cache = arm_insn_r->regcache;
11945   uint32_t ret = 0; /* function return value: -1:record failure ;  0:success  */
11946
11947   /* Handle SWI insn; system call would be handled over here.  */
11948
11949   arm_insn_r->opcode = bits (arm_insn_r->arm_insn, 24, 27);
11950   if (15 == arm_insn_r->opcode)
11951   {
11952     /* Handle arm syscall insn.  */
11953     if (tdep->arm_swi_record != NULL)
11954       {
11955         ret = tdep->arm_swi_record(reg_cache);
11956       }
11957     else
11958       {
11959         printf_unfiltered (_("no syscall record support\n"));
11960         ret = -1;
11961       }
11962   }
11963
11964   printf_unfiltered (_("Process record does not support instruction "
11965                         "0x%0x at address %s.\n"),arm_insn_r->arm_insn,
11966                         paddress (arm_insn_r->gdbarch, arm_insn_r->this_addr));
11967   return ret;
11968 }
11969
11970 /* Handling opcode 000 insns.  */
11971
11972 static int
11973 thumb_record_shift_add_sub (insn_decode_record *thumb_insn_r)
11974 {
11975   uint32_t record_buf[8];
11976   uint32_t reg_src1 = 0;
11977
11978   reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
11979
11980   record_buf[0] = ARM_PS_REGNUM;
11981   record_buf[1] = reg_src1;
11982   thumb_insn_r->reg_rec_count = 2;
11983
11984   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
11985
11986   return 0;
11987 }
11988
11989
11990 /* Handling opcode 001 insns.  */
11991
11992 static int
11993 thumb_record_add_sub_cmp_mov (insn_decode_record *thumb_insn_r)
11994 {
11995   uint32_t record_buf[8];
11996   uint32_t reg_src1 = 0;
11997
11998   reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
11999
12000   record_buf[0] = ARM_PS_REGNUM;
12001   record_buf[1] = reg_src1;
12002   thumb_insn_r->reg_rec_count = 2;
12003
12004   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12005
12006   return 0;
12007 }
12008
12009 /* Handling opcode 010 insns.  */
12010
12011 static int
12012 thumb_record_ld_st_reg_offset (insn_decode_record *thumb_insn_r)
12013 {
12014   struct regcache *reg_cache =  thumb_insn_r->regcache;
12015   uint32_t record_buf[8], record_buf_mem[8];
12016
12017   uint32_t reg_src1 = 0, reg_src2 = 0;
12018   uint32_t opcode1 = 0, opcode2 = 0, opcode3 = 0;
12019
12020   ULONGEST u_regval[2] = {0};
12021
12022   opcode1 = bits (thumb_insn_r->arm_insn, 10, 12);
12023
12024   if (bit (thumb_insn_r->arm_insn, 12))
12025     {
12026       /* Handle load/store register offset.  */
12027       opcode2 = bits (thumb_insn_r->arm_insn, 9, 10);
12028       if (opcode2 >= 12 && opcode2 <= 15)
12029         {
12030           /* LDR(2), LDRB(2) , LDRH(2), LDRSB, LDRSH.  */
12031           reg_src1 = bits (thumb_insn_r->arm_insn,0, 2);
12032           record_buf[0] = reg_src1;
12033           thumb_insn_r->reg_rec_count = 1;
12034         }
12035       else if (opcode2 >= 8 && opcode2 <= 10)
12036         {
12037           /* STR(2), STRB(2), STRH(2) .  */
12038           reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12039           reg_src2 = bits (thumb_insn_r->arm_insn, 6, 8);
12040           regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval[0]);
12041           regcache_raw_read_unsigned (reg_cache, reg_src2, &u_regval[1]);
12042           if (8 == opcode2)
12043             record_buf_mem[0] = 4;    /* STR (2).  */
12044           else if (10 == opcode2)
12045             record_buf_mem[0] = 1;    /*  STRB (2).  */
12046           else if (9 == opcode2)
12047             record_buf_mem[0] = 2;    /* STRH (2).  */
12048           record_buf_mem[1] = u_regval[0] + u_regval[1];
12049           thumb_insn_r->mem_rec_count = 1;
12050         }
12051     }
12052   else if (bit (thumb_insn_r->arm_insn, 11))
12053     {
12054       /* Handle load from literal pool.  */
12055       /* LDR(3).  */
12056       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12057       record_buf[0] = reg_src1;
12058       thumb_insn_r->reg_rec_count = 1;
12059     }
12060   else if (opcode1)
12061     {
12062       opcode2 = bits (thumb_insn_r->arm_insn, 8, 9);
12063       opcode3 = bits (thumb_insn_r->arm_insn, 0, 2);
12064       if ((3 == opcode2) && (!opcode3))
12065         {
12066           /* Branch with exchange.  */
12067           record_buf[0] = ARM_PS_REGNUM;
12068           thumb_insn_r->reg_rec_count = 1;
12069         }
12070       else
12071         {
12072           /* Format 8; special data processing insns.  */
12073           reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12074           record_buf[0] = ARM_PS_REGNUM;
12075           record_buf[1] = reg_src1;
12076           thumb_insn_r->reg_rec_count = 2;
12077         }
12078     }
12079   else
12080     {
12081       /* Format 5; data processing insns.  */
12082       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12083       if (bit (thumb_insn_r->arm_insn, 7))
12084         {
12085           reg_src1 = reg_src1 + 8;
12086         }
12087       record_buf[0] = ARM_PS_REGNUM;
12088       record_buf[1] = reg_src1;
12089       thumb_insn_r->reg_rec_count = 2;
12090     }
12091
12092   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12093   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12094              record_buf_mem);
12095
12096   return 0;
12097 }
12098
12099 /* Handling opcode 001 insns.  */
12100
12101 static int
12102 thumb_record_ld_st_imm_offset (insn_decode_record *thumb_insn_r)
12103 {
12104   struct regcache *reg_cache = thumb_insn_r->regcache;
12105   uint32_t record_buf[8], record_buf_mem[8];
12106
12107   uint32_t reg_src1 = 0;
12108   uint32_t opcode = 0, immed_5 = 0;
12109
12110   ULONGEST u_regval = 0;
12111
12112   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12113
12114   if (opcode)
12115     {
12116       /* LDR(1).  */
12117       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12118       record_buf[0] = reg_src1;
12119       thumb_insn_r->reg_rec_count = 1;
12120     }
12121   else
12122     {
12123       /* STR(1).  */
12124       reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12125       immed_5 = bits (thumb_insn_r->arm_insn, 6, 10);
12126       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12127       record_buf_mem[0] = 4;
12128       record_buf_mem[1] = u_regval + (immed_5 * 4);
12129       thumb_insn_r->mem_rec_count = 1;
12130     }
12131
12132   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12133   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count, 
12134              record_buf_mem);
12135
12136   return 0;
12137 }
12138
12139 /* Handling opcode 100 insns.  */
12140
12141 static int
12142 thumb_record_ld_st_stack (insn_decode_record *thumb_insn_r)
12143 {
12144   struct regcache *reg_cache = thumb_insn_r->regcache;
12145   uint32_t record_buf[8], record_buf_mem[8];
12146
12147   uint32_t reg_src1 = 0;
12148   uint32_t opcode = 0, immed_8 = 0, immed_5 = 0;
12149
12150   ULONGEST u_regval = 0;
12151
12152   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12153
12154   if (3 == opcode)
12155     {
12156       /* LDR(4).  */
12157       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12158       record_buf[0] = reg_src1;
12159       thumb_insn_r->reg_rec_count = 1;
12160     }
12161   else if (1 == opcode)
12162     {
12163       /* LDRH(1).  */
12164       reg_src1 = bits (thumb_insn_r->arm_insn, 0, 2);
12165       record_buf[0] = reg_src1;
12166       thumb_insn_r->reg_rec_count = 1;
12167     }
12168   else if (2 == opcode)
12169     {
12170       /* STR(3).  */
12171       immed_8 = bits (thumb_insn_r->arm_insn, 0, 7);
12172       regcache_raw_read_unsigned (reg_cache, ARM_SP_REGNUM, &u_regval);
12173       record_buf_mem[0] = 4;
12174       record_buf_mem[1] = u_regval + (immed_8 * 4);
12175       thumb_insn_r->mem_rec_count = 1;
12176     }
12177   else if (0 == opcode)
12178     {
12179       /* STRH(1).  */
12180       immed_5 = bits (thumb_insn_r->arm_insn, 6, 10);
12181       reg_src1 = bits (thumb_insn_r->arm_insn, 3, 5);
12182       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12183       record_buf_mem[0] = 2;
12184       record_buf_mem[1] = u_regval + (immed_5 * 2);
12185       thumb_insn_r->mem_rec_count = 1;
12186     }
12187
12188   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12189   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12190              record_buf_mem);
12191
12192   return 0;
12193 }
12194
12195 /* Handling opcode 101 insns.  */
12196
12197 static int
12198 thumb_record_misc (insn_decode_record *thumb_insn_r)
12199 {
12200   struct regcache *reg_cache = thumb_insn_r->regcache;
12201
12202   uint32_t opcode = 0, opcode1 = 0, opcode2 = 0;
12203   uint32_t register_bits = 0, register_count = 0;
12204   uint32_t register_list[8] = {0}, index = 0, start_address = 0;
12205   uint32_t record_buf[24], record_buf_mem[48];
12206   uint32_t reg_src1;
12207
12208   ULONGEST u_regval = 0;
12209
12210   opcode = bits (thumb_insn_r->arm_insn, 11, 12);
12211   opcode1 = bits (thumb_insn_r->arm_insn, 8, 12);
12212   opcode2 = bits (thumb_insn_r->arm_insn, 9, 12);
12213
12214   if (14 == opcode2)
12215     {
12216       /* POP.  */
12217       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12218       while (register_bits)
12219         {
12220           if (register_bits & 0x00000001)
12221             register_list[register_count++] = 1;
12222           register_bits = register_bits >> 1;
12223         }
12224       record_buf[register_count] = ARM_PS_REGNUM;
12225       record_buf[register_count + 1] = ARM_SP_REGNUM;
12226       thumb_insn_r->reg_rec_count = register_count + 2;
12227       for (register_count = 0; register_count < 8; register_count++)
12228         {
12229           if  (register_list[register_count])
12230             {
12231               record_buf[index] = register_count;
12232               index++;
12233             }
12234         }
12235     }
12236   else if (10 == opcode2)
12237     {
12238       /* PUSH.  */
12239       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12240       regcache_raw_read_unsigned (reg_cache, ARM_PC_REGNUM, &u_regval);
12241       while (register_bits)
12242         {
12243           if (register_bits & 0x00000001)
12244             register_count++;
12245           register_bits = register_bits >> 1;
12246         }
12247       start_address = u_regval -  \
12248                   (4 * (bit (thumb_insn_r->arm_insn, 8) + register_count));
12249       thumb_insn_r->mem_rec_count = register_count;
12250       while (register_count)
12251         {
12252           record_buf_mem[(register_count * 2) - 1] = start_address;
12253           record_buf_mem[(register_count * 2) - 2] = 4;
12254           start_address = start_address + 4;
12255           register_count--;
12256         }
12257       record_buf[0] = ARM_SP_REGNUM;
12258       thumb_insn_r->reg_rec_count = 1;
12259     }
12260   else if (0x1E == opcode1)
12261     {
12262       /* BKPT insn.  */
12263       /* Handle enhanced software breakpoint insn, BKPT.  */
12264       /* CPSR is changed to be executed in ARM state,  disabling normal
12265          interrupts, entering abort mode.  */
12266       /* According to high vector configuration PC is set.  */
12267       /* User hits breakpoint and type reverse, in that case, we need to go back with 
12268       previous CPSR and Program Counter.  */
12269       record_buf[0] = ARM_PS_REGNUM;
12270       record_buf[1] = ARM_LR_REGNUM;
12271       thumb_insn_r->reg_rec_count = 2;
12272       /* We need to save SPSR value, which is not yet done.  */
12273       printf_unfiltered (_("Process record does not support instruction "
12274                            "0x%0x at address %s.\n"),
12275                            thumb_insn_r->arm_insn,
12276                            paddress (thumb_insn_r->gdbarch,
12277                            thumb_insn_r->this_addr));
12278       return -1;
12279     }
12280   else if ((0 == opcode) || (1 == opcode))
12281     {
12282       /* ADD(5), ADD(6).  */
12283       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12284       record_buf[0] = reg_src1;
12285       thumb_insn_r->reg_rec_count = 1;
12286     }
12287   else if (2 == opcode)
12288     {
12289       /* ADD(7), SUB(4).  */
12290       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12291       record_buf[0] = ARM_SP_REGNUM;
12292       thumb_insn_r->reg_rec_count = 1;
12293     }
12294
12295   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12296   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12297              record_buf_mem);
12298
12299   return 0;
12300 }
12301
12302 /* Handling opcode 110 insns.  */
12303
12304 static int
12305 thumb_record_ldm_stm_swi (insn_decode_record *thumb_insn_r)                
12306 {
12307   struct gdbarch_tdep *tdep = gdbarch_tdep (thumb_insn_r->gdbarch);
12308   struct regcache *reg_cache = thumb_insn_r->regcache;
12309
12310   uint32_t ret = 0; /* function return value: -1:record failure ;  0:success  */
12311   uint32_t reg_src1 = 0;
12312   uint32_t opcode1 = 0, opcode2 = 0, register_bits = 0, register_count = 0;
12313   uint32_t register_list[8] = {0}, index = 0, start_address = 0;
12314   uint32_t record_buf[24], record_buf_mem[48];
12315
12316   ULONGEST u_regval = 0;
12317
12318   opcode1 = bits (thumb_insn_r->arm_insn, 8, 12);
12319   opcode2 = bits (thumb_insn_r->arm_insn, 11, 12);
12320
12321   if (1 == opcode2)
12322     {
12323
12324       /* LDMIA.  */
12325       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12326       /* Get Rn.  */
12327       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12328       while (register_bits)
12329         {
12330           if (register_bits & 0x00000001)
12331             register_list[register_count++] = 1;
12332           register_bits = register_bits >> 1;
12333         }
12334       record_buf[register_count] = reg_src1;
12335       thumb_insn_r->reg_rec_count = register_count + 1;
12336       for (register_count = 0; register_count < 8; register_count++)
12337         {
12338           if (register_list[register_count])
12339             {
12340               record_buf[index] = register_count;
12341               index++;
12342             }
12343         }
12344     }
12345   else if (0 == opcode2)
12346     {
12347       /* It handles both STMIA.  */
12348       register_bits = bits (thumb_insn_r->arm_insn, 0, 7);
12349       /* Get Rn.  */
12350       reg_src1 = bits (thumb_insn_r->arm_insn, 8, 10);
12351       regcache_raw_read_unsigned (reg_cache, reg_src1, &u_regval);
12352       while (register_bits)
12353         {
12354           if (register_bits & 0x00000001)
12355             register_count++;
12356           register_bits = register_bits >> 1;
12357         }
12358       start_address = u_regval;
12359       thumb_insn_r->mem_rec_count = register_count;
12360       while (register_count)
12361         {
12362           record_buf_mem[(register_count * 2) - 1] = start_address;
12363           record_buf_mem[(register_count * 2) - 2] = 4;
12364           start_address = start_address + 4;
12365           register_count--;
12366         }
12367     }
12368   else if (0x1F == opcode1)
12369     {
12370         /* Handle arm syscall insn.  */
12371         if (tdep->arm_swi_record != NULL)
12372           {
12373             ret = tdep->arm_swi_record(reg_cache);
12374           }
12375         else
12376           {
12377             printf_unfiltered (_("no syscall record support\n"));
12378             return -1;
12379           }
12380     }
12381
12382   /* B (1), conditional branch is automatically taken care in process_record,
12383     as PC is saved there.  */
12384
12385   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12386   MEM_ALLOC (thumb_insn_r->arm_mems, thumb_insn_r->mem_rec_count,
12387              record_buf_mem);
12388
12389   return ret;
12390 }
12391
12392 /* Handling opcode 111 insns.  */
12393
12394 static int
12395 thumb_record_branch (insn_decode_record *thumb_insn_r)
12396 {
12397   uint32_t record_buf[8];
12398   uint32_t bits_h = 0;
12399
12400   bits_h = bits (thumb_insn_r->arm_insn, 11, 12);
12401
12402   if (2 == bits_h || 3 == bits_h)
12403     {
12404       /* BL */
12405       record_buf[0] = ARM_LR_REGNUM;
12406       thumb_insn_r->reg_rec_count = 1;
12407     }
12408   else if (1 == bits_h)
12409     {
12410       /* BLX(1). */
12411       record_buf[0] = ARM_PS_REGNUM;
12412       record_buf[1] = ARM_LR_REGNUM;
12413       thumb_insn_r->reg_rec_count = 2;
12414     }
12415
12416   /* B(2) is automatically taken care in process_record, as PC is 
12417      saved there.  */
12418
12419   REG_ALLOC (thumb_insn_r->arm_regs, thumb_insn_r->reg_rec_count, record_buf);
12420
12421   return 0;     
12422 }
12423
12424
12425 /* Extracts arm/thumb/thumb2 insn depending on the size, and returns 0 on success 
12426 and positive val on fauilure.  */
12427
12428 static int
12429 extract_arm_insn (insn_decode_record *insn_record, uint32_t insn_size)
12430 {
12431   gdb_byte buf[insn_size];
12432
12433   memset (&buf[0], 0, insn_size);
12434   
12435   if (target_read_memory (insn_record->this_addr, &buf[0], insn_size))
12436     return 1;
12437   insn_record->arm_insn = (uint32_t) extract_unsigned_integer (&buf[0],
12438                            insn_size, 
12439                            gdbarch_byte_order (insn_record->gdbarch));
12440   return 0;
12441 }
12442
12443 typedef int (*sti_arm_hdl_fp_t) (insn_decode_record*);
12444
12445 /* Decode arm/thumb insn depending on condition cods and opcodes; and
12446    dispatch it.  */
12447
12448 static int
12449 decode_insn (insn_decode_record *arm_record, record_type_t record_type,
12450                 uint32_t insn_size)
12451 {
12452
12453   /* (Starting from numerical 0); bits 25, 26, 27 decodes type of arm instruction.  */
12454   static const sti_arm_hdl_fp_t const arm_handle_insn[8] =                    
12455   {
12456     arm_record_data_proc_misc_ld_str,   /* 000.  */
12457     arm_record_data_proc_imm,           /* 001.  */
12458     arm_record_ld_st_imm_offset,        /* 010.  */
12459     arm_record_ld_st_reg_offset,        /* 011.  */
12460     arm_record_ld_st_multiple,          /* 100.  */
12461     arm_record_b_bl,                    /* 101.  */
12462     arm_record_coproc,                  /* 110.  */
12463     arm_record_coproc_data_proc         /* 111.  */
12464   };
12465
12466   /* (Starting from numerical 0); bits 13,14,15 decodes type of thumb instruction.  */
12467   static const sti_arm_hdl_fp_t const thumb_handle_insn[8] =
12468   { \
12469     thumb_record_shift_add_sub,        /* 000.  */
12470     thumb_record_add_sub_cmp_mov,      /* 001.  */
12471     thumb_record_ld_st_reg_offset,     /* 010.  */
12472     thumb_record_ld_st_imm_offset,     /* 011.  */
12473     thumb_record_ld_st_stack,          /* 100.  */
12474     thumb_record_misc,                 /* 101.  */
12475     thumb_record_ldm_stm_swi,          /* 110.  */
12476     thumb_record_branch                /* 111.  */
12477   };
12478
12479   uint32_t ret = 0;    /* return value: negative:failure   0:success.  */
12480   uint32_t insn_id = 0;
12481
12482   if (extract_arm_insn (arm_record, insn_size))
12483     {
12484       if (record_debug)
12485         {
12486           printf_unfiltered (_("Process record: error reading memory at "
12487                               "addr %s len = %d.\n"),
12488           paddress (arm_record->gdbarch, arm_record->this_addr), insn_size);        
12489         }
12490       return -1;
12491     }
12492   else if (ARM_RECORD == record_type)
12493     {
12494       arm_record->cond = bits (arm_record->arm_insn, 28, 31);
12495       insn_id = bits (arm_record->arm_insn, 25, 27);
12496       ret = arm_record_extension_space (arm_record);
12497       /* If this insn has fallen into extension space 
12498          then we need not decode it anymore.  */
12499       if (ret != -1 && !INSN_RECORDED(arm_record))
12500         {
12501           ret = arm_handle_insn[insn_id] (arm_record);
12502         }
12503     }
12504   else if (THUMB_RECORD == record_type)
12505     {
12506       /* As thumb does not have condition codes, we set negative.  */
12507       arm_record->cond = -1;
12508       insn_id = bits (arm_record->arm_insn, 13, 15);
12509       ret = thumb_handle_insn[insn_id] (arm_record);
12510     }
12511   else if (THUMB2_RECORD == record_type)
12512     {
12513       printf_unfiltered (_("Process record doesnt support thumb32 instruction "
12514                            "0x%0x at address %s.\n"),arm_record->arm_insn,
12515                            paddress (arm_record->gdbarch, 
12516                            arm_record->this_addr));
12517       ret = -1;
12518     }
12519   else
12520     {
12521       /* Throw assertion.  */
12522       gdb_assert_not_reached ("not a valid instruction, could not decode");
12523     }
12524
12525   return ret;
12526 }
12527
12528
12529 /* Cleans up local record registers and memory allocations.  */
12530
12531 static void 
12532 deallocate_reg_mem (insn_decode_record *record)
12533 {
12534   xfree (record->arm_regs);
12535   xfree (record->arm_mems);    
12536 }
12537
12538
12539 /* Parse the current instruction and record the values of the registers and    
12540    memory that will be changed in current instruction to record_arch_list".
12541    Return -1 if something is wrong.  */
12542
12543 int
12544 arm_process_record (struct gdbarch *gdbarch, struct regcache *regcache, 
12545                         CORE_ADDR insn_addr)
12546 {
12547
12548   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
12549   uint32_t no_of_rec = 0;
12550   uint32_t ret = 0;  /* return value: -1:record failure ;  0:success  */
12551   ULONGEST t_bit = 0, insn_id = 0;
12552
12553   ULONGEST u_regval = 0;
12554
12555   insn_decode_record arm_record;
12556
12557   memset (&arm_record, 0, sizeof (insn_decode_record));
12558   arm_record.regcache = regcache;
12559   arm_record.this_addr = insn_addr;
12560   arm_record.gdbarch = gdbarch;
12561
12562
12563   if (record_debug > 1)
12564     {
12565       fprintf_unfiltered (gdb_stdlog, "Process record: arm_process_record "
12566                                       "addr = %s\n",
12567       paddress (gdbarch, arm_record.this_addr));
12568     }
12569
12570   if (extract_arm_insn (&arm_record, 2))
12571     {
12572       if (record_debug)
12573         {
12574           printf_unfiltered (_("Process record: error reading memory at "
12575                              "addr %s len = %d.\n"),
12576                              paddress (arm_record.gdbarch, 
12577                              arm_record.this_addr), 2);
12578         }
12579       return -1;
12580     }
12581
12582   /* Check the insn, whether it is thumb or arm one.  */
12583
12584   t_bit = arm_psr_thumb_bit (arm_record.gdbarch);
12585   regcache_raw_read_unsigned (arm_record.regcache, ARM_PS_REGNUM, &u_regval);
12586
12587
12588   if (!(u_regval & t_bit))
12589     {
12590       /* We are decoding arm insn.  */
12591       ret = decode_insn (&arm_record, ARM_RECORD, ARM_INSN_SIZE_BYTES);
12592     }
12593   else
12594     {
12595       insn_id = bits (arm_record.arm_insn, 11, 15);
12596       /* is it thumb2 insn?  */
12597       if ((0x1D == insn_id) || (0x1E == insn_id) || (0x1F == insn_id))
12598         {
12599           ret = decode_insn (&arm_record, THUMB2_RECORD, 
12600                              THUMB2_INSN_SIZE_BYTES);
12601         }
12602       else
12603         {
12604           /* We are decoding thumb insn.  */
12605           ret = decode_insn (&arm_record, THUMB_RECORD, THUMB_INSN_SIZE_BYTES);
12606         }
12607     }
12608
12609   if (0 == ret)
12610     {
12611       /* Record registers.  */
12612       record_arch_list_add_reg (arm_record.regcache, ARM_PC_REGNUM);
12613       if (arm_record.arm_regs)
12614         {
12615           for (no_of_rec = 0; no_of_rec < arm_record.reg_rec_count; no_of_rec++)
12616             {
12617               if (record_arch_list_add_reg (arm_record.regcache , 
12618                                             arm_record.arm_regs[no_of_rec]))
12619               ret = -1;
12620             }
12621         }
12622       /* Record memories.  */
12623       if (arm_record.arm_mems)
12624         {
12625           for (no_of_rec = 0; no_of_rec < arm_record.mem_rec_count; no_of_rec++)
12626             {
12627               if (record_arch_list_add_mem 
12628                   ((CORE_ADDR)arm_record.arm_mems[no_of_rec].addr,
12629                   arm_record.arm_mems[no_of_rec].len))
12630                 ret = -1;
12631             }
12632         }
12633
12634       if (record_arch_list_add_end ())
12635         ret = -1;
12636     }
12637
12638
12639   deallocate_reg_mem (&arm_record);
12640
12641   return ret;
12642 }
12643