4570622a17b1b303a1a6e951d6ea8ce4cf8d68ed
[external/binutils.git] / gdb / amd64-windows-tdep.c
1 /* Copyright (C) 2009-2016 Free Software Foundation, Inc.
2
3    This file is part of GDB.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #include "defs.h"
19 #include "osabi.h"
20 #include "amd64-tdep.h"
21 #include "gdbtypes.h"
22 #include "gdbcore.h"
23 #include "regcache.h"
24 #include "windows-tdep.h"
25 #include "frame.h"
26 #include "objfiles.h"
27 #include "frame-unwind.h"
28 #include "coff/internal.h"
29 #include "coff/i386.h"
30 #include "coff/pe.h"
31 #include "libcoff.h"
32 #include "value.h"
33 #include <algorithm>
34
35 /* The registers used to pass integer arguments during a function call.  */
36 static int amd64_windows_dummy_call_integer_regs[] =
37 {
38   AMD64_RCX_REGNUM,          /* %rcx */
39   AMD64_RDX_REGNUM,          /* %rdx */
40   AMD64_R8_REGNUM,           /* %r8 */
41   AMD64_R9_REGNUM            /* %r9 */
42 };
43
44 /* Return nonzero if an argument of type TYPE should be passed
45    via one of the integer registers.  */
46
47 static int
48 amd64_windows_passed_by_integer_register (struct type *type)
49 {
50   switch (TYPE_CODE (type))
51     {
52       case TYPE_CODE_INT:
53       case TYPE_CODE_ENUM:
54       case TYPE_CODE_BOOL:
55       case TYPE_CODE_RANGE:
56       case TYPE_CODE_CHAR:
57       case TYPE_CODE_PTR:
58       case TYPE_CODE_REF:
59       case TYPE_CODE_STRUCT:
60       case TYPE_CODE_UNION:
61         return (TYPE_LENGTH (type) == 1
62                 || TYPE_LENGTH (type) == 2
63                 || TYPE_LENGTH (type) == 4
64                 || TYPE_LENGTH (type) == 8);
65
66       default:
67         return 0;
68     }
69 }
70
71 /* Return nonzero if an argument of type TYPE should be passed
72    via one of the XMM registers.  */
73
74 static int
75 amd64_windows_passed_by_xmm_register (struct type *type)
76 {
77   return ((TYPE_CODE (type) == TYPE_CODE_FLT
78            || TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
79           && (TYPE_LENGTH (type) == 4 || TYPE_LENGTH (type) == 8));
80 }
81
82 /* Return non-zero iff an argument of the given TYPE should be passed
83    by pointer.  */
84
85 static int
86 amd64_windows_passed_by_pointer (struct type *type)
87 {
88   if (amd64_windows_passed_by_integer_register (type))
89     return 0;
90
91   if (amd64_windows_passed_by_xmm_register (type))
92     return 0;
93
94   return 1;
95 }
96
97 /* For each argument that should be passed by pointer, reserve some
98    stack space, store a copy of the argument on the stack, and replace
99    the argument by its address.  Return the new Stack Pointer value.
100
101    NARGS is the number of arguments. ARGS is the array containing
102    the value of each argument.  SP is value of the Stack Pointer.  */
103
104 static CORE_ADDR
105 amd64_windows_adjust_args_passed_by_pointer (struct value **args,
106                                              int nargs, CORE_ADDR sp)
107 {
108   int i;
109
110   for (i = 0; i < nargs; i++)
111     if (amd64_windows_passed_by_pointer (value_type (args[i])))
112       {
113         struct type *type = value_type (args[i]);
114         const gdb_byte *valbuf = value_contents (args[i]);
115         const int len = TYPE_LENGTH (type);
116
117         /* Store a copy of that argument on the stack, aligned to
118            a 16 bytes boundary, and then use the copy's address as
119            the argument.  */
120
121         sp -= len;
122         sp &= ~0xf;
123         write_memory (sp, valbuf, len);
124
125         args[i]
126           = value_addr (value_from_contents_and_address (type, valbuf, sp));
127       }
128
129   return sp;
130 }
131
132 /* Store the value of ARG in register REGNO (right-justified).
133    REGCACHE is the register cache.  */
134
135 static void
136 amd64_windows_store_arg_in_reg (struct regcache *regcache,
137                                 struct value *arg, int regno)
138 {
139   struct type *type = value_type (arg);
140   const gdb_byte *valbuf = value_contents (arg);
141   gdb_byte buf[8];
142
143   gdb_assert (TYPE_LENGTH (type) <= 8);
144   memset (buf, 0, sizeof buf);
145   memcpy (buf, valbuf, std::min (TYPE_LENGTH (type), (unsigned int) 8));
146   regcache_cooked_write (regcache, regno, buf);
147 }
148
149 /* Push the arguments for an inferior function call, and return
150    the updated value of the SP (Stack Pointer).
151
152    All arguments are identical to the arguments used in
153    amd64_windows_push_dummy_call.  */
154
155 static CORE_ADDR
156 amd64_windows_push_arguments (struct regcache *regcache, int nargs,
157                               struct value **args, CORE_ADDR sp,
158                               int struct_return)
159 {
160   int reg_idx = 0;
161   int i;
162   struct value **stack_args = XALLOCAVEC (struct value *, nargs);
163   int num_stack_args = 0;
164   int num_elements = 0;
165   int element = 0;
166
167   /* First, handle the arguments passed by pointer.
168
169      These arguments are replaced by pointers to a copy we are making
170      in inferior memory.  So use a copy of the ARGS table, to avoid
171      modifying the original one.  */
172   {
173     struct value **args1 = XALLOCAVEC (struct value *, nargs);
174
175     memcpy (args1, args, nargs * sizeof (struct value *));
176     sp = amd64_windows_adjust_args_passed_by_pointer (args1, nargs, sp);
177     args = args1;
178   }
179
180   /* Reserve a register for the "hidden" argument.  */
181   if (struct_return)
182     reg_idx++;
183
184   for (i = 0; i < nargs; i++)
185     {
186       struct type *type = value_type (args[i]);
187       int len = TYPE_LENGTH (type);
188       int on_stack_p = 1;
189
190       if (reg_idx < ARRAY_SIZE (amd64_windows_dummy_call_integer_regs))
191         {
192           if (amd64_windows_passed_by_integer_register (type))
193             {
194               amd64_windows_store_arg_in_reg
195                 (regcache, args[i],
196                  amd64_windows_dummy_call_integer_regs[reg_idx]);
197               on_stack_p = 0;
198               reg_idx++;
199             }
200           else if (amd64_windows_passed_by_xmm_register (type))
201             {
202               amd64_windows_store_arg_in_reg
203                 (regcache, args[i], AMD64_XMM0_REGNUM + reg_idx);
204               /* In case of varargs, these parameters must also be
205                  passed via the integer registers.  */
206               amd64_windows_store_arg_in_reg
207                 (regcache, args[i],
208                  amd64_windows_dummy_call_integer_regs[reg_idx]);
209               on_stack_p = 0;
210               reg_idx++;
211             }
212         }
213
214       if (on_stack_p)
215         {
216           num_elements += ((len + 7) / 8);
217           stack_args[num_stack_args++] = args[i];
218         }
219     }
220
221   /* Allocate space for the arguments on the stack, keeping it
222      aligned on a 16 byte boundary.  */
223   sp -= num_elements * 8;
224   sp &= ~0xf;
225
226   /* Write out the arguments to the stack.  */
227   for (i = 0; i < num_stack_args; i++)
228     {
229       struct type *type = value_type (stack_args[i]);
230       const gdb_byte *valbuf = value_contents (stack_args[i]);
231
232       write_memory (sp + element * 8, valbuf, TYPE_LENGTH (type));
233       element += ((TYPE_LENGTH (type) + 7) / 8);
234     }
235
236   return sp;
237 }
238
239 /* Implement the "push_dummy_call" gdbarch method.  */
240
241 static CORE_ADDR
242 amd64_windows_push_dummy_call
243   (struct gdbarch *gdbarch, struct value *function,
244    struct regcache *regcache, CORE_ADDR bp_addr,
245    int nargs, struct value **args,
246    CORE_ADDR sp, int struct_return, CORE_ADDR struct_addr)
247 {
248   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
249   gdb_byte buf[8];
250
251   /* Pass arguments.  */
252   sp = amd64_windows_push_arguments (regcache, nargs, args, sp,
253                                      struct_return);
254
255   /* Pass "hidden" argument".  */
256   if (struct_return)
257     {
258       /* The "hidden" argument is passed throught the first argument
259          register.  */
260       const int arg_regnum = amd64_windows_dummy_call_integer_regs[0];
261
262       store_unsigned_integer (buf, 8, byte_order, struct_addr);
263       regcache_cooked_write (regcache, arg_regnum, buf);
264     }
265
266   /* Reserve some memory on the stack for the integer-parameter
267      registers, as required by the ABI.  */
268   sp -= ARRAY_SIZE (amd64_windows_dummy_call_integer_regs) * 8;
269
270   /* Store return address.  */
271   sp -= 8;
272   store_unsigned_integer (buf, 8, byte_order, bp_addr);
273   write_memory (sp, buf, 8);
274
275   /* Update the stack pointer...  */
276   store_unsigned_integer (buf, 8, byte_order, sp);
277   regcache_cooked_write (regcache, AMD64_RSP_REGNUM, buf);
278
279   /* ...and fake a frame pointer.  */
280   regcache_cooked_write (regcache, AMD64_RBP_REGNUM, buf);
281
282   return sp + 16;
283 }
284
285 /* Implement the "return_value" gdbarch method for amd64-windows.  */
286
287 static enum return_value_convention
288 amd64_windows_return_value (struct gdbarch *gdbarch, struct value *function,
289                             struct type *type, struct regcache *regcache,
290                             gdb_byte *readbuf, const gdb_byte *writebuf)
291 {
292   int len = TYPE_LENGTH (type);
293   int regnum = -1;
294
295   /* See if our value is returned through a register.  If it is, then
296      store the associated register number in REGNUM.  */
297   switch (TYPE_CODE (type))
298     {
299       case TYPE_CODE_FLT:
300       case TYPE_CODE_DECFLOAT:
301         /* __m128, __m128i, __m128d, floats, and doubles are returned
302            via XMM0.  */
303         if (len == 4 || len == 8 || len == 16)
304           regnum = AMD64_XMM0_REGNUM;
305         break;
306       default:
307         /* All other values that are 1, 2, 4 or 8 bytes long are returned
308            via RAX.  */
309         if (len == 1 || len == 2 || len == 4 || len == 8)
310           regnum = AMD64_RAX_REGNUM;
311         break;
312     }
313
314   if (regnum < 0)
315     {
316       /* RAX contains the address where the return value has been stored.  */
317       if (readbuf)
318         {
319           ULONGEST addr;
320
321           regcache_raw_read_unsigned (regcache, AMD64_RAX_REGNUM, &addr);
322           read_memory (addr, readbuf, TYPE_LENGTH (type));
323         }
324       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
325     }
326   else
327     {
328       /* Extract the return value from the register where it was stored.  */
329       if (readbuf)
330         regcache_raw_read_part (regcache, regnum, 0, len, readbuf);
331       if (writebuf)
332         regcache_raw_write_part (regcache, regnum, 0, len, writebuf);
333       return RETURN_VALUE_REGISTER_CONVENTION;
334     }
335 }
336
337 /* Check that the code pointed to by PC corresponds to a call to
338    __main, skip it if so.  Return PC otherwise.  */
339
340 static CORE_ADDR
341 amd64_skip_main_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
342 {
343   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
344   gdb_byte op;
345
346   target_read_memory (pc, &op, 1);
347   if (op == 0xe8)
348     {
349       gdb_byte buf[4];
350
351       if (target_read_memory (pc + 1, buf, sizeof buf) == 0)
352         {
353           struct bound_minimal_symbol s;
354           CORE_ADDR call_dest;
355
356           call_dest = pc + 5 + extract_signed_integer (buf, 4, byte_order);
357           s = lookup_minimal_symbol_by_pc (call_dest);
358           if (s.minsym != NULL
359               && MSYMBOL_LINKAGE_NAME (s.minsym) != NULL
360               && strcmp (MSYMBOL_LINKAGE_NAME (s.minsym), "__main") == 0)
361             pc += 5;
362         }
363     }
364
365   return pc;
366 }
367
368 struct amd64_windows_frame_cache
369 {
370   /* ImageBase for the module.  */
371   CORE_ADDR image_base;
372
373   /* Function start and end rva.  */
374   CORE_ADDR start_rva;
375   CORE_ADDR end_rva;
376
377   /* Next instruction to be executed.  */
378   CORE_ADDR pc;
379
380   /* Current sp.  */
381   CORE_ADDR sp;
382
383   /* Address of saved integer and xmm registers.  */
384   CORE_ADDR prev_reg_addr[16];
385   CORE_ADDR prev_xmm_addr[16];
386
387   /* These two next fields are set only for machine info frames.  */
388
389   /* Likewise for RIP.  */
390   CORE_ADDR prev_rip_addr;
391
392   /* Likewise for RSP.  */
393   CORE_ADDR prev_rsp_addr;
394
395   /* Address of the previous frame.  */
396   CORE_ADDR prev_sp;
397 };
398
399 /* Convert a Windows register number to gdb.  */
400 static const enum amd64_regnum amd64_windows_w2gdb_regnum[] =
401 {
402   AMD64_RAX_REGNUM,
403   AMD64_RCX_REGNUM,
404   AMD64_RDX_REGNUM,
405   AMD64_RBX_REGNUM,
406   AMD64_RSP_REGNUM,
407   AMD64_RBP_REGNUM,
408   AMD64_RSI_REGNUM,
409   AMD64_RDI_REGNUM,
410   AMD64_R8_REGNUM,
411   AMD64_R9_REGNUM,
412   AMD64_R10_REGNUM,
413   AMD64_R11_REGNUM,
414   AMD64_R12_REGNUM,
415   AMD64_R13_REGNUM,
416   AMD64_R14_REGNUM,
417   AMD64_R15_REGNUM
418 };
419
420 /* Return TRUE iff PC is the the range of the function corresponding to
421    CACHE.  */
422
423 static int
424 pc_in_range (CORE_ADDR pc, const struct amd64_windows_frame_cache *cache)
425 {
426   return (pc >= cache->image_base + cache->start_rva
427           && pc < cache->image_base + cache->end_rva);
428 }
429
430 /* Try to recognize and decode an epilogue sequence.
431
432    Return -1 if we fail to read the instructions for any reason.
433    Return 1 if an epilogue sequence was recognized, 0 otherwise.  */
434
435 static int
436 amd64_windows_frame_decode_epilogue (struct frame_info *this_frame,
437                                      struct amd64_windows_frame_cache *cache)
438 {
439   /* According to MSDN an epilogue "must consist of either an add RSP,constant
440      or lea RSP,constant[FPReg], followed by a series of zero or more 8-byte
441      register pops and a return or a jmp".
442
443      Furthermore, according to RtlVirtualUnwind, the complete list of
444      epilog marker is:
445      - ret                      [c3]
446      - ret n                    [c2 imm16]
447      - rep ret                  [f3 c3]
448      - jmp imm8 | imm32         [eb rel8] or [e9 rel32]
449      - jmp qword ptr imm32                 - not handled
450      - rex.w jmp reg            [4X ff eY]
451   */
452
453   CORE_ADDR pc = cache->pc;
454   CORE_ADDR cur_sp = cache->sp;
455   struct gdbarch *gdbarch = get_frame_arch (this_frame);
456   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
457   gdb_byte op;
458   gdb_byte rex;
459
460   /* We don't care about the instruction deallocating the frame:
461      if it hasn't been executed, the pc is still in the body,
462      if it has been executed, the following epilog decoding will work.  */
463
464   /* First decode:
465      -  pop reg                 [41 58-5f] or [58-5f].  */
466
467   while (1)
468     {
469       /* Read opcode. */
470       if (target_read_memory (pc, &op, 1) != 0)
471         return -1;
472
473       if (op >= 0x40 && op <= 0x4f)
474         {
475           /* REX prefix.  */
476           rex = op;
477
478           /* Read opcode. */
479           if (target_read_memory (pc + 1, &op, 1) != 0)
480             return -1;
481         }
482       else
483         rex = 0;
484
485       if (op >= 0x58 && op <= 0x5f)
486         {
487           /* pop reg  */
488           gdb_byte reg = (op & 0x0f) | ((rex & 1) << 3);
489
490           cache->prev_reg_addr[amd64_windows_w2gdb_regnum[reg]] = cur_sp;
491           cur_sp += 8;
492           pc += rex ? 2 : 1;
493         }
494       else
495         break;
496
497       /* Allow the user to break this loop.  This shouldn't happen as the
498          number of consecutive pop should be small.  */
499       QUIT;
500     }
501
502   /* Then decode the marker.  */
503
504   /* Read opcode.  */
505   if (target_read_memory (pc, &op, 1) != 0)
506     return -1;
507
508   switch (op)
509     {
510     case 0xc3:
511       /* Ret.  */
512       cache->prev_rip_addr = cur_sp;
513       cache->prev_sp = cur_sp + 8;
514       return 1;
515
516     case 0xeb:
517       {
518         /* jmp rel8  */
519         gdb_byte rel8;
520         CORE_ADDR npc;
521
522         if (target_read_memory (pc + 1, &rel8, 1) != 0)
523           return -1;
524         npc = pc + 2 + (signed char) rel8;
525
526         /* If the jump is within the function, then this is not a marker,
527            otherwise this is a tail-call.  */
528         return !pc_in_range (npc, cache);
529       }
530
531     case 0xec:
532       {
533         /* jmp rel32  */
534         gdb_byte rel32[4];
535         CORE_ADDR npc;
536
537         if (target_read_memory (pc + 1, rel32, 4) != 0)
538           return -1;
539         npc = pc + 5 + extract_signed_integer (rel32, 4, byte_order);
540
541         /* If the jump is within the function, then this is not a marker,
542            otherwise this is a tail-call.  */
543         return !pc_in_range (npc, cache);
544       }
545
546     case 0xc2:
547       {
548         /* ret n  */
549         gdb_byte imm16[2];
550
551         if (target_read_memory (pc + 1, imm16, 2) != 0)
552           return -1;
553         cache->prev_rip_addr = cur_sp;
554         cache->prev_sp = cur_sp
555           + extract_unsigned_integer (imm16, 4, byte_order);
556         return 1;
557       }
558
559     case 0xf3:
560       {
561         /* rep; ret  */
562         gdb_byte op1;
563
564         if (target_read_memory (pc + 2, &op1, 1) != 0)
565           return -1;
566         if (op1 != 0xc3)
567           return 0;
568
569         cache->prev_rip_addr = cur_sp;
570         cache->prev_sp = cur_sp + 8;
571         return 1;
572       }
573
574     case 0x40:
575     case 0x41:
576     case 0x42:
577     case 0x43:
578     case 0x44:
579     case 0x45:
580     case 0x46:
581     case 0x47:
582     case 0x48:
583     case 0x49:
584     case 0x4a:
585     case 0x4b:
586     case 0x4c:
587     case 0x4d:
588     case 0x4e:
589     case 0x4f:
590       /* Got a REX prefix, read next byte.  */
591       rex = op;
592       if (target_read_memory (pc + 1, &op, 1) != 0)
593         return -1;
594
595       if (op == 0xff)
596         {
597           /* rex jmp reg  */
598           gdb_byte op1;
599
600           if (target_read_memory (pc + 2, &op1, 1) != 0)
601             return -1;
602           return (op1 & 0xf8) == 0xe0;
603         }
604       else
605         return 0;
606
607     default:
608       /* Not REX, so unknown.  */
609       return 0;
610     }
611 }
612
613 /* Decode and execute unwind insns at UNWIND_INFO.  */
614
615 static void
616 amd64_windows_frame_decode_insns (struct frame_info *this_frame,
617                                   struct amd64_windows_frame_cache *cache,
618                                   CORE_ADDR unwind_info)
619 {
620   CORE_ADDR save_addr = 0;
621   CORE_ADDR cur_sp = cache->sp;
622   struct gdbarch *gdbarch = get_frame_arch (this_frame);
623   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
624   int first = 1;
625
626   /* There are at least 3 possibilities to share an unwind info entry:
627      1. Two different runtime_function entries (in .pdata) can point to the
628         same unwind info entry.  There is no such indication while unwinding,
629         so we don't really care about that case.  We suppose this scheme is
630         used to save memory when the unwind entries are exactly the same.
631      2. Chained unwind_info entries, with no unwind codes (no prologue).
632         There is a major difference with the previous case: the pc range for
633         the function is different (in case 1, the pc range comes from the
634         runtime_function entry; in case 2, the pc range for the chained entry
635         comes from the first unwind entry).  Case 1 cannot be used instead as
636         the pc is not in the prologue.  This case is officially documented.
637         (There might be unwind code in the first unwind entry to handle
638         additional unwinding).  GCC (at least until gcc 5.0) doesn't chain
639         entries.
640      3. Undocumented unwind info redirection.  Hard to know the exact purpose,
641         so it is considered as a memory optimization of case 2.
642   */
643
644   if (unwind_info & 1)
645     {
646       /* Unofficially documented unwind info redirection, when UNWIND_INFO
647          address is odd (http://www.codemachine.com/article_x64deepdive.html).
648       */
649       struct external_pex64_runtime_function d;
650
651       if (target_read_memory (cache->image_base + (unwind_info & ~1),
652                               (gdb_byte *) &d, sizeof (d)) != 0)
653         return;
654
655       cache->start_rva
656         = extract_unsigned_integer (d.rva_BeginAddress, 4, byte_order);
657       cache->end_rva
658         = extract_unsigned_integer (d.rva_EndAddress, 4, byte_order);
659       unwind_info
660         = extract_unsigned_integer (d.rva_UnwindData, 4, byte_order);
661     }
662
663   while (1)
664     {
665       struct external_pex64_unwind_info ex_ui;
666       /* There are at most 256 16-bit unwind insns.  */
667       gdb_byte insns[2 * 256];
668       gdb_byte *p;
669       gdb_byte *end_insns;
670       unsigned char codes_count;
671       unsigned char frame_reg;
672       CORE_ADDR start;
673
674       /* Read and decode header.  */
675       if (target_read_memory (cache->image_base + unwind_info,
676                               (gdb_byte *) &ex_ui, sizeof (ex_ui)) != 0)
677         return;
678
679       if (frame_debug)
680         fprintf_unfiltered
681           (gdb_stdlog,
682            "amd64_windows_frame_decodes_insn: "
683            "%s: ver: %02x, plgsz: %02x, cnt: %02x, frame: %02x\n",
684            paddress (gdbarch, unwind_info),
685            ex_ui.Version_Flags, ex_ui.SizeOfPrologue,
686            ex_ui.CountOfCodes, ex_ui.FrameRegisterOffset);
687
688       /* Check version.  */
689       if (PEX64_UWI_VERSION (ex_ui.Version_Flags) != 1
690           && PEX64_UWI_VERSION (ex_ui.Version_Flags) != 2)
691         return;
692
693       start = cache->image_base + cache->start_rva;
694       if (first
695           && !(cache->pc >= start && cache->pc < start + ex_ui.SizeOfPrologue))
696         {
697           /* We want to detect if the PC points to an epilogue.  This needs
698              to be checked only once, and an epilogue can be anywhere but in
699              the prologue.  If so, the epilogue detection+decoding function is
700              sufficient.  Otherwise, the unwinder will consider that the PC
701              is in the body of the function and will need to decode unwind
702              info.  */
703           if (amd64_windows_frame_decode_epilogue (this_frame, cache) == 1)
704             return;
705
706           /* Not in an epilog.  Clear possible side effects.  */
707           memset (cache->prev_reg_addr, 0, sizeof (cache->prev_reg_addr));
708         }
709
710       codes_count = ex_ui.CountOfCodes;
711       frame_reg = PEX64_UWI_FRAMEREG (ex_ui.FrameRegisterOffset);
712
713       if (frame_reg != 0)
714         {
715           /* According to msdn:
716              If an FP reg is used, then any unwind code taking an offset must
717              only be used after the FP reg is established in the prolog.  */
718           gdb_byte buf[8];
719           int frreg = amd64_windows_w2gdb_regnum[frame_reg];
720
721           get_frame_register (this_frame, frreg, buf);
722           save_addr = extract_unsigned_integer (buf, 8, byte_order);
723
724           if (frame_debug)
725             fprintf_unfiltered (gdb_stdlog, "   frame_reg=%s, val=%s\n",
726                                 gdbarch_register_name (gdbarch, frreg),
727                                 paddress (gdbarch, save_addr));
728         }
729
730       /* Read opcodes.  */
731       if (codes_count != 0
732           && target_read_memory (cache->image_base + unwind_info
733                                  + sizeof (ex_ui),
734                                  insns, codes_count * 2) != 0)
735         return;
736
737       end_insns = &insns[codes_count * 2];
738       p = insns;
739
740       /* Skip opcodes 6 of version 2.  This opcode is not documented.  */
741       if (PEX64_UWI_VERSION (ex_ui.Version_Flags) == 2)
742         {
743           for (; p < end_insns; p += 2)
744             if (PEX64_UNWCODE_CODE (p[1]) != 6)
745               break;
746         }
747
748       for (; p < end_insns; p += 2)
749         {
750           int reg;
751
752           /* Virtually execute the operation if the pc is after the
753              corresponding instruction (that does matter in case of break
754              within the prologue).  Note that for chained info (!first), the
755              prologue has been fully executed.  */
756           if (cache->pc >= start + p[0] || cache->pc < start)
757             {
758               if (frame_debug)
759                 fprintf_unfiltered
760                   (gdb_stdlog, "   op #%u: off=0x%02x, insn=0x%02x\n",
761                    (unsigned) (p - insns), p[0], p[1]);
762
763               /* If there is no frame registers defined, the current value of
764                  rsp is used instead.  */
765               if (frame_reg == 0)
766                 save_addr = cur_sp;
767
768               reg = -1;
769
770               switch (PEX64_UNWCODE_CODE (p[1]))
771                 {
772                 case UWOP_PUSH_NONVOL:
773                   /* Push pre-decrements RSP.  */
774                   reg = amd64_windows_w2gdb_regnum[PEX64_UNWCODE_INFO (p[1])];
775                   cache->prev_reg_addr[reg] = cur_sp;
776                   cur_sp += 8;
777                   break;
778                 case UWOP_ALLOC_LARGE:
779                   if (PEX64_UNWCODE_INFO (p[1]) == 0)
780                     cur_sp +=
781                       8 * extract_unsigned_integer (p + 2, 2, byte_order);
782                   else if (PEX64_UNWCODE_INFO (p[1]) == 1)
783                     cur_sp += extract_unsigned_integer (p + 2, 4, byte_order);
784                   else
785                     return;
786                   break;
787                 case UWOP_ALLOC_SMALL:
788                   cur_sp += 8 + 8 * PEX64_UNWCODE_INFO (p[1]);
789                   break;
790                 case UWOP_SET_FPREG:
791                   cur_sp = save_addr
792                     - PEX64_UWI_FRAMEOFF (ex_ui.FrameRegisterOffset) * 16;
793                   break;
794                 case UWOP_SAVE_NONVOL:
795                   reg = amd64_windows_w2gdb_regnum[PEX64_UNWCODE_INFO (p[1])];
796                   cache->prev_reg_addr[reg] = save_addr
797                     + 8 * extract_unsigned_integer (p + 2, 2, byte_order);
798                   break;
799                 case UWOP_SAVE_NONVOL_FAR:
800                   reg = amd64_windows_w2gdb_regnum[PEX64_UNWCODE_INFO (p[1])];
801                   cache->prev_reg_addr[reg] = save_addr
802                     + 8 * extract_unsigned_integer (p + 2, 4, byte_order);
803                   break;
804                 case UWOP_SAVE_XMM128:
805                   cache->prev_xmm_addr[PEX64_UNWCODE_INFO (p[1])] =
806                     save_addr
807                     - 16 * extract_unsigned_integer (p + 2, 2, byte_order);
808                   break;
809                 case UWOP_SAVE_XMM128_FAR:
810                   cache->prev_xmm_addr[PEX64_UNWCODE_INFO (p[1])] =
811                     save_addr
812                     - 16 * extract_unsigned_integer (p + 2, 4, byte_order);
813                   break;
814                 case UWOP_PUSH_MACHFRAME:
815                   if (PEX64_UNWCODE_INFO (p[1]) == 0)
816                     {
817                       cache->prev_rip_addr = cur_sp + 0;
818                       cache->prev_rsp_addr = cur_sp + 24;
819                       cur_sp += 40;
820                     }
821                   else if (PEX64_UNWCODE_INFO (p[1]) == 1)
822                     {
823                       cache->prev_rip_addr = cur_sp + 8;
824                       cache->prev_rsp_addr = cur_sp + 32;
825                       cur_sp += 48;
826                     }
827                   else
828                     return;
829                   break;
830                 default:
831                   return;
832                 }
833
834               /* Display address where the register was saved.  */
835               if (frame_debug && reg >= 0)
836                 fprintf_unfiltered
837                   (gdb_stdlog, "     [reg %s at %s]\n",
838                    gdbarch_register_name (gdbarch, reg),
839                    paddress (gdbarch, cache->prev_reg_addr[reg]));
840             }
841
842           /* Adjust with the length of the opcode.  */
843           switch (PEX64_UNWCODE_CODE (p[1]))
844             {
845             case UWOP_PUSH_NONVOL:
846             case UWOP_ALLOC_SMALL:
847             case UWOP_SET_FPREG:
848             case UWOP_PUSH_MACHFRAME:
849               break;
850             case UWOP_ALLOC_LARGE:
851               if (PEX64_UNWCODE_INFO (p[1]) == 0)
852                 p += 2;
853               else if (PEX64_UNWCODE_INFO (p[1]) == 1)
854                 p += 4;
855               else
856                 return;
857               break;
858             case UWOP_SAVE_NONVOL:
859             case UWOP_SAVE_XMM128:
860               p += 2;
861               break;
862             case UWOP_SAVE_NONVOL_FAR:
863             case UWOP_SAVE_XMM128_FAR:
864               p += 4;
865               break;
866             default:
867               return;
868             }
869         }
870       if (PEX64_UWI_FLAGS (ex_ui.Version_Flags) != UNW_FLAG_CHAININFO)
871         {
872           /* End of unwind info.  */
873           break;
874         }
875       else
876         {
877           /* Read the chained unwind info.  */
878           struct external_pex64_runtime_function d;
879           CORE_ADDR chain_vma;
880
881           /* Not anymore the first entry.  */
882           first = 0;
883
884           /* Stay aligned on word boundary.  */
885           chain_vma = cache->image_base + unwind_info
886             + sizeof (ex_ui) + ((codes_count + 1) & ~1) * 2;
887
888           if (target_read_memory (chain_vma, (gdb_byte *) &d, sizeof (d)) != 0)
889             return;
890
891           /* Decode begin/end.  This may be different from .pdata index, as
892              an unwind info may be shared by several functions (in particular
893              if many functions have the same prolog and handler.  */
894           cache->start_rva =
895             extract_unsigned_integer (d.rva_BeginAddress, 4, byte_order);
896           cache->end_rva =
897             extract_unsigned_integer (d.rva_EndAddress, 4, byte_order);
898           unwind_info =
899             extract_unsigned_integer (d.rva_UnwindData, 4, byte_order);
900
901           if (frame_debug)
902             fprintf_unfiltered
903               (gdb_stdlog,
904                "amd64_windows_frame_decodes_insn (next in chain):"
905                " unwind_data=%s, start_rva=%s, end_rva=%s\n",
906                paddress (gdbarch, unwind_info),
907                paddress (gdbarch, cache->start_rva),
908                paddress (gdbarch, cache->end_rva));
909         }
910
911       /* Allow the user to break this loop.  */
912       QUIT;
913     }
914   /* PC is saved by the call.  */
915   if (cache->prev_rip_addr == 0)
916     cache->prev_rip_addr = cur_sp;
917   cache->prev_sp = cur_sp + 8;
918
919   if (frame_debug)
920     fprintf_unfiltered (gdb_stdlog, "   prev_sp: %s, prev_pc @%s\n",
921                         paddress (gdbarch, cache->prev_sp),
922                         paddress (gdbarch, cache->prev_rip_addr));
923 }
924
925 /* Find SEH unwind info for PC, returning 0 on success.
926
927    UNWIND_INFO is set to the rva of unwind info address, IMAGE_BASE
928    to the base address of the corresponding image, and START_RVA
929    to the rva of the function containing PC.  */
930
931 static int
932 amd64_windows_find_unwind_info (struct gdbarch *gdbarch, CORE_ADDR pc,
933                                 CORE_ADDR *unwind_info,
934                                 CORE_ADDR *image_base,
935                                 CORE_ADDR *start_rva,
936                                 CORE_ADDR *end_rva)
937 {
938   struct obj_section *sec;
939   pe_data_type *pe;
940   IMAGE_DATA_DIRECTORY *dir;
941   struct objfile *objfile;
942   unsigned long lo, hi;
943   CORE_ADDR base;
944   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
945
946   /* Get the corresponding exception directory.  */
947   sec = find_pc_section (pc);
948   if (sec == NULL)
949     return -1;
950   objfile = sec->objfile;
951   pe = pe_data (sec->objfile->obfd);
952   dir = &pe->pe_opthdr.DataDirectory[PE_EXCEPTION_TABLE];
953
954   base = pe->pe_opthdr.ImageBase
955     + ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
956   *image_base = base;
957
958   /* Find the entry.
959
960      Note: This does not handle dynamically added entries (for JIT
961      engines).  For this, we would need to ask the kernel directly,
962      which means getting some info from the native layer.  For the
963      rest of the code, however, it's probably faster to search
964      the entry ourselves.  */
965   lo = 0;
966   hi = dir->Size / sizeof (struct external_pex64_runtime_function);
967   *unwind_info = 0;
968   while (lo <= hi)
969     {
970       unsigned long mid = lo + (hi - lo) / 2;
971       struct external_pex64_runtime_function d;
972       CORE_ADDR sa, ea;
973
974       if (target_read_memory (base + dir->VirtualAddress + mid * sizeof (d),
975                               (gdb_byte *) &d, sizeof (d)) != 0)
976         return -1;
977
978       sa = extract_unsigned_integer (d.rva_BeginAddress, 4, byte_order);
979       ea = extract_unsigned_integer (d.rva_EndAddress, 4, byte_order);
980       if (pc < base + sa)
981         hi = mid - 1;
982       else if (pc >= base + ea)
983         lo = mid + 1;
984       else if (pc >= base + sa && pc < base + ea)
985         {
986           /* Got it.  */
987           *start_rva = sa;
988           *end_rva = ea;
989           *unwind_info =
990             extract_unsigned_integer (d.rva_UnwindData, 4, byte_order);
991           break;
992         }
993       else
994         break;
995     }
996
997   if (frame_debug)
998     fprintf_unfiltered
999       (gdb_stdlog,
1000        "amd64_windows_find_unwind_data:  image_base=%s, unwind_data=%s\n",
1001        paddress (gdbarch, base), paddress (gdbarch, *unwind_info));
1002
1003   return 0;
1004 }
1005
1006 /* Fill THIS_CACHE using the native amd64-windows unwinding data
1007    for THIS_FRAME.  */
1008
1009 static struct amd64_windows_frame_cache *
1010 amd64_windows_frame_cache (struct frame_info *this_frame, void **this_cache)
1011 {
1012   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1013   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1014   struct amd64_windows_frame_cache *cache;
1015   gdb_byte buf[8];
1016   CORE_ADDR pc;
1017   CORE_ADDR unwind_info = 0;
1018
1019   if (*this_cache)
1020     return (struct amd64_windows_frame_cache *) *this_cache;
1021
1022   cache = FRAME_OBSTACK_ZALLOC (struct amd64_windows_frame_cache);
1023   *this_cache = cache;
1024
1025   /* Get current PC and SP.  */
1026   pc = get_frame_pc (this_frame);
1027   get_frame_register (this_frame, AMD64_RSP_REGNUM, buf);
1028   cache->sp = extract_unsigned_integer (buf, 8, byte_order);
1029   cache->pc = pc;
1030
1031   if (amd64_windows_find_unwind_info (gdbarch, pc, &unwind_info,
1032                                       &cache->image_base,
1033                                       &cache->start_rva,
1034                                       &cache->end_rva))
1035     return cache;
1036
1037   if (unwind_info == 0)
1038     {
1039       /* Assume a leaf function.  */
1040       cache->prev_sp = cache->sp + 8;
1041       cache->prev_rip_addr = cache->sp;
1042     }
1043   else
1044     {
1045       /* Decode unwind insns to compute saved addresses.  */
1046       amd64_windows_frame_decode_insns (this_frame, cache, unwind_info);
1047     }
1048   return cache;
1049 }
1050
1051 /* Implement the "prev_register" method of struct frame_unwind
1052    using the standard Windows x64 SEH info.  */
1053
1054 static struct value *
1055 amd64_windows_frame_prev_register (struct frame_info *this_frame,
1056                                    void **this_cache, int regnum)
1057 {
1058   struct gdbarch *gdbarch = get_frame_arch (this_frame);
1059   struct amd64_windows_frame_cache *cache =
1060     amd64_windows_frame_cache (this_frame, this_cache);
1061   CORE_ADDR prev;
1062
1063   if (frame_debug)
1064     fprintf_unfiltered (gdb_stdlog,
1065                         "amd64_windows_frame_prev_register %s for sp=%s\n",
1066                         gdbarch_register_name (gdbarch, regnum),
1067                         paddress (gdbarch, cache->prev_sp));
1068
1069   if (regnum >= AMD64_XMM0_REGNUM && regnum <= AMD64_XMM0_REGNUM + 15)
1070       prev = cache->prev_xmm_addr[regnum - AMD64_XMM0_REGNUM];
1071   else if (regnum == AMD64_RSP_REGNUM)
1072     {
1073       prev = cache->prev_rsp_addr;
1074       if (prev == 0)
1075         return frame_unwind_got_constant (this_frame, regnum, cache->prev_sp);
1076     }
1077   else if (regnum >= AMD64_RAX_REGNUM && regnum <= AMD64_R15_REGNUM)
1078     prev = cache->prev_reg_addr[regnum - AMD64_RAX_REGNUM];
1079   else if (regnum == AMD64_RIP_REGNUM)
1080     prev = cache->prev_rip_addr;
1081   else
1082     prev = 0;
1083
1084   if (prev && frame_debug)
1085     fprintf_unfiltered (gdb_stdlog, "  -> at %s\n", paddress (gdbarch, prev));
1086
1087   if (prev)
1088     {
1089       /* Register was saved.  */
1090       return frame_unwind_got_memory (this_frame, regnum, prev);
1091     }
1092   else
1093     {
1094       /* Register is either volatile or not modified.  */
1095       return frame_unwind_got_register (this_frame, regnum, regnum);
1096     }
1097 }
1098
1099 /* Implement the "this_id" method of struct frame_unwind using
1100    the standard Windows x64 SEH info.  */
1101
1102 static void
1103 amd64_windows_frame_this_id (struct frame_info *this_frame, void **this_cache,
1104                    struct frame_id *this_id)
1105 {
1106   struct amd64_windows_frame_cache *cache =
1107     amd64_windows_frame_cache (this_frame, this_cache);
1108
1109   *this_id = frame_id_build (cache->prev_sp,
1110                              cache->image_base + cache->start_rva);
1111 }
1112
1113 /* Windows x64 SEH unwinder.  */
1114
1115 static const struct frame_unwind amd64_windows_frame_unwind =
1116 {
1117   NORMAL_FRAME,
1118   default_frame_unwind_stop_reason,
1119   &amd64_windows_frame_this_id,
1120   &amd64_windows_frame_prev_register,
1121   NULL,
1122   default_frame_sniffer
1123 };
1124
1125 /* Implement the "skip_prologue" gdbarch method.  */
1126
1127 static CORE_ADDR
1128 amd64_windows_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
1129 {
1130   CORE_ADDR func_addr;
1131   CORE_ADDR unwind_info = 0;
1132   CORE_ADDR image_base, start_rva, end_rva;
1133   struct external_pex64_unwind_info ex_ui;
1134
1135   /* Use prologue size from unwind info.  */
1136   if (amd64_windows_find_unwind_info (gdbarch, pc, &unwind_info,
1137                                       &image_base, &start_rva, &end_rva) == 0)
1138     {
1139       if (unwind_info == 0)
1140         {
1141           /* Leaf function.  */
1142           return pc;
1143         }
1144       else if (target_read_memory (image_base + unwind_info,
1145                                    (gdb_byte *) &ex_ui, sizeof (ex_ui)) == 0
1146                && PEX64_UWI_VERSION (ex_ui.Version_Flags) == 1)
1147         return std::max (pc, image_base + start_rva + ex_ui.SizeOfPrologue);
1148     }
1149
1150   /* See if we can determine the end of the prologue via the symbol
1151      table.  If so, then return either the PC, or the PC after
1152      the prologue, whichever is greater.  */
1153   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
1154     {
1155       CORE_ADDR post_prologue_pc
1156         = skip_prologue_using_sal (gdbarch, func_addr);
1157
1158       if (post_prologue_pc != 0)
1159         return std::max (pc, post_prologue_pc);
1160     }
1161
1162   return pc;
1163 }
1164
1165 /* Check Win64 DLL jmp trampolines and find jump destination.  */
1166
1167 static CORE_ADDR
1168 amd64_windows_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc)
1169 {
1170   CORE_ADDR destination = 0;
1171   struct gdbarch *gdbarch = get_frame_arch (frame);
1172   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1173
1174   /* Check for jmp *<offset>(%rip) (jump near, absolute indirect (/4)).  */
1175   if (pc && read_memory_unsigned_integer (pc, 2, byte_order) == 0x25ff)
1176     {
1177       /* Get opcode offset and see if we can find a reference in our data.  */
1178       ULONGEST offset
1179         = read_memory_unsigned_integer (pc + 2, 4, byte_order);
1180
1181       /* Get address of function pointer at end of pc.  */
1182       CORE_ADDR indirect_addr = pc + offset + 6;
1183
1184       struct minimal_symbol *indsym
1185         = (indirect_addr
1186            ? lookup_minimal_symbol_by_pc (indirect_addr).minsym
1187            : NULL);
1188       const char *symname = indsym ? MSYMBOL_LINKAGE_NAME (indsym) : NULL;
1189
1190       if (symname)
1191         {
1192           if (startswith (symname, "__imp_")
1193               || startswith (symname, "_imp_"))
1194             destination
1195               = read_memory_unsigned_integer (indirect_addr, 8, byte_order);
1196         }
1197     }
1198
1199   return destination;
1200 }
1201
1202 /* Implement the "auto_wide_charset" gdbarch method.  */
1203
1204 static const char *
1205 amd64_windows_auto_wide_charset (void)
1206 {
1207   return "UTF-16";
1208 }
1209
1210 static void
1211 amd64_windows_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
1212 {
1213   /* The dwarf2 unwinder (appended very early by i386_gdbarch_init) is
1214      preferred over the SEH one.  The reasons are:
1215      - binaries without SEH but with dwarf2 debug info are correcly handled
1216        (although they aren't ABI compliant, gcc before 4.7 didn't emit SEH
1217        info).
1218      - dwarf3 DW_OP_call_frame_cfa is correctly handled (it can only be
1219        handled if the dwarf2 unwinder is used).
1220
1221     The call to amd64_init_abi appends default unwinders, that aren't
1222     compatible with the SEH one.
1223   */
1224   frame_unwind_append_unwinder (gdbarch, &amd64_windows_frame_unwind);
1225
1226   amd64_init_abi (info, gdbarch);
1227
1228   windows_init_abi (info, gdbarch);
1229
1230   /* On Windows, "long"s are only 32bit.  */
1231   set_gdbarch_long_bit (gdbarch, 32);
1232
1233   /* Function calls.  */
1234   set_gdbarch_push_dummy_call (gdbarch, amd64_windows_push_dummy_call);
1235   set_gdbarch_return_value (gdbarch, amd64_windows_return_value);
1236   set_gdbarch_skip_main_prologue (gdbarch, amd64_skip_main_prologue);
1237   set_gdbarch_skip_trampoline_code (gdbarch,
1238                                     amd64_windows_skip_trampoline_code);
1239
1240   set_gdbarch_skip_prologue (gdbarch, amd64_windows_skip_prologue);
1241
1242   set_gdbarch_auto_wide_charset (gdbarch, amd64_windows_auto_wide_charset);
1243 }
1244
1245 /* -Wmissing-prototypes */
1246 extern initialize_file_ftype _initialize_amd64_windows_tdep;
1247
1248 void
1249 _initialize_amd64_windows_tdep (void)
1250 {
1251   gdbarch_register_osabi (bfd_arch_i386, bfd_mach_x86_64, GDB_OSABI_CYGWIN,
1252                           amd64_windows_init_abi);
1253 }