mf: Add MFGetSupportedMimeTypes stub.
[wine.git] / dlls / ntdll / signal_x86_64.c
blob691ee1ffdbfec875b8ffed3a48bc8aa3a0ff08b8
1 /*
2 * x86-64 signal handling routines
4 * Copyright 1999, 2005 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #ifdef __x86_64__
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <sys/types.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #ifdef HAVE_MACHINE_SYSARCH_H
36 # include <machine/sysarch.h>
37 #endif
38 #ifdef HAVE_SYS_PARAM_H
39 # include <sys/param.h>
40 #endif
41 #ifdef HAVE_SYSCALL_H
42 # include <syscall.h>
43 #else
44 # ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 # endif
47 #endif
48 #ifdef HAVE_SYS_SIGNAL_H
49 # include <sys/signal.h>
50 #endif
51 #ifdef HAVE_SYS_UCONTEXT_H
52 # include <sys/ucontext.h>
53 #endif
54 #ifdef HAVE_LIBUNWIND_H
55 # define UNW_LOCAL_ONLY
56 # include <libunwind.h>
57 #endif
59 #define NONAMELESSUNION
60 #define NONAMELESSSTRUCT
61 #include "ntstatus.h"
62 #define WIN32_NO_STATUS
63 #include "windef.h"
64 #include "winternl.h"
65 #include "wine/library.h"
66 #include "wine/exception.h"
67 #include "wine/list.h"
68 #include "ntdll_misc.h"
69 #include "wine/debug.h"
71 #ifdef HAVE_VALGRIND_MEMCHECK_H
72 #include <valgrind/memcheck.h>
73 #endif
75 WINE_DEFAULT_DEBUG_CHANNEL(seh);
77 struct _DISPATCHER_CONTEXT;
79 typedef LONG (WINAPI *PC_LANGUAGE_EXCEPTION_HANDLER)( EXCEPTION_POINTERS *ptrs, ULONG64 frame );
80 typedef EXCEPTION_DISPOSITION (WINAPI *PEXCEPTION_ROUTINE)( EXCEPTION_RECORD *rec,
81 ULONG64 frame,
82 CONTEXT *context,
83 struct _DISPATCHER_CONTEXT *dispatch );
84 typedef void (WINAPI *TERMINATION_HANDLER)( ULONG flags, ULONG64 frame );
86 typedef struct _DISPATCHER_CONTEXT
88 ULONG64 ControlPc;
89 ULONG64 ImageBase;
90 PRUNTIME_FUNCTION FunctionEntry;
91 ULONG64 EstablisherFrame;
92 ULONG64 TargetIp;
93 PCONTEXT ContextRecord;
94 PEXCEPTION_ROUTINE LanguageHandler;
95 PVOID HandlerData;
96 PUNWIND_HISTORY_TABLE HistoryTable;
97 ULONG ScopeIndex;
98 } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;
100 typedef struct _SCOPE_TABLE
102 ULONG Count;
103 struct
105 ULONG BeginAddress;
106 ULONG EndAddress;
107 ULONG HandlerAddress;
108 ULONG JumpTarget;
109 } ScopeRecord[1];
110 } SCOPE_TABLE, *PSCOPE_TABLE;
113 /* layering violation: the setjmp buffer is defined in msvcrt, but used by RtlUnwindEx */
114 struct MSVCRT_JUMP_BUFFER
116 ULONG64 Frame;
117 ULONG64 Rbx;
118 ULONG64 Rsp;
119 ULONG64 Rbp;
120 ULONG64 Rsi;
121 ULONG64 Rdi;
122 ULONG64 R12;
123 ULONG64 R13;
124 ULONG64 R14;
125 ULONG64 R15;
126 ULONG64 Rip;
127 ULONG64 Spare;
128 M128A Xmm6;
129 M128A Xmm7;
130 M128A Xmm8;
131 M128A Xmm9;
132 M128A Xmm10;
133 M128A Xmm11;
134 M128A Xmm12;
135 M128A Xmm13;
136 M128A Xmm14;
137 M128A Xmm15;
140 /***********************************************************************
141 * signal context platform-specific definitions
143 #ifdef linux
145 #include <asm/prctl.h>
146 static inline int arch_prctl( int func, void *ptr ) { return syscall( __NR_arch_prctl, func, ptr ); }
148 #define RAX_sig(context) ((context)->uc_mcontext.gregs[REG_RAX])
149 #define RBX_sig(context) ((context)->uc_mcontext.gregs[REG_RBX])
150 #define RCX_sig(context) ((context)->uc_mcontext.gregs[REG_RCX])
151 #define RDX_sig(context) ((context)->uc_mcontext.gregs[REG_RDX])
152 #define RSI_sig(context) ((context)->uc_mcontext.gregs[REG_RSI])
153 #define RDI_sig(context) ((context)->uc_mcontext.gregs[REG_RDI])
154 #define RBP_sig(context) ((context)->uc_mcontext.gregs[REG_RBP])
155 #define R8_sig(context) ((context)->uc_mcontext.gregs[REG_R8])
156 #define R9_sig(context) ((context)->uc_mcontext.gregs[REG_R9])
157 #define R10_sig(context) ((context)->uc_mcontext.gregs[REG_R10])
158 #define R11_sig(context) ((context)->uc_mcontext.gregs[REG_R11])
159 #define R12_sig(context) ((context)->uc_mcontext.gregs[REG_R12])
160 #define R13_sig(context) ((context)->uc_mcontext.gregs[REG_R13])
161 #define R14_sig(context) ((context)->uc_mcontext.gregs[REG_R14])
162 #define R15_sig(context) ((context)->uc_mcontext.gregs[REG_R15])
164 #define CS_sig(context) (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 0))
165 #define GS_sig(context) (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 1))
166 #define FS_sig(context) (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 2))
168 #define RSP_sig(context) ((context)->uc_mcontext.gregs[REG_RSP])
169 #define RIP_sig(context) ((context)->uc_mcontext.gregs[REG_RIP])
170 #define EFL_sig(context) ((context)->uc_mcontext.gregs[REG_EFL])
171 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[REG_TRAPNO])
172 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[REG_ERR])
174 #define FPU_sig(context) ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.fpregs))
176 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__)
178 #define RAX_sig(context) ((context)->uc_mcontext.mc_rax)
179 #define RBX_sig(context) ((context)->uc_mcontext.mc_rbx)
180 #define RCX_sig(context) ((context)->uc_mcontext.mc_rcx)
181 #define RDX_sig(context) ((context)->uc_mcontext.mc_rdx)
182 #define RSI_sig(context) ((context)->uc_mcontext.mc_rsi)
183 #define RDI_sig(context) ((context)->uc_mcontext.mc_rdi)
184 #define RBP_sig(context) ((context)->uc_mcontext.mc_rbp)
185 #define R8_sig(context) ((context)->uc_mcontext.mc_r8)
186 #define R9_sig(context) ((context)->uc_mcontext.mc_r9)
187 #define R10_sig(context) ((context)->uc_mcontext.mc_r10)
188 #define R11_sig(context) ((context)->uc_mcontext.mc_r11)
189 #define R12_sig(context) ((context)->uc_mcontext.mc_r12)
190 #define R13_sig(context) ((context)->uc_mcontext.mc_r13)
191 #define R14_sig(context) ((context)->uc_mcontext.mc_r14)
192 #define R15_sig(context) ((context)->uc_mcontext.mc_r15)
194 #define CS_sig(context) ((context)->uc_mcontext.mc_cs)
195 #define DS_sig(context) ((context)->uc_mcontext.mc_ds)
196 #define ES_sig(context) ((context)->uc_mcontext.mc_es)
197 #define FS_sig(context) ((context)->uc_mcontext.mc_fs)
198 #define GS_sig(context) ((context)->uc_mcontext.mc_gs)
199 #define SS_sig(context) ((context)->uc_mcontext.mc_ss)
201 #define EFL_sig(context) ((context)->uc_mcontext.mc_rflags)
203 #define RIP_sig(context) ((context)->uc_mcontext.mc_rip)
204 #define RSP_sig(context) ((context)->uc_mcontext.mc_rsp)
205 #define TRAP_sig(context) ((context)->uc_mcontext.mc_trapno)
206 #define ERROR_sig(context) ((context)->uc_mcontext.mc_err)
208 #define FPU_sig(context) ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.mc_fpstate))
210 #elif defined(__NetBSD__)
212 #define RAX_sig(context) ((context)->uc_mcontext.__gregs[_REG_RAX])
213 #define RBX_sig(context) ((context)->uc_mcontext.__gregs[_REG_RBX])
214 #define RCX_sig(context) ((context)->uc_mcontext.__gregs[_REG_RCX])
215 #define RDX_sig(context) ((context)->uc_mcontext.__gregs[_REG_RDX])
216 #define RSI_sig(context) ((context)->uc_mcontext.__gregs[_REG_RSI])
217 #define RDI_sig(context) ((context)->uc_mcontext.__gregs[_REG_RDI])
218 #define RBP_sig(context) ((context)->uc_mcontext.__gregs[_REG_RBP])
219 #define R8_sig(context) ((context)->uc_mcontext.__gregs[_REG_R8])
220 #define R9_sig(context) ((context)->uc_mcontext.__gregs[_REG_R9])
221 #define R10_sig(context) ((context)->uc_mcontext.__gregs[_REG_R10])
222 #define R11_sig(context) ((context)->uc_mcontext.__gregs[_REG_R11])
223 #define R12_sig(context) ((context)->uc_mcontext.__gregs[_REG_R12])
224 #define R13_sig(context) ((context)->uc_mcontext.__gregs[_REG_R13])
225 #define R14_sig(context) ((context)->uc_mcontext.__gregs[_REG_R14])
226 #define R15_sig(context) ((context)->uc_mcontext.__gregs[_REG_R15])
228 #define CS_sig(context) ((context)->uc_mcontext.__gregs[_REG_CS])
229 #define DS_sig(context) ((context)->uc_mcontext.__gregs[_REG_DS])
230 #define ES_sig(context) ((context)->uc_mcontext.__gregs[_REG_ES])
231 #define FS_sig(context) ((context)->uc_mcontext.__gregs[_REG_FS])
232 #define GS_sig(context) ((context)->uc_mcontext.__gregs[_REG_GS])
233 #define SS_sig(context) ((context)->uc_mcontext.__gregs[_REG_SS])
235 #define EFL_sig(context) ((context)->uc_mcontext.__gregs[_REG_RFL])
237 #define RIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_RIP]))
238 #define RSP_sig(context) (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_URSP]))
240 #define TRAP_sig(context) ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
241 #define ERROR_sig(context) ((context)->uc_mcontext.__gregs[_REG_ERR])
243 #define FPU_sig(context) ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.__fpregs))
244 #elif defined (__APPLE__)
245 #define RAX_sig(context) ((context)->uc_mcontext->__ss.__rax)
246 #define RBX_sig(context) ((context)->uc_mcontext->__ss.__rbx)
247 #define RCX_sig(context) ((context)->uc_mcontext->__ss.__rcx)
248 #define RDX_sig(context) ((context)->uc_mcontext->__ss.__rdx)
249 #define RSI_sig(context) ((context)->uc_mcontext->__ss.__rsi)
250 #define RDI_sig(context) ((context)->uc_mcontext->__ss.__rdi)
251 #define RBP_sig(context) ((context)->uc_mcontext->__ss.__rbp)
252 #define R8_sig(context) ((context)->uc_mcontext->__ss.__r8)
253 #define R9_sig(context) ((context)->uc_mcontext->__ss.__r9)
254 #define R10_sig(context) ((context)->uc_mcontext->__ss.__r10)
255 #define R11_sig(context) ((context)->uc_mcontext->__ss.__r11)
256 #define R12_sig(context) ((context)->uc_mcontext->__ss.__r12)
257 #define R13_sig(context) ((context)->uc_mcontext->__ss.__r13)
258 #define R14_sig(context) ((context)->uc_mcontext->__ss.__r14)
259 #define R15_sig(context) ((context)->uc_mcontext->__ss.__r15)
261 #define CS_sig(context) ((context)->uc_mcontext->__ss.__cs)
262 #define FS_sig(context) ((context)->uc_mcontext->__ss.__fs)
263 #define GS_sig(context) ((context)->uc_mcontext->__ss.__gs)
265 #define EFL_sig(context) ((context)->uc_mcontext->__ss.__rflags)
267 #define RIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__rip))
268 #define RSP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__rsp))
270 #define TRAP_sig(context) ((context)->uc_mcontext->__es.__trapno)
271 #define ERROR_sig(context) ((context)->uc_mcontext->__es.__err)
273 #define FPU_sig(context) ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->__fs.__fpu_fcw)
275 #else
276 #error You must define the signal context functions for your platform
277 #endif
279 enum i386_trap_code
281 TRAP_x86_UNKNOWN = -1, /* Unknown fault (TRAP_sig not defined) */
282 TRAP_x86_DIVIDE = 0, /* Division by zero exception */
283 TRAP_x86_TRCTRAP = 1, /* Single-step exception */
284 TRAP_x86_NMI = 2, /* NMI interrupt */
285 TRAP_x86_BPTFLT = 3, /* Breakpoint exception */
286 TRAP_x86_OFLOW = 4, /* Overflow exception */
287 TRAP_x86_BOUND = 5, /* Bound range exception */
288 TRAP_x86_PRIVINFLT = 6, /* Invalid opcode exception */
289 TRAP_x86_DNA = 7, /* Device not available exception */
290 TRAP_x86_DOUBLEFLT = 8, /* Double fault exception */
291 TRAP_x86_FPOPFLT = 9, /* Coprocessor segment overrun */
292 TRAP_x86_TSSFLT = 10, /* Invalid TSS exception */
293 TRAP_x86_SEGNPFLT = 11, /* Segment not present exception */
294 TRAP_x86_STKFLT = 12, /* Stack fault */
295 TRAP_x86_PROTFLT = 13, /* General protection fault */
296 TRAP_x86_PAGEFLT = 14, /* Page fault */
297 TRAP_x86_ARITHTRAP = 16, /* Floating point exception */
298 TRAP_x86_ALIGNFLT = 17, /* Alignment check exception */
299 TRAP_x86_MCHK = 18, /* Machine check exception */
300 TRAP_x86_CACHEFLT = 19 /* Cache flush exception */
303 static const size_t teb_size = 0x2000; /* we reserve two pages for the TEB */
304 static size_t signal_stack_size;
306 typedef void (*raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
307 typedef int (*wine_signal_handler)(unsigned int sig);
309 static wine_signal_handler handlers[256];
311 struct amd64_thread_data
313 DWORD_PTR dr0; /* debug registers */
314 DWORD_PTR dr1;
315 DWORD_PTR dr2;
316 DWORD_PTR dr3;
317 DWORD_PTR dr6;
318 DWORD_PTR dr7;
319 void *exit_frame; /* exit frame pointer */
322 C_ASSERT( sizeof(struct amd64_thread_data) <= sizeof(((TEB *)0)->SystemReserved2) );
324 static inline struct amd64_thread_data *amd64_thread_data(void)
326 return (struct amd64_thread_data *)NtCurrentTeb()->SystemReserved2;
329 /***********************************************************************
330 * Dynamic unwind table
333 struct dynamic_unwind_entry
335 struct list entry;
337 /* memory region which matches this entry */
338 DWORD64 base;
339 DWORD size;
341 /* lookup table */
342 RUNTIME_FUNCTION *table;
343 DWORD table_size;
345 /* user defined callback */
346 PGET_RUNTIME_FUNCTION_CALLBACK callback;
347 PVOID context;
350 static struct list dynamic_unwind_list = LIST_INIT(dynamic_unwind_list);
352 static RTL_CRITICAL_SECTION dynamic_unwind_section;
353 static RTL_CRITICAL_SECTION_DEBUG dynamic_unwind_debug =
355 0, 0, &dynamic_unwind_section,
356 { &dynamic_unwind_debug.ProcessLocksList, &dynamic_unwind_debug.ProcessLocksList },
357 0, 0, { (DWORD_PTR)(__FILE__ ": dynamic_unwind_section") }
359 static RTL_CRITICAL_SECTION dynamic_unwind_section = { &dynamic_unwind_debug, -1, 0, 0, 0, 0 };
361 /***********************************************************************
362 * Definitions for Win32 unwind tables
365 union handler_data
367 RUNTIME_FUNCTION chain;
368 ULONG handler;
371 struct opcode
373 BYTE offset;
374 BYTE code : 4;
375 BYTE info : 4;
378 struct UNWIND_INFO
380 BYTE version : 3;
381 BYTE flags : 5;
382 BYTE prolog;
383 BYTE count;
384 BYTE frame_reg : 4;
385 BYTE frame_offset : 4;
386 struct opcode opcodes[1]; /* info->count entries */
387 /* followed by handler_data */
390 #define UWOP_PUSH_NONVOL 0
391 #define UWOP_ALLOC_LARGE 1
392 #define UWOP_ALLOC_SMALL 2
393 #define UWOP_SET_FPREG 3
394 #define UWOP_SAVE_NONVOL 4
395 #define UWOP_SAVE_NONVOL_FAR 5
396 #define UWOP_SAVE_XMM128 8
397 #define UWOP_SAVE_XMM128_FAR 9
398 #define UWOP_PUSH_MACHFRAME 10
400 static void dump_unwind_info( ULONG64 base, RUNTIME_FUNCTION *function )
402 static const char * const reg_names[16] =
403 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
404 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
406 union handler_data *handler_data;
407 struct UNWIND_INFO *info;
408 unsigned int i, count;
410 TRACE( "**** func %x-%x\n", function->BeginAddress, function->EndAddress );
411 for (;;)
413 if (function->UnwindData & 1)
415 RUNTIME_FUNCTION *next = (RUNTIME_FUNCTION *)((char *)base + (function->UnwindData & ~1));
416 TRACE( "unwind info for function %p-%p chained to function %p-%p\n",
417 (char *)base + function->BeginAddress, (char *)base + function->EndAddress,
418 (char *)base + next->BeginAddress, (char *)base + next->EndAddress );
419 function = next;
420 continue;
422 info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
424 TRACE( "unwind info at %p flags %x prolog 0x%x bytes function %p-%p\n",
425 info, info->flags, info->prolog,
426 (char *)base + function->BeginAddress, (char *)base + function->EndAddress );
428 if (info->frame_reg)
429 TRACE( " frame register %s offset 0x%x(%%rsp)\n",
430 reg_names[info->frame_reg], info->frame_offset * 16 );
432 for (i = 0; i < info->count; i++)
434 TRACE( " 0x%x: ", info->opcodes[i].offset );
435 switch (info->opcodes[i].code)
437 case UWOP_PUSH_NONVOL:
438 TRACE( "pushq %%%s\n", reg_names[info->opcodes[i].info] );
439 break;
440 case UWOP_ALLOC_LARGE:
441 if (info->opcodes[i].info)
443 count = *(DWORD *)&info->opcodes[i+1];
444 i += 2;
446 else
448 count = *(USHORT *)&info->opcodes[i+1] * 8;
449 i++;
451 TRACE( "subq $0x%x,%%rsp\n", count );
452 break;
453 case UWOP_ALLOC_SMALL:
454 count = (info->opcodes[i].info + 1) * 8;
455 TRACE( "subq $0x%x,%%rsp\n", count );
456 break;
457 case UWOP_SET_FPREG:
458 TRACE( "leaq 0x%x(%%rsp),%s\n",
459 info->frame_offset * 16, reg_names[info->frame_reg] );
460 break;
461 case UWOP_SAVE_NONVOL:
462 count = *(USHORT *)&info->opcodes[i+1] * 8;
463 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
464 i++;
465 break;
466 case UWOP_SAVE_NONVOL_FAR:
467 count = *(DWORD *)&info->opcodes[i+1];
468 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
469 i += 2;
470 break;
471 case UWOP_SAVE_XMM128:
472 count = *(USHORT *)&info->opcodes[i+1] * 16;
473 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
474 i++;
475 break;
476 case UWOP_SAVE_XMM128_FAR:
477 count = *(DWORD *)&info->opcodes[i+1];
478 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
479 i += 2;
480 break;
481 case UWOP_PUSH_MACHFRAME:
482 TRACE( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
483 break;
484 default:
485 FIXME( "unknown code %u\n", info->opcodes[i].code );
486 break;
490 handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
491 if (info->flags & UNW_FLAG_CHAININFO)
493 TRACE( " chained to function %p-%p\n",
494 (char *)base + handler_data->chain.BeginAddress,
495 (char *)base + handler_data->chain.EndAddress );
496 function = &handler_data->chain;
497 continue;
499 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
500 TRACE( " handler %p data at %p\n",
501 (char *)base + handler_data->handler, &handler_data->handler + 1 );
502 break;
506 static void dump_scope_table( ULONG64 base, const SCOPE_TABLE *table )
508 unsigned int i;
510 TRACE( "scope table at %p\n", table );
511 for (i = 0; i < table->Count; i++)
512 TRACE( " %u: %lx-%lx handler %lx target %lx\n", i,
513 base + table->ScopeRecord[i].BeginAddress,
514 base + table->ScopeRecord[i].EndAddress,
515 base + table->ScopeRecord[i].HandlerAddress,
516 base + table->ScopeRecord[i].JumpTarget );
520 /***********************************************************************
521 * Definitions for Dwarf unwind tables
524 enum dwarf_call_frame_info
526 DW_CFA_advance_loc = 0x40,
527 DW_CFA_offset = 0x80,
528 DW_CFA_restore = 0xc0,
529 DW_CFA_nop = 0x00,
530 DW_CFA_set_loc = 0x01,
531 DW_CFA_advance_loc1 = 0x02,
532 DW_CFA_advance_loc2 = 0x03,
533 DW_CFA_advance_loc4 = 0x04,
534 DW_CFA_offset_extended = 0x05,
535 DW_CFA_restore_extended = 0x06,
536 DW_CFA_undefined = 0x07,
537 DW_CFA_same_value = 0x08,
538 DW_CFA_register = 0x09,
539 DW_CFA_remember_state = 0x0a,
540 DW_CFA_restore_state = 0x0b,
541 DW_CFA_def_cfa = 0x0c,
542 DW_CFA_def_cfa_register = 0x0d,
543 DW_CFA_def_cfa_offset = 0x0e,
544 DW_CFA_def_cfa_expression = 0x0f,
545 DW_CFA_expression = 0x10,
546 DW_CFA_offset_extended_sf = 0x11,
547 DW_CFA_def_cfa_sf = 0x12,
548 DW_CFA_def_cfa_offset_sf = 0x13,
549 DW_CFA_val_offset = 0x14,
550 DW_CFA_val_offset_sf = 0x15,
551 DW_CFA_val_expression = 0x16,
554 enum dwarf_operation
556 DW_OP_addr = 0x03,
557 DW_OP_deref = 0x06,
558 DW_OP_const1u = 0x08,
559 DW_OP_const1s = 0x09,
560 DW_OP_const2u = 0x0a,
561 DW_OP_const2s = 0x0b,
562 DW_OP_const4u = 0x0c,
563 DW_OP_const4s = 0x0d,
564 DW_OP_const8u = 0x0e,
565 DW_OP_const8s = 0x0f,
566 DW_OP_constu = 0x10,
567 DW_OP_consts = 0x11,
568 DW_OP_dup = 0x12,
569 DW_OP_drop = 0x13,
570 DW_OP_over = 0x14,
571 DW_OP_pick = 0x15,
572 DW_OP_swap = 0x16,
573 DW_OP_rot = 0x17,
574 DW_OP_xderef = 0x18,
575 DW_OP_abs = 0x19,
576 DW_OP_and = 0x1a,
577 DW_OP_div = 0x1b,
578 DW_OP_minus = 0x1c,
579 DW_OP_mod = 0x1d,
580 DW_OP_mul = 0x1e,
581 DW_OP_neg = 0x1f,
582 DW_OP_not = 0x20,
583 DW_OP_or = 0x21,
584 DW_OP_plus = 0x22,
585 DW_OP_plus_uconst = 0x23,
586 DW_OP_shl = 0x24,
587 DW_OP_shr = 0x25,
588 DW_OP_shra = 0x26,
589 DW_OP_xor = 0x27,
590 DW_OP_bra = 0x28,
591 DW_OP_eq = 0x29,
592 DW_OP_ge = 0x2a,
593 DW_OP_gt = 0x2b,
594 DW_OP_le = 0x2c,
595 DW_OP_lt = 0x2d,
596 DW_OP_ne = 0x2e,
597 DW_OP_skip = 0x2f,
598 DW_OP_lit0 = 0x30,
599 DW_OP_lit1 = 0x31,
600 DW_OP_lit2 = 0x32,
601 DW_OP_lit3 = 0x33,
602 DW_OP_lit4 = 0x34,
603 DW_OP_lit5 = 0x35,
604 DW_OP_lit6 = 0x36,
605 DW_OP_lit7 = 0x37,
606 DW_OP_lit8 = 0x38,
607 DW_OP_lit9 = 0x39,
608 DW_OP_lit10 = 0x3a,
609 DW_OP_lit11 = 0x3b,
610 DW_OP_lit12 = 0x3c,
611 DW_OP_lit13 = 0x3d,
612 DW_OP_lit14 = 0x3e,
613 DW_OP_lit15 = 0x3f,
614 DW_OP_lit16 = 0x40,
615 DW_OP_lit17 = 0x41,
616 DW_OP_lit18 = 0x42,
617 DW_OP_lit19 = 0x43,
618 DW_OP_lit20 = 0x44,
619 DW_OP_lit21 = 0x45,
620 DW_OP_lit22 = 0x46,
621 DW_OP_lit23 = 0x47,
622 DW_OP_lit24 = 0x48,
623 DW_OP_lit25 = 0x49,
624 DW_OP_lit26 = 0x4a,
625 DW_OP_lit27 = 0x4b,
626 DW_OP_lit28 = 0x4c,
627 DW_OP_lit29 = 0x4d,
628 DW_OP_lit30 = 0x4e,
629 DW_OP_lit31 = 0x4f,
630 DW_OP_reg0 = 0x50,
631 DW_OP_reg1 = 0x51,
632 DW_OP_reg2 = 0x52,
633 DW_OP_reg3 = 0x53,
634 DW_OP_reg4 = 0x54,
635 DW_OP_reg5 = 0x55,
636 DW_OP_reg6 = 0x56,
637 DW_OP_reg7 = 0x57,
638 DW_OP_reg8 = 0x58,
639 DW_OP_reg9 = 0x59,
640 DW_OP_reg10 = 0x5a,
641 DW_OP_reg11 = 0x5b,
642 DW_OP_reg12 = 0x5c,
643 DW_OP_reg13 = 0x5d,
644 DW_OP_reg14 = 0x5e,
645 DW_OP_reg15 = 0x5f,
646 DW_OP_reg16 = 0x60,
647 DW_OP_reg17 = 0x61,
648 DW_OP_reg18 = 0x62,
649 DW_OP_reg19 = 0x63,
650 DW_OP_reg20 = 0x64,
651 DW_OP_reg21 = 0x65,
652 DW_OP_reg22 = 0x66,
653 DW_OP_reg23 = 0x67,
654 DW_OP_reg24 = 0x68,
655 DW_OP_reg25 = 0x69,
656 DW_OP_reg26 = 0x6a,
657 DW_OP_reg27 = 0x6b,
658 DW_OP_reg28 = 0x6c,
659 DW_OP_reg29 = 0x6d,
660 DW_OP_reg30 = 0x6e,
661 DW_OP_reg31 = 0x6f,
662 DW_OP_breg0 = 0x70,
663 DW_OP_breg1 = 0x71,
664 DW_OP_breg2 = 0x72,
665 DW_OP_breg3 = 0x73,
666 DW_OP_breg4 = 0x74,
667 DW_OP_breg5 = 0x75,
668 DW_OP_breg6 = 0x76,
669 DW_OP_breg7 = 0x77,
670 DW_OP_breg8 = 0x78,
671 DW_OP_breg9 = 0x79,
672 DW_OP_breg10 = 0x7a,
673 DW_OP_breg11 = 0x7b,
674 DW_OP_breg12 = 0x7c,
675 DW_OP_breg13 = 0x7d,
676 DW_OP_breg14 = 0x7e,
677 DW_OP_breg15 = 0x7f,
678 DW_OP_breg16 = 0x80,
679 DW_OP_breg17 = 0x81,
680 DW_OP_breg18 = 0x82,
681 DW_OP_breg19 = 0x83,
682 DW_OP_breg20 = 0x84,
683 DW_OP_breg21 = 0x85,
684 DW_OP_breg22 = 0x86,
685 DW_OP_breg23 = 0x87,
686 DW_OP_breg24 = 0x88,
687 DW_OP_breg25 = 0x89,
688 DW_OP_breg26 = 0x8a,
689 DW_OP_breg27 = 0x8b,
690 DW_OP_breg28 = 0x8c,
691 DW_OP_breg29 = 0x8d,
692 DW_OP_breg30 = 0x8e,
693 DW_OP_breg31 = 0x8f,
694 DW_OP_regx = 0x90,
695 DW_OP_fbreg = 0x91,
696 DW_OP_bregx = 0x92,
697 DW_OP_piece = 0x93,
698 DW_OP_deref_size = 0x94,
699 DW_OP_xderef_size = 0x95,
700 DW_OP_nop = 0x96,
701 DW_OP_push_object_address = 0x97,
702 DW_OP_call2 = 0x98,
703 DW_OP_call4 = 0x99,
704 DW_OP_call_ref = 0x9a,
705 DW_OP_form_tls_address = 0x9b,
706 DW_OP_call_frame_cfa = 0x9c,
707 DW_OP_bit_piece = 0x9d,
708 DW_OP_lo_user = 0xe0,
709 DW_OP_hi_user = 0xff,
710 DW_OP_GNU_push_tls_address = 0xe0,
711 DW_OP_GNU_uninit = 0xf0,
712 DW_OP_GNU_encoded_addr = 0xf1,
715 #define DW_EH_PE_native 0x00
716 #define DW_EH_PE_leb128 0x01
717 #define DW_EH_PE_data2 0x02
718 #define DW_EH_PE_data4 0x03
719 #define DW_EH_PE_data8 0x04
720 #define DW_EH_PE_signed 0x08
721 #define DW_EH_PE_abs 0x00
722 #define DW_EH_PE_pcrel 0x10
723 #define DW_EH_PE_textrel 0x20
724 #define DW_EH_PE_datarel 0x30
725 #define DW_EH_PE_funcrel 0x40
726 #define DW_EH_PE_aligned 0x50
727 #define DW_EH_PE_indirect 0x80
728 #define DW_EH_PE_omit 0xff
730 struct dwarf_eh_bases
732 void *tbase;
733 void *dbase;
734 void *func;
737 struct dwarf_cie
739 unsigned int length;
740 int id;
741 unsigned char version;
742 unsigned char augmentation[1];
745 struct dwarf_fde
747 unsigned int length;
748 unsigned int cie_offset;
751 extern const struct dwarf_fde *_Unwind_Find_FDE (void *, struct dwarf_eh_bases *);
753 static unsigned char dwarf_get_u1( const unsigned char **p )
755 return *(*p)++;
758 static unsigned short dwarf_get_u2( const unsigned char **p )
760 unsigned int ret = (*p)[0] | ((*p)[1] << 8);
761 (*p) += 2;
762 return ret;
765 static unsigned int dwarf_get_u4( const unsigned char **p )
767 unsigned int ret = (*p)[0] | ((*p)[1] << 8) | ((*p)[2] << 16) | ((*p)[3] << 24);
768 (*p) += 4;
769 return ret;
772 static ULONG64 dwarf_get_u8( const unsigned char **p )
774 ULONG64 low = dwarf_get_u4( p );
775 ULONG64 high = dwarf_get_u4( p );
776 return low | (high << 32);
779 static ULONG_PTR dwarf_get_uleb128( const unsigned char **p )
781 ULONG_PTR ret = 0;
782 unsigned int shift = 0;
783 unsigned char byte;
787 byte = **p;
788 ret |= (ULONG_PTR)(byte & 0x7f) << shift;
789 shift += 7;
790 (*p)++;
791 } while (byte & 0x80);
792 return ret;
795 static LONG_PTR dwarf_get_sleb128( const unsigned char **p )
797 ULONG_PTR ret = 0;
798 unsigned int shift = 0;
799 unsigned char byte;
803 byte = **p;
804 ret |= (ULONG_PTR)(byte & 0x7f) << shift;
805 shift += 7;
806 (*p)++;
807 } while (byte & 0x80);
809 if ((shift < 8 * sizeof(ret)) && (byte & 0x40)) ret |= -((ULONG_PTR)1 << shift);
810 return ret;
813 static ULONG_PTR dwarf_get_ptr( const unsigned char **p, unsigned char encoding )
815 ULONG_PTR base;
817 if (encoding == DW_EH_PE_omit) return 0;
819 switch (encoding & 0xf0)
821 case DW_EH_PE_abs:
822 base = 0;
823 break;
824 case DW_EH_PE_pcrel:
825 base = (ULONG_PTR)*p;
826 break;
827 default:
828 FIXME( "unsupported encoding %02x\n", encoding );
829 return 0;
832 switch (encoding & 0x0f)
834 case DW_EH_PE_native:
835 return base + dwarf_get_u8( p );
836 case DW_EH_PE_leb128:
837 return base + dwarf_get_uleb128( p );
838 case DW_EH_PE_data2:
839 return base + dwarf_get_u2( p );
840 case DW_EH_PE_data4:
841 return base + dwarf_get_u4( p );
842 case DW_EH_PE_data8:
843 return base + dwarf_get_u8( p );
844 case DW_EH_PE_signed|DW_EH_PE_leb128:
845 return base + dwarf_get_sleb128( p );
846 case DW_EH_PE_signed|DW_EH_PE_data2:
847 return base + (signed short)dwarf_get_u2( p );
848 case DW_EH_PE_signed|DW_EH_PE_data4:
849 return base + (signed int)dwarf_get_u4( p );
850 case DW_EH_PE_signed|DW_EH_PE_data8:
851 return base + (LONG64)dwarf_get_u8( p );
852 default:
853 FIXME( "unsupported encoding %02x\n", encoding );
854 return 0;
858 enum reg_rule
860 RULE_UNSET, /* not set at all */
861 RULE_UNDEFINED, /* undefined value */
862 RULE_SAME, /* same value as previous frame */
863 RULE_CFA_OFFSET, /* stored at cfa offset */
864 RULE_OTHER_REG, /* stored in other register */
865 RULE_EXPRESSION, /* address specified by expression */
866 RULE_VAL_EXPRESSION /* value specified by expression */
869 #define NB_FRAME_REGS 41
870 #define MAX_SAVED_STATES 16
872 struct frame_state
874 ULONG_PTR cfa_offset;
875 unsigned char cfa_reg;
876 enum reg_rule cfa_rule;
877 enum reg_rule rules[NB_FRAME_REGS];
878 ULONG64 regs[NB_FRAME_REGS];
881 struct frame_info
883 ULONG_PTR ip;
884 ULONG_PTR code_align;
885 LONG_PTR data_align;
886 unsigned char retaddr_reg;
887 unsigned char fde_encoding;
888 unsigned char signal_frame;
889 unsigned char state_sp;
890 struct frame_state state;
891 struct frame_state *state_stack;
894 static const char *dwarf_reg_names[NB_FRAME_REGS] =
896 /* 0-7 */ "%rax", "%rdx", "%rcx", "%rbx", "%rsi", "%rdi", "%rbp", "%rsp",
897 /* 8-16 */ "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "%rip",
898 /* 17-24 */ "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
899 /* 25-32 */ "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15",
900 /* 33-40 */ "%st0", "%st1", "%st2", "%st3", "%st4", "%st5", "%st6", "%st7"
903 static BOOL valid_reg( ULONG_PTR reg )
905 if (reg >= NB_FRAME_REGS) FIXME( "unsupported reg %lx\n", reg );
906 return (reg < NB_FRAME_REGS);
909 static void execute_cfa_instructions( const unsigned char *ptr, const unsigned char *end,
910 ULONG_PTR last_ip, struct frame_info *info )
912 while (ptr < end && info->ip < last_ip + info->signal_frame)
914 enum dwarf_call_frame_info op = *ptr++;
916 if (op & 0xc0)
918 switch (op & 0xc0)
920 case DW_CFA_advance_loc:
922 ULONG_PTR offset = (op & 0x3f) * info->code_align;
923 TRACE( "%lx: DW_CFA_advance_loc %lu\n", info->ip, offset );
924 info->ip += offset;
925 break;
927 case DW_CFA_offset:
929 ULONG_PTR reg = op & 0x3f;
930 LONG_PTR offset = dwarf_get_uleb128( &ptr ) * info->data_align;
931 if (!valid_reg( reg )) break;
932 TRACE( "%lx: DW_CFA_offset %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
933 info->state.regs[reg] = offset;
934 info->state.rules[reg] = RULE_CFA_OFFSET;
935 break;
937 case DW_CFA_restore:
939 ULONG_PTR reg = op & 0x3f;
940 if (!valid_reg( reg )) break;
941 TRACE( "%lx: DW_CFA_restore %s\n", info->ip, dwarf_reg_names[reg] );
942 info->state.rules[reg] = RULE_UNSET;
943 break;
947 else switch (op)
949 case DW_CFA_nop:
950 break;
951 case DW_CFA_set_loc:
953 ULONG_PTR loc = dwarf_get_ptr( &ptr, info->fde_encoding );
954 TRACE( "%lx: DW_CFA_set_loc %lx\n", info->ip, loc );
955 info->ip = loc;
956 break;
958 case DW_CFA_advance_loc1:
960 ULONG_PTR offset = *ptr++ * info->code_align;
961 TRACE( "%lx: DW_CFA_advance_loc1 %lu\n", info->ip, offset );
962 info->ip += offset;
963 break;
965 case DW_CFA_advance_loc2:
967 ULONG_PTR offset = dwarf_get_u2( &ptr ) * info->code_align;
968 TRACE( "%lx: DW_CFA_advance_loc2 %lu\n", info->ip, offset );
969 info->ip += offset;
970 break;
972 case DW_CFA_advance_loc4:
974 ULONG_PTR offset = dwarf_get_u4( &ptr ) * info->code_align;
975 TRACE( "%lx: DW_CFA_advance_loc4 %lu\n", info->ip, offset );
976 info->ip += offset;
977 break;
979 case DW_CFA_offset_extended:
980 case DW_CFA_offset_extended_sf:
982 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
983 LONG_PTR offset = (op == DW_CFA_offset_extended) ? dwarf_get_uleb128( &ptr ) * info->data_align
984 : dwarf_get_sleb128( &ptr ) * info->data_align;
985 if (!valid_reg( reg )) break;
986 TRACE( "%lx: DW_CFA_offset_extended %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
987 info->state.regs[reg] = offset;
988 info->state.rules[reg] = RULE_CFA_OFFSET;
989 break;
991 case DW_CFA_restore_extended:
993 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
994 if (!valid_reg( reg )) break;
995 TRACE( "%lx: DW_CFA_restore_extended %s\n", info->ip, dwarf_reg_names[reg] );
996 info->state.rules[reg] = RULE_UNSET;
997 break;
999 case DW_CFA_undefined:
1001 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1002 if (!valid_reg( reg )) break;
1003 TRACE( "%lx: DW_CFA_undefined %s\n", info->ip, dwarf_reg_names[reg] );
1004 info->state.rules[reg] = RULE_UNDEFINED;
1005 break;
1007 case DW_CFA_same_value:
1009 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1010 if (!valid_reg( reg )) break;
1011 TRACE( "%lx: DW_CFA_same_value %s\n", info->ip, dwarf_reg_names[reg] );
1012 info->state.regs[reg] = reg;
1013 info->state.rules[reg] = RULE_SAME;
1014 break;
1016 case DW_CFA_register:
1018 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1019 ULONG_PTR reg2 = dwarf_get_uleb128( &ptr );
1020 if (!valid_reg( reg ) || !valid_reg( reg2 )) break;
1021 TRACE( "%lx: DW_CFA_register %s == %s\n", info->ip, dwarf_reg_names[reg], dwarf_reg_names[reg2] );
1022 info->state.regs[reg] = reg2;
1023 info->state.rules[reg] = RULE_OTHER_REG;
1024 break;
1026 case DW_CFA_remember_state:
1027 TRACE( "%lx: DW_CFA_remember_state\n", info->ip );
1028 if (info->state_sp >= MAX_SAVED_STATES)
1029 FIXME( "%lx: DW_CFA_remember_state too many nested saves\n", info->ip );
1030 else
1031 info->state_stack[info->state_sp++] = info->state;
1032 break;
1033 case DW_CFA_restore_state:
1034 TRACE( "%lx: DW_CFA_restore_state\n", info->ip );
1035 if (!info->state_sp)
1036 FIXME( "%lx: DW_CFA_restore_state without corresponding save\n", info->ip );
1037 else
1038 info->state = info->state_stack[--info->state_sp];
1039 break;
1040 case DW_CFA_def_cfa:
1041 case DW_CFA_def_cfa_sf:
1043 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1044 ULONG_PTR offset = (op == DW_CFA_def_cfa) ? dwarf_get_uleb128( &ptr )
1045 : dwarf_get_sleb128( &ptr ) * info->data_align;
1046 if (!valid_reg( reg )) break;
1047 TRACE( "%lx: DW_CFA_def_cfa %s, %lu\n", info->ip, dwarf_reg_names[reg], offset );
1048 info->state.cfa_reg = reg;
1049 info->state.cfa_offset = offset;
1050 info->state.cfa_rule = RULE_CFA_OFFSET;
1051 break;
1053 case DW_CFA_def_cfa_register:
1055 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1056 if (!valid_reg( reg )) break;
1057 TRACE( "%lx: DW_CFA_def_cfa_register %s\n", info->ip, dwarf_reg_names[reg] );
1058 info->state.cfa_reg = reg;
1059 info->state.cfa_rule = RULE_CFA_OFFSET;
1060 break;
1062 case DW_CFA_def_cfa_offset:
1063 case DW_CFA_def_cfa_offset_sf:
1065 ULONG_PTR offset = (op == DW_CFA_def_cfa_offset) ? dwarf_get_uleb128( &ptr )
1066 : dwarf_get_sleb128( &ptr ) * info->data_align;
1067 TRACE( "%lx: DW_CFA_def_cfa_offset %lu\n", info->ip, offset );
1068 info->state.cfa_offset = offset;
1069 info->state.cfa_rule = RULE_CFA_OFFSET;
1070 break;
1072 case DW_CFA_def_cfa_expression:
1074 ULONG_PTR expr = (ULONG_PTR)ptr;
1075 ULONG_PTR len = dwarf_get_uleb128( &ptr );
1076 TRACE( "%lx: DW_CFA_def_cfa_expression %lx-%lx\n", info->ip, expr, expr+len );
1077 info->state.cfa_offset = expr;
1078 info->state.cfa_rule = RULE_VAL_EXPRESSION;
1079 ptr += len;
1080 break;
1082 case DW_CFA_expression:
1083 case DW_CFA_val_expression:
1085 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1086 ULONG_PTR expr = (ULONG_PTR)ptr;
1087 ULONG_PTR len = dwarf_get_uleb128( &ptr );
1088 if (!valid_reg( reg )) break;
1089 TRACE( "%lx: DW_CFA_%sexpression %s %lx-%lx\n",
1090 info->ip, (op == DW_CFA_expression) ? "" : "val_", dwarf_reg_names[reg], expr, expr+len );
1091 info->state.regs[reg] = expr;
1092 info->state.rules[reg] = (op == DW_CFA_expression) ? RULE_EXPRESSION : RULE_VAL_EXPRESSION;
1093 ptr += len;
1094 break;
1096 default:
1097 FIXME( "%lx: unknown CFA opcode %02x\n", info->ip, op );
1098 break;
1103 /* retrieve a context register from its dwarf number */
1104 static void *get_context_reg( CONTEXT *context, ULONG_PTR dw_reg )
1106 switch (dw_reg)
1108 case 0: return &context->Rax;
1109 case 1: return &context->Rdx;
1110 case 2: return &context->Rcx;
1111 case 3: return &context->Rbx;
1112 case 4: return &context->Rsi;
1113 case 5: return &context->Rdi;
1114 case 6: return &context->Rbp;
1115 case 7: return &context->Rsp;
1116 case 8: return &context->R8;
1117 case 9: return &context->R9;
1118 case 10: return &context->R10;
1119 case 11: return &context->R11;
1120 case 12: return &context->R12;
1121 case 13: return &context->R13;
1122 case 14: return &context->R14;
1123 case 15: return &context->R15;
1124 case 16: return &context->Rip;
1125 case 17: return &context->u.s.Xmm0;
1126 case 18: return &context->u.s.Xmm1;
1127 case 19: return &context->u.s.Xmm2;
1128 case 20: return &context->u.s.Xmm3;
1129 case 21: return &context->u.s.Xmm4;
1130 case 22: return &context->u.s.Xmm5;
1131 case 23: return &context->u.s.Xmm6;
1132 case 24: return &context->u.s.Xmm7;
1133 case 25: return &context->u.s.Xmm8;
1134 case 26: return &context->u.s.Xmm9;
1135 case 27: return &context->u.s.Xmm10;
1136 case 28: return &context->u.s.Xmm11;
1137 case 29: return &context->u.s.Xmm12;
1138 case 30: return &context->u.s.Xmm13;
1139 case 31: return &context->u.s.Xmm14;
1140 case 32: return &context->u.s.Xmm15;
1141 case 33: return &context->u.s.Legacy[0];
1142 case 34: return &context->u.s.Legacy[1];
1143 case 35: return &context->u.s.Legacy[2];
1144 case 36: return &context->u.s.Legacy[3];
1145 case 37: return &context->u.s.Legacy[4];
1146 case 38: return &context->u.s.Legacy[5];
1147 case 39: return &context->u.s.Legacy[6];
1148 case 40: return &context->u.s.Legacy[7];
1149 default: return NULL;
1153 /* set a context register from its dwarf number */
1154 static void set_context_reg( CONTEXT *context, ULONG_PTR dw_reg, void *val )
1156 switch (dw_reg)
1158 case 0: context->Rax = *(ULONG64 *)val; break;
1159 case 1: context->Rdx = *(ULONG64 *)val; break;
1160 case 2: context->Rcx = *(ULONG64 *)val; break;
1161 case 3: context->Rbx = *(ULONG64 *)val; break;
1162 case 4: context->Rsi = *(ULONG64 *)val; break;
1163 case 5: context->Rdi = *(ULONG64 *)val; break;
1164 case 6: context->Rbp = *(ULONG64 *)val; break;
1165 case 7: context->Rsp = *(ULONG64 *)val; break;
1166 case 8: context->R8 = *(ULONG64 *)val; break;
1167 case 9: context->R9 = *(ULONG64 *)val; break;
1168 case 10: context->R10 = *(ULONG64 *)val; break;
1169 case 11: context->R11 = *(ULONG64 *)val; break;
1170 case 12: context->R12 = *(ULONG64 *)val; break;
1171 case 13: context->R13 = *(ULONG64 *)val; break;
1172 case 14: context->R14 = *(ULONG64 *)val; break;
1173 case 15: context->R15 = *(ULONG64 *)val; break;
1174 case 16: context->Rip = *(ULONG64 *)val; break;
1175 case 17: memcpy( &context->u.s.Xmm0, val, sizeof(M128A) ); break;
1176 case 18: memcpy( &context->u.s.Xmm1, val, sizeof(M128A) ); break;
1177 case 19: memcpy( &context->u.s.Xmm2, val, sizeof(M128A) ); break;
1178 case 20: memcpy( &context->u.s.Xmm3, val, sizeof(M128A) ); break;
1179 case 21: memcpy( &context->u.s.Xmm4, val, sizeof(M128A) ); break;
1180 case 22: memcpy( &context->u.s.Xmm5, val, sizeof(M128A) ); break;
1181 case 23: memcpy( &context->u.s.Xmm6, val, sizeof(M128A) ); break;
1182 case 24: memcpy( &context->u.s.Xmm7, val, sizeof(M128A) ); break;
1183 case 25: memcpy( &context->u.s.Xmm8, val, sizeof(M128A) ); break;
1184 case 26: memcpy( &context->u.s.Xmm9, val, sizeof(M128A) ); break;
1185 case 27: memcpy( &context->u.s.Xmm10, val, sizeof(M128A) ); break;
1186 case 28: memcpy( &context->u.s.Xmm11, val, sizeof(M128A) ); break;
1187 case 29: memcpy( &context->u.s.Xmm12, val, sizeof(M128A) ); break;
1188 case 30: memcpy( &context->u.s.Xmm13, val, sizeof(M128A) ); break;
1189 case 31: memcpy( &context->u.s.Xmm14, val, sizeof(M128A) ); break;
1190 case 32: memcpy( &context->u.s.Xmm15, val, sizeof(M128A) ); break;
1191 case 33: memcpy( &context->u.s.Legacy[0], val, sizeof(M128A) ); break;
1192 case 34: memcpy( &context->u.s.Legacy[1], val, sizeof(M128A) ); break;
1193 case 35: memcpy( &context->u.s.Legacy[2], val, sizeof(M128A) ); break;
1194 case 36: memcpy( &context->u.s.Legacy[3], val, sizeof(M128A) ); break;
1195 case 37: memcpy( &context->u.s.Legacy[4], val, sizeof(M128A) ); break;
1196 case 38: memcpy( &context->u.s.Legacy[5], val, sizeof(M128A) ); break;
1197 case 39: memcpy( &context->u.s.Legacy[6], val, sizeof(M128A) ); break;
1198 case 40: memcpy( &context->u.s.Legacy[7], val, sizeof(M128A) ); break;
1202 static ULONG_PTR eval_expression( const unsigned char *p, CONTEXT *context )
1204 ULONG_PTR reg, tmp, stack[64];
1205 int sp = -1;
1206 ULONG_PTR len = dwarf_get_uleb128(&p);
1207 const unsigned char *end = p + len;
1209 while (p < end)
1211 unsigned char opcode = dwarf_get_u1(&p);
1213 if (opcode >= DW_OP_lit0 && opcode <= DW_OP_lit31)
1214 stack[++sp] = opcode - DW_OP_lit0;
1215 else if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31)
1216 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_reg0 );
1217 else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31)
1218 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_breg0 ) + dwarf_get_sleb128(&p);
1219 else switch (opcode)
1221 case DW_OP_nop: break;
1222 case DW_OP_addr: stack[++sp] = dwarf_get_u8(&p); break;
1223 case DW_OP_const1u: stack[++sp] = dwarf_get_u1(&p); break;
1224 case DW_OP_const1s: stack[++sp] = (signed char)dwarf_get_u1(&p); break;
1225 case DW_OP_const2u: stack[++sp] = dwarf_get_u2(&p); break;
1226 case DW_OP_const2s: stack[++sp] = (short)dwarf_get_u2(&p); break;
1227 case DW_OP_const4u: stack[++sp] = dwarf_get_u4(&p); break;
1228 case DW_OP_const4s: stack[++sp] = (signed int)dwarf_get_u4(&p); break;
1229 case DW_OP_const8u: stack[++sp] = dwarf_get_u8(&p); break;
1230 case DW_OP_const8s: stack[++sp] = (LONG_PTR)dwarf_get_u8(&p); break;
1231 case DW_OP_constu: stack[++sp] = dwarf_get_uleb128(&p); break;
1232 case DW_OP_consts: stack[++sp] = dwarf_get_sleb128(&p); break;
1233 case DW_OP_deref: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1234 case DW_OP_dup: stack[sp + 1] = stack[sp]; sp++; break;
1235 case DW_OP_drop: sp--; break;
1236 case DW_OP_over: stack[sp + 1] = stack[sp - 1]; sp++; break;
1237 case DW_OP_pick: stack[sp + 1] = stack[sp - dwarf_get_u1(&p)]; sp++; break;
1238 case DW_OP_swap: tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = tmp; break;
1239 case DW_OP_rot: tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = stack[sp-2]; stack[sp-2] = tmp; break;
1240 case DW_OP_abs: stack[sp] = labs(stack[sp]); break;
1241 case DW_OP_neg: stack[sp] = -stack[sp]; break;
1242 case DW_OP_not: stack[sp] = ~stack[sp]; break;
1243 case DW_OP_and: stack[sp-1] &= stack[sp]; sp--; break;
1244 case DW_OP_or: stack[sp-1] |= stack[sp]; sp--; break;
1245 case DW_OP_minus: stack[sp-1] -= stack[sp]; sp--; break;
1246 case DW_OP_mul: stack[sp-1] *= stack[sp]; sp--; break;
1247 case DW_OP_plus: stack[sp-1] += stack[sp]; sp--; break;
1248 case DW_OP_xor: stack[sp-1] ^= stack[sp]; sp--; break;
1249 case DW_OP_shl: stack[sp-1] <<= stack[sp]; sp--; break;
1250 case DW_OP_shr: stack[sp-1] >>= stack[sp]; sp--; break;
1251 case DW_OP_plus_uconst: stack[sp] += dwarf_get_uleb128(&p); break;
1252 case DW_OP_shra: stack[sp-1] = (LONG_PTR)stack[sp-1] / (1 << stack[sp]); sp--; break;
1253 case DW_OP_div: stack[sp-1] = (LONG_PTR)stack[sp-1] / (LONG_PTR)stack[sp]; sp--; break;
1254 case DW_OP_mod: stack[sp-1] = (LONG_PTR)stack[sp-1] % (LONG_PTR)stack[sp]; sp--; break;
1255 case DW_OP_ge: stack[sp-1] = ((LONG_PTR)stack[sp-1] >= (LONG_PTR)stack[sp]); sp--; break;
1256 case DW_OP_gt: stack[sp-1] = ((LONG_PTR)stack[sp-1] > (LONG_PTR)stack[sp]); sp--; break;
1257 case DW_OP_le: stack[sp-1] = ((LONG_PTR)stack[sp-1] <= (LONG_PTR)stack[sp]); sp--; break;
1258 case DW_OP_lt: stack[sp-1] = ((LONG_PTR)stack[sp-1] < (LONG_PTR)stack[sp]); sp--; break;
1259 case DW_OP_eq: stack[sp-1] = (stack[sp-1] == stack[sp]); sp--; break;
1260 case DW_OP_ne: stack[sp-1] = (stack[sp-1] != stack[sp]); sp--; break;
1261 case DW_OP_skip: tmp = (short)dwarf_get_u2(&p); p += tmp; break;
1262 case DW_OP_bra: tmp = (short)dwarf_get_u2(&p); if (!stack[sp--]) p += tmp; break;
1263 case DW_OP_GNU_encoded_addr: tmp = *p++; stack[++sp] = dwarf_get_ptr( &p, tmp ); break;
1264 case DW_OP_regx: stack[++sp] = *(ULONG_PTR *)get_context_reg( context, dwarf_get_uleb128(&p) ); break;
1265 case DW_OP_bregx:
1266 reg = dwarf_get_uleb128(&p);
1267 tmp = dwarf_get_sleb128(&p);
1268 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, reg ) + tmp;
1269 break;
1270 case DW_OP_deref_size:
1271 switch (*p++)
1273 case 1: stack[sp] = *(unsigned char *)stack[sp]; break;
1274 case 2: stack[sp] = *(unsigned short *)stack[sp]; break;
1275 case 4: stack[sp] = *(unsigned int *)stack[sp]; break;
1276 case 8: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1278 break;
1279 default:
1280 FIXME( "unhandled opcode %02x\n", opcode );
1283 return stack[sp];
1286 /* apply the computed frame info to the actual context */
1287 static void apply_frame_state( CONTEXT *context, struct frame_state *state )
1289 unsigned int i;
1290 ULONG_PTR cfa, value;
1291 CONTEXT new_context = *context;
1293 switch (state->cfa_rule)
1295 case RULE_EXPRESSION:
1296 cfa = *(ULONG_PTR *)eval_expression( (const unsigned char *)state->cfa_offset, context );
1297 break;
1298 case RULE_VAL_EXPRESSION:
1299 cfa = eval_expression( (const unsigned char *)state->cfa_offset, context );
1300 break;
1301 default:
1302 cfa = *(ULONG_PTR *)get_context_reg( context, state->cfa_reg ) + state->cfa_offset;
1303 break;
1305 if (!cfa) return;
1307 for (i = 0; i < NB_FRAME_REGS; i++)
1309 switch (state->rules[i])
1311 case RULE_UNSET:
1312 case RULE_UNDEFINED:
1313 case RULE_SAME:
1314 break;
1315 case RULE_CFA_OFFSET:
1316 set_context_reg( &new_context, i, (char *)cfa + state->regs[i] );
1317 break;
1318 case RULE_OTHER_REG:
1319 set_context_reg( &new_context, i, get_context_reg( context, state->regs[i] ));
1320 break;
1321 case RULE_EXPRESSION:
1322 value = eval_expression( (const unsigned char *)state->regs[i], context );
1323 set_context_reg( &new_context, i, (void *)value );
1324 break;
1325 case RULE_VAL_EXPRESSION:
1326 value = eval_expression( (const unsigned char *)state->regs[i], context );
1327 set_context_reg( &new_context, i, &value );
1328 break;
1331 new_context.Rsp = cfa;
1332 *context = new_context;
1336 /***********************************************************************
1337 * dwarf_virtual_unwind
1339 * Equivalent of RtlVirtualUnwind for builtin modules.
1341 static NTSTATUS dwarf_virtual_unwind( ULONG64 ip, ULONG64 *frame,CONTEXT *context,
1342 const struct dwarf_fde *fde, const struct dwarf_eh_bases *bases,
1343 PEXCEPTION_ROUTINE *handler, void **handler_data )
1345 const struct dwarf_cie *cie;
1346 const unsigned char *ptr, *augmentation, *end;
1347 ULONG_PTR len, code_end;
1348 struct frame_info info;
1349 struct frame_state state_stack[MAX_SAVED_STATES];
1350 int aug_z_format = 0;
1351 unsigned char lsda_encoding = DW_EH_PE_omit;
1353 memset( &info, 0, sizeof(info) );
1354 info.state_stack = state_stack;
1355 info.ip = (ULONG_PTR)bases->func;
1356 *handler = NULL;
1358 cie = (const struct dwarf_cie *)((const char *)&fde->cie_offset - fde->cie_offset);
1360 /* parse the CIE first */
1362 if (cie->version != 1 && cie->version != 3)
1364 FIXME( "unknown CIE version %u at %p\n", cie->version, cie );
1365 return STATUS_INVALID_DISPOSITION;
1367 ptr = cie->augmentation + strlen((const char *)cie->augmentation) + 1;
1369 info.code_align = dwarf_get_uleb128( &ptr );
1370 info.data_align = dwarf_get_sleb128( &ptr );
1371 if (cie->version == 1)
1372 info.retaddr_reg = *ptr++;
1373 else
1374 info.retaddr_reg = dwarf_get_uleb128( &ptr );
1375 info.state.cfa_rule = RULE_CFA_OFFSET;
1377 TRACE( "function %lx base %p cie %p len %x id %x version %x aug '%s' code_align %lu data_align %ld retaddr %s\n",
1378 ip, bases->func, cie, cie->length, cie->id, cie->version, cie->augmentation,
1379 info.code_align, info.data_align, dwarf_reg_names[info.retaddr_reg] );
1381 end = NULL;
1382 for (augmentation = cie->augmentation; *augmentation; augmentation++)
1384 switch (*augmentation)
1386 case 'z':
1387 len = dwarf_get_uleb128( &ptr );
1388 end = ptr + len;
1389 aug_z_format = 1;
1390 continue;
1391 case 'L':
1392 lsda_encoding = *ptr++;
1393 continue;
1394 case 'P':
1396 unsigned char encoding = *ptr++;
1397 *handler = (void *)dwarf_get_ptr( &ptr, encoding );
1398 continue;
1400 case 'R':
1401 info.fde_encoding = *ptr++;
1402 continue;
1403 case 'S':
1404 info.signal_frame = 1;
1405 continue;
1407 FIXME( "unknown augmentation '%c'\n", *augmentation );
1408 if (!end) return STATUS_INVALID_DISPOSITION; /* cannot continue */
1409 break;
1411 if (end) ptr = end;
1413 end = (const unsigned char *)(&cie->length + 1) + cie->length;
1414 execute_cfa_instructions( ptr, end, ip, &info );
1416 ptr = (const unsigned char *)(fde + 1);
1417 info.ip = dwarf_get_ptr( &ptr, info.fde_encoding ); /* fde code start */
1418 code_end = info.ip + dwarf_get_ptr( &ptr, info.fde_encoding & 0x0f ); /* fde code length */
1420 if (aug_z_format) /* get length of augmentation data */
1422 len = dwarf_get_uleb128( &ptr );
1423 end = ptr + len;
1425 else end = NULL;
1427 *handler_data = (void *)dwarf_get_ptr( &ptr, lsda_encoding );
1428 if (end) ptr = end;
1430 end = (const unsigned char *)(&fde->length + 1) + fde->length;
1431 TRACE( "fde %p len %x personality %p lsda %p code %lx-%lx\n",
1432 fde, fde->length, *handler, *handler_data, info.ip, code_end );
1433 execute_cfa_instructions( ptr, end, ip, &info );
1434 *frame = context->Rsp;
1435 apply_frame_state( context, &info.state );
1437 TRACE( "next function rip=%016lx\n", context->Rip );
1438 TRACE( " rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1439 context->Rax, context->Rbx, context->Rcx, context->Rdx );
1440 TRACE( " rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1441 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1442 TRACE( " r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
1443 context->R8, context->R9, context->R10, context->R11 );
1444 TRACE( " r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1445 context->R12, context->R13, context->R14, context->R15 );
1447 return STATUS_SUCCESS;
1451 #ifdef HAVE_LIBUNWIND_H
1452 /***********************************************************************
1453 * libunwind_set_cursor_from_context
1455 static int libunwind_set_cursor_from_context( unw_cursor_t *cursor, CONTEXT *context, ULONG64 ip )
1457 int rc;
1459 rc = unw_set_reg(cursor, UNW_REG_IP, ip);
1460 if (rc == UNW_ESUCCESS)
1461 rc = unw_set_reg(cursor, UNW_REG_SP, context->Rsp);
1462 if (rc == UNW_ESUCCESS)
1463 rc = unw_set_reg(cursor, UNW_X86_64_RAX, context->Rax);
1464 if (rc == UNW_ESUCCESS)
1465 rc = unw_set_reg(cursor, UNW_X86_64_RDX, context->Rdx);
1466 if (rc == UNW_ESUCCESS)
1467 rc = unw_set_reg(cursor, UNW_X86_64_RCX, context->Rcx);
1468 if (rc == UNW_ESUCCESS)
1469 rc = unw_set_reg(cursor, UNW_X86_64_RBX, context->Rbx);
1470 if (rc == UNW_ESUCCESS)
1471 rc = unw_set_reg(cursor, UNW_X86_64_RSI, context->Rsi);
1472 if (rc == UNW_ESUCCESS)
1473 rc = unw_set_reg(cursor, UNW_X86_64_RDI, context->Rdi);
1474 if (rc == UNW_ESUCCESS)
1475 rc = unw_set_reg(cursor, UNW_X86_64_RBP, context->Rbp);
1476 if (rc == UNW_ESUCCESS)
1477 rc = unw_set_reg(cursor, UNW_X86_64_R8, context->R8);
1478 if (rc == UNW_ESUCCESS)
1479 rc = unw_set_reg(cursor, UNW_X86_64_R9, context->R9);
1480 if (rc == UNW_ESUCCESS)
1481 rc = unw_set_reg(cursor, UNW_X86_64_R10, context->R10);
1482 if (rc == UNW_ESUCCESS)
1483 rc = unw_set_reg(cursor, UNW_X86_64_R11, context->R11);
1484 if (rc == UNW_ESUCCESS)
1485 rc = unw_set_reg(cursor, UNW_X86_64_R12, context->R12);
1486 if (rc == UNW_ESUCCESS)
1487 rc = unw_set_reg(cursor, UNW_X86_64_R13, context->R13);
1488 if (rc == UNW_ESUCCESS)
1489 rc = unw_set_reg(cursor, UNW_X86_64_R14, context->R14);
1490 if (rc == UNW_ESUCCESS)
1491 rc = unw_set_reg(cursor, UNW_X86_64_R15, context->R15);
1493 return rc;
1497 /***********************************************************************
1498 * libunwind_get_reg
1500 static int libunwind_get_reg( unw_cursor_t *cursor, unw_regnum_t reg, ULONG64 *val )
1502 int rc;
1503 unw_word_t word;
1505 rc = unw_get_reg(cursor, reg, &word);
1506 if (rc == UNW_ESUCCESS)
1507 *val = word;
1509 return rc;
1513 /***********************************************************************
1514 * libunwind_set_context_from_cursor
1516 static BOOL libunwind_set_context_from_cursor( CONTEXT *context, unw_cursor_t *cursor )
1518 int rc;
1520 rc = libunwind_get_reg(cursor, UNW_REG_IP, &context->Rip);
1521 if (rc == UNW_ESUCCESS)
1522 rc = libunwind_get_reg(cursor, UNW_REG_SP, &context->Rsp);
1523 if (rc == UNW_ESUCCESS)
1524 rc = libunwind_get_reg(cursor, UNW_X86_64_RAX, &context->Rax);
1525 if (rc == UNW_ESUCCESS)
1526 rc = libunwind_get_reg(cursor, UNW_X86_64_RDX, &context->Rdx);
1527 if (rc == UNW_ESUCCESS)
1528 rc = libunwind_get_reg(cursor, UNW_X86_64_RCX, &context->Rcx);
1529 if (rc == UNW_ESUCCESS)
1530 rc = libunwind_get_reg(cursor, UNW_X86_64_RBX, &context->Rbx);
1531 if (rc == UNW_ESUCCESS)
1532 rc = libunwind_get_reg(cursor, UNW_X86_64_RSI, &context->Rsi);
1533 if (rc == UNW_ESUCCESS)
1534 rc = libunwind_get_reg(cursor, UNW_X86_64_RDI, &context->Rdi);
1535 if (rc == UNW_ESUCCESS)
1536 rc = libunwind_get_reg(cursor, UNW_X86_64_RBP, &context->Rbp);
1537 if (rc == UNW_ESUCCESS)
1538 rc = libunwind_get_reg(cursor, UNW_X86_64_R8, &context->R8);
1539 if (rc == UNW_ESUCCESS)
1540 rc = libunwind_get_reg(cursor, UNW_X86_64_R9, &context->R9);
1541 if (rc == UNW_ESUCCESS)
1542 rc = libunwind_get_reg(cursor, UNW_X86_64_R10, &context->R10);
1543 if (rc == UNW_ESUCCESS)
1544 rc = libunwind_get_reg(cursor, UNW_X86_64_R11, &context->R11);
1545 if (rc == UNW_ESUCCESS)
1546 rc = libunwind_get_reg(cursor, UNW_X86_64_R12, &context->R12);
1547 if (rc == UNW_ESUCCESS)
1548 rc = libunwind_get_reg(cursor, UNW_X86_64_R13, &context->R13);
1549 if (rc == UNW_ESUCCESS)
1550 rc = libunwind_get_reg(cursor, UNW_X86_64_R14, &context->R14);
1551 if (rc == UNW_ESUCCESS)
1552 rc = libunwind_get_reg(cursor, UNW_X86_64_R15, &context->R15);
1554 return rc;
1558 /***********************************************************************
1559 * libunwind_virtual_unwind
1561 * Equivalent of RtlVirtualUnwind for builtin modules.
1563 static NTSTATUS libunwind_virtual_unwind( ULONG64 ip, BOOL* got_info, ULONG64 *frame, CONTEXT *context,
1564 PEXCEPTION_ROUTINE *handler, void **handler_data )
1566 unw_context_t unw_context;
1567 unw_cursor_t cursor;
1568 unw_proc_info_t info;
1569 int rc;
1571 rc = unw_getcontext( &unw_context );
1572 if (rc == UNW_ESUCCESS)
1573 rc = unw_init_local( &cursor, &unw_context );
1574 if (rc == UNW_ESUCCESS)
1575 rc = libunwind_set_cursor_from_context( &cursor, context, ip - 1 );
1576 if (rc != UNW_ESUCCESS)
1578 WARN( "setup failed: %d\n", rc );
1579 return STATUS_INVALID_DISPOSITION;
1582 rc = unw_get_proc_info(&cursor, &info);
1583 if (rc != UNW_ESUCCESS && rc != UNW_ENOINFO)
1585 WARN( "failed to get info: %d\n", rc );
1586 return STATUS_INVALID_DISPOSITION;
1588 if (rc == UNW_ENOINFO || ip < info.start_ip || info.end_ip <= ip || !info.format)
1590 *got_info = FALSE;
1591 return STATUS_SUCCESS;
1594 TRACE( "ip %#lx function %#lx-%#lx personality %#lx lsda %#lx fde %#lx\n",
1595 ip, (unsigned long)info.start_ip, (unsigned long)info.end_ip, (unsigned long)info.handler,
1596 (unsigned long)info.lsda, (unsigned long)info.unwind_info );
1598 rc = unw_step(&cursor);
1599 if (rc < 0)
1601 WARN( "failed to unwind: %d\n", rc );
1602 return STATUS_INVALID_DISPOSITION;
1605 *frame = context->Rsp;
1607 rc = libunwind_set_context_from_cursor( context, &cursor );
1608 if (rc != UNW_ESUCCESS)
1610 WARN( "failed to update context after unwind: %d\n", rc );
1611 return STATUS_INVALID_DISPOSITION;
1614 *handler = (void*)info.handler;
1615 *handler_data = (void*)info.lsda;
1616 *got_info = TRUE;
1618 TRACE( "next function rip=%016lx\n", context->Rip );
1619 TRACE( " rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1620 context->Rax, context->Rbx, context->Rcx, context->Rdx );
1621 TRACE( " rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1622 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1623 TRACE( " r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
1624 context->R8, context->R9, context->R10, context->R11 );
1625 TRACE( " r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1626 context->R12, context->R13, context->R14, context->R15 );
1628 return STATUS_SUCCESS;
1630 #endif
1633 /***********************************************************************
1634 * dispatch_signal
1636 static inline int dispatch_signal(unsigned int sig)
1638 if (handlers[sig] == NULL) return 0;
1639 return handlers[sig](sig);
1642 /***********************************************************************
1643 * get_signal_stack
1645 * Get the base of the signal stack for the current thread.
1647 static inline void *get_signal_stack(void)
1649 return (char *)NtCurrentTeb() + teb_size;
1652 /***********************************************************************
1653 * is_inside_signal_stack
1655 * Check if pointer is inside the signal stack.
1657 static inline BOOL is_inside_signal_stack( void *ptr )
1659 return ((char *)ptr >= (char *)get_signal_stack() &&
1660 (char *)ptr < (char *)get_signal_stack() + signal_stack_size);
1663 /***********************************************************************
1664 * save_context
1666 * Set the register values from a sigcontext.
1668 static void save_context( CONTEXT *context, const ucontext_t *sigcontext )
1670 context->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS;
1671 context->Rax = RAX_sig(sigcontext);
1672 context->Rcx = RCX_sig(sigcontext);
1673 context->Rdx = RDX_sig(sigcontext);
1674 context->Rbx = RBX_sig(sigcontext);
1675 context->Rsp = RSP_sig(sigcontext);
1676 context->Rbp = RBP_sig(sigcontext);
1677 context->Rsi = RSI_sig(sigcontext);
1678 context->Rdi = RDI_sig(sigcontext);
1679 context->R8 = R8_sig(sigcontext);
1680 context->R9 = R9_sig(sigcontext);
1681 context->R10 = R10_sig(sigcontext);
1682 context->R11 = R11_sig(sigcontext);
1683 context->R12 = R12_sig(sigcontext);
1684 context->R13 = R13_sig(sigcontext);
1685 context->R14 = R14_sig(sigcontext);
1686 context->R15 = R15_sig(sigcontext);
1687 context->Rip = RIP_sig(sigcontext);
1688 context->SegCs = CS_sig(sigcontext);
1689 context->SegFs = FS_sig(sigcontext);
1690 context->SegGs = GS_sig(sigcontext);
1691 context->EFlags = EFL_sig(sigcontext);
1692 #ifdef DS_sig
1693 context->SegDs = DS_sig(sigcontext);
1694 #else
1695 __asm__("movw %%ds,%0" : "=m" (context->SegDs));
1696 #endif
1697 #ifdef ES_sig
1698 context->SegEs = ES_sig(sigcontext);
1699 #else
1700 __asm__("movw %%es,%0" : "=m" (context->SegEs));
1701 #endif
1702 #ifdef SS_sig
1703 context->SegSs = SS_sig(sigcontext);
1704 #else
1705 __asm__("movw %%ss,%0" : "=m" (context->SegSs));
1706 #endif
1707 context->Dr0 = amd64_thread_data()->dr0;
1708 context->Dr1 = amd64_thread_data()->dr1;
1709 context->Dr2 = amd64_thread_data()->dr2;
1710 context->Dr3 = amd64_thread_data()->dr3;
1711 context->Dr6 = amd64_thread_data()->dr6;
1712 context->Dr7 = amd64_thread_data()->dr7;
1713 if (FPU_sig(sigcontext))
1715 context->ContextFlags |= CONTEXT_FLOATING_POINT;
1716 context->u.FltSave = *FPU_sig(sigcontext);
1717 context->MxCsr = context->u.FltSave.MxCsr;
1722 /***********************************************************************
1723 * restore_context
1725 * Build a sigcontext from the register values.
1727 static void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1729 amd64_thread_data()->dr0 = context->Dr0;
1730 amd64_thread_data()->dr1 = context->Dr1;
1731 amd64_thread_data()->dr2 = context->Dr2;
1732 amd64_thread_data()->dr3 = context->Dr3;
1733 amd64_thread_data()->dr6 = context->Dr6;
1734 amd64_thread_data()->dr7 = context->Dr7;
1735 RAX_sig(sigcontext) = context->Rax;
1736 RCX_sig(sigcontext) = context->Rcx;
1737 RDX_sig(sigcontext) = context->Rdx;
1738 RBX_sig(sigcontext) = context->Rbx;
1739 RSP_sig(sigcontext) = context->Rsp;
1740 RBP_sig(sigcontext) = context->Rbp;
1741 RSI_sig(sigcontext) = context->Rsi;
1742 RDI_sig(sigcontext) = context->Rdi;
1743 R8_sig(sigcontext) = context->R8;
1744 R9_sig(sigcontext) = context->R9;
1745 R10_sig(sigcontext) = context->R10;
1746 R11_sig(sigcontext) = context->R11;
1747 R12_sig(sigcontext) = context->R12;
1748 R13_sig(sigcontext) = context->R13;
1749 R14_sig(sigcontext) = context->R14;
1750 R15_sig(sigcontext) = context->R15;
1751 RIP_sig(sigcontext) = context->Rip;
1752 CS_sig(sigcontext) = context->SegCs;
1753 FS_sig(sigcontext) = context->SegFs;
1754 GS_sig(sigcontext) = context->SegGs;
1755 EFL_sig(sigcontext) = context->EFlags;
1756 #ifdef DS_sig
1757 DS_sig(sigcontext) = context->SegDs;
1758 #endif
1759 #ifdef ES_sig
1760 ES_sig(sigcontext) = context->SegEs;
1761 #endif
1762 #ifdef SS_sig
1763 SS_sig(sigcontext) = context->SegSs;
1764 #endif
1765 if (FPU_sig(sigcontext)) *FPU_sig(sigcontext) = context->u.FltSave;
1769 /**************************************************************************
1770 * __chkstk (NTDLL.@)
1772 * Supposed to touch all the stack pages, but we shouldn't need that.
1774 __ASM_GLOBAL_FUNC( __chkstk, "ret" );
1777 /***********************************************************************
1778 * RtlCaptureContext (NTDLL.@)
1780 __ASM_GLOBAL_FUNC( RtlCaptureContext,
1781 "pushfq\n\t"
1782 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
1783 "movl $0x001000f,0x30(%rcx)\n\t" /* context->ContextFlags */
1784 "stmxcsr 0x34(%rcx)\n\t" /* context->MxCsr */
1785 "movw %cs,0x38(%rcx)\n\t" /* context->SegCs */
1786 "movw %ds,0x3a(%rcx)\n\t" /* context->SegDs */
1787 "movw %es,0x3c(%rcx)\n\t" /* context->SegEs */
1788 "movw %fs,0x3e(%rcx)\n\t" /* context->SegFs */
1789 "movw %gs,0x40(%rcx)\n\t" /* context->SegGs */
1790 "movw %ss,0x42(%rcx)\n\t" /* context->SegSs */
1791 "popq 0x44(%rcx)\n\t" /* context->Eflags */
1792 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
1793 "movq %rax,0x78(%rcx)\n\t" /* context->Rax */
1794 "movq %rcx,0x80(%rcx)\n\t" /* context->Rcx */
1795 "movq %rdx,0x88(%rcx)\n\t" /* context->Rdx */
1796 "movq %rbx,0x90(%rcx)\n\t" /* context->Rbx */
1797 "leaq 8(%rsp),%rax\n\t"
1798 "movq %rax,0x98(%rcx)\n\t" /* context->Rsp */
1799 "movq %rbp,0xa0(%rcx)\n\t" /* context->Rbp */
1800 "movq %rsi,0xa8(%rcx)\n\t" /* context->Rsi */
1801 "movq %rdi,0xb0(%rcx)\n\t" /* context->Rdi */
1802 "movq %r8,0xb8(%rcx)\n\t" /* context->R8 */
1803 "movq %r9,0xc0(%rcx)\n\t" /* context->R9 */
1804 "movq %r10,0xc8(%rcx)\n\t" /* context->R10 */
1805 "movq %r11,0xd0(%rcx)\n\t" /* context->R11 */
1806 "movq %r12,0xd8(%rcx)\n\t" /* context->R12 */
1807 "movq %r13,0xe0(%rcx)\n\t" /* context->R13 */
1808 "movq %r14,0xe8(%rcx)\n\t" /* context->R14 */
1809 "movq %r15,0xf0(%rcx)\n\t" /* context->R15 */
1810 "movq (%rsp),%rax\n\t"
1811 "movq %rax,0xf8(%rcx)\n\t" /* context->Rip */
1812 "fxsave 0x100(%rcx)\n\t" /* context->FtlSave */
1813 "movdqa %xmm0,0x1a0(%rcx)\n\t" /* context->Xmm0 */
1814 "movdqa %xmm1,0x1b0(%rcx)\n\t" /* context->Xmm1 */
1815 "movdqa %xmm2,0x1c0(%rcx)\n\t" /* context->Xmm2 */
1816 "movdqa %xmm3,0x1d0(%rcx)\n\t" /* context->Xmm3 */
1817 "movdqa %xmm4,0x1e0(%rcx)\n\t" /* context->Xmm4 */
1818 "movdqa %xmm5,0x1f0(%rcx)\n\t" /* context->Xmm5 */
1819 "movdqa %xmm6,0x200(%rcx)\n\t" /* context->Xmm6 */
1820 "movdqa %xmm7,0x210(%rcx)\n\t" /* context->Xmm7 */
1821 "movdqa %xmm8,0x220(%rcx)\n\t" /* context->Xmm8 */
1822 "movdqa %xmm9,0x230(%rcx)\n\t" /* context->Xmm9 */
1823 "movdqa %xmm10,0x240(%rcx)\n\t" /* context->Xmm10 */
1824 "movdqa %xmm11,0x250(%rcx)\n\t" /* context->Xmm11 */
1825 "movdqa %xmm12,0x260(%rcx)\n\t" /* context->Xmm12 */
1826 "movdqa %xmm13,0x270(%rcx)\n\t" /* context->Xmm13 */
1827 "movdqa %xmm14,0x280(%rcx)\n\t" /* context->Xmm14 */
1828 "movdqa %xmm15,0x290(%rcx)\n\t" /* context->Xmm15 */
1829 "ret" );
1831 /***********************************************************************
1832 * set_full_cpu_context
1834 * Set the new CPU context.
1836 extern void set_full_cpu_context( const CONTEXT *context );
1837 __ASM_GLOBAL_FUNC( set_full_cpu_context,
1838 "subq $40,%rsp\n\t"
1839 __ASM_CFI(".cfi_adjust_cfa_offset 40\n\t")
1840 "ldmxcsr 0x34(%rdi)\n\t" /* context->MxCsr */
1841 "movw 0x38(%rdi),%ax\n\t" /* context->SegCs */
1842 "movq %rax,8(%rsp)\n\t"
1843 "movw 0x42(%rdi),%ax\n\t" /* context->SegSs */
1844 "movq %rax,32(%rsp)\n\t"
1845 "movq 0x44(%rdi),%rax\n\t" /* context->Eflags */
1846 "movq %rax,16(%rsp)\n\t"
1847 "movq 0x80(%rdi),%rcx\n\t" /* context->Rcx */
1848 "movq 0x88(%rdi),%rdx\n\t" /* context->Rdx */
1849 "movq 0x90(%rdi),%rbx\n\t" /* context->Rbx */
1850 "movq 0x98(%rdi),%rax\n\t" /* context->Rsp */
1851 "movq %rax,24(%rsp)\n\t"
1852 "movq 0xa0(%rdi),%rbp\n\t" /* context->Rbp */
1853 "movq 0xa8(%rdi),%rsi\n\t" /* context->Rsi */
1854 "movq 0xb8(%rdi),%r8\n\t" /* context->R8 */
1855 "movq 0xc0(%rdi),%r9\n\t" /* context->R9 */
1856 "movq 0xc8(%rdi),%r10\n\t" /* context->R10 */
1857 "movq 0xd0(%rdi),%r11\n\t" /* context->R11 */
1858 "movq 0xd8(%rdi),%r12\n\t" /* context->R12 */
1859 "movq 0xe0(%rdi),%r13\n\t" /* context->R13 */
1860 "movq 0xe8(%rdi),%r14\n\t" /* context->R14 */
1861 "movq 0xf0(%rdi),%r15\n\t" /* context->R15 */
1862 "movq 0xf8(%rdi),%rax\n\t" /* context->Rip */
1863 "movq %rax,(%rsp)\n\t"
1864 "fxrstor 0x100(%rdi)\n\t" /* context->FtlSave */
1865 "movdqa 0x1a0(%rdi),%xmm0\n\t" /* context->Xmm0 */
1866 "movdqa 0x1b0(%rdi),%xmm1\n\t" /* context->Xmm1 */
1867 "movdqa 0x1c0(%rdi),%xmm2\n\t" /* context->Xmm2 */
1868 "movdqa 0x1d0(%rdi),%xmm3\n\t" /* context->Xmm3 */
1869 "movdqa 0x1e0(%rdi),%xmm4\n\t" /* context->Xmm4 */
1870 "movdqa 0x1f0(%rdi),%xmm5\n\t" /* context->Xmm5 */
1871 "movdqa 0x200(%rdi),%xmm6\n\t" /* context->Xmm6 */
1872 "movdqa 0x210(%rdi),%xmm7\n\t" /* context->Xmm7 */
1873 "movdqa 0x220(%rdi),%xmm8\n\t" /* context->Xmm8 */
1874 "movdqa 0x230(%rdi),%xmm9\n\t" /* context->Xmm9 */
1875 "movdqa 0x240(%rdi),%xmm10\n\t" /* context->Xmm10 */
1876 "movdqa 0x250(%rdi),%xmm11\n\t" /* context->Xmm11 */
1877 "movdqa 0x260(%rdi),%xmm12\n\t" /* context->Xmm12 */
1878 "movdqa 0x270(%rdi),%xmm13\n\t" /* context->Xmm13 */
1879 "movdqa 0x280(%rdi),%xmm14\n\t" /* context->Xmm14 */
1880 "movdqa 0x290(%rdi),%xmm15\n\t" /* context->Xmm15 */
1881 "movq 0x78(%rdi),%rax\n\t" /* context->Rax */
1882 "movq 0xb0(%rdi),%rdi\n\t" /* context->Rdi */
1883 "iretq" );
1886 /***********************************************************************
1887 * set_cpu_context
1889 * Set the new CPU context. Used by NtSetContextThread.
1891 static void set_cpu_context( const CONTEXT *context )
1893 DWORD flags = context->ContextFlags & ~CONTEXT_AMD64;
1895 if (flags & CONTEXT_DEBUG_REGISTERS)
1897 amd64_thread_data()->dr0 = context->Dr0;
1898 amd64_thread_data()->dr1 = context->Dr1;
1899 amd64_thread_data()->dr2 = context->Dr2;
1900 amd64_thread_data()->dr3 = context->Dr3;
1901 amd64_thread_data()->dr6 = context->Dr6;
1902 amd64_thread_data()->dr7 = context->Dr7;
1904 if (flags & CONTEXT_FULL)
1906 if (!(flags & CONTEXT_CONTROL))
1907 FIXME( "setting partial context (%x) not supported\n", flags );
1908 else
1909 set_full_cpu_context( context );
1914 /***********************************************************************
1915 * copy_context
1917 * Copy a register context according to the flags.
1919 static void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
1921 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
1922 if (flags & CONTEXT_CONTROL)
1924 to->Rbp = from->Rbp;
1925 to->Rip = from->Rip;
1926 to->Rsp = from->Rsp;
1927 to->SegCs = from->SegCs;
1928 to->SegSs = from->SegSs;
1929 to->EFlags = from->EFlags;
1931 if (flags & CONTEXT_INTEGER)
1933 to->Rax = from->Rax;
1934 to->Rcx = from->Rcx;
1935 to->Rdx = from->Rdx;
1936 to->Rbx = from->Rbx;
1937 to->Rsi = from->Rsi;
1938 to->Rdi = from->Rdi;
1939 to->R8 = from->R8;
1940 to->R9 = from->R9;
1941 to->R10 = from->R10;
1942 to->R11 = from->R11;
1943 to->R12 = from->R12;
1944 to->R13 = from->R13;
1945 to->R14 = from->R14;
1946 to->R15 = from->R15;
1948 if (flags & CONTEXT_SEGMENTS)
1950 to->SegDs = from->SegDs;
1951 to->SegEs = from->SegEs;
1952 to->SegFs = from->SegFs;
1953 to->SegGs = from->SegGs;
1955 if (flags & CONTEXT_FLOATING_POINT)
1957 to->MxCsr = from->MxCsr;
1958 to->u.FltSave = from->u.FltSave;
1960 if (flags & CONTEXT_DEBUG_REGISTERS)
1962 to->Dr0 = from->Dr0;
1963 to->Dr1 = from->Dr1;
1964 to->Dr2 = from->Dr2;
1965 to->Dr3 = from->Dr3;
1966 to->Dr6 = from->Dr6;
1967 to->Dr7 = from->Dr7;
1972 /***********************************************************************
1973 * context_to_server
1975 * Convert a register context to the server format.
1977 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1979 DWORD flags = from->ContextFlags & ~CONTEXT_AMD64; /* get rid of CPU id */
1981 memset( to, 0, sizeof(*to) );
1982 to->cpu = CPU_x86_64;
1984 if (flags & CONTEXT_CONTROL)
1986 to->flags |= SERVER_CTX_CONTROL;
1987 to->ctl.x86_64_regs.rbp = from->Rbp;
1988 to->ctl.x86_64_regs.rip = from->Rip;
1989 to->ctl.x86_64_regs.rsp = from->Rsp;
1990 to->ctl.x86_64_regs.cs = from->SegCs;
1991 to->ctl.x86_64_regs.ss = from->SegSs;
1992 to->ctl.x86_64_regs.flags = from->EFlags;
1994 if (flags & CONTEXT_INTEGER)
1996 to->flags |= SERVER_CTX_INTEGER;
1997 to->integer.x86_64_regs.rax = from->Rax;
1998 to->integer.x86_64_regs.rcx = from->Rcx;
1999 to->integer.x86_64_regs.rdx = from->Rdx;
2000 to->integer.x86_64_regs.rbx = from->Rbx;
2001 to->integer.x86_64_regs.rsi = from->Rsi;
2002 to->integer.x86_64_regs.rdi = from->Rdi;
2003 to->integer.x86_64_regs.r8 = from->R8;
2004 to->integer.x86_64_regs.r9 = from->R9;
2005 to->integer.x86_64_regs.r10 = from->R10;
2006 to->integer.x86_64_regs.r11 = from->R11;
2007 to->integer.x86_64_regs.r12 = from->R12;
2008 to->integer.x86_64_regs.r13 = from->R13;
2009 to->integer.x86_64_regs.r14 = from->R14;
2010 to->integer.x86_64_regs.r15 = from->R15;
2012 if (flags & CONTEXT_SEGMENTS)
2014 to->flags |= SERVER_CTX_SEGMENTS;
2015 to->seg.x86_64_regs.ds = from->SegDs;
2016 to->seg.x86_64_regs.es = from->SegEs;
2017 to->seg.x86_64_regs.fs = from->SegFs;
2018 to->seg.x86_64_regs.gs = from->SegGs;
2020 if (flags & CONTEXT_FLOATING_POINT)
2022 to->flags |= SERVER_CTX_FLOATING_POINT;
2023 memcpy( to->fp.x86_64_regs.fpregs, &from->u.FltSave, sizeof(to->fp.x86_64_regs.fpregs) );
2025 if (flags & CONTEXT_DEBUG_REGISTERS)
2027 to->flags |= SERVER_CTX_DEBUG_REGISTERS;
2028 to->debug.x86_64_regs.dr0 = from->Dr0;
2029 to->debug.x86_64_regs.dr1 = from->Dr1;
2030 to->debug.x86_64_regs.dr2 = from->Dr2;
2031 to->debug.x86_64_regs.dr3 = from->Dr3;
2032 to->debug.x86_64_regs.dr6 = from->Dr6;
2033 to->debug.x86_64_regs.dr7 = from->Dr7;
2035 return STATUS_SUCCESS;
2039 /***********************************************************************
2040 * context_from_server
2042 * Convert a register context from the server format.
2044 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
2046 if (from->cpu != CPU_x86_64) return STATUS_INVALID_PARAMETER;
2048 to->ContextFlags = CONTEXT_AMD64;
2049 if (from->flags & SERVER_CTX_CONTROL)
2051 to->ContextFlags |= CONTEXT_CONTROL;
2052 to->Rbp = from->ctl.x86_64_regs.rbp;
2053 to->Rip = from->ctl.x86_64_regs.rip;
2054 to->Rsp = from->ctl.x86_64_regs.rsp;
2055 to->SegCs = from->ctl.x86_64_regs.cs;
2056 to->SegSs = from->ctl.x86_64_regs.ss;
2057 to->EFlags = from->ctl.x86_64_regs.flags;
2060 if (from->flags & SERVER_CTX_INTEGER)
2062 to->ContextFlags |= CONTEXT_INTEGER;
2063 to->Rax = from->integer.x86_64_regs.rax;
2064 to->Rcx = from->integer.x86_64_regs.rcx;
2065 to->Rdx = from->integer.x86_64_regs.rdx;
2066 to->Rbx = from->integer.x86_64_regs.rbx;
2067 to->Rsi = from->integer.x86_64_regs.rsi;
2068 to->Rdi = from->integer.x86_64_regs.rdi;
2069 to->R8 = from->integer.x86_64_regs.r8;
2070 to->R9 = from->integer.x86_64_regs.r9;
2071 to->R10 = from->integer.x86_64_regs.r10;
2072 to->R11 = from->integer.x86_64_regs.r11;
2073 to->R12 = from->integer.x86_64_regs.r12;
2074 to->R13 = from->integer.x86_64_regs.r13;
2075 to->R14 = from->integer.x86_64_regs.r14;
2076 to->R15 = from->integer.x86_64_regs.r15;
2078 if (from->flags & SERVER_CTX_SEGMENTS)
2080 to->ContextFlags |= CONTEXT_SEGMENTS;
2081 to->SegDs = from->seg.x86_64_regs.ds;
2082 to->SegEs = from->seg.x86_64_regs.es;
2083 to->SegFs = from->seg.x86_64_regs.fs;
2084 to->SegGs = from->seg.x86_64_regs.gs;
2086 if (from->flags & SERVER_CTX_FLOATING_POINT)
2088 to->ContextFlags |= CONTEXT_FLOATING_POINT;
2089 memcpy( &to->u.FltSave, from->fp.x86_64_regs.fpregs, sizeof(from->fp.x86_64_regs.fpregs) );
2090 to->MxCsr = to->u.FltSave.MxCsr;
2092 if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
2094 to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
2095 to->Dr0 = from->debug.x86_64_regs.dr0;
2096 to->Dr1 = from->debug.x86_64_regs.dr1;
2097 to->Dr2 = from->debug.x86_64_regs.dr2;
2098 to->Dr3 = from->debug.x86_64_regs.dr3;
2099 to->Dr6 = from->debug.x86_64_regs.dr6;
2100 to->Dr7 = from->debug.x86_64_regs.dr7;
2102 return STATUS_SUCCESS;
2106 /***********************************************************************
2107 * NtSetContextThread (NTDLL.@)
2108 * ZwSetContextThread (NTDLL.@)
2110 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
2112 NTSTATUS ret = STATUS_SUCCESS;
2113 BOOL self = (handle == GetCurrentThread());
2115 /* debug registers require a server call */
2116 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64)))
2117 self = (amd64_thread_data()->dr0 == context->Dr0 &&
2118 amd64_thread_data()->dr1 == context->Dr1 &&
2119 amd64_thread_data()->dr2 == context->Dr2 &&
2120 amd64_thread_data()->dr3 == context->Dr3 &&
2121 amd64_thread_data()->dr6 == context->Dr6 &&
2122 amd64_thread_data()->dr7 == context->Dr7);
2124 if (!self) ret = set_thread_context( handle, context, &self );
2126 if (self && ret == STATUS_SUCCESS) set_cpu_context( context );
2127 return ret;
2131 /***********************************************************************
2132 * NtGetContextThread (NTDLL.@)
2133 * ZwGetContextThread (NTDLL.@)
2135 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
2137 NTSTATUS ret;
2138 DWORD needed_flags = context->ContextFlags;
2139 BOOL self = (handle == GetCurrentThread());
2141 /* debug registers require a server call */
2142 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64)) self = FALSE;
2144 if (!self)
2146 if ((ret = get_thread_context( handle, context, &self ))) return ret;
2147 needed_flags &= ~context->ContextFlags;
2150 if (self)
2152 if (needed_flags)
2154 CONTEXT ctx;
2155 RtlCaptureContext( &ctx );
2156 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
2157 context->ContextFlags |= ctx.ContextFlags & needed_flags;
2159 /* update the cached version of the debug registers */
2160 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64))
2162 amd64_thread_data()->dr0 = context->Dr0;
2163 amd64_thread_data()->dr1 = context->Dr1;
2164 amd64_thread_data()->dr2 = context->Dr2;
2165 amd64_thread_data()->dr3 = context->Dr3;
2166 amd64_thread_data()->dr6 = context->Dr6;
2167 amd64_thread_data()->dr7 = context->Dr7;
2170 return STATUS_SUCCESS;
2174 extern void raise_func_trampoline( EXCEPTION_RECORD *rec, CONTEXT *context, raise_func func );
2175 __ASM_GLOBAL_FUNC( raise_func_trampoline,
2176 __ASM_CFI(".cfi_signal_frame\n\t")
2177 __ASM_CFI(".cfi_def_cfa %rbp,160\n\t") /* red zone + rip + rbp + rdi + rsi */
2178 __ASM_CFI(".cfi_rel_offset %rip,24\n\t")
2179 __ASM_CFI(".cfi_rel_offset %rbp,16\n\t")
2180 __ASM_CFI(".cfi_rel_offset %rdi,8\n\t")
2181 __ASM_CFI(".cfi_rel_offset %rsi,0\n\t")
2182 "call *%rdx\n\t"
2183 "int $3")
2185 /***********************************************************************
2186 * setup_exception
2188 * Setup a proper stack frame for the raise function, and modify the
2189 * sigcontext so that the return from the signal handler will call
2190 * the raise function.
2192 static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
2194 struct stack_layout
2196 CONTEXT context;
2197 EXCEPTION_RECORD rec;
2198 ULONG64 rsi;
2199 ULONG64 rdi;
2200 ULONG64 rbp;
2201 ULONG64 rip;
2202 ULONG64 red_zone[16];
2203 } *stack;
2204 ULONG64 *rsp_ptr;
2205 DWORD exception_code = 0;
2207 stack = (struct stack_layout *)(RSP_sig(sigcontext) & ~15);
2209 /* stack sanity checks */
2211 if (is_inside_signal_stack( stack ))
2213 ERR( "nested exception on signal stack in thread %04x eip %016lx esp %016lx stack %p-%p\n",
2214 GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext), (ULONG_PTR)RSP_sig(sigcontext),
2215 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2216 abort_thread(1);
2219 if (stack - 1 > stack || /* check for overflow in subtraction */
2220 (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
2221 (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
2223 WARN( "exception outside of stack limits in thread %04x eip %016lx esp %016lx stack %p-%p\n",
2224 GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext), (ULONG_PTR)RSP_sig(sigcontext),
2225 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2227 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
2229 /* stack overflow on last page, unrecoverable */
2230 UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
2231 ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
2232 diff, GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext),
2233 (ULONG_PTR)RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
2234 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2235 abort_thread(1);
2237 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
2239 /* stack access below stack limit, may be recoverable */
2240 if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
2241 else
2243 UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
2244 ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
2245 diff, GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext),
2246 (ULONG_PTR)RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
2247 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2248 abort_thread(1);
2252 stack--; /* push the stack_layout structure */
2253 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
2254 VALGRIND_MAKE_MEM_UNDEFINED(stack, sizeof(*stack));
2255 #elif defined(VALGRIND_MAKE_WRITABLE)
2256 VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
2257 #endif
2258 stack->rec.ExceptionRecord = NULL;
2259 stack->rec.ExceptionCode = exception_code;
2260 stack->rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
2261 stack->rec.ExceptionAddress = (void *)RIP_sig(sigcontext);
2262 stack->rec.NumberParameters = 0;
2263 save_context( &stack->context, sigcontext );
2265 /* store return address and %rbp without aligning, so that the offset is fixed */
2266 rsp_ptr = (ULONG64 *)RSP_sig(sigcontext) - 16;
2267 *(--rsp_ptr) = RIP_sig(sigcontext);
2268 *(--rsp_ptr) = RBP_sig(sigcontext);
2269 *(--rsp_ptr) = RDI_sig(sigcontext);
2270 *(--rsp_ptr) = RSI_sig(sigcontext);
2272 /* now modify the sigcontext to return to the raise function */
2273 RIP_sig(sigcontext) = (ULONG_PTR)raise_func_trampoline;
2274 RDI_sig(sigcontext) = (ULONG_PTR)&stack->rec;
2275 RSI_sig(sigcontext) = (ULONG_PTR)&stack->context;
2276 RDX_sig(sigcontext) = (ULONG_PTR)func;
2277 RBP_sig(sigcontext) = (ULONG_PTR)rsp_ptr;
2278 RSP_sig(sigcontext) = (ULONG_PTR)stack;
2279 /* clear single-step, direction, and align check flag */
2280 EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
2282 return &stack->rec;
2286 /***********************************************************************
2287 * get_exception_context
2289 * Get a pointer to the context built by setup_exception.
2291 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
2293 return (CONTEXT *)rec - 1; /* cf. stack_layout structure */
2297 /**********************************************************************
2298 * find_function_info
2300 static RUNTIME_FUNCTION *find_function_info( ULONG64 pc, HMODULE module,
2301 RUNTIME_FUNCTION *func, ULONG size )
2303 int min = 0;
2304 int max = size/sizeof(*func) - 1;
2306 while (min <= max)
2308 int pos = (min + max) / 2;
2309 if ((char *)pc < (char *)module + func[pos].BeginAddress) max = pos - 1;
2310 else if ((char *)pc >= (char *)module + func[pos].EndAddress) min = pos + 1;
2311 else
2313 func += pos;
2314 while (func->UnwindData & 1) /* follow chained entry */
2315 func = (RUNTIME_FUNCTION *)((char *)module + (func->UnwindData & ~1));
2316 return func;
2319 return NULL;
2322 /**********************************************************************
2323 * lookup_function_info
2325 static RUNTIME_FUNCTION *lookup_function_info( ULONG64 pc, ULONG64 *base, LDR_MODULE **module )
2327 RUNTIME_FUNCTION *func = NULL;
2328 struct dynamic_unwind_entry *entry;
2329 ULONG size;
2331 /* PE module or wine module */
2332 if (!LdrFindEntryForAddress( (void *)pc, module ))
2334 *base = (ULONG64)(*module)->BaseAddress;
2335 if ((func = RtlImageDirectoryEntryToData( (*module)->BaseAddress, TRUE,
2336 IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )))
2338 /* lookup in function table */
2339 func = find_function_info( pc, (*module)->BaseAddress, func, size );
2342 else
2344 *module = NULL;
2346 RtlEnterCriticalSection( &dynamic_unwind_section );
2347 LIST_FOR_EACH_ENTRY( entry, &dynamic_unwind_list, struct dynamic_unwind_entry, entry )
2349 if (pc >= entry->base && pc < entry->base + entry->size)
2351 *base = entry->base;
2353 /* use callback or lookup in function table */
2354 if (entry->callback)
2355 func = entry->callback( pc, entry->context );
2356 else
2357 func = find_function_info( pc, (HMODULE)entry->base, entry->table, entry->table_size );
2358 break;
2361 RtlLeaveCriticalSection( &dynamic_unwind_section );
2364 return func;
2367 static DWORD nested_exception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
2368 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
2370 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)) return ExceptionContinueSearch;
2372 /* FIXME */
2373 return ExceptionNestedException;
2376 /**********************************************************************
2377 * call_handler
2379 * Call a single exception handler.
2380 * FIXME: Handle nested exceptions.
2382 static DWORD call_handler( EXCEPTION_RECORD *rec, CONTEXT *context, DISPATCHER_CONTEXT *dispatch )
2384 EXCEPTION_REGISTRATION_RECORD frame;
2385 DWORD res;
2387 frame.Handler = nested_exception_handler;
2388 __wine_push_frame( &frame );
2390 TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
2391 dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
2392 res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, context, dispatch );
2393 TRACE( "handler at %p returned %u\n", dispatch->LanguageHandler, res );
2395 __wine_pop_frame( &frame );
2396 return res;
2400 /**********************************************************************
2401 * call_teb_handler
2403 * Call a single exception handler from the TEB chain.
2404 * FIXME: Handle nested exceptions.
2406 static DWORD call_teb_handler( EXCEPTION_RECORD *rec, CONTEXT *context, DISPATCHER_CONTEXT *dispatch,
2407 EXCEPTION_REGISTRATION_RECORD *teb_frame )
2409 DWORD res;
2411 TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatch=%p)\n",
2412 teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, dispatch );
2413 res = teb_frame->Handler( rec, teb_frame, context, (EXCEPTION_REGISTRATION_RECORD**)dispatch );
2414 TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
2415 return res;
2419 /**********************************************************************
2420 * call_stack_handlers
2422 * Call the stack handlers chain.
2424 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *orig_context )
2426 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
2427 UNWIND_HISTORY_TABLE table;
2428 DISPATCHER_CONTEXT dispatch;
2429 CONTEXT context;
2430 LDR_MODULE *module;
2431 NTSTATUS status;
2433 context = *orig_context;
2434 dispatch.TargetIp = 0;
2435 dispatch.ContextRecord = &context;
2436 dispatch.HistoryTable = &table;
2437 for (;;)
2439 /* FIXME: should use the history table to make things faster */
2441 dispatch.ImageBase = 0;
2442 dispatch.ControlPc = context.Rip;
2443 dispatch.ScopeIndex = 0;
2445 /* first look for PE exception information */
2447 if ((dispatch.FunctionEntry = lookup_function_info( dispatch.ControlPc, &dispatch.ImageBase, &module )))
2449 dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, dispatch.ImageBase,
2450 dispatch.ControlPc, dispatch.FunctionEntry,
2451 &context, &dispatch.HandlerData,
2452 &dispatch.EstablisherFrame, NULL );
2453 goto unwind_done;
2456 /* then look for host system exception information */
2458 if (!module || (module->Flags & LDR_WINE_INTERNAL))
2460 BOOL got_info = FALSE;
2461 struct dwarf_eh_bases bases;
2462 const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(dispatch.ControlPc - 1), &bases );
2464 if (fde)
2466 status = dwarf_virtual_unwind( dispatch.ControlPc, &dispatch.EstablisherFrame, &context,
2467 fde, &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
2468 if (status != STATUS_SUCCESS) return status;
2469 got_info = TRUE;
2471 #ifdef HAVE_LIBUNWIND_H
2472 else
2474 status = libunwind_virtual_unwind( dispatch.ControlPc, &got_info, &dispatch.EstablisherFrame, &context,
2475 &dispatch.LanguageHandler, &dispatch.HandlerData );
2476 if (status != STATUS_SUCCESS) return status;
2478 #endif
2480 if (got_info)
2482 dispatch.FunctionEntry = NULL;
2483 if (dispatch.LanguageHandler && !module)
2485 FIXME( "calling personality routine in system library not supported yet\n" );
2486 dispatch.LanguageHandler = NULL;
2488 goto unwind_done;
2491 else WARN( "exception data not found in %s\n", debugstr_w(module->BaseDllName.Buffer) );
2493 context.Rip = *(ULONG64 *)context.Rsp;
2494 context.Rsp = context.Rsp + sizeof(ULONG64);
2495 dispatch.EstablisherFrame = context.Rsp;
2496 dispatch.LanguageHandler = NULL;
2498 unwind_done:
2499 if (!dispatch.EstablisherFrame) break;
2501 if ((dispatch.EstablisherFrame & 7) ||
2502 dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
2503 dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
2505 ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
2506 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2507 rec->ExceptionFlags |= EH_STACK_INVALID;
2508 break;
2511 if (dispatch.LanguageHandler)
2513 switch (call_handler( rec, orig_context, &dispatch ))
2515 case ExceptionContinueExecution:
2516 if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
2517 return STATUS_SUCCESS;
2518 case ExceptionContinueSearch:
2519 break;
2520 case ExceptionNestedException:
2521 FIXME( "nested exception\n" );
2522 break;
2523 case ExceptionCollidedUnwind: {
2524 ULONG64 frame;
2526 context = *dispatch.ContextRecord;
2527 dispatch.ContextRecord = &context;
2528 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
2529 dispatch.ControlPc, dispatch.FunctionEntry,
2530 &context, NULL, &frame, NULL );
2531 goto unwind_done;
2533 default:
2534 return STATUS_INVALID_DISPOSITION;
2537 /* hack: call wine handlers registered in the tib list */
2538 else while ((ULONG64)teb_frame < context.Rsp)
2540 TRACE( "found wine frame %p rsp %lx handler %p\n",
2541 teb_frame, context.Rsp, teb_frame->Handler );
2542 dispatch.EstablisherFrame = (ULONG64)teb_frame;
2543 switch (call_teb_handler( rec, orig_context, &dispatch, teb_frame ))
2545 case ExceptionContinueExecution:
2546 if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
2547 return STATUS_SUCCESS;
2548 case ExceptionContinueSearch:
2549 break;
2550 case ExceptionNestedException:
2551 FIXME( "nested exception\n" );
2552 break;
2553 case ExceptionCollidedUnwind: {
2554 ULONG64 frame;
2556 context = *dispatch.ContextRecord;
2557 dispatch.ContextRecord = &context;
2558 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
2559 dispatch.ControlPc, dispatch.FunctionEntry,
2560 &context, NULL, &frame, NULL );
2561 teb_frame = teb_frame->Prev;
2562 goto unwind_done;
2564 default:
2565 return STATUS_INVALID_DISPOSITION;
2567 teb_frame = teb_frame->Prev;
2570 if (context.Rsp == (ULONG64)NtCurrentTeb()->Tib.StackBase) break;
2572 return STATUS_UNHANDLED_EXCEPTION;
2576 /*******************************************************************
2577 * NtRaiseException (NTDLL.@)
2579 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
2581 NTSTATUS status;
2583 if (first_chance)
2585 DWORD c;
2587 TRACE( "code=%x flags=%x addr=%p ip=%lx tid=%04x\n",
2588 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
2589 context->Rip, GetCurrentThreadId() );
2590 for (c = 0; c < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); c++)
2591 TRACE( " info[%d]=%016lx\n", c, rec->ExceptionInformation[c] );
2592 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
2594 if (rec->ExceptionInformation[1] >> 16)
2595 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
2596 rec->ExceptionAddress,
2597 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
2598 else
2599 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
2600 rec->ExceptionAddress,
2601 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
2603 else
2605 TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
2606 context->Rax, context->Rbx, context->Rcx, context->Rdx );
2607 TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
2608 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
2609 TRACE(" r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
2610 context->R8, context->R9, context->R10, context->R11 );
2611 TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
2612 context->R12, context->R13, context->R14, context->R15 );
2614 status = send_debug_event( rec, TRUE, context );
2615 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED) goto done;
2617 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
2618 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Rip--;
2620 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION) goto done;
2622 if ((status = call_stack_handlers( rec, context )) == STATUS_SUCCESS) goto done;
2623 if (status != STATUS_UNHANDLED_EXCEPTION) return status;
2626 /* last chance exception */
2628 status = send_debug_event( rec, FALSE, context );
2629 if (status != DBG_CONTINUE)
2631 if (rec->ExceptionFlags & EH_STACK_INVALID)
2632 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
2633 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
2634 ERR("Process attempted to continue execution after noncontinuable exception.\n");
2635 else
2636 ERR("Unhandled exception code %x flags %x addr %p\n",
2637 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
2638 NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
2641 done:
2642 return NtSetContextThread( GetCurrentThread(), context );
2646 /**********************************************************************
2647 * raise_segv_exception
2649 static void raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2651 NTSTATUS status;
2653 switch(rec->ExceptionCode)
2655 case EXCEPTION_ACCESS_VIOLATION:
2656 if (rec->NumberParameters == 2)
2658 if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
2659 rec->ExceptionInformation[0], FALSE )))
2660 set_cpu_context( context );
2662 break;
2663 case EXCEPTION_BREAKPOINT:
2664 switch (rec->ExceptionInformation[0])
2666 case 1: /* BREAKPOINT_PRINT */
2667 case 3: /* BREAKPOINT_LOAD_SYMBOLS */
2668 case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
2669 case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
2670 set_cpu_context( context );
2672 break;
2674 status = NtRaiseException( rec, context, TRUE );
2675 raise_status( status, rec );
2679 /**********************************************************************
2680 * raise_trap_exception
2682 static void raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2684 NTSTATUS status;
2686 if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
2688 /* when single stepping can't tell whether this is a hw bp or a
2689 * single step interrupt. try to avoid as much overhead as possible
2690 * and only do a server call if there is any hw bp enabled. */
2692 if( !(context->EFlags & 0x100) || (amd64_thread_data()->dr7 & 0xff) )
2694 /* (possible) hardware breakpoint, fetch the debug registers */
2695 DWORD saved_flags = context->ContextFlags;
2696 context->ContextFlags = CONTEXT_DEBUG_REGISTERS;
2697 NtGetContextThread(GetCurrentThread(), context);
2698 context->ContextFlags |= saved_flags; /* restore flags */
2701 context->EFlags &= ~0x100; /* clear single-step flag */
2704 status = NtRaiseException( rec, context, TRUE );
2705 raise_status( status, rec );
2709 /**********************************************************************
2710 * raise_generic_exception
2712 * Generic raise function for exceptions that don't need special treatment.
2714 static void raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2716 NTSTATUS status = NtRaiseException( rec, context, TRUE );
2717 raise_status( status, rec );
2721 /***********************************************************************
2722 * handle_interrupt
2724 * Handle an interrupt.
2726 static inline BOOL handle_interrupt( unsigned int interrupt, EXCEPTION_RECORD *rec, CONTEXT *context )
2728 switch(interrupt)
2730 case 0x2d:
2731 context->Rip += 3;
2732 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2733 rec->ExceptionAddress = (void *)context->Rip;
2734 rec->NumberParameters = 1;
2735 rec->ExceptionInformation[0] = context->Rax;
2736 return TRUE;
2737 default:
2738 return FALSE;
2743 /**********************************************************************
2744 * segv_handler
2746 * Handler for SIGSEGV and related errors.
2748 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2750 EXCEPTION_RECORD *rec;
2751 ucontext_t *ucontext = sigcontext;
2753 /* check for page fault inside the thread stack */
2754 if (TRAP_sig(ucontext) == TRAP_x86_PAGEFLT &&
2755 (char *)siginfo->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
2756 (char *)siginfo->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
2757 virtual_handle_stack_fault( siginfo->si_addr ))
2759 /* check if this was the last guard page */
2760 if ((char *)siginfo->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
2762 rec = setup_exception( sigcontext, raise_segv_exception );
2763 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2765 return;
2768 rec = setup_exception( sigcontext, raise_segv_exception );
2769 if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
2771 switch(TRAP_sig(ucontext))
2773 case TRAP_x86_OFLOW: /* Overflow exception */
2774 rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2775 break;
2776 case TRAP_x86_BOUND: /* Bound range exception */
2777 rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2778 break;
2779 case TRAP_x86_PRIVINFLT: /* Invalid opcode exception */
2780 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2781 break;
2782 case TRAP_x86_STKFLT: /* Stack fault */
2783 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2784 break;
2785 case TRAP_x86_SEGNPFLT: /* Segment not present exception */
2786 case TRAP_x86_PROTFLT: /* General protection fault */
2787 case TRAP_x86_UNKNOWN: /* Unknown fault code */
2789 CONTEXT *win_context = get_exception_context( rec );
2790 WORD err = ERROR_sig(ucontext);
2791 if ((err & 7) == 2 && handle_interrupt( err >> 3, rec, win_context )) break;
2792 rec->ExceptionCode = err ? EXCEPTION_ACCESS_VIOLATION : EXCEPTION_PRIV_INSTRUCTION;
2793 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2795 break;
2796 case TRAP_x86_PAGEFLT: /* Page fault */
2797 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2798 rec->NumberParameters = 2;
2799 rec->ExceptionInformation[0] = (ERROR_sig(ucontext) & 2) != 0;
2800 rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2801 break;
2802 case TRAP_x86_ALIGNFLT: /* Alignment check exception */
2803 rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2804 break;
2805 default:
2806 ERR( "Got unexpected trap %ld\n", (ULONG_PTR)TRAP_sig(ucontext) );
2807 /* fall through */
2808 case TRAP_x86_NMI: /* NMI interrupt */
2809 case TRAP_x86_DNA: /* Device not available exception */
2810 case TRAP_x86_DOUBLEFLT: /* Double fault exception */
2811 case TRAP_x86_TSSFLT: /* Invalid TSS exception */
2812 case TRAP_x86_MCHK: /* Machine check exception */
2813 case TRAP_x86_CACHEFLT: /* Cache flush exception */
2814 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2815 break;
2819 /**********************************************************************
2820 * trap_handler
2822 * Handler for SIGTRAP.
2824 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2826 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_trap_exception );
2828 switch (siginfo->si_code)
2830 case TRAP_TRACE: /* Single-step exception */
2831 case 4 /* TRAP_HWBKPT */: /* Hardware breakpoint exception */
2832 rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
2833 break;
2834 case TRAP_BRKPT: /* Breakpoint exception */
2835 rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1; /* back up over the int3 instruction */
2836 /* fall through */
2837 default:
2838 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2839 rec->NumberParameters = 1;
2840 rec->ExceptionInformation[0] = 0;
2841 break;
2845 /**********************************************************************
2846 * fpe_handler
2848 * Handler for SIGFPE.
2850 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2852 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2854 switch (siginfo->si_code)
2856 case FPE_FLTSUB:
2857 rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2858 break;
2859 case FPE_INTDIV:
2860 rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2861 break;
2862 case FPE_INTOVF:
2863 rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2864 break;
2865 case FPE_FLTDIV:
2866 rec->ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO;
2867 break;
2868 case FPE_FLTOVF:
2869 rec->ExceptionCode = EXCEPTION_FLT_OVERFLOW;
2870 break;
2871 case FPE_FLTUND:
2872 rec->ExceptionCode = EXCEPTION_FLT_UNDERFLOW;
2873 break;
2874 case FPE_FLTRES:
2875 rec->ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT;
2876 break;
2877 case FPE_FLTINV:
2878 default:
2879 rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2880 break;
2884 /**********************************************************************
2885 * int_handler
2887 * Handler for SIGINT.
2889 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2891 if (!dispatch_signal(SIGINT))
2893 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2894 rec->ExceptionCode = CONTROL_C_EXIT;
2899 /**********************************************************************
2900 * abrt_handler
2902 * Handler for SIGABRT.
2904 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2906 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2907 rec->ExceptionCode = EXCEPTION_WINE_ASSERTION;
2908 rec->ExceptionFlags = EH_NONCONTINUABLE;
2912 /**********************************************************************
2913 * quit_handler
2915 * Handler for SIGQUIT.
2917 static void quit_handler( int signal, siginfo_t *siginfo, void *ucontext )
2919 abort_thread(0);
2923 /**********************************************************************
2924 * usr1_handler
2926 * Handler for SIGUSR1, used to signal a thread that it got suspended.
2928 static void usr1_handler( int signal, siginfo_t *siginfo, void *ucontext )
2930 CONTEXT context;
2932 save_context( &context, ucontext );
2933 wait_suspend( &context );
2934 restore_context( &context, ucontext );
2938 /***********************************************************************
2939 * __wine_set_signal_handler (NTDLL.@)
2941 int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
2943 if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
2944 if (handlers[sig] != NULL) return -2;
2945 handlers[sig] = wsh;
2946 return 0;
2950 /**********************************************************************
2951 * signal_alloc_thread
2953 NTSTATUS signal_alloc_thread( TEB **teb )
2955 static size_t sigstack_zero_bits;
2956 SIZE_T size;
2957 NTSTATUS status;
2959 if (!sigstack_zero_bits)
2961 size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2962 /* find the first power of two not smaller than min_size */
2963 sigstack_zero_bits = 12;
2964 while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
2965 signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
2966 assert( sizeof(TEB) <= teb_size );
2969 size = 1 << sigstack_zero_bits;
2970 *teb = NULL;
2971 if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)teb, sigstack_zero_bits,
2972 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
2974 (*teb)->Tib.Self = &(*teb)->Tib;
2975 (*teb)->Tib.ExceptionList = (void *)~0UL;
2977 return status;
2981 /**********************************************************************
2982 * signal_free_thread
2984 void signal_free_thread( TEB *teb )
2986 SIZE_T size;
2988 if (teb->DeallocationStack)
2990 size = 0;
2991 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
2993 size = 0;
2994 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2997 #ifdef __APPLE__
2998 /**********************************************************************
2999 * mac_thread_gsbase
3001 static void *mac_thread_gsbase(void)
3003 static int gsbase_offset = -1;
3004 void *ret;
3006 if (gsbase_offset < 0)
3008 /* Search for the array of TLS slots within the pthread data structure.
3009 That's what the macOS pthread implementation uses for gsbase. */
3010 const void* const sentinel1 = (const void*)0x2bffb6b4f11228ae;
3011 const void* const sentinel2 = (const void*)0x0845a7ff6ab76707;
3012 int rc;
3013 pthread_key_t key;
3014 const void** p = (const void**)pthread_self();
3015 int i;
3017 gsbase_offset = 0;
3018 if ((rc = pthread_key_create(&key, NULL)))
3020 ERR("failed to create sentinel key for gsbase search: %d\n", rc);
3021 return NULL;
3024 pthread_setspecific(key, sentinel1);
3026 for (i = key + 1; i < 2000; i++) /* arbitrary limit */
3028 if (p[i] == sentinel1)
3030 pthread_setspecific(key, sentinel2);
3032 if (p[i] == sentinel2)
3034 gsbase_offset = (i - key) * sizeof(*p);
3035 break;
3038 pthread_setspecific(key, sentinel1);
3042 pthread_key_delete(key);
3045 if (gsbase_offset)
3047 ret = (char*)pthread_self() + gsbase_offset;
3048 TRACE("pthread_self() %p + offset 0x%08x -> gsbase %p\n", pthread_self(), gsbase_offset, ret);
3050 else
3052 ret = NULL;
3053 ERR("failed to locate gsbase; won't be able to poke ThreadLocalStoragePointer into pthread TLS; expect crashes\n");
3056 return ret;
3058 #endif
3061 /***********************************************************************
3062 * start_process
3064 static void CDECL start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
3066 call_thread_entry_point( kernel32_start_process, entry );
3070 /**********************************************************************
3071 * signal_init_thread
3073 void signal_init_thread( TEB *teb )
3075 const WORD fpu_cw = 0x27f;
3076 stack_t ss;
3078 #if defined __linux__
3079 arch_prctl( ARCH_SET_GS, teb );
3080 #elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
3081 amd64_set_gsbase( teb );
3082 #elif defined(__NetBSD__)
3083 sysarch( X86_64_SET_GSBASE, &teb );
3084 #elif defined (__APPLE__)
3085 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
3087 : "r" (teb->Tib.Self), "n" (FIELD_OFFSET(TEB, Tib.Self)));
3088 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
3090 : "r" (teb->ThreadLocalStoragePointer), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
3092 /* alloc_tls_slot() needs to poke a value to an address relative to each
3093 thread's gsbase. Have each thread record its gsbase pointer into its
3094 TEB so alloc_tls_slot() can find it. */
3095 teb->Reserved5[0] = mac_thread_gsbase();
3096 #else
3097 # error Please define setting %gs for your architecture
3098 #endif
3100 ss.ss_sp = (char *)teb + teb_size;
3101 ss.ss_size = signal_stack_size;
3102 ss.ss_flags = 0;
3103 if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
3105 #ifdef __GNUC__
3106 __asm__ volatile ("fninit; fldcw %0" : : "m" (fpu_cw));
3107 #else
3108 FIXME("FPU setup not implemented for this platform.\n");
3109 #endif
3112 /**********************************************************************
3113 * signal_init_process
3115 void signal_init_process( CONTEXT *context, LPTHREAD_START_ROUTINE entry )
3117 struct sigaction sig_act;
3119 sig_act.sa_mask = server_block_set;
3120 sig_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
3122 sig_act.sa_sigaction = int_handler;
3123 if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
3124 sig_act.sa_sigaction = fpe_handler;
3125 if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
3126 sig_act.sa_sigaction = abrt_handler;
3127 if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
3128 sig_act.sa_sigaction = quit_handler;
3129 if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
3130 sig_act.sa_sigaction = usr1_handler;
3131 if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
3133 sig_act.sa_sigaction = segv_handler;
3134 if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
3135 if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
3136 #ifdef SIGBUS
3137 if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
3138 #endif
3140 #ifdef SIGTRAP
3141 sig_act.sa_sigaction = trap_handler;
3142 if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
3143 #endif
3145 /* build the initial context */
3146 context->ContextFlags = CONTEXT_FULL;
3147 __asm__( "movw %%cs,%0" : "=m" (context->SegCs) );
3148 __asm__( "movw %%ss,%0" : "=m" (context->SegSs) );
3149 __asm__( "fxsave %0" : "=m" (context->u.FltSave) );
3150 context->Rcx = (ULONG_PTR)entry;
3151 context->Rdx = (ULONG_PTR)NtCurrentTeb()->Peb;
3152 context->Rsp = (ULONG_PTR)NtCurrentTeb()->Tib.StackBase - 0x28;
3153 context->Rip = (ULONG_PTR)start_process;
3154 return;
3156 error:
3157 perror("sigaction");
3158 exit(1);
3162 /**********************************************************************
3163 * RtlAddFunctionTable (NTDLL.@)
3165 BOOLEAN CDECL RtlAddFunctionTable( RUNTIME_FUNCTION *table, DWORD count, DWORD64 addr )
3167 struct dynamic_unwind_entry *entry;
3169 TRACE( "%p %u %lx\n", table, count, addr );
3171 /* NOTE: Windows doesn't check if table is aligned or a NULL pointer */
3173 entry = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*entry) );
3174 if (!entry)
3175 return FALSE;
3177 entry->base = addr;
3178 entry->size = table[count - 1].EndAddress;
3179 entry->table = table;
3180 entry->table_size = count * sizeof(RUNTIME_FUNCTION);
3181 entry->callback = NULL;
3182 entry->context = NULL;
3184 RtlEnterCriticalSection( &dynamic_unwind_section );
3185 list_add_tail( &dynamic_unwind_list, &entry->entry );
3186 RtlLeaveCriticalSection( &dynamic_unwind_section );
3188 return TRUE;
3192 /**********************************************************************
3193 * RtlInstallFunctionTableCallback (NTDLL.@)
3195 BOOLEAN CDECL RtlInstallFunctionTableCallback( DWORD64 table, DWORD64 base, DWORD length,
3196 PGET_RUNTIME_FUNCTION_CALLBACK callback, PVOID context, PCWSTR dll )
3198 struct dynamic_unwind_entry *entry;
3200 TRACE( "%lx %lx %d %p %p %s\n", table, base, length, callback, context, wine_dbgstr_w(dll) );
3202 /* NOTE: Windows doesn't check if the provided callback is a NULL pointer */
3204 /* both low-order bits must be set */
3205 if ((table & 0x3) != 0x3)
3206 return FALSE;
3208 entry = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*entry) );
3209 if (!entry)
3210 return FALSE;
3212 entry->base = base;
3213 entry->size = length;
3214 entry->table = (RUNTIME_FUNCTION *)table;
3215 entry->table_size = 0;
3216 entry->callback = callback;
3217 entry->context = context;
3219 RtlEnterCriticalSection( &dynamic_unwind_section );
3220 list_add_tail( &dynamic_unwind_list, &entry->entry );
3221 RtlLeaveCriticalSection( &dynamic_unwind_section );
3223 return TRUE;
3227 /**********************************************************************
3228 * RtlDeleteFunctionTable (NTDLL.@)
3230 BOOLEAN CDECL RtlDeleteFunctionTable( RUNTIME_FUNCTION *table )
3232 struct dynamic_unwind_entry *entry, *to_free = NULL;
3234 TRACE( "%p\n", table );
3236 RtlEnterCriticalSection( &dynamic_unwind_section );
3237 LIST_FOR_EACH_ENTRY( entry, &dynamic_unwind_list, struct dynamic_unwind_entry, entry )
3239 if (entry->table == table)
3241 to_free = entry;
3242 list_remove( &entry->entry );
3243 break;
3246 RtlLeaveCriticalSection( &dynamic_unwind_section );
3248 if (!to_free)
3249 return FALSE;
3251 RtlFreeHeap( GetProcessHeap(), 0, to_free );
3252 return TRUE;
3256 /**********************************************************************
3257 * RtlLookupFunctionEntry (NTDLL.@)
3259 PRUNTIME_FUNCTION WINAPI RtlLookupFunctionEntry( ULONG64 pc, ULONG64 *base, UNWIND_HISTORY_TABLE *table )
3261 LDR_MODULE *module;
3262 RUNTIME_FUNCTION *func;
3264 /* FIXME: should use the history table to make things faster */
3266 func = lookup_function_info( pc, base, &module );
3267 if (!func)
3269 *base = 0;
3270 if (module)
3271 WARN( "no exception table found in module %p pc %lx\n", module->BaseAddress, pc );
3272 else
3273 WARN( "module not found for %lx\n", pc );
3276 return func;
3279 static ULONG64 get_int_reg( CONTEXT *context, int reg )
3281 return *(&context->Rax + reg);
3284 static void set_int_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, ULONG64 *val )
3286 *(&context->Rax + reg) = *val;
3287 if (ctx_ptr) ctx_ptr->u2.IntegerContext[reg] = val;
3290 static void set_float_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, M128A *val )
3292 *(&context->u.s.Xmm0 + reg) = *val;
3293 if (ctx_ptr) ctx_ptr->u.FloatingContext[reg] = val;
3296 static int get_opcode_size( struct opcode op )
3298 switch (op.code)
3300 case UWOP_ALLOC_LARGE:
3301 return 2 + (op.info != 0);
3302 case UWOP_SAVE_NONVOL:
3303 case UWOP_SAVE_XMM128:
3304 return 2;
3305 case UWOP_SAVE_NONVOL_FAR:
3306 case UWOP_SAVE_XMM128_FAR:
3307 return 3;
3308 default:
3309 return 1;
3313 static BOOL is_inside_epilog( BYTE *pc, ULONG64 base, const RUNTIME_FUNCTION *function )
3315 /* add or lea must be the first instruction, and it must have a rex.W prefix */
3316 if ((pc[0] & 0xf8) == 0x48)
3318 switch (pc[1])
3320 case 0x81: /* add $nnnn,%rsp */
3321 if (pc[0] == 0x48 && pc[2] == 0xc4)
3323 pc += 7;
3324 break;
3326 return FALSE;
3327 case 0x83: /* add $n,%rsp */
3328 if (pc[0] == 0x48 && pc[2] == 0xc4)
3330 pc += 4;
3331 break;
3333 return FALSE;
3334 case 0x8d: /* lea n(reg),%rsp */
3335 if (pc[0] & 0x06) return FALSE; /* rex.RX must be cleared */
3336 if (((pc[2] >> 3) & 7) != 4) return FALSE; /* dest reg mus be %rsp */
3337 if ((pc[2] & 7) == 4) return FALSE; /* no SIB byte allowed */
3338 if ((pc[2] >> 6) == 1) /* 8-bit offset */
3340 pc += 4;
3341 break;
3343 if ((pc[2] >> 6) == 2) /* 32-bit offset */
3345 pc += 7;
3346 break;
3348 return FALSE;
3352 /* now check for various pop instructions */
3354 for (;;)
3356 if ((*pc & 0xf0) == 0x40) pc++; /* rex prefix */
3358 switch (*pc)
3360 case 0x58: /* pop %rax/%r8 */
3361 case 0x59: /* pop %rcx/%r9 */
3362 case 0x5a: /* pop %rdx/%r10 */
3363 case 0x5b: /* pop %rbx/%r11 */
3364 case 0x5c: /* pop %rsp/%r12 */
3365 case 0x5d: /* pop %rbp/%r13 */
3366 case 0x5e: /* pop %rsi/%r14 */
3367 case 0x5f: /* pop %rdi/%r15 */
3368 pc++;
3369 continue;
3370 case 0xc2: /* ret $nn */
3371 case 0xc3: /* ret */
3372 return TRUE;
3373 case 0xe9: /* jmp nnnn */
3374 pc += 5 + *(LONG *)(pc + 1);
3375 if (pc - (BYTE *)base >= function->BeginAddress && pc - (BYTE *)base < function->EndAddress)
3376 continue;
3377 break;
3378 case 0xeb: /* jmp n */
3379 pc += 2 + (signed char)pc[1];
3380 if (pc - (BYTE *)base >= function->BeginAddress && pc - (BYTE *)base < function->EndAddress)
3381 continue;
3382 break;
3383 case 0xf3: /* rep; ret (for amd64 prediction bug) */
3384 return pc[1] == 0xc3;
3386 return FALSE;
3390 /* execute a function epilog, which must have been validated with is_inside_epilog() */
3391 static void interpret_epilog( BYTE *pc, CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
3393 for (;;)
3395 BYTE rex = 0;
3397 if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f; /* rex prefix */
3399 switch (*pc)
3401 case 0x58: /* pop %rax/r8 */
3402 case 0x59: /* pop %rcx/r9 */
3403 case 0x5a: /* pop %rdx/r10 */
3404 case 0x5b: /* pop %rbx/r11 */
3405 case 0x5c: /* pop %rsp/r12 */
3406 case 0x5d: /* pop %rbp/r13 */
3407 case 0x5e: /* pop %rsi/r14 */
3408 case 0x5f: /* pop %rdi/r15 */
3409 set_int_reg( context, ctx_ptr, *pc - 0x58 + (rex & 1) * 8, (ULONG64 *)context->Rsp );
3410 context->Rsp += sizeof(ULONG64);
3411 pc++;
3412 continue;
3413 case 0x81: /* add $nnnn,%rsp */
3414 context->Rsp += *(LONG *)(pc + 2);
3415 pc += 2 + sizeof(LONG);
3416 continue;
3417 case 0x83: /* add $n,%rsp */
3418 context->Rsp += (signed char)pc[2];
3419 pc += 3;
3420 continue;
3421 case 0x8d:
3422 if ((pc[1] >> 6) == 1) /* lea n(reg),%rsp */
3424 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + (signed char)pc[2];
3425 pc += 3;
3427 else /* lea nnnn(reg),%rsp */
3429 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + *(LONG *)(pc + 2);
3430 pc += 2 + sizeof(LONG);
3432 continue;
3433 case 0xc2: /* ret $nn */
3434 context->Rip = *(ULONG64 *)context->Rsp;
3435 context->Rsp += sizeof(ULONG64) + *(WORD *)(pc + 1);
3436 return;
3437 case 0xc3: /* ret */
3438 case 0xf3: /* rep; ret */
3439 context->Rip = *(ULONG64 *)context->Rsp;
3440 context->Rsp += sizeof(ULONG64);
3441 return;
3442 case 0xe9: /* jmp nnnn */
3443 pc += 5 + *(LONG *)(pc + 1);
3444 continue;
3445 case 0xeb: /* jmp n */
3446 pc += 2 + (signed char)pc[1];
3447 continue;
3449 return;
3453 /**********************************************************************
3454 * RtlVirtualUnwind (NTDLL.@)
3456 PVOID WINAPI RtlVirtualUnwind( ULONG type, ULONG64 base, ULONG64 pc,
3457 RUNTIME_FUNCTION *function, CONTEXT *context,
3458 PVOID *data, ULONG64 *frame_ret,
3459 KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
3461 union handler_data *handler_data;
3462 ULONG64 frame, off;
3463 struct UNWIND_INFO *info;
3464 unsigned int i, prolog_offset;
3466 TRACE( "type %x rip %lx rsp %lx\n", type, pc, context->Rsp );
3467 if (TRACE_ON(seh)) dump_unwind_info( base, function );
3469 frame = *frame_ret = context->Rsp;
3470 for (;;)
3472 info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
3473 handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
3475 if (info->version != 1)
3477 FIXME( "unknown unwind info version %u at %p\n", info->version, info );
3478 return NULL;
3481 if (info->frame_reg)
3482 frame = get_int_reg( context, info->frame_reg ) - info->frame_offset * 16;
3484 /* check if in prolog */
3485 if (pc >= base + function->BeginAddress && pc < base + function->BeginAddress + info->prolog)
3487 prolog_offset = pc - base - function->BeginAddress;
3489 else
3491 prolog_offset = ~0;
3492 if (is_inside_epilog( (BYTE *)pc, base, function ))
3494 interpret_epilog( (BYTE *)pc, context, ctx_ptr );
3495 *frame_ret = frame;
3496 return NULL;
3500 for (i = 0; i < info->count; i += get_opcode_size(info->opcodes[i]))
3502 if (prolog_offset < info->opcodes[i].offset) continue; /* skip it */
3504 switch (info->opcodes[i].code)
3506 case UWOP_PUSH_NONVOL: /* pushq %reg */
3507 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)context->Rsp );
3508 context->Rsp += sizeof(ULONG64);
3509 break;
3510 case UWOP_ALLOC_LARGE: /* subq $nn,%rsp */
3511 if (info->opcodes[i].info) context->Rsp += *(DWORD *)&info->opcodes[i+1];
3512 else context->Rsp += *(USHORT *)&info->opcodes[i+1] * 8;
3513 break;
3514 case UWOP_ALLOC_SMALL: /* subq $n,%rsp */
3515 context->Rsp += (info->opcodes[i].info + 1) * 8;
3516 break;
3517 case UWOP_SET_FPREG: /* leaq nn(%rsp),%framereg */
3518 context->Rsp = *frame_ret = frame;
3519 break;
3520 case UWOP_SAVE_NONVOL: /* movq %reg,n(%rsp) */
3521 off = frame + *(USHORT *)&info->opcodes[i+1] * 8;
3522 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)off );
3523 break;
3524 case UWOP_SAVE_NONVOL_FAR: /* movq %reg,nn(%rsp) */
3525 off = frame + *(DWORD *)&info->opcodes[i+1];
3526 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)off );
3527 break;
3528 case UWOP_SAVE_XMM128: /* movaps %xmmreg,n(%rsp) */
3529 off = frame + *(USHORT *)&info->opcodes[i+1] * 16;
3530 set_float_reg( context, ctx_ptr, info->opcodes[i].info, (M128A *)off );
3531 break;
3532 case UWOP_SAVE_XMM128_FAR: /* movaps %xmmreg,nn(%rsp) */
3533 off = frame + *(DWORD *)&info->opcodes[i+1];
3534 set_float_reg( context, ctx_ptr, info->opcodes[i].info, (M128A *)off );
3535 break;
3536 case UWOP_PUSH_MACHFRAME:
3537 FIXME( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
3538 break;
3539 default:
3540 FIXME( "unknown code %u\n", info->opcodes[i].code );
3541 break;
3545 if (!(info->flags & UNW_FLAG_CHAININFO)) break;
3546 function = &handler_data->chain; /* restart with the chained info */
3549 /* now pop return address */
3550 context->Rip = *(ULONG64 *)context->Rsp;
3551 context->Rsp += sizeof(ULONG64);
3553 if (!(info->flags & type)) return NULL; /* no matching handler */
3554 if (prolog_offset != ~0) return NULL; /* inside prolog */
3556 *data = &handler_data->handler + 1;
3557 return (char *)base + handler_data->handler;
3560 struct unwind_exception_frame
3562 EXCEPTION_REGISTRATION_RECORD frame;
3563 DISPATCHER_CONTEXT *dispatch;
3566 /**********************************************************************
3567 * unwind_exception_handler
3569 * Handler for exceptions happening while calling an unwind handler.
3571 static DWORD unwind_exception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
3572 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
3574 struct unwind_exception_frame *unwind_frame = (struct unwind_exception_frame *)frame;
3575 DISPATCHER_CONTEXT *dispatch = (DISPATCHER_CONTEXT *)dispatcher;
3577 /* copy the original dispatcher into the current one, except for the TargetIp */
3578 dispatch->ControlPc = unwind_frame->dispatch->ControlPc;
3579 dispatch->ImageBase = unwind_frame->dispatch->ImageBase;
3580 dispatch->FunctionEntry = unwind_frame->dispatch->FunctionEntry;
3581 dispatch->EstablisherFrame = unwind_frame->dispatch->EstablisherFrame;
3582 dispatch->ContextRecord = unwind_frame->dispatch->ContextRecord;
3583 dispatch->LanguageHandler = unwind_frame->dispatch->LanguageHandler;
3584 dispatch->HandlerData = unwind_frame->dispatch->HandlerData;
3585 dispatch->HistoryTable = unwind_frame->dispatch->HistoryTable;
3586 dispatch->ScopeIndex = unwind_frame->dispatch->ScopeIndex;
3587 TRACE( "detected collided unwind\n" );
3588 return ExceptionCollidedUnwind;
3591 /**********************************************************************
3592 * call_unwind_handler
3594 * Call a single unwind handler.
3596 static DWORD call_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch )
3598 struct unwind_exception_frame frame;
3599 DWORD res;
3601 frame.frame.Handler = unwind_exception_handler;
3602 frame.dispatch = dispatch;
3603 __wine_push_frame( &frame.frame );
3605 TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
3606 dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
3607 res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
3608 TRACE( "handler %p returned %x\n", dispatch->LanguageHandler, res );
3610 __wine_pop_frame( &frame.frame );
3612 switch (res)
3614 case ExceptionContinueSearch:
3615 case ExceptionCollidedUnwind:
3616 break;
3617 default:
3618 raise_status( STATUS_INVALID_DISPOSITION, rec );
3619 break;
3622 return res;
3626 /**********************************************************************
3627 * call_teb_unwind_handler
3629 * Call a single unwind handler from the TEB chain.
3631 static DWORD call_teb_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
3632 EXCEPTION_REGISTRATION_RECORD *teb_frame )
3634 DWORD res;
3636 TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatch=%p)\n",
3637 teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, dispatch );
3638 res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, (EXCEPTION_REGISTRATION_RECORD**)dispatch );
3639 TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
3641 switch (res)
3643 case ExceptionContinueSearch:
3644 case ExceptionCollidedUnwind:
3645 break;
3646 default:
3647 raise_status( STATUS_INVALID_DISPOSITION, rec );
3648 break;
3651 return res;
3655 /**********************************************************************
3656 * call_consolidate_callback
3658 * Wrapper function to call a consolidate callback from a fake frame.
3659 * If the callback executes RtlUnwindEx (like for example done in C++ handlers),
3660 * we have to skip all frames which were already processed. To do that we
3661 * trick the unwinding functions into thinking the call came from somewhere
3662 * else. All CFI instructions are either DW_CFA_def_cfa_expression or
3663 * DW_CFA_expression, and the expressions have the following format:
3665 * DW_OP_breg6; sleb128 0x10 | Load %rbp + 0x10
3666 * DW_OP_deref | Get *(%rbp + 0x10) == context
3667 * DW_OP_plus_uconst; uleb128 <OFFSET> | Add offset to get struct member
3668 * [DW_OP_deref] | Dereference, only for CFA
3670 extern void * WINAPI call_consolidate_callback( CONTEXT *context,
3671 void *(CALLBACK *callback)(EXCEPTION_RECORD *),
3672 EXCEPTION_RECORD *rec );
3673 __ASM_GLOBAL_FUNC( call_consolidate_callback,
3674 "pushq %rbp\n\t"
3675 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
3676 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
3677 "movq %rsp,%rbp\n\t"
3678 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
3679 "subq $0x20,%rsp\n\t"
3680 "movq %rcx,0x10(%rbp)\n\t"
3681 __ASM_CFI(".cfi_remember_state\n\t")
3682 __ASM_CFI(".cfi_escape 0x0f,0x07,0x76,0x10,0x06,0x23,0x98,0x01,0x06\n\t") /* CFA */
3683 __ASM_CFI(".cfi_escape 0x10,0x03,0x06,0x76,0x10,0x06,0x23,0x90,0x01\n\t") /* %rbx */
3684 __ASM_CFI(".cfi_escape 0x10,0x04,0x06,0x76,0x10,0x06,0x23,0xa8,0x01\n\t") /* %rsi */
3685 __ASM_CFI(".cfi_escape 0x10,0x05,0x06,0x76,0x10,0x06,0x23,0xb0,0x01\n\t") /* %rdi */
3686 __ASM_CFI(".cfi_escape 0x10,0x06,0x06,0x76,0x10,0x06,0x23,0xa0,0x01\n\t") /* %rbp */
3687 __ASM_CFI(".cfi_escape 0x10,0x0c,0x06,0x76,0x10,0x06,0x23,0xd8,0x01\n\t") /* %r12 */
3688 __ASM_CFI(".cfi_escape 0x10,0x0d,0x06,0x76,0x10,0x06,0x23,0xe0,0x01\n\t") /* %r13 */
3689 __ASM_CFI(".cfi_escape 0x10,0x0e,0x06,0x76,0x10,0x06,0x23,0xe8,0x01\n\t") /* %r14 */
3690 __ASM_CFI(".cfi_escape 0x10,0x0f,0x06,0x76,0x10,0x06,0x23,0xf0,0x01\n\t") /* %r15 */
3691 __ASM_CFI(".cfi_escape 0x10,0x10,0x06,0x76,0x10,0x06,0x23,0xf8,0x01\n\t") /* %rip */
3692 __ASM_CFI(".cfi_escape 0x10,0x17,0x06,0x76,0x10,0x06,0x23,0x80,0x04\n\t") /* %xmm6 */
3693 __ASM_CFI(".cfi_escape 0x10,0x18,0x06,0x76,0x10,0x06,0x23,0x90,0x04\n\t") /* %xmm7 */
3694 __ASM_CFI(".cfi_escape 0x10,0x19,0x06,0x76,0x10,0x06,0x23,0xa0,0x04\n\t") /* %xmm8 */
3695 __ASM_CFI(".cfi_escape 0x10,0x1a,0x06,0x76,0x10,0x06,0x23,0xb0,0x04\n\t") /* %xmm9 */
3696 __ASM_CFI(".cfi_escape 0x10,0x1b,0x06,0x76,0x10,0x06,0x23,0xc0,0x04\n\t") /* %xmm10 */
3697 __ASM_CFI(".cfi_escape 0x10,0x1c,0x06,0x76,0x10,0x06,0x23,0xd0,0x04\n\t") /* %xmm11 */
3698 __ASM_CFI(".cfi_escape 0x10,0x1d,0x06,0x76,0x10,0x06,0x23,0xe0,0x04\n\t") /* %xmm12 */
3699 __ASM_CFI(".cfi_escape 0x10,0x1e,0x06,0x76,0x10,0x06,0x23,0xf0,0x04\n\t") /* %xmm13 */
3700 __ASM_CFI(".cfi_escape 0x10,0x1f,0x06,0x76,0x10,0x06,0x23,0x80,0x05\n\t") /* %xmm14 */
3701 __ASM_CFI(".cfi_escape 0x10,0x20,0x06,0x76,0x10,0x06,0x23,0x90,0x05\n\t") /* %xmm15 */
3702 "movq %r8,%rcx\n\t"
3703 "callq *%rdx\n\t"
3704 __ASM_CFI(".cfi_restore_state\n\t")
3705 "movq %rbp,%rsp\n\t"
3706 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
3707 "popq %rbp\n\t"
3708 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
3709 __ASM_CFI(".cfi_same_value %rbp\n\t")
3710 "ret")
3712 /*******************************************************************
3713 * RtlRestoreContext (NTDLL.@)
3715 void WINAPI RtlRestoreContext( CONTEXT *context, EXCEPTION_RECORD *rec )
3717 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
3719 if (rec && rec->ExceptionCode == STATUS_LONGJUMP && rec->NumberParameters >= 1)
3721 struct MSVCRT_JUMP_BUFFER *jmp = (struct MSVCRT_JUMP_BUFFER *)rec->ExceptionInformation[0];
3722 context->Rbx = jmp->Rbx;
3723 context->Rsp = jmp->Rsp;
3724 context->Rbp = jmp->Rbp;
3725 context->Rsi = jmp->Rsi;
3726 context->Rdi = jmp->Rdi;
3727 context->R12 = jmp->R12;
3728 context->R13 = jmp->R13;
3729 context->R14 = jmp->R14;
3730 context->R15 = jmp->R15;
3731 context->Rip = jmp->Rip;
3732 context->u.s.Xmm6 = jmp->Xmm6;
3733 context->u.s.Xmm7 = jmp->Xmm7;
3734 context->u.s.Xmm8 = jmp->Xmm8;
3735 context->u.s.Xmm9 = jmp->Xmm9;
3736 context->u.s.Xmm10 = jmp->Xmm10;
3737 context->u.s.Xmm11 = jmp->Xmm11;
3738 context->u.s.Xmm12 = jmp->Xmm12;
3739 context->u.s.Xmm13 = jmp->Xmm13;
3740 context->u.s.Xmm14 = jmp->Xmm14;
3741 context->u.s.Xmm15 = jmp->Xmm15;
3743 else if (rec && rec->ExceptionCode == STATUS_UNWIND_CONSOLIDATE && rec->NumberParameters >= 1)
3745 PVOID (CALLBACK *consolidate)(EXCEPTION_RECORD *) = (void *)rec->ExceptionInformation[0];
3746 TRACE( "calling consolidate callback %p (rec=%p)\n", consolidate, rec );
3747 context->Rip = (ULONG64)call_consolidate_callback( context, consolidate, rec );
3750 /* hack: remove no longer accessible TEB frames */
3751 while ((ULONG64)teb_frame < context->Rsp)
3753 TRACE( "removing TEB frame: %p\n", teb_frame );
3754 teb_frame = __wine_pop_frame( teb_frame );
3757 TRACE( "returning to %lx stack %lx\n", context->Rip, context->Rsp );
3758 set_cpu_context( context );
3762 /*******************************************************************
3763 * RtlUnwindEx (NTDLL.@)
3765 void WINAPI RtlUnwindEx( PVOID end_frame, PVOID target_ip, EXCEPTION_RECORD *rec,
3766 PVOID retval, CONTEXT *context, UNWIND_HISTORY_TABLE *table )
3768 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
3769 EXCEPTION_RECORD record;
3770 DISPATCHER_CONTEXT dispatch;
3771 CONTEXT new_context;
3772 LDR_MODULE *module;
3773 NTSTATUS status;
3774 DWORD i;
3776 RtlCaptureContext( context );
3777 new_context = *context;
3779 /* build an exception record, if we do not have one */
3780 if (!rec)
3782 record.ExceptionCode = STATUS_UNWIND;
3783 record.ExceptionFlags = 0;
3784 record.ExceptionRecord = NULL;
3785 record.ExceptionAddress = (void *)context->Rip;
3786 record.NumberParameters = 0;
3787 rec = &record;
3790 rec->ExceptionFlags |= EH_UNWINDING | (end_frame ? 0 : EH_EXIT_UNWIND);
3792 TRACE( "code=%x flags=%x end_frame=%p target_ip=%p rip=%016lx\n",
3793 rec->ExceptionCode, rec->ExceptionFlags, end_frame, target_ip, context->Rip );
3794 for (i = 0; i < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); i++)
3795 TRACE( " info[%d]=%016lx\n", i, rec->ExceptionInformation[i] );
3796 TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
3797 context->Rax, context->Rbx, context->Rcx, context->Rdx );
3798 TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
3799 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
3800 TRACE(" r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
3801 context->R8, context->R9, context->R10, context->R11 );
3802 TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
3803 context->R12, context->R13, context->R14, context->R15 );
3805 dispatch.EstablisherFrame = context->Rsp;
3806 dispatch.TargetIp = (ULONG64)target_ip;
3807 dispatch.ContextRecord = context;
3808 dispatch.HistoryTable = table;
3810 for (;;)
3812 /* FIXME: should use the history table to make things faster */
3814 dispatch.ImageBase = 0;
3815 dispatch.ScopeIndex = 0;
3816 dispatch.ControlPc = context->Rip;
3818 /* first look for PE exception information */
3820 if ((dispatch.FunctionEntry = lookup_function_info( context->Rip, &dispatch.ImageBase, &module )))
3822 dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_UHANDLER, dispatch.ImageBase,
3823 context->Rip, dispatch.FunctionEntry,
3824 &new_context, &dispatch.HandlerData,
3825 &dispatch.EstablisherFrame, NULL );
3826 goto unwind_done;
3829 /* then look for host system exception information */
3831 if (!module || (module->Flags & LDR_WINE_INTERNAL))
3833 BOOL got_info = FALSE;
3834 struct dwarf_eh_bases bases;
3835 const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context->Rip - 1), &bases );
3837 if (fde)
3839 status = dwarf_virtual_unwind( context->Rip, &dispatch.EstablisherFrame, &new_context, fde,
3840 &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
3841 if (status != STATUS_SUCCESS) raise_status( status, rec );
3842 got_info = TRUE;
3844 #ifdef HAVE_LIBUNWIND_H
3845 else
3847 status = libunwind_virtual_unwind( context->Rip, &got_info, &dispatch.EstablisherFrame, &new_context,
3848 &dispatch.LanguageHandler, &dispatch.HandlerData );
3849 if (status != STATUS_SUCCESS) raise_status( status, rec );
3851 #endif
3853 if (got_info)
3855 dispatch.FunctionEntry = NULL;
3856 if (dispatch.LanguageHandler && !module)
3858 FIXME( "calling personality routine in system library not supported yet\n" );
3859 dispatch.LanguageHandler = NULL;
3861 goto unwind_done;
3864 else WARN( "exception data not found in %s\n", debugstr_w(module->BaseDllName.Buffer) );
3866 /* no exception information, treat as a leaf function */
3868 new_context.Rip = *(ULONG64 *)context->Rsp;
3869 new_context.Rsp = context->Rsp + sizeof(ULONG64);
3870 dispatch.EstablisherFrame = new_context.Rsp;
3871 dispatch.LanguageHandler = NULL;
3873 unwind_done:
3874 if (!dispatch.EstablisherFrame) break;
3876 if (is_inside_signal_stack( (void *)dispatch.EstablisherFrame ))
3878 TRACE( "frame %lx is inside signal stack (%p-%p)\n", dispatch.EstablisherFrame,
3879 get_signal_stack(), (char *)get_signal_stack() + signal_stack_size );
3880 *context = new_context;
3881 continue;
3884 if ((dispatch.EstablisherFrame & 7) ||
3885 dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
3886 dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
3888 ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
3889 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
3890 rec->ExceptionFlags |= EH_STACK_INVALID;
3891 break;
3894 if (dispatch.LanguageHandler)
3896 if (end_frame && (dispatch.EstablisherFrame > (ULONG64)end_frame))
3898 ERR( "invalid end frame %lx/%p\n", dispatch.EstablisherFrame, end_frame );
3899 raise_status( STATUS_INVALID_UNWIND_TARGET, rec );
3901 if (dispatch.EstablisherFrame == (ULONG64)end_frame) rec->ExceptionFlags |= EH_TARGET_UNWIND;
3902 if (call_unwind_handler( rec, &dispatch ) == ExceptionCollidedUnwind)
3904 ULONG64 frame;
3906 *context = new_context = *dispatch.ContextRecord;
3907 dispatch.ContextRecord = context;
3908 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
3909 dispatch.ControlPc, dispatch.FunctionEntry,
3910 &new_context, NULL, &frame, NULL );
3911 rec->ExceptionFlags |= EH_COLLIDED_UNWIND;
3912 goto unwind_done;
3914 rec->ExceptionFlags &= ~EH_COLLIDED_UNWIND;
3916 else /* hack: call builtin handlers registered in the tib list */
3918 DWORD64 backup_frame = dispatch.EstablisherFrame;
3919 while ((ULONG64)teb_frame < new_context.Rsp && (ULONG64)teb_frame < (ULONG64)end_frame)
3921 TRACE( "found builtin frame %p handler %p\n", teb_frame, teb_frame->Handler );
3922 dispatch.EstablisherFrame = (ULONG64)teb_frame;
3923 if (call_teb_unwind_handler( rec, &dispatch, teb_frame ) == ExceptionCollidedUnwind)
3925 ULONG64 frame;
3927 teb_frame = __wine_pop_frame( teb_frame );
3929 *context = new_context = *dispatch.ContextRecord;
3930 dispatch.ContextRecord = context;
3931 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
3932 dispatch.ControlPc, dispatch.FunctionEntry,
3933 &new_context, NULL, &frame, NULL );
3934 rec->ExceptionFlags |= EH_COLLIDED_UNWIND;
3935 goto unwind_done;
3937 teb_frame = __wine_pop_frame( teb_frame );
3939 if ((ULONG64)teb_frame == (ULONG64)end_frame && (ULONG64)end_frame < new_context.Rsp) break;
3940 dispatch.EstablisherFrame = backup_frame;
3943 if (dispatch.EstablisherFrame == (ULONG64)end_frame) break;
3944 *context = new_context;
3947 context->Rax = (ULONG64)retval;
3948 context->Rip = (ULONG64)target_ip;
3949 RtlRestoreContext(context, rec);
3953 /*******************************************************************
3954 * RtlUnwind (NTDLL.@)
3956 void WINAPI RtlUnwind( void *frame, void *target_ip, EXCEPTION_RECORD *rec, void *retval )
3958 CONTEXT context;
3959 RtlUnwindEx( frame, target_ip, rec, retval, &context, NULL );
3963 /*******************************************************************
3964 * _local_unwind (NTDLL.@)
3966 void WINAPI _local_unwind( void *frame, void *target_ip )
3968 CONTEXT context;
3969 RtlUnwindEx( frame, target_ip, NULL, NULL, &context, NULL );
3972 /*******************************************************************
3973 * __C_specific_handler (NTDLL.@)
3975 EXCEPTION_DISPOSITION WINAPI __C_specific_handler( EXCEPTION_RECORD *rec,
3976 ULONG64 frame,
3977 CONTEXT *context,
3978 struct _DISPATCHER_CONTEXT *dispatch )
3980 SCOPE_TABLE *table = dispatch->HandlerData;
3981 ULONG i;
3983 TRACE( "%p %lx %p %p\n", rec, frame, context, dispatch );
3984 if (TRACE_ON(seh)) dump_scope_table( dispatch->ImageBase, table );
3986 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
3988 for (i = dispatch->ScopeIndex; i < table->Count; i++)
3990 if (dispatch->ControlPc >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
3991 dispatch->ControlPc < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
3993 TERMINATION_HANDLER handler;
3995 if (table->ScopeRecord[i].JumpTarget) continue;
3997 if (rec->ExceptionFlags & EH_TARGET_UNWIND &&
3998 dispatch->TargetIp >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
3999 dispatch->TargetIp < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
4001 break;
4004 handler = (TERMINATION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
4005 dispatch->ScopeIndex = i+1;
4007 TRACE( "calling __finally %p frame %lx\n", handler, frame );
4008 handler( 1, frame );
4011 return ExceptionContinueSearch;
4014 for (i = dispatch->ScopeIndex; i < table->Count; i++)
4016 if (dispatch->ControlPc >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
4017 dispatch->ControlPc < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
4019 if (!table->ScopeRecord[i].JumpTarget) continue;
4020 if (table->ScopeRecord[i].HandlerAddress != EXCEPTION_EXECUTE_HANDLER)
4022 EXCEPTION_POINTERS ptrs;
4023 PC_LANGUAGE_EXCEPTION_HANDLER filter;
4025 filter = (PC_LANGUAGE_EXCEPTION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
4026 ptrs.ExceptionRecord = rec;
4027 ptrs.ContextRecord = context;
4028 TRACE( "calling filter %p ptrs %p frame %lx\n", filter, &ptrs, frame );
4029 switch (filter( &ptrs, frame ))
4031 case EXCEPTION_EXECUTE_HANDLER:
4032 break;
4033 case EXCEPTION_CONTINUE_SEARCH:
4034 continue;
4035 case EXCEPTION_CONTINUE_EXECUTION:
4036 return ExceptionContinueExecution;
4039 TRACE( "unwinding to target %lx\n", dispatch->ImageBase + table->ScopeRecord[i].JumpTarget );
4040 RtlUnwindEx( (void *)frame, (char *)dispatch->ImageBase + table->ScopeRecord[i].JumpTarget,
4041 rec, 0, dispatch->ContextRecord, dispatch->HistoryTable );
4044 return ExceptionContinueSearch;
4048 /***********************************************************************
4049 * RtlRaiseException (NTDLL.@)
4051 __ASM_GLOBAL_FUNC( RtlRaiseException,
4052 "movq %rcx,8(%rsp)\n\t"
4053 "sub $0x4f8,%rsp\n\t"
4054 __ASM_CFI(".cfi_adjust_cfa_offset 0x4f8\n\t")
4055 "leaq 0x20(%rsp),%rcx\n\t"
4056 "call " __ASM_NAME("RtlCaptureContext") "\n\t"
4057 "leaq 0x20(%rsp),%rdx\n\t" /* context pointer */
4058 "leaq 0x500(%rsp),%rax\n\t" /* orig stack pointer */
4059 "movq %rax,0x98(%rdx)\n\t" /* context->Rsp */
4060 "movq (%rax),%rcx\n\t" /* original first parameter */
4061 "movq %rcx,0x80(%rdx)\n\t" /* context->Rcx */
4062 "movq 0x4f8(%rsp),%rax\n\t" /* return address */
4063 "movq %rax,0xf8(%rdx)\n\t" /* context->Rip */
4064 "movq %rax,0x10(%rcx)\n\t" /* rec->ExceptionAddress */
4065 "movl $1,%r8d\n\t"
4066 "call " __ASM_NAME("NtRaiseException") "\n\t"
4067 "movq %rax,%rcx\n\t"
4068 "call " __ASM_NAME("RtlRaiseStatus") /* does not return */ );
4071 /*************************************************************************
4072 * RtlCaptureStackBackTrace (NTDLL.@)
4074 USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
4076 FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash );
4077 return 0;
4081 /***********************************************************************
4082 * call_thread_func
4084 void DECLSPEC_HIDDEN call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
4086 amd64_thread_data()->exit_frame = frame;
4087 __TRY
4089 RtlExitUserThread( entry( arg ));
4091 __EXCEPT(unhandled_exception_filter)
4093 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
4095 __ENDTRY
4096 abort(); /* should not be reached */
4099 extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
4100 __ASM_GLOBAL_FUNC( call_thread_entry_point,
4101 "subq $56,%rsp\n\t"
4102 __ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
4103 "movq %rbp,48(%rsp)\n\t"
4104 __ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
4105 "movq %rbx,40(%rsp)\n\t"
4106 __ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
4107 "movq %r12,32(%rsp)\n\t"
4108 __ASM_CFI(".cfi_rel_offset %r12,32\n\t")
4109 "movq %r13,24(%rsp)\n\t"
4110 __ASM_CFI(".cfi_rel_offset %r13,24\n\t")
4111 "movq %r14,16(%rsp)\n\t"
4112 __ASM_CFI(".cfi_rel_offset %r14,16\n\t")
4113 "movq %r15,8(%rsp)\n\t"
4114 __ASM_CFI(".cfi_rel_offset %r15,8\n\t")
4115 "movq %rsp,%rdx\n\t"
4116 "call " __ASM_NAME("call_thread_func") );
4118 extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
4119 __ASM_GLOBAL_FUNC( call_thread_exit_func,
4120 "movq %rdx,%rsp\n\t"
4121 __ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
4122 __ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
4123 __ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
4124 __ASM_CFI(".cfi_rel_offset %r12,32\n\t")
4125 __ASM_CFI(".cfi_rel_offset %r13,24\n\t")
4126 __ASM_CFI(".cfi_rel_offset %r14,16\n\t")
4127 __ASM_CFI(".cfi_rel_offset %r15,8\n\t")
4128 "call *%rsi" );
4130 /***********************************************************************
4131 * RtlExitUserThread (NTDLL.@)
4133 void WINAPI RtlExitUserThread( ULONG status )
4135 if (!amd64_thread_data()->exit_frame) exit_thread( status );
4136 call_thread_exit_func( status, exit_thread, amd64_thread_data()->exit_frame );
4139 /***********************************************************************
4140 * abort_thread
4142 void abort_thread( int status )
4144 if (!amd64_thread_data()->exit_frame) terminate_thread( status );
4145 call_thread_exit_func( status, terminate_thread, amd64_thread_data()->exit_frame );
4148 /**********************************************************************
4149 * __wine_enter_vm86 (NTDLL.@)
4151 void __wine_enter_vm86( CONTEXT *context )
4153 MESSAGE("vm86 mode not supported on this platform\n");
4156 /**********************************************************************
4157 * DbgBreakPoint (NTDLL.@)
4159 __ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
4161 /**********************************************************************
4162 * DbgUserBreakPoint (NTDLL.@)
4164 __ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
4166 #endif /* __x86_64__ */