server: Extend get_token_user server call to also retrieve SIDs for the token's owner...
[wine] / dlls / ntdll / signal_x86_64.c
1 /*
2  * x86-64 signal handling routines
3  *
4  * Copyright 1999, 2005 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #ifdef __x86_64__
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <assert.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #ifdef HAVE_SYS_PARAM_H
36 # include <sys/param.h>
37 #endif
38 #ifdef HAVE_SYS_SIGNAL_H
39 # include <sys/signal.h>
40 #endif
41
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "windef.h"
47 #include "winternl.h"
48 #include "wine/library.h"
49 #include "wine/exception.h"
50 #include "ntdll_misc.h"
51 #include "wine/debug.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(seh);
54
55 struct _DISPATCHER_CONTEXT;
56
57 typedef LONG (WINAPI *PC_LANGUAGE_EXCEPTION_HANDLER)( EXCEPTION_POINTERS *ptrs, ULONG64 frame );
58 typedef EXCEPTION_DISPOSITION (WINAPI *PEXCEPTION_ROUTINE)( EXCEPTION_RECORD *rec,
59                                                             ULONG64 frame,
60                                                             CONTEXT *context,
61                                                             struct _DISPATCHER_CONTEXT *dispatch );
62
63 typedef struct _DISPATCHER_CONTEXT
64 {
65     ULONG64               ControlPc;
66     ULONG64               ImageBase;
67     PRUNTIME_FUNCTION     FunctionEntry;
68     ULONG64               EstablisherFrame;
69     ULONG64               TargetIp;
70     PCONTEXT              ContextRecord;
71     PEXCEPTION_ROUTINE    LanguageHandler;
72     PVOID                 HandlerData;
73     PUNWIND_HISTORY_TABLE HistoryTable;
74     ULONG                 ScopeIndex;
75 } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;
76
77 typedef struct _SCOPE_TABLE
78 {
79     ULONG Count;
80     struct
81     {
82         ULONG BeginAddress;
83         ULONG EndAddress;
84         ULONG HandlerAddress;
85         ULONG JumpTarget;
86     } ScopeRecord[1];
87 } SCOPE_TABLE, *PSCOPE_TABLE;
88
89
90 /***********************************************************************
91  * signal context platform-specific definitions
92  */
93 #ifdef linux
94
95 #include <asm/prctl.h>
96 extern int arch_prctl(int func, void *ptr);
97
98 #define RAX_sig(context)     ((context)->uc_mcontext.gregs[REG_RAX])
99 #define RBX_sig(context)     ((context)->uc_mcontext.gregs[REG_RBX])
100 #define RCX_sig(context)     ((context)->uc_mcontext.gregs[REG_RCX])
101 #define RDX_sig(context)     ((context)->uc_mcontext.gregs[REG_RDX])
102 #define RSI_sig(context)     ((context)->uc_mcontext.gregs[REG_RSI])
103 #define RDI_sig(context)     ((context)->uc_mcontext.gregs[REG_RDI])
104 #define RBP_sig(context)     ((context)->uc_mcontext.gregs[REG_RBP])
105 #define R8_sig(context)      ((context)->uc_mcontext.gregs[REG_R8])
106 #define R9_sig(context)      ((context)->uc_mcontext.gregs[REG_R9])
107 #define R10_sig(context)     ((context)->uc_mcontext.gregs[REG_R10])
108 #define R11_sig(context)     ((context)->uc_mcontext.gregs[REG_R11])
109 #define R12_sig(context)     ((context)->uc_mcontext.gregs[REG_R12])
110 #define R13_sig(context)     ((context)->uc_mcontext.gregs[REG_R13])
111 #define R14_sig(context)     ((context)->uc_mcontext.gregs[REG_R14])
112 #define R15_sig(context)     ((context)->uc_mcontext.gregs[REG_R15])
113
114 #define CS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 0))
115 #define GS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 1))
116 #define FS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 2))
117
118 #define RSP_sig(context)     ((context)->uc_mcontext.gregs[REG_RSP])
119 #define RIP_sig(context)     ((context)->uc_mcontext.gregs[REG_RIP])
120 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
121 #define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
122 #define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])
123
124 #define FPU_sig(context)     ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.fpregs))
125
126 #endif /* linux */
127
128 #if defined(__NetBSD__)
129 # include <sys/ucontext.h>
130 # include <sys/types.h>
131 # include <signal.h>
132
133 #define RAX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RAX])
134 #define RBX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RBX])
135 #define RCX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RCX])
136 #define RDX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RDX])
137 #define RSI_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RSI])
138 #define RDI_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RDI])
139 #define RBP_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RBP])
140 #define R8_sig(context)     ((context)->uc_mcontext.__gregs[_REG_R8])
141 #define R9_sig(context)     ((context)->uc_mcontext.__gregs[_REG_R9])
142 #define R10_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R10])
143 #define R11_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R11])
144 #define R12_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R12])
145 #define R13_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R13])
146 #define R14_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R14])
147 #define R15_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R15])
148
149 #define CS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_CS])
150 #define DS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_DS])
151 #define ES_sig(context)     ((context)->uc_mcontext.__gregs[_REG_ES])
152 #define FS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_FS])
153 #define GS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_GS])
154 #define SS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_SS])
155
156 #define EFL_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RFL])
157
158 #define RIP_sig(context)    (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_RIP]))
159 #define RSP_sig(context)    (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_URSP]))
160
161 #define TRAP_sig(context)   ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
162 #define ERROR_sig(context)  ((context)->uc_mcontext.__gregs[_REG_ERR])
163
164 #define FPU_sig(context)   ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.__fpregs))
165 #endif /* __NetBSD__ */
166
167 enum i386_trap_code
168 {
169     TRAP_x86_UNKNOWN    = -1,  /* Unknown fault (TRAP_sig not defined) */
170     TRAP_x86_DIVIDE     = 0,   /* Division by zero exception */
171     TRAP_x86_TRCTRAP    = 1,   /* Single-step exception */
172     TRAP_x86_NMI        = 2,   /* NMI interrupt */
173     TRAP_x86_BPTFLT     = 3,   /* Breakpoint exception */
174     TRAP_x86_OFLOW      = 4,   /* Overflow exception */
175     TRAP_x86_BOUND      = 5,   /* Bound range exception */
176     TRAP_x86_PRIVINFLT  = 6,   /* Invalid opcode exception */
177     TRAP_x86_DNA        = 7,   /* Device not available exception */
178     TRAP_x86_DOUBLEFLT  = 8,   /* Double fault exception */
179     TRAP_x86_FPOPFLT    = 9,   /* Coprocessor segment overrun */
180     TRAP_x86_TSSFLT     = 10,  /* Invalid TSS exception */
181     TRAP_x86_SEGNPFLT   = 11,  /* Segment not present exception */
182     TRAP_x86_STKFLT     = 12,  /* Stack fault */
183     TRAP_x86_PROTFLT    = 13,  /* General protection fault */
184     TRAP_x86_PAGEFLT    = 14,  /* Page fault */
185     TRAP_x86_ARITHTRAP  = 16,  /* Floating point exception */
186     TRAP_x86_ALIGNFLT   = 17,  /* Alignment check exception */
187     TRAP_x86_MCHK       = 18,  /* Machine check exception */
188     TRAP_x86_CACHEFLT   = 19   /* Cache flush exception */
189 };
190
191 static const size_t teb_size = 0x2000;  /* we reserve two pages for the TEB */
192 static size_t signal_stack_size;
193
194 typedef void (*raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
195 typedef int (*wine_signal_handler)(unsigned int sig);
196
197 static wine_signal_handler handlers[256];
198
199
200 /***********************************************************************
201  * Definitions for Win32 unwind tables
202  */
203
204 union handler_data
205 {
206     RUNTIME_FUNCTION chain;
207     ULONG handler;
208 };
209
210 struct opcode
211 {
212     BYTE offset;
213     BYTE code : 4;
214     BYTE info : 4;
215 };
216
217 struct UNWIND_INFO
218 {
219     BYTE version : 3;
220     BYTE flags : 5;
221     BYTE prolog;
222     BYTE count;
223     BYTE frame_reg : 4;
224     BYTE frame_offset : 4;
225     struct opcode opcodes[1];  /* info->count entries */
226     /* followed by handler_data */
227 };
228
229 #define UWOP_PUSH_NONVOL     0
230 #define UWOP_ALLOC_LARGE     1
231 #define UWOP_ALLOC_SMALL     2
232 #define UWOP_SET_FPREG       3
233 #define UWOP_SAVE_NONVOL     4
234 #define UWOP_SAVE_NONVOL_FAR 5
235 #define UWOP_SAVE_XMM128     8
236 #define UWOP_SAVE_XMM128_FAR 9
237 #define UWOP_PUSH_MACHFRAME  10
238
239 static void dump_unwind_info( ULONG64 base, RUNTIME_FUNCTION *function )
240 {
241     static const char * const reg_names[16] =
242         { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
243           "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15" };
244
245     union handler_data *handler_data;
246     struct UNWIND_INFO *info;
247     unsigned int i, count;
248
249     TRACE( "**** func %x-%x\n", function->BeginAddress, function->EndAddress );
250     for (;;)
251     {
252         if (function->UnwindData & 1)
253         {
254             RUNTIME_FUNCTION *next = (RUNTIME_FUNCTION *)((char *)base + (function->UnwindData & ~1));
255             TRACE( "unwind info for function %p-%p chained to function %p-%p\n",
256                    (char *)base + function->BeginAddress, (char *)base + function->EndAddress,
257                    (char *)base + next->BeginAddress, (char *)base + next->EndAddress );
258             function = next;
259             continue;
260         }
261         info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
262
263         TRACE( "unwind info at %p flags %x prolog 0x%x bytes function %p-%p\n",
264                info, info->flags, info->prolog,
265                (char *)base + function->BeginAddress, (char *)base + function->EndAddress );
266
267         if (info->frame_reg)
268             TRACE( "    frame register %s offset 0x%x(%%rsp)\n",
269                    reg_names[info->frame_reg], info->frame_offset * 16 );
270
271         for (i = 0; i < info->count; i++)
272         {
273             TRACE( "    0x%x: ", info->opcodes[i].offset );
274             switch (info->opcodes[i].code)
275             {
276             case UWOP_PUSH_NONVOL:
277                 TRACE( "pushq %%%s\n", reg_names[info->opcodes[i].info] );
278                 break;
279             case UWOP_ALLOC_LARGE:
280                 if (info->opcodes[i].info)
281                 {
282                     count = *(DWORD *)&info->opcodes[i+1];
283                     i += 2;
284                 }
285                 else
286                 {
287                     count = *(USHORT *)&info->opcodes[i+1] * 8;
288                     i++;
289                 }
290                 TRACE( "subq $0x%x,%%rsp\n", count );
291                 break;
292             case UWOP_ALLOC_SMALL:
293                 count = (info->opcodes[i].info + 1) * 8;
294                 TRACE( "subq $0x%x,%%rsp\n", count );
295                 break;
296             case UWOP_SET_FPREG:
297                 TRACE( "leaq 0x%x(%%rsp),%s\n",
298                      info->frame_offset * 16, reg_names[info->frame_reg] );
299                 break;
300             case UWOP_SAVE_NONVOL:
301                 count = *(USHORT *)&info->opcodes[i+1] * 8;
302                 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
303                 i++;
304                 break;
305             case UWOP_SAVE_NONVOL_FAR:
306                 count = *(DWORD *)&info->opcodes[i+1];
307                 TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
308                 i += 2;
309                 break;
310             case UWOP_SAVE_XMM128:
311                 count = *(USHORT *)&info->opcodes[i+1] * 16;
312                 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
313                 i++;
314                 break;
315             case UWOP_SAVE_XMM128_FAR:
316                 count = *(DWORD *)&info->opcodes[i+1];
317                 TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
318                 i += 2;
319                 break;
320             case UWOP_PUSH_MACHFRAME:
321                 TRACE( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
322                 break;
323             default:
324                 FIXME( "unknown code %u\n", info->opcodes[i].code );
325                 break;
326             }
327         }
328
329         handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
330         if (info->flags & UNW_FLAG_CHAININFO)
331         {
332             TRACE( "    chained to function %p-%p\n",
333                    (char *)base + handler_data->chain.BeginAddress,
334                    (char *)base + handler_data->chain.EndAddress );
335             function = &handler_data->chain;
336             continue;
337         }
338         if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
339             TRACE( "    handler %p data at %p\n",
340                    (char *)base + handler_data->handler, &handler_data->handler + 1 );
341         break;
342     }
343 }
344
345 static void dump_scope_table( ULONG64 base, const SCOPE_TABLE *table )
346 {
347     unsigned int i;
348
349     TRACE( "scope table at %p\n", table );
350     for (i = 0; i < table->Count; i++)
351         TRACE( "  %u: %lx-%lx handler %lx target %lx\n", i,
352                base + table->ScopeRecord[i].BeginAddress,
353                base + table->ScopeRecord[i].EndAddress,
354                base + table->ScopeRecord[i].HandlerAddress,
355                base + table->ScopeRecord[i].JumpTarget );
356 }
357
358
359 /***********************************************************************
360  * Definitions for Dwarf unwind tables
361  */
362
363 enum dwarf_call_frame_info
364 {
365     DW_CFA_advance_loc = 0x40,
366     DW_CFA_offset = 0x80,
367     DW_CFA_restore = 0xc0,
368     DW_CFA_nop = 0x00,
369     DW_CFA_set_loc = 0x01,
370     DW_CFA_advance_loc1 = 0x02,
371     DW_CFA_advance_loc2 = 0x03,
372     DW_CFA_advance_loc4 = 0x04,
373     DW_CFA_offset_extended = 0x05,
374     DW_CFA_restore_extended = 0x06,
375     DW_CFA_undefined = 0x07,
376     DW_CFA_same_value = 0x08,
377     DW_CFA_register = 0x09,
378     DW_CFA_remember_state = 0x0a,
379     DW_CFA_restore_state = 0x0b,
380     DW_CFA_def_cfa = 0x0c,
381     DW_CFA_def_cfa_register = 0x0d,
382     DW_CFA_def_cfa_offset = 0x0e,
383     DW_CFA_def_cfa_expression = 0x0f,
384     DW_CFA_expression = 0x10,
385     DW_CFA_offset_extended_sf = 0x11,
386     DW_CFA_def_cfa_sf = 0x12,
387     DW_CFA_def_cfa_offset_sf = 0x13,
388     DW_CFA_val_offset = 0x14,
389     DW_CFA_val_offset_sf = 0x15,
390     DW_CFA_val_expression = 0x16,
391 };
392
393 enum dwarf_operation
394 {
395     DW_OP_addr                 = 0x03,
396     DW_OP_deref                = 0x06,
397     DW_OP_const1u              = 0x08,
398     DW_OP_const1s              = 0x09,
399     DW_OP_const2u              = 0x0a,
400     DW_OP_const2s              = 0x0b,
401     DW_OP_const4u              = 0x0c,
402     DW_OP_const4s              = 0x0d,
403     DW_OP_const8u              = 0x0e,
404     DW_OP_const8s              = 0x0f,
405     DW_OP_constu               = 0x10,
406     DW_OP_consts               = 0x11,
407     DW_OP_dup                  = 0x12,
408     DW_OP_drop                 = 0x13,
409     DW_OP_over                 = 0x14,
410     DW_OP_pick                 = 0x15,
411     DW_OP_swap                 = 0x16,
412     DW_OP_rot                  = 0x17,
413     DW_OP_xderef               = 0x18,
414     DW_OP_abs                  = 0x19,
415     DW_OP_and                  = 0x1a,
416     DW_OP_div                  = 0x1b,
417     DW_OP_minus                = 0x1c,
418     DW_OP_mod                  = 0x1d,
419     DW_OP_mul                  = 0x1e,
420     DW_OP_neg                  = 0x1f,
421     DW_OP_not                  = 0x20,
422     DW_OP_or                   = 0x21,
423     DW_OP_plus                 = 0x22,
424     DW_OP_plus_uconst          = 0x23,
425     DW_OP_shl                  = 0x24,
426     DW_OP_shr                  = 0x25,
427     DW_OP_shra                 = 0x26,
428     DW_OP_xor                  = 0x27,
429     DW_OP_bra                  = 0x28,
430     DW_OP_eq                   = 0x29,
431     DW_OP_ge                   = 0x2a,
432     DW_OP_gt                   = 0x2b,
433     DW_OP_le                   = 0x2c,
434     DW_OP_lt                   = 0x2d,
435     DW_OP_ne                   = 0x2e,
436     DW_OP_skip                 = 0x2f,
437     DW_OP_lit0                 = 0x30,
438     DW_OP_lit1                 = 0x31,
439     DW_OP_lit2                 = 0x32,
440     DW_OP_lit3                 = 0x33,
441     DW_OP_lit4                 = 0x34,
442     DW_OP_lit5                 = 0x35,
443     DW_OP_lit6                 = 0x36,
444     DW_OP_lit7                 = 0x37,
445     DW_OP_lit8                 = 0x38,
446     DW_OP_lit9                 = 0x39,
447     DW_OP_lit10                = 0x3a,
448     DW_OP_lit11                = 0x3b,
449     DW_OP_lit12                = 0x3c,
450     DW_OP_lit13                = 0x3d,
451     DW_OP_lit14                = 0x3e,
452     DW_OP_lit15                = 0x3f,
453     DW_OP_lit16                = 0x40,
454     DW_OP_lit17                = 0x41,
455     DW_OP_lit18                = 0x42,
456     DW_OP_lit19                = 0x43,
457     DW_OP_lit20                = 0x44,
458     DW_OP_lit21                = 0x45,
459     DW_OP_lit22                = 0x46,
460     DW_OP_lit23                = 0x47,
461     DW_OP_lit24                = 0x48,
462     DW_OP_lit25                = 0x49,
463     DW_OP_lit26                = 0x4a,
464     DW_OP_lit27                = 0x4b,
465     DW_OP_lit28                = 0x4c,
466     DW_OP_lit29                = 0x4d,
467     DW_OP_lit30                = 0x4e,
468     DW_OP_lit31                = 0x4f,
469     DW_OP_reg0                 = 0x50,
470     DW_OP_reg1                 = 0x51,
471     DW_OP_reg2                 = 0x52,
472     DW_OP_reg3                 = 0x53,
473     DW_OP_reg4                 = 0x54,
474     DW_OP_reg5                 = 0x55,
475     DW_OP_reg6                 = 0x56,
476     DW_OP_reg7                 = 0x57,
477     DW_OP_reg8                 = 0x58,
478     DW_OP_reg9                 = 0x59,
479     DW_OP_reg10                = 0x5a,
480     DW_OP_reg11                = 0x5b,
481     DW_OP_reg12                = 0x5c,
482     DW_OP_reg13                = 0x5d,
483     DW_OP_reg14                = 0x5e,
484     DW_OP_reg15                = 0x5f,
485     DW_OP_reg16                = 0x60,
486     DW_OP_reg17                = 0x61,
487     DW_OP_reg18                = 0x62,
488     DW_OP_reg19                = 0x63,
489     DW_OP_reg20                = 0x64,
490     DW_OP_reg21                = 0x65,
491     DW_OP_reg22                = 0x66,
492     DW_OP_reg23                = 0x67,
493     DW_OP_reg24                = 0x68,
494     DW_OP_reg25                = 0x69,
495     DW_OP_reg26                = 0x6a,
496     DW_OP_reg27                = 0x6b,
497     DW_OP_reg28                = 0x6c,
498     DW_OP_reg29                = 0x6d,
499     DW_OP_reg30                = 0x6e,
500     DW_OP_reg31                = 0x6f,
501     DW_OP_breg0                = 0x70,
502     DW_OP_breg1                = 0x71,
503     DW_OP_breg2                = 0x72,
504     DW_OP_breg3                = 0x73,
505     DW_OP_breg4                = 0x74,
506     DW_OP_breg5                = 0x75,
507     DW_OP_breg6                = 0x76,
508     DW_OP_breg7                = 0x77,
509     DW_OP_breg8                = 0x78,
510     DW_OP_breg9                = 0x79,
511     DW_OP_breg10               = 0x7a,
512     DW_OP_breg11               = 0x7b,
513     DW_OP_breg12               = 0x7c,
514     DW_OP_breg13               = 0x7d,
515     DW_OP_breg14               = 0x7e,
516     DW_OP_breg15               = 0x7f,
517     DW_OP_breg16               = 0x80,
518     DW_OP_breg17               = 0x81,
519     DW_OP_breg18               = 0x82,
520     DW_OP_breg19               = 0x83,
521     DW_OP_breg20               = 0x84,
522     DW_OP_breg21               = 0x85,
523     DW_OP_breg22               = 0x86,
524     DW_OP_breg23               = 0x87,
525     DW_OP_breg24               = 0x88,
526     DW_OP_breg25               = 0x89,
527     DW_OP_breg26               = 0x8a,
528     DW_OP_breg27               = 0x8b,
529     DW_OP_breg28               = 0x8c,
530     DW_OP_breg29               = 0x8d,
531     DW_OP_breg30               = 0x8e,
532     DW_OP_breg31               = 0x8f,
533     DW_OP_regx                 = 0x90,
534     DW_OP_fbreg                = 0x91,
535     DW_OP_bregx                = 0x92,
536     DW_OP_piece                = 0x93,
537     DW_OP_deref_size           = 0x94,
538     DW_OP_xderef_size          = 0x95,
539     DW_OP_nop                  = 0x96,
540     DW_OP_push_object_address  = 0x97,
541     DW_OP_call2                = 0x98,
542     DW_OP_call4                = 0x99,
543     DW_OP_call_ref             = 0x9a,
544     DW_OP_form_tls_address     = 0x9b,
545     DW_OP_call_frame_cfa       = 0x9c,
546     DW_OP_bit_piece            = 0x9d,
547     DW_OP_lo_user              = 0xe0,
548     DW_OP_hi_user              = 0xff,
549     DW_OP_GNU_push_tls_address = 0xe0,
550     DW_OP_GNU_uninit           = 0xf0,
551     DW_OP_GNU_encoded_addr     = 0xf1,
552 };
553
554 #define DW_EH_PE_native   0x00
555 #define DW_EH_PE_leb128   0x01
556 #define DW_EH_PE_data2    0x02
557 #define DW_EH_PE_data4    0x03
558 #define DW_EH_PE_data8    0x04
559 #define DW_EH_PE_signed   0x08
560 #define DW_EH_PE_abs      0x00
561 #define DW_EH_PE_pcrel    0x10
562 #define DW_EH_PE_textrel  0x20
563 #define DW_EH_PE_datarel  0x30
564 #define DW_EH_PE_funcrel  0x40
565 #define DW_EH_PE_aligned  0x50
566 #define DW_EH_PE_indirect 0x80
567 #define DW_EH_PE_omit     0xff
568
569 struct dwarf_eh_bases
570 {
571     void *tbase;
572     void *dbase;
573     void *func;
574 };
575
576 struct dwarf_cie
577 {
578     unsigned int  length;
579     int           id;
580     unsigned char version;
581     unsigned char augmentation[1];
582 };
583
584 struct dwarf_fde
585 {
586     unsigned int length;
587     unsigned int cie_offset;
588 };
589
590 extern const struct dwarf_fde *_Unwind_Find_FDE (void *, struct dwarf_eh_bases *);
591
592 static unsigned char dwarf_get_u1( const unsigned char **p )
593 {
594     return *(*p)++;
595 }
596
597 static unsigned short dwarf_get_u2( const unsigned char **p )
598 {
599     unsigned int ret = (*p)[0] | ((*p)[1] << 8);
600     (*p) += 2;
601     return ret;
602 }
603
604 static unsigned int dwarf_get_u4( const unsigned char **p )
605 {
606     unsigned int ret = (*p)[0] | ((*p)[1] << 8) | ((*p)[2] << 16) | ((*p)[3] << 24);
607     (*p) += 4;
608     return ret;
609 }
610
611 static ULONG64 dwarf_get_u8( const unsigned char **p )
612 {
613     ULONG64 low  = dwarf_get_u4( p );
614     ULONG64 high = dwarf_get_u4( p );
615     return low | (high << 32);
616 }
617
618 static ULONG_PTR dwarf_get_uleb128( const unsigned char **p )
619 {
620     ULONG_PTR ret = 0;
621     unsigned int shift = 0;
622     unsigned char byte;
623
624     do
625     {
626         byte = **p;
627         ret |= (ULONG_PTR)(byte & 0x7f) << shift;
628         shift += 7;
629         (*p)++;
630     } while (byte & 0x80);
631     return ret;
632 }
633
634 static LONG_PTR dwarf_get_sleb128( const unsigned char **p )
635 {
636     ULONG_PTR ret = 0;
637     unsigned int shift = 0;
638     unsigned char byte;
639
640     do
641     {
642         byte = **p;
643         ret |= (ULONG_PTR)(byte & 0x7f) << shift;
644         shift += 7;
645         (*p)++;
646     } while (byte & 0x80);
647
648     if ((shift < 8 * sizeof(ret)) && (byte & 0x40)) ret |= -((ULONG_PTR)1 << shift);
649     return ret;
650 }
651
652 static ULONG_PTR dwarf_get_ptr( const unsigned char **p, unsigned char encoding )
653 {
654     ULONG_PTR base;
655
656     if (encoding == DW_EH_PE_omit) return 0;
657
658     switch (encoding & 0xf0)
659     {
660     case DW_EH_PE_abs:
661         base = 0;
662         break;
663     case DW_EH_PE_pcrel:
664         base = (ULONG_PTR)*p;
665         break;
666     default:
667         FIXME( "unsupported encoding %02x\n", encoding );
668         return 0;
669     }
670
671     switch (encoding & 0x0f)
672     {
673     case DW_EH_PE_native:
674         return base + dwarf_get_u8( p );
675     case DW_EH_PE_leb128:
676         return base + dwarf_get_uleb128( p );
677     case DW_EH_PE_data2:
678         return base + dwarf_get_u2( p );
679     case DW_EH_PE_data4:
680         return base + dwarf_get_u4( p );
681     case DW_EH_PE_data8:
682         return base + dwarf_get_u8( p );
683     case DW_EH_PE_signed|DW_EH_PE_leb128:
684         return base + dwarf_get_sleb128( p );
685     case DW_EH_PE_signed|DW_EH_PE_data2:
686         return base + (signed short)dwarf_get_u2( p );
687     case DW_EH_PE_signed|DW_EH_PE_data4:
688         return base + (signed int)dwarf_get_u4( p );
689     case DW_EH_PE_signed|DW_EH_PE_data8:
690         return base + (LONG64)dwarf_get_u8( p );
691     default:
692         FIXME( "unsupported encoding %02x\n", encoding );
693         return 0;
694     }
695 }
696
697 enum reg_rule
698 {
699     RULE_UNSET,          /* not set at all */
700     RULE_UNDEFINED,      /* undefined value */
701     RULE_SAME,           /* same value as previous frame */
702     RULE_CFA_OFFSET,     /* stored at cfa offset */
703     RULE_OTHER_REG,      /* stored in other register */
704     RULE_EXPRESSION,     /* address specified by expression */
705     RULE_VAL_EXPRESSION  /* value specified by expression */
706 };
707
708 #define NB_FRAME_REGS 41
709
710 struct frame_info
711 {
712     ULONG_PTR     ip;
713     ULONG_PTR     code_align;
714     LONG_PTR      data_align;
715     ULONG_PTR     cfa_offset;
716     enum reg_rule cfa_rule;
717     unsigned char cfa_reg;
718     unsigned char retaddr_reg;
719     unsigned char fde_encoding;
720     unsigned char signal_frame;
721     enum reg_rule rules[NB_FRAME_REGS];
722     ULONG64       regs[NB_FRAME_REGS];
723 };
724
725 static const char *dwarf_reg_names[NB_FRAME_REGS] =
726 {
727 /*  0-7  */ "%rax", "%rdx", "%rcx", "%rbx", "%rsi", "%rdi", "%rbp", "%rsp",
728 /*  8-16 */ "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "%rip",
729 /* 17-24 */ "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
730 /* 25-32 */ "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15",
731 /* 33-40 */ "%st0", "%st1", "%st2", "%st3", "%st4", "%st5", "%st6", "%st7"
732 };
733
734 static int valid_reg( ULONG_PTR reg )
735 {
736     if (reg >= NB_FRAME_REGS) FIXME( "unsupported reg %lx\n", reg );
737     return (reg < NB_FRAME_REGS);
738 }
739
740 static void execute_cfa_instructions( const unsigned char *ptr, const unsigned char *end,
741                                       ULONG_PTR last_ip, struct frame_info *info )
742 {
743     while (ptr < end && info->ip < last_ip + info->signal_frame)
744     {
745         enum dwarf_call_frame_info op = *ptr++;
746
747         if (op & 0xc0)
748         {
749             switch (op & 0xc0)
750             {
751             case DW_CFA_advance_loc:
752             {
753                 ULONG_PTR offset = (op & 0x3f) * info->code_align;
754                 TRACE( "%lx: DW_CFA_advance_loc %lu\n", info->ip, offset );
755                 info->ip += offset;
756                 break;
757             }
758             case DW_CFA_offset:
759             {
760                 ULONG_PTR reg = op & 0x3f;
761                 LONG_PTR offset = dwarf_get_uleb128( &ptr ) * info->data_align;
762                 if (!valid_reg( reg )) break;
763                 TRACE( "%lx: DW_CFA_offset %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
764                 info->regs[reg]  = offset;
765                 info->rules[reg] = RULE_CFA_OFFSET;
766                 break;
767             }
768             case DW_CFA_restore:
769             {
770                 ULONG_PTR reg = op & 0x3f;
771                 if (!valid_reg( reg )) break;
772                 TRACE( "%lx: DW_CFA_restore %s\n", info->ip, dwarf_reg_names[reg] );
773                 info->rules[reg] = RULE_UNSET;
774                 break;
775             }
776             }
777         }
778         else switch (op)
779         {
780         case DW_CFA_nop:
781             break;
782         case DW_CFA_set_loc:
783         {
784             ULONG_PTR loc = dwarf_get_ptr( &ptr, info->fde_encoding );
785             TRACE( "%lx: DW_CFA_set_loc %lx\n", info->ip, loc );
786             info->ip = loc;
787             break;
788         }
789         case DW_CFA_advance_loc1:
790         {
791             ULONG_PTR offset = *ptr++ * info->code_align;
792             TRACE( "%lx: DW_CFA_advance_loc1 %lu\n", info->ip, offset );
793             info->ip += offset;
794             break;
795         }
796         case DW_CFA_advance_loc2:
797         {
798             ULONG_PTR offset = dwarf_get_u2( &ptr ) * info->code_align;
799             TRACE( "%lx: DW_CFA_advance_loc2 %lu\n", info->ip, offset );
800             info->ip += offset;
801             break;
802         }
803         case DW_CFA_advance_loc4:
804         {
805             ULONG_PTR offset = dwarf_get_u4( &ptr ) * info->code_align;
806             TRACE( "%lx: DW_CFA_advance_loc4 %lu\n", info->ip, offset );
807             info->ip += offset;
808             break;
809         }
810         case DW_CFA_offset_extended:
811         case DW_CFA_offset_extended_sf:
812         {
813             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
814             LONG_PTR offset = (op == DW_CFA_offset_extended) ? dwarf_get_uleb128( &ptr ) * info->data_align
815                                                              : dwarf_get_sleb128( &ptr ) * info->data_align;
816             if (!valid_reg( reg )) break;
817             TRACE( "%lx: DW_CFA_offset_extended %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
818             info->regs[reg]  = offset;
819             info->rules[reg] = RULE_CFA_OFFSET;
820             break;
821         }
822         case DW_CFA_restore_extended:
823         {
824             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
825             if (!valid_reg( reg )) break;
826             TRACE( "%lx: DW_CFA_restore_extended %s\n", info->ip, dwarf_reg_names[reg] );
827             info->rules[reg] = RULE_UNSET;
828             break;
829         }
830         case DW_CFA_undefined:
831         {
832             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
833             if (!valid_reg( reg )) break;
834             TRACE( "%lx: DW_CFA_undefined %s\n", info->ip, dwarf_reg_names[reg] );
835             info->rules[reg] = RULE_UNDEFINED;
836             break;
837         }
838         case DW_CFA_same_value:
839         {
840             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
841             if (!valid_reg( reg )) break;
842             TRACE( "%lx: DW_CFA_same_value %s\n", info->ip, dwarf_reg_names[reg] );
843             info->regs[reg]  = reg;
844             info->rules[reg] = RULE_SAME;
845             break;
846         }
847         case DW_CFA_register:
848         {
849             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
850             ULONG_PTR reg2 = dwarf_get_uleb128( &ptr );
851             if (!valid_reg( reg ) || !valid_reg( reg2 )) break;
852             TRACE( "%lx: DW_CFA_register %s == %s\n", info->ip, dwarf_reg_names[reg], dwarf_reg_names[reg2] );
853             info->regs[reg]  = reg2;
854             info->rules[reg] = RULE_OTHER_REG;
855             break;
856         }
857         case DW_CFA_remember_state:
858             FIXME( "%lx: DW_CFA_remember_state not implemented\n", info->ip );
859             break;
860         case DW_CFA_restore_state:
861             FIXME( "%lx: DW_CFA_restore_state not implemented\n", info->ip );
862             break;
863         case DW_CFA_def_cfa:
864         case DW_CFA_def_cfa_sf:
865         {
866             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
867             ULONG_PTR offset = (op == DW_CFA_def_cfa) ? dwarf_get_uleb128( &ptr )
868                                                       : dwarf_get_sleb128( &ptr ) * info->data_align;
869             if (!valid_reg( reg )) break;
870             TRACE( "%lx: DW_CFA_def_cfa %s, %lu\n", info->ip, dwarf_reg_names[reg], offset );
871             info->cfa_reg    = reg;
872             info->cfa_offset = offset;
873             info->cfa_rule   = RULE_CFA_OFFSET;
874             break;
875         }
876         case DW_CFA_def_cfa_register:
877         {
878             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
879             if (!valid_reg( reg )) break;
880             TRACE( "%lx: DW_CFA_def_cfa_register %s\n", info->ip, dwarf_reg_names[reg] );
881             info->cfa_reg = reg;
882             info->cfa_rule = RULE_CFA_OFFSET;
883             break;
884         }
885         case DW_CFA_def_cfa_offset:
886         case DW_CFA_def_cfa_offset_sf:
887         {
888             ULONG_PTR offset = (op == DW_CFA_def_cfa_offset) ? dwarf_get_uleb128( &ptr )
889                                                              : dwarf_get_sleb128( &ptr ) * info->data_align;
890             TRACE( "%lx: DW_CFA_def_cfa_offset %lu\n", info->ip, offset );
891             info->cfa_offset = offset;
892             info->cfa_rule = RULE_CFA_OFFSET;
893             break;
894         }
895         case DW_CFA_def_cfa_expression:
896         {
897             ULONG_PTR expr = (ULONG_PTR)ptr;
898             ULONG_PTR len = dwarf_get_uleb128( &ptr );
899             TRACE( "%lx: DW_CFA_def_cfa_expression %lx-%lx\n", info->ip, expr, expr+len );
900             info->cfa_offset = expr;
901             info->cfa_rule = RULE_VAL_EXPRESSION;
902             ptr += len;
903             break;
904         }
905         case DW_CFA_expression:
906         case DW_CFA_val_expression:
907         {
908             ULONG_PTR reg = dwarf_get_uleb128( &ptr );
909             ULONG_PTR expr = (ULONG_PTR)ptr;
910             ULONG_PTR len = dwarf_get_uleb128( &ptr );
911             if (!valid_reg( reg )) break;
912             TRACE( "%lx: DW_CFA_%sexpression %s %lx-%lx\n",
913                    info->ip, (op == DW_CFA_expression) ? "" : "val_", dwarf_reg_names[reg], expr, expr+len );
914             info->regs[reg]  = expr;
915             info->rules[reg] = (op == DW_CFA_expression) ? RULE_EXPRESSION : RULE_VAL_EXPRESSION;
916             ptr += len;
917             break;
918         }
919         default:
920             FIXME( "%lx: unknown CFA opcode %02x\n", info->ip, op );
921             break;
922         }
923     }
924 }
925
926 /* retrieve a context register from its dwarf number */
927 static void *get_context_reg( CONTEXT *context, ULONG_PTR dw_reg )
928 {
929     switch (dw_reg)
930     {
931     case 0:  return &context->Rax;
932     case 1:  return &context->Rdx;
933     case 2:  return &context->Rcx;
934     case 3:  return &context->Rbx;
935     case 4:  return &context->Rsi;
936     case 5:  return &context->Rdi;
937     case 6:  return &context->Rbp;
938     case 7:  return &context->Rsp;
939     case 8:  return &context->R8;
940     case 9:  return &context->R9;
941     case 10: return &context->R10;
942     case 11: return &context->R11;
943     case 12: return &context->R12;
944     case 13: return &context->R13;
945     case 14: return &context->R14;
946     case 15: return &context->R15;
947     case 16: return &context->Rip;
948     case 17: return &context->u.s.Xmm0;
949     case 18: return &context->u.s.Xmm1;
950     case 19: return &context->u.s.Xmm2;
951     case 20: return &context->u.s.Xmm3;
952     case 21: return &context->u.s.Xmm4;
953     case 22: return &context->u.s.Xmm5;
954     case 23: return &context->u.s.Xmm6;
955     case 24: return &context->u.s.Xmm7;
956     case 25: return &context->u.s.Xmm8;
957     case 26: return &context->u.s.Xmm9;
958     case 27: return &context->u.s.Xmm10;
959     case 28: return &context->u.s.Xmm11;
960     case 29: return &context->u.s.Xmm12;
961     case 30: return &context->u.s.Xmm13;
962     case 31: return &context->u.s.Xmm14;
963     case 32: return &context->u.s.Xmm15;
964     case 33: return &context->u.s.Legacy[0];
965     case 34: return &context->u.s.Legacy[1];
966     case 35: return &context->u.s.Legacy[2];
967     case 36: return &context->u.s.Legacy[3];
968     case 37: return &context->u.s.Legacy[4];
969     case 38: return &context->u.s.Legacy[5];
970     case 39: return &context->u.s.Legacy[6];
971     case 40: return &context->u.s.Legacy[7];
972     default: return NULL;
973     }
974 }
975
976 /* set a context register from its dwarf number */
977 static void set_context_reg( CONTEXT *context, ULONG_PTR dw_reg, void *val )
978 {
979     switch (dw_reg)
980     {
981     case 0:  context->Rax = *(ULONG64 *)val; break;
982     case 1:  context->Rdx = *(ULONG64 *)val; break;
983     case 2:  context->Rcx = *(ULONG64 *)val; break;
984     case 3:  context->Rbx = *(ULONG64 *)val; break;
985     case 4:  context->Rsi = *(ULONG64 *)val; break;
986     case 5:  context->Rdi = *(ULONG64 *)val; break;
987     case 6:  context->Rbp = *(ULONG64 *)val; break;
988     case 7:  context->Rsp = *(ULONG64 *)val; break;
989     case 8:  context->R8  = *(ULONG64 *)val; break;
990     case 9:  context->R9  = *(ULONG64 *)val; break;
991     case 10: context->R10 = *(ULONG64 *)val; break;
992     case 11: context->R11 = *(ULONG64 *)val; break;
993     case 12: context->R12 = *(ULONG64 *)val; break;
994     case 13: context->R13 = *(ULONG64 *)val; break;
995     case 14: context->R14 = *(ULONG64 *)val; break;
996     case 15: context->R15 = *(ULONG64 *)val; break;
997     case 16: context->Rip = *(ULONG64 *)val; break;
998     case 17: context->u.s.Xmm0  = *(M128A *)val; break;
999     case 18: context->u.s.Xmm1  = *(M128A *)val; break;
1000     case 19: context->u.s.Xmm2  = *(M128A *)val; break;
1001     case 20: context->u.s.Xmm3  = *(M128A *)val; break;
1002     case 21: context->u.s.Xmm4  = *(M128A *)val; break;
1003     case 22: context->u.s.Xmm5  = *(M128A *)val; break;
1004     case 23: context->u.s.Xmm6  = *(M128A *)val; break;
1005     case 24: context->u.s.Xmm7  = *(M128A *)val; break;
1006     case 25: context->u.s.Xmm8  = *(M128A *)val; break;
1007     case 26: context->u.s.Xmm9  = *(M128A *)val; break;
1008     case 27: context->u.s.Xmm10 = *(M128A *)val; break;
1009     case 28: context->u.s.Xmm11 = *(M128A *)val; break;
1010     case 29: context->u.s.Xmm12 = *(M128A *)val; break;
1011     case 30: context->u.s.Xmm13 = *(M128A *)val; break;
1012     case 31: context->u.s.Xmm14 = *(M128A *)val; break;
1013     case 32: context->u.s.Xmm15 = *(M128A *)val; break;
1014     case 33: context->u.s.Legacy[0] = *(M128A *)val; break;
1015     case 34: context->u.s.Legacy[1] = *(M128A *)val; break;
1016     case 35: context->u.s.Legacy[2] = *(M128A *)val; break;
1017     case 36: context->u.s.Legacy[3] = *(M128A *)val; break;
1018     case 37: context->u.s.Legacy[4] = *(M128A *)val; break;
1019     case 38: context->u.s.Legacy[5] = *(M128A *)val; break;
1020     case 39: context->u.s.Legacy[6] = *(M128A *)val; break;
1021     case 40: context->u.s.Legacy[7] = *(M128A *)val; break;
1022     }
1023 }
1024
1025 static ULONG_PTR eval_expression( const unsigned char *p, CONTEXT *context )
1026 {
1027     ULONG_PTR reg, tmp, stack[64];
1028     int sp = -1;
1029     ULONG_PTR len = dwarf_get_uleb128(&p);
1030     const unsigned char *end = p + len;
1031
1032     while (p < end)
1033     {
1034         unsigned char opcode = dwarf_get_u1(&p);
1035
1036         if (opcode >= DW_OP_lit0 && opcode <= DW_OP_lit31)
1037             stack[++sp] = opcode - DW_OP_lit0;
1038         else if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31)
1039             stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_reg0 );
1040         else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31)
1041             stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_breg0 ) + dwarf_get_sleb128(&p);
1042         else switch (opcode)
1043         {
1044         case DW_OP_nop:         break;
1045         case DW_OP_addr:        stack[++sp] = dwarf_get_u8(&p); break;
1046         case DW_OP_const1u:     stack[++sp] = dwarf_get_u1(&p); break;
1047         case DW_OP_const1s:     stack[++sp] = (signed char)dwarf_get_u1(&p); break;
1048         case DW_OP_const2u:     stack[++sp] = dwarf_get_u2(&p); break;
1049         case DW_OP_const2s:     stack[++sp] = (short)dwarf_get_u2(&p); break;
1050         case DW_OP_const4u:     stack[++sp] = dwarf_get_u4(&p); break;
1051         case DW_OP_const4s:     stack[++sp] = (signed int)dwarf_get_u4(&p); break;
1052         case DW_OP_const8u:     stack[++sp] = dwarf_get_u8(&p); break;
1053         case DW_OP_const8s:     stack[++sp] = (LONG_PTR)dwarf_get_u8(&p); break;
1054         case DW_OP_constu:      stack[++sp] = dwarf_get_uleb128(&p); break;
1055         case DW_OP_consts:      stack[++sp] = dwarf_get_sleb128(&p); break;
1056         case DW_OP_deref:       stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1057         case DW_OP_dup:         stack[sp + 1] = stack[sp]; sp++; break;
1058         case DW_OP_drop:        sp--; break;
1059         case DW_OP_over:        stack[sp + 1] = stack[sp - 1]; sp++; break;
1060         case DW_OP_pick:        stack[sp + 1] = stack[sp - dwarf_get_u1(&p)]; sp++; break;
1061         case DW_OP_swap:        tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = tmp; break;
1062         case DW_OP_rot:         tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = stack[sp-2]; stack[sp-2] = tmp; break;
1063         case DW_OP_abs:         stack[sp] = labs(stack[sp]); break;
1064         case DW_OP_neg:         stack[sp] = -stack[sp]; break;
1065         case DW_OP_not:         stack[sp] = ~stack[sp]; break;
1066         case DW_OP_and:         stack[sp-1] &= stack[sp]; sp--; break;
1067         case DW_OP_or:          stack[sp-1] |= stack[sp]; sp--; break;
1068         case DW_OP_minus:       stack[sp-1] -= stack[sp]; sp--; break;
1069         case DW_OP_mul:         stack[sp-1] *= stack[sp]; sp--; break;
1070         case DW_OP_plus:        stack[sp-1] += stack[sp]; sp--; break;
1071         case DW_OP_xor:         stack[sp-1] ^= stack[sp]; sp--; break;
1072         case DW_OP_shl:         stack[sp-1] <<= stack[sp]; sp--; break;
1073         case DW_OP_shr:         stack[sp-1] >>= stack[sp]; sp--; break;
1074         case DW_OP_plus_uconst: stack[sp] += dwarf_get_uleb128(&p); break;
1075         case DW_OP_shra:        stack[sp-1] = (LONG_PTR)stack[sp-1] / (1 << stack[sp]); sp--; break;
1076         case DW_OP_div:         stack[sp-1] = (LONG_PTR)stack[sp-1] / (LONG_PTR)stack[sp]; sp--; break;
1077         case DW_OP_mod:         stack[sp-1] = (LONG_PTR)stack[sp-1] % (LONG_PTR)stack[sp]; sp--; break;
1078         case DW_OP_ge:          stack[sp-1] = ((LONG_PTR)stack[sp-1] >= (LONG_PTR)stack[sp]); sp--; break;
1079         case DW_OP_gt:          stack[sp-1] = ((LONG_PTR)stack[sp-1] >  (LONG_PTR)stack[sp]); sp--; break;
1080         case DW_OP_le:          stack[sp-1] = ((LONG_PTR)stack[sp-1] <= (LONG_PTR)stack[sp]); sp--; break;
1081         case DW_OP_lt:          stack[sp-1] = ((LONG_PTR)stack[sp-1] <  (LONG_PTR)stack[sp]); sp--; break;
1082         case DW_OP_eq:          stack[sp-1] = (stack[sp-1] == stack[sp]); sp--; break;
1083         case DW_OP_ne:          stack[sp-1] = (stack[sp-1] != stack[sp]); sp--; break;
1084         case DW_OP_skip:        tmp = (short)dwarf_get_u2(&p); p += tmp; break;
1085         case DW_OP_bra:         tmp = (short)dwarf_get_u2(&p); if (!stack[sp--]) p += tmp; break;
1086         case DW_OP_GNU_encoded_addr: tmp = *p++; stack[++sp] = dwarf_get_ptr( &p, tmp ); break;
1087         case DW_OP_regx:        stack[++sp] = *(ULONG_PTR *)get_context_reg( context, dwarf_get_uleb128(&p) ); break;
1088         case DW_OP_bregx:
1089             reg = dwarf_get_uleb128(&p);
1090             tmp = dwarf_get_sleb128(&p);
1091             stack[++sp] = *(ULONG_PTR *)get_context_reg( context, reg ) + tmp;
1092             break;
1093         case DW_OP_deref_size:
1094             switch (*p++)
1095             {
1096             case 1: stack[sp] = *(unsigned char *)stack[sp]; break;
1097             case 2: stack[sp] = *(unsigned short *)stack[sp]; break;
1098             case 4: stack[sp] = *(unsigned int *)stack[sp]; break;
1099             case 8: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
1100             }
1101             break;
1102         default:
1103             FIXME( "unhandled opcode %02x\n", opcode );
1104         }
1105     }
1106     return stack[sp];
1107 }
1108
1109 /* apply the computed frame info to the actual context */
1110 static void apply_frame_info( CONTEXT *context, struct frame_info *info )
1111 {
1112     unsigned int i;
1113     ULONG_PTR cfa, value;
1114     CONTEXT new_context = *context;
1115
1116     switch (info->cfa_rule)
1117     {
1118     case RULE_EXPRESSION:
1119         cfa = *(ULONG_PTR *)eval_expression( (const unsigned char *)info->cfa_offset, context );
1120         break;
1121     case RULE_VAL_EXPRESSION:
1122         cfa = eval_expression( (const unsigned char *)info->cfa_offset, context );
1123         break;
1124     default:
1125         cfa = *(ULONG_PTR *)get_context_reg( context, info->cfa_reg ) + info->cfa_offset;
1126         break;
1127     }
1128     if (!cfa) return;
1129
1130     for (i = 0; i < NB_FRAME_REGS; i++)
1131     {
1132         switch (info->rules[i])
1133         {
1134         case RULE_UNSET:
1135         case RULE_UNDEFINED:
1136         case RULE_SAME:
1137             break;
1138         case RULE_CFA_OFFSET:
1139             set_context_reg( &new_context, i, (char *)cfa + info->regs[i] );
1140             break;
1141         case RULE_OTHER_REG:
1142             set_context_reg( &new_context, i, get_context_reg( context, info->regs[i] ));
1143             break;
1144         case RULE_EXPRESSION:
1145             value = eval_expression( (const unsigned char *)info->regs[i], context );
1146             set_context_reg( &new_context, i, (void *)value );
1147             break;
1148         case RULE_VAL_EXPRESSION:
1149             value = eval_expression( (const unsigned char *)info->regs[i], context );
1150             set_context_reg( &new_context, i, &value );
1151             break;
1152         }
1153     }
1154     new_context.Rsp = cfa;
1155     *context = new_context;
1156 }
1157
1158
1159 /***********************************************************************
1160  *           dwarf_virtual_unwind
1161  *
1162  * Equivalent of RtlVirtualUnwind for builtin modules.
1163  */
1164 static NTSTATUS dwarf_virtual_unwind( ULONG64 ip, ULONG64 *frame,CONTEXT *context,
1165                                       const struct dwarf_fde *fde, const struct dwarf_eh_bases *bases,
1166                                       PEXCEPTION_ROUTINE *handler, void **handler_data )
1167 {
1168     const struct dwarf_cie *cie;
1169     const unsigned char *ptr, *augmentation, *end;
1170     ULONG_PTR len, code_end;
1171     struct frame_info info;
1172     int aug_z_format = 0;
1173     unsigned char lsda_encoding = DW_EH_PE_omit;
1174
1175     memset( &info, 0, sizeof(info) );
1176     info.ip = (ULONG_PTR)bases->func;
1177     *handler = NULL;
1178
1179     cie = (const struct dwarf_cie *)((const char *)&fde->cie_offset - fde->cie_offset);
1180
1181     /* parse the CIE first */
1182
1183     if (cie->version != 1)
1184     {
1185         FIXME( "unknown CIE version %u at %p\n", cie->version, cie );
1186         return STATUS_INVALID_DISPOSITION;
1187     }
1188     ptr = cie->augmentation + strlen((const char *)cie->augmentation) + 1;
1189
1190     info.code_align = dwarf_get_uleb128( &ptr );
1191     info.data_align = dwarf_get_sleb128( &ptr );
1192     info.retaddr_reg = *ptr++;
1193     info.cfa_rule = RULE_CFA_OFFSET;
1194
1195     TRACE( "function %lx base %p cie %p len %x id %x version %x aug '%s' code_align %lu data_align %ld retaddr %s\n",
1196            ip, bases->func, cie, cie->length, cie->id, cie->version, cie->augmentation,
1197            info.code_align, info.data_align, dwarf_reg_names[info.retaddr_reg] );
1198
1199     end = NULL;
1200     for (augmentation = cie->augmentation; *augmentation; augmentation++)
1201     {
1202         switch (*augmentation)
1203         {
1204         case 'z':
1205             len = dwarf_get_uleb128( &ptr );
1206             end = ptr + len;
1207             aug_z_format = 1;
1208             continue;
1209         case 'L':
1210             lsda_encoding = *ptr++;
1211             continue;
1212         case 'P':
1213         {
1214             unsigned char encoding = *ptr++;
1215             *handler = (void *)dwarf_get_ptr( &ptr, encoding );
1216             continue;
1217         }
1218         case 'R':
1219             info.fde_encoding = *ptr++;
1220             continue;
1221         case 'S':
1222             info.signal_frame = 1;
1223             continue;
1224         }
1225         FIXME( "unknown augmentation '%c'\n", *augmentation );
1226         if (!end) return STATUS_INVALID_DISPOSITION;  /* cannot continue */
1227         break;
1228     }
1229     if (end) ptr = end;
1230
1231     end = (const unsigned char *)(&cie->length + 1) + cie->length;
1232     execute_cfa_instructions( ptr, end, ip, &info );
1233
1234     ptr = (const unsigned char *)(fde + 1);
1235     info.ip = dwarf_get_ptr( &ptr, info.fde_encoding );  /* fde code start */
1236     code_end = info.ip + dwarf_get_ptr( &ptr, info.fde_encoding & 0x0f );  /* fde code length */
1237
1238     if (aug_z_format)  /* get length of augmentation data */
1239     {
1240         len = dwarf_get_uleb128( &ptr );
1241         end = ptr + len;
1242     }
1243     else end = NULL;
1244
1245     *handler_data = (void *)dwarf_get_ptr( &ptr, lsda_encoding );
1246     if (end) ptr = end;
1247
1248     end = (const unsigned char *)(&fde->length + 1) + fde->length;
1249     TRACE( "fde %p len %x personality %p lsda %p code %lx-%lx\n",
1250            fde, fde->length, *handler, *handler_data, info.ip, code_end );
1251     execute_cfa_instructions( ptr, end, ip, &info );
1252     apply_frame_info( context, &info );
1253     *frame = context->Rsp;
1254
1255     TRACE( "next function rip=%016lx\n", context->Rip );
1256     TRACE( "  rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1257            context->Rax, context->Rbx, context->Rcx, context->Rdx );
1258     TRACE( "  rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1259            context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1260     TRACE( "   r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
1261            context->R8, context->R9, context->R10, context->R11 );
1262     TRACE( "  r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1263            context->R12, context->R13, context->R14, context->R15 );
1264
1265     return STATUS_SUCCESS;
1266 }
1267
1268
1269 /***********************************************************************
1270  *           dispatch_signal
1271  */
1272 static inline int dispatch_signal(unsigned int sig)
1273 {
1274     if (handlers[sig] == NULL) return 0;
1275     return handlers[sig](sig);
1276 }
1277
1278 /***********************************************************************
1279  *           get_signal_stack
1280  *
1281  * Get the base of the signal stack for the current thread.
1282  */
1283 static inline void *get_signal_stack(void)
1284 {
1285     return (char *)NtCurrentTeb() + teb_size;
1286 }
1287
1288 /***********************************************************************
1289  *           is_inside_signal_stack
1290  *
1291  * Check if pointer is inside the signal stack.
1292  */
1293 static inline int is_inside_signal_stack( void *ptr )
1294 {
1295     return ((char *)ptr >= (char *)get_signal_stack() &&
1296             (char *)ptr < (char *)get_signal_stack() + signal_stack_size);
1297 }
1298
1299 /***********************************************************************
1300  *           save_context
1301  *
1302  * Set the register values from a sigcontext.
1303  */
1304 static void save_context( CONTEXT *context, const ucontext_t *sigcontext )
1305 {
1306     context->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
1307     context->Rax    = RAX_sig(sigcontext);
1308     context->Rcx    = RCX_sig(sigcontext);
1309     context->Rdx    = RDX_sig(sigcontext);
1310     context->Rbx    = RBX_sig(sigcontext);
1311     context->Rsp    = RSP_sig(sigcontext);
1312     context->Rbp    = RBP_sig(sigcontext);
1313     context->Rsi    = RSI_sig(sigcontext);
1314     context->Rdi    = RDI_sig(sigcontext);
1315     context->R8     = R8_sig(sigcontext);
1316     context->R9     = R9_sig(sigcontext);
1317     context->R10    = R10_sig(sigcontext);
1318     context->R11    = R11_sig(sigcontext);
1319     context->R12    = R12_sig(sigcontext);
1320     context->R13    = R13_sig(sigcontext);
1321     context->R14    = R14_sig(sigcontext);
1322     context->R15    = R15_sig(sigcontext);
1323     context->Rip    = RIP_sig(sigcontext);
1324     context->SegCs  = CS_sig(sigcontext);
1325     context->SegFs  = FS_sig(sigcontext);
1326     context->SegGs  = GS_sig(sigcontext);
1327     context->EFlags = EFL_sig(sigcontext);
1328 #ifdef DS_sig
1329     context->SegDs  = DS_sig(sigcontext);
1330 #else
1331     __asm__("movw %%ds,%0" : "=m" (context->SegDs));
1332 #endif
1333 #ifdef ES_sig
1334     context->SegEs  = ES_sig(sigcontext);
1335 #else
1336     __asm__("movw %%es,%0" : "=m" (context->SegEs));
1337 #endif
1338 #ifdef SS_sig
1339     context->SegSs  = SS_sig(sigcontext);
1340 #else
1341     __asm__("movw %%ss,%0" : "=m" (context->SegSs));
1342 #endif
1343     if (FPU_sig(sigcontext))
1344     {
1345         context->ContextFlags |= CONTEXT_FLOATING_POINT;
1346         context->u.FltSave = *FPU_sig(sigcontext);
1347         context->MxCsr = context->u.FltSave.MxCsr;
1348     }
1349 }
1350
1351
1352 /***********************************************************************
1353  *           restore_context
1354  *
1355  * Build a sigcontext from the register values.
1356  */
1357 static void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1358 {
1359     RAX_sig(sigcontext) = context->Rax;
1360     RCX_sig(sigcontext) = context->Rcx;
1361     RDX_sig(sigcontext) = context->Rdx;
1362     RBX_sig(sigcontext) = context->Rbx;
1363     RSP_sig(sigcontext) = context->Rsp;
1364     RBP_sig(sigcontext) = context->Rbp;
1365     RSI_sig(sigcontext) = context->Rsi;
1366     RDI_sig(sigcontext) = context->Rdi;
1367     R8_sig(sigcontext)  = context->R8;
1368     R9_sig(sigcontext)  = context->R9;
1369     R10_sig(sigcontext) = context->R10;
1370     R11_sig(sigcontext) = context->R11;
1371     R12_sig(sigcontext) = context->R12;
1372     R13_sig(sigcontext) = context->R13;
1373     R14_sig(sigcontext) = context->R14;
1374     R15_sig(sigcontext) = context->R15;
1375     RIP_sig(sigcontext) = context->Rip;
1376     CS_sig(sigcontext)  = context->SegCs;
1377     FS_sig(sigcontext)  = context->SegFs;
1378     GS_sig(sigcontext)  = context->SegGs;
1379     EFL_sig(sigcontext) = context->EFlags;
1380 #ifdef DS_sig
1381     DS_sig(sigcontext) = context->SegDs;
1382 #endif
1383 #ifdef ES_sig
1384     ES_sig(sigcontext) = context->SegEs;
1385 #endif
1386 #ifdef SS_sig
1387     SS_sig(sigcontext) = context->SegSs;
1388 #endif
1389     if (FPU_sig(sigcontext)) *FPU_sig(sigcontext) = context->u.FltSave;
1390 }
1391
1392
1393 /***********************************************************************
1394  *              RtlCaptureContext (NTDLL.@)
1395  */
1396 void WINAPI __regs_RtlCaptureContext( CONTEXT *context, CONTEXT *regs )
1397 {
1398     *context = *regs;
1399 }
1400 DEFINE_REGS_ENTRYPOINT( RtlCaptureContext, 1 )
1401
1402
1403 /***********************************************************************
1404  *           set_cpu_context
1405  *
1406  * Set the new CPU context.
1407  */
1408 void set_cpu_context( const CONTEXT *context )
1409 {
1410     extern void CDECL __wine_restore_regs( const CONTEXT * ) DECLSPEC_NORETURN;
1411     __wine_restore_regs( context );
1412 }
1413
1414
1415 /***********************************************************************
1416  *           copy_context
1417  *
1418  * Copy a register context according to the flags.
1419  */
1420 void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
1421 {
1422     flags &= ~CONTEXT_AMD64;  /* get rid of CPU id */
1423     if (flags & CONTEXT_CONTROL)
1424     {
1425         to->Rbp    = from->Rbp;
1426         to->Rip    = from->Rip;
1427         to->Rsp    = from->Rsp;
1428         to->SegCs  = from->SegCs;
1429         to->SegSs  = from->SegSs;
1430         to->EFlags = from->EFlags;
1431     }
1432     if (flags & CONTEXT_INTEGER)
1433     {
1434         to->Rax = from->Rax;
1435         to->Rcx = from->Rcx;
1436         to->Rdx = from->Rdx;
1437         to->Rbx = from->Rbx;
1438         to->Rsi = from->Rsi;
1439         to->Rdi = from->Rdi;
1440         to->R8  = from->R8;
1441         to->R9  = from->R9;
1442         to->R10 = from->R10;
1443         to->R11 = from->R11;
1444         to->R12 = from->R12;
1445         to->R13 = from->R13;
1446         to->R14 = from->R14;
1447         to->R15 = from->R15;
1448     }
1449     if (flags & CONTEXT_SEGMENTS)
1450     {
1451         to->SegDs = from->SegDs;
1452         to->SegEs = from->SegEs;
1453         to->SegFs = from->SegFs;
1454         to->SegGs = from->SegGs;
1455     }
1456     if (flags & CONTEXT_FLOATING_POINT)
1457     {
1458         to->MxCsr = from->MxCsr;
1459         to->u.FltSave = from->u.FltSave;
1460     }
1461     if (flags & CONTEXT_DEBUG_REGISTERS)
1462     {
1463         to->Dr0 = from->Dr0;
1464         to->Dr1 = from->Dr1;
1465         to->Dr2 = from->Dr2;
1466         to->Dr3 = from->Dr3;
1467         to->Dr6 = from->Dr6;
1468         to->Dr7 = from->Dr7;
1469     }
1470 }
1471
1472
1473 /***********************************************************************
1474  *           context_to_server
1475  *
1476  * Convert a register context to the server format.
1477  */
1478 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1479 {
1480     DWORD flags = from->ContextFlags & ~CONTEXT_AMD64;  /* get rid of CPU id */
1481
1482     memset( to, 0, sizeof(*to) );
1483     to->cpu = CPU_x86_64;
1484
1485     if (flags & CONTEXT_CONTROL)
1486     {
1487         to->flags |= SERVER_CTX_CONTROL;
1488         to->ctl.x86_64_regs.rbp   = from->Rbp;
1489         to->ctl.x86_64_regs.rip   = from->Rip;
1490         to->ctl.x86_64_regs.rsp   = from->Rsp;
1491         to->ctl.x86_64_regs.cs    = from->SegCs;
1492         to->ctl.x86_64_regs.ss    = from->SegSs;
1493         to->ctl.x86_64_regs.flags = from->EFlags;
1494     }
1495     if (flags & CONTEXT_INTEGER)
1496     {
1497         to->flags |= SERVER_CTX_INTEGER;
1498         to->integer.x86_64_regs.rax = from->Rax;
1499         to->integer.x86_64_regs.rcx = from->Rcx;
1500         to->integer.x86_64_regs.rdx = from->Rdx;
1501         to->integer.x86_64_regs.rbx = from->Rbx;
1502         to->integer.x86_64_regs.rsi = from->Rsi;
1503         to->integer.x86_64_regs.rdi = from->Rdi;
1504         to->integer.x86_64_regs.r8  = from->R8;
1505         to->integer.x86_64_regs.r9  = from->R9;
1506         to->integer.x86_64_regs.r10 = from->R10;
1507         to->integer.x86_64_regs.r11 = from->R11;
1508         to->integer.x86_64_regs.r12 = from->R12;
1509         to->integer.x86_64_regs.r13 = from->R13;
1510         to->integer.x86_64_regs.r14 = from->R14;
1511         to->integer.x86_64_regs.r15 = from->R15;
1512     }
1513     if (flags & CONTEXT_SEGMENTS)
1514     {
1515         to->flags |= SERVER_CTX_SEGMENTS;
1516         to->seg.x86_64_regs.ds = from->SegDs;
1517         to->seg.x86_64_regs.es = from->SegEs;
1518         to->seg.x86_64_regs.fs = from->SegFs;
1519         to->seg.x86_64_regs.gs = from->SegGs;
1520     }
1521     if (flags & CONTEXT_FLOATING_POINT)
1522     {
1523         to->flags |= SERVER_CTX_FLOATING_POINT;
1524         memcpy( to->fp.x86_64_regs.fpregs, &from->u.FltSave, sizeof(to->fp.x86_64_regs.fpregs) );
1525     }
1526     if (flags & CONTEXT_DEBUG_REGISTERS)
1527     {
1528         to->flags |= SERVER_CTX_DEBUG_REGISTERS;
1529         to->debug.x86_64_regs.dr0 = from->Dr0;
1530         to->debug.x86_64_regs.dr1 = from->Dr1;
1531         to->debug.x86_64_regs.dr2 = from->Dr2;
1532         to->debug.x86_64_regs.dr3 = from->Dr3;
1533         to->debug.x86_64_regs.dr6 = from->Dr6;
1534         to->debug.x86_64_regs.dr7 = from->Dr7;
1535     }
1536     return STATUS_SUCCESS;
1537 }
1538
1539
1540 /***********************************************************************
1541  *           context_from_server
1542  *
1543  * Convert a register context from the server format.
1544  */
1545 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
1546 {
1547     if (from->cpu != CPU_x86_64) return STATUS_INVALID_PARAMETER;
1548
1549     to->ContextFlags = CONTEXT_AMD64;
1550     if (from->flags & SERVER_CTX_CONTROL)
1551     {
1552         to->ContextFlags |= CONTEXT_CONTROL;
1553         to->Rbp    = from->ctl.x86_64_regs.rbp;
1554         to->Rip    = from->ctl.x86_64_regs.rip;
1555         to->Rsp    = from->ctl.x86_64_regs.rsp;
1556         to->SegCs  = from->ctl.x86_64_regs.cs;
1557         to->SegSs  = from->ctl.x86_64_regs.ss;
1558         to->EFlags = from->ctl.x86_64_regs.flags;
1559     }
1560
1561     if (from->flags & SERVER_CTX_INTEGER)
1562     {
1563         to->ContextFlags |= CONTEXT_INTEGER;
1564         to->Rax = from->integer.x86_64_regs.rax;
1565         to->Rcx = from->integer.x86_64_regs.rcx;
1566         to->Rdx = from->integer.x86_64_regs.rdx;
1567         to->Rbx = from->integer.x86_64_regs.rbx;
1568         to->Rsi = from->integer.x86_64_regs.rsi;
1569         to->Rdi = from->integer.x86_64_regs.rdi;
1570         to->R8  = from->integer.x86_64_regs.r8;
1571         to->R9  = from->integer.x86_64_regs.r9;
1572         to->R10 = from->integer.x86_64_regs.r10;
1573         to->R11 = from->integer.x86_64_regs.r11;
1574         to->R12 = from->integer.x86_64_regs.r12;
1575         to->R13 = from->integer.x86_64_regs.r13;
1576         to->R14 = from->integer.x86_64_regs.r14;
1577         to->R15 = from->integer.x86_64_regs.r15;
1578     }
1579     if (from->flags & SERVER_CTX_SEGMENTS)
1580     {
1581         to->ContextFlags |= CONTEXT_SEGMENTS;
1582         to->SegDs = from->seg.x86_64_regs.ds;
1583         to->SegEs = from->seg.x86_64_regs.es;
1584         to->SegFs = from->seg.x86_64_regs.fs;
1585         to->SegGs = from->seg.x86_64_regs.gs;
1586     }
1587     if (from->flags & SERVER_CTX_FLOATING_POINT)
1588     {
1589         to->ContextFlags |= CONTEXT_FLOATING_POINT;
1590         memcpy( &to->u.FltSave, from->fp.x86_64_regs.fpregs, sizeof(from->fp.x86_64_regs.fpregs) );
1591         to->MxCsr = to->u.FltSave.MxCsr;
1592     }
1593     if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
1594     {
1595         to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1596         to->Dr0 = from->debug.x86_64_regs.dr0;
1597         to->Dr1 = from->debug.x86_64_regs.dr1;
1598         to->Dr2 = from->debug.x86_64_regs.dr2;
1599         to->Dr3 = from->debug.x86_64_regs.dr3;
1600         to->Dr6 = from->debug.x86_64_regs.dr6;
1601         to->Dr7 = from->debug.x86_64_regs.dr7;
1602     }
1603     return STATUS_SUCCESS;
1604 }
1605
1606
1607 extern void raise_func_trampoline( EXCEPTION_RECORD *rec, CONTEXT *context, raise_func func );
1608 __ASM_GLOBAL_FUNC( raise_func_trampoline,
1609                    ".cfi_signal_frame\n\t"
1610                    ".cfi_def_cfa %rbp,144\n\t"  /* red zone + rip + rbp */
1611                    ".cfi_rel_offset %rip,8\n\t"
1612                    ".cfi_rel_offset %rbp,0\n\t"
1613                    "call *%rdx\n\t"
1614                    "int $3")
1615
1616 /***********************************************************************
1617  *           setup_exception
1618  *
1619  * Setup a proper stack frame for the raise function, and modify the
1620  * sigcontext so that the return from the signal handler will call
1621  * the raise function.
1622  */
1623 static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
1624 {
1625     struct stack_layout
1626     {
1627         CONTEXT           context;
1628         EXCEPTION_RECORD  rec;
1629         ULONG64           rbp;
1630         ULONG64           rip;
1631         ULONG64           red_zone[16];
1632     } *stack;
1633     ULONG64 *rsp_ptr;
1634     DWORD exception_code = 0;
1635
1636     stack = (struct stack_layout *)(RSP_sig(sigcontext) & ~15);
1637
1638     /* stack sanity checks */
1639
1640     if (is_inside_signal_stack( stack ))
1641     {
1642         ERR( "nested exception on signal stack in thread %04x eip %016lx esp %016lx stack %p-%p\n",
1643              GetCurrentThreadId(), RIP_sig(sigcontext), RSP_sig(sigcontext),
1644              NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1645         abort_thread(1);
1646     }
1647
1648     if (stack - 1 > stack || /* check for overflow in subtraction */
1649         (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
1650         (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
1651     {
1652         WARN( "exception outside of stack limits in thread %04x eip %016lx esp %016lx stack %p-%p\n",
1653               GetCurrentThreadId(), RIP_sig(sigcontext), RSP_sig(sigcontext),
1654               NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1655     }
1656     else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
1657     {
1658         /* stack overflow on last page, unrecoverable */
1659         UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
1660         ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
1661              diff, GetCurrentThreadId(), RIP_sig(sigcontext),
1662              RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1663              NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1664         abort_thread(1);
1665     }
1666     else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
1667     {
1668         /* stack access below stack limit, may be recoverable */
1669         if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
1670         else
1671         {
1672             UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
1673             ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
1674                  diff, GetCurrentThreadId(), RIP_sig(sigcontext),
1675                  RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1676                  NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1677             abort_thread(1);
1678         }
1679     }
1680
1681     stack--;  /* push the stack_layout structure */
1682     stack->rec.ExceptionRecord  = NULL;
1683     stack->rec.ExceptionCode    = exception_code;
1684     stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
1685     stack->rec.ExceptionAddress = (void *)RIP_sig(sigcontext);
1686     stack->rec.NumberParameters = 0;
1687     save_context( &stack->context, sigcontext );
1688
1689     /* store return address and %rbp without aligning, so that the offset is fixed */
1690     rsp_ptr = (ULONG64 *)RSP_sig(sigcontext) - 16;
1691     *(--rsp_ptr) = RIP_sig(sigcontext);
1692     *(--rsp_ptr) = RBP_sig(sigcontext);
1693
1694     /* now modify the sigcontext to return to the raise function */
1695     RIP_sig(sigcontext) = (ULONG_PTR)raise_func_trampoline;
1696     RDI_sig(sigcontext) = (ULONG_PTR)&stack->rec;
1697     RSI_sig(sigcontext) = (ULONG_PTR)&stack->context;
1698     RDX_sig(sigcontext) = (ULONG_PTR)func;
1699     RBP_sig(sigcontext) = (ULONG_PTR)rsp_ptr;
1700     RSP_sig(sigcontext) = (ULONG_PTR)stack;
1701     /* clear single-step, direction, and align check flag */
1702     EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
1703
1704     return &stack->rec;
1705 }
1706
1707
1708 /**********************************************************************
1709  *           find_function_info
1710  */
1711 static RUNTIME_FUNCTION *find_function_info( ULONG64 pc, HMODULE module,
1712                                              RUNTIME_FUNCTION *func, ULONG size )
1713 {
1714     int min = 0;
1715     int max = size/sizeof(*func) - 1;
1716
1717     while (min <= max)
1718     {
1719         int pos = (min + max) / 2;
1720         if ((char *)pc < (char *)module + func[pos].BeginAddress) max = pos - 1;
1721         else if ((char *)pc >= (char *)module + func[pos].EndAddress) min = pos + 1;
1722         else
1723         {
1724             func += pos;
1725             while (func->UnwindData & 1)  /* follow chained entry */
1726                 func = (RUNTIME_FUNCTION *)((char *)module + (func->UnwindData & ~1));
1727             return func;
1728         }
1729     }
1730     return NULL;
1731 }
1732
1733
1734 /**********************************************************************
1735  *           call_handler
1736  *
1737  * Call a single exception handler.
1738  * FIXME: Handle nested exceptions.
1739  */
1740 static NTSTATUS call_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch, CONTEXT *orig_context )
1741 {
1742     DWORD res;
1743
1744     dispatch->ControlPc = dispatch->ContextRecord->Rip;
1745
1746     TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
1747            dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
1748     res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
1749     TRACE( "handler at %p returned %u\n", dispatch->LanguageHandler, res );
1750
1751     switch (res)
1752     {
1753     case ExceptionContinueExecution:
1754         if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
1755         *orig_context = *dispatch->ContextRecord;
1756         return STATUS_SUCCESS;
1757     case ExceptionContinueSearch:
1758         break;
1759     case ExceptionNestedException:
1760         break;
1761     default:
1762         return STATUS_INVALID_DISPOSITION;
1763     }
1764     return STATUS_UNHANDLED_EXCEPTION;
1765 }
1766
1767
1768 /**********************************************************************
1769  *           call_teb_handler
1770  *
1771  * Call a single exception handler from the TEB chain.
1772  * FIXME: Handle nested exceptions.
1773  */
1774 static NTSTATUS call_teb_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
1775                                   EXCEPTION_REGISTRATION_RECORD *teb_frame, CONTEXT *orig_context )
1776 {
1777     EXCEPTION_REGISTRATION_RECORD *dispatcher;
1778     DWORD res;
1779
1780     TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatcher=%p)\n",
1781            teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, &dispatcher );
1782     res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, &dispatcher );
1783     TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
1784
1785     switch (res)
1786     {
1787     case ExceptionContinueExecution:
1788         if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
1789         *orig_context = *dispatch->ContextRecord;
1790         return STATUS_SUCCESS;
1791     case ExceptionContinueSearch:
1792         break;
1793     case ExceptionNestedException:
1794         break;
1795     default:
1796         return STATUS_INVALID_DISPOSITION;
1797     }
1798     return STATUS_UNHANDLED_EXCEPTION;
1799 }
1800
1801
1802 /**********************************************************************
1803  *           call_stack_handlers
1804  *
1805  * Call the stack handlers chain.
1806  */
1807 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *orig_context )
1808 {
1809     EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
1810     UNWIND_HISTORY_TABLE table;
1811     RUNTIME_FUNCTION *dir;
1812     DISPATCHER_CONTEXT dispatch;
1813     CONTEXT context, new_context;
1814     LDR_MODULE *module;
1815     DWORD size;
1816     NTSTATUS status;
1817
1818     context = *orig_context;
1819     dispatch.TargetIp      = 0;
1820     dispatch.ContextRecord = &context;
1821     dispatch.HistoryTable  = &table;
1822     dispatch.ScopeIndex    = 0; /* FIXME */
1823     for (;;)
1824     {
1825         new_context = context;
1826
1827         /* FIXME: should use the history table to make things faster */
1828
1829         dir = NULL;
1830         module = NULL;
1831         dispatch.ImageBase = 0;
1832
1833         if (!LdrFindEntryForAddress( (void *)context.Rip, &module ))
1834         {
1835             if (!(dir = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
1836                                                       IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )) &&
1837                 !(module->Flags & LDR_WINE_INTERNAL))
1838             {
1839                 ERR( "module %s doesn't contain exception data, can't dispatch exception\n",
1840                      debugstr_w(module->BaseDllName.Buffer) );
1841                 break;
1842             }
1843             dispatch.ImageBase = (ULONG64)module->BaseAddress;
1844         }
1845
1846         if (!dir)
1847         {
1848             struct dwarf_eh_bases bases;
1849             const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context.Rip - 1), &bases );
1850             if (!fde)
1851             {
1852                 /* assume leaf function */
1853                 context.Rip = *(ULONG64 *)context.Rsp;
1854                 context.Rsp += sizeof(ULONG64);
1855                 continue;
1856             }
1857             status = dwarf_virtual_unwind( context.Rip, &dispatch.EstablisherFrame, &new_context,
1858                                            fde, &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
1859             if (status != STATUS_SUCCESS) return status;
1860             dispatch.FunctionEntry = NULL;
1861             if (dispatch.LanguageHandler && !module)
1862             {
1863                 FIXME( "calling personality routine in system library not supported yet\n" );
1864                 dispatch.LanguageHandler = NULL;
1865             }
1866         }
1867         else
1868         {
1869             if (!(dispatch.FunctionEntry = find_function_info( context.Rip, module->BaseAddress,
1870                                                                dir, size )))
1871             {
1872                 /* leaf function */
1873                 context.Rip = *(ULONG64 *)context.Rsp;
1874                 context.Rsp += sizeof(ULONG64);
1875                 continue;
1876             }
1877             dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, dispatch.ImageBase,
1878                                                          context.Rip, dispatch.FunctionEntry,
1879                                                          &new_context, &dispatch.HandlerData,
1880                                                          &dispatch.EstablisherFrame, NULL );
1881         }
1882
1883         if (!dispatch.EstablisherFrame) break;
1884
1885         if ((dispatch.EstablisherFrame & 7) ||
1886             dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
1887             dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
1888         {
1889             ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
1890                  NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1891             rec->ExceptionFlags |= EH_STACK_INVALID;
1892             break;
1893         }
1894
1895         if (dispatch.LanguageHandler)
1896         {
1897             status = call_handler( rec, &dispatch, orig_context );
1898             if (status != STATUS_UNHANDLED_EXCEPTION) return status;
1899         }
1900         /* hack: call wine handlers registered in the tib list */
1901         else while ((ULONG64)teb_frame < new_context.Rsp)
1902         {
1903             TRACE( "found wine frame %p rsp %lx handler %p\n",
1904                    teb_frame, new_context.Rsp, teb_frame->Handler );
1905             dispatch.EstablisherFrame = (ULONG64)teb_frame;
1906             context = *orig_context;
1907             status = call_teb_handler( rec, &dispatch, teb_frame, orig_context );
1908             if (status != STATUS_UNHANDLED_EXCEPTION) return status;
1909             teb_frame = teb_frame->Prev;
1910         }
1911
1912         if (new_context.Rsp == (ULONG64)NtCurrentTeb()->Tib.StackBase) break;
1913         context = new_context;
1914     }
1915     return STATUS_UNHANDLED_EXCEPTION;
1916 }
1917
1918
1919 /*******************************************************************
1920  *              raise_exception
1921  *
1922  * Implementation of NtRaiseException.
1923  */
1924 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
1925 {
1926     NTSTATUS status;
1927
1928     if (first_chance)
1929     {
1930         DWORD c;
1931
1932         TRACE( "code=%x flags=%x addr=%p ip=%lx tid=%04x\n",
1933                rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
1934                context->Rip, GetCurrentThreadId() );
1935         for (c = 0; c < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); c++)
1936             TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
1937         if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
1938         {
1939             if (rec->ExceptionInformation[1] >> 16)
1940                 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
1941                          rec->ExceptionAddress,
1942                          (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
1943             else
1944                 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
1945                          rec->ExceptionAddress,
1946                          (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
1947         }
1948         else
1949         {
1950             TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
1951                   context->Rax, context->Rbx, context->Rcx, context->Rdx );
1952             TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
1953                   context->Rsi, context->Rdi, context->Rbp, context->Rsp );
1954             TRACE("  r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
1955                   context->R8, context->R9, context->R10, context->R11 );
1956             TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
1957                   context->R12, context->R13, context->R14, context->R15 );
1958         }
1959         status = send_debug_event( rec, TRUE, context );
1960         if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
1961             return STATUS_SUCCESS;
1962
1963         if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
1964             return STATUS_SUCCESS;
1965
1966         if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
1967             return status;
1968     }
1969
1970     /* last chance exception */
1971
1972     status = send_debug_event( rec, FALSE, context );
1973     if (status != DBG_CONTINUE)
1974     {
1975         if (rec->ExceptionFlags & EH_STACK_INVALID)
1976             ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
1977         else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
1978             ERR("Process attempted to continue execution after noncontinuable exception.\n");
1979         else
1980             ERR("Unhandled exception code %x flags %x addr %p\n",
1981                 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
1982         NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
1983     }
1984     return STATUS_SUCCESS;
1985 }
1986
1987
1988 /**********************************************************************
1989  *              raise_segv_exception
1990  */
1991 static void raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1992 {
1993     NTSTATUS status;
1994
1995     switch(rec->ExceptionCode)
1996     {
1997     case EXCEPTION_ACCESS_VIOLATION:
1998         if (rec->NumberParameters == 2)
1999         {
2000             if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
2001                                                              rec->ExceptionInformation[0] )))
2002                 set_cpu_context( context );
2003         }
2004         break;
2005     }
2006     status = raise_exception( rec, context, TRUE );
2007     if (status) raise_status( status, rec );
2008     set_cpu_context( context );
2009 }
2010
2011
2012 /**********************************************************************
2013  *              raise_generic_exception
2014  *
2015  * Generic raise function for exceptions that don't need special treatment.
2016  */
2017 static void raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2018 {
2019     NTSTATUS status = raise_exception( rec, context, TRUE );
2020     if (status) raise_status( status, rec );
2021     set_cpu_context( context );
2022 }
2023
2024
2025 /**********************************************************************
2026  *              segv_handler
2027  *
2028  * Handler for SIGSEGV and related errors.
2029  */
2030 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2031 {
2032     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_segv_exception );
2033     ucontext_t *ucontext = sigcontext;
2034
2035     switch(TRAP_sig(ucontext))
2036     {
2037     case TRAP_x86_OFLOW:   /* Overflow exception */
2038         rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2039         break;
2040     case TRAP_x86_BOUND:   /* Bound range exception */
2041         rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2042         break;
2043     case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
2044         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2045         break;
2046     case TRAP_x86_STKFLT:  /* Stack fault */
2047         rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2048         break;
2049     case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
2050     case TRAP_x86_PROTFLT:   /* General protection fault */
2051     case TRAP_x86_UNKNOWN:   /* Unknown fault code */
2052         rec->ExceptionCode = ERROR_sig(ucontext) ? EXCEPTION_ACCESS_VIOLATION : EXCEPTION_PRIV_INSTRUCTION;
2053         rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2054         break;
2055     case TRAP_x86_PAGEFLT:  /* Page fault */
2056         rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2057         rec->NumberParameters = 2;
2058         rec->ExceptionInformation[0] = (ERROR_sig(ucontext) & 2) != 0;
2059         rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2060         break;
2061     case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
2062         rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2063         break;
2064     default:
2065         ERR( "Got unexpected trap %ld\n", TRAP_sig(ucontext) );
2066         /* fall through */
2067     case TRAP_x86_NMI:       /* NMI interrupt */
2068     case TRAP_x86_DNA:       /* Device not available exception */
2069     case TRAP_x86_DOUBLEFLT: /* Double fault exception */
2070     case TRAP_x86_TSSFLT:    /* Invalid TSS exception */
2071     case TRAP_x86_MCHK:      /* Machine check exception */
2072     case TRAP_x86_CACHEFLT:  /* Cache flush exception */
2073         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2074         break;
2075     }
2076 }
2077
2078 /**********************************************************************
2079  *              trap_handler
2080  *
2081  * Handler for SIGTRAP.
2082  */
2083 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2084 {
2085     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2086
2087     switch (siginfo->si_code)
2088     {
2089     case TRAP_TRACE:  /* Single-step exception */
2090         rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
2091         break;
2092     case TRAP_BRKPT:   /* Breakpoint exception */
2093         rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
2094         /* fall through */
2095     default:
2096         rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2097         break;
2098     }
2099 }
2100
2101 /**********************************************************************
2102  *              fpe_handler
2103  *
2104  * Handler for SIGFPE.
2105  */
2106 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2107 {
2108     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2109
2110     switch (siginfo->si_code)
2111     {
2112     case FPE_FLTSUB:
2113         rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2114         break;
2115     case FPE_INTDIV:
2116         rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2117         break;
2118     case FPE_INTOVF:
2119         rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2120         break;
2121     case FPE_FLTDIV:
2122         rec->ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO;
2123         break;
2124     case FPE_FLTOVF:
2125         rec->ExceptionCode = EXCEPTION_FLT_OVERFLOW;
2126         break;
2127     case FPE_FLTUND:
2128         rec->ExceptionCode = EXCEPTION_FLT_UNDERFLOW;
2129         break;
2130     case FPE_FLTRES:
2131         rec->ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT;
2132         break;
2133     case FPE_FLTINV:
2134     default:
2135         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2136         break;
2137     }
2138 }
2139
2140 /**********************************************************************
2141  *              int_handler
2142  *
2143  * Handler for SIGINT.
2144  */
2145 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2146 {
2147     if (!dispatch_signal(SIGINT))
2148     {
2149         EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2150         rec->ExceptionCode = CONTROL_C_EXIT;
2151     }
2152 }
2153
2154
2155 /**********************************************************************
2156  *              abrt_handler
2157  *
2158  * Handler for SIGABRT.
2159  */
2160 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2161 {
2162     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2163     rec->ExceptionCode = EXCEPTION_WINE_ASSERTION;
2164     rec->ExceptionFlags = EH_NONCONTINUABLE;
2165 }
2166
2167
2168 /**********************************************************************
2169  *              quit_handler
2170  *
2171  * Handler for SIGQUIT.
2172  */
2173 static void quit_handler( int signal, siginfo_t *siginfo, void *ucontext )
2174 {
2175     abort_thread(0);
2176 }
2177
2178
2179 /**********************************************************************
2180  *              usr1_handler
2181  *
2182  * Handler for SIGUSR1, used to signal a thread that it got suspended.
2183  */
2184 static void usr1_handler( int signal, siginfo_t *siginfo, void *ucontext )
2185 {
2186     CONTEXT context;
2187
2188     save_context( &context, ucontext );
2189     wait_suspend( &context );
2190     restore_context( &context, ucontext );
2191 }
2192
2193
2194 /**********************************************************************
2195  *              get_signal_stack_total_size
2196  *
2197  * Retrieve the size to allocate for the signal stack, including the TEB at the bottom.
2198  * Must be a power of two.
2199  */
2200 size_t get_signal_stack_total_size(void)
2201 {
2202     assert( sizeof(TEB) <= teb_size );
2203     if (!signal_stack_size)
2204     {
2205         size_t size = 8192, min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2206         /* find the first power of two not smaller than min_size */
2207         while (size < min_size) size *= 2;
2208         signal_stack_size = size - teb_size;
2209     }
2210     return signal_stack_size + teb_size;
2211 }
2212
2213
2214 /***********************************************************************
2215  *           __wine_set_signal_handler   (NTDLL.@)
2216  */
2217 int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
2218 {
2219     if (sig > sizeof(handlers) / sizeof(handlers[0])) return -1;
2220     if (handlers[sig] != NULL) return -2;
2221     handlers[sig] = wsh;
2222     return 0;
2223 }
2224
2225
2226 /**********************************************************************
2227  *              signal_init_thread
2228  */
2229 void signal_init_thread( TEB *teb )
2230 {
2231     stack_t ss;
2232
2233 #ifdef __linux__
2234     arch_prctl( ARCH_SET_GS, teb );
2235 #else
2236 # error Please define setting %gs for your architecture
2237 #endif
2238
2239     ss.ss_sp    = (char *)teb + teb_size;
2240     ss.ss_size  = signal_stack_size;
2241     ss.ss_flags = 0;
2242     if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
2243 }
2244
2245 /**********************************************************************
2246  *              signal_init_process
2247  */
2248 void signal_init_process(void)
2249 {
2250     struct sigaction sig_act;
2251
2252     sig_act.sa_mask = server_block_set;
2253     sig_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
2254
2255     sig_act.sa_sigaction = int_handler;
2256     if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
2257     sig_act.sa_sigaction = fpe_handler;
2258     if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
2259     sig_act.sa_sigaction = abrt_handler;
2260     if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
2261     sig_act.sa_sigaction = quit_handler;
2262     if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
2263     sig_act.sa_sigaction = usr1_handler;
2264     if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
2265
2266     sig_act.sa_sigaction = segv_handler;
2267     if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
2268     if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2269 #ifdef SIGBUS
2270     if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2271 #endif
2272
2273 #ifdef SIGTRAP
2274     sig_act.sa_sigaction = trap_handler;
2275     if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2276 #endif
2277     return;
2278
2279  error:
2280     perror("sigaction");
2281     exit(1);
2282 }
2283
2284
2285 /**********************************************************************
2286  *              RtlLookupFunctionEntry   (NTDLL.@)
2287  */
2288 PRUNTIME_FUNCTION WINAPI RtlLookupFunctionEntry( ULONG64 pc, ULONG64 *base, UNWIND_HISTORY_TABLE *table )
2289 {
2290     LDR_MODULE *module;
2291     RUNTIME_FUNCTION *func;
2292     ULONG size;
2293
2294     /* FIXME: should use the history table to make things faster */
2295
2296     if (LdrFindEntryForAddress( (void *)pc, &module ))
2297     {
2298         WARN( "module not found for %lx\n", pc );
2299         return NULL;
2300     }
2301     if (!(func = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
2302                                                IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )))
2303     {
2304         WARN( "no exception table found in module %p pc %lx\n", module->BaseAddress, pc );
2305         return NULL;
2306     }
2307     func = find_function_info( pc, module->BaseAddress, func, size );
2308     if (func) *base = (ULONG64)module->BaseAddress;
2309     return func;
2310 }
2311
2312 static ULONG64 get_int_reg( CONTEXT *context, int reg )
2313 {
2314     return *(&context->Rax + reg);
2315 }
2316
2317 static void set_int_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, ULONG64 val )
2318 {
2319     *(&context->Rax + reg) = val;
2320     if (ctx_ptr) ctx_ptr->u2.IntegerContext[reg] = &context->Rax + reg;
2321 }
2322
2323 static void set_float_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, M128A val )
2324 {
2325     *(&context->u.s.Xmm0 + reg) = val;
2326     if (ctx_ptr) ctx_ptr->u1.FloatingContext[reg] = &context->u.s.Xmm0 + reg;
2327 }
2328
2329 static int get_opcode_size( struct opcode op )
2330 {
2331     switch (op.code)
2332     {
2333     case UWOP_ALLOC_LARGE:
2334         return 2 + (op.info != 0);
2335     case UWOP_SAVE_NONVOL:
2336     case UWOP_SAVE_XMM128:
2337         return 2;
2338     case UWOP_SAVE_NONVOL_FAR:
2339     case UWOP_SAVE_XMM128_FAR:
2340         return 3;
2341     default:
2342         return 1;
2343     }
2344 }
2345
2346 static BOOL is_inside_epilog( BYTE *pc )
2347 {
2348     /* add or lea must be the first instruction, and it must have a rex.W prefix */
2349     if ((pc[0] & 0xf8) == 0x48)
2350     {
2351         switch (pc[1])
2352         {
2353         case 0x81: /* add $nnnn,%rsp */
2354             if (pc[0] == 0x48 && pc[2] == 0xc4)
2355             {
2356                 pc += 7;
2357                 break;
2358             }
2359             return FALSE;
2360         case 0x83: /* add $n,%rsp */
2361             if (pc[0] == 0x48 && pc[2] == 0xc4)
2362             {
2363                 pc += 4;
2364                 break;
2365             }
2366             return FALSE;
2367         case 0x8d: /* lea n(reg),%rsp */
2368             if (pc[0] & 0x06) return FALSE;  /* rex.RX must be cleared */
2369             if (((pc[2] >> 3) & 7) != 4) return FALSE;  /* dest reg mus be %rsp */
2370             if ((pc[2] & 7) == 4) return FALSE;  /* no SIB byte allowed */
2371             if ((pc[2] >> 6) == 1)  /* 8-bit offset */
2372             {
2373                 pc += 4;
2374                 break;
2375             }
2376             if ((pc[2] >> 6) == 2)  /* 32-bit offset */
2377             {
2378                 pc += 7;
2379                 break;
2380             }
2381             return FALSE;
2382         }
2383     }
2384
2385     /* now check for various pop instructions */
2386
2387     for (;;)
2388     {
2389         BYTE rex = 0;
2390
2391         if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f;  /* rex prefix */
2392
2393         switch (*pc)
2394         {
2395         case 0x58: /* pop %rax/%r8 */
2396         case 0x59: /* pop %rcx/%r9 */
2397         case 0x5a: /* pop %rdx/%r10 */
2398         case 0x5b: /* pop %rbx/%r11 */
2399         case 0x5c: /* pop %rsp/%r12 */
2400         case 0x5d: /* pop %rbp/%r13 */
2401         case 0x5e: /* pop %rsi/%r14 */
2402         case 0x5f: /* pop %rdi/%r15 */
2403             pc++;
2404             continue;
2405         case 0xc2: /* ret $nn */
2406         case 0xc3: /* ret */
2407             return TRUE;
2408         /* FIXME: add various jump instructions */
2409         }
2410         return FALSE;
2411     }
2412 }
2413
2414 /* execute a function epilog, which must have been validated with is_inside_epilog() */
2415 static void interpret_epilog( BYTE *pc, CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
2416 {
2417     for (;;)
2418     {
2419         BYTE rex = 0;
2420
2421         if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f;  /* rex prefix */
2422
2423         switch (*pc)
2424         {
2425         case 0x58: /* pop %rax/r8 */
2426         case 0x59: /* pop %rcx/r9 */
2427         case 0x5a: /* pop %rdx/r10 */
2428         case 0x5b: /* pop %rbx/r11 */
2429         case 0x5c: /* pop %rsp/r12 */
2430         case 0x5d: /* pop %rbp/r13 */
2431         case 0x5e: /* pop %rsi/r14 */
2432         case 0x5f: /* pop %rdi/r15 */
2433             set_int_reg( context, ctx_ptr, *pc - 0x58 + (rex & 1) * 8, *(ULONG64 *)context->Rsp );
2434             context->Rsp += sizeof(ULONG64);
2435             pc++;
2436             continue;
2437         case 0x81: /* add $nnnn,%rsp */
2438             context->Rsp += *(LONG *)(pc + 2);
2439             pc += 2 + sizeof(LONG);
2440             continue;
2441         case 0x83: /* add $n,%rsp */
2442             context->Rsp += (signed char)pc[2];
2443             pc += 3;
2444             continue;
2445         case 0x8d:
2446             if ((pc[1] >> 6) == 1)  /* lea n(reg),%rsp */
2447             {
2448                 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + (signed char)pc[2];
2449                 pc += 3;
2450             }
2451             else  /* lea nnnn(reg),%rsp */
2452             {
2453                 context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + *(LONG *)(pc + 2);
2454                 pc += 2 + sizeof(LONG);
2455             }
2456             continue;
2457         case 0xc2: /* ret $nn */
2458             context->Rip = *(ULONG64 *)context->Rsp;
2459             context->Rsp += sizeof(ULONG64) + *(WORD *)(pc + 1);
2460             return;
2461         case 0xc3: /* ret */
2462             context->Rip = *(ULONG64 *)context->Rsp;
2463             context->Rsp += sizeof(ULONG64);
2464             return;
2465         /* FIXME: add various jump instructions */
2466         }
2467         return;
2468     }
2469 }
2470
2471 /**********************************************************************
2472  *              RtlVirtualUnwind   (NTDLL.@)
2473  */
2474 PVOID WINAPI RtlVirtualUnwind( ULONG type, ULONG64 base, ULONG64 pc,
2475                                RUNTIME_FUNCTION *function, CONTEXT *context,
2476                                PVOID *data, ULONG64 *frame_ret,
2477                                KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
2478 {
2479     union handler_data *handler_data;
2480     ULONG64 frame, off;
2481     struct UNWIND_INFO *info;
2482     unsigned int i, prolog_offset;
2483
2484     TRACE( "type %x rip %lx rsp %lx\n", type, pc, context->Rsp );
2485     if (TRACE_ON(seh)) dump_unwind_info( base, function );
2486
2487     frame = *frame_ret = context->Rsp;
2488     for (;;)
2489     {
2490         info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
2491         handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
2492
2493         if (info->version != 1)
2494         {
2495             FIXME( "unknown unwind info version %u at %p\n", info->version, info );
2496             return NULL;
2497         }
2498
2499         if (info->frame_reg)
2500             frame = get_int_reg( context, info->frame_reg ) - info->frame_offset * 16;
2501
2502         /* check if in prolog */
2503         if (pc >= base + function->BeginAddress && pc < base + function->BeginAddress + info->prolog)
2504         {
2505             prolog_offset = pc - base - function->BeginAddress;
2506         }
2507         else
2508         {
2509             prolog_offset = ~0;
2510             if (is_inside_epilog( (BYTE *)pc ))
2511             {
2512                 interpret_epilog( (BYTE *)pc, context, ctx_ptr );
2513                 *frame_ret = frame;
2514                 return NULL;
2515             }
2516         }
2517
2518         for (i = 0; i < info->count; i += get_opcode_size(info->opcodes[i]))
2519         {
2520             if (prolog_offset < info->opcodes[i].offset) continue; /* skip it */
2521
2522             switch (info->opcodes[i].code)
2523             {
2524             case UWOP_PUSH_NONVOL:  /* pushq %reg */
2525                 set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)context->Rsp );
2526                 context->Rsp += sizeof(ULONG64);
2527                 break;
2528             case UWOP_ALLOC_LARGE:  /* subq $nn,%rsp */
2529                 if (info->opcodes[i].info) context->Rsp += *(DWORD *)&info->opcodes[i+1];
2530                 else context->Rsp += *(USHORT *)&info->opcodes[i+1] * 8;
2531                 break;
2532             case UWOP_ALLOC_SMALL:  /* subq $n,%rsp */
2533                 context->Rsp += (info->opcodes[i].info + 1) * 8;
2534                 break;
2535             case UWOP_SET_FPREG:  /* leaq nn(%rsp),%framereg */
2536                 context->Rsp = *frame_ret = frame;
2537                 break;
2538             case UWOP_SAVE_NONVOL:  /* movq %reg,n(%rsp) */
2539                 off = frame + *(USHORT *)&info->opcodes[i+1] * 8;
2540                 set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)off );
2541                 break;
2542             case UWOP_SAVE_NONVOL_FAR:  /* movq %reg,nn(%rsp) */
2543                 off = frame + *(DWORD *)&info->opcodes[i+1];
2544                 set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)off );
2545                 break;
2546             case UWOP_SAVE_XMM128:  /* movaps %xmmreg,n(%rsp) */
2547                 off = frame + *(USHORT *)&info->opcodes[i+1] * 16;
2548                 set_float_reg( context, ctx_ptr, info->opcodes[i].info, *(M128A *)off );
2549                 break;
2550             case UWOP_SAVE_XMM128_FAR:  /* movaps %xmmreg,nn(%rsp) */
2551                 off = frame + *(DWORD *)&info->opcodes[i+1];
2552                 set_float_reg( context, ctx_ptr, info->opcodes[i].info, *(M128A *)off );
2553                 break;
2554             case UWOP_PUSH_MACHFRAME:
2555                 FIXME( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
2556                 break;
2557             default:
2558                 FIXME( "unknown code %u\n", info->opcodes[i].code );
2559                 break;
2560             }
2561         }
2562
2563         if (!(info->flags & UNW_FLAG_CHAININFO)) break;
2564         function = &handler_data->chain;  /* restart with the chained info */
2565     }
2566
2567     /* now pop return address */
2568     context->Rip = *(ULONG64 *)context->Rsp;
2569     context->Rsp += sizeof(ULONG64);
2570
2571     if (!(info->flags & type)) return NULL;  /* no matching handler */
2572     if (prolog_offset != ~0) return NULL;  /* inside prolog */
2573
2574     *data = &handler_data->handler + 1;
2575     return (char *)base + handler_data->handler;
2576 }
2577
2578
2579 /**********************************************************************
2580  *           call_unwind_handler
2581  *
2582  * Call a single unwind handler.
2583  * FIXME: Handle nested exceptions.
2584  */
2585 static void call_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch )
2586 {
2587     DWORD res;
2588
2589     dispatch->ControlPc = dispatch->ContextRecord->Rip;
2590
2591     TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
2592          dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
2593     res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
2594     TRACE( "handler %p returned %x\n", dispatch->LanguageHandler, res );
2595
2596     switch (res)
2597     {
2598     case ExceptionContinueSearch:
2599         break;
2600     case ExceptionCollidedUnwind:
2601         FIXME( "ExceptionCollidedUnwind not supported yet\n" );
2602         break;
2603     default:
2604         raise_status( STATUS_INVALID_DISPOSITION, rec );
2605         break;
2606     }
2607 }
2608
2609
2610 /**********************************************************************
2611  *           call_teb_unwind_handler
2612  *
2613  * Call a single unwind handler from the TEB chain.
2614  * FIXME: Handle nested exceptions.
2615  */
2616 static void call_teb_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
2617                                      EXCEPTION_REGISTRATION_RECORD *teb_frame )
2618 {
2619     EXCEPTION_REGISTRATION_RECORD *dispatcher;
2620     DWORD res;
2621
2622     TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatcher=%p)\n",
2623            teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, &dispatcher );
2624     res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, &dispatcher );
2625     TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );
2626
2627     switch (res)
2628     {
2629     case ExceptionContinueSearch:
2630         break;
2631     case ExceptionCollidedUnwind:
2632         FIXME( "ExceptionCollidedUnwind not supported yet\n" );
2633         break;
2634     default:
2635         raise_status( STATUS_INVALID_DISPOSITION, rec );
2636         break;
2637     }
2638 }
2639
2640
2641 /*******************************************************************
2642  *              RtlUnwindEx (NTDLL.@)
2643  */
2644 void WINAPI RtlUnwindEx( ULONG64 end_frame, ULONG64 target_ip, EXCEPTION_RECORD *rec,
2645                          ULONG64 retval, CONTEXT *orig_context, UNWIND_HISTORY_TABLE *table )
2646 {
2647     EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
2648     EXCEPTION_RECORD record;
2649     RUNTIME_FUNCTION *dir;
2650     DISPATCHER_CONTEXT dispatch;
2651     CONTEXT context, new_context;
2652     LDR_MODULE *module;
2653     NTSTATUS status;
2654     DWORD size;
2655
2656     /* build an exception record, if we do not have one */
2657     if (!rec)
2658     {
2659         record.ExceptionCode    = STATUS_UNWIND;
2660         record.ExceptionFlags   = 0;
2661         record.ExceptionRecord  = NULL;
2662         record.ExceptionAddress = (void *)orig_context->Rip;
2663         record.NumberParameters = 0;
2664         rec = &record;
2665     }
2666
2667     rec->ExceptionFlags |= EH_UNWINDING | (end_frame ? 0 : EH_EXIT_UNWIND);
2668
2669     TRACE( "code=%x flags=%x end_frame=%lx target_ip=%lx rip=%016lx\n",
2670            rec->ExceptionCode, rec->ExceptionFlags, end_frame, target_ip, orig_context->Rip );
2671     TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
2672           orig_context->Rax, orig_context->Rbx, orig_context->Rcx, orig_context->Rdx );
2673     TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
2674           orig_context->Rsi, orig_context->Rdi, orig_context->Rbp, orig_context->Rsp );
2675     TRACE("  r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
2676           orig_context->R8, orig_context->R9, orig_context->R10, orig_context->R11 );
2677     TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
2678           orig_context->R12, orig_context->R13, orig_context->R14, orig_context->R15 );
2679
2680     context = *orig_context;
2681     dispatch.EstablisherFrame = context.Rsp;
2682     dispatch.TargetIp         = target_ip;
2683     dispatch.ContextRecord    = &context;
2684     dispatch.HistoryTable     = table;
2685
2686     while (dispatch.EstablisherFrame != end_frame)
2687     {
2688         new_context = context;
2689
2690         /* FIXME: should use the history table to make things faster */
2691
2692         dir = NULL;
2693         module = NULL;
2694         dispatch.ImageBase = 0;
2695         dispatch.ScopeIndex = 0; /* FIXME */
2696
2697         if (!LdrFindEntryForAddress( (void *)context.Rip, &module ))
2698         {
2699             if (!(dir = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
2700                                                       IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )) &&
2701                 !(module->Flags & LDR_WINE_INTERNAL))
2702             {
2703                 ERR( "module %s doesn't contain exception data, can't unwind exception\n",
2704                      debugstr_w(module->BaseDllName.Buffer) );
2705                 raise_status( STATUS_BAD_FUNCTION_TABLE, rec );
2706             }
2707             dispatch.ImageBase = (ULONG64)module->BaseAddress;
2708         }
2709
2710         if (!dir)
2711         {
2712             struct dwarf_eh_bases bases;
2713             const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context.Rip - 1), &bases );
2714             if (!fde)
2715             {
2716                 /* assume leaf function */
2717                 context.Rip = *(ULONG64 *)context.Rsp;
2718                 context.Rsp += sizeof(ULONG64);
2719                 continue;
2720             }
2721             dispatch.FunctionEntry = NULL;
2722             status = dwarf_virtual_unwind( context.Rip, &dispatch.EstablisherFrame, &new_context, fde,
2723                                            &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
2724             if (status != STATUS_SUCCESS) raise_status( status, rec );
2725             if (dispatch.LanguageHandler && !module)
2726             {
2727                 FIXME( "calling personality routine in system library not supported yet\n" );
2728                 dispatch.LanguageHandler = NULL;
2729             }
2730         }
2731         else
2732         {
2733             if (!(dispatch.FunctionEntry = find_function_info( context.Rip, module->BaseAddress,
2734                                                                dir, size )))
2735             {
2736                 /* leaf function */
2737                 context.Rip = *(ULONG64 *)context.Rsp;
2738                 context.Rsp += sizeof(ULONG64);
2739                 continue;
2740             }
2741             dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_UHANDLER, dispatch.ImageBase,
2742                                                          context.Rip, dispatch.FunctionEntry,
2743                                                          &new_context, &dispatch.HandlerData,
2744                                                          &dispatch.EstablisherFrame, NULL );
2745         }
2746
2747         if (!dispatch.EstablisherFrame) break;
2748
2749         if (is_inside_signal_stack( (void *)dispatch.EstablisherFrame ))
2750         {
2751             TRACE( "frame %lx is inside signal stack (%p-%p)\n", dispatch.EstablisherFrame,
2752                    get_signal_stack(), (char *)get_signal_stack() + signal_stack_size );
2753             context = new_context;
2754             continue;
2755         }
2756
2757         if ((dispatch.EstablisherFrame & 7) ||
2758             dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
2759             dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
2760         {
2761             ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
2762                  NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
2763             rec->ExceptionFlags |= EH_STACK_INVALID;
2764             break;
2765         }
2766
2767         if (dispatch.LanguageHandler)
2768         {
2769             if (end_frame && (dispatch.EstablisherFrame > end_frame))
2770             {
2771                 ERR( "invalid end frame %lx/%lx\n", dispatch.EstablisherFrame, end_frame );
2772                 raise_status( STATUS_INVALID_UNWIND_TARGET, rec );
2773             }
2774             call_unwind_handler( rec, &dispatch );
2775         }
2776         else  /* hack: call builtin handlers registered in the tib list */
2777         {
2778             while ((ULONG64)teb_frame < new_context.Rsp && (ULONG64)teb_frame < end_frame)
2779             {
2780                 TRACE( "found builtin frame %p handler %p\n", teb_frame, teb_frame->Handler );
2781                 dispatch.EstablisherFrame = (ULONG64)teb_frame;
2782                 call_teb_unwind_handler( rec, &dispatch, teb_frame );
2783                 teb_frame = __wine_pop_frame( teb_frame );
2784             }
2785             if ((ULONG64)teb_frame == end_frame && end_frame < new_context.Rsp) break;
2786             dispatch.EstablisherFrame = new_context.Rsp;
2787         }
2788
2789         context = new_context;
2790     }
2791     context.Rax = retval;
2792     context.Rip = target_ip;
2793     TRACE( "returning to %lx stack %lx\n", context.Rip, context.Rsp );
2794     set_cpu_context( &context );
2795 }
2796
2797
2798 /*******************************************************************
2799  *              RtlUnwind (NTDLL.@)
2800  */
2801 void WINAPI __regs_RtlUnwind( ULONG64 frame, ULONG64 target_ip, EXCEPTION_RECORD *rec,
2802                               ULONG64 retval, CONTEXT *context )
2803 {
2804     RtlUnwindEx( frame, target_ip, rec, retval, context, NULL );
2805 }
2806 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )
2807
2808
2809 /*******************************************************************
2810  *              __C_specific_handler (NTDLL.@)
2811  */
2812 EXCEPTION_DISPOSITION WINAPI __C_specific_handler( EXCEPTION_RECORD *rec,
2813                                                    ULONG64 frame,
2814                                                    CONTEXT *context,
2815                                                    struct _DISPATCHER_CONTEXT *dispatch )
2816 {
2817     SCOPE_TABLE *table = dispatch->HandlerData;
2818     ULONG i;
2819
2820     TRACE( "%p %lx %p %p\n", rec, frame, context, dispatch );
2821     if (TRACE_ON(seh)) dump_scope_table( dispatch->ImageBase, table );
2822
2823     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))  /* FIXME */
2824         return ExceptionContinueSearch;
2825
2826     for (i = 0; i < table->Count; i++)
2827     {
2828         if (context->Rip >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
2829             context->Rip < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
2830         {
2831             if (!table->ScopeRecord[i].JumpTarget) continue;
2832             if (table->ScopeRecord[i].HandlerAddress != EXCEPTION_EXECUTE_HANDLER)
2833             {
2834                 EXCEPTION_POINTERS ptrs;
2835                 PC_LANGUAGE_EXCEPTION_HANDLER filter;
2836
2837                 filter = (PC_LANGUAGE_EXCEPTION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
2838                 ptrs.ExceptionRecord = rec;
2839                 ptrs.ContextRecord = context;
2840                 TRACE( "calling filter %p ptrs %p frame %lx\n", filter, &ptrs, frame );
2841                 switch (filter( &ptrs, frame ))
2842                 {
2843                 case EXCEPTION_EXECUTE_HANDLER:
2844                     break;
2845                 case EXCEPTION_CONTINUE_SEARCH:
2846                     continue;
2847                 case EXCEPTION_CONTINUE_EXECUTION:
2848                     return ExceptionContinueExecution;
2849                 }
2850             }
2851             TRACE( "unwinding to target %lx\n", dispatch->ImageBase + table->ScopeRecord[i].JumpTarget );
2852             RtlUnwindEx( frame, dispatch->ImageBase + table->ScopeRecord[i].JumpTarget,
2853                          rec, 0, context, dispatch->HistoryTable );
2854         }
2855     }
2856     return ExceptionContinueSearch;
2857 }
2858
2859
2860 /*******************************************************************
2861  *              NtRaiseException (NTDLL.@)
2862  */
2863 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
2864 {
2865     NTSTATUS status = raise_exception( rec, context, first_chance );
2866     if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
2867     return status;
2868 }
2869
2870
2871 /***********************************************************************
2872  *              RtlRaiseException (NTDLL.@)
2873  */
2874 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
2875 {
2876     NTSTATUS status;
2877
2878     rec->ExceptionAddress = (void *)context->Rip;
2879     status = raise_exception( rec, context, TRUE );
2880     if (status != STATUS_SUCCESS) raise_status( status, rec );
2881 }
2882 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 1 )
2883
2884
2885 /*************************************************************************
2886  *              RtlCaptureStackBackTrace (NTDLL.@)
2887  */
2888 USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
2889 {
2890     FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash );
2891     return 0;
2892 }
2893
2894
2895 /***********************************************************************
2896  *           call_thread_func
2897  */
2898 void call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
2899 {
2900     ntdll_get_thread_data()->exit_frame = frame;
2901     __TRY
2902     {
2903         RtlExitUserThread( entry( arg ));
2904     }
2905     __EXCEPT(unhandled_exception_filter)
2906     {
2907         NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
2908     }
2909     __ENDTRY
2910     abort();  /* should not be reached */
2911 }
2912
2913 extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
2914 __ASM_GLOBAL_FUNC( call_thread_entry_point,
2915                    "subq $8,%rsp\n\t"
2916                    ".cfi_adjust_cfa_offset 8\n\t"
2917                    "movq %rsp,%rdx\n\t"
2918                    "call " __ASM_NAME("call_thread_func") );
2919
2920 extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
2921 __ASM_GLOBAL_FUNC( call_thread_exit_func,
2922                    "subq $8,%rsp\n\t"
2923                    ".cfi_adjust_cfa_offset 8\n\t"
2924                    "movq %rdx,%rsp\n\t"
2925                    "call *%rsi" );
2926
2927 /***********************************************************************
2928  *           RtlExitUserThread  (NTDLL.@)
2929  */
2930 void WINAPI RtlExitUserThread( ULONG status )
2931 {
2932     if (!ntdll_get_thread_data()->exit_frame) exit_thread( status );
2933     call_thread_exit_func( status, exit_thread, ntdll_get_thread_data()->exit_frame );
2934 }
2935
2936 /***********************************************************************
2937  *           abort_thread
2938  */
2939 void abort_thread( int status )
2940 {
2941     if (!ntdll_get_thread_data()->exit_frame) terminate_thread( status );
2942     call_thread_exit_func( status, terminate_thread, ntdll_get_thread_data()->exit_frame );
2943 }
2944
2945 /**********************************************************************
2946  *              __wine_enter_vm86   (NTDLL.@)
2947  */
2948 void __wine_enter_vm86( CONTEXT *context )
2949 {
2950     MESSAGE("vm86 mode not supported on this platform\n");
2951 }
2952
2953 /**********************************************************************
2954  *              DbgBreakPoint   (NTDLL.@)
2955  */
2956 __ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
2957
2958 /**********************************************************************
2959  *              DbgUserBreakPoint   (NTDLL.@)
2960  */
2961 __ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
2962
2963 #endif  /* __x86_64__ */