* amd64-tdep.c (amd64_push_dummy_call): Remove nested definition
[external/binutils.git] / gdb / amd64-tdep.c
1 /* Target-dependent code for AMD64.
2
3    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
4    2011 Free Software Foundation, Inc.
5
6    Contributed by Jiri Smid, SuSE Labs.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "opcode/i386.h"
25 #include "dis-asm.h"
26 #include "arch-utils.h"
27 #include "block.h"
28 #include "dummy-frame.h"
29 #include "frame.h"
30 #include "frame-base.h"
31 #include "frame-unwind.h"
32 #include "inferior.h"
33 #include "gdbcmd.h"
34 #include "gdbcore.h"
35 #include "objfiles.h"
36 #include "regcache.h"
37 #include "regset.h"
38 #include "symfile.h"
39 #include "disasm.h"
40 #include "gdb_assert.h"
41 #include "exceptions.h"
42 #include "amd64-tdep.h"
43 #include "i387-tdep.h"
44
45 #include "features/i386/amd64.c"
46 #include "features/i386/amd64-avx.c"
47
48 #include "ax.h"
49 #include "ax-gdb.h"
50
51 /* Note that the AMD64 architecture was previously known as x86-64.
52    The latter is (forever) engraved into the canonical system name as
53    returned by config.guess, and used as the name for the AMD64 port
54    of GNU/Linux.  The BSD's have renamed their ports to amd64; they
55    don't like to shout.  For GDB we prefer the amd64_-prefix over the
56    x86_64_-prefix since it's so much easier to type.  */
57
58 /* Register information.  */
59
60 static const char *amd64_register_names[] = 
61 {
62   "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp",
63
64   /* %r8 is indeed register number 8.  */
65   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
66   "rip", "eflags", "cs", "ss", "ds", "es", "fs", "gs",
67
68   /* %st0 is register number 24.  */
69   "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7",
70   "fctrl", "fstat", "ftag", "fiseg", "fioff", "foseg", "fooff", "fop",
71
72   /* %xmm0 is register number 40.  */
73   "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
74   "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
75   "mxcsr",
76 };
77
78 static const char *amd64_ymm_names[] = 
79 {
80   "ymm0", "ymm1", "ymm2", "ymm3",
81   "ymm4", "ymm5", "ymm6", "ymm7",
82   "ymm8", "ymm9", "ymm10", "ymm11",
83   "ymm12", "ymm13", "ymm14", "ymm15"
84 };
85
86 static const char *amd64_ymmh_names[] = 
87 {
88   "ymm0h", "ymm1h", "ymm2h", "ymm3h",
89   "ymm4h", "ymm5h", "ymm6h", "ymm7h",
90   "ymm8h", "ymm9h", "ymm10h", "ymm11h",
91   "ymm12h", "ymm13h", "ymm14h", "ymm15h"
92 };
93
94 /* The registers used to pass integer arguments during a function call.  */
95 static int amd64_dummy_call_integer_regs[] =
96 {
97   AMD64_RDI_REGNUM,             /* %rdi */
98   AMD64_RSI_REGNUM,             /* %rsi */
99   AMD64_RDX_REGNUM,             /* %rdx */
100   AMD64_RCX_REGNUM,             /* %rcx */
101   8,                            /* %r8 */
102   9                             /* %r9 */
103 };
104
105 /* DWARF Register Number Mapping as defined in the System V psABI,
106    section 3.6.  */
107
108 static int amd64_dwarf_regmap[] =
109 {
110   /* General Purpose Registers RAX, RDX, RCX, RBX, RSI, RDI.  */
111   AMD64_RAX_REGNUM, AMD64_RDX_REGNUM,
112   AMD64_RCX_REGNUM, AMD64_RBX_REGNUM,
113   AMD64_RSI_REGNUM, AMD64_RDI_REGNUM,
114
115   /* Frame Pointer Register RBP.  */
116   AMD64_RBP_REGNUM,
117
118   /* Stack Pointer Register RSP.  */
119   AMD64_RSP_REGNUM,
120
121   /* Extended Integer Registers 8 - 15.  */
122   8, 9, 10, 11, 12, 13, 14, 15,
123
124   /* Return Address RA.  Mapped to RIP.  */
125   AMD64_RIP_REGNUM,
126
127   /* SSE Registers 0 - 7.  */
128   AMD64_XMM0_REGNUM + 0, AMD64_XMM1_REGNUM,
129   AMD64_XMM0_REGNUM + 2, AMD64_XMM0_REGNUM + 3,
130   AMD64_XMM0_REGNUM + 4, AMD64_XMM0_REGNUM + 5,
131   AMD64_XMM0_REGNUM + 6, AMD64_XMM0_REGNUM + 7,
132
133   /* Extended SSE Registers 8 - 15.  */
134   AMD64_XMM0_REGNUM + 8, AMD64_XMM0_REGNUM + 9,
135   AMD64_XMM0_REGNUM + 10, AMD64_XMM0_REGNUM + 11,
136   AMD64_XMM0_REGNUM + 12, AMD64_XMM0_REGNUM + 13,
137   AMD64_XMM0_REGNUM + 14, AMD64_XMM0_REGNUM + 15,
138
139   /* Floating Point Registers 0-7.  */
140   AMD64_ST0_REGNUM + 0, AMD64_ST0_REGNUM + 1,
141   AMD64_ST0_REGNUM + 2, AMD64_ST0_REGNUM + 3,
142   AMD64_ST0_REGNUM + 4, AMD64_ST0_REGNUM + 5,
143   AMD64_ST0_REGNUM + 6, AMD64_ST0_REGNUM + 7,
144   
145   /* Control and Status Flags Register.  */
146   AMD64_EFLAGS_REGNUM,
147
148   /* Selector Registers.  */
149   AMD64_ES_REGNUM,
150   AMD64_CS_REGNUM,
151   AMD64_SS_REGNUM,
152   AMD64_DS_REGNUM,
153   AMD64_FS_REGNUM,
154   AMD64_GS_REGNUM,
155   -1,
156   -1,
157
158   /* Segment Base Address Registers.  */
159   -1,
160   -1,
161   -1,
162   -1,
163
164   /* Special Selector Registers.  */
165   -1,
166   -1,
167
168   /* Floating Point Control Registers.  */
169   AMD64_MXCSR_REGNUM,
170   AMD64_FCTRL_REGNUM,
171   AMD64_FSTAT_REGNUM
172 };
173
174 static const int amd64_dwarf_regmap_len =
175   (sizeof (amd64_dwarf_regmap) / sizeof (amd64_dwarf_regmap[0]));
176
177 /* Convert DWARF register number REG to the appropriate register
178    number used by GDB.  */
179
180 static int
181 amd64_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
182 {
183   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
184   int ymm0_regnum = tdep->ymm0_regnum;
185   int regnum = -1;
186
187   if (reg >= 0 && reg < amd64_dwarf_regmap_len)
188     regnum = amd64_dwarf_regmap[reg];
189
190   if (regnum == -1)
191     warning (_("Unmapped DWARF Register #%d encountered."), reg);
192   else if (ymm0_regnum >= 0
193            && i386_xmm_regnum_p (gdbarch, regnum))
194     regnum += ymm0_regnum - I387_XMM0_REGNUM (tdep);
195
196   return regnum;
197 }
198
199 /* Map architectural register numbers to gdb register numbers.  */
200
201 static const int amd64_arch_regmap[16] =
202 {
203   AMD64_RAX_REGNUM,     /* %rax */
204   AMD64_RCX_REGNUM,     /* %rcx */
205   AMD64_RDX_REGNUM,     /* %rdx */
206   AMD64_RBX_REGNUM,     /* %rbx */
207   AMD64_RSP_REGNUM,     /* %rsp */
208   AMD64_RBP_REGNUM,     /* %rbp */
209   AMD64_RSI_REGNUM,     /* %rsi */
210   AMD64_RDI_REGNUM,     /* %rdi */
211   AMD64_R8_REGNUM,      /* %r8 */
212   AMD64_R9_REGNUM,      /* %r9 */
213   AMD64_R10_REGNUM,     /* %r10 */
214   AMD64_R11_REGNUM,     /* %r11 */
215   AMD64_R12_REGNUM,     /* %r12 */
216   AMD64_R13_REGNUM,     /* %r13 */
217   AMD64_R14_REGNUM,     /* %r14 */
218   AMD64_R15_REGNUM      /* %r15 */
219 };
220
221 static const int amd64_arch_regmap_len =
222   (sizeof (amd64_arch_regmap) / sizeof (amd64_arch_regmap[0]));
223
224 /* Convert architectural register number REG to the appropriate register
225    number used by GDB.  */
226
227 static int
228 amd64_arch_reg_to_regnum (int reg)
229 {
230   gdb_assert (reg >= 0 && reg < amd64_arch_regmap_len);
231
232   return amd64_arch_regmap[reg];
233 }
234
235 /* Register names for byte pseudo-registers.  */
236
237 static const char *amd64_byte_names[] =
238 {
239   "al", "bl", "cl", "dl", "sil", "dil", "bpl", "spl",
240   "r8l", "r9l", "r10l", "r11l", "r12l", "r13l", "r14l", "r15l",
241   "ah", "bh", "ch", "dh"
242 };
243
244 /* Number of lower byte registers.  */
245 #define AMD64_NUM_LOWER_BYTE_REGS 16
246
247 /* Register names for word pseudo-registers.  */
248
249 static const char *amd64_word_names[] =
250 {
251   "ax", "bx", "cx", "dx", "si", "di", "bp", "", 
252   "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"
253 };
254
255 /* Register names for dword pseudo-registers.  */
256
257 static const char *amd64_dword_names[] =
258 {
259   "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", 
260   "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"
261 };
262
263 /* Return the name of register REGNUM.  */
264
265 static const char *
266 amd64_pseudo_register_name (struct gdbarch *gdbarch, int regnum)
267 {
268   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
269   if (i386_byte_regnum_p (gdbarch, regnum))
270     return amd64_byte_names[regnum - tdep->al_regnum];
271   else if (i386_ymm_regnum_p (gdbarch, regnum))
272     return amd64_ymm_names[regnum - tdep->ymm0_regnum];
273   else if (i386_word_regnum_p (gdbarch, regnum))
274     return amd64_word_names[regnum - tdep->ax_regnum];
275   else if (i386_dword_regnum_p (gdbarch, regnum))
276     return amd64_dword_names[regnum - tdep->eax_regnum];
277   else
278     return i386_pseudo_register_name (gdbarch, regnum);
279 }
280
281 static struct value *
282 amd64_pseudo_register_read_value (struct gdbarch *gdbarch,
283                                   struct regcache *regcache,
284                                   int regnum)
285 {
286   gdb_byte raw_buf[MAX_REGISTER_SIZE];
287   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
288   enum register_status status;
289   struct value *result_value;
290   gdb_byte *buf;
291
292   result_value = allocate_value (register_type (gdbarch, regnum));
293   VALUE_LVAL (result_value) = lval_register;
294   VALUE_REGNUM (result_value) = regnum;
295   buf = value_contents_raw (result_value);
296
297   if (i386_byte_regnum_p (gdbarch, regnum))
298     {
299       int gpnum = regnum - tdep->al_regnum;
300
301       /* Extract (always little endian).  */
302       if (gpnum >= AMD64_NUM_LOWER_BYTE_REGS)
303         {
304           /* Special handling for AH, BH, CH, DH.  */
305           status = regcache_raw_read (regcache,
306                                       gpnum - AMD64_NUM_LOWER_BYTE_REGS,
307                                       raw_buf);
308           if (status == REG_VALID)
309             memcpy (buf, raw_buf + 1, 1);
310           else
311             mark_value_bytes_unavailable (result_value, 0,
312                                           TYPE_LENGTH (value_type (result_value)));
313         }
314       else
315         {
316           status = regcache_raw_read (regcache, gpnum, raw_buf);
317           if (status == REG_VALID)
318             memcpy (buf, raw_buf, 1);
319           else
320             mark_value_bytes_unavailable (result_value, 0,
321                                           TYPE_LENGTH (value_type (result_value)));
322         }
323     }
324   else if (i386_dword_regnum_p (gdbarch, regnum))
325     {
326       int gpnum = regnum - tdep->eax_regnum;
327       /* Extract (always little endian).  */
328       status = regcache_raw_read (regcache, gpnum, raw_buf);
329       if (status == REG_VALID)
330         memcpy (buf, raw_buf, 4);
331       else
332         mark_value_bytes_unavailable (result_value, 0,
333                                       TYPE_LENGTH (value_type (result_value)));
334     }
335   else
336     i386_pseudo_register_read_into_value (gdbarch, regcache, regnum,
337                                           result_value);
338
339   return result_value;
340 }
341
342 static void
343 amd64_pseudo_register_write (struct gdbarch *gdbarch,
344                              struct regcache *regcache,
345                              int regnum, const gdb_byte *buf)
346 {
347   gdb_byte raw_buf[MAX_REGISTER_SIZE];
348   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
349
350   if (i386_byte_regnum_p (gdbarch, regnum))
351     {
352       int gpnum = regnum - tdep->al_regnum;
353
354       if (gpnum >= AMD64_NUM_LOWER_BYTE_REGS)
355         {
356           /* Read ... AH, BH, CH, DH.  */
357           regcache_raw_read (regcache,
358                              gpnum - AMD64_NUM_LOWER_BYTE_REGS, raw_buf);
359           /* ... Modify ... (always little endian).  */
360           memcpy (raw_buf + 1, buf, 1);
361           /* ... Write.  */
362           regcache_raw_write (regcache,
363                               gpnum - AMD64_NUM_LOWER_BYTE_REGS, raw_buf);
364         }
365       else
366         {
367           /* Read ...  */
368           regcache_raw_read (regcache, gpnum, raw_buf);
369           /* ... Modify ... (always little endian).  */
370           memcpy (raw_buf, buf, 1);
371           /* ... Write.  */
372           regcache_raw_write (regcache, gpnum, raw_buf);
373         }
374     }
375   else if (i386_dword_regnum_p (gdbarch, regnum))
376     {
377       int gpnum = regnum - tdep->eax_regnum;
378
379       /* Read ...  */
380       regcache_raw_read (regcache, gpnum, raw_buf);
381       /* ... Modify ... (always little endian).  */
382       memcpy (raw_buf, buf, 4);
383       /* ... Write.  */
384       regcache_raw_write (regcache, gpnum, raw_buf);
385     }
386   else
387     i386_pseudo_register_write (gdbarch, regcache, regnum, buf);
388 }
389
390 \f
391
392 /* Return the union class of CLASS1 and CLASS2.  See the psABI for
393    details.  */
394
395 static enum amd64_reg_class
396 amd64_merge_classes (enum amd64_reg_class class1, enum amd64_reg_class class2)
397 {
398   /* Rule (a): If both classes are equal, this is the resulting class.  */
399   if (class1 == class2)
400     return class1;
401
402   /* Rule (b): If one of the classes is NO_CLASS, the resulting class
403      is the other class.  */
404   if (class1 == AMD64_NO_CLASS)
405     return class2;
406   if (class2 == AMD64_NO_CLASS)
407     return class1;
408
409   /* Rule (c): If one of the classes is MEMORY, the result is MEMORY.  */
410   if (class1 == AMD64_MEMORY || class2 == AMD64_MEMORY)
411     return AMD64_MEMORY;
412
413   /* Rule (d): If one of the classes is INTEGER, the result is INTEGER.  */
414   if (class1 == AMD64_INTEGER || class2 == AMD64_INTEGER)
415     return AMD64_INTEGER;
416
417   /* Rule (e): If one of the classes is X87, X87UP, COMPLEX_X87 class,
418      MEMORY is used as class.  */
419   if (class1 == AMD64_X87 || class1 == AMD64_X87UP
420       || class1 == AMD64_COMPLEX_X87 || class2 == AMD64_X87
421       || class2 == AMD64_X87UP || class2 == AMD64_COMPLEX_X87)
422     return AMD64_MEMORY;
423
424   /* Rule (f): Otherwise class SSE is used.  */
425   return AMD64_SSE;
426 }
427
428 /* Return non-zero if TYPE is a non-POD structure or union type.  */
429
430 static int
431 amd64_non_pod_p (struct type *type)
432 {
433   /* ??? A class with a base class certainly isn't POD, but does this
434      catch all non-POD structure types?  */
435   if (TYPE_CODE (type) == TYPE_CODE_STRUCT && TYPE_N_BASECLASSES (type) > 0)
436     return 1;
437
438   return 0;
439 }
440
441 /* Classify TYPE according to the rules for aggregate (structures and
442    arrays) and union types, and store the result in CLASS.  */
443
444 static void
445 amd64_classify_aggregate (struct type *type, enum amd64_reg_class class[2])
446 {
447   int len = TYPE_LENGTH (type);
448
449   /* 1. If the size of an object is larger than two eightbytes, or in
450         C++, is a non-POD structure or union type, or contains
451         unaligned fields, it has class memory.  */
452   if (len > 16 || amd64_non_pod_p (type))
453     {
454       class[0] = class[1] = AMD64_MEMORY;
455       return;
456     }
457
458   /* 2. Both eightbytes get initialized to class NO_CLASS.  */
459   class[0] = class[1] = AMD64_NO_CLASS;
460
461   /* 3. Each field of an object is classified recursively so that
462         always two fields are considered. The resulting class is
463         calculated according to the classes of the fields in the
464         eightbyte: */
465
466   if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
467     {
468       struct type *subtype = check_typedef (TYPE_TARGET_TYPE (type));
469
470       /* All fields in an array have the same type.  */
471       amd64_classify (subtype, class);
472       if (len > 8 && class[1] == AMD64_NO_CLASS)
473         class[1] = class[0];
474     }
475   else
476     {
477       int i;
478
479       /* Structure or union.  */
480       gdb_assert (TYPE_CODE (type) == TYPE_CODE_STRUCT
481                   || TYPE_CODE (type) == TYPE_CODE_UNION);
482
483       for (i = 0; i < TYPE_NFIELDS (type); i++)
484         {
485           struct type *subtype = check_typedef (TYPE_FIELD_TYPE (type, i));
486           int pos = TYPE_FIELD_BITPOS (type, i) / 64;
487           enum amd64_reg_class subclass[2];
488           int bitsize = TYPE_FIELD_BITSIZE (type, i);
489           int endpos;
490
491           if (bitsize == 0)
492             bitsize = TYPE_LENGTH (subtype) * 8;
493           endpos = (TYPE_FIELD_BITPOS (type, i) + bitsize - 1) / 64;
494
495           /* Ignore static fields.  */
496           if (field_is_static (&TYPE_FIELD (type, i)))
497             continue;
498
499           gdb_assert (pos == 0 || pos == 1);
500
501           amd64_classify (subtype, subclass);
502           class[pos] = amd64_merge_classes (class[pos], subclass[0]);
503           if (bitsize <= 64 && pos == 0 && endpos == 1)
504             /* This is a bit of an odd case:  We have a field that would
505                normally fit in one of the two eightbytes, except that
506                it is placed in a way that this field straddles them.
507                This has been seen with a structure containing an array.
508
509                The ABI is a bit unclear in this case, but we assume that
510                this field's class (stored in subclass[0]) must also be merged
511                into class[1].  In other words, our field has a piece stored
512                in the second eight-byte, and thus its class applies to
513                the second eight-byte as well.
514
515                In the case where the field length exceeds 8 bytes,
516                it should not be necessary to merge the field class
517                into class[1].  As LEN > 8, subclass[1] is necessarily
518                different from AMD64_NO_CLASS.  If subclass[1] is equal
519                to subclass[0], then the normal class[1]/subclass[1]
520                merging will take care of everything.  For subclass[1]
521                to be different from subclass[0], I can only see the case
522                where we have a SSE/SSEUP or X87/X87UP pair, which both
523                use up all 16 bytes of the aggregate, and are already
524                handled just fine (because each portion sits on its own
525                8-byte).  */
526             class[1] = amd64_merge_classes (class[1], subclass[0]);
527           if (pos == 0)
528             class[1] = amd64_merge_classes (class[1], subclass[1]);
529         }
530     }
531
532   /* 4. Then a post merger cleanup is done:  */
533
534   /* Rule (a): If one of the classes is MEMORY, the whole argument is
535      passed in memory.  */
536   if (class[0] == AMD64_MEMORY || class[1] == AMD64_MEMORY)
537     class[0] = class[1] = AMD64_MEMORY;
538
539   /* Rule (b): If SSEUP is not preceded by SSE, it is converted to
540      SSE.  */
541   if (class[0] == AMD64_SSEUP)
542     class[0] = AMD64_SSE;
543   if (class[1] == AMD64_SSEUP && class[0] != AMD64_SSE)
544     class[1] = AMD64_SSE;
545 }
546
547 /* Classify TYPE, and store the result in CLASS.  */
548
549 void
550 amd64_classify (struct type *type, enum amd64_reg_class class[2])
551 {
552   enum type_code code = TYPE_CODE (type);
553   int len = TYPE_LENGTH (type);
554
555   class[0] = class[1] = AMD64_NO_CLASS;
556
557   /* Arguments of types (signed and unsigned) _Bool, char, short, int,
558      long, long long, and pointers are in the INTEGER class.  Similarly,
559      range types, used by languages such as Ada, are also in the INTEGER
560      class.  */
561   if ((code == TYPE_CODE_INT || code == TYPE_CODE_ENUM
562        || code == TYPE_CODE_BOOL || code == TYPE_CODE_RANGE
563        || code == TYPE_CODE_CHAR
564        || code == TYPE_CODE_PTR || code == TYPE_CODE_REF)
565       && (len == 1 || len == 2 || len == 4 || len == 8))
566     class[0] = AMD64_INTEGER;
567
568   /* Arguments of types float, double, _Decimal32, _Decimal64 and __m64
569      are in class SSE.  */
570   else if ((code == TYPE_CODE_FLT || code == TYPE_CODE_DECFLOAT)
571            && (len == 4 || len == 8))
572     /* FIXME: __m64 .  */
573     class[0] = AMD64_SSE;
574
575   /* Arguments of types __float128, _Decimal128 and __m128 are split into
576      two halves.  The least significant ones belong to class SSE, the most
577      significant one to class SSEUP.  */
578   else if (code == TYPE_CODE_DECFLOAT && len == 16)
579     /* FIXME: __float128, __m128.  */
580     class[0] = AMD64_SSE, class[1] = AMD64_SSEUP;
581
582   /* The 64-bit mantissa of arguments of type long double belongs to
583      class X87, the 16-bit exponent plus 6 bytes of padding belongs to
584      class X87UP.  */
585   else if (code == TYPE_CODE_FLT && len == 16)
586     /* Class X87 and X87UP.  */
587     class[0] = AMD64_X87, class[1] = AMD64_X87UP;
588
589   /* Aggregates.  */
590   else if (code == TYPE_CODE_ARRAY || code == TYPE_CODE_STRUCT
591            || code == TYPE_CODE_UNION)
592     amd64_classify_aggregate (type, class);
593 }
594
595 static enum return_value_convention
596 amd64_return_value (struct gdbarch *gdbarch, struct type *func_type,
597                     struct type *type, struct regcache *regcache,
598                     gdb_byte *readbuf, const gdb_byte *writebuf)
599 {
600   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
601   enum amd64_reg_class class[2];
602   int len = TYPE_LENGTH (type);
603   static int integer_regnum[] = { AMD64_RAX_REGNUM, AMD64_RDX_REGNUM };
604   static int sse_regnum[] = { AMD64_XMM0_REGNUM, AMD64_XMM1_REGNUM };
605   int integer_reg = 0;
606   int sse_reg = 0;
607   int i;
608
609   gdb_assert (!(readbuf && writebuf));
610   gdb_assert (tdep->classify);
611
612   /* 1. Classify the return type with the classification algorithm.  */
613   tdep->classify (type, class);
614
615   /* 2. If the type has class MEMORY, then the caller provides space
616      for the return value and passes the address of this storage in
617      %rdi as if it were the first argument to the function.  In effect,
618      this address becomes a hidden first argument.
619
620      On return %rax will contain the address that has been passed in
621      by the caller in %rdi.  */
622   if (class[0] == AMD64_MEMORY)
623     {
624       /* As indicated by the comment above, the ABI guarantees that we
625          can always find the return value just after the function has
626          returned.  */
627
628       if (readbuf)
629         {
630           ULONGEST addr;
631
632           regcache_raw_read_unsigned (regcache, AMD64_RAX_REGNUM, &addr);
633           read_memory (addr, readbuf, TYPE_LENGTH (type));
634         }
635
636       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
637     }
638
639   gdb_assert (class[1] != AMD64_MEMORY);
640   gdb_assert (len <= 16);
641
642   for (i = 0; len > 0; i++, len -= 8)
643     {
644       int regnum = -1;
645       int offset = 0;
646
647       switch (class[i])
648         {
649         case AMD64_INTEGER:
650           /* 3. If the class is INTEGER, the next available register
651              of the sequence %rax, %rdx is used.  */
652           regnum = integer_regnum[integer_reg++];
653           break;
654
655         case AMD64_SSE:
656           /* 4. If the class is SSE, the next available SSE register
657              of the sequence %xmm0, %xmm1 is used.  */
658           regnum = sse_regnum[sse_reg++];
659           break;
660
661         case AMD64_SSEUP:
662           /* 5. If the class is SSEUP, the eightbyte is passed in the
663              upper half of the last used SSE register.  */
664           gdb_assert (sse_reg > 0);
665           regnum = sse_regnum[sse_reg - 1];
666           offset = 8;
667           break;
668
669         case AMD64_X87:
670           /* 6. If the class is X87, the value is returned on the X87
671              stack in %st0 as 80-bit x87 number.  */
672           regnum = AMD64_ST0_REGNUM;
673           if (writebuf)
674             i387_return_value (gdbarch, regcache);
675           break;
676
677         case AMD64_X87UP:
678           /* 7. If the class is X87UP, the value is returned together
679              with the previous X87 value in %st0.  */
680           gdb_assert (i > 0 && class[0] == AMD64_X87);
681           regnum = AMD64_ST0_REGNUM;
682           offset = 8;
683           len = 2;
684           break;
685
686         case AMD64_NO_CLASS:
687           continue;
688
689         default:
690           gdb_assert (!"Unexpected register class.");
691         }
692
693       gdb_assert (regnum != -1);
694
695       if (readbuf)
696         regcache_raw_read_part (regcache, regnum, offset, min (len, 8),
697                                 readbuf + i * 8);
698       if (writebuf)
699         regcache_raw_write_part (regcache, regnum, offset, min (len, 8),
700                                  writebuf + i * 8);
701     }
702
703   return RETURN_VALUE_REGISTER_CONVENTION;
704 }
705 \f
706
707 static CORE_ADDR
708 amd64_push_arguments (struct regcache *regcache, int nargs,
709                       struct value **args, CORE_ADDR sp, int struct_return)
710 {
711   struct gdbarch *gdbarch = get_regcache_arch (regcache);
712   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
713   int *integer_regs = tdep->call_dummy_integer_regs;
714   int num_integer_regs = tdep->call_dummy_num_integer_regs;
715
716   static int sse_regnum[] =
717   {
718     /* %xmm0 ... %xmm7 */
719     AMD64_XMM0_REGNUM + 0, AMD64_XMM1_REGNUM,
720     AMD64_XMM0_REGNUM + 2, AMD64_XMM0_REGNUM + 3,
721     AMD64_XMM0_REGNUM + 4, AMD64_XMM0_REGNUM + 5,
722     AMD64_XMM0_REGNUM + 6, AMD64_XMM0_REGNUM + 7,
723   };
724   struct value **stack_args = alloca (nargs * sizeof (struct value *));
725   /* An array that mirrors the stack_args array.  For all arguments
726      that are passed by MEMORY, if that argument's address also needs
727      to be stored in a register, the ARG_ADDR_REGNO array will contain
728      that register number (or a negative value otherwise).  */
729   int *arg_addr_regno = alloca (nargs * sizeof (int));
730   int num_stack_args = 0;
731   int num_elements = 0;
732   int element = 0;
733   int integer_reg = 0;
734   int sse_reg = 0;
735   int i;
736
737   gdb_assert (tdep->classify);
738
739   /* Reserve a register for the "hidden" argument.  */
740   if (struct_return)
741     integer_reg++;
742
743   for (i = 0; i < nargs; i++)
744     {
745       struct type *type = value_type (args[i]);
746       int len = TYPE_LENGTH (type);
747       enum amd64_reg_class class[2];
748       int needed_integer_regs = 0;
749       int needed_sse_regs = 0;
750       int j;
751
752       /* Classify argument.  */
753       tdep->classify (type, class);
754
755       /* Calculate the number of integer and SSE registers needed for
756          this argument.  */
757       for (j = 0; j < 2; j++)
758         {
759           if (class[j] == AMD64_INTEGER)
760             needed_integer_regs++;
761           else if (class[j] == AMD64_SSE)
762             needed_sse_regs++;
763         }
764
765       /* Check whether enough registers are available, and if the
766          argument should be passed in registers at all.  */
767       if (integer_reg + needed_integer_regs > num_integer_regs
768           || sse_reg + needed_sse_regs > ARRAY_SIZE (sse_regnum)
769           || (needed_integer_regs == 0 && needed_sse_regs == 0))
770         {
771           /* The argument will be passed on the stack.  */
772           num_elements += ((len + 7) / 8);
773           stack_args[num_stack_args] = args[i];
774           /* If this is an AMD64_MEMORY argument whose address must also
775              be passed in one of the integer registers, reserve that
776              register and associate this value to that register so that
777              we can store the argument address as soon as we know it.  */
778           if (class[0] == AMD64_MEMORY
779               && tdep->memory_args_by_pointer
780               && integer_reg < tdep->call_dummy_num_integer_regs)
781             arg_addr_regno[num_stack_args] =
782               tdep->call_dummy_integer_regs[integer_reg++];
783           else
784             arg_addr_regno[num_stack_args] = -1;
785           num_stack_args++;
786         }
787       else
788         {
789           /* The argument will be passed in registers.  */
790           const gdb_byte *valbuf = value_contents (args[i]);
791           gdb_byte buf[8];
792
793           gdb_assert (len <= 16);
794
795           for (j = 0; len > 0; j++, len -= 8)
796             {
797               int regnum = -1;
798               int offset = 0;
799
800               switch (class[j])
801                 {
802                 case AMD64_INTEGER:
803                   regnum = integer_regs[integer_reg++];
804                   break;
805
806                 case AMD64_SSE:
807                   regnum = sse_regnum[sse_reg++];
808                   break;
809
810                 case AMD64_SSEUP:
811                   gdb_assert (sse_reg > 0);
812                   regnum = sse_regnum[sse_reg - 1];
813                   offset = 8;
814                   break;
815
816                 default:
817                   gdb_assert (!"Unexpected register class.");
818                 }
819
820               gdb_assert (regnum != -1);
821               memset (buf, 0, sizeof buf);
822               memcpy (buf, valbuf + j * 8, min (len, 8));
823               regcache_raw_write_part (regcache, regnum, offset, 8, buf);
824             }
825         }
826     }
827
828   /* Allocate space for the arguments on the stack.  */
829   sp -= num_elements * 8;
830
831   /* The psABI says that "The end of the input argument area shall be
832      aligned on a 16 byte boundary."  */
833   sp &= ~0xf;
834
835   /* Write out the arguments to the stack.  */
836   for (i = 0; i < num_stack_args; i++)
837     {
838       struct type *type = value_type (stack_args[i]);
839       const gdb_byte *valbuf = value_contents (stack_args[i]);
840       int len = TYPE_LENGTH (type);
841       CORE_ADDR arg_addr = sp + element * 8;
842
843       write_memory (arg_addr, valbuf, len);
844       if (arg_addr_regno[i] >= 0)
845         {
846           /* We also need to store the address of that argument in
847              the given register.  */
848           gdb_byte buf[8];
849           enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
850
851           store_unsigned_integer (buf, 8, byte_order, arg_addr);
852           regcache_cooked_write (regcache, arg_addr_regno[i], buf);
853         }
854       element += ((len + 7) / 8);
855     }
856
857   /* The psABI says that "For calls that may call functions that use
858      varargs or stdargs (prototype-less calls or calls to functions
859      containing ellipsis (...) in the declaration) %al is used as
860      hidden argument to specify the number of SSE registers used.  */
861   regcache_raw_write_unsigned (regcache, AMD64_RAX_REGNUM, sse_reg);
862   return sp; 
863 }
864
865 static CORE_ADDR
866 amd64_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
867                        struct regcache *regcache, CORE_ADDR bp_addr,
868                        int nargs, struct value **args,  CORE_ADDR sp,
869                        int struct_return, CORE_ADDR struct_addr)
870 {
871   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
872   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
873   gdb_byte buf[8];
874
875   /* Pass arguments.  */
876   sp = amd64_push_arguments (regcache, nargs, args, sp, struct_return);
877
878   /* Pass "hidden" argument".  */
879   if (struct_return)
880     {
881       /* The "hidden" argument is passed throught the first argument
882          register.  */
883       const int arg_regnum = tdep->call_dummy_integer_regs[0];
884
885       store_unsigned_integer (buf, 8, byte_order, struct_addr);
886       regcache_cooked_write (regcache, arg_regnum, buf);
887     }
888
889   /* Reserve some memory on the stack for the integer-parameter registers,
890      if required by the ABI.  */
891   if (tdep->integer_param_regs_saved_in_caller_frame)
892     sp -= tdep->call_dummy_num_integer_regs * 8;
893
894   /* Store return address.  */
895   sp -= 8;
896   store_unsigned_integer (buf, 8, byte_order, bp_addr);
897   write_memory (sp, buf, 8);
898
899   /* Finally, update the stack pointer...  */
900   store_unsigned_integer (buf, 8, byte_order, sp);
901   regcache_cooked_write (regcache, AMD64_RSP_REGNUM, buf);
902
903   /* ...and fake a frame pointer.  */
904   regcache_cooked_write (regcache, AMD64_RBP_REGNUM, buf);
905
906   return sp + 16;
907 }
908 \f
909 /* Displaced instruction handling.  */
910
911 /* A partially decoded instruction.
912    This contains enough details for displaced stepping purposes.  */
913
914 struct amd64_insn
915 {
916   /* The number of opcode bytes.  */
917   int opcode_len;
918   /* The offset of the rex prefix or -1 if not present.  */
919   int rex_offset;
920   /* The offset to the first opcode byte.  */
921   int opcode_offset;
922   /* The offset to the modrm byte or -1 if not present.  */
923   int modrm_offset;
924
925   /* The raw instruction.  */
926   gdb_byte *raw_insn;
927 };
928
929 struct displaced_step_closure
930 {
931   /* For rip-relative insns, saved copy of the reg we use instead of %rip.  */
932   int tmp_used;
933   int tmp_regno;
934   ULONGEST tmp_save;
935
936   /* Details of the instruction.  */
937   struct amd64_insn insn_details;
938
939   /* Amount of space allocated to insn_buf.  */
940   int max_len;
941
942   /* The possibly modified insn.
943      This is a variable-length field.  */
944   gdb_byte insn_buf[1];
945 };
946
947 /* WARNING: Keep onebyte_has_modrm, twobyte_has_modrm in sync with
948    ../opcodes/i386-dis.c (until libopcodes exports them, or an alternative,
949    at which point delete these in favor of libopcodes' versions).  */
950
951 static const unsigned char onebyte_has_modrm[256] = {
952   /*       0 1 2 3 4 5 6 7 8 9 a b c d e f        */
953   /*       -------------------------------        */
954   /* 00 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 00 */
955   /* 10 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 10 */
956   /* 20 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 20 */
957   /* 30 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 30 */
958   /* 40 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 40 */
959   /* 50 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 50 */
960   /* 60 */ 0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0, /* 60 */
961   /* 70 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 70 */
962   /* 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 80 */
963   /* 90 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 90 */
964   /* a0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* a0 */
965   /* b0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* b0 */
966   /* c0 */ 1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0, /* c0 */
967   /* d0 */ 1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1, /* d0 */
968   /* e0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* e0 */
969   /* f0 */ 0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1  /* f0 */
970   /*       -------------------------------        */
971   /*       0 1 2 3 4 5 6 7 8 9 a b c d e f        */
972 };
973
974 static const unsigned char twobyte_has_modrm[256] = {
975   /*       0 1 2 3 4 5 6 7 8 9 a b c d e f        */
976   /*       -------------------------------        */
977   /* 00 */ 1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,1, /* 0f */
978   /* 10 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 1f */
979   /* 20 */ 1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1, /* 2f */
980   /* 30 */ 0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0, /* 3f */
981   /* 40 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 4f */
982   /* 50 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 5f */
983   /* 60 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 6f */
984   /* 70 */ 1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1, /* 7f */
985   /* 80 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 8f */
986   /* 90 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 9f */
987   /* a0 */ 0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,1, /* af */
988   /* b0 */ 1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1, /* bf */
989   /* c0 */ 1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0, /* cf */
990   /* d0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* df */
991   /* e0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* ef */
992   /* f0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0  /* ff */
993   /*       -------------------------------        */
994   /*       0 1 2 3 4 5 6 7 8 9 a b c d e f        */
995 };
996
997 static int amd64_syscall_p (const struct amd64_insn *insn, int *lengthp);
998
999 static int
1000 rex_prefix_p (gdb_byte pfx)
1001 {
1002   return REX_PREFIX_P (pfx);
1003 }
1004
1005 /* Skip the legacy instruction prefixes in INSN.
1006    We assume INSN is properly sentineled so we don't have to worry
1007    about falling off the end of the buffer.  */
1008
1009 static gdb_byte *
1010 amd64_skip_prefixes (gdb_byte *insn)
1011 {
1012   while (1)
1013     {
1014       switch (*insn)
1015         {
1016         case DATA_PREFIX_OPCODE:
1017         case ADDR_PREFIX_OPCODE:
1018         case CS_PREFIX_OPCODE:
1019         case DS_PREFIX_OPCODE:
1020         case ES_PREFIX_OPCODE:
1021         case FS_PREFIX_OPCODE:
1022         case GS_PREFIX_OPCODE:
1023         case SS_PREFIX_OPCODE:
1024         case LOCK_PREFIX_OPCODE:
1025         case REPE_PREFIX_OPCODE:
1026         case REPNE_PREFIX_OPCODE:
1027           ++insn;
1028           continue;
1029         default:
1030           break;
1031         }
1032       break;
1033     }
1034
1035   return insn;
1036 }
1037
1038 /* Return an integer register (other than RSP) that is unused as an input
1039    operand in INSN.
1040    In order to not require adding a rex prefix if the insn doesn't already
1041    have one, the result is restricted to RAX ... RDI, sans RSP.
1042    The register numbering of the result follows architecture ordering,
1043    e.g. RDI = 7.  */
1044
1045 static int
1046 amd64_get_unused_input_int_reg (const struct amd64_insn *details)
1047 {
1048   /* 1 bit for each reg */
1049   int used_regs_mask = 0;
1050
1051   /* There can be at most 3 int regs used as inputs in an insn, and we have
1052      7 to choose from (RAX ... RDI, sans RSP).
1053      This allows us to take a conservative approach and keep things simple.
1054      E.g. By avoiding RAX, we don't have to specifically watch for opcodes
1055      that implicitly specify RAX.  */
1056
1057   /* Avoid RAX.  */
1058   used_regs_mask |= 1 << EAX_REG_NUM;
1059   /* Similarily avoid RDX, implicit operand in divides.  */
1060   used_regs_mask |= 1 << EDX_REG_NUM;
1061   /* Avoid RSP.  */
1062   used_regs_mask |= 1 << ESP_REG_NUM;
1063
1064   /* If the opcode is one byte long and there's no ModRM byte,
1065      assume the opcode specifies a register.  */
1066   if (details->opcode_len == 1 && details->modrm_offset == -1)
1067     used_regs_mask |= 1 << (details->raw_insn[details->opcode_offset] & 7);
1068
1069   /* Mark used regs in the modrm/sib bytes.  */
1070   if (details->modrm_offset != -1)
1071     {
1072       int modrm = details->raw_insn[details->modrm_offset];
1073       int mod = MODRM_MOD_FIELD (modrm);
1074       int reg = MODRM_REG_FIELD (modrm);
1075       int rm = MODRM_RM_FIELD (modrm);
1076       int have_sib = mod != 3 && rm == 4;
1077
1078       /* Assume the reg field of the modrm byte specifies a register.  */
1079       used_regs_mask |= 1 << reg;
1080
1081       if (have_sib)
1082         {
1083           int base = SIB_BASE_FIELD (details->raw_insn[details->modrm_offset + 1]);
1084           int index = SIB_INDEX_FIELD (details->raw_insn[details->modrm_offset + 1]);
1085           used_regs_mask |= 1 << base;
1086           used_regs_mask |= 1 << index;
1087         }
1088       else
1089         {
1090           used_regs_mask |= 1 << rm;
1091         }
1092     }
1093
1094   gdb_assert (used_regs_mask < 256);
1095   gdb_assert (used_regs_mask != 255);
1096
1097   /* Finally, find a free reg.  */
1098   {
1099     int i;
1100
1101     for (i = 0; i < 8; ++i)
1102       {
1103         if (! (used_regs_mask & (1 << i)))
1104           return i;
1105       }
1106
1107     /* We shouldn't get here.  */
1108     internal_error (__FILE__, __LINE__, _("unable to find free reg"));
1109   }
1110 }
1111
1112 /* Extract the details of INSN that we need.  */
1113
1114 static void
1115 amd64_get_insn_details (gdb_byte *insn, struct amd64_insn *details)
1116 {
1117   gdb_byte *start = insn;
1118   int need_modrm;
1119
1120   details->raw_insn = insn;
1121
1122   details->opcode_len = -1;
1123   details->rex_offset = -1;
1124   details->opcode_offset = -1;
1125   details->modrm_offset = -1;
1126
1127   /* Skip legacy instruction prefixes.  */
1128   insn = amd64_skip_prefixes (insn);
1129
1130   /* Skip REX instruction prefix.  */
1131   if (rex_prefix_p (*insn))
1132     {
1133       details->rex_offset = insn - start;
1134       ++insn;
1135     }
1136
1137   details->opcode_offset = insn - start;
1138
1139   if (*insn == TWO_BYTE_OPCODE_ESCAPE)
1140     {
1141       /* Two or three-byte opcode.  */
1142       ++insn;
1143       need_modrm = twobyte_has_modrm[*insn];
1144
1145       /* Check for three-byte opcode.  */
1146       switch (*insn)
1147         {
1148         case 0x24:
1149         case 0x25:
1150         case 0x38:
1151         case 0x3a:
1152         case 0x7a:
1153         case 0x7b:
1154           ++insn;
1155           details->opcode_len = 3;
1156           break;
1157         default:
1158           details->opcode_len = 2;
1159           break;
1160         }
1161     }
1162   else
1163     {
1164       /* One-byte opcode.  */
1165       need_modrm = onebyte_has_modrm[*insn];
1166       details->opcode_len = 1;
1167     }
1168
1169   if (need_modrm)
1170     {
1171       ++insn;
1172       details->modrm_offset = insn - start;
1173     }
1174 }
1175
1176 /* Update %rip-relative addressing in INSN.
1177
1178    %rip-relative addressing only uses a 32-bit displacement.
1179    32 bits is not enough to be guaranteed to cover the distance between where
1180    the real instruction is and where its copy is.
1181    Convert the insn to use base+disp addressing.
1182    We set base = pc + insn_length so we can leave disp unchanged.  */
1183
1184 static void
1185 fixup_riprel (struct gdbarch *gdbarch, struct displaced_step_closure *dsc,
1186               CORE_ADDR from, CORE_ADDR to, struct regcache *regs)
1187 {
1188   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1189   const struct amd64_insn *insn_details = &dsc->insn_details;
1190   int modrm_offset = insn_details->modrm_offset;
1191   gdb_byte *insn = insn_details->raw_insn + modrm_offset;
1192   CORE_ADDR rip_base;
1193   int32_t disp;
1194   int insn_length;
1195   int arch_tmp_regno, tmp_regno;
1196   ULONGEST orig_value;
1197
1198   /* %rip+disp32 addressing mode, displacement follows ModRM byte.  */
1199   ++insn;
1200
1201   /* Compute the rip-relative address.  */
1202   disp = extract_signed_integer (insn, sizeof (int32_t), byte_order);
1203   insn_length = gdb_buffered_insn_length (gdbarch, dsc->insn_buf,
1204                                           dsc->max_len, from);
1205   rip_base = from + insn_length;
1206
1207   /* We need a register to hold the address.
1208      Pick one not used in the insn.
1209      NOTE: arch_tmp_regno uses architecture ordering, e.g. RDI = 7.  */
1210   arch_tmp_regno = amd64_get_unused_input_int_reg (insn_details);
1211   tmp_regno = amd64_arch_reg_to_regnum (arch_tmp_regno);
1212
1213   /* REX.B should be unset as we were using rip-relative addressing,
1214      but ensure it's unset anyway, tmp_regno is not r8-r15.  */
1215   if (insn_details->rex_offset != -1)
1216     dsc->insn_buf[insn_details->rex_offset] &= ~REX_B;
1217
1218   regcache_cooked_read_unsigned (regs, tmp_regno, &orig_value);
1219   dsc->tmp_regno = tmp_regno;
1220   dsc->tmp_save = orig_value;
1221   dsc->tmp_used = 1;
1222
1223   /* Convert the ModRM field to be base+disp.  */
1224   dsc->insn_buf[modrm_offset] &= ~0xc7;
1225   dsc->insn_buf[modrm_offset] |= 0x80 + arch_tmp_regno;
1226
1227   regcache_cooked_write_unsigned (regs, tmp_regno, rip_base);
1228
1229   if (debug_displaced)
1230     fprintf_unfiltered (gdb_stdlog, "displaced: %%rip-relative addressing used.\n"
1231                         "displaced: using temp reg %d, old value %s, new value %s\n",
1232                         dsc->tmp_regno, paddress (gdbarch, dsc->tmp_save),
1233                         paddress (gdbarch, rip_base));
1234 }
1235
1236 static void
1237 fixup_displaced_copy (struct gdbarch *gdbarch,
1238                       struct displaced_step_closure *dsc,
1239                       CORE_ADDR from, CORE_ADDR to, struct regcache *regs)
1240 {
1241   const struct amd64_insn *details = &dsc->insn_details;
1242
1243   if (details->modrm_offset != -1)
1244     {
1245       gdb_byte modrm = details->raw_insn[details->modrm_offset];
1246
1247       if ((modrm & 0xc7) == 0x05)
1248         {
1249           /* The insn uses rip-relative addressing.
1250              Deal with it.  */
1251           fixup_riprel (gdbarch, dsc, from, to, regs);
1252         }
1253     }
1254 }
1255
1256 struct displaced_step_closure *
1257 amd64_displaced_step_copy_insn (struct gdbarch *gdbarch,
1258                                 CORE_ADDR from, CORE_ADDR to,
1259                                 struct regcache *regs)
1260 {
1261   int len = gdbarch_max_insn_length (gdbarch);
1262   /* Extra space for sentinels so fixup_{riprel,displaced_copy don't have to
1263      continually watch for running off the end of the buffer.  */
1264   int fixup_sentinel_space = len;
1265   struct displaced_step_closure *dsc =
1266     xmalloc (sizeof (*dsc) + len + fixup_sentinel_space);
1267   gdb_byte *buf = &dsc->insn_buf[0];
1268   struct amd64_insn *details = &dsc->insn_details;
1269
1270   dsc->tmp_used = 0;
1271   dsc->max_len = len + fixup_sentinel_space;
1272
1273   read_memory (from, buf, len);
1274
1275   /* Set up the sentinel space so we don't have to worry about running
1276      off the end of the buffer.  An excessive number of leading prefixes
1277      could otherwise cause this.  */
1278   memset (buf + len, 0, fixup_sentinel_space);
1279
1280   amd64_get_insn_details (buf, details);
1281
1282   /* GDB may get control back after the insn after the syscall.
1283      Presumably this is a kernel bug.
1284      If this is a syscall, make sure there's a nop afterwards.  */
1285   {
1286     int syscall_length;
1287
1288     if (amd64_syscall_p (details, &syscall_length))
1289       buf[details->opcode_offset + syscall_length] = NOP_OPCODE;
1290   }
1291
1292   /* Modify the insn to cope with the address where it will be executed from.
1293      In particular, handle any rip-relative addressing.  */
1294   fixup_displaced_copy (gdbarch, dsc, from, to, regs);
1295
1296   write_memory (to, buf, len);
1297
1298   if (debug_displaced)
1299     {
1300       fprintf_unfiltered (gdb_stdlog, "displaced: copy %s->%s: ",
1301                           paddress (gdbarch, from), paddress (gdbarch, to));
1302       displaced_step_dump_bytes (gdb_stdlog, buf, len);
1303     }
1304
1305   return dsc;
1306 }
1307
1308 static int
1309 amd64_absolute_jmp_p (const struct amd64_insn *details)
1310 {
1311   const gdb_byte *insn = &details->raw_insn[details->opcode_offset];
1312
1313   if (insn[0] == 0xff)
1314     {
1315       /* jump near, absolute indirect (/4) */
1316       if ((insn[1] & 0x38) == 0x20)
1317         return 1;
1318
1319       /* jump far, absolute indirect (/5) */
1320       if ((insn[1] & 0x38) == 0x28)
1321         return 1;
1322     }
1323
1324   return 0;
1325 }
1326
1327 static int
1328 amd64_absolute_call_p (const struct amd64_insn *details)
1329 {
1330   const gdb_byte *insn = &details->raw_insn[details->opcode_offset];
1331
1332   if (insn[0] == 0xff)
1333     {
1334       /* Call near, absolute indirect (/2) */
1335       if ((insn[1] & 0x38) == 0x10)
1336         return 1;
1337
1338       /* Call far, absolute indirect (/3) */
1339       if ((insn[1] & 0x38) == 0x18)
1340         return 1;
1341     }
1342
1343   return 0;
1344 }
1345
1346 static int
1347 amd64_ret_p (const struct amd64_insn *details)
1348 {
1349   /* NOTE: gcc can emit "repz ; ret".  */
1350   const gdb_byte *insn = &details->raw_insn[details->opcode_offset];
1351
1352   switch (insn[0])
1353     {
1354     case 0xc2: /* ret near, pop N bytes */
1355     case 0xc3: /* ret near */
1356     case 0xca: /* ret far, pop N bytes */
1357     case 0xcb: /* ret far */
1358     case 0xcf: /* iret */
1359       return 1;
1360
1361     default:
1362       return 0;
1363     }
1364 }
1365
1366 static int
1367 amd64_call_p (const struct amd64_insn *details)
1368 {
1369   const gdb_byte *insn = &details->raw_insn[details->opcode_offset];
1370
1371   if (amd64_absolute_call_p (details))
1372     return 1;
1373
1374   /* call near, relative */
1375   if (insn[0] == 0xe8)
1376     return 1;
1377
1378   return 0;
1379 }
1380
1381 /* Return non-zero if INSN is a system call, and set *LENGTHP to its
1382    length in bytes.  Otherwise, return zero.  */
1383
1384 static int
1385 amd64_syscall_p (const struct amd64_insn *details, int *lengthp)
1386 {
1387   const gdb_byte *insn = &details->raw_insn[details->opcode_offset];
1388
1389   if (insn[0] == 0x0f && insn[1] == 0x05)
1390     {
1391       *lengthp = 2;
1392       return 1;
1393     }
1394
1395   return 0;
1396 }
1397
1398 /* Fix up the state of registers and memory after having single-stepped
1399    a displaced instruction.  */
1400
1401 void
1402 amd64_displaced_step_fixup (struct gdbarch *gdbarch,
1403                             struct displaced_step_closure *dsc,
1404                             CORE_ADDR from, CORE_ADDR to,
1405                             struct regcache *regs)
1406 {
1407   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1408   /* The offset we applied to the instruction's address.  */
1409   ULONGEST insn_offset = to - from;
1410   gdb_byte *insn = dsc->insn_buf;
1411   const struct amd64_insn *insn_details = &dsc->insn_details;
1412
1413   if (debug_displaced)
1414     fprintf_unfiltered (gdb_stdlog,
1415                         "displaced: fixup (%s, %s), "
1416                         "insn = 0x%02x 0x%02x ...\n",
1417                         paddress (gdbarch, from), paddress (gdbarch, to),
1418                         insn[0], insn[1]);
1419
1420   /* If we used a tmp reg, restore it.  */
1421
1422   if (dsc->tmp_used)
1423     {
1424       if (debug_displaced)
1425         fprintf_unfiltered (gdb_stdlog, "displaced: restoring reg %d to %s\n",
1426                             dsc->tmp_regno, paddress (gdbarch, dsc->tmp_save));
1427       regcache_cooked_write_unsigned (regs, dsc->tmp_regno, dsc->tmp_save);
1428     }
1429
1430   /* The list of issues to contend with here is taken from
1431      resume_execution in arch/x86/kernel/kprobes.c, Linux 2.6.28.
1432      Yay for Free Software!  */
1433
1434   /* Relocate the %rip back to the program's instruction stream,
1435      if necessary.  */
1436
1437   /* Except in the case of absolute or indirect jump or call
1438      instructions, or a return instruction, the new rip is relative to
1439      the displaced instruction; make it relative to the original insn.
1440      Well, signal handler returns don't need relocation either, but we use the
1441      value of %rip to recognize those; see below.  */
1442   if (! amd64_absolute_jmp_p (insn_details)
1443       && ! amd64_absolute_call_p (insn_details)
1444       && ! amd64_ret_p (insn_details))
1445     {
1446       ULONGEST orig_rip;
1447       int insn_len;
1448
1449       regcache_cooked_read_unsigned (regs, AMD64_RIP_REGNUM, &orig_rip);
1450
1451       /* A signal trampoline system call changes the %rip, resuming
1452          execution of the main program after the signal handler has
1453          returned.  That makes them like 'return' instructions; we
1454          shouldn't relocate %rip.
1455
1456          But most system calls don't, and we do need to relocate %rip.
1457
1458          Our heuristic for distinguishing these cases: if stepping
1459          over the system call instruction left control directly after
1460          the instruction, the we relocate --- control almost certainly
1461          doesn't belong in the displaced copy.  Otherwise, we assume
1462          the instruction has put control where it belongs, and leave
1463          it unrelocated.  Goodness help us if there are PC-relative
1464          system calls.  */
1465       if (amd64_syscall_p (insn_details, &insn_len)
1466           && orig_rip != to + insn_len
1467           /* GDB can get control back after the insn after the syscall.
1468              Presumably this is a kernel bug.
1469              Fixup ensures its a nop, we add one to the length for it.  */
1470           && orig_rip != to + insn_len + 1)
1471         {
1472           if (debug_displaced)
1473             fprintf_unfiltered (gdb_stdlog,
1474                                 "displaced: syscall changed %%rip; "
1475                                 "not relocating\n");
1476         }
1477       else
1478         {
1479           ULONGEST rip = orig_rip - insn_offset;
1480
1481           /* If we just stepped over a breakpoint insn, we don't backup
1482              the pc on purpose; this is to match behaviour without
1483              stepping.  */
1484
1485           regcache_cooked_write_unsigned (regs, AMD64_RIP_REGNUM, rip);
1486
1487           if (debug_displaced)
1488             fprintf_unfiltered (gdb_stdlog,
1489                                 "displaced: "
1490                                 "relocated %%rip from %s to %s\n",
1491                                 paddress (gdbarch, orig_rip),
1492                                 paddress (gdbarch, rip));
1493         }
1494     }
1495
1496   /* If the instruction was PUSHFL, then the TF bit will be set in the
1497      pushed value, and should be cleared.  We'll leave this for later,
1498      since GDB already messes up the TF flag when stepping over a
1499      pushfl.  */
1500
1501   /* If the instruction was a call, the return address now atop the
1502      stack is the address following the copied instruction.  We need
1503      to make it the address following the original instruction.  */
1504   if (amd64_call_p (insn_details))
1505     {
1506       ULONGEST rsp;
1507       ULONGEST retaddr;
1508       const ULONGEST retaddr_len = 8;
1509
1510       regcache_cooked_read_unsigned (regs, AMD64_RSP_REGNUM, &rsp);
1511       retaddr = read_memory_unsigned_integer (rsp, retaddr_len, byte_order);
1512       retaddr = (retaddr - insn_offset) & 0xffffffffUL;
1513       write_memory_unsigned_integer (rsp, retaddr_len, byte_order, retaddr);
1514
1515       if (debug_displaced)
1516         fprintf_unfiltered (gdb_stdlog,
1517                             "displaced: relocated return addr at %s "
1518                             "to %s\n",
1519                             paddress (gdbarch, rsp),
1520                             paddress (gdbarch, retaddr));
1521     }
1522 }
1523
1524 /* If the instruction INSN uses RIP-relative addressing, return the
1525    offset into the raw INSN where the displacement to be adjusted is
1526    found.  Returns 0 if the instruction doesn't use RIP-relative
1527    addressing.  */
1528
1529 static int
1530 rip_relative_offset (struct amd64_insn *insn)
1531 {
1532   if (insn->modrm_offset != -1)
1533     {
1534       gdb_byte modrm = insn->raw_insn[insn->modrm_offset];
1535
1536       if ((modrm & 0xc7) == 0x05)
1537         {
1538           /* The displacement is found right after the ModRM byte.  */
1539           return insn->modrm_offset + 1;
1540         }
1541     }
1542
1543   return 0;
1544 }
1545
1546 static void
1547 append_insns (CORE_ADDR *to, ULONGEST len, const gdb_byte *buf)
1548 {
1549   target_write_memory (*to, buf, len);
1550   *to += len;
1551 }
1552
1553 static void
1554 amd64_relocate_instruction (struct gdbarch *gdbarch,
1555                             CORE_ADDR *to, CORE_ADDR oldloc)
1556 {
1557   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1558   int len = gdbarch_max_insn_length (gdbarch);
1559   /* Extra space for sentinels.  */
1560   int fixup_sentinel_space = len;
1561   gdb_byte *buf = xmalloc (len + fixup_sentinel_space);
1562   struct amd64_insn insn_details;
1563   int offset = 0;
1564   LONGEST rel32, newrel;
1565   gdb_byte *insn;
1566   int insn_length;
1567
1568   read_memory (oldloc, buf, len);
1569
1570   /* Set up the sentinel space so we don't have to worry about running
1571      off the end of the buffer.  An excessive number of leading prefixes
1572      could otherwise cause this.  */
1573   memset (buf + len, 0, fixup_sentinel_space);
1574
1575   insn = buf;
1576   amd64_get_insn_details (insn, &insn_details);
1577
1578   insn_length = gdb_buffered_insn_length (gdbarch, insn, len, oldloc);
1579
1580   /* Skip legacy instruction prefixes.  */
1581   insn = amd64_skip_prefixes (insn);
1582
1583   /* Adjust calls with 32-bit relative addresses as push/jump, with
1584      the address pushed being the location where the original call in
1585      the user program would return to.  */
1586   if (insn[0] == 0xe8)
1587     {
1588       gdb_byte push_buf[16];
1589       unsigned int ret_addr;
1590
1591       /* Where "ret" in the original code will return to.  */
1592       ret_addr = oldloc + insn_length;
1593       push_buf[0] = 0x68; /* pushq $...  */
1594       memcpy (&push_buf[1], &ret_addr, 4);
1595       /* Push the push.  */
1596       append_insns (to, 5, push_buf);
1597
1598       /* Convert the relative call to a relative jump.  */
1599       insn[0] = 0xe9;
1600
1601       /* Adjust the destination offset.  */
1602       rel32 = extract_signed_integer (insn + 1, 4, byte_order);
1603       newrel = (oldloc - *to) + rel32;
1604       store_signed_integer (insn + 1, 4, byte_order, newrel);
1605
1606       if (debug_displaced)
1607         fprintf_unfiltered (gdb_stdlog,
1608                             "Adjusted insn rel32=%s at %s to"
1609                             " rel32=%s at %s\n",
1610                             hex_string (rel32), paddress (gdbarch, oldloc),
1611                             hex_string (newrel), paddress (gdbarch, *to));
1612
1613       /* Write the adjusted jump into its displaced location.  */
1614       append_insns (to, 5, insn);
1615       return;
1616     }
1617
1618   offset = rip_relative_offset (&insn_details);
1619   if (!offset)
1620     {
1621       /* Adjust jumps with 32-bit relative addresses.  Calls are
1622          already handled above.  */
1623       if (insn[0] == 0xe9)
1624         offset = 1;
1625       /* Adjust conditional jumps.  */
1626       else if (insn[0] == 0x0f && (insn[1] & 0xf0) == 0x80)
1627         offset = 2;
1628     }
1629
1630   if (offset)
1631     {
1632       rel32 = extract_signed_integer (insn + offset, 4, byte_order);
1633       newrel = (oldloc - *to) + rel32;
1634       store_signed_integer (insn + offset, 4, byte_order, newrel);
1635       if (debug_displaced)
1636         fprintf_unfiltered (gdb_stdlog,
1637                             "Adjusted insn rel32=%s at %s to"
1638                             " rel32=%s at %s\n",
1639                             hex_string (rel32), paddress (gdbarch, oldloc),
1640                             hex_string (newrel), paddress (gdbarch, *to));
1641     }
1642
1643   /* Write the adjusted instruction into its displaced location.  */
1644   append_insns (to, insn_length, buf);
1645 }
1646
1647 \f
1648 /* The maximum number of saved registers.  This should include %rip.  */
1649 #define AMD64_NUM_SAVED_REGS    AMD64_NUM_GREGS
1650
1651 struct amd64_frame_cache
1652 {
1653   /* Base address.  */
1654   CORE_ADDR base;
1655   int base_p;
1656   CORE_ADDR sp_offset;
1657   CORE_ADDR pc;
1658
1659   /* Saved registers.  */
1660   CORE_ADDR saved_regs[AMD64_NUM_SAVED_REGS];
1661   CORE_ADDR saved_sp;
1662   int saved_sp_reg;
1663
1664   /* Do we have a frame?  */
1665   int frameless_p;
1666 };
1667
1668 /* Initialize a frame cache.  */
1669
1670 static void
1671 amd64_init_frame_cache (struct amd64_frame_cache *cache)
1672 {
1673   int i;
1674
1675   /* Base address.  */
1676   cache->base = 0;
1677   cache->base_p = 0;
1678   cache->sp_offset = -8;
1679   cache->pc = 0;
1680
1681   /* Saved registers.  We initialize these to -1 since zero is a valid
1682      offset (that's where %rbp is supposed to be stored).
1683      The values start out as being offsets, and are later converted to
1684      addresses (at which point -1 is interpreted as an address, still meaning
1685      "invalid").  */
1686   for (i = 0; i < AMD64_NUM_SAVED_REGS; i++)
1687     cache->saved_regs[i] = -1;
1688   cache->saved_sp = 0;
1689   cache->saved_sp_reg = -1;
1690
1691   /* Frameless until proven otherwise.  */
1692   cache->frameless_p = 1;
1693 }
1694
1695 /* Allocate and initialize a frame cache.  */
1696
1697 static struct amd64_frame_cache *
1698 amd64_alloc_frame_cache (void)
1699 {
1700   struct amd64_frame_cache *cache;
1701
1702   cache = FRAME_OBSTACK_ZALLOC (struct amd64_frame_cache);
1703   amd64_init_frame_cache (cache);
1704   return cache;
1705 }
1706
1707 /* GCC 4.4 and later, can put code in the prologue to realign the
1708    stack pointer.  Check whether PC points to such code, and update
1709    CACHE accordingly.  Return the first instruction after the code
1710    sequence or CURRENT_PC, whichever is smaller.  If we don't
1711    recognize the code, return PC.  */
1712
1713 static CORE_ADDR
1714 amd64_analyze_stack_align (CORE_ADDR pc, CORE_ADDR current_pc,
1715                            struct amd64_frame_cache *cache)
1716 {
1717   /* There are 2 code sequences to re-align stack before the frame
1718      gets set up:
1719
1720         1. Use a caller-saved saved register:
1721
1722                 leaq  8(%rsp), %reg
1723                 andq  $-XXX, %rsp
1724                 pushq -8(%reg)
1725
1726         2. Use a callee-saved saved register:
1727
1728                 pushq %reg
1729                 leaq  16(%rsp), %reg
1730                 andq  $-XXX, %rsp
1731                 pushq -8(%reg)
1732
1733      "andq $-XXX, %rsp" can be either 4 bytes or 7 bytes:
1734      
1735         0x48 0x83 0xe4 0xf0                     andq $-16, %rsp
1736         0x48 0x81 0xe4 0x00 0xff 0xff 0xff      andq $-256, %rsp
1737    */
1738
1739   gdb_byte buf[18];
1740   int reg, r;
1741   int offset, offset_and;
1742
1743   if (target_read_memory (pc, buf, sizeof buf))
1744     return pc;
1745
1746   /* Check caller-saved saved register.  The first instruction has
1747      to be "leaq 8(%rsp), %reg".  */
1748   if ((buf[0] & 0xfb) == 0x48
1749       && buf[1] == 0x8d
1750       && buf[3] == 0x24
1751       && buf[4] == 0x8)
1752     {
1753       /* MOD must be binary 10 and R/M must be binary 100.  */
1754       if ((buf[2] & 0xc7) != 0x44)
1755         return pc;
1756
1757       /* REG has register number.  */
1758       reg = (buf[2] >> 3) & 7;
1759
1760       /* Check the REX.R bit.  */
1761       if (buf[0] == 0x4c)
1762         reg += 8;
1763
1764       offset = 5;
1765     }
1766   else
1767     {
1768       /* Check callee-saved saved register.  The first instruction
1769          has to be "pushq %reg".  */
1770       reg = 0;
1771       if ((buf[0] & 0xf8) == 0x50)
1772         offset = 0;
1773       else if ((buf[0] & 0xf6) == 0x40
1774                && (buf[1] & 0xf8) == 0x50)
1775         {
1776           /* Check the REX.B bit.  */
1777           if ((buf[0] & 1) != 0)
1778             reg = 8;
1779
1780           offset = 1;
1781         }
1782       else
1783         return pc;
1784
1785       /* Get register.  */
1786       reg += buf[offset] & 0x7;
1787
1788       offset++;
1789
1790       /* The next instruction has to be "leaq 16(%rsp), %reg".  */
1791       if ((buf[offset] & 0xfb) != 0x48
1792           || buf[offset + 1] != 0x8d
1793           || buf[offset + 3] != 0x24
1794           || buf[offset + 4] != 0x10)
1795         return pc;
1796
1797       /* MOD must be binary 10 and R/M must be binary 100.  */
1798       if ((buf[offset + 2] & 0xc7) != 0x44)
1799         return pc;
1800       
1801       /* REG has register number.  */
1802       r = (buf[offset + 2] >> 3) & 7;
1803
1804       /* Check the REX.R bit.  */
1805       if (buf[offset] == 0x4c)
1806         r += 8;
1807
1808       /* Registers in pushq and leaq have to be the same.  */
1809       if (reg != r)
1810         return pc;
1811
1812       offset += 5;
1813     }
1814
1815   /* Rigister can't be %rsp nor %rbp.  */
1816   if (reg == 4 || reg == 5)
1817     return pc;
1818
1819   /* The next instruction has to be "andq $-XXX, %rsp".  */
1820   if (buf[offset] != 0x48
1821       || buf[offset + 2] != 0xe4
1822       || (buf[offset + 1] != 0x81 && buf[offset + 1] != 0x83))
1823     return pc;
1824
1825   offset_and = offset;
1826   offset += buf[offset + 1] == 0x81 ? 7 : 4;
1827
1828   /* The next instruction has to be "pushq -8(%reg)".  */
1829   r = 0;
1830   if (buf[offset] == 0xff)
1831     offset++;
1832   else if ((buf[offset] & 0xf6) == 0x40
1833            && buf[offset + 1] == 0xff)
1834     {
1835       /* Check the REX.B bit.  */
1836       if ((buf[offset] & 0x1) != 0)
1837         r = 8;
1838       offset += 2;
1839     }
1840   else
1841     return pc;
1842
1843   /* 8bit -8 is 0xf8.  REG must be binary 110 and MOD must be binary
1844      01.  */
1845   if (buf[offset + 1] != 0xf8
1846       || (buf[offset] & 0xf8) != 0x70)
1847     return pc;
1848
1849   /* R/M has register.  */
1850   r += buf[offset] & 7;
1851
1852   /* Registers in leaq and pushq have to be the same.  */
1853   if (reg != r)
1854     return pc;
1855
1856   if (current_pc > pc + offset_and)
1857     cache->saved_sp_reg = amd64_arch_reg_to_regnum (reg);
1858
1859   return min (pc + offset + 2, current_pc);
1860 }
1861
1862 /* Do a limited analysis of the prologue at PC and update CACHE
1863    accordingly.  Bail out early if CURRENT_PC is reached.  Return the
1864    address where the analysis stopped.
1865
1866    We will handle only functions beginning with:
1867
1868       pushq %rbp        0x55
1869       movq %rsp, %rbp   0x48 0x89 0xe5
1870
1871    Any function that doesn't start with this sequence will be assumed
1872    to have no prologue and thus no valid frame pointer in %rbp.  */
1873
1874 static CORE_ADDR
1875 amd64_analyze_prologue (struct gdbarch *gdbarch,
1876                         CORE_ADDR pc, CORE_ADDR current_pc,
1877                         struct amd64_frame_cache *cache)
1878 {
1879   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1880   static gdb_byte proto[3] = { 0x48, 0x89, 0xe5 }; /* movq %rsp, %rbp */
1881   gdb_byte buf[3];
1882   gdb_byte op;
1883
1884   if (current_pc <= pc)
1885     return current_pc;
1886
1887   pc = amd64_analyze_stack_align (pc, current_pc, cache);
1888
1889   op = read_memory_unsigned_integer (pc, 1, byte_order);
1890
1891   if (op == 0x55)               /* pushq %rbp */
1892     {
1893       /* Take into account that we've executed the `pushq %rbp' that
1894          starts this instruction sequence.  */
1895       cache->saved_regs[AMD64_RBP_REGNUM] = 0;
1896       cache->sp_offset += 8;
1897
1898       /* If that's all, return now.  */
1899       if (current_pc <= pc + 1)
1900         return current_pc;
1901
1902       /* Check for `movq %rsp, %rbp'.  */
1903       read_memory (pc + 1, buf, 3);
1904       if (memcmp (buf, proto, 3) != 0)
1905         return pc + 1;
1906
1907       /* OK, we actually have a frame.  */
1908       cache->frameless_p = 0;
1909       return pc + 4;
1910     }
1911
1912   return pc;
1913 }
1914
1915 /* Work around false termination of prologue - GCC PR debug/48827.
1916
1917    START_PC is the first instruction of a function, PC is its minimal already
1918    determined advanced address.  Function returns PC if it has nothing to do.
1919
1920    84 c0                test   %al,%al
1921    74 23                je     after
1922    <-- here is 0 lines advance - the false prologue end marker.
1923    0f 29 85 70 ff ff ff movaps %xmm0,-0x90(%rbp)
1924    0f 29 4d 80          movaps %xmm1,-0x80(%rbp)
1925    0f 29 55 90          movaps %xmm2,-0x70(%rbp)
1926    0f 29 5d a0          movaps %xmm3,-0x60(%rbp)
1927    0f 29 65 b0          movaps %xmm4,-0x50(%rbp)
1928    0f 29 6d c0          movaps %xmm5,-0x40(%rbp)
1929    0f 29 75 d0          movaps %xmm6,-0x30(%rbp)
1930    0f 29 7d e0          movaps %xmm7,-0x20(%rbp)
1931    after:  */
1932
1933 static CORE_ADDR
1934 amd64_skip_xmm_prologue (CORE_ADDR pc, CORE_ADDR start_pc)
1935 {
1936   struct symtab_and_line start_pc_sal, next_sal;
1937   gdb_byte buf[4 + 8 * 7];
1938   int offset, xmmreg;
1939
1940   if (pc == start_pc)
1941     return pc;
1942
1943   start_pc_sal = find_pc_sect_line (start_pc, NULL, 0);
1944   if (start_pc_sal.symtab == NULL
1945       || producer_is_gcc_ge_4 (start_pc_sal.symtab->producer) < 6
1946       || start_pc_sal.pc != start_pc || pc >= start_pc_sal.end)
1947     return pc;
1948
1949   next_sal = find_pc_sect_line (start_pc_sal.end, NULL, 0);
1950   if (next_sal.line != start_pc_sal.line)
1951     return pc;
1952
1953   /* START_PC can be from overlayed memory, ignored here.  */
1954   if (target_read_memory (next_sal.pc - 4, buf, sizeof (buf)) != 0)
1955     return pc;
1956
1957   /* test %al,%al */
1958   if (buf[0] != 0x84 || buf[1] != 0xc0)
1959     return pc;
1960   /* je AFTER */
1961   if (buf[2] != 0x74)
1962     return pc;
1963
1964   offset = 4;
1965   for (xmmreg = 0; xmmreg < 8; xmmreg++)
1966     {
1967       /* 0x0f 0x29 0b??000101 movaps %xmmreg?,-0x??(%rbp) */
1968       if (buf[offset] != 0x0f || buf[offset + 1] != 0x29
1969           || (buf[offset + 2] & 0x3f) != (xmmreg << 3 | 0x5))
1970         return pc;
1971
1972       /* 0b01?????? */
1973       if ((buf[offset + 2] & 0xc0) == 0x40)
1974         {
1975           /* 8-bit displacement.  */
1976           offset += 4;
1977         }
1978       /* 0b10?????? */
1979       else if ((buf[offset + 2] & 0xc0) == 0x80)
1980         {
1981           /* 32-bit displacement.  */
1982           offset += 7;
1983         }
1984       else
1985         return pc;
1986     }
1987
1988   /* je AFTER */
1989   if (offset - 4 != buf[3])
1990     return pc;
1991
1992   return next_sal.end;
1993 }
1994
1995 /* Return PC of first real instruction.  */
1996
1997 static CORE_ADDR
1998 amd64_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR start_pc)
1999 {
2000   struct amd64_frame_cache cache;
2001   CORE_ADDR pc;
2002
2003   amd64_init_frame_cache (&cache);
2004   pc = amd64_analyze_prologue (gdbarch, start_pc, 0xffffffffffffffffLL,
2005                                &cache);
2006   if (cache.frameless_p)
2007     return start_pc;
2008
2009   return amd64_skip_xmm_prologue (pc, start_pc);
2010 }
2011 \f
2012
2013 /* Normal frames.  */
2014
2015 static void
2016 amd64_frame_cache_1 (struct frame_info *this_frame,
2017                      struct amd64_frame_cache *cache)
2018 {
2019   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2020   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2021   gdb_byte buf[8];
2022   int i;
2023
2024   cache->pc = get_frame_func (this_frame);
2025   if (cache->pc != 0)
2026     amd64_analyze_prologue (gdbarch, cache->pc, get_frame_pc (this_frame),
2027                             cache);
2028
2029   if (cache->frameless_p)
2030     {
2031       /* We didn't find a valid frame.  If we're at the start of a
2032          function, or somewhere half-way its prologue, the function's
2033          frame probably hasn't been fully setup yet.  Try to
2034          reconstruct the base address for the stack frame by looking
2035          at the stack pointer.  For truly "frameless" functions this
2036          might work too.  */
2037
2038       if (cache->saved_sp_reg != -1)
2039         {
2040           /* Stack pointer has been saved.  */
2041           get_frame_register (this_frame, cache->saved_sp_reg, buf);
2042           cache->saved_sp = extract_unsigned_integer (buf, 8, byte_order);
2043
2044           /* We're halfway aligning the stack.  */
2045           cache->base = ((cache->saved_sp - 8) & 0xfffffffffffffff0LL) - 8;
2046           cache->saved_regs[AMD64_RIP_REGNUM] = cache->saved_sp - 8;
2047
2048           /* This will be added back below.  */
2049           cache->saved_regs[AMD64_RIP_REGNUM] -= cache->base;
2050         }
2051       else
2052         {
2053           get_frame_register (this_frame, AMD64_RSP_REGNUM, buf);
2054           cache->base = extract_unsigned_integer (buf, 8, byte_order)
2055                         + cache->sp_offset;
2056         }
2057     }
2058   else
2059     {
2060       get_frame_register (this_frame, AMD64_RBP_REGNUM, buf);
2061       cache->base = extract_unsigned_integer (buf, 8, byte_order);
2062     }
2063
2064   /* Now that we have the base address for the stack frame we can
2065      calculate the value of %rsp in the calling frame.  */
2066   cache->saved_sp = cache->base + 16;
2067
2068   /* For normal frames, %rip is stored at 8(%rbp).  If we don't have a
2069      frame we find it at the same offset from the reconstructed base
2070      address.  If we're halfway aligning the stack, %rip is handled
2071      differently (see above).  */
2072   if (!cache->frameless_p || cache->saved_sp_reg == -1)
2073     cache->saved_regs[AMD64_RIP_REGNUM] = 8;
2074
2075   /* Adjust all the saved registers such that they contain addresses
2076      instead of offsets.  */
2077   for (i = 0; i < AMD64_NUM_SAVED_REGS; i++)
2078     if (cache->saved_regs[i] != -1)
2079       cache->saved_regs[i] += cache->base;
2080
2081   cache->base_p = 1;
2082 }
2083
2084 static struct amd64_frame_cache *
2085 amd64_frame_cache (struct frame_info *this_frame, void **this_cache)
2086 {
2087   volatile struct gdb_exception ex;
2088   struct amd64_frame_cache *cache;
2089
2090   if (*this_cache)
2091     return *this_cache;
2092
2093   cache = amd64_alloc_frame_cache ();
2094   *this_cache = cache;
2095
2096   TRY_CATCH (ex, RETURN_MASK_ERROR)
2097     {
2098       amd64_frame_cache_1 (this_frame, cache);
2099     }
2100   if (ex.reason < 0 && ex.error != NOT_AVAILABLE_ERROR)
2101     throw_exception (ex);
2102
2103   return cache;
2104 }
2105
2106 static enum unwind_stop_reason
2107 amd64_frame_unwind_stop_reason (struct frame_info *this_frame,
2108                                 void **this_cache)
2109 {
2110   struct amd64_frame_cache *cache =
2111     amd64_frame_cache (this_frame, this_cache);
2112
2113   if (!cache->base_p)
2114     return UNWIND_UNAVAILABLE;
2115
2116   /* This marks the outermost frame.  */
2117   if (cache->base == 0)
2118     return UNWIND_OUTERMOST;
2119
2120   return UNWIND_NO_REASON;
2121 }
2122
2123 static void
2124 amd64_frame_this_id (struct frame_info *this_frame, void **this_cache,
2125                      struct frame_id *this_id)
2126 {
2127   struct amd64_frame_cache *cache =
2128     amd64_frame_cache (this_frame, this_cache);
2129
2130   if (!cache->base_p)
2131     return;
2132
2133   /* This marks the outermost frame.  */
2134   if (cache->base == 0)
2135     return;
2136
2137   (*this_id) = frame_id_build (cache->base + 16, cache->pc);
2138 }
2139
2140 static struct value *
2141 amd64_frame_prev_register (struct frame_info *this_frame, void **this_cache,
2142                            int regnum)
2143 {
2144   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2145   struct amd64_frame_cache *cache =
2146     amd64_frame_cache (this_frame, this_cache);
2147
2148   gdb_assert (regnum >= 0);
2149
2150   if (regnum == gdbarch_sp_regnum (gdbarch) && cache->saved_sp)
2151     return frame_unwind_got_constant (this_frame, regnum, cache->saved_sp);
2152
2153   if (regnum < AMD64_NUM_SAVED_REGS && cache->saved_regs[regnum] != -1)
2154     return frame_unwind_got_memory (this_frame, regnum,
2155                                     cache->saved_regs[regnum]);
2156
2157   return frame_unwind_got_register (this_frame, regnum, regnum);
2158 }
2159
2160 static const struct frame_unwind amd64_frame_unwind =
2161 {
2162   NORMAL_FRAME,
2163   amd64_frame_unwind_stop_reason,
2164   amd64_frame_this_id,
2165   amd64_frame_prev_register,
2166   NULL,
2167   default_frame_sniffer
2168 };
2169 \f
2170 /* Generate a bytecode expression to get the value of the saved PC.  */
2171
2172 static void
2173 amd64_gen_return_address (struct gdbarch *gdbarch,
2174                           struct agent_expr *ax, struct axs_value *value,
2175                           CORE_ADDR scope)
2176 {
2177   /* The following sequence assumes the traditional use of the base
2178      register.  */
2179   ax_reg (ax, AMD64_RBP_REGNUM);
2180   ax_const_l (ax, 8);
2181   ax_simple (ax, aop_add);
2182   value->type = register_type (gdbarch, AMD64_RIP_REGNUM);
2183   value->kind = axs_lvalue_memory;
2184 }
2185 \f
2186
2187 /* Signal trampolines.  */
2188
2189 /* FIXME: kettenis/20030419: Perhaps, we can unify the 32-bit and
2190    64-bit variants.  This would require using identical frame caches
2191    on both platforms.  */
2192
2193 static struct amd64_frame_cache *
2194 amd64_sigtramp_frame_cache (struct frame_info *this_frame, void **this_cache)
2195 {
2196   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2197   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2198   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2199   volatile struct gdb_exception ex;
2200   struct amd64_frame_cache *cache;
2201   CORE_ADDR addr;
2202   gdb_byte buf[8];
2203   int i;
2204
2205   if (*this_cache)
2206     return *this_cache;
2207
2208   cache = amd64_alloc_frame_cache ();
2209
2210   TRY_CATCH (ex, RETURN_MASK_ERROR)
2211     {
2212       get_frame_register (this_frame, AMD64_RSP_REGNUM, buf);
2213       cache->base = extract_unsigned_integer (buf, 8, byte_order) - 8;
2214
2215       addr = tdep->sigcontext_addr (this_frame);
2216       gdb_assert (tdep->sc_reg_offset);
2217       gdb_assert (tdep->sc_num_regs <= AMD64_NUM_SAVED_REGS);
2218       for (i = 0; i < tdep->sc_num_regs; i++)
2219         if (tdep->sc_reg_offset[i] != -1)
2220           cache->saved_regs[i] = addr + tdep->sc_reg_offset[i];
2221
2222       cache->base_p = 1;
2223     }
2224   if (ex.reason < 0 && ex.error != NOT_AVAILABLE_ERROR)
2225     throw_exception (ex);
2226
2227   *this_cache = cache;
2228   return cache;
2229 }
2230
2231 static enum unwind_stop_reason
2232 amd64_sigtramp_frame_unwind_stop_reason (struct frame_info *this_frame,
2233                                          void **this_cache)
2234 {
2235   struct amd64_frame_cache *cache =
2236     amd64_sigtramp_frame_cache (this_frame, this_cache);
2237
2238   if (!cache->base_p)
2239     return UNWIND_UNAVAILABLE;
2240
2241   return UNWIND_NO_REASON;
2242 }
2243
2244 static void
2245 amd64_sigtramp_frame_this_id (struct frame_info *this_frame,
2246                               void **this_cache, struct frame_id *this_id)
2247 {
2248   struct amd64_frame_cache *cache =
2249     amd64_sigtramp_frame_cache (this_frame, this_cache);
2250
2251   if (!cache->base_p)
2252     return;
2253
2254   (*this_id) = frame_id_build (cache->base + 16, get_frame_pc (this_frame));
2255 }
2256
2257 static struct value *
2258 amd64_sigtramp_frame_prev_register (struct frame_info *this_frame,
2259                                     void **this_cache, int regnum)
2260 {
2261   /* Make sure we've initialized the cache.  */
2262   amd64_sigtramp_frame_cache (this_frame, this_cache);
2263
2264   return amd64_frame_prev_register (this_frame, this_cache, regnum);
2265 }
2266
2267 static int
2268 amd64_sigtramp_frame_sniffer (const struct frame_unwind *self,
2269                               struct frame_info *this_frame,
2270                               void **this_cache)
2271 {
2272   struct gdbarch_tdep *tdep = gdbarch_tdep (get_frame_arch (this_frame));
2273
2274   /* We shouldn't even bother if we don't have a sigcontext_addr
2275      handler.  */
2276   if (tdep->sigcontext_addr == NULL)
2277     return 0;
2278
2279   if (tdep->sigtramp_p != NULL)
2280     {
2281       if (tdep->sigtramp_p (this_frame))
2282         return 1;
2283     }
2284
2285   if (tdep->sigtramp_start != 0)
2286     {
2287       CORE_ADDR pc = get_frame_pc (this_frame);
2288
2289       gdb_assert (tdep->sigtramp_end != 0);
2290       if (pc >= tdep->sigtramp_start && pc < tdep->sigtramp_end)
2291         return 1;
2292     }
2293
2294   return 0;
2295 }
2296
2297 static const struct frame_unwind amd64_sigtramp_frame_unwind =
2298 {
2299   SIGTRAMP_FRAME,
2300   amd64_sigtramp_frame_unwind_stop_reason,
2301   amd64_sigtramp_frame_this_id,
2302   amd64_sigtramp_frame_prev_register,
2303   NULL,
2304   amd64_sigtramp_frame_sniffer
2305 };
2306 \f
2307
2308 static CORE_ADDR
2309 amd64_frame_base_address (struct frame_info *this_frame, void **this_cache)
2310 {
2311   struct amd64_frame_cache *cache =
2312     amd64_frame_cache (this_frame, this_cache);
2313
2314   return cache->base;
2315 }
2316
2317 static const struct frame_base amd64_frame_base =
2318 {
2319   &amd64_frame_unwind,
2320   amd64_frame_base_address,
2321   amd64_frame_base_address,
2322   amd64_frame_base_address
2323 };
2324
2325 /* Normal frames, but in a function epilogue.  */
2326
2327 /* The epilogue is defined here as the 'ret' instruction, which will
2328    follow any instruction such as 'leave' or 'pop %ebp' that destroys
2329    the function's stack frame.  */
2330
2331 static int
2332 amd64_in_function_epilogue_p (struct gdbarch *gdbarch, CORE_ADDR pc)
2333 {
2334   gdb_byte insn;
2335   struct symtab *symtab;
2336
2337   symtab = find_pc_symtab (pc);
2338   if (symtab && symtab->epilogue_unwind_valid)
2339     return 0;
2340
2341   if (target_read_memory (pc, &insn, 1))
2342     return 0;   /* Can't read memory at pc.  */
2343
2344   if (insn != 0xc3)     /* 'ret' instruction.  */
2345     return 0;
2346
2347   return 1;
2348 }
2349
2350 static int
2351 amd64_epilogue_frame_sniffer (const struct frame_unwind *self,
2352                               struct frame_info *this_frame,
2353                               void **this_prologue_cache)
2354 {
2355   if (frame_relative_level (this_frame) == 0)
2356     return amd64_in_function_epilogue_p (get_frame_arch (this_frame),
2357                                          get_frame_pc (this_frame));
2358   else
2359     return 0;
2360 }
2361
2362 static struct amd64_frame_cache *
2363 amd64_epilogue_frame_cache (struct frame_info *this_frame, void **this_cache)
2364 {
2365   struct gdbarch *gdbarch = get_frame_arch (this_frame);
2366   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
2367   volatile struct gdb_exception ex;
2368   struct amd64_frame_cache *cache;
2369   gdb_byte buf[8];
2370
2371   if (*this_cache)
2372     return *this_cache;
2373
2374   cache = amd64_alloc_frame_cache ();
2375   *this_cache = cache;
2376
2377   TRY_CATCH (ex, RETURN_MASK_ERROR)
2378     {
2379       /* Cache base will be %esp plus cache->sp_offset (-8).  */
2380       get_frame_register (this_frame, AMD64_RSP_REGNUM, buf);
2381       cache->base = extract_unsigned_integer (buf, 8,
2382                                               byte_order) + cache->sp_offset;
2383
2384       /* Cache pc will be the frame func.  */
2385       cache->pc = get_frame_pc (this_frame);
2386
2387       /* The saved %esp will be at cache->base plus 16.  */
2388       cache->saved_sp = cache->base + 16;
2389
2390       /* The saved %eip will be at cache->base plus 8.  */
2391       cache->saved_regs[AMD64_RIP_REGNUM] = cache->base + 8;
2392
2393       cache->base_p = 1;
2394     }
2395   if (ex.reason < 0 && ex.error != NOT_AVAILABLE_ERROR)
2396     throw_exception (ex);
2397
2398   return cache;
2399 }
2400
2401 static enum unwind_stop_reason
2402 amd64_epilogue_frame_unwind_stop_reason (struct frame_info *this_frame,
2403                                          void **this_cache)
2404 {
2405   struct amd64_frame_cache *cache
2406     = amd64_epilogue_frame_cache (this_frame, this_cache);
2407
2408   if (!cache->base_p)
2409     return UNWIND_UNAVAILABLE;
2410
2411   return UNWIND_NO_REASON;
2412 }
2413
2414 static void
2415 amd64_epilogue_frame_this_id (struct frame_info *this_frame,
2416                               void **this_cache,
2417                               struct frame_id *this_id)
2418 {
2419   struct amd64_frame_cache *cache = amd64_epilogue_frame_cache (this_frame,
2420                                                                this_cache);
2421
2422   if (!cache->base_p)
2423     return;
2424
2425   (*this_id) = frame_id_build (cache->base + 8, cache->pc);
2426 }
2427
2428 static const struct frame_unwind amd64_epilogue_frame_unwind =
2429 {
2430   NORMAL_FRAME,
2431   amd64_epilogue_frame_unwind_stop_reason,
2432   amd64_epilogue_frame_this_id,
2433   amd64_frame_prev_register,
2434   NULL, 
2435   amd64_epilogue_frame_sniffer
2436 };
2437
2438 static struct frame_id
2439 amd64_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
2440 {
2441   CORE_ADDR fp;
2442
2443   fp = get_frame_register_unsigned (this_frame, AMD64_RBP_REGNUM);
2444
2445   return frame_id_build (fp + 16, get_frame_pc (this_frame));
2446 }
2447
2448 /* 16 byte align the SP per frame requirements.  */
2449
2450 static CORE_ADDR
2451 amd64_frame_align (struct gdbarch *gdbarch, CORE_ADDR sp)
2452 {
2453   return sp & -(CORE_ADDR)16;
2454 }
2455 \f
2456
2457 /* Supply register REGNUM from the buffer specified by FPREGS and LEN
2458    in the floating-point register set REGSET to register cache
2459    REGCACHE.  If REGNUM is -1, do this for all registers in REGSET.  */
2460
2461 static void
2462 amd64_supply_fpregset (const struct regset *regset, struct regcache *regcache,
2463                        int regnum, const void *fpregs, size_t len)
2464 {
2465   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2466
2467   gdb_assert (len == tdep->sizeof_fpregset);
2468   amd64_supply_fxsave (regcache, regnum, fpregs);
2469 }
2470
2471 /* Collect register REGNUM from the register cache REGCACHE and store
2472    it in the buffer specified by FPREGS and LEN as described by the
2473    floating-point register set REGSET.  If REGNUM is -1, do this for
2474    all registers in REGSET.  */
2475
2476 static void
2477 amd64_collect_fpregset (const struct regset *regset,
2478                         const struct regcache *regcache,
2479                         int regnum, void *fpregs, size_t len)
2480 {
2481   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2482
2483   gdb_assert (len == tdep->sizeof_fpregset);
2484   amd64_collect_fxsave (regcache, regnum, fpregs);
2485 }
2486
2487 /* Similar to amd64_supply_fpregset, but use XSAVE extended state.  */
2488
2489 static void
2490 amd64_supply_xstateregset (const struct regset *regset,
2491                            struct regcache *regcache, int regnum,
2492                            const void *xstateregs, size_t len)
2493 {
2494   amd64_supply_xsave (regcache, regnum, xstateregs);
2495 }
2496
2497 /* Similar to amd64_collect_fpregset, but use XSAVE extended state.  */
2498
2499 static void
2500 amd64_collect_xstateregset (const struct regset *regset,
2501                             const struct regcache *regcache,
2502                             int regnum, void *xstateregs, size_t len)
2503 {
2504   amd64_collect_xsave (regcache, regnum, xstateregs, 1);
2505 }
2506
2507 /* Return the appropriate register set for the core section identified
2508    by SECT_NAME and SECT_SIZE.  */
2509
2510 static const struct regset *
2511 amd64_regset_from_core_section (struct gdbarch *gdbarch,
2512                                 const char *sect_name, size_t sect_size)
2513 {
2514   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2515
2516   if (strcmp (sect_name, ".reg2") == 0 && sect_size == tdep->sizeof_fpregset)
2517     {
2518       if (tdep->fpregset == NULL)
2519         tdep->fpregset = regset_alloc (gdbarch, amd64_supply_fpregset,
2520                                        amd64_collect_fpregset);
2521
2522       return tdep->fpregset;
2523     }
2524
2525   if (strcmp (sect_name, ".reg-xstate") == 0)
2526     {
2527       if (tdep->xstateregset == NULL)
2528         tdep->xstateregset = regset_alloc (gdbarch,
2529                                            amd64_supply_xstateregset,
2530                                            amd64_collect_xstateregset);
2531
2532       return tdep->xstateregset;
2533     }
2534
2535   return i386_regset_from_core_section (gdbarch, sect_name, sect_size);
2536 }
2537 \f
2538
2539 /* Figure out where the longjmp will land.  Slurp the jmp_buf out of
2540    %rdi.  We expect its value to be a pointer to the jmp_buf structure
2541    from which we extract the address that we will land at.  This
2542    address is copied into PC.  This routine returns non-zero on
2543    success.  */
2544
2545 static int
2546 amd64_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
2547 {
2548   gdb_byte buf[8];
2549   CORE_ADDR jb_addr;
2550   struct gdbarch *gdbarch = get_frame_arch (frame);
2551   int jb_pc_offset = gdbarch_tdep (gdbarch)->jb_pc_offset;
2552   int len = TYPE_LENGTH (builtin_type (gdbarch)->builtin_func_ptr);
2553
2554   /* If JB_PC_OFFSET is -1, we have no way to find out where the
2555      longjmp will land.  */
2556   if (jb_pc_offset == -1)
2557     return 0;
2558
2559   get_frame_register (frame, AMD64_RDI_REGNUM, buf);
2560   jb_addr= extract_typed_address
2561             (buf, builtin_type (gdbarch)->builtin_data_ptr);
2562   if (target_read_memory (jb_addr + jb_pc_offset, buf, len))
2563     return 0;
2564
2565   *pc = extract_typed_address (buf, builtin_type (gdbarch)->builtin_func_ptr);
2566
2567   return 1;
2568 }
2569
2570 static const int amd64_record_regmap[] =
2571 {
2572   AMD64_RAX_REGNUM, AMD64_RCX_REGNUM, AMD64_RDX_REGNUM, AMD64_RBX_REGNUM,
2573   AMD64_RSP_REGNUM, AMD64_RBP_REGNUM, AMD64_RSI_REGNUM, AMD64_RDI_REGNUM,
2574   AMD64_R8_REGNUM, AMD64_R9_REGNUM, AMD64_R10_REGNUM, AMD64_R11_REGNUM,
2575   AMD64_R12_REGNUM, AMD64_R13_REGNUM, AMD64_R14_REGNUM, AMD64_R15_REGNUM,
2576   AMD64_RIP_REGNUM, AMD64_EFLAGS_REGNUM, AMD64_CS_REGNUM, AMD64_SS_REGNUM,
2577   AMD64_DS_REGNUM, AMD64_ES_REGNUM, AMD64_FS_REGNUM, AMD64_GS_REGNUM
2578 };
2579
2580 void
2581 amd64_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2582 {
2583   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2584   const struct target_desc *tdesc = info.target_desc;
2585
2586   /* AMD64 generally uses `fxsave' instead of `fsave' for saving its
2587      floating-point registers.  */
2588   tdep->sizeof_fpregset = I387_SIZEOF_FXSAVE;
2589
2590   if (! tdesc_has_registers (tdesc))
2591     tdesc = tdesc_amd64;
2592   tdep->tdesc = tdesc;
2593
2594   tdep->num_core_regs = AMD64_NUM_GREGS + I387_NUM_REGS;
2595   tdep->register_names = amd64_register_names;
2596
2597   if (tdesc_find_feature (tdesc, "org.gnu.gdb.i386.avx") != NULL)
2598     {
2599       tdep->ymmh_register_names = amd64_ymmh_names;
2600       tdep->num_ymm_regs = 16;
2601       tdep->ymm0h_regnum = AMD64_YMM0H_REGNUM;
2602     }
2603
2604   tdep->num_byte_regs = 20;
2605   tdep->num_word_regs = 16;
2606   tdep->num_dword_regs = 16;
2607   /* Avoid wiring in the MMX registers for now.  */
2608   tdep->num_mmx_regs = 0;
2609
2610   set_gdbarch_pseudo_register_read_value (gdbarch,
2611                                           amd64_pseudo_register_read_value);
2612   set_gdbarch_pseudo_register_write (gdbarch,
2613                                      amd64_pseudo_register_write);
2614
2615   set_tdesc_pseudo_register_name (gdbarch, amd64_pseudo_register_name);
2616
2617   /* AMD64 has an FPU and 16 SSE registers.  */
2618   tdep->st0_regnum = AMD64_ST0_REGNUM;
2619   tdep->num_xmm_regs = 16;
2620
2621   /* This is what all the fuss is about.  */
2622   set_gdbarch_long_bit (gdbarch, 64);
2623   set_gdbarch_long_long_bit (gdbarch, 64);
2624   set_gdbarch_ptr_bit (gdbarch, 64);
2625
2626   /* In contrast to the i386, on AMD64 a `long double' actually takes
2627      up 128 bits, even though it's still based on the i387 extended
2628      floating-point format which has only 80 significant bits.  */
2629   set_gdbarch_long_double_bit (gdbarch, 128);
2630
2631   set_gdbarch_num_regs (gdbarch, AMD64_NUM_REGS);
2632
2633   /* Register numbers of various important registers.  */
2634   set_gdbarch_sp_regnum (gdbarch, AMD64_RSP_REGNUM); /* %rsp */
2635   set_gdbarch_pc_regnum (gdbarch, AMD64_RIP_REGNUM); /* %rip */
2636   set_gdbarch_ps_regnum (gdbarch, AMD64_EFLAGS_REGNUM); /* %eflags */
2637   set_gdbarch_fp0_regnum (gdbarch, AMD64_ST0_REGNUM); /* %st(0) */
2638
2639   /* The "default" register numbering scheme for AMD64 is referred to
2640      as the "DWARF Register Number Mapping" in the System V psABI.
2641      The preferred debugging format for all known AMD64 targets is
2642      actually DWARF2, and GCC doesn't seem to support DWARF (that is
2643      DWARF-1), but we provide the same mapping just in case.  This
2644      mapping is also used for stabs, which GCC does support.  */
2645   set_gdbarch_stab_reg_to_regnum (gdbarch, amd64_dwarf_reg_to_regnum);
2646   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, amd64_dwarf_reg_to_regnum);
2647
2648   /* We don't override SDB_REG_RO_REGNUM, since COFF doesn't seem to
2649      be in use on any of the supported AMD64 targets.  */
2650
2651   /* Call dummy code.  */
2652   set_gdbarch_push_dummy_call (gdbarch, amd64_push_dummy_call);
2653   set_gdbarch_frame_align (gdbarch, amd64_frame_align);
2654   set_gdbarch_frame_red_zone_size (gdbarch, 128);
2655   tdep->call_dummy_num_integer_regs =
2656     ARRAY_SIZE (amd64_dummy_call_integer_regs);
2657   tdep->call_dummy_integer_regs = amd64_dummy_call_integer_regs;
2658   tdep->classify = amd64_classify;
2659
2660   set_gdbarch_convert_register_p (gdbarch, i387_convert_register_p);
2661   set_gdbarch_register_to_value (gdbarch, i387_register_to_value);
2662   set_gdbarch_value_to_register (gdbarch, i387_value_to_register);
2663
2664   set_gdbarch_return_value (gdbarch, amd64_return_value);
2665
2666   set_gdbarch_skip_prologue (gdbarch, amd64_skip_prologue);
2667
2668   tdep->record_regmap = amd64_record_regmap;
2669
2670   set_gdbarch_dummy_id (gdbarch, amd64_dummy_id);
2671
2672   /* Hook the function epilogue frame unwinder.  This unwinder is
2673      appended to the list first, so that it supercedes the other
2674      unwinders in function epilogues.  */
2675   frame_unwind_prepend_unwinder (gdbarch, &amd64_epilogue_frame_unwind);
2676
2677   /* Hook the prologue-based frame unwinders.  */
2678   frame_unwind_append_unwinder (gdbarch, &amd64_sigtramp_frame_unwind);
2679   frame_unwind_append_unwinder (gdbarch, &amd64_frame_unwind);
2680   frame_base_set_default (gdbarch, &amd64_frame_base);
2681
2682   /* If we have a register mapping, enable the generic core file support.  */
2683   if (tdep->gregset_reg_offset)
2684     set_gdbarch_regset_from_core_section (gdbarch,
2685                                           amd64_regset_from_core_section);
2686
2687   set_gdbarch_get_longjmp_target (gdbarch, amd64_get_longjmp_target);
2688
2689   set_gdbarch_relocate_instruction (gdbarch, amd64_relocate_instruction);
2690
2691   set_gdbarch_gen_return_address (gdbarch, amd64_gen_return_address);
2692 }
2693
2694 /* Provide a prototype to silence -Wmissing-prototypes.  */
2695 void _initialize_amd64_tdep (void);
2696
2697 void
2698 _initialize_amd64_tdep (void)
2699 {
2700   initialize_tdesc_amd64 ();
2701   initialize_tdesc_amd64_avx ();
2702 }
2703 \f
2704
2705 /* The 64-bit FXSAVE format differs from the 32-bit format in the
2706    sense that the instruction pointer and data pointer are simply
2707    64-bit offsets into the code segment and the data segment instead
2708    of a selector offset pair.  The functions below store the upper 32
2709    bits of these pointers (instead of just the 16-bits of the segment
2710    selector).  */
2711
2712 /* Fill register REGNUM in REGCACHE with the appropriate
2713    floating-point or SSE register value from *FXSAVE.  If REGNUM is
2714    -1, do this for all registers.  This function masks off any of the
2715    reserved bits in *FXSAVE.  */
2716
2717 void
2718 amd64_supply_fxsave (struct regcache *regcache, int regnum,
2719                      const void *fxsave)
2720 {
2721   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2722   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2723
2724   i387_supply_fxsave (regcache, regnum, fxsave);
2725
2726   if (fxsave && gdbarch_ptr_bit (gdbarch) == 64)
2727     {
2728       const gdb_byte *regs = fxsave;
2729
2730       if (regnum == -1 || regnum == I387_FISEG_REGNUM (tdep))
2731         regcache_raw_supply (regcache, I387_FISEG_REGNUM (tdep), regs + 12);
2732       if (regnum == -1 || regnum == I387_FOSEG_REGNUM (tdep))
2733         regcache_raw_supply (regcache, I387_FOSEG_REGNUM (tdep), regs + 20);
2734     }
2735 }
2736
2737 /* Similar to amd64_supply_fxsave, but use XSAVE extended state.  */
2738
2739 void
2740 amd64_supply_xsave (struct regcache *regcache, int regnum,
2741                     const void *xsave)
2742 {
2743   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2744   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2745
2746   i387_supply_xsave (regcache, regnum, xsave);
2747
2748   if (xsave && gdbarch_ptr_bit (gdbarch) == 64)
2749     {
2750       const gdb_byte *regs = xsave;
2751
2752       if (regnum == -1 || regnum == I387_FISEG_REGNUM (tdep))
2753         regcache_raw_supply (regcache, I387_FISEG_REGNUM (tdep),
2754                              regs + 12);
2755       if (regnum == -1 || regnum == I387_FOSEG_REGNUM (tdep))
2756         regcache_raw_supply (regcache, I387_FOSEG_REGNUM (tdep),
2757                              regs + 20);
2758     }
2759 }
2760
2761 /* Fill register REGNUM (if it is a floating-point or SSE register) in
2762    *FXSAVE with the value from REGCACHE.  If REGNUM is -1, do this for
2763    all registers.  This function doesn't touch any of the reserved
2764    bits in *FXSAVE.  */
2765
2766 void
2767 amd64_collect_fxsave (const struct regcache *regcache, int regnum,
2768                       void *fxsave)
2769 {
2770   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2771   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2772   gdb_byte *regs = fxsave;
2773
2774   i387_collect_fxsave (regcache, regnum, fxsave);
2775
2776   if (gdbarch_ptr_bit (gdbarch) == 64)
2777     {
2778       if (regnum == -1 || regnum == I387_FISEG_REGNUM (tdep))
2779         regcache_raw_collect (regcache, I387_FISEG_REGNUM (tdep), regs + 12);
2780       if (regnum == -1 || regnum == I387_FOSEG_REGNUM (tdep))
2781         regcache_raw_collect (regcache, I387_FOSEG_REGNUM (tdep), regs + 20);
2782     }
2783 }
2784
2785 /* Similar to amd64_collect_fxsave, but use XSAVE extended state.  */
2786
2787 void
2788 amd64_collect_xsave (const struct regcache *regcache, int regnum,
2789                      void *xsave, int gcore)
2790 {
2791   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2792   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2793   gdb_byte *regs = xsave;
2794
2795   i387_collect_xsave (regcache, regnum, xsave, gcore);
2796
2797   if (gdbarch_ptr_bit (gdbarch) == 64)
2798     {
2799       if (regnum == -1 || regnum == I387_FISEG_REGNUM (tdep))
2800         regcache_raw_collect (regcache, I387_FISEG_REGNUM (tdep),
2801                               regs + 12);
2802       if (regnum == -1 || regnum == I387_FOSEG_REGNUM (tdep))
2803         regcache_raw_collect (regcache, I387_FOSEG_REGNUM (tdep),
2804                               regs + 20);
2805     }
2806 }