ntdll: Move the plaform-specific thread data to the SystemReserved2 TEB field.
[wine.git] / dlls / ntdll / signal_x86_64.c
blobf0127f77caf9b979870170aeed76b6e0d37560e7
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 void *exit_frame; /* exit frame pointer */
316 C_ASSERT( sizeof(struct amd64_thread_data) <= sizeof(((TEB *)0)->SystemReserved2) );
318 static inline struct amd64_thread_data *amd64_thread_data(void)
320 return (struct amd64_thread_data *)NtCurrentTeb()->SystemReserved2;
323 /***********************************************************************
324 * Dynamic unwind table
327 struct dynamic_unwind_entry
329 struct list entry;
331 /* memory region which matches this entry */
332 DWORD64 base;
333 DWORD size;
335 /* lookup table */
336 RUNTIME_FUNCTION *table;
337 DWORD table_size;
339 /* user defined callback */
340 PGET_RUNTIME_FUNCTION_CALLBACK callback;
341 PVOID context;
344 static struct list dynamic_unwind_list = LIST_INIT(dynamic_unwind_list);
346 static RTL_CRITICAL_SECTION dynamic_unwind_section;
347 static RTL_CRITICAL_SECTION_DEBUG dynamic_unwind_debug =
349 0, 0, &dynamic_unwind_section,
350 { &dynamic_unwind_debug.ProcessLocksList, &dynamic_unwind_debug.ProcessLocksList },
351 0, 0, { (DWORD_PTR)(__FILE__ ": dynamic_unwind_section") }
353 static RTL_CRITICAL_SECTION dynamic_unwind_section = { &dynamic_unwind_debug, -1, 0, 0, 0, 0 };
355 /***********************************************************************
356 * Definitions for Win32 unwind tables
359 union handler_data
361 RUNTIME_FUNCTION chain;
362 ULONG handler;
365 struct opcode
367 BYTE offset;
368 BYTE code : 4;
369 BYTE info : 4;
372 struct UNWIND_INFO
374 BYTE version : 3;
375 BYTE flags : 5;
376 BYTE prolog;
377 BYTE count;
378 BYTE frame_reg : 4;
379 BYTE frame_offset : 4;
380 struct opcode opcodes[1]; /* info->count entries */
381 /* followed by handler_data */
384 #define UWOP_PUSH_NONVOL 0
385 #define UWOP_ALLOC_LARGE 1
386 #define UWOP_ALLOC_SMALL 2
387 #define UWOP_SET_FPREG 3
388 #define UWOP_SAVE_NONVOL 4
389 #define UWOP_SAVE_NONVOL_FAR 5
390 #define UWOP_SAVE_XMM128 8
391 #define UWOP_SAVE_XMM128_FAR 9
392 #define UWOP_PUSH_MACHFRAME 10
394 static void dump_unwind_info( ULONG64 base, RUNTIME_FUNCTION *function )
396 static const char * const reg_names[16] =
397 { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
398 "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
400 union handler_data *handler_data;
401 struct UNWIND_INFO *info;
402 unsigned int i, count;
404 TRACE( "**** func %x-%x\n", function->BeginAddress, function->EndAddress );
405 for (;;)
407 if (function->UnwindData & 1)
409 RUNTIME_FUNCTION *next = (RUNTIME_FUNCTION *)((char *)base + (function->UnwindData & ~1));
410 TRACE( "unwind info for function %p-%p chained to function %p-%p\n",
411 (char *)base + function->BeginAddress, (char *)base + function->EndAddress,
412 (char *)base + next->BeginAddress, (char *)base + next->EndAddress );
413 function = next;
414 continue;
416 info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
418 TRACE( "unwind info at %p flags %x prolog 0x%x bytes function %p-%p\n",
419 info, info->flags, info->prolog,
420 (char *)base + function->BeginAddress, (char *)base + function->EndAddress );
422 if (info->frame_reg)
423 TRACE( " frame register %s offset 0x%x(%%rsp)\n",
424 reg_names[info->frame_reg], info->frame_offset * 16 );
426 for (i = 0; i < info->count; i++)
428 TRACE( " 0x%x: ", info->opcodes[i].offset );
429 switch (info->opcodes[i].code)
431 case UWOP_PUSH_NONVOL:
432 TRACE( "pushq %%%s\n", reg_names[info->opcodes[i].info] );
433 break;
434 case UWOP_ALLOC_LARGE:
435 if (info->opcodes[i].info)
437 count = *(DWORD *)&info->opcodes[i+1];
438 i += 2;
440 else
442 count = *(USHORT *)&info->opcodes[i+1] * 8;
443 i++;
445 TRACE( "subq $0x%x,%%rsp\n", count );
446 break;
447 case UWOP_ALLOC_SMALL:
448 count = (info->opcodes[i].info + 1) * 8;
449 TRACE( "subq $0x%x,%%rsp\n", count );
450 break;
451 case UWOP_SET_FPREG:
452 TRACE( "leaq 0x%x(%%rsp),%s\n",
453 info->frame_offset * 16, reg_names[info->frame_reg] );
454 break;
455 case UWOP_SAVE_NONVOL:
456 count = *(USHORT *)&info->opcodes[i+1] * 8;
457 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
458 i++;
459 break;
460 case UWOP_SAVE_NONVOL_FAR:
461 count = *(DWORD *)&info->opcodes[i+1];
462 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
463 i += 2;
464 break;
465 case UWOP_SAVE_XMM128:
466 count = *(USHORT *)&info->opcodes[i+1] * 16;
467 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
468 i++;
469 break;
470 case UWOP_SAVE_XMM128_FAR:
471 count = *(DWORD *)&info->opcodes[i+1];
472 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
473 i += 2;
474 break;
475 case UWOP_PUSH_MACHFRAME:
476 TRACE( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
477 break;
478 default:
479 FIXME( "unknown code %u\n", info->opcodes[i].code );
480 break;
484 handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
485 if (info->flags & UNW_FLAG_CHAININFO)
487 TRACE( " chained to function %p-%p\n",
488 (char *)base + handler_data->chain.BeginAddress,
489 (char *)base + handler_data->chain.EndAddress );
490 function = &handler_data->chain;
491 continue;
493 if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
494 TRACE( " handler %p data at %p\n",
495 (char *)base + handler_data->handler, &handler_data->handler + 1 );
496 break;
500 static void dump_scope_table( ULONG64 base, const SCOPE_TABLE *table )
502 unsigned int i;
504 TRACE( "scope table at %p\n", table );
505 for (i = 0; i < table->Count; i++)
506 TRACE( " %u: %lx-%lx handler %lx target %lx\n", i,
507 base + table->ScopeRecord[i].BeginAddress,
508 base + table->ScopeRecord[i].EndAddress,
509 base + table->ScopeRecord[i].HandlerAddress,
510 base + table->ScopeRecord[i].JumpTarget );
514 /***********************************************************************
515 * Definitions for Dwarf unwind tables
518 enum dwarf_call_frame_info
520 DW_CFA_advance_loc = 0x40,
521 DW_CFA_offset = 0x80,
522 DW_CFA_restore = 0xc0,
523 DW_CFA_nop = 0x00,
524 DW_CFA_set_loc = 0x01,
525 DW_CFA_advance_loc1 = 0x02,
526 DW_CFA_advance_loc2 = 0x03,
527 DW_CFA_advance_loc4 = 0x04,
528 DW_CFA_offset_extended = 0x05,
529 DW_CFA_restore_extended = 0x06,
530 DW_CFA_undefined = 0x07,
531 DW_CFA_same_value = 0x08,
532 DW_CFA_register = 0x09,
533 DW_CFA_remember_state = 0x0a,
534 DW_CFA_restore_state = 0x0b,
535 DW_CFA_def_cfa = 0x0c,
536 DW_CFA_def_cfa_register = 0x0d,
537 DW_CFA_def_cfa_offset = 0x0e,
538 DW_CFA_def_cfa_expression = 0x0f,
539 DW_CFA_expression = 0x10,
540 DW_CFA_offset_extended_sf = 0x11,
541 DW_CFA_def_cfa_sf = 0x12,
542 DW_CFA_def_cfa_offset_sf = 0x13,
543 DW_CFA_val_offset = 0x14,
544 DW_CFA_val_offset_sf = 0x15,
545 DW_CFA_val_expression = 0x16,
548 enum dwarf_operation
550 DW_OP_addr = 0x03,
551 DW_OP_deref = 0x06,
552 DW_OP_const1u = 0x08,
553 DW_OP_const1s = 0x09,
554 DW_OP_const2u = 0x0a,
555 DW_OP_const2s = 0x0b,
556 DW_OP_const4u = 0x0c,
557 DW_OP_const4s = 0x0d,
558 DW_OP_const8u = 0x0e,
559 DW_OP_const8s = 0x0f,
560 DW_OP_constu = 0x10,
561 DW_OP_consts = 0x11,
562 DW_OP_dup = 0x12,
563 DW_OP_drop = 0x13,
564 DW_OP_over = 0x14,
565 DW_OP_pick = 0x15,
566 DW_OP_swap = 0x16,
567 DW_OP_rot = 0x17,
568 DW_OP_xderef = 0x18,
569 DW_OP_abs = 0x19,
570 DW_OP_and = 0x1a,
571 DW_OP_div = 0x1b,
572 DW_OP_minus = 0x1c,
573 DW_OP_mod = 0x1d,
574 DW_OP_mul = 0x1e,
575 DW_OP_neg = 0x1f,
576 DW_OP_not = 0x20,
577 DW_OP_or = 0x21,
578 DW_OP_plus = 0x22,
579 DW_OP_plus_uconst = 0x23,
580 DW_OP_shl = 0x24,
581 DW_OP_shr = 0x25,
582 DW_OP_shra = 0x26,
583 DW_OP_xor = 0x27,
584 DW_OP_bra = 0x28,
585 DW_OP_eq = 0x29,
586 DW_OP_ge = 0x2a,
587 DW_OP_gt = 0x2b,
588 DW_OP_le = 0x2c,
589 DW_OP_lt = 0x2d,
590 DW_OP_ne = 0x2e,
591 DW_OP_skip = 0x2f,
592 DW_OP_lit0 = 0x30,
593 DW_OP_lit1 = 0x31,
594 DW_OP_lit2 = 0x32,
595 DW_OP_lit3 = 0x33,
596 DW_OP_lit4 = 0x34,
597 DW_OP_lit5 = 0x35,
598 DW_OP_lit6 = 0x36,
599 DW_OP_lit7 = 0x37,
600 DW_OP_lit8 = 0x38,
601 DW_OP_lit9 = 0x39,
602 DW_OP_lit10 = 0x3a,
603 DW_OP_lit11 = 0x3b,
604 DW_OP_lit12 = 0x3c,
605 DW_OP_lit13 = 0x3d,
606 DW_OP_lit14 = 0x3e,
607 DW_OP_lit15 = 0x3f,
608 DW_OP_lit16 = 0x40,
609 DW_OP_lit17 = 0x41,
610 DW_OP_lit18 = 0x42,
611 DW_OP_lit19 = 0x43,
612 DW_OP_lit20 = 0x44,
613 DW_OP_lit21 = 0x45,
614 DW_OP_lit22 = 0x46,
615 DW_OP_lit23 = 0x47,
616 DW_OP_lit24 = 0x48,
617 DW_OP_lit25 = 0x49,
618 DW_OP_lit26 = 0x4a,
619 DW_OP_lit27 = 0x4b,
620 DW_OP_lit28 = 0x4c,
621 DW_OP_lit29 = 0x4d,
622 DW_OP_lit30 = 0x4e,
623 DW_OP_lit31 = 0x4f,
624 DW_OP_reg0 = 0x50,
625 DW_OP_reg1 = 0x51,
626 DW_OP_reg2 = 0x52,
627 DW_OP_reg3 = 0x53,
628 DW_OP_reg4 = 0x54,
629 DW_OP_reg5 = 0x55,
630 DW_OP_reg6 = 0x56,
631 DW_OP_reg7 = 0x57,
632 DW_OP_reg8 = 0x58,
633 DW_OP_reg9 = 0x59,
634 DW_OP_reg10 = 0x5a,
635 DW_OP_reg11 = 0x5b,
636 DW_OP_reg12 = 0x5c,
637 DW_OP_reg13 = 0x5d,
638 DW_OP_reg14 = 0x5e,
639 DW_OP_reg15 = 0x5f,
640 DW_OP_reg16 = 0x60,
641 DW_OP_reg17 = 0x61,
642 DW_OP_reg18 = 0x62,
643 DW_OP_reg19 = 0x63,
644 DW_OP_reg20 = 0x64,
645 DW_OP_reg21 = 0x65,
646 DW_OP_reg22 = 0x66,
647 DW_OP_reg23 = 0x67,
648 DW_OP_reg24 = 0x68,
649 DW_OP_reg25 = 0x69,
650 DW_OP_reg26 = 0x6a,
651 DW_OP_reg27 = 0x6b,
652 DW_OP_reg28 = 0x6c,
653 DW_OP_reg29 = 0x6d,
654 DW_OP_reg30 = 0x6e,
655 DW_OP_reg31 = 0x6f,
656 DW_OP_breg0 = 0x70,
657 DW_OP_breg1 = 0x71,
658 DW_OP_breg2 = 0x72,
659 DW_OP_breg3 = 0x73,
660 DW_OP_breg4 = 0x74,
661 DW_OP_breg5 = 0x75,
662 DW_OP_breg6 = 0x76,
663 DW_OP_breg7 = 0x77,
664 DW_OP_breg8 = 0x78,
665 DW_OP_breg9 = 0x79,
666 DW_OP_breg10 = 0x7a,
667 DW_OP_breg11 = 0x7b,
668 DW_OP_breg12 = 0x7c,
669 DW_OP_breg13 = 0x7d,
670 DW_OP_breg14 = 0x7e,
671 DW_OP_breg15 = 0x7f,
672 DW_OP_breg16 = 0x80,
673 DW_OP_breg17 = 0x81,
674 DW_OP_breg18 = 0x82,
675 DW_OP_breg19 = 0x83,
676 DW_OP_breg20 = 0x84,
677 DW_OP_breg21 = 0x85,
678 DW_OP_breg22 = 0x86,
679 DW_OP_breg23 = 0x87,
680 DW_OP_breg24 = 0x88,
681 DW_OP_breg25 = 0x89,
682 DW_OP_breg26 = 0x8a,
683 DW_OP_breg27 = 0x8b,
684 DW_OP_breg28 = 0x8c,
685 DW_OP_breg29 = 0x8d,
686 DW_OP_breg30 = 0x8e,
687 DW_OP_breg31 = 0x8f,
688 DW_OP_regx = 0x90,
689 DW_OP_fbreg = 0x91,
690 DW_OP_bregx = 0x92,
691 DW_OP_piece = 0x93,
692 DW_OP_deref_size = 0x94,
693 DW_OP_xderef_size = 0x95,
694 DW_OP_nop = 0x96,
695 DW_OP_push_object_address = 0x97,
696 DW_OP_call2 = 0x98,
697 DW_OP_call4 = 0x99,
698 DW_OP_call_ref = 0x9a,
699 DW_OP_form_tls_address = 0x9b,
700 DW_OP_call_frame_cfa = 0x9c,
701 DW_OP_bit_piece = 0x9d,
702 DW_OP_lo_user = 0xe0,
703 DW_OP_hi_user = 0xff,
704 DW_OP_GNU_push_tls_address = 0xe0,
705 DW_OP_GNU_uninit = 0xf0,
706 DW_OP_GNU_encoded_addr = 0xf1,
709 #define DW_EH_PE_native 0x00
710 #define DW_EH_PE_leb128 0x01
711 #define DW_EH_PE_data2 0x02
712 #define DW_EH_PE_data4 0x03
713 #define DW_EH_PE_data8 0x04
714 #define DW_EH_PE_signed 0x08
715 #define DW_EH_PE_abs 0x00
716 #define DW_EH_PE_pcrel 0x10
717 #define DW_EH_PE_textrel 0x20
718 #define DW_EH_PE_datarel 0x30
719 #define DW_EH_PE_funcrel 0x40
720 #define DW_EH_PE_aligned 0x50
721 #define DW_EH_PE_indirect 0x80
722 #define DW_EH_PE_omit 0xff
724 struct dwarf_eh_bases
726 void *tbase;
727 void *dbase;
728 void *func;
731 struct dwarf_cie
733 unsigned int length;
734 int id;
735 unsigned char version;
736 unsigned char augmentation[1];
739 struct dwarf_fde
741 unsigned int length;
742 unsigned int cie_offset;
745 extern const struct dwarf_fde *_Unwind_Find_FDE (void *, struct dwarf_eh_bases *);
747 static unsigned char dwarf_get_u1( const unsigned char **p )
749 return *(*p)++;
752 static unsigned short dwarf_get_u2( const unsigned char **p )
754 unsigned int ret = (*p)[0] | ((*p)[1] << 8);
755 (*p) += 2;
756 return ret;
759 static unsigned int dwarf_get_u4( const unsigned char **p )
761 unsigned int ret = (*p)[0] | ((*p)[1] << 8) | ((*p)[2] << 16) | ((*p)[3] << 24);
762 (*p) += 4;
763 return ret;
766 static ULONG64 dwarf_get_u8( const unsigned char **p )
768 ULONG64 low = dwarf_get_u4( p );
769 ULONG64 high = dwarf_get_u4( p );
770 return low | (high << 32);
773 static ULONG_PTR dwarf_get_uleb128( const unsigned char **p )
775 ULONG_PTR ret = 0;
776 unsigned int shift = 0;
777 unsigned char byte;
781 byte = **p;
782 ret |= (ULONG_PTR)(byte & 0x7f) << shift;
783 shift += 7;
784 (*p)++;
785 } while (byte & 0x80);
786 return ret;
789 static LONG_PTR dwarf_get_sleb128( const unsigned char **p )
791 ULONG_PTR ret = 0;
792 unsigned int shift = 0;
793 unsigned char byte;
797 byte = **p;
798 ret |= (ULONG_PTR)(byte & 0x7f) << shift;
799 shift += 7;
800 (*p)++;
801 } while (byte & 0x80);
803 if ((shift < 8 * sizeof(ret)) && (byte & 0x40)) ret |= -((ULONG_PTR)1 << shift);
804 return ret;
807 static ULONG_PTR dwarf_get_ptr( const unsigned char **p, unsigned char encoding )
809 ULONG_PTR base;
811 if (encoding == DW_EH_PE_omit) return 0;
813 switch (encoding & 0xf0)
815 case DW_EH_PE_abs:
816 base = 0;
817 break;
818 case DW_EH_PE_pcrel:
819 base = (ULONG_PTR)*p;
820 break;
821 default:
822 FIXME( "unsupported encoding %02x\n", encoding );
823 return 0;
826 switch (encoding & 0x0f)
828 case DW_EH_PE_native:
829 return base + dwarf_get_u8( p );
830 case DW_EH_PE_leb128:
831 return base + dwarf_get_uleb128( p );
832 case DW_EH_PE_data2:
833 return base + dwarf_get_u2( p );
834 case DW_EH_PE_data4:
835 return base + dwarf_get_u4( p );
836 case DW_EH_PE_data8:
837 return base + dwarf_get_u8( p );
838 case DW_EH_PE_signed|DW_EH_PE_leb128:
839 return base + dwarf_get_sleb128( p );
840 case DW_EH_PE_signed|DW_EH_PE_data2:
841 return base + (signed short)dwarf_get_u2( p );
842 case DW_EH_PE_signed|DW_EH_PE_data4:
843 return base + (signed int)dwarf_get_u4( p );
844 case DW_EH_PE_signed|DW_EH_PE_data8:
845 return base + (LONG64)dwarf_get_u8( p );
846 default:
847 FIXME( "unsupported encoding %02x\n", encoding );
848 return 0;
852 enum reg_rule
854 RULE_UNSET, /* not set at all */
855 RULE_UNDEFINED, /* undefined value */
856 RULE_SAME, /* same value as previous frame */
857 RULE_CFA_OFFSET, /* stored at cfa offset */
858 RULE_OTHER_REG, /* stored in other register */
859 RULE_EXPRESSION, /* address specified by expression */
860 RULE_VAL_EXPRESSION /* value specified by expression */
863 #define NB_FRAME_REGS 41
864 #define MAX_SAVED_STATES 16
866 struct frame_state
868 ULONG_PTR cfa_offset;
869 unsigned char cfa_reg;
870 enum reg_rule cfa_rule;
871 enum reg_rule rules[NB_FRAME_REGS];
872 ULONG64 regs[NB_FRAME_REGS];
875 struct frame_info
877 ULONG_PTR ip;
878 ULONG_PTR code_align;
879 LONG_PTR data_align;
880 unsigned char retaddr_reg;
881 unsigned char fde_encoding;
882 unsigned char signal_frame;
883 unsigned char state_sp;
884 struct frame_state state;
885 struct frame_state *state_stack;
888 static const char *dwarf_reg_names[NB_FRAME_REGS] =
890 /* 0-7 */ "%rax", "%rdx", "%rcx", "%rbx", "%rsi", "%rdi", "%rbp", "%rsp",
891 /* 8-16 */ "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "%rip",
892 /* 17-24 */ "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
893 /* 25-32 */ "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15",
894 /* 33-40 */ "%st0", "%st1", "%st2", "%st3", "%st4", "%st5", "%st6", "%st7"
897 static BOOL valid_reg( ULONG_PTR reg )
899 if (reg >= NB_FRAME_REGS) FIXME( "unsupported reg %lx\n", reg );
900 return (reg < NB_FRAME_REGS);
903 static void execute_cfa_instructions( const unsigned char *ptr, const unsigned char *end,
904 ULONG_PTR last_ip, struct frame_info *info )
906 while (ptr < end && info->ip < last_ip + info->signal_frame)
908 enum dwarf_call_frame_info op = *ptr++;
910 if (op & 0xc0)
912 switch (op & 0xc0)
914 case DW_CFA_advance_loc:
916 ULONG_PTR offset = (op & 0x3f) * info->code_align;
917 TRACE( "%lx: DW_CFA_advance_loc %lu\n", info->ip, offset );
918 info->ip += offset;
919 break;
921 case DW_CFA_offset:
923 ULONG_PTR reg = op & 0x3f;
924 LONG_PTR offset = dwarf_get_uleb128( &ptr ) * info->data_align;
925 if (!valid_reg( reg )) break;
926 TRACE( "%lx: DW_CFA_offset %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
927 info->state.regs[reg] = offset;
928 info->state.rules[reg] = RULE_CFA_OFFSET;
929 break;
931 case DW_CFA_restore:
933 ULONG_PTR reg = op & 0x3f;
934 if (!valid_reg( reg )) break;
935 TRACE( "%lx: DW_CFA_restore %s\n", info->ip, dwarf_reg_names[reg] );
936 info->state.rules[reg] = RULE_UNSET;
937 break;
941 else switch (op)
943 case DW_CFA_nop:
944 break;
945 case DW_CFA_set_loc:
947 ULONG_PTR loc = dwarf_get_ptr( &ptr, info->fde_encoding );
948 TRACE( "%lx: DW_CFA_set_loc %lx\n", info->ip, loc );
949 info->ip = loc;
950 break;
952 case DW_CFA_advance_loc1:
954 ULONG_PTR offset = *ptr++ * info->code_align;
955 TRACE( "%lx: DW_CFA_advance_loc1 %lu\n", info->ip, offset );
956 info->ip += offset;
957 break;
959 case DW_CFA_advance_loc2:
961 ULONG_PTR offset = dwarf_get_u2( &ptr ) * info->code_align;
962 TRACE( "%lx: DW_CFA_advance_loc2 %lu\n", info->ip, offset );
963 info->ip += offset;
964 break;
966 case DW_CFA_advance_loc4:
968 ULONG_PTR offset = dwarf_get_u4( &ptr ) * info->code_align;
969 TRACE( "%lx: DW_CFA_advance_loc4 %lu\n", info->ip, offset );
970 info->ip += offset;
971 break;
973 case DW_CFA_offset_extended:
974 case DW_CFA_offset_extended_sf:
976 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
977 LONG_PTR offset = (op == DW_CFA_offset_extended) ? dwarf_get_uleb128( &ptr ) * info->data_align
978 : dwarf_get_sleb128( &ptr ) * info->data_align;
979 if (!valid_reg( reg )) break;
980 TRACE( "%lx: DW_CFA_offset_extended %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
981 info->state.regs[reg] = offset;
982 info->state.rules[reg] = RULE_CFA_OFFSET;
983 break;
985 case DW_CFA_restore_extended:
987 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
988 if (!valid_reg( reg )) break;
989 TRACE( "%lx: DW_CFA_restore_extended %s\n", info->ip, dwarf_reg_names[reg] );
990 info->state.rules[reg] = RULE_UNSET;
991 break;
993 case DW_CFA_undefined:
995 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
996 if (!valid_reg( reg )) break;
997 TRACE( "%lx: DW_CFA_undefined %s\n", info->ip, dwarf_reg_names[reg] );
998 info->state.rules[reg] = RULE_UNDEFINED;
999 break;
1001 case DW_CFA_same_value:
1003 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1004 if (!valid_reg( reg )) break;
1005 TRACE( "%lx: DW_CFA_same_value %s\n", info->ip, dwarf_reg_names[reg] );
1006 info->state.regs[reg] = reg;
1007 info->state.rules[reg] = RULE_SAME;
1008 break;
1010 case DW_CFA_register:
1012 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1013 ULONG_PTR reg2 = dwarf_get_uleb128( &ptr );
1014 if (!valid_reg( reg ) || !valid_reg( reg2 )) break;
1015 TRACE( "%lx: DW_CFA_register %s == %s\n", info->ip, dwarf_reg_names[reg], dwarf_reg_names[reg2] );
1016 info->state.regs[reg] = reg2;
1017 info->state.rules[reg] = RULE_OTHER_REG;
1018 break;
1020 case DW_CFA_remember_state:
1021 TRACE( "%lx: DW_CFA_remember_state\n", info->ip );
1022 if (info->state_sp >= MAX_SAVED_STATES)
1023 FIXME( "%lx: DW_CFA_remember_state too many nested saves\n", info->ip );
1024 else
1025 info->state_stack[info->state_sp++] = info->state;
1026 break;
1027 case DW_CFA_restore_state:
1028 TRACE( "%lx: DW_CFA_restore_state\n", info->ip );
1029 if (!info->state_sp)
1030 FIXME( "%lx: DW_CFA_restore_state without corresponding save\n", info->ip );
1031 else
1032 info->state = info->state_stack[--info->state_sp];
1033 break;
1034 case DW_CFA_def_cfa:
1035 case DW_CFA_def_cfa_sf:
1037 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1038 ULONG_PTR offset = (op == DW_CFA_def_cfa) ? dwarf_get_uleb128( &ptr )
1039 : dwarf_get_sleb128( &ptr ) * info->data_align;
1040 if (!valid_reg( reg )) break;
1041 TRACE( "%lx: DW_CFA_def_cfa %s, %lu\n", info->ip, dwarf_reg_names[reg], offset );
1042 info->state.cfa_reg = reg;
1043 info->state.cfa_offset = offset;
1044 info->state.cfa_rule = RULE_CFA_OFFSET;
1045 break;
1047 case DW_CFA_def_cfa_register:
1049 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1050 if (!valid_reg( reg )) break;
1051 TRACE( "%lx: DW_CFA_def_cfa_register %s\n", info->ip, dwarf_reg_names[reg] );
1052 info->state.cfa_reg = reg;
1053 info->state.cfa_rule = RULE_CFA_OFFSET;
1054 break;
1056 case DW_CFA_def_cfa_offset:
1057 case DW_CFA_def_cfa_offset_sf:
1059 ULONG_PTR offset = (op == DW_CFA_def_cfa_offset) ? dwarf_get_uleb128( &ptr )
1060 : dwarf_get_sleb128( &ptr ) * info->data_align;
1061 TRACE( "%lx: DW_CFA_def_cfa_offset %lu\n", info->ip, offset );
1062 info->state.cfa_offset = offset;
1063 info->state.cfa_rule = RULE_CFA_OFFSET;
1064 break;
1066 case DW_CFA_def_cfa_expression:
1068 ULONG_PTR expr = (ULONG_PTR)ptr;
1069 ULONG_PTR len = dwarf_get_uleb128( &ptr );
1070 TRACE( "%lx: DW_CFA_def_cfa_expression %lx-%lx\n", info->ip, expr, expr+len );
1071 info->state.cfa_offset = expr;
1072 info->state.cfa_rule = RULE_VAL_EXPRESSION;
1073 ptr += len;
1074 break;
1076 case DW_CFA_expression:
1077 case DW_CFA_val_expression:
1079 ULONG_PTR reg = dwarf_get_uleb128( &ptr );
1080 ULONG_PTR expr = (ULONG_PTR)ptr;
1081 ULONG_PTR len = dwarf_get_uleb128( &ptr );
1082 if (!valid_reg( reg )) break;
1083 TRACE( "%lx: DW_CFA_%sexpression %s %lx-%lx\n",
1084 info->ip, (op == DW_CFA_expression) ? "" : "val_", dwarf_reg_names[reg], expr, expr+len );
1085 info->state.regs[reg] = expr;
1086 info->state.rules[reg] = (op == DW_CFA_expression) ? RULE_EXPRESSION : RULE_VAL_EXPRESSION;
1087 ptr += len;
1088 break;
1090 default:
1091 FIXME( "%lx: unknown CFA opcode %02x\n", info->ip, op );
1092 break;
1097 /* retrieve a context register from its dwarf number */
1098 static void *get_context_reg( CONTEXT *context, ULONG_PTR dw_reg )
1100 switch (dw_reg)
1102 case 0: return &context->Rax;
1103 case 1: return &context->Rdx;
1104 case 2: return &context->Rcx;
1105 case 3: return &context->Rbx;
1106 case 4: return &context->Rsi;
1107 case 5: return &context->Rdi;
1108 case 6: return &context->Rbp;
1109 case 7: return &context->Rsp;
1110 case 8: return &context->R8;
1111 case 9: return &context->R9;
1112 case 10: return &context->R10;
1113 case 11: return &context->R11;
1114 case 12: return &context->R12;
1115 case 13: return &context->R13;
1116 case 14: return &context->R14;
1117 case 15: return &context->R15;
1118 case 16: return &context->Rip;
1119 case 17: return &context->u.s.Xmm0;
1120 case 18: return &context->u.s.Xmm1;
1121 case 19: return &context->u.s.Xmm2;
1122 case 20: return &context->u.s.Xmm3;
1123 case 21: return &context->u.s.Xmm4;
1124 case 22: return &context->u.s.Xmm5;
1125 case 23: return &context->u.s.Xmm6;
1126 case 24: return &context->u.s.Xmm7;
1127 case 25: return &context->u.s.Xmm8;
1128 case 26: return &context->u.s.Xmm9;
1129 case 27: return &context->u.s.Xmm10;
1130 case 28: return &context->u.s.Xmm11;
1131 case 29: return &context->u.s.Xmm12;
1132 case 30: return &context->u.s.Xmm13;
1133 case 31: return &context->u.s.Xmm14;
1134 case 32: return &context->u.s.Xmm15;
1135 case 33: return &context->u.s.Legacy[0];
1136 case 34: return &context->u.s.Legacy[1];
1137 case 35: return &context->u.s.Legacy[2];
1138 case 36: return &context->u.s.Legacy[3];
1139 case 37: return &context->u.s.Legacy[4];
1140 case 38: return &context->u.s.Legacy[5];
1141 case 39: return &context->u.s.Legacy[6];
1142 case 40: return &context->u.s.Legacy[7];
1143 default: return NULL;
1147 /* set a context register from its dwarf number */
1148 static void set_context_reg( CONTEXT *context, ULONG_PTR dw_reg, void *val )
1150 switch (dw_reg)
1152 case 0: context->Rax = *(ULONG64 *)val; break;
1153 case 1: context->Rdx = *(ULONG64 *)val; break;
1154 case 2: context->Rcx = *(ULONG64 *)val; break;
1155 case 3: context->Rbx = *(ULONG64 *)val; break;
1156 case 4: context->Rsi = *(ULONG64 *)val; break;
1157 case 5: context->Rdi = *(ULONG64 *)val; break;
1158 case 6: context->Rbp = *(ULONG64 *)val; break;
1159 case 7: context->Rsp = *(ULONG64 *)val; break;
1160 case 8: context->R8 = *(ULONG64 *)val; break;
1161 case 9: context->R9 = *(ULONG64 *)val; break;
1162 case 10: context->R10 = *(ULONG64 *)val; break;
1163 case 11: context->R11 = *(ULONG64 *)val; break;
1164 case 12: context->R12 = *(ULONG64 *)val; break;
1165 case 13: context->R13 = *(ULONG64 *)val; break;
1166 case 14: context->R14 = *(ULONG64 *)val; break;
1167 case 15: context->R15 = *(ULONG64 *)val; break;
1168 case 16: context->Rip = *(ULONG64 *)val; break;
1169 case 17: memcpy( &context->u.s.Xmm0, val, sizeof(M128A) ); break;
1170 case 18: memcpy( &context->u.s.Xmm1, val, sizeof(M128A) ); break;
1171 case 19: memcpy( &context->u.s.Xmm2, val, sizeof(M128A) ); break;
1172 case 20: memcpy( &context->u.s.Xmm3, val, sizeof(M128A) ); break;
1173 case 21: memcpy( &context->u.s.Xmm4, val, sizeof(M128A) ); break;
1174 case 22: memcpy( &context->u.s.Xmm5, val, sizeof(M128A) ); break;
1175 case 23: memcpy( &context->u.s.Xmm6, val, sizeof(M128A) ); break;
1176 case 24: memcpy( &context->u.s.Xmm7, val, sizeof(M128A) ); break;
1177 case 25: memcpy( &context->u.s.Xmm8, val, sizeof(M128A) ); break;
1178 case 26: memcpy( &context->u.s.Xmm9, val, sizeof(M128A) ); break;
1179 case 27: memcpy( &context->u.s.Xmm10, val, sizeof(M128A) ); break;
1180 case 28: memcpy( &context->u.s.Xmm11, val, sizeof(M128A) ); break;
1181 case 29: memcpy( &context->u.s.Xmm12, val, sizeof(M128A) ); break;
1182 case 30: memcpy( &context->u.s.Xmm13, val, sizeof(M128A) ); break;
1183 case 31: memcpy( &context->u.s.Xmm14, val, sizeof(M128A) ); break;
1184 case 32: memcpy( &context->u.s.Xmm15, val, sizeof(M128A) ); break;
1185 case 33: memcpy( &context->u.s.Legacy[0], val, sizeof(M128A) ); break;
1186 case 34: memcpy( &context->u.s.Legacy[1], val, sizeof(M128A) ); break;
1187 case 35: memcpy( &context->u.s.Legacy[2], val, sizeof(M128A) ); break;
1188 case 36: memcpy( &context->u.s.Legacy[3], val, sizeof(M128A) ); break;
1189 case 37: memcpy( &context->u.s.Legacy[4], val, sizeof(M128A) ); break;
1190 case 38: memcpy( &context->u.s.Legacy[5], val, sizeof(M128A) ); break;
1191 case 39: memcpy( &context->u.s.Legacy[6], val, sizeof(M128A) ); break;
1192 case 40: memcpy( &context->u.s.Legacy[7], val, sizeof(M128A) ); break;
1196 static ULONG_PTR eval_expression( const unsigned char *p, CONTEXT *context )
1198 ULONG_PTR reg, tmp, stack[64];
1199 int sp = -1;
1200 ULONG_PTR len = dwarf_get_uleb128(&p);
1201 const unsigned char *end = p + len;
1203 while (p < end)
1205 unsigned char opcode = dwarf_get_u1(&p);
1207 if (opcode >= DW_OP_lit0 && opcode <= DW_OP_lit31)
1208 stack[++sp] = opcode - DW_OP_lit0;
1209 else if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31)
1210 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_reg0 );
1211 else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31)
1212 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_breg0 ) + dwarf_get_sleb128(&p);
1213 else switch (opcode)
1215 case DW_OP_nop: break;
1216 case DW_OP_addr: stack[++sp] = dwarf_get_u8(&p); break;
1217 case DW_OP_const1u: stack[++sp] = dwarf_get_u1(&p); break;
1218 case DW_OP_const1s: stack[++sp] = (signed char)dwarf_get_u1(&p); break;
1219 case DW_OP_const2u: stack[++sp] = dwarf_get_u2(&p); break;
1220 case DW_OP_const2s: stack[++sp] = (short)dwarf_get_u2(&p); break;
1221 case DW_OP_const4u: stack[++sp] = dwarf_get_u4(&p); break;
1222 case DW_OP_const4s: stack[++sp] = (signed int)dwarf_get_u4(&p); break;
1223 case DW_OP_const8u: stack[++sp] = dwarf_get_u8(&p); break;
1224 case DW_OP_const8s: stack[++sp] = (LONG_PTR)dwarf_get_u8(&p); break;
1225 case DW_OP_constu: stack[++sp] = dwarf_get_uleb128(&p); break;
1226 case DW_OP_consts: stack[++sp] = dwarf_get_sleb128(&p); break;
1227 case DW_OP_deref: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1228 case DW_OP_dup: stack[sp + 1] = stack[sp]; sp++; break;
1229 case DW_OP_drop: sp--; break;
1230 case DW_OP_over: stack[sp + 1] = stack[sp - 1]; sp++; break;
1231 case DW_OP_pick: stack[sp + 1] = stack[sp - dwarf_get_u1(&p)]; sp++; break;
1232 case DW_OP_swap: tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = tmp; break;
1233 case DW_OP_rot: tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = stack[sp-2]; stack[sp-2] = tmp; break;
1234 case DW_OP_abs: stack[sp] = labs(stack[sp]); break;
1235 case DW_OP_neg: stack[sp] = -stack[sp]; break;
1236 case DW_OP_not: stack[sp] = ~stack[sp]; break;
1237 case DW_OP_and: stack[sp-1] &= stack[sp]; sp--; break;
1238 case DW_OP_or: stack[sp-1] |= stack[sp]; sp--; break;
1239 case DW_OP_minus: stack[sp-1] -= stack[sp]; sp--; break;
1240 case DW_OP_mul: stack[sp-1] *= stack[sp]; sp--; break;
1241 case DW_OP_plus: stack[sp-1] += stack[sp]; sp--; break;
1242 case DW_OP_xor: stack[sp-1] ^= stack[sp]; sp--; break;
1243 case DW_OP_shl: stack[sp-1] <<= stack[sp]; sp--; break;
1244 case DW_OP_shr: stack[sp-1] >>= stack[sp]; sp--; break;
1245 case DW_OP_plus_uconst: stack[sp] += dwarf_get_uleb128(&p); break;
1246 case DW_OP_shra: stack[sp-1] = (LONG_PTR)stack[sp-1] / (1 << stack[sp]); sp--; break;
1247 case DW_OP_div: stack[sp-1] = (LONG_PTR)stack[sp-1] / (LONG_PTR)stack[sp]; sp--; break;
1248 case DW_OP_mod: stack[sp-1] = (LONG_PTR)stack[sp-1] % (LONG_PTR)stack[sp]; sp--; break;
1249 case DW_OP_ge: stack[sp-1] = ((LONG_PTR)stack[sp-1] >= (LONG_PTR)stack[sp]); sp--; break;
1250 case DW_OP_gt: stack[sp-1] = ((LONG_PTR)stack[sp-1] > (LONG_PTR)stack[sp]); sp--; break;
1251 case DW_OP_le: stack[sp-1] = ((LONG_PTR)stack[sp-1] <= (LONG_PTR)stack[sp]); sp--; break;
1252 case DW_OP_lt: stack[sp-1] = ((LONG_PTR)stack[sp-1] < (LONG_PTR)stack[sp]); sp--; break;
1253 case DW_OP_eq: stack[sp-1] = (stack[sp-1] == stack[sp]); sp--; break;
1254 case DW_OP_ne: stack[sp-1] = (stack[sp-1] != stack[sp]); sp--; break;
1255 case DW_OP_skip: tmp = (short)dwarf_get_u2(&p); p += tmp; break;
1256 case DW_OP_bra: tmp = (short)dwarf_get_u2(&p); if (!stack[sp--]) p += tmp; break;
1257 case DW_OP_GNU_encoded_addr: tmp = *p++; stack[++sp] = dwarf_get_ptr( &p, tmp ); break;
1258 case DW_OP_regx: stack[++sp] = *(ULONG_PTR *)get_context_reg( context, dwarf_get_uleb128(&p) ); break;
1259 case DW_OP_bregx:
1260 reg = dwarf_get_uleb128(&p);
1261 tmp = dwarf_get_sleb128(&p);
1262 stack[++sp] = *(ULONG_PTR *)get_context_reg( context, reg ) + tmp;
1263 break;
1264 case DW_OP_deref_size:
1265 switch (*p++)
1267 case 1: stack[sp] = *(unsigned char *)stack[sp]; break;
1268 case 2: stack[sp] = *(unsigned short *)stack[sp]; break;
1269 case 4: stack[sp] = *(unsigned int *)stack[sp]; break;
1270 case 8: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1272 break;
1273 default:
1274 FIXME( "unhandled opcode %02x\n", opcode );
1277 return stack[sp];
1280 /* apply the computed frame info to the actual context */
1281 static void apply_frame_state( CONTEXT *context, struct frame_state *state )
1283 unsigned int i;
1284 ULONG_PTR cfa, value;
1285 CONTEXT new_context = *context;
1287 switch (state->cfa_rule)
1289 case RULE_EXPRESSION:
1290 cfa = *(ULONG_PTR *)eval_expression( (const unsigned char *)state->cfa_offset, context );
1291 break;
1292 case RULE_VAL_EXPRESSION:
1293 cfa = eval_expression( (const unsigned char *)state->cfa_offset, context );
1294 break;
1295 default:
1296 cfa = *(ULONG_PTR *)get_context_reg( context, state->cfa_reg ) + state->cfa_offset;
1297 break;
1299 if (!cfa) return;
1301 for (i = 0; i < NB_FRAME_REGS; i++)
1303 switch (state->rules[i])
1305 case RULE_UNSET:
1306 case RULE_UNDEFINED:
1307 case RULE_SAME:
1308 break;
1309 case RULE_CFA_OFFSET:
1310 set_context_reg( &new_context, i, (char *)cfa + state->regs[i] );
1311 break;
1312 case RULE_OTHER_REG:
1313 set_context_reg( &new_context, i, get_context_reg( context, state->regs[i] ));
1314 break;
1315 case RULE_EXPRESSION:
1316 value = eval_expression( (const unsigned char *)state->regs[i], context );
1317 set_context_reg( &new_context, i, (void *)value );
1318 break;
1319 case RULE_VAL_EXPRESSION:
1320 value = eval_expression( (const unsigned char *)state->regs[i], context );
1321 set_context_reg( &new_context, i, &value );
1322 break;
1325 new_context.Rsp = cfa;
1326 *context = new_context;
1330 /***********************************************************************
1331 * dwarf_virtual_unwind
1333 * Equivalent of RtlVirtualUnwind for builtin modules.
1335 static NTSTATUS dwarf_virtual_unwind( ULONG64 ip, ULONG64 *frame,CONTEXT *context,
1336 const struct dwarf_fde *fde, const struct dwarf_eh_bases *bases,
1337 PEXCEPTION_ROUTINE *handler, void **handler_data )
1339 const struct dwarf_cie *cie;
1340 const unsigned char *ptr, *augmentation, *end;
1341 ULONG_PTR len, code_end;
1342 struct frame_info info;
1343 struct frame_state state_stack[MAX_SAVED_STATES];
1344 int aug_z_format = 0;
1345 unsigned char lsda_encoding = DW_EH_PE_omit;
1347 memset( &info, 0, sizeof(info) );
1348 info.state_stack = state_stack;
1349 info.ip = (ULONG_PTR)bases->func;
1350 *handler = NULL;
1352 cie = (const struct dwarf_cie *)((const char *)&fde->cie_offset - fde->cie_offset);
1354 /* parse the CIE first */
1356 if (cie->version != 1 && cie->version != 3)
1358 FIXME( "unknown CIE version %u at %p\n", cie->version, cie );
1359 return STATUS_INVALID_DISPOSITION;
1361 ptr = cie->augmentation + strlen((const char *)cie->augmentation) + 1;
1363 info.code_align = dwarf_get_uleb128( &ptr );
1364 info.data_align = dwarf_get_sleb128( &ptr );
1365 if (cie->version == 1)
1366 info.retaddr_reg = *ptr++;
1367 else
1368 info.retaddr_reg = dwarf_get_uleb128( &ptr );
1369 info.state.cfa_rule = RULE_CFA_OFFSET;
1371 TRACE( "function %lx base %p cie %p len %x id %x version %x aug '%s' code_align %lu data_align %ld retaddr %s\n",
1372 ip, bases->func, cie, cie->length, cie->id, cie->version, cie->augmentation,
1373 info.code_align, info.data_align, dwarf_reg_names[info.retaddr_reg] );
1375 end = NULL;
1376 for (augmentation = cie->augmentation; *augmentation; augmentation++)
1378 switch (*augmentation)
1380 case 'z':
1381 len = dwarf_get_uleb128( &ptr );
1382 end = ptr + len;
1383 aug_z_format = 1;
1384 continue;
1385 case 'L':
1386 lsda_encoding = *ptr++;
1387 continue;
1388 case 'P':
1390 unsigned char encoding = *ptr++;
1391 *handler = (void *)dwarf_get_ptr( &ptr, encoding );
1392 continue;
1394 case 'R':
1395 info.fde_encoding = *ptr++;
1396 continue;
1397 case 'S':
1398 info.signal_frame = 1;
1399 continue;
1401 FIXME( "unknown augmentation '%c'\n", *augmentation );
1402 if (!end) return STATUS_INVALID_DISPOSITION; /* cannot continue */
1403 break;
1405 if (end) ptr = end;
1407 end = (const unsigned char *)(&cie->length + 1) + cie->length;
1408 execute_cfa_instructions( ptr, end, ip, &info );
1410 ptr = (const unsigned char *)(fde + 1);
1411 info.ip = dwarf_get_ptr( &ptr, info.fde_encoding ); /* fde code start */
1412 code_end = info.ip + dwarf_get_ptr( &ptr, info.fde_encoding & 0x0f ); /* fde code length */
1414 if (aug_z_format) /* get length of augmentation data */
1416 len = dwarf_get_uleb128( &ptr );
1417 end = ptr + len;
1419 else end = NULL;
1421 *handler_data = (void *)dwarf_get_ptr( &ptr, lsda_encoding );
1422 if (end) ptr = end;
1424 end = (const unsigned char *)(&fde->length + 1) + fde->length;
1425 TRACE( "fde %p len %x personality %p lsda %p code %lx-%lx\n",
1426 fde, fde->length, *handler, *handler_data, info.ip, code_end );
1427 execute_cfa_instructions( ptr, end, ip, &info );
1428 *frame = context->Rsp;
1429 apply_frame_state( context, &info.state );
1431 TRACE( "next function rip=%016lx\n", context->Rip );
1432 TRACE( " rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1433 context->Rax, context->Rbx, context->Rcx, context->Rdx );
1434 TRACE( " rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1435 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1436 TRACE( " r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
1437 context->R8, context->R9, context->R10, context->R11 );
1438 TRACE( " r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1439 context->R12, context->R13, context->R14, context->R15 );
1441 return STATUS_SUCCESS;
1445 #ifdef HAVE_LIBUNWIND_H
1446 /***********************************************************************
1447 * libunwind_set_cursor_from_context
1449 static int libunwind_set_cursor_from_context( unw_cursor_t *cursor, CONTEXT *context, ULONG64 ip )
1451 int rc;
1453 rc = unw_set_reg(cursor, UNW_REG_IP, ip);
1454 if (rc == UNW_ESUCCESS)
1455 rc = unw_set_reg(cursor, UNW_REG_SP, context->Rsp);
1456 if (rc == UNW_ESUCCESS)
1457 rc = unw_set_reg(cursor, UNW_X86_64_RAX, context->Rax);
1458 if (rc == UNW_ESUCCESS)
1459 rc = unw_set_reg(cursor, UNW_X86_64_RDX, context->Rdx);
1460 if (rc == UNW_ESUCCESS)
1461 rc = unw_set_reg(cursor, UNW_X86_64_RCX, context->Rcx);
1462 if (rc == UNW_ESUCCESS)
1463 rc = unw_set_reg(cursor, UNW_X86_64_RBX, context->Rbx);
1464 if (rc == UNW_ESUCCESS)
1465 rc = unw_set_reg(cursor, UNW_X86_64_RSI, context->Rsi);
1466 if (rc == UNW_ESUCCESS)
1467 rc = unw_set_reg(cursor, UNW_X86_64_RDI, context->Rdi);
1468 if (rc == UNW_ESUCCESS)
1469 rc = unw_set_reg(cursor, UNW_X86_64_RBP, context->Rbp);
1470 if (rc == UNW_ESUCCESS)
1471 rc = unw_set_reg(cursor, UNW_X86_64_R8, context->R8);
1472 if (rc == UNW_ESUCCESS)
1473 rc = unw_set_reg(cursor, UNW_X86_64_R9, context->R9);
1474 if (rc == UNW_ESUCCESS)
1475 rc = unw_set_reg(cursor, UNW_X86_64_R10, context->R10);
1476 if (rc == UNW_ESUCCESS)
1477 rc = unw_set_reg(cursor, UNW_X86_64_R11, context->R11);
1478 if (rc == UNW_ESUCCESS)
1479 rc = unw_set_reg(cursor, UNW_X86_64_R12, context->R12);
1480 if (rc == UNW_ESUCCESS)
1481 rc = unw_set_reg(cursor, UNW_X86_64_R13, context->R13);
1482 if (rc == UNW_ESUCCESS)
1483 rc = unw_set_reg(cursor, UNW_X86_64_R14, context->R14);
1484 if (rc == UNW_ESUCCESS)
1485 rc = unw_set_reg(cursor, UNW_X86_64_R15, context->R15);
1487 return rc;
1491 /***********************************************************************
1492 * libunwind_get_reg
1494 static int libunwind_get_reg( unw_cursor_t *cursor, unw_regnum_t reg, ULONG64 *val )
1496 int rc;
1497 unw_word_t word;
1499 rc = unw_get_reg(cursor, reg, &word);
1500 if (rc == UNW_ESUCCESS)
1501 *val = word;
1503 return rc;
1507 /***********************************************************************
1508 * libunwind_set_context_from_cursor
1510 static BOOL libunwind_set_context_from_cursor( CONTEXT *context, unw_cursor_t *cursor )
1512 int rc;
1514 rc = libunwind_get_reg(cursor, UNW_REG_IP, &context->Rip);
1515 if (rc == UNW_ESUCCESS)
1516 rc = libunwind_get_reg(cursor, UNW_REG_SP, &context->Rsp);
1517 if (rc == UNW_ESUCCESS)
1518 rc = libunwind_get_reg(cursor, UNW_X86_64_RAX, &context->Rax);
1519 if (rc == UNW_ESUCCESS)
1520 rc = libunwind_get_reg(cursor, UNW_X86_64_RDX, &context->Rdx);
1521 if (rc == UNW_ESUCCESS)
1522 rc = libunwind_get_reg(cursor, UNW_X86_64_RCX, &context->Rcx);
1523 if (rc == UNW_ESUCCESS)
1524 rc = libunwind_get_reg(cursor, UNW_X86_64_RBX, &context->Rbx);
1525 if (rc == UNW_ESUCCESS)
1526 rc = libunwind_get_reg(cursor, UNW_X86_64_RSI, &context->Rsi);
1527 if (rc == UNW_ESUCCESS)
1528 rc = libunwind_get_reg(cursor, UNW_X86_64_RDI, &context->Rdi);
1529 if (rc == UNW_ESUCCESS)
1530 rc = libunwind_get_reg(cursor, UNW_X86_64_RBP, &context->Rbp);
1531 if (rc == UNW_ESUCCESS)
1532 rc = libunwind_get_reg(cursor, UNW_X86_64_R8, &context->R8);
1533 if (rc == UNW_ESUCCESS)
1534 rc = libunwind_get_reg(cursor, UNW_X86_64_R9, &context->R9);
1535 if (rc == UNW_ESUCCESS)
1536 rc = libunwind_get_reg(cursor, UNW_X86_64_R10, &context->R10);
1537 if (rc == UNW_ESUCCESS)
1538 rc = libunwind_get_reg(cursor, UNW_X86_64_R11, &context->R11);
1539 if (rc == UNW_ESUCCESS)
1540 rc = libunwind_get_reg(cursor, UNW_X86_64_R12, &context->R12);
1541 if (rc == UNW_ESUCCESS)
1542 rc = libunwind_get_reg(cursor, UNW_X86_64_R13, &context->R13);
1543 if (rc == UNW_ESUCCESS)
1544 rc = libunwind_get_reg(cursor, UNW_X86_64_R14, &context->R14);
1545 if (rc == UNW_ESUCCESS)
1546 rc = libunwind_get_reg(cursor, UNW_X86_64_R15, &context->R15);
1548 return rc;
1552 /***********************************************************************
1553 * libunwind_virtual_unwind
1555 * Equivalent of RtlVirtualUnwind for builtin modules.
1557 static NTSTATUS libunwind_virtual_unwind( ULONG64 ip, BOOL* got_info, ULONG64 *frame, CONTEXT *context,
1558 PEXCEPTION_ROUTINE *handler, void **handler_data )
1560 unw_context_t unw_context;
1561 unw_cursor_t cursor;
1562 unw_proc_info_t info;
1563 int rc;
1565 rc = unw_getcontext( &unw_context );
1566 if (rc == UNW_ESUCCESS)
1567 rc = unw_init_local( &cursor, &unw_context );
1568 if (rc == UNW_ESUCCESS)
1569 rc = libunwind_set_cursor_from_context( &cursor, context, ip - 1 );
1570 if (rc != UNW_ESUCCESS)
1572 WARN( "setup failed: %d\n", rc );
1573 return STATUS_INVALID_DISPOSITION;
1576 rc = unw_get_proc_info(&cursor, &info);
1577 if (rc != UNW_ESUCCESS && rc != UNW_ENOINFO)
1579 WARN( "failed to get info: %d\n", rc );
1580 return STATUS_INVALID_DISPOSITION;
1582 if (rc == UNW_ENOINFO || ip < info.start_ip || info.end_ip <= ip || !info.format)
1584 *got_info = FALSE;
1585 return STATUS_SUCCESS;
1588 TRACE( "ip %#lx function %#lx-%#lx personality %#lx lsda %#lx fde %#lx\n",
1589 ip, (unsigned long)info.start_ip, (unsigned long)info.end_ip, (unsigned long)info.handler,
1590 (unsigned long)info.lsda, (unsigned long)info.unwind_info );
1592 rc = unw_step(&cursor);
1593 if (rc < 0)
1595 WARN( "failed to unwind: %d\n", rc );
1596 return STATUS_INVALID_DISPOSITION;
1599 *frame = context->Rsp;
1601 rc = libunwind_set_context_from_cursor( context, &cursor );
1602 if (rc != UNW_ESUCCESS)
1604 WARN( "failed to update context after unwind: %d\n", rc );
1605 return STATUS_INVALID_DISPOSITION;
1608 *handler = (void*)info.handler;
1609 *handler_data = (void*)info.lsda;
1610 *got_info = TRUE;
1612 TRACE( "next function rip=%016lx\n", context->Rip );
1613 TRACE( " rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1614 context->Rax, context->Rbx, context->Rcx, context->Rdx );
1615 TRACE( " rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1616 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1617 TRACE( " r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
1618 context->R8, context->R9, context->R10, context->R11 );
1619 TRACE( " r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1620 context->R12, context->R13, context->R14, context->R15 );
1622 return STATUS_SUCCESS;
1624 #endif
1627 /***********************************************************************
1628 * dispatch_signal
1630 static inline int dispatch_signal(unsigned int sig)
1632 if (handlers[sig] == NULL) return 0;
1633 return handlers[sig](sig);
1636 /***********************************************************************
1637 * get_signal_stack
1639 * Get the base of the signal stack for the current thread.
1641 static inline void *get_signal_stack(void)
1643 return (char *)NtCurrentTeb() + teb_size;
1646 /***********************************************************************
1647 * is_inside_signal_stack
1649 * Check if pointer is inside the signal stack.
1651 static inline BOOL is_inside_signal_stack( void *ptr )
1653 return ((char *)ptr >= (char *)get_signal_stack() &&
1654 (char *)ptr < (char *)get_signal_stack() + signal_stack_size);
1657 /***********************************************************************
1658 * save_context
1660 * Set the register values from a sigcontext.
1662 static void save_context( CONTEXT *context, const ucontext_t *sigcontext )
1664 context->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
1665 context->Rax = RAX_sig(sigcontext);
1666 context->Rcx = RCX_sig(sigcontext);
1667 context->Rdx = RDX_sig(sigcontext);
1668 context->Rbx = RBX_sig(sigcontext);
1669 context->Rsp = RSP_sig(sigcontext);
1670 context->Rbp = RBP_sig(sigcontext);
1671 context->Rsi = RSI_sig(sigcontext);
1672 context->Rdi = RDI_sig(sigcontext);
1673 context->R8 = R8_sig(sigcontext);
1674 context->R9 = R9_sig(sigcontext);
1675 context->R10 = R10_sig(sigcontext);
1676 context->R11 = R11_sig(sigcontext);
1677 context->R12 = R12_sig(sigcontext);
1678 context->R13 = R13_sig(sigcontext);
1679 context->R14 = R14_sig(sigcontext);
1680 context->R15 = R15_sig(sigcontext);
1681 context->Rip = RIP_sig(sigcontext);
1682 context->SegCs = CS_sig(sigcontext);
1683 context->SegFs = FS_sig(sigcontext);
1684 context->SegGs = GS_sig(sigcontext);
1685 context->EFlags = EFL_sig(sigcontext);
1686 #ifdef DS_sig
1687 context->SegDs = DS_sig(sigcontext);
1688 #else
1689 __asm__("movw %%ds,%0" : "=m" (context->SegDs));
1690 #endif
1691 #ifdef ES_sig
1692 context->SegEs = ES_sig(sigcontext);
1693 #else
1694 __asm__("movw %%es,%0" : "=m" (context->SegEs));
1695 #endif
1696 #ifdef SS_sig
1697 context->SegSs = SS_sig(sigcontext);
1698 #else
1699 __asm__("movw %%ss,%0" : "=m" (context->SegSs));
1700 #endif
1701 if (FPU_sig(sigcontext))
1703 context->ContextFlags |= CONTEXT_FLOATING_POINT;
1704 context->u.FltSave = *FPU_sig(sigcontext);
1705 context->MxCsr = context->u.FltSave.MxCsr;
1710 /***********************************************************************
1711 * restore_context
1713 * Build a sigcontext from the register values.
1715 static void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1717 RAX_sig(sigcontext) = context->Rax;
1718 RCX_sig(sigcontext) = context->Rcx;
1719 RDX_sig(sigcontext) = context->Rdx;
1720 RBX_sig(sigcontext) = context->Rbx;
1721 RSP_sig(sigcontext) = context->Rsp;
1722 RBP_sig(sigcontext) = context->Rbp;
1723 RSI_sig(sigcontext) = context->Rsi;
1724 RDI_sig(sigcontext) = context->Rdi;
1725 R8_sig(sigcontext) = context->R8;
1726 R9_sig(sigcontext) = context->R9;
1727 R10_sig(sigcontext) = context->R10;
1728 R11_sig(sigcontext) = context->R11;
1729 R12_sig(sigcontext) = context->R12;
1730 R13_sig(sigcontext) = context->R13;
1731 R14_sig(sigcontext) = context->R14;
1732 R15_sig(sigcontext) = context->R15;
1733 RIP_sig(sigcontext) = context->Rip;
1734 CS_sig(sigcontext) = context->SegCs;
1735 FS_sig(sigcontext) = context->SegFs;
1736 GS_sig(sigcontext) = context->SegGs;
1737 EFL_sig(sigcontext) = context->EFlags;
1738 #ifdef DS_sig
1739 DS_sig(sigcontext) = context->SegDs;
1740 #endif
1741 #ifdef ES_sig
1742 ES_sig(sigcontext) = context->SegEs;
1743 #endif
1744 #ifdef SS_sig
1745 SS_sig(sigcontext) = context->SegSs;
1746 #endif
1747 if (FPU_sig(sigcontext)) *FPU_sig(sigcontext) = context->u.FltSave;
1751 /**************************************************************************
1752 * __chkstk (NTDLL.@)
1754 * Supposed to touch all the stack pages, but we shouldn't need that.
1756 __ASM_GLOBAL_FUNC( __chkstk, "ret" );
1759 /***********************************************************************
1760 * RtlCaptureContext (NTDLL.@)
1762 __ASM_GLOBAL_FUNC( RtlCaptureContext,
1763 "pushfq\n\t"
1764 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
1765 "movl $0x001000f,0x30(%rcx)\n\t" /* context->ContextFlags */
1766 "stmxcsr 0x34(%rcx)\n\t" /* context->MxCsr */
1767 "movw %cs,0x38(%rcx)\n\t" /* context->SegCs */
1768 "movw %ds,0x3a(%rcx)\n\t" /* context->SegDs */
1769 "movw %es,0x3c(%rcx)\n\t" /* context->SegEs */
1770 "movw %fs,0x3e(%rcx)\n\t" /* context->SegFs */
1771 "movw %gs,0x40(%rcx)\n\t" /* context->SegGs */
1772 "movw %ss,0x42(%rcx)\n\t" /* context->SegSs */
1773 "popq 0x44(%rcx)\n\t" /* context->Eflags */
1774 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
1775 "movq %rax,0x78(%rcx)\n\t" /* context->Rax */
1776 "movq %rcx,0x80(%rcx)\n\t" /* context->Rcx */
1777 "movq %rdx,0x88(%rcx)\n\t" /* context->Rdx */
1778 "movq %rbx,0x90(%rcx)\n\t" /* context->Rbx */
1779 "leaq 8(%rsp),%rax\n\t"
1780 "movq %rax,0x98(%rcx)\n\t" /* context->Rsp */
1781 "movq %rbp,0xa0(%rcx)\n\t" /* context->Rbp */
1782 "movq %rsi,0xa8(%rcx)\n\t" /* context->Rsi */
1783 "movq %rdi,0xb0(%rcx)\n\t" /* context->Rdi */
1784 "movq %r8,0xb8(%rcx)\n\t" /* context->R8 */
1785 "movq %r9,0xc0(%rcx)\n\t" /* context->R9 */
1786 "movq %r10,0xc8(%rcx)\n\t" /* context->R10 */
1787 "movq %r11,0xd0(%rcx)\n\t" /* context->R11 */
1788 "movq %r12,0xd8(%rcx)\n\t" /* context->R12 */
1789 "movq %r13,0xe0(%rcx)\n\t" /* context->R13 */
1790 "movq %r14,0xe8(%rcx)\n\t" /* context->R14 */
1791 "movq %r15,0xf0(%rcx)\n\t" /* context->R15 */
1792 "movq (%rsp),%rax\n\t"
1793 "movq %rax,0xf8(%rcx)\n\t" /* context->Rip */
1794 "fxsave 0x100(%rcx)\n\t" /* context->FtlSave */
1795 "movdqa %xmm0,0x1a0(%rcx)\n\t" /* context->Xmm0 */
1796 "movdqa %xmm1,0x1b0(%rcx)\n\t" /* context->Xmm1 */
1797 "movdqa %xmm2,0x1c0(%rcx)\n\t" /* context->Xmm2 */
1798 "movdqa %xmm3,0x1d0(%rcx)\n\t" /* context->Xmm3 */
1799 "movdqa %xmm4,0x1e0(%rcx)\n\t" /* context->Xmm4 */
1800 "movdqa %xmm5,0x1f0(%rcx)\n\t" /* context->Xmm5 */
1801 "movdqa %xmm6,0x200(%rcx)\n\t" /* context->Xmm6 */
1802 "movdqa %xmm7,0x210(%rcx)\n\t" /* context->Xmm7 */
1803 "movdqa %xmm8,0x220(%rcx)\n\t" /* context->Xmm8 */
1804 "movdqa %xmm9,0x230(%rcx)\n\t" /* context->Xmm9 */
1805 "movdqa %xmm10,0x240(%rcx)\n\t" /* context->Xmm10 */
1806 "movdqa %xmm11,0x250(%rcx)\n\t" /* context->Xmm11 */
1807 "movdqa %xmm12,0x260(%rcx)\n\t" /* context->Xmm12 */
1808 "movdqa %xmm13,0x270(%rcx)\n\t" /* context->Xmm13 */
1809 "movdqa %xmm14,0x280(%rcx)\n\t" /* context->Xmm14 */
1810 "movdqa %xmm15,0x290(%rcx)\n\t" /* context->Xmm15 */
1811 "ret" );
1813 /***********************************************************************
1814 * set_full_cpu_context
1816 * Set the new CPU context.
1818 extern void set_full_cpu_context( const CONTEXT *context );
1819 __ASM_GLOBAL_FUNC( set_full_cpu_context,
1820 "subq $40,%rsp\n\t"
1821 __ASM_CFI(".cfi_adjust_cfa_offset 40\n\t")
1822 "ldmxcsr 0x34(%rdi)\n\t" /* context->MxCsr */
1823 "movw 0x38(%rdi),%ax\n\t" /* context->SegCs */
1824 "movq %rax,8(%rsp)\n\t"
1825 "movw 0x42(%rdi),%ax\n\t" /* context->SegSs */
1826 "movq %rax,32(%rsp)\n\t"
1827 "movq 0x44(%rdi),%rax\n\t" /* context->Eflags */
1828 "movq %rax,16(%rsp)\n\t"
1829 "movq 0x80(%rdi),%rcx\n\t" /* context->Rcx */
1830 "movq 0x88(%rdi),%rdx\n\t" /* context->Rdx */
1831 "movq 0x90(%rdi),%rbx\n\t" /* context->Rbx */
1832 "movq 0x98(%rdi),%rax\n\t" /* context->Rsp */
1833 "movq %rax,24(%rsp)\n\t"
1834 "movq 0xa0(%rdi),%rbp\n\t" /* context->Rbp */
1835 "movq 0xa8(%rdi),%rsi\n\t" /* context->Rsi */
1836 "movq 0xb8(%rdi),%r8\n\t" /* context->R8 */
1837 "movq 0xc0(%rdi),%r9\n\t" /* context->R9 */
1838 "movq 0xc8(%rdi),%r10\n\t" /* context->R10 */
1839 "movq 0xd0(%rdi),%r11\n\t" /* context->R11 */
1840 "movq 0xd8(%rdi),%r12\n\t" /* context->R12 */
1841 "movq 0xe0(%rdi),%r13\n\t" /* context->R13 */
1842 "movq 0xe8(%rdi),%r14\n\t" /* context->R14 */
1843 "movq 0xf0(%rdi),%r15\n\t" /* context->R15 */
1844 "movq 0xf8(%rdi),%rax\n\t" /* context->Rip */
1845 "movq %rax,(%rsp)\n\t"
1846 "fxrstor 0x100(%rdi)\n\t" /* context->FtlSave */
1847 "movdqa 0x1a0(%rdi),%xmm0\n\t" /* context->Xmm0 */
1848 "movdqa 0x1b0(%rdi),%xmm1\n\t" /* context->Xmm1 */
1849 "movdqa 0x1c0(%rdi),%xmm2\n\t" /* context->Xmm2 */
1850 "movdqa 0x1d0(%rdi),%xmm3\n\t" /* context->Xmm3 */
1851 "movdqa 0x1e0(%rdi),%xmm4\n\t" /* context->Xmm4 */
1852 "movdqa 0x1f0(%rdi),%xmm5\n\t" /* context->Xmm5 */
1853 "movdqa 0x200(%rdi),%xmm6\n\t" /* context->Xmm6 */
1854 "movdqa 0x210(%rdi),%xmm7\n\t" /* context->Xmm7 */
1855 "movdqa 0x220(%rdi),%xmm8\n\t" /* context->Xmm8 */
1856 "movdqa 0x230(%rdi),%xmm9\n\t" /* context->Xmm9 */
1857 "movdqa 0x240(%rdi),%xmm10\n\t" /* context->Xmm10 */
1858 "movdqa 0x250(%rdi),%xmm11\n\t" /* context->Xmm11 */
1859 "movdqa 0x260(%rdi),%xmm12\n\t" /* context->Xmm12 */
1860 "movdqa 0x270(%rdi),%xmm13\n\t" /* context->Xmm13 */
1861 "movdqa 0x280(%rdi),%xmm14\n\t" /* context->Xmm14 */
1862 "movdqa 0x290(%rdi),%xmm15\n\t" /* context->Xmm15 */
1863 "movq 0x78(%rdi),%rax\n\t" /* context->Rax */
1864 "movq 0xb0(%rdi),%rdi\n\t" /* context->Rdi */
1865 "iretq" );
1868 /***********************************************************************
1869 * set_cpu_context
1871 * Set the new CPU context. Used by NtSetContextThread.
1873 static void set_cpu_context( const CONTEXT *context )
1875 DWORD flags = context->ContextFlags & ~CONTEXT_AMD64;
1876 if (flags & CONTEXT_FULL)
1878 if (!(flags & CONTEXT_CONTROL))
1879 FIXME( "setting partial context (%x) not supported\n", flags );
1880 else
1881 set_full_cpu_context( context );
1886 /***********************************************************************
1887 * copy_context
1889 * Copy a register context according to the flags.
1891 static void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
1893 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
1894 if (flags & CONTEXT_CONTROL)
1896 to->Rbp = from->Rbp;
1897 to->Rip = from->Rip;
1898 to->Rsp = from->Rsp;
1899 to->SegCs = from->SegCs;
1900 to->SegSs = from->SegSs;
1901 to->EFlags = from->EFlags;
1903 if (flags & CONTEXT_INTEGER)
1905 to->Rax = from->Rax;
1906 to->Rcx = from->Rcx;
1907 to->Rdx = from->Rdx;
1908 to->Rbx = from->Rbx;
1909 to->Rsi = from->Rsi;
1910 to->Rdi = from->Rdi;
1911 to->R8 = from->R8;
1912 to->R9 = from->R9;
1913 to->R10 = from->R10;
1914 to->R11 = from->R11;
1915 to->R12 = from->R12;
1916 to->R13 = from->R13;
1917 to->R14 = from->R14;
1918 to->R15 = from->R15;
1920 if (flags & CONTEXT_SEGMENTS)
1922 to->SegDs = from->SegDs;
1923 to->SegEs = from->SegEs;
1924 to->SegFs = from->SegFs;
1925 to->SegGs = from->SegGs;
1927 if (flags & CONTEXT_FLOATING_POINT)
1929 to->MxCsr = from->MxCsr;
1930 to->u.FltSave = from->u.FltSave;
1932 if (flags & CONTEXT_DEBUG_REGISTERS)
1934 to->Dr0 = from->Dr0;
1935 to->Dr1 = from->Dr1;
1936 to->Dr2 = from->Dr2;
1937 to->Dr3 = from->Dr3;
1938 to->Dr6 = from->Dr6;
1939 to->Dr7 = from->Dr7;
1944 /***********************************************************************
1945 * context_to_server
1947 * Convert a register context to the server format.
1949 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1951 DWORD flags = from->ContextFlags & ~CONTEXT_AMD64; /* get rid of CPU id */
1953 memset( to, 0, sizeof(*to) );
1954 to->cpu = CPU_x86_64;
1956 if (flags & CONTEXT_CONTROL)
1958 to->flags |= SERVER_CTX_CONTROL;
1959 to->ctl.x86_64_regs.rbp = from->Rbp;
1960 to->ctl.x86_64_regs.rip = from->Rip;
1961 to->ctl.x86_64_regs.rsp = from->Rsp;
1962 to->ctl.x86_64_regs.cs = from->SegCs;
1963 to->ctl.x86_64_regs.ss = from->SegSs;
1964 to->ctl.x86_64_regs.flags = from->EFlags;
1966 if (flags & CONTEXT_INTEGER)
1968 to->flags |= SERVER_CTX_INTEGER;
1969 to->integer.x86_64_regs.rax = from->Rax;
1970 to->integer.x86_64_regs.rcx = from->Rcx;
1971 to->integer.x86_64_regs.rdx = from->Rdx;
1972 to->integer.x86_64_regs.rbx = from->Rbx;
1973 to->integer.x86_64_regs.rsi = from->Rsi;
1974 to->integer.x86_64_regs.rdi = from->Rdi;
1975 to->integer.x86_64_regs.r8 = from->R8;
1976 to->integer.x86_64_regs.r9 = from->R9;
1977 to->integer.x86_64_regs.r10 = from->R10;
1978 to->integer.x86_64_regs.r11 = from->R11;
1979 to->integer.x86_64_regs.r12 = from->R12;
1980 to->integer.x86_64_regs.r13 = from->R13;
1981 to->integer.x86_64_regs.r14 = from->R14;
1982 to->integer.x86_64_regs.r15 = from->R15;
1984 if (flags & CONTEXT_SEGMENTS)
1986 to->flags |= SERVER_CTX_SEGMENTS;
1987 to->seg.x86_64_regs.ds = from->SegDs;
1988 to->seg.x86_64_regs.es = from->SegEs;
1989 to->seg.x86_64_regs.fs = from->SegFs;
1990 to->seg.x86_64_regs.gs = from->SegGs;
1992 if (flags & CONTEXT_FLOATING_POINT)
1994 to->flags |= SERVER_CTX_FLOATING_POINT;
1995 memcpy( to->fp.x86_64_regs.fpregs, &from->u.FltSave, sizeof(to->fp.x86_64_regs.fpregs) );
1997 if (flags & CONTEXT_DEBUG_REGISTERS)
1999 to->flags |= SERVER_CTX_DEBUG_REGISTERS;
2000 to->debug.x86_64_regs.dr0 = from->Dr0;
2001 to->debug.x86_64_regs.dr1 = from->Dr1;
2002 to->debug.x86_64_regs.dr2 = from->Dr2;
2003 to->debug.x86_64_regs.dr3 = from->Dr3;
2004 to->debug.x86_64_regs.dr6 = from->Dr6;
2005 to->debug.x86_64_regs.dr7 = from->Dr7;
2007 return STATUS_SUCCESS;
2011 /***********************************************************************
2012 * context_from_server
2014 * Convert a register context from the server format.
2016 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
2018 if (from->cpu != CPU_x86_64) return STATUS_INVALID_PARAMETER;
2020 to->ContextFlags = CONTEXT_AMD64;
2021 if (from->flags & SERVER_CTX_CONTROL)
2023 to->ContextFlags |= CONTEXT_CONTROL;
2024 to->Rbp = from->ctl.x86_64_regs.rbp;
2025 to->Rip = from->ctl.x86_64_regs.rip;
2026 to->Rsp = from->ctl.x86_64_regs.rsp;
2027 to->SegCs = from->ctl.x86_64_regs.cs;
2028 to->SegSs = from->ctl.x86_64_regs.ss;
2029 to->EFlags = from->ctl.x86_64_regs.flags;
2032 if (from->flags & SERVER_CTX_INTEGER)
2034 to->ContextFlags |= CONTEXT_INTEGER;
2035 to->Rax = from->integer.x86_64_regs.rax;
2036 to->Rcx = from->integer.x86_64_regs.rcx;
2037 to->Rdx = from->integer.x86_64_regs.rdx;
2038 to->Rbx = from->integer.x86_64_regs.rbx;
2039 to->Rsi = from->integer.x86_64_regs.rsi;
2040 to->Rdi = from->integer.x86_64_regs.rdi;
2041 to->R8 = from->integer.x86_64_regs.r8;
2042 to->R9 = from->integer.x86_64_regs.r9;
2043 to->R10 = from->integer.x86_64_regs.r10;
2044 to->R11 = from->integer.x86_64_regs.r11;
2045 to->R12 = from->integer.x86_64_regs.r12;
2046 to->R13 = from->integer.x86_64_regs.r13;
2047 to->R14 = from->integer.x86_64_regs.r14;
2048 to->R15 = from->integer.x86_64_regs.r15;
2050 if (from->flags & SERVER_CTX_SEGMENTS)
2052 to->ContextFlags |= CONTEXT_SEGMENTS;
2053 to->SegDs = from->seg.x86_64_regs.ds;
2054 to->SegEs = from->seg.x86_64_regs.es;
2055 to->SegFs = from->seg.x86_64_regs.fs;
2056 to->SegGs = from->seg.x86_64_regs.gs;
2058 if (from->flags & SERVER_CTX_FLOATING_POINT)
2060 to->ContextFlags |= CONTEXT_FLOATING_POINT;
2061 memcpy( &to->u.FltSave, from->fp.x86_64_regs.fpregs, sizeof(from->fp.x86_64_regs.fpregs) );
2062 to->MxCsr = to->u.FltSave.MxCsr;
2064 if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
2066 to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
2067 to->Dr0 = from->debug.x86_64_regs.dr0;
2068 to->Dr1 = from->debug.x86_64_regs.dr1;
2069 to->Dr2 = from->debug.x86_64_regs.dr2;
2070 to->Dr3 = from->debug.x86_64_regs.dr3;
2071 to->Dr6 = from->debug.x86_64_regs.dr6;
2072 to->Dr7 = from->debug.x86_64_regs.dr7;
2074 return STATUS_SUCCESS;
2078 /***********************************************************************
2079 * NtSetContextThread (NTDLL.@)
2080 * ZwSetContextThread (NTDLL.@)
2082 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
2084 NTSTATUS ret;
2085 BOOL self;
2087 ret = set_thread_context( handle, context, &self );
2088 if (self && ret == STATUS_SUCCESS) set_cpu_context( context );
2089 return ret;
2093 /***********************************************************************
2094 * NtGetContextThread (NTDLL.@)
2095 * ZwGetContextThread (NTDLL.@)
2097 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
2099 NTSTATUS ret;
2100 DWORD needed_flags = context->ContextFlags;
2101 BOOL self = (handle == GetCurrentThread());
2103 /* debug registers require a server call */
2104 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64)) self = FALSE;
2106 if (!self)
2108 if ((ret = get_thread_context( handle, context, &self ))) return ret;
2109 needed_flags &= ~context->ContextFlags;
2112 if (self && needed_flags)
2114 CONTEXT ctx;
2115 RtlCaptureContext( &ctx );
2116 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
2117 context->ContextFlags |= ctx.ContextFlags & needed_flags;
2119 return STATUS_SUCCESS;
2123 extern void raise_func_trampoline( EXCEPTION_RECORD *rec, CONTEXT *context, raise_func func );
2124 __ASM_GLOBAL_FUNC( raise_func_trampoline,
2125 __ASM_CFI(".cfi_signal_frame\n\t")
2126 __ASM_CFI(".cfi_def_cfa %rbp,160\n\t") /* red zone + rip + rbp + rdi + rsi */
2127 __ASM_CFI(".cfi_rel_offset %rip,24\n\t")
2128 __ASM_CFI(".cfi_rel_offset %rbp,16\n\t")
2129 __ASM_CFI(".cfi_rel_offset %rdi,8\n\t")
2130 __ASM_CFI(".cfi_rel_offset %rsi,0\n\t")
2131 "call *%rdx\n\t"
2132 "int $3")
2134 /***********************************************************************
2135 * setup_exception
2137 * Setup a proper stack frame for the raise function, and modify the
2138 * sigcontext so that the return from the signal handler will call
2139 * the raise function.
2141 static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
2143 struct stack_layout
2145 CONTEXT context;
2146 EXCEPTION_RECORD rec;
2147 ULONG64 rsi;
2148 ULONG64 rdi;
2149 ULONG64 rbp;
2150 ULONG64 rip;
2151 ULONG64 red_zone[16];
2152 } *stack;
2153 ULONG64 *rsp_ptr;
2154 DWORD exception_code = 0;
2156 stack = (struct stack_layout *)(RSP_sig(sigcontext) & ~15);
2158 /* stack sanity checks */
2160 if (is_inside_signal_stack( stack ))
2162 ERR( "nested exception on signal stack in thread %04x eip %016lx esp %016lx stack %p-%p\n",
2163 GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext), (ULONG_PTR)RSP_sig(sigcontext),
2164 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2165 abort_thread(1);
2168 if (stack - 1 > stack || /* check for overflow in subtraction */
2169 (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
2170 (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
2172 WARN( "exception outside of stack limits in thread %04x eip %016lx esp %016lx stack %p-%p\n",
2173 GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext), (ULONG_PTR)RSP_sig(sigcontext),
2174 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2176 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
2178 /* stack overflow on last page, unrecoverable */
2179 UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
2180 ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
2181 diff, GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext),
2182 (ULONG_PTR)RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
2183 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2184 abort_thread(1);
2186 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
2188 /* stack access below stack limit, may be recoverable */
2189 if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
2190 else
2192 UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
2193 ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
2194 diff, GetCurrentThreadId(), (ULONG_PTR)RIP_sig(sigcontext),
2195 (ULONG_PTR)RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
2196 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2197 abort_thread(1);
2201 stack--; /* push the stack_layout structure */
2202 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
2203 VALGRIND_MAKE_MEM_UNDEFINED(stack, sizeof(*stack));
2204 #elif defined(VALGRIND_MAKE_WRITABLE)
2205 VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
2206 #endif
2207 stack->rec.ExceptionRecord = NULL;
2208 stack->rec.ExceptionCode = exception_code;
2209 stack->rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
2210 stack->rec.ExceptionAddress = (void *)RIP_sig(sigcontext);
2211 stack->rec.NumberParameters = 0;
2212 save_context( &stack->context, sigcontext );
2214 /* store return address and %rbp without aligning, so that the offset is fixed */
2215 rsp_ptr = (ULONG64 *)RSP_sig(sigcontext) - 16;
2216 *(--rsp_ptr) = RIP_sig(sigcontext);
2217 *(--rsp_ptr) = RBP_sig(sigcontext);
2218 *(--rsp_ptr) = RDI_sig(sigcontext);
2219 *(--rsp_ptr) = RSI_sig(sigcontext);
2221 /* now modify the sigcontext to return to the raise function */
2222 RIP_sig(sigcontext) = (ULONG_PTR)raise_func_trampoline;
2223 RDI_sig(sigcontext) = (ULONG_PTR)&stack->rec;
2224 RSI_sig(sigcontext) = (ULONG_PTR)&stack->context;
2225 RDX_sig(sigcontext) = (ULONG_PTR)func;
2226 RBP_sig(sigcontext) = (ULONG_PTR)rsp_ptr;
2227 RSP_sig(sigcontext) = (ULONG_PTR)stack;
2228 /* clear single-step, direction, and align check flag */
2229 EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
2231 return &stack->rec;
2235 /***********************************************************************
2236 * get_exception_context
2238 * Get a pointer to the context built by setup_exception.
2240 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
2242 return (CONTEXT *)rec - 1; /* cf. stack_layout structure */
2246 /**********************************************************************
2247 * find_function_info
2249 static RUNTIME_FUNCTION *find_function_info( ULONG64 pc, HMODULE module,
2250 RUNTIME_FUNCTION *func, ULONG size )
2252 int min = 0;
2253 int max = size/sizeof(*func) - 1;
2255 while (min <= max)
2257 int pos = (min + max) / 2;
2258 if ((char *)pc < (char *)module + func[pos].BeginAddress) max = pos - 1;
2259 else if ((char *)pc >= (char *)module + func[pos].EndAddress) min = pos + 1;
2260 else
2262 func += pos;
2263 while (func->UnwindData & 1) /* follow chained entry */
2264 func = (RUNTIME_FUNCTION *)((char *)module + (func->UnwindData & ~1));
2265 return func;
2268 return NULL;
2271 /**********************************************************************
2272 * lookup_function_info
2274 static RUNTIME_FUNCTION *lookup_function_info( ULONG64 pc, ULONG64 *base, LDR_MODULE **module )
2276 RUNTIME_FUNCTION *func = NULL;
2277 struct dynamic_unwind_entry *entry;
2278 ULONG size;
2280 /* PE module or wine module */
2281 if (!LdrFindEntryForAddress( (void *)pc, module ))
2283 *base = (ULONG64)(*module)->BaseAddress;
2284 if ((func = RtlImageDirectoryEntryToData( (*module)->BaseAddress, TRUE,
2285 IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )))
2287 /* lookup in function table */
2288 func = find_function_info( pc, (*module)->BaseAddress, func, size );
2291 else
2293 *module = NULL;
2295 RtlEnterCriticalSection( &dynamic_unwind_section );
2296 LIST_FOR_EACH_ENTRY( entry, &dynamic_unwind_list, struct dynamic_unwind_entry, entry )
2298 if (pc >= entry->base && pc < entry->base + entry->size)
2300 *base = entry->base;
2302 /* use callback or lookup in function table */
2303 if (entry->callback)
2304 func = entry->callback( pc, entry->context );
2305 else
2306 func = find_function_info( pc, (HMODULE)entry->base, entry->table, entry->table_size );
2307 break;
2310 RtlLeaveCriticalSection( &dynamic_unwind_section );
2313 return func;
2316 static DWORD nested_exception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
2317 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
2319 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)) return ExceptionContinueSearch;
2321 /* FIXME */
2322 return ExceptionNestedException;
2325 /**********************************************************************
2326 * call_handler
2328 * Call a single exception handler.
2329 * FIXME: Handle nested exceptions.
2331 static DWORD call_handler( EXCEPTION_RECORD *rec, CONTEXT *context, DISPATCHER_CONTEXT *dispatch )
2333 EXCEPTION_REGISTRATION_RECORD frame;
2334 DWORD res;
2336 frame.Handler = nested_exception_handler;
2337 __wine_push_frame( &frame );
2339 TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
2340 dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
2341 res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, context, dispatch );
2342 TRACE( "handler at %p returned %u\n", dispatch->LanguageHandler, res );
2344 __wine_pop_frame( &frame );
2345 return res;
2349 /**********************************************************************
2350 * call_teb_handler
2352 * Call a single exception handler from the TEB chain.
2353 * FIXME: Handle nested exceptions.
2355 static DWORD call_teb_handler( EXCEPTION_RECORD *rec, CONTEXT *context, DISPATCHER_CONTEXT *dispatch,
2356 EXCEPTION_REGISTRATION_RECORD *teb_frame )
2358 DWORD res;
2360 TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatch=%p)\n",
2361 teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, dispatch );
2362 res = teb_frame->Handler( rec, teb_frame, context, (EXCEPTION_REGISTRATION_RECORD**)dispatch );
2363 TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
2364 return res;
2368 /**********************************************************************
2369 * call_stack_handlers
2371 * Call the stack handlers chain.
2373 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *orig_context )
2375 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
2376 UNWIND_HISTORY_TABLE table;
2377 DISPATCHER_CONTEXT dispatch;
2378 CONTEXT context;
2379 LDR_MODULE *module;
2380 NTSTATUS status;
2382 context = *orig_context;
2383 dispatch.TargetIp = 0;
2384 dispatch.ContextRecord = &context;
2385 dispatch.HistoryTable = &table;
2386 for (;;)
2388 /* FIXME: should use the history table to make things faster */
2390 dispatch.ImageBase = 0;
2391 dispatch.ControlPc = context.Rip;
2392 dispatch.ScopeIndex = 0;
2394 /* first look for PE exception information */
2396 if ((dispatch.FunctionEntry = lookup_function_info( dispatch.ControlPc, &dispatch.ImageBase, &module )))
2398 dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, dispatch.ImageBase,
2399 dispatch.ControlPc, dispatch.FunctionEntry,
2400 &context, &dispatch.HandlerData,
2401 &dispatch.EstablisherFrame, NULL );
2402 goto unwind_done;
2405 /* then look for host system exception information */
2407 if (!module || (module->Flags & LDR_WINE_INTERNAL))
2409 BOOL got_info = FALSE;
2410 struct dwarf_eh_bases bases;
2411 const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(dispatch.ControlPc - 1), &bases );
2413 if (fde)
2415 status = dwarf_virtual_unwind( dispatch.ControlPc, &dispatch.EstablisherFrame, &context,
2416 fde, &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
2417 if (status != STATUS_SUCCESS) return status;
2418 got_info = TRUE;
2420 #ifdef HAVE_LIBUNWIND_H
2421 else
2423 status = libunwind_virtual_unwind( dispatch.ControlPc, &got_info, &dispatch.EstablisherFrame, &context,
2424 &dispatch.LanguageHandler, &dispatch.HandlerData );
2425 if (status != STATUS_SUCCESS) return status;
2427 #endif
2429 if (got_info)
2431 dispatch.FunctionEntry = NULL;
2432 if (dispatch.LanguageHandler && !module)
2434 FIXME( "calling personality routine in system library not supported yet\n" );
2435 dispatch.LanguageHandler = NULL;
2437 goto unwind_done;
2440 else WARN( "exception data not found in %s\n", debugstr_w(module->BaseDllName.Buffer) );
2442 context.Rip = *(ULONG64 *)context.Rsp;
2443 context.Rsp = context.Rsp + sizeof(ULONG64);
2444 dispatch.EstablisherFrame = context.Rsp;
2445 dispatch.LanguageHandler = NULL;
2447 unwind_done:
2448 if (!dispatch.EstablisherFrame) break;
2450 if ((dispatch.EstablisherFrame & 7) ||
2451 dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
2452 dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
2454 ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
2455 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2456 rec->ExceptionFlags |= EH_STACK_INVALID;
2457 break;
2460 if (dispatch.LanguageHandler)
2462 switch (call_handler( rec, orig_context, &dispatch ))
2464 case ExceptionContinueExecution:
2465 if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
2466 return STATUS_SUCCESS;
2467 case ExceptionContinueSearch:
2468 break;
2469 case ExceptionNestedException:
2470 FIXME( "nested exception\n" );
2471 break;
2472 case ExceptionCollidedUnwind: {
2473 ULONG64 frame;
2475 context = *dispatch.ContextRecord;
2476 dispatch.ContextRecord = &context;
2477 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
2478 dispatch.ControlPc, dispatch.FunctionEntry,
2479 &context, NULL, &frame, NULL );
2480 goto unwind_done;
2482 default:
2483 return STATUS_INVALID_DISPOSITION;
2486 /* hack: call wine handlers registered in the tib list */
2487 else while ((ULONG64)teb_frame < context.Rsp)
2489 TRACE( "found wine frame %p rsp %lx handler %p\n",
2490 teb_frame, context.Rsp, teb_frame->Handler );
2491 dispatch.EstablisherFrame = (ULONG64)teb_frame;
2492 switch (call_teb_handler( rec, orig_context, &dispatch, teb_frame ))
2494 case ExceptionContinueExecution:
2495 if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
2496 return STATUS_SUCCESS;
2497 case ExceptionContinueSearch:
2498 break;
2499 case ExceptionNestedException:
2500 FIXME( "nested exception\n" );
2501 break;
2502 case ExceptionCollidedUnwind: {
2503 ULONG64 frame;
2505 context = *dispatch.ContextRecord;
2506 dispatch.ContextRecord = &context;
2507 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
2508 dispatch.ControlPc, dispatch.FunctionEntry,
2509 &context, NULL, &frame, NULL );
2510 teb_frame = teb_frame->Prev;
2511 goto unwind_done;
2513 default:
2514 return STATUS_INVALID_DISPOSITION;
2516 teb_frame = teb_frame->Prev;
2519 if (context.Rsp == (ULONG64)NtCurrentTeb()->Tib.StackBase) break;
2521 return STATUS_UNHANDLED_EXCEPTION;
2525 /*******************************************************************
2526 * raise_exception
2528 * Implementation of NtRaiseException.
2530 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
2532 NTSTATUS status;
2534 if (first_chance)
2536 DWORD c;
2538 TRACE( "code=%x flags=%x addr=%p ip=%lx tid=%04x\n",
2539 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
2540 context->Rip, GetCurrentThreadId() );
2541 for (c = 0; c < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); c++)
2542 TRACE( " info[%d]=%016lx\n", c, rec->ExceptionInformation[c] );
2543 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
2545 if (rec->ExceptionInformation[1] >> 16)
2546 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
2547 rec->ExceptionAddress,
2548 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
2549 else
2550 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
2551 rec->ExceptionAddress,
2552 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
2554 else
2556 TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
2557 context->Rax, context->Rbx, context->Rcx, context->Rdx );
2558 TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
2559 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
2560 TRACE(" r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
2561 context->R8, context->R9, context->R10, context->R11 );
2562 TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
2563 context->R12, context->R13, context->R14, context->R15 );
2565 status = send_debug_event( rec, TRUE, context );
2566 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
2567 return STATUS_SUCCESS;
2569 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
2570 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Rip--;
2572 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
2573 return STATUS_SUCCESS;
2575 if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
2576 return status;
2579 /* last chance exception */
2581 status = send_debug_event( rec, FALSE, context );
2582 if (status != DBG_CONTINUE)
2584 if (rec->ExceptionFlags & EH_STACK_INVALID)
2585 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
2586 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
2587 ERR("Process attempted to continue execution after noncontinuable exception.\n");
2588 else
2589 ERR("Unhandled exception code %x flags %x addr %p\n",
2590 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
2591 NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
2593 return STATUS_SUCCESS;
2597 /**********************************************************************
2598 * raise_segv_exception
2600 static void raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2602 NTSTATUS status;
2604 switch(rec->ExceptionCode)
2606 case EXCEPTION_ACCESS_VIOLATION:
2607 if (rec->NumberParameters == 2)
2609 if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
2610 rec->ExceptionInformation[0], FALSE )))
2611 set_cpu_context( context );
2613 break;
2614 case EXCEPTION_BREAKPOINT:
2615 switch (rec->ExceptionInformation[0])
2617 case 1: /* BREAKPOINT_PRINT */
2618 case 3: /* BREAKPOINT_LOAD_SYMBOLS */
2619 case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
2620 case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
2621 goto done;
2623 break;
2625 status = raise_exception( rec, context, TRUE );
2626 if (status) raise_status( status, rec );
2627 done:
2628 set_cpu_context( context );
2632 /**********************************************************************
2633 * raise_generic_exception
2635 * Generic raise function for exceptions that don't need special treatment.
2637 static void raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2639 NTSTATUS status = raise_exception( rec, context, TRUE );
2640 if (status) raise_status( status, rec );
2641 set_cpu_context( context );
2645 /***********************************************************************
2646 * handle_interrupt
2648 * Handle an interrupt.
2650 static inline BOOL handle_interrupt( unsigned int interrupt, EXCEPTION_RECORD *rec, CONTEXT *context )
2652 switch(interrupt)
2654 case 0x2d:
2655 context->Rip += 3;
2656 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2657 rec->ExceptionAddress = (void *)context->Rip;
2658 rec->NumberParameters = 1;
2659 rec->ExceptionInformation[0] = context->Rax;
2660 return TRUE;
2661 default:
2662 return FALSE;
2667 /**********************************************************************
2668 * segv_handler
2670 * Handler for SIGSEGV and related errors.
2672 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2674 EXCEPTION_RECORD *rec;
2675 ucontext_t *ucontext = sigcontext;
2677 /* check for page fault inside the thread stack */
2678 if (TRAP_sig(ucontext) == TRAP_x86_PAGEFLT &&
2679 (char *)siginfo->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
2680 (char *)siginfo->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
2681 virtual_handle_stack_fault( siginfo->si_addr ))
2683 /* check if this was the last guard page */
2684 if ((char *)siginfo->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
2686 rec = setup_exception( sigcontext, raise_segv_exception );
2687 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2689 return;
2692 rec = setup_exception( sigcontext, raise_segv_exception );
2693 if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
2695 switch(TRAP_sig(ucontext))
2697 case TRAP_x86_OFLOW: /* Overflow exception */
2698 rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2699 break;
2700 case TRAP_x86_BOUND: /* Bound range exception */
2701 rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2702 break;
2703 case TRAP_x86_PRIVINFLT: /* Invalid opcode exception */
2704 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2705 break;
2706 case TRAP_x86_STKFLT: /* Stack fault */
2707 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2708 break;
2709 case TRAP_x86_SEGNPFLT: /* Segment not present exception */
2710 case TRAP_x86_PROTFLT: /* General protection fault */
2711 case TRAP_x86_UNKNOWN: /* Unknown fault code */
2713 CONTEXT *win_context = get_exception_context( rec );
2714 WORD err = ERROR_sig(ucontext);
2715 if ((err & 7) == 2 && handle_interrupt( err >> 3, rec, win_context )) break;
2716 rec->ExceptionCode = err ? EXCEPTION_ACCESS_VIOLATION : EXCEPTION_PRIV_INSTRUCTION;
2717 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2719 break;
2720 case TRAP_x86_PAGEFLT: /* Page fault */
2721 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2722 rec->NumberParameters = 2;
2723 rec->ExceptionInformation[0] = (ERROR_sig(ucontext) & 2) != 0;
2724 rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2725 break;
2726 case TRAP_x86_ALIGNFLT: /* Alignment check exception */
2727 rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2728 break;
2729 default:
2730 ERR( "Got unexpected trap %ld\n", (ULONG_PTR)TRAP_sig(ucontext) );
2731 /* fall through */
2732 case TRAP_x86_NMI: /* NMI interrupt */
2733 case TRAP_x86_DNA: /* Device not available exception */
2734 case TRAP_x86_DOUBLEFLT: /* Double fault exception */
2735 case TRAP_x86_TSSFLT: /* Invalid TSS exception */
2736 case TRAP_x86_MCHK: /* Machine check exception */
2737 case TRAP_x86_CACHEFLT: /* Cache flush exception */
2738 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2739 break;
2743 /**********************************************************************
2744 * trap_handler
2746 * Handler for SIGTRAP.
2748 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2750 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2752 switch (siginfo->si_code)
2754 case TRAP_TRACE: /* Single-step exception */
2755 case 4 /* TRAP_HWBKPT */: /* Hardware breakpoint exception */
2756 rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
2757 break;
2758 case TRAP_BRKPT: /* Breakpoint exception */
2759 rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1; /* back up over the int3 instruction */
2760 /* fall through */
2761 default:
2762 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2763 rec->NumberParameters = 1;
2764 rec->ExceptionInformation[0] = 0;
2765 break;
2769 /**********************************************************************
2770 * fpe_handler
2772 * Handler for SIGFPE.
2774 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2776 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2778 switch (siginfo->si_code)
2780 case FPE_FLTSUB:
2781 rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2782 break;
2783 case FPE_INTDIV:
2784 rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2785 break;
2786 case FPE_INTOVF:
2787 rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2788 break;
2789 case FPE_FLTDIV:
2790 rec->ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO;
2791 break;
2792 case FPE_FLTOVF:
2793 rec->ExceptionCode = EXCEPTION_FLT_OVERFLOW;
2794 break;
2795 case FPE_FLTUND:
2796 rec->ExceptionCode = EXCEPTION_FLT_UNDERFLOW;
2797 break;
2798 case FPE_FLTRES:
2799 rec->ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT;
2800 break;
2801 case FPE_FLTINV:
2802 default:
2803 rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2804 break;
2808 /**********************************************************************
2809 * int_handler
2811 * Handler for SIGINT.
2813 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2815 if (!dispatch_signal(SIGINT))
2817 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2818 rec->ExceptionCode = CONTROL_C_EXIT;
2823 /**********************************************************************
2824 * abrt_handler
2826 * Handler for SIGABRT.
2828 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2830 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2831 rec->ExceptionCode = EXCEPTION_WINE_ASSERTION;
2832 rec->ExceptionFlags = EH_NONCONTINUABLE;
2836 /**********************************************************************
2837 * quit_handler
2839 * Handler for SIGQUIT.
2841 static void quit_handler( int signal, siginfo_t *siginfo, void *ucontext )
2843 abort_thread(0);
2847 /**********************************************************************
2848 * usr1_handler
2850 * Handler for SIGUSR1, used to signal a thread that it got suspended.
2852 static void usr1_handler( int signal, siginfo_t *siginfo, void *ucontext )
2854 CONTEXT context;
2856 save_context( &context, ucontext );
2857 wait_suspend( &context );
2858 restore_context( &context, ucontext );
2862 /***********************************************************************
2863 * __wine_set_signal_handler (NTDLL.@)
2865 int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
2867 if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
2868 if (handlers[sig] != NULL) return -2;
2869 handlers[sig] = wsh;
2870 return 0;
2874 /**********************************************************************
2875 * signal_alloc_thread
2877 NTSTATUS signal_alloc_thread( TEB **teb )
2879 static size_t sigstack_zero_bits;
2880 SIZE_T size;
2881 NTSTATUS status;
2883 if (!sigstack_zero_bits)
2885 size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2886 /* find the first power of two not smaller than min_size */
2887 sigstack_zero_bits = 12;
2888 while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
2889 signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
2890 assert( sizeof(TEB) <= teb_size );
2893 size = 1 << sigstack_zero_bits;
2894 *teb = NULL;
2895 if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)teb, sigstack_zero_bits,
2896 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
2898 (*teb)->Tib.Self = &(*teb)->Tib;
2899 (*teb)->Tib.ExceptionList = (void *)~0UL;
2901 return status;
2905 /**********************************************************************
2906 * signal_free_thread
2908 void signal_free_thread( TEB *teb )
2910 SIZE_T size;
2912 if (teb->DeallocationStack)
2914 size = 0;
2915 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
2917 size = 0;
2918 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2921 #ifdef __APPLE__
2922 /**********************************************************************
2923 * mac_thread_gsbase
2925 static void *mac_thread_gsbase(void)
2927 static int gsbase_offset = -1;
2928 void *ret;
2930 if (gsbase_offset < 0)
2932 /* Search for the array of TLS slots within the pthread data structure.
2933 That's what the macOS pthread implementation uses for gsbase. */
2934 const void* const sentinel1 = (const void*)0x2bffb6b4f11228ae;
2935 const void* const sentinel2 = (const void*)0x0845a7ff6ab76707;
2936 int rc;
2937 pthread_key_t key;
2938 const void** p = (const void**)pthread_self();
2939 int i;
2941 gsbase_offset = 0;
2942 if ((rc = pthread_key_create(&key, NULL)))
2944 ERR("failed to create sentinel key for gsbase search: %d\n", rc);
2945 return NULL;
2948 pthread_setspecific(key, sentinel1);
2950 for (i = key + 1; i < 2000; i++) /* arbitrary limit */
2952 if (p[i] == sentinel1)
2954 pthread_setspecific(key, sentinel2);
2956 if (p[i] == sentinel2)
2958 gsbase_offset = (i - key) * sizeof(*p);
2959 break;
2962 pthread_setspecific(key, sentinel1);
2966 pthread_key_delete(key);
2969 if (gsbase_offset)
2971 ret = (char*)pthread_self() + gsbase_offset;
2972 TRACE("pthread_self() %p + offset 0x%08x -> gsbase %p\n", pthread_self(), gsbase_offset, ret);
2974 else
2976 ret = NULL;
2977 ERR("failed to locate gsbase; won't be able to poke ThreadLocalStoragePointer into pthread TLS; expect crashes\n");
2980 return ret;
2982 #endif
2984 /**********************************************************************
2985 * signal_init_thread
2987 void signal_init_thread( TEB *teb )
2989 const WORD fpu_cw = 0x27f;
2990 stack_t ss;
2992 #if defined __linux__
2993 arch_prctl( ARCH_SET_GS, teb );
2994 #elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
2995 amd64_set_gsbase( teb );
2996 #elif defined(__NetBSD__)
2997 sysarch( X86_64_SET_GSBASE, &teb );
2998 #elif defined (__APPLE__)
2999 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
3001 : "r" (teb->Tib.Self), "n" (FIELD_OFFSET(TEB, Tib.Self)));
3002 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
3004 : "r" (teb->ThreadLocalStoragePointer), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
3006 /* alloc_tls_slot() needs to poke a value to an address relative to each
3007 thread's gsbase. Have each thread record its gsbase pointer into its
3008 TEB so alloc_tls_slot() can find it. */
3009 teb->Reserved5[0] = mac_thread_gsbase();
3010 #else
3011 # error Please define setting %gs for your architecture
3012 #endif
3014 ss.ss_sp = (char *)teb + teb_size;
3015 ss.ss_size = signal_stack_size;
3016 ss.ss_flags = 0;
3017 if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
3019 #ifdef __GNUC__
3020 __asm__ volatile ("fninit; fldcw %0" : : "m" (fpu_cw));
3021 #else
3022 FIXME("FPU setup not implemented for this platform.\n");
3023 #endif
3026 /**********************************************************************
3027 * signal_init_process
3029 void signal_init_process(void)
3031 struct sigaction sig_act;
3033 sig_act.sa_mask = server_block_set;
3034 sig_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
3036 sig_act.sa_sigaction = int_handler;
3037 if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
3038 sig_act.sa_sigaction = fpe_handler;
3039 if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
3040 sig_act.sa_sigaction = abrt_handler;
3041 if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
3042 sig_act.sa_sigaction = quit_handler;
3043 if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
3044 sig_act.sa_sigaction = usr1_handler;
3045 if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
3047 sig_act.sa_sigaction = segv_handler;
3048 if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
3049 if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
3050 #ifdef SIGBUS
3051 if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
3052 #endif
3054 #ifdef SIGTRAP
3055 sig_act.sa_sigaction = trap_handler;
3056 if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
3057 #endif
3058 return;
3060 error:
3061 perror("sigaction");
3062 exit(1);
3066 /**********************************************************************
3067 * RtlAddFunctionTable (NTDLL.@)
3069 BOOLEAN CDECL RtlAddFunctionTable( RUNTIME_FUNCTION *table, DWORD count, DWORD64 addr )
3071 struct dynamic_unwind_entry *entry;
3073 TRACE( "%p %u %lx\n", table, count, addr );
3075 /* NOTE: Windows doesn't check if table is aligned or a NULL pointer */
3077 entry = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*entry) );
3078 if (!entry)
3079 return FALSE;
3081 entry->base = addr;
3082 entry->size = table[count - 1].EndAddress;
3083 entry->table = table;
3084 entry->table_size = count * sizeof(RUNTIME_FUNCTION);
3085 entry->callback = NULL;
3086 entry->context = NULL;
3088 RtlEnterCriticalSection( &dynamic_unwind_section );
3089 list_add_tail( &dynamic_unwind_list, &entry->entry );
3090 RtlLeaveCriticalSection( &dynamic_unwind_section );
3092 return TRUE;
3096 /**********************************************************************
3097 * RtlInstallFunctionTableCallback (NTDLL.@)
3099 BOOLEAN CDECL RtlInstallFunctionTableCallback( DWORD64 table, DWORD64 base, DWORD length,
3100 PGET_RUNTIME_FUNCTION_CALLBACK callback, PVOID context, PCWSTR dll )
3102 struct dynamic_unwind_entry *entry;
3104 TRACE( "%lx %lx %d %p %p %s\n", table, base, length, callback, context, wine_dbgstr_w(dll) );
3106 /* NOTE: Windows doesn't check if the provided callback is a NULL pointer */
3108 /* both low-order bits must be set */
3109 if ((table & 0x3) != 0x3)
3110 return FALSE;
3112 entry = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*entry) );
3113 if (!entry)
3114 return FALSE;
3116 entry->base = base;
3117 entry->size = length;
3118 entry->table = (RUNTIME_FUNCTION *)table;
3119 entry->table_size = 0;
3120 entry->callback = callback;
3121 entry->context = context;
3123 RtlEnterCriticalSection( &dynamic_unwind_section );
3124 list_add_tail( &dynamic_unwind_list, &entry->entry );
3125 RtlLeaveCriticalSection( &dynamic_unwind_section );
3127 return TRUE;
3131 /**********************************************************************
3132 * RtlDeleteFunctionTable (NTDLL.@)
3134 BOOLEAN CDECL RtlDeleteFunctionTable( RUNTIME_FUNCTION *table )
3136 struct dynamic_unwind_entry *entry, *to_free = NULL;
3138 TRACE( "%p\n", table );
3140 RtlEnterCriticalSection( &dynamic_unwind_section );
3141 LIST_FOR_EACH_ENTRY( entry, &dynamic_unwind_list, struct dynamic_unwind_entry, entry )
3143 if (entry->table == table)
3145 to_free = entry;
3146 list_remove( &entry->entry );
3147 break;
3150 RtlLeaveCriticalSection( &dynamic_unwind_section );
3152 if (!to_free)
3153 return FALSE;
3155 RtlFreeHeap( GetProcessHeap(), 0, to_free );
3156 return TRUE;
3160 /**********************************************************************
3161 * RtlLookupFunctionEntry (NTDLL.@)
3163 PRUNTIME_FUNCTION WINAPI RtlLookupFunctionEntry( ULONG64 pc, ULONG64 *base, UNWIND_HISTORY_TABLE *table )
3165 LDR_MODULE *module;
3166 RUNTIME_FUNCTION *func;
3168 /* FIXME: should use the history table to make things faster */
3170 func = lookup_function_info( pc, base, &module );
3171 if (!func)
3173 *base = 0;
3174 if (module)
3175 WARN( "no exception table found in module %p pc %lx\n", module->BaseAddress, pc );
3176 else
3177 WARN( "module not found for %lx\n", pc );
3180 return func;
3183 static ULONG64 get_int_reg( CONTEXT *context, int reg )
3185 return *(&context->Rax + reg);
3188 static void set_int_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, ULONG64 *val )
3190 *(&context->Rax + reg) = *val;
3191 if (ctx_ptr) ctx_ptr->u2.IntegerContext[reg] = val;
3194 static void set_float_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, M128A *val )
3196 *(&context->u.s.Xmm0 + reg) = *val;
3197 if (ctx_ptr) ctx_ptr->u.FloatingContext[reg] = val;
3200 static int get_opcode_size( struct opcode op )
3202 switch (op.code)
3204 case UWOP_ALLOC_LARGE:
3205 return 2 + (op.info != 0);
3206 case UWOP_SAVE_NONVOL:
3207 case UWOP_SAVE_XMM128:
3208 return 2;
3209 case UWOP_SAVE_NONVOL_FAR:
3210 case UWOP_SAVE_XMM128_FAR:
3211 return 3;
3212 default:
3213 return 1;
3217 static BOOL is_inside_epilog( BYTE *pc, ULONG64 base, const RUNTIME_FUNCTION *function )
3219 /* add or lea must be the first instruction, and it must have a rex.W prefix */
3220 if ((pc[0] & 0xf8) == 0x48)
3222 switch (pc[1])
3224 case 0x81: /* add $nnnn,%rsp */
3225 if (pc[0] == 0x48 && pc[2] == 0xc4)
3227 pc += 7;
3228 break;
3230 return FALSE;
3231 case 0x83: /* add $n,%rsp */
3232 if (pc[0] == 0x48 && pc[2] == 0xc4)
3234 pc += 4;
3235 break;
3237 return FALSE;
3238 case 0x8d: /* lea n(reg),%rsp */
3239 if (pc[0] & 0x06) return FALSE; /* rex.RX must be cleared */
3240 if (((pc[2] >> 3) & 7) != 4) return FALSE; /* dest reg mus be %rsp */
3241 if ((pc[2] & 7) == 4) return FALSE; /* no SIB byte allowed */
3242 if ((pc[2] >> 6) == 1) /* 8-bit offset */
3244 pc += 4;
3245 break;
3247 if ((pc[2] >> 6) == 2) /* 32-bit offset */
3249 pc += 7;
3250 break;
3252 return FALSE;
3256 /* now check for various pop instructions */
3258 for (;;)
3260 if ((*pc & 0xf0) == 0x40) pc++; /* rex prefix */
3262 switch (*pc)
3264 case 0x58: /* pop %rax/%r8 */
3265 case 0x59: /* pop %rcx/%r9 */
3266 case 0x5a: /* pop %rdx/%r10 */
3267 case 0x5b: /* pop %rbx/%r11 */
3268 case 0x5c: /* pop %rsp/%r12 */
3269 case 0x5d: /* pop %rbp/%r13 */
3270 case 0x5e: /* pop %rsi/%r14 */
3271 case 0x5f: /* pop %rdi/%r15 */
3272 pc++;
3273 continue;
3274 case 0xc2: /* ret $nn */
3275 case 0xc3: /* ret */
3276 return TRUE;
3277 case 0xe9: /* jmp nnnn */
3278 pc += 5 + *(LONG *)(pc + 1);
3279 if (pc - (BYTE *)base >= function->BeginAddress && pc - (BYTE *)base < function->EndAddress)
3280 continue;
3281 break;
3282 case 0xeb: /* jmp n */
3283 pc += 2 + (signed char)pc[1];
3284 if (pc - (BYTE *)base >= function->BeginAddress && pc - (BYTE *)base < function->EndAddress)
3285 continue;
3286 break;
3287 case 0xf3: /* rep; ret (for amd64 prediction bug) */
3288 return pc[1] == 0xc3;
3290 return FALSE;
3294 /* execute a function epilog, which must have been validated with is_inside_epilog() */
3295 static void interpret_epilog( BYTE *pc, CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
3297 for (;;)
3299 BYTE rex = 0;
3301 if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f; /* rex prefix */
3303 switch (*pc)
3305 case 0x58: /* pop %rax/r8 */
3306 case 0x59: /* pop %rcx/r9 */
3307 case 0x5a: /* pop %rdx/r10 */
3308 case 0x5b: /* pop %rbx/r11 */
3309 case 0x5c: /* pop %rsp/r12 */
3310 case 0x5d: /* pop %rbp/r13 */
3311 case 0x5e: /* pop %rsi/r14 */
3312 case 0x5f: /* pop %rdi/r15 */
3313 set_int_reg( context, ctx_ptr, *pc - 0x58 + (rex & 1) * 8, (ULONG64 *)context->Rsp );
3314 context->Rsp += sizeof(ULONG64);
3315 pc++;
3316 continue;
3317 case 0x81: /* add $nnnn,%rsp */
3318 context->Rsp += *(LONG *)(pc + 2);
3319 pc += 2 + sizeof(LONG);
3320 continue;
3321 case 0x83: /* add $n,%rsp */
3322 context->Rsp += (signed char)pc[2];
3323 pc += 3;
3324 continue;
3325 case 0x8d:
3326 if ((pc[1] >> 6) == 1) /* lea n(reg),%rsp */
3328 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + (signed char)pc[2];
3329 pc += 3;
3331 else /* lea nnnn(reg),%rsp */
3333 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + *(LONG *)(pc + 2);
3334 pc += 2 + sizeof(LONG);
3336 continue;
3337 case 0xc2: /* ret $nn */
3338 context->Rip = *(ULONG64 *)context->Rsp;
3339 context->Rsp += sizeof(ULONG64) + *(WORD *)(pc + 1);
3340 return;
3341 case 0xc3: /* ret */
3342 case 0xf3: /* rep; ret */
3343 context->Rip = *(ULONG64 *)context->Rsp;
3344 context->Rsp += sizeof(ULONG64);
3345 return;
3346 case 0xe9: /* jmp nnnn */
3347 pc += 5 + *(LONG *)(pc + 1);
3348 continue;
3349 case 0xeb: /* jmp n */
3350 pc += 2 + (signed char)pc[1];
3351 continue;
3353 return;
3357 /**********************************************************************
3358 * RtlVirtualUnwind (NTDLL.@)
3360 PVOID WINAPI RtlVirtualUnwind( ULONG type, ULONG64 base, ULONG64 pc,
3361 RUNTIME_FUNCTION *function, CONTEXT *context,
3362 PVOID *data, ULONG64 *frame_ret,
3363 KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
3365 union handler_data *handler_data;
3366 ULONG64 frame, off;
3367 struct UNWIND_INFO *info;
3368 unsigned int i, prolog_offset;
3370 TRACE( "type %x rip %lx rsp %lx\n", type, pc, context->Rsp );
3371 if (TRACE_ON(seh)) dump_unwind_info( base, function );
3373 frame = *frame_ret = context->Rsp;
3374 for (;;)
3376 info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
3377 handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
3379 if (info->version != 1)
3381 FIXME( "unknown unwind info version %u at %p\n", info->version, info );
3382 return NULL;
3385 if (info->frame_reg)
3386 frame = get_int_reg( context, info->frame_reg ) - info->frame_offset * 16;
3388 /* check if in prolog */
3389 if (pc >= base + function->BeginAddress && pc < base + function->BeginAddress + info->prolog)
3391 prolog_offset = pc - base - function->BeginAddress;
3393 else
3395 prolog_offset = ~0;
3396 if (is_inside_epilog( (BYTE *)pc, base, function ))
3398 interpret_epilog( (BYTE *)pc, context, ctx_ptr );
3399 *frame_ret = frame;
3400 return NULL;
3404 for (i = 0; i < info->count; i += get_opcode_size(info->opcodes[i]))
3406 if (prolog_offset < info->opcodes[i].offset) continue; /* skip it */
3408 switch (info->opcodes[i].code)
3410 case UWOP_PUSH_NONVOL: /* pushq %reg */
3411 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)context->Rsp );
3412 context->Rsp += sizeof(ULONG64);
3413 break;
3414 case UWOP_ALLOC_LARGE: /* subq $nn,%rsp */
3415 if (info->opcodes[i].info) context->Rsp += *(DWORD *)&info->opcodes[i+1];
3416 else context->Rsp += *(USHORT *)&info->opcodes[i+1] * 8;
3417 break;
3418 case UWOP_ALLOC_SMALL: /* subq $n,%rsp */
3419 context->Rsp += (info->opcodes[i].info + 1) * 8;
3420 break;
3421 case UWOP_SET_FPREG: /* leaq nn(%rsp),%framereg */
3422 context->Rsp = *frame_ret = frame;
3423 break;
3424 case UWOP_SAVE_NONVOL: /* movq %reg,n(%rsp) */
3425 off = frame + *(USHORT *)&info->opcodes[i+1] * 8;
3426 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)off );
3427 break;
3428 case UWOP_SAVE_NONVOL_FAR: /* movq %reg,nn(%rsp) */
3429 off = frame + *(DWORD *)&info->opcodes[i+1];
3430 set_int_reg( context, ctx_ptr, info->opcodes[i].info, (ULONG64 *)off );
3431 break;
3432 case UWOP_SAVE_XMM128: /* movaps %xmmreg,n(%rsp) */
3433 off = frame + *(USHORT *)&info->opcodes[i+1] * 16;
3434 set_float_reg( context, ctx_ptr, info->opcodes[i].info, (M128A *)off );
3435 break;
3436 case UWOP_SAVE_XMM128_FAR: /* movaps %xmmreg,nn(%rsp) */
3437 off = frame + *(DWORD *)&info->opcodes[i+1];
3438 set_float_reg( context, ctx_ptr, info->opcodes[i].info, (M128A *)off );
3439 break;
3440 case UWOP_PUSH_MACHFRAME:
3441 FIXME( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
3442 break;
3443 default:
3444 FIXME( "unknown code %u\n", info->opcodes[i].code );
3445 break;
3449 if (!(info->flags & UNW_FLAG_CHAININFO)) break;
3450 function = &handler_data->chain; /* restart with the chained info */
3453 /* now pop return address */
3454 context->Rip = *(ULONG64 *)context->Rsp;
3455 context->Rsp += sizeof(ULONG64);
3457 if (!(info->flags & type)) return NULL; /* no matching handler */
3458 if (prolog_offset != ~0) return NULL; /* inside prolog */
3460 *data = &handler_data->handler + 1;
3461 return (char *)base + handler_data->handler;
3464 struct unwind_exception_frame
3466 EXCEPTION_REGISTRATION_RECORD frame;
3467 DISPATCHER_CONTEXT *dispatch;
3470 /**********************************************************************
3471 * unwind_exception_handler
3473 * Handler for exceptions happening while calling an unwind handler.
3475 static DWORD unwind_exception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
3476 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
3478 struct unwind_exception_frame *unwind_frame = (struct unwind_exception_frame *)frame;
3479 DISPATCHER_CONTEXT *dispatch = (DISPATCHER_CONTEXT *)dispatcher;
3481 /* copy the original dispatcher into the current one, except for the TargetIp */
3482 dispatch->ControlPc = unwind_frame->dispatch->ControlPc;
3483 dispatch->ImageBase = unwind_frame->dispatch->ImageBase;
3484 dispatch->FunctionEntry = unwind_frame->dispatch->FunctionEntry;
3485 dispatch->EstablisherFrame = unwind_frame->dispatch->EstablisherFrame;
3486 dispatch->ContextRecord = unwind_frame->dispatch->ContextRecord;
3487 dispatch->LanguageHandler = unwind_frame->dispatch->LanguageHandler;
3488 dispatch->HandlerData = unwind_frame->dispatch->HandlerData;
3489 dispatch->HistoryTable = unwind_frame->dispatch->HistoryTable;
3490 dispatch->ScopeIndex = unwind_frame->dispatch->ScopeIndex;
3491 TRACE( "detected collided unwind\n" );
3492 return ExceptionCollidedUnwind;
3495 /**********************************************************************
3496 * call_unwind_handler
3498 * Call a single unwind handler.
3500 static DWORD call_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch )
3502 struct unwind_exception_frame frame;
3503 DWORD res;
3505 frame.frame.Handler = unwind_exception_handler;
3506 frame.dispatch = dispatch;
3507 __wine_push_frame( &frame.frame );
3509 TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
3510 dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
3511 res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
3512 TRACE( "handler %p returned %x\n", dispatch->LanguageHandler, res );
3514 __wine_pop_frame( &frame.frame );
3516 switch (res)
3518 case ExceptionContinueSearch:
3519 case ExceptionCollidedUnwind:
3520 break;
3521 default:
3522 raise_status( STATUS_INVALID_DISPOSITION, rec );
3523 break;
3526 return res;
3530 /**********************************************************************
3531 * call_teb_unwind_handler
3533 * Call a single unwind handler from the TEB chain.
3535 static DWORD call_teb_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
3536 EXCEPTION_REGISTRATION_RECORD *teb_frame )
3538 DWORD res;
3540 TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatch=%p)\n",
3541 teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, dispatch );
3542 res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, (EXCEPTION_REGISTRATION_RECORD**)dispatch );
3543 TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
3545 switch (res)
3547 case ExceptionContinueSearch:
3548 case ExceptionCollidedUnwind:
3549 break;
3550 default:
3551 raise_status( STATUS_INVALID_DISPOSITION, rec );
3552 break;
3555 return res;
3559 /**********************************************************************
3560 * call_consolidate_callback
3562 * Wrapper function to call a consolidate callback from a fake frame.
3563 * If the callback executes RtlUnwindEx (like for example done in C++ handlers),
3564 * we have to skip all frames which were already processed. To do that we
3565 * trick the unwinding functions into thinking the call came from somewhere
3566 * else. All CFI instructions are either DW_CFA_def_cfa_expression or
3567 * DW_CFA_expression, and the expressions have the following format:
3569 * DW_OP_breg6; sleb128 0x10 | Load %rbp + 0x10
3570 * DW_OP_deref | Get *(%rbp + 0x10) == context
3571 * DW_OP_plus_uconst; uleb128 <OFFSET> | Add offset to get struct member
3572 * [DW_OP_deref] | Dereference, only for CFA
3574 extern void * WINAPI call_consolidate_callback( CONTEXT *context,
3575 void *(CALLBACK *callback)(EXCEPTION_RECORD *),
3576 EXCEPTION_RECORD *rec );
3577 __ASM_GLOBAL_FUNC( call_consolidate_callback,
3578 "pushq %rbp\n\t"
3579 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
3580 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
3581 "movq %rsp,%rbp\n\t"
3582 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
3583 "subq $0x20,%rsp\n\t"
3584 "movq %rcx,0x10(%rbp)\n\t"
3585 __ASM_CFI(".cfi_remember_state\n\t")
3586 __ASM_CFI(".cfi_escape 0x0f,0x07,0x76,0x10,0x06,0x23,0x98,0x01,0x06\n\t") /* CFA */
3587 __ASM_CFI(".cfi_escape 0x10,0x03,0x06,0x76,0x10,0x06,0x23,0x90,0x01\n\t") /* %rbx */
3588 __ASM_CFI(".cfi_escape 0x10,0x04,0x06,0x76,0x10,0x06,0x23,0xa8,0x01\n\t") /* %rsi */
3589 __ASM_CFI(".cfi_escape 0x10,0x05,0x06,0x76,0x10,0x06,0x23,0xb0,0x01\n\t") /* %rdi */
3590 __ASM_CFI(".cfi_escape 0x10,0x06,0x06,0x76,0x10,0x06,0x23,0xa0,0x01\n\t") /* %rbp */
3591 __ASM_CFI(".cfi_escape 0x10,0x0c,0x06,0x76,0x10,0x06,0x23,0xd8,0x01\n\t") /* %r12 */
3592 __ASM_CFI(".cfi_escape 0x10,0x0d,0x06,0x76,0x10,0x06,0x23,0xe0,0x01\n\t") /* %r13 */
3593 __ASM_CFI(".cfi_escape 0x10,0x0e,0x06,0x76,0x10,0x06,0x23,0xe8,0x01\n\t") /* %r14 */
3594 __ASM_CFI(".cfi_escape 0x10,0x0f,0x06,0x76,0x10,0x06,0x23,0xf0,0x01\n\t") /* %r15 */
3595 __ASM_CFI(".cfi_escape 0x10,0x10,0x06,0x76,0x10,0x06,0x23,0xf8,0x01\n\t") /* %rip */
3596 __ASM_CFI(".cfi_escape 0x10,0x17,0x06,0x76,0x10,0x06,0x23,0x80,0x04\n\t") /* %xmm6 */
3597 __ASM_CFI(".cfi_escape 0x10,0x18,0x06,0x76,0x10,0x06,0x23,0x90,0x04\n\t") /* %xmm7 */
3598 __ASM_CFI(".cfi_escape 0x10,0x19,0x06,0x76,0x10,0x06,0x23,0xa0,0x04\n\t") /* %xmm8 */
3599 __ASM_CFI(".cfi_escape 0x10,0x1a,0x06,0x76,0x10,0x06,0x23,0xb0,0x04\n\t") /* %xmm9 */
3600 __ASM_CFI(".cfi_escape 0x10,0x1b,0x06,0x76,0x10,0x06,0x23,0xc0,0x04\n\t") /* %xmm10 */
3601 __ASM_CFI(".cfi_escape 0x10,0x1c,0x06,0x76,0x10,0x06,0x23,0xd0,0x04\n\t") /* %xmm11 */
3602 __ASM_CFI(".cfi_escape 0x10,0x1d,0x06,0x76,0x10,0x06,0x23,0xe0,0x04\n\t") /* %xmm12 */
3603 __ASM_CFI(".cfi_escape 0x10,0x1e,0x06,0x76,0x10,0x06,0x23,0xf0,0x04\n\t") /* %xmm13 */
3604 __ASM_CFI(".cfi_escape 0x10,0x1f,0x06,0x76,0x10,0x06,0x23,0x80,0x05\n\t") /* %xmm14 */
3605 __ASM_CFI(".cfi_escape 0x10,0x20,0x06,0x76,0x10,0x06,0x23,0x90,0x05\n\t") /* %xmm15 */
3606 "movq %r8,%rcx\n\t"
3607 "callq *%rdx\n\t"
3608 __ASM_CFI(".cfi_restore_state\n\t")
3609 "movq %rbp,%rsp\n\t"
3610 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
3611 "popq %rbp\n\t"
3612 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
3613 __ASM_CFI(".cfi_same_value %rbp\n\t")
3614 "ret")
3616 /*******************************************************************
3617 * RtlRestoreContext (NTDLL.@)
3619 void WINAPI RtlRestoreContext( CONTEXT *context, EXCEPTION_RECORD *rec )
3621 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
3623 if (rec && rec->ExceptionCode == STATUS_LONGJUMP && rec->NumberParameters >= 1)
3625 struct MSVCRT_JUMP_BUFFER *jmp = (struct MSVCRT_JUMP_BUFFER *)rec->ExceptionInformation[0];
3626 context->Rbx = jmp->Rbx;
3627 context->Rsp = jmp->Rsp;
3628 context->Rbp = jmp->Rbp;
3629 context->Rsi = jmp->Rsi;
3630 context->Rdi = jmp->Rdi;
3631 context->R12 = jmp->R12;
3632 context->R13 = jmp->R13;
3633 context->R14 = jmp->R14;
3634 context->R15 = jmp->R15;
3635 context->Rip = jmp->Rip;
3636 context->u.s.Xmm6 = jmp->Xmm6;
3637 context->u.s.Xmm7 = jmp->Xmm7;
3638 context->u.s.Xmm8 = jmp->Xmm8;
3639 context->u.s.Xmm9 = jmp->Xmm9;
3640 context->u.s.Xmm10 = jmp->Xmm10;
3641 context->u.s.Xmm11 = jmp->Xmm11;
3642 context->u.s.Xmm12 = jmp->Xmm12;
3643 context->u.s.Xmm13 = jmp->Xmm13;
3644 context->u.s.Xmm14 = jmp->Xmm14;
3645 context->u.s.Xmm15 = jmp->Xmm15;
3647 else if (rec && rec->ExceptionCode == STATUS_UNWIND_CONSOLIDATE && rec->NumberParameters >= 1)
3649 PVOID (CALLBACK *consolidate)(EXCEPTION_RECORD *) = (void *)rec->ExceptionInformation[0];
3650 TRACE( "calling consolidate callback %p (rec=%p)\n", consolidate, rec );
3651 context->Rip = (ULONG64)call_consolidate_callback( context, consolidate, rec );
3654 /* hack: remove no longer accessible TEB frames */
3655 while ((ULONG64)teb_frame < context->Rsp)
3657 TRACE( "removing TEB frame: %p\n", teb_frame );
3658 teb_frame = __wine_pop_frame( teb_frame );
3661 TRACE( "returning to %lx stack %lx\n", context->Rip, context->Rsp );
3662 set_cpu_context( context );
3666 /*******************************************************************
3667 * RtlUnwindEx (NTDLL.@)
3669 void WINAPI RtlUnwindEx( PVOID end_frame, PVOID target_ip, EXCEPTION_RECORD *rec,
3670 PVOID retval, CONTEXT *context, UNWIND_HISTORY_TABLE *table )
3672 EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
3673 EXCEPTION_RECORD record;
3674 DISPATCHER_CONTEXT dispatch;
3675 CONTEXT new_context;
3676 LDR_MODULE *module;
3677 NTSTATUS status;
3678 DWORD i;
3680 RtlCaptureContext( context );
3681 new_context = *context;
3683 /* build an exception record, if we do not have one */
3684 if (!rec)
3686 record.ExceptionCode = STATUS_UNWIND;
3687 record.ExceptionFlags = 0;
3688 record.ExceptionRecord = NULL;
3689 record.ExceptionAddress = (void *)context->Rip;
3690 record.NumberParameters = 0;
3691 rec = &record;
3694 rec->ExceptionFlags |= EH_UNWINDING | (end_frame ? 0 : EH_EXIT_UNWIND);
3696 TRACE( "code=%x flags=%x end_frame=%p target_ip=%p rip=%016lx\n",
3697 rec->ExceptionCode, rec->ExceptionFlags, end_frame, target_ip, context->Rip );
3698 for (i = 0; i < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); i++)
3699 TRACE( " info[%d]=%016lx\n", i, rec->ExceptionInformation[i] );
3700 TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
3701 context->Rax, context->Rbx, context->Rcx, context->Rdx );
3702 TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
3703 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
3704 TRACE(" r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
3705 context->R8, context->R9, context->R10, context->R11 );
3706 TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
3707 context->R12, context->R13, context->R14, context->R15 );
3709 dispatch.EstablisherFrame = context->Rsp;
3710 dispatch.TargetIp = (ULONG64)target_ip;
3711 dispatch.ContextRecord = context;
3712 dispatch.HistoryTable = table;
3714 for (;;)
3716 /* FIXME: should use the history table to make things faster */
3718 dispatch.ImageBase = 0;
3719 dispatch.ScopeIndex = 0;
3720 dispatch.ControlPc = context->Rip;
3722 /* first look for PE exception information */
3724 if ((dispatch.FunctionEntry = lookup_function_info( context->Rip, &dispatch.ImageBase, &module )))
3726 dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_UHANDLER, dispatch.ImageBase,
3727 context->Rip, dispatch.FunctionEntry,
3728 &new_context, &dispatch.HandlerData,
3729 &dispatch.EstablisherFrame, NULL );
3730 goto unwind_done;
3733 /* then look for host system exception information */
3735 if (!module || (module->Flags & LDR_WINE_INTERNAL))
3737 BOOL got_info = FALSE;
3738 struct dwarf_eh_bases bases;
3739 const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context->Rip - 1), &bases );
3741 if (fde)
3743 status = dwarf_virtual_unwind( context->Rip, &dispatch.EstablisherFrame, &new_context, fde,
3744 &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
3745 if (status != STATUS_SUCCESS) raise_status( status, rec );
3746 got_info = TRUE;
3748 #ifdef HAVE_LIBUNWIND_H
3749 else
3751 status = libunwind_virtual_unwind( context->Rip, &got_info, &dispatch.EstablisherFrame, &new_context,
3752 &dispatch.LanguageHandler, &dispatch.HandlerData );
3753 if (status != STATUS_SUCCESS) raise_status( status, rec );
3755 #endif
3757 if (got_info)
3759 dispatch.FunctionEntry = NULL;
3760 if (dispatch.LanguageHandler && !module)
3762 FIXME( "calling personality routine in system library not supported yet\n" );
3763 dispatch.LanguageHandler = NULL;
3765 goto unwind_done;
3768 else WARN( "exception data not found in %s\n", debugstr_w(module->BaseDllName.Buffer) );
3770 /* no exception information, treat as a leaf function */
3772 new_context.Rip = *(ULONG64 *)context->Rsp;
3773 new_context.Rsp = context->Rsp + sizeof(ULONG64);
3774 dispatch.EstablisherFrame = new_context.Rsp;
3775 dispatch.LanguageHandler = NULL;
3777 unwind_done:
3778 if (!dispatch.EstablisherFrame) break;
3780 if (is_inside_signal_stack( (void *)dispatch.EstablisherFrame ))
3782 TRACE( "frame %lx is inside signal stack (%p-%p)\n", dispatch.EstablisherFrame,
3783 get_signal_stack(), (char *)get_signal_stack() + signal_stack_size );
3784 *context = new_context;
3785 continue;
3788 if ((dispatch.EstablisherFrame & 7) ||
3789 dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
3790 dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
3792 ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
3793 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
3794 rec->ExceptionFlags |= EH_STACK_INVALID;
3795 break;
3798 if (dispatch.LanguageHandler)
3800 if (end_frame && (dispatch.EstablisherFrame > (ULONG64)end_frame))
3802 ERR( "invalid end frame %lx/%p\n", dispatch.EstablisherFrame, end_frame );
3803 raise_status( STATUS_INVALID_UNWIND_TARGET, rec );
3805 if (dispatch.EstablisherFrame == (ULONG64)end_frame) rec->ExceptionFlags |= EH_TARGET_UNWIND;
3806 if (call_unwind_handler( rec, &dispatch ) == ExceptionCollidedUnwind)
3808 ULONG64 frame;
3810 *context = new_context = *dispatch.ContextRecord;
3811 dispatch.ContextRecord = context;
3812 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
3813 dispatch.ControlPc, dispatch.FunctionEntry,
3814 &new_context, NULL, &frame, NULL );
3815 rec->ExceptionFlags |= EH_COLLIDED_UNWIND;
3816 goto unwind_done;
3818 rec->ExceptionFlags &= ~EH_COLLIDED_UNWIND;
3820 else /* hack: call builtin handlers registered in the tib list */
3822 DWORD64 backup_frame = dispatch.EstablisherFrame;
3823 while ((ULONG64)teb_frame < new_context.Rsp && (ULONG64)teb_frame < (ULONG64)end_frame)
3825 TRACE( "found builtin frame %p handler %p\n", teb_frame, teb_frame->Handler );
3826 dispatch.EstablisherFrame = (ULONG64)teb_frame;
3827 if (call_teb_unwind_handler( rec, &dispatch, teb_frame ) == ExceptionCollidedUnwind)
3829 ULONG64 frame;
3831 teb_frame = __wine_pop_frame( teb_frame );
3833 *context = new_context = *dispatch.ContextRecord;
3834 dispatch.ContextRecord = context;
3835 RtlVirtualUnwind( UNW_FLAG_NHANDLER, dispatch.ImageBase,
3836 dispatch.ControlPc, dispatch.FunctionEntry,
3837 &new_context, NULL, &frame, NULL );
3838 rec->ExceptionFlags |= EH_COLLIDED_UNWIND;
3839 goto unwind_done;
3841 teb_frame = __wine_pop_frame( teb_frame );
3843 if ((ULONG64)teb_frame == (ULONG64)end_frame && (ULONG64)end_frame < new_context.Rsp) break;
3844 dispatch.EstablisherFrame = backup_frame;
3847 if (dispatch.EstablisherFrame == (ULONG64)end_frame) break;
3848 *context = new_context;
3851 context->Rax = (ULONG64)retval;
3852 context->Rip = (ULONG64)target_ip;
3853 RtlRestoreContext(context, rec);
3857 /*******************************************************************
3858 * RtlUnwind (NTDLL.@)
3860 void WINAPI RtlUnwind( void *frame, void *target_ip, EXCEPTION_RECORD *rec, void *retval )
3862 CONTEXT context;
3863 RtlUnwindEx( frame, target_ip, rec, retval, &context, NULL );
3867 /*******************************************************************
3868 * _local_unwind (NTDLL.@)
3870 void WINAPI _local_unwind( void *frame, void *target_ip )
3872 CONTEXT context;
3873 RtlUnwindEx( frame, target_ip, NULL, NULL, &context, NULL );
3876 /*******************************************************************
3877 * __C_specific_handler (NTDLL.@)
3879 EXCEPTION_DISPOSITION WINAPI __C_specific_handler( EXCEPTION_RECORD *rec,
3880 ULONG64 frame,
3881 CONTEXT *context,
3882 struct _DISPATCHER_CONTEXT *dispatch )
3884 SCOPE_TABLE *table = dispatch->HandlerData;
3885 ULONG i;
3887 TRACE( "%p %lx %p %p\n", rec, frame, context, dispatch );
3888 if (TRACE_ON(seh)) dump_scope_table( dispatch->ImageBase, table );
3890 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
3892 for (i = dispatch->ScopeIndex; i < table->Count; i++)
3894 if (dispatch->ControlPc >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
3895 dispatch->ControlPc < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
3897 TERMINATION_HANDLER handler;
3899 if (table->ScopeRecord[i].JumpTarget) continue;
3901 if (rec->ExceptionFlags & EH_TARGET_UNWIND &&
3902 dispatch->TargetIp >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
3903 dispatch->TargetIp < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
3905 break;
3908 handler = (TERMINATION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
3909 dispatch->ScopeIndex = i+1;
3911 TRACE( "calling __finally %p frame %lx\n", handler, frame );
3912 handler( 1, frame );
3915 return ExceptionContinueSearch;
3918 for (i = dispatch->ScopeIndex; i < table->Count; i++)
3920 if (dispatch->ControlPc >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
3921 dispatch->ControlPc < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
3923 if (!table->ScopeRecord[i].JumpTarget) continue;
3924 if (table->ScopeRecord[i].HandlerAddress != EXCEPTION_EXECUTE_HANDLER)
3926 EXCEPTION_POINTERS ptrs;
3927 PC_LANGUAGE_EXCEPTION_HANDLER filter;
3929 filter = (PC_LANGUAGE_EXCEPTION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
3930 ptrs.ExceptionRecord = rec;
3931 ptrs.ContextRecord = context;
3932 TRACE( "calling filter %p ptrs %p frame %lx\n", filter, &ptrs, frame );
3933 switch (filter( &ptrs, frame ))
3935 case EXCEPTION_EXECUTE_HANDLER:
3936 break;
3937 case EXCEPTION_CONTINUE_SEARCH:
3938 continue;
3939 case EXCEPTION_CONTINUE_EXECUTION:
3940 return ExceptionContinueExecution;
3943 TRACE( "unwinding to target %lx\n", dispatch->ImageBase + table->ScopeRecord[i].JumpTarget );
3944 RtlUnwindEx( (void *)frame, (char *)dispatch->ImageBase + table->ScopeRecord[i].JumpTarget,
3945 rec, 0, dispatch->ContextRecord, dispatch->HistoryTable );
3948 return ExceptionContinueSearch;
3952 /*******************************************************************
3953 * NtRaiseException (NTDLL.@)
3955 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
3957 NTSTATUS status = raise_exception( rec, context, first_chance );
3958 if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
3959 return status;
3963 /***********************************************************************
3964 * RtlRaiseException (NTDLL.@)
3966 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
3968 NTSTATUS status;
3970 rec->ExceptionAddress = (void *)context->Rip;
3971 status = raise_exception( rec, context, TRUE );
3972 if (status != STATUS_SUCCESS) raise_status( status, rec );
3974 __ASM_GLOBAL_FUNC( RtlRaiseException,
3975 "movq %rcx,8(%rsp)\n\t"
3976 "sub $0x4f8,%rsp\n\t"
3977 __ASM_CFI(".cfi_adjust_cfa_offset 0x4f8\n\t")
3978 "leaq 0x20(%rsp),%rcx\n\t"
3979 "call " __ASM_NAME("RtlCaptureContext") "\n\t"
3980 "leaq 0x20(%rsp),%rdx\n\t" /* context pointer */
3981 "movq 0x4f8(%rsp),%rax\n\t" /* return address */
3982 "movq %rax,0xf8(%rdx)\n\t" /* context->Rip */
3983 "leaq 0x500(%rsp),%rax\n\t" /* orig stack pointer */
3984 "movq %rax,0x98(%rdx)\n\t" /* context->Rsp */
3985 "movq (%rax),%rcx\n\t" /* original first parameter */
3986 "movq %rcx,0x80(%rdx)\n\t" /* context->Rcx */
3987 "call " __ASM_NAME("__regs_RtlRaiseException") "\n\t"
3988 "leaq 0x20(%rsp),%rdi\n\t" /* context pointer */
3989 "call " __ASM_NAME("set_full_cpu_context") /* does not return */ );
3992 /*************************************************************************
3993 * RtlCaptureStackBackTrace (NTDLL.@)
3995 USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
3997 FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash );
3998 return 0;
4002 /***********************************************************************
4003 * call_thread_func
4005 void call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
4007 amd64_thread_data()->exit_frame = frame;
4008 __TRY
4010 RtlExitUserThread( entry( arg ));
4012 __EXCEPT(unhandled_exception_filter)
4014 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
4016 __ENDTRY
4017 abort(); /* should not be reached */
4020 extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
4021 __ASM_GLOBAL_FUNC( call_thread_entry_point,
4022 "subq $56,%rsp\n\t"
4023 __ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
4024 "movq %rbp,48(%rsp)\n\t"
4025 __ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
4026 "movq %rbx,40(%rsp)\n\t"
4027 __ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
4028 "movq %r12,32(%rsp)\n\t"
4029 __ASM_CFI(".cfi_rel_offset %r12,32\n\t")
4030 "movq %r13,24(%rsp)\n\t"
4031 __ASM_CFI(".cfi_rel_offset %r13,24\n\t")
4032 "movq %r14,16(%rsp)\n\t"
4033 __ASM_CFI(".cfi_rel_offset %r14,16\n\t")
4034 "movq %r15,8(%rsp)\n\t"
4035 __ASM_CFI(".cfi_rel_offset %r15,8\n\t")
4036 "movq %rsp,%rdx\n\t"
4037 "call " __ASM_NAME("call_thread_func") );
4039 extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
4040 __ASM_GLOBAL_FUNC( call_thread_exit_func,
4041 "movq %rdx,%rsp\n\t"
4042 __ASM_CFI(".cfi_adjust_cfa_offset 56\n\t")
4043 __ASM_CFI(".cfi_rel_offset %rbp,48\n\t")
4044 __ASM_CFI(".cfi_rel_offset %rbx,40\n\t")
4045 __ASM_CFI(".cfi_rel_offset %r12,32\n\t")
4046 __ASM_CFI(".cfi_rel_offset %r13,24\n\t")
4047 __ASM_CFI(".cfi_rel_offset %r14,16\n\t")
4048 __ASM_CFI(".cfi_rel_offset %r15,8\n\t")
4049 "call *%rsi" );
4051 /***********************************************************************
4052 * RtlExitUserThread (NTDLL.@)
4054 void WINAPI RtlExitUserThread( ULONG status )
4056 if (!amd64_thread_data()->exit_frame) exit_thread( status );
4057 call_thread_exit_func( status, exit_thread, amd64_thread_data()->exit_frame );
4060 /***********************************************************************
4061 * abort_thread
4063 void abort_thread( int status )
4065 if (!amd64_thread_data()->exit_frame) terminate_thread( status );
4066 call_thread_exit_func( status, terminate_thread, amd64_thread_data()->exit_frame );
4069 /**********************************************************************
4070 * __wine_enter_vm86 (NTDLL.@)
4072 void __wine_enter_vm86( CONTEXT *context )
4074 MESSAGE("vm86 mode not supported on this platform\n");
4077 /**********************************************************************
4078 * DbgBreakPoint (NTDLL.@)
4080 __ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
4082 /**********************************************************************
4083 * DbgUserBreakPoint (NTDLL.@)
4085 __ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
4087 #endif /* __x86_64__ */