ntdll: Always restore the context after an exception even if setting the debug regist...
[wine] / dlls / ntdll / signal_i386.c
1 /*
2  * i386 signal handling routines
3  *
4  * Copyright 1999 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 __i386__
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <sys/types.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35
36 #ifdef HAVE_SYS_PARAM_H
37 # include <sys/param.h>
38 #endif
39 #ifdef HAVE_SYSCALL_H
40 # include <syscall.h>
41 #else
42 # ifdef HAVE_SYS_SYSCALL_H
43 #  include <sys/syscall.h>
44 # endif
45 #endif
46
47 #ifdef HAVE_SYS_VM86_H
48 # include <sys/vm86.h>
49 #endif
50
51 #ifdef HAVE_SYS_SIGNAL_H
52 # include <sys/signal.h>
53 #endif
54 #ifdef HAVE_SYS_SYSCTL_H
55 # include <sys/sysctl.h>
56 #endif
57
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "windef.h"
61 #include "wine/library.h"
62 #include "ntdll_misc.h"
63 #include "wine/exception.h"
64 #include "wine/debug.h"
65
66 #ifdef HAVE_VALGRIND_MEMCHECK_H
67 #include <valgrind/memcheck.h>
68 #endif
69
70 #undef ERR  /* Solaris needs to define this */
71
72 /* not defined for x86, so copy the x86_64 definition */
73 typedef struct DECLSPEC_ALIGN(16) _M128A
74 {
75     ULONGLONG Low;
76     LONGLONG High;
77 } M128A;
78
79 typedef struct
80 {
81     WORD ControlWord;
82     WORD StatusWord;
83     BYTE TagWord;
84     BYTE Reserved1;
85     WORD ErrorOpcode;
86     DWORD ErrorOffset;
87     WORD ErrorSelector;
88     WORD Reserved2;
89     DWORD DataOffset;
90     WORD DataSelector;
91     WORD Reserved3;
92     DWORD MxCsr;
93     DWORD MxCsr_Mask;
94     M128A FloatRegisters[8];
95     M128A XmmRegisters[16];
96     BYTE Reserved4[96];
97 } XMM_SAVE_AREA32;
98
99 /***********************************************************************
100  * signal context platform-specific definitions
101  */
102
103 #ifdef linux
104
105 typedef ucontext_t SIGCONTEXT;
106
107 #define EAX_sig(context)     ((context)->uc_mcontext.gregs[REG_EAX])
108 #define EBX_sig(context)     ((context)->uc_mcontext.gregs[REG_EBX])
109 #define ECX_sig(context)     ((context)->uc_mcontext.gregs[REG_ECX])
110 #define EDX_sig(context)     ((context)->uc_mcontext.gregs[REG_EDX])
111 #define ESI_sig(context)     ((context)->uc_mcontext.gregs[REG_ESI])
112 #define EDI_sig(context)     ((context)->uc_mcontext.gregs[REG_EDI])
113 #define EBP_sig(context)     ((context)->uc_mcontext.gregs[REG_EBP])
114 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[REG_ESP])
115
116 #define CS_sig(context)      ((context)->uc_mcontext.gregs[REG_CS])
117 #define DS_sig(context)      ((context)->uc_mcontext.gregs[REG_DS])
118 #define ES_sig(context)      ((context)->uc_mcontext.gregs[REG_ES])
119 #define SS_sig(context)      ((context)->uc_mcontext.gregs[REG_SS])
120 #define FS_sig(context)      ((context)->uc_mcontext.gregs[REG_FS])
121 #define GS_sig(context)      ((context)->uc_mcontext.gregs[REG_GS])
122
123 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
124 #define EIP_sig(context)     ((context)->uc_mcontext.gregs[REG_EIP])
125 #define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
126 #define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])
127
128 #define FPU_sig(context)     ((FLOATING_SAVE_AREA*)((context)->uc_mcontext.fpregs))
129 #define FPUX_sig(context)    (FPU_sig(context) && !((context)->uc_mcontext.fpregs->status >> 16) ? (XMM_SAVE_AREA32 *)(FPU_sig(context) + 1) : NULL)
130
131 #define VM86_EAX 0 /* the %eax value while vm86_enter is executing */
132 #define VIF_FLAG 0x00080000
133 #define VIP_FLAG 0x00100000
134
135 int vm86_enter( void **vm86_ptr );
136 void vm86_return(void);
137 void vm86_return_end(void);
138 __ASM_GLOBAL_FUNC(vm86_enter,
139                   "pushl %ebp\n\t"
140                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
141                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
142                   "movl %esp,%ebp\n\t"
143                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
144                   "pushl %ebx\n\t"
145                   __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
146                   "movl $166,%eax\n\t"  /*SYS_vm86*/
147                   "movl 8(%ebp),%ecx\n\t" /* vm86_ptr */
148                   "movl (%ecx),%ecx\n\t"
149                   "movl $1,%ebx\n\t"    /*VM86_ENTER*/
150                   "pushl %ecx\n\t"      /* put vm86plus_struct ptr somewhere we can find it */
151                   "pushl %fs\n\t"
152                   "pushl %gs\n\t"
153                   "int $0x80\n"
154                   ".globl " __ASM_NAME("vm86_return") "\n\t"
155                   __ASM_FUNC("vm86_return") "\n"
156                   __ASM_NAME("vm86_return") ":\n\t"
157                   "popl %gs\n\t"
158                   "popl %fs\n\t"
159                   "popl %ecx\n\t"
160                   "popl %ebx\n\t"
161                   __ASM_CFI(".cfi_same_value %ebx\n\t")
162                   "popl %ebp\n\t"
163                   __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
164                   __ASM_CFI(".cfi_same_value %ebp\n\t")
165                   "testl %eax,%eax\n\t"
166                   "jl 0f\n\t"
167                   "cmpb $0,%al\n\t" /* VM86_SIGNAL */
168                   "je " __ASM_NAME("vm86_enter") "\n\t"
169                   "0:\n\t"
170                   "movl 4(%esp),%ecx\n\t"  /* vm86_ptr */
171                   "movl $0,(%ecx)\n\t"
172                   ".globl " __ASM_NAME("vm86_return_end") "\n\t"
173                   __ASM_FUNC("vm86_return_end") "\n"
174                   __ASM_NAME("vm86_return_end") ":\n\t"
175                   "ret" )
176
177 #ifdef HAVE_SYS_VM86_H
178 # define __HAVE_VM86
179 #endif
180
181 #endif  /* linux */
182
183 #ifdef BSDI
184
185 #include <machine/frame.h>
186 typedef struct trapframe SIGCONTEXT;
187
188 #define EAX_sig(context)     ((context)->tf_eax)
189 #define EBX_sig(context)     ((context)->tf_ebx)
190 #define ECX_sig(context)     ((context)->tf_ecx)
191 #define EDX_sig(context)     ((context)->tf_edx)
192 #define ESI_sig(context)     ((context)->tf_esi)
193 #define EDI_sig(context)     ((context)->tf_edi)
194 #define EBP_sig(context)     ((context)->tf_ebp)
195
196 #define CS_sig(context)      ((context)->tf_cs)
197 #define DS_sig(context)      ((context)->tf_ds)
198 #define ES_sig(context)      ((context)->tf_es)
199 #define SS_sig(context)      ((context)->tf_ss)
200
201 #define EFL_sig(context)     ((context)->tf_eflags)
202
203 #define EIP_sig(context)     (*((unsigned long*)&(context)->tf_eip))
204 #define ESP_sig(context)     (*((unsigned long*)&(context)->tf_esp))
205
206 #define FPU_sig(context)     NULL  /* FIXME */
207 #define FPUX_sig(context)    NULL  /* FIXME */
208
209 #endif /* bsdi */
210
211 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
212
213 typedef struct sigcontext SIGCONTEXT;
214
215 #define EAX_sig(context)     ((context)->sc_eax)
216 #define EBX_sig(context)     ((context)->sc_ebx)
217 #define ECX_sig(context)     ((context)->sc_ecx)
218 #define EDX_sig(context)     ((context)->sc_edx)
219 #define ESI_sig(context)     ((context)->sc_esi)
220 #define EDI_sig(context)     ((context)->sc_edi)
221 #define EBP_sig(context)     ((context)->sc_ebp)
222
223 #define CS_sig(context)      ((context)->sc_cs)
224 #define DS_sig(context)      ((context)->sc_ds)
225 #define ES_sig(context)      ((context)->sc_es)
226 #define FS_sig(context)      ((context)->sc_fs)
227 #define GS_sig(context)      ((context)->sc_gs)
228 #define SS_sig(context)      ((context)->sc_ss)
229
230 #define TRAP_sig(context)    ((context)->sc_trapno)
231 #define ERROR_sig(context)   ((context)->sc_err)
232 #define EFL_sig(context)     ((context)->sc_eflags)
233
234 #define EIP_sig(context)     ((context)->sc_eip)
235 #define ESP_sig(context)     ((context)->sc_esp)
236
237 #define FPU_sig(context)     NULL  /* FIXME */
238 #define FPUX_sig(context)    NULL  /* FIXME */
239
240 #endif  /* __FreeBSD__ */
241
242 #ifdef __OpenBSD__
243
244 typedef struct sigcontext SIGCONTEXT;
245
246 #define EAX_sig(context)     ((context)->sc_eax)
247 #define EBX_sig(context)     ((context)->sc_ebx)
248 #define ECX_sig(context)     ((context)->sc_ecx)
249 #define EDX_sig(context)     ((context)->sc_edx)
250 #define ESI_sig(context)     ((context)->sc_esi)
251 #define EDI_sig(context)     ((context)->sc_edi)
252 #define EBP_sig(context)     ((context)->sc_ebp)
253
254 #define CS_sig(context)      ((context)->sc_cs)
255 #define DS_sig(context)      ((context)->sc_ds)
256 #define ES_sig(context)      ((context)->sc_es)
257 #define FS_sig(context)      ((context)->sc_fs)
258 #define GS_sig(context)      ((context)->sc_gs)
259 #define SS_sig(context)      ((context)->sc_ss)
260
261 #define TRAP_sig(context)    ((context)->sc_trapno)
262 #define ERROR_sig(context)   ((context)->sc_err)
263 #define EFL_sig(context)     ((context)->sc_eflags)
264
265 #define EIP_sig(context)     ((context)->sc_eip)
266 #define ESP_sig(context)     ((context)->sc_esp)
267
268 #define FPU_sig(context)     NULL  /* FIXME */
269 #define FPUX_sig(context)    NULL  /* FIXME */
270
271 #define T_MCHK T_MACHK
272 #define T_XMMFLT T_XFTRAP
273
274 #endif  /* __OpenBSD__ */
275
276 #if defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
277
278 #ifdef _SCO_DS
279 #include <sys/regset.h>
280 #endif
281 #include <sys/ucontext.h>
282 typedef struct ucontext SIGCONTEXT;
283
284 #ifdef _SCO_DS
285 #define gregs regs
286 #endif
287
288 #define EAX_sig(context)     ((context)->uc_mcontext.gregs[EAX])
289 #define EBX_sig(context)     ((context)->uc_mcontext.gregs[EBX])
290 #define ECX_sig(context)     ((context)->uc_mcontext.gregs[ECX])
291 #define EDX_sig(context)     ((context)->uc_mcontext.gregs[EDX])
292 #define ESI_sig(context)     ((context)->uc_mcontext.gregs[ESI])
293 #define EDI_sig(context)     ((context)->uc_mcontext.gregs[EDI])
294 #define EBP_sig(context)     ((context)->uc_mcontext.gregs[EBP])
295
296 #define CS_sig(context)      ((context)->uc_mcontext.gregs[CS])
297 #define DS_sig(context)      ((context)->uc_mcontext.gregs[DS])
298 #define ES_sig(context)      ((context)->uc_mcontext.gregs[ES])
299 #define SS_sig(context)      ((context)->uc_mcontext.gregs[SS])
300
301 #define FS_sig(context)      ((context)->uc_mcontext.gregs[FS])
302 #define GS_sig(context)      ((context)->uc_mcontext.gregs[GS])
303
304 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[EFL])
305
306 #define EIP_sig(context)     ((context)->uc_mcontext.gregs[EIP])
307 #ifdef UESP
308 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[UESP])
309 #elif defined(R_ESP)
310 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[R_ESP])
311 #else
312 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[ESP])
313 #endif
314 #ifdef ERR
315 #define ERROR_sig(context)   ((context)->uc_mcontext.gregs[ERR])
316 #endif
317 #ifdef TRAPNO
318 #define TRAP_sig(context)     ((context)->uc_mcontext.gregs[TRAPNO])
319 #endif
320
321 #define FPU_sig(context)     NULL  /* FIXME */
322 #define FPUX_sig(context)    NULL  /* FIXME */
323
324 #endif  /* svr4 || SCO_DS */
325
326 #ifdef __APPLE__
327 # include <sys/ucontext.h>
328
329 typedef ucontext_t SIGCONTEXT;
330
331 /* work around silly renaming of struct members in OS X 10.5 */
332 #if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32)
333 #define EAX_sig(context)     ((context)->uc_mcontext->__ss.__eax)
334 #define EBX_sig(context)     ((context)->uc_mcontext->__ss.__ebx)
335 #define ECX_sig(context)     ((context)->uc_mcontext->__ss.__ecx)
336 #define EDX_sig(context)     ((context)->uc_mcontext->__ss.__edx)
337 #define ESI_sig(context)     ((context)->uc_mcontext->__ss.__esi)
338 #define EDI_sig(context)     ((context)->uc_mcontext->__ss.__edi)
339 #define EBP_sig(context)     ((context)->uc_mcontext->__ss.__ebp)
340 #define CS_sig(context)      ((context)->uc_mcontext->__ss.__cs)
341 #define DS_sig(context)      ((context)->uc_mcontext->__ss.__ds)
342 #define ES_sig(context)      ((context)->uc_mcontext->__ss.__es)
343 #define FS_sig(context)      ((context)->uc_mcontext->__ss.__fs)
344 #define GS_sig(context)      ((context)->uc_mcontext->__ss.__gs)
345 #define SS_sig(context)      ((context)->uc_mcontext->__ss.__ss)
346 #define EFL_sig(context)     ((context)->uc_mcontext->__ss.__eflags)
347 #define EIP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->__ss.__eip))
348 #define ESP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->__ss.__esp))
349 #define TRAP_sig(context)    ((context)->uc_mcontext->__es.__trapno)
350 #define ERROR_sig(context)   ((context)->uc_mcontext->__es.__err)
351 #define FPU_sig(context)     NULL
352 #define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->__fs.__fpu_fcw)
353 #else
354 #define EAX_sig(context)     ((context)->uc_mcontext->ss.eax)
355 #define EBX_sig(context)     ((context)->uc_mcontext->ss.ebx)
356 #define ECX_sig(context)     ((context)->uc_mcontext->ss.ecx)
357 #define EDX_sig(context)     ((context)->uc_mcontext->ss.edx)
358 #define ESI_sig(context)     ((context)->uc_mcontext->ss.esi)
359 #define EDI_sig(context)     ((context)->uc_mcontext->ss.edi)
360 #define EBP_sig(context)     ((context)->uc_mcontext->ss.ebp)
361 #define CS_sig(context)      ((context)->uc_mcontext->ss.cs)
362 #define DS_sig(context)      ((context)->uc_mcontext->ss.ds)
363 #define ES_sig(context)      ((context)->uc_mcontext->ss.es)
364 #define FS_sig(context)      ((context)->uc_mcontext->ss.fs)
365 #define GS_sig(context)      ((context)->uc_mcontext->ss.gs)
366 #define SS_sig(context)      ((context)->uc_mcontext->ss.ss)
367 #define EFL_sig(context)     ((context)->uc_mcontext->ss.eflags)
368 #define EIP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.eip))
369 #define ESP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.esp))
370 #define TRAP_sig(context)    ((context)->uc_mcontext->es.trapno)
371 #define ERROR_sig(context)   ((context)->uc_mcontext->es.err)
372 #define FPU_sig(context)     NULL
373 #define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->fs.fpu_fcw)
374 #endif
375
376 #endif /* __APPLE__ */
377
378 #if defined(__NetBSD__)
379 # include <sys/ucontext.h>
380 # include <sys/types.h>
381 # include <signal.h>
382
383 typedef ucontext_t SIGCONTEXT;
384
385 #define EAX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EAX])
386 #define EBX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EBX])
387 #define ECX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_ECX])
388 #define EDX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EDX])
389 #define ESI_sig(context)       ((context)->uc_mcontext.__gregs[_REG_ESI])
390 #define EDI_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EDI])
391 #define EBP_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EBP])
392 #define ESP_sig(context)       _UC_MACHINE_SP(context)
393
394 #define CS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_CS])
395 #define DS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_DS])
396 #define ES_sig(context)        ((context)->uc_mcontext.__gregs[_REG_ES])
397 #define SS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_SS])
398 #define FS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_FS])
399 #define GS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_GS])
400
401 #define EFL_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EFL])
402 #define EIP_sig(context)       _UC_MACHINE_PC(context)
403 #define TRAP_sig(context)      ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
404 #define ERROR_sig(context)     ((context)->uc_mcontext.__gregs[_REG_ERR])
405
406 #define FPU_sig(context)     NULL
407 #define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&((context)->uc_mcontext.__fpregs))
408
409 #define T_MCHK T_MCA
410 #define T_XMMFLT T_XMM
411
412 #endif /* __NetBSD__ */
413
414 WINE_DEFAULT_DEBUG_CHANNEL(seh);
415
416 typedef int (*wine_signal_handler)(unsigned int sig);
417
418 static const size_t teb_size = 4096;  /* we reserve one page for the TEB */
419 static size_t signal_stack_mask;
420 static size_t signal_stack_size;
421
422 static wine_signal_handler handlers[256];
423
424 static int fpux_support;  /* whether the CPU support extended fpu context */
425
426 extern void DECLSPEC_NORETURN __wine_restore_regs( const CONTEXT *context );
427
428 enum i386_trap_code
429 {
430     TRAP_x86_UNKNOWN    = -1,  /* Unknown fault (TRAP_sig not defined) */
431 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
432     TRAP_x86_DIVIDE     = T_DIVIDE,     /* Division by zero exception */
433     TRAP_x86_TRCTRAP    = T_TRCTRAP,    /* Single-step exception */
434     TRAP_x86_NMI        = T_NMI,        /* NMI interrupt */
435     TRAP_x86_BPTFLT     = T_BPTFLT,     /* Breakpoint exception */
436     TRAP_x86_OFLOW      = T_OFLOW,      /* Overflow exception */
437     TRAP_x86_BOUND      = T_BOUND,      /* Bound range exception */
438     TRAP_x86_PRIVINFLT  = T_PRIVINFLT,  /* Invalid opcode exception */
439     TRAP_x86_DNA        = T_DNA,        /* Device not available exception */
440     TRAP_x86_DOUBLEFLT  = T_DOUBLEFLT,  /* Double fault exception */
441     TRAP_x86_FPOPFLT    = T_FPOPFLT,    /* Coprocessor segment overrun */
442     TRAP_x86_TSSFLT     = T_TSSFLT,     /* Invalid TSS exception */
443     TRAP_x86_SEGNPFLT   = T_SEGNPFLT,   /* Segment not present exception */
444     TRAP_x86_STKFLT     = T_STKFLT,     /* Stack fault */
445     TRAP_x86_PROTFLT    = T_PROTFLT,    /* General protection fault */
446     TRAP_x86_PAGEFLT    = T_PAGEFLT,    /* Page fault */
447     TRAP_x86_ARITHTRAP  = T_ARITHTRAP,  /* Floating point exception */
448     TRAP_x86_ALIGNFLT   = T_ALIGNFLT,   /* Alignment check exception */
449     TRAP_x86_MCHK       = T_MCHK,       /* Machine check exception */
450     TRAP_x86_CACHEFLT   = T_XMMFLT      /* Cache flush exception */
451 #else
452     TRAP_x86_DIVIDE     = 0,   /* Division by zero exception */
453     TRAP_x86_TRCTRAP    = 1,   /* Single-step exception */
454     TRAP_x86_NMI        = 2,   /* NMI interrupt */
455     TRAP_x86_BPTFLT     = 3,   /* Breakpoint exception */
456     TRAP_x86_OFLOW      = 4,   /* Overflow exception */
457     TRAP_x86_BOUND      = 5,   /* Bound range exception */
458     TRAP_x86_PRIVINFLT  = 6,   /* Invalid opcode exception */
459     TRAP_x86_DNA        = 7,   /* Device not available exception */
460     TRAP_x86_DOUBLEFLT  = 8,   /* Double fault exception */
461     TRAP_x86_FPOPFLT    = 9,   /* Coprocessor segment overrun */
462     TRAP_x86_TSSFLT     = 10,  /* Invalid TSS exception */
463     TRAP_x86_SEGNPFLT   = 11,  /* Segment not present exception */
464     TRAP_x86_STKFLT     = 12,  /* Stack fault */
465     TRAP_x86_PROTFLT    = 13,  /* General protection fault */
466     TRAP_x86_PAGEFLT    = 14,  /* Page fault */
467     TRAP_x86_ARITHTRAP  = 16,  /* Floating point exception */
468     TRAP_x86_ALIGNFLT   = 17,  /* Alignment check exception */
469     TRAP_x86_MCHK       = 18,  /* Machine check exception */
470     TRAP_x86_CACHEFLT   = 19   /* SIMD exception (via SIGFPE) if CPU is SSE capable
471                                   otherwise Cache flush exception (via SIGSEV) */
472 #endif
473 };
474
475 /* Exception record for handling exceptions happening inside exception handlers */
476 typedef struct
477 {
478     EXCEPTION_REGISTRATION_RECORD frame;
479     EXCEPTION_REGISTRATION_RECORD *prevFrame;
480 } EXC_NESTED_FRAME;
481
482 extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
483                               CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
484                               PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler );
485
486 /***********************************************************************
487  *           dispatch_signal
488  */
489 static inline int dispatch_signal(unsigned int sig)
490 {
491     if (handlers[sig] == NULL) return 0;
492     return handlers[sig](sig);
493 }
494
495
496 /***********************************************************************
497  *           get_trap_code
498  *
499  * Get the trap code for a signal.
500  */
501 static inline enum i386_trap_code get_trap_code( const SIGCONTEXT *sigcontext )
502 {
503 #ifdef TRAP_sig
504     return TRAP_sig(sigcontext);
505 #else
506     return TRAP_x86_UNKNOWN;  /* unknown trap code */
507 #endif
508 }
509
510 /***********************************************************************
511  *           get_error_code
512  *
513  * Get the error code for a signal.
514  */
515 static inline WORD get_error_code( const SIGCONTEXT *sigcontext )
516 {
517 #ifdef ERROR_sig
518     return ERROR_sig(sigcontext);
519 #else
520     return 0;
521 #endif
522 }
523
524 /***********************************************************************
525  *           get_signal_stack
526  *
527  * Get the base of the signal stack for the current thread.
528  */
529 static inline void *get_signal_stack(void)
530 {
531     return (char *)NtCurrentTeb() + 4096;
532 }
533
534
535 /***********************************************************************
536  *           get_current_teb
537  *
538  * Get the current teb based on the stack pointer.
539  */
540 static inline TEB *get_current_teb(void)
541 {
542     unsigned long esp;
543     __asm__("movl %%esp,%0" : "=g" (esp) );
544     return (TEB *)(esp & ~signal_stack_mask);
545 }
546
547
548 /*******************************************************************
549  *         raise_handler
550  *
551  * Handler for exceptions happening inside a handler.
552  */
553 static DWORD raise_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
554                             CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
555 {
556     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
557         return ExceptionContinueSearch;
558     /* We shouldn't get here so we store faulty frame in dispatcher */
559     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
560     return ExceptionNestedException;
561 }
562
563
564 /*******************************************************************
565  *         unwind_handler
566  *
567  * Handler for exceptions happening inside an unwind handler.
568  */
569 static DWORD unwind_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
570                              CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
571 {
572     if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
573         return ExceptionContinueSearch;
574     /* We shouldn't get here so we store faulty frame in dispatcher */
575     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
576     return ExceptionCollidedUnwind;
577 }
578
579
580 /**********************************************************************
581  *           call_stack_handlers
582  *
583  * Call the stack handlers chain.
584  */
585 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
586 {
587     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
588     DWORD res;
589
590     frame = NtCurrentTeb()->Tib.ExceptionList;
591     nested_frame = NULL;
592     while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
593     {
594         /* Check frame address */
595         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
596             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
597             (ULONG_PTR)frame & 3)
598         {
599             rec->ExceptionFlags |= EH_STACK_INVALID;
600             break;
601         }
602
603         /* Call handler */
604         TRACE( "calling handler at %p code=%x flags=%x\n",
605                frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
606         res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, raise_handler );
607         TRACE( "handler at %p returned %x\n", frame->Handler, res );
608
609         if (frame == nested_frame)
610         {
611             /* no longer nested */
612             nested_frame = NULL;
613             rec->ExceptionFlags &= ~EH_NESTED_CALL;
614         }
615
616         switch(res)
617         {
618         case ExceptionContinueExecution:
619             if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
620             return STATUS_NONCONTINUABLE_EXCEPTION;
621         case ExceptionContinueSearch:
622             break;
623         case ExceptionNestedException:
624             if (nested_frame < dispatch) nested_frame = dispatch;
625             rec->ExceptionFlags |= EH_NESTED_CALL;
626             break;
627         default:
628             return STATUS_INVALID_DISPOSITION;
629         }
630         frame = frame->Prev;
631     }
632     return STATUS_UNHANDLED_EXCEPTION;
633 }
634
635
636 /*******************************************************************
637  *              raise_exception
638  *
639  * Implementation of NtRaiseException.
640  */
641 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
642 {
643     NTSTATUS status;
644
645     if (first_chance)
646     {
647         DWORD c;
648
649         TRACE( "code=%x flags=%x addr=%p ip=%08x tid=%04x\n",
650                rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
651                context->Eip, GetCurrentThreadId() );
652         for (c = 0; c < rec->NumberParameters; c++)
653             TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
654         if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
655         {
656             if (rec->ExceptionInformation[1] >> 16)
657                 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
658                          rec->ExceptionAddress,
659                          (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
660             else
661                 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
662                          rec->ExceptionAddress,
663                          (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
664         }
665         else
666         {
667             TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
668                   context->Eax, context->Ebx, context->Ecx,
669                   context->Edx, context->Esi, context->Edi );
670             TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
671                   context->Ebp, context->Esp, context->SegCs, context->SegDs,
672                   context->SegEs, context->SegFs, context->SegGs, context->EFlags );
673         }
674         status = send_debug_event( rec, TRUE, context );
675         if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
676             return STATUS_SUCCESS;
677
678         /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
679         if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
680
681         if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
682             return STATUS_SUCCESS;
683
684         if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
685             return status;
686     }
687
688     /* last chance exception */
689
690     status = send_debug_event( rec, FALSE, context );
691     if (status != DBG_CONTINUE)
692     {
693         if (rec->ExceptionFlags & EH_STACK_INVALID)
694             WINE_ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
695         else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
696             WINE_ERR("Process attempted to continue execution after noncontinuable exception.\n");
697         else
698             WINE_ERR("Unhandled exception code %x flags %x addr %p\n",
699                      rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
700         NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
701     }
702     return STATUS_SUCCESS;
703 }
704
705
706 #ifdef __HAVE_VM86
707 /***********************************************************************
708  *           save_vm86_context
709  *
710  * Set the register values from a vm86 structure.
711  */
712 static void save_vm86_context( CONTEXT *context, const struct vm86plus_struct *vm86 )
713 {
714     context->ContextFlags = CONTEXT_FULL;
715     context->Eax    = vm86->regs.eax;
716     context->Ebx    = vm86->regs.ebx;
717     context->Ecx    = vm86->regs.ecx;
718     context->Edx    = vm86->regs.edx;
719     context->Esi    = vm86->regs.esi;
720     context->Edi    = vm86->regs.edi;
721     context->Esp    = vm86->regs.esp;
722     context->Ebp    = vm86->regs.ebp;
723     context->Eip    = vm86->regs.eip;
724     context->SegCs  = vm86->regs.cs;
725     context->SegDs  = vm86->regs.ds;
726     context->SegEs  = vm86->regs.es;
727     context->SegFs  = vm86->regs.fs;
728     context->SegGs  = vm86->regs.gs;
729     context->SegSs  = vm86->regs.ss;
730     context->EFlags = vm86->regs.eflags;
731 }
732
733
734 /***********************************************************************
735  *           restore_vm86_context
736  *
737  * Build a vm86 structure from the register values.
738  */
739 static void restore_vm86_context( const CONTEXT *context, struct vm86plus_struct *vm86 )
740 {
741     vm86->regs.eax    = context->Eax;
742     vm86->regs.ebx    = context->Ebx;
743     vm86->regs.ecx    = context->Ecx;
744     vm86->regs.edx    = context->Edx;
745     vm86->regs.esi    = context->Esi;
746     vm86->regs.edi    = context->Edi;
747     vm86->regs.esp    = context->Esp;
748     vm86->regs.ebp    = context->Ebp;
749     vm86->regs.eip    = context->Eip;
750     vm86->regs.cs     = context->SegCs;
751     vm86->regs.ds     = context->SegDs;
752     vm86->regs.es     = context->SegEs;
753     vm86->regs.fs     = context->SegFs;
754     vm86->regs.gs     = context->SegGs;
755     vm86->regs.ss     = context->SegSs;
756     vm86->regs.eflags = context->EFlags;
757 }
758
759
760 /**********************************************************************
761  *              merge_vm86_pending_flags
762  *
763  * Merges TEB.vm86_ptr and TEB.vm86_pending VIP flags and
764  * raises exception if there are pending events and VIF flag
765  * has been turned on.
766  *
767  * Called from __wine_enter_vm86 because vm86_enter
768  * doesn't check for pending events. 
769  *
770  * Called from raise_vm86_sti_exception to check for
771  * pending events in a signal safe way.
772  */
773 static void merge_vm86_pending_flags( EXCEPTION_RECORD *rec )
774 {
775     BOOL check_pending = TRUE;
776     struct vm86plus_struct *vm86 =
777         (struct vm86plus_struct*)(ntdll_get_thread_data()->vm86_ptr);
778
779     /*
780      * In order to prevent a race when SIGUSR2 occurs while
781      * we are returning from exception handler, pending events
782      * will be rechecked after each raised exception.
783      */
784     while (check_pending && get_vm86_teb_info()->vm86_pending)
785     {
786         check_pending = FALSE;
787         ntdll_get_thread_data()->vm86_ptr = NULL;
788             
789         /*
790          * If VIF is set, throw exception.
791          * Note that SIGUSR2 may turn VIF flag off so
792          * VIF check must occur only when TEB.vm86_ptr is NULL.
793          */
794         if (vm86->regs.eflags & VIF_FLAG)
795         {
796             CONTEXT vcontext;
797             save_vm86_context( &vcontext, vm86 );
798             
799             rec->ExceptionCode    = EXCEPTION_VM86_STI;
800             rec->ExceptionFlags   = EXCEPTION_CONTINUABLE;
801             rec->ExceptionRecord  = NULL;
802             rec->NumberParameters = 0;
803             rec->ExceptionAddress = (LPVOID)vcontext.Eip;
804
805             vcontext.EFlags &= ~VIP_FLAG;
806             get_vm86_teb_info()->vm86_pending = 0;
807             raise_exception( rec, &vcontext, TRUE );
808
809             restore_vm86_context( &vcontext, vm86 );
810             check_pending = TRUE;
811         }
812
813         ntdll_get_thread_data()->vm86_ptr = vm86;
814     }
815
816     /*
817      * Merge VIP flags in a signal safe way. This requires
818      * that the following operation compiles into atomic
819      * instruction.
820      */
821     vm86->regs.eflags |= get_vm86_teb_info()->vm86_pending;
822 }
823 #endif /* __HAVE_VM86 */
824
825
826 #ifdef __sun
827
828 /* We have to workaround two Solaris breakages:
829  * - Solaris doesn't restore %ds and %es before calling the signal handler so exceptions in 16-bit
830  *   code crash badly.
831  * - Solaris inserts a libc trampoline to call our handler, but the trampoline expects that registers
832  *   are setup correctly. So we need to insert our own trampoline below the libc trampoline to set %gs.
833  */
834
835 extern int sigaction_syscall( int sig, const struct sigaction *new, struct sigaction *old );
836 __ASM_GLOBAL_FUNC( sigaction_syscall,
837                   "movl $0x62,%eax\n\t"
838                   "int $0x91\n\t"
839                   "ret" )
840
841 /* assume the same libc handler is used for all signals */
842 static void (*libc_sigacthandler)( int signal, siginfo_t *siginfo, void *context );
843
844 static void wine_sigacthandler( int signal, siginfo_t *siginfo, void *sigcontext )
845 {
846     struct ntdll_thread_data *thread_data;
847
848     __asm__ __volatile__("mov %ss,%ax; mov %ax,%ds; mov %ax,%es");
849
850     thread_data = (struct ntdll_thread_data *)get_current_teb()->SpareBytes1;
851     wine_set_fs( thread_data->fs );
852     wine_set_gs( thread_data->gs );
853
854     libc_sigacthandler( signal, siginfo, sigcontext );
855 }
856
857 static int solaris_sigaction( int sig, const struct sigaction *new, struct sigaction *old )
858 {
859     struct sigaction real_act;
860
861     if (sigaction( sig, new, old ) == -1) return -1;
862
863     /* retrieve the real handler and flags with a direct syscall */
864     sigaction_syscall( sig, NULL, &real_act );
865     libc_sigacthandler = real_act.sa_sigaction;
866     real_act.sa_sigaction = wine_sigacthandler;
867     sigaction_syscall( sig, &real_act, NULL );
868     return 0;
869 }
870 #define sigaction(sig,new,old) solaris_sigaction(sig,new,old)
871
872 #endif
873
874 typedef void (WINAPI *raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
875
876
877 /***********************************************************************
878  *           init_handler
879  *
880  * Handler initialization when the full context is not needed.
881  * Return the stack pointer to use for pushing the exception data.
882  */
883 static inline void *init_handler( const SIGCONTEXT *sigcontext, WORD *fs, WORD *gs )
884 {
885     TEB *teb = get_current_teb();
886
887     /* get %fs and %gs at time of the fault */
888 #ifdef FS_sig
889     *fs = LOWORD(FS_sig(sigcontext));
890 #else
891     *fs = wine_get_fs();
892 #endif
893 #ifdef GS_sig
894     *gs = LOWORD(GS_sig(sigcontext));
895 #else
896     *gs = wine_get_gs();
897 #endif
898
899 #ifndef __sun  /* see above for Solaris handling */
900     {
901         struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
902         wine_set_fs( thread_data->fs );
903         wine_set_gs( thread_data->gs );
904     }
905 #endif
906
907     if (!wine_ldt_is_system(CS_sig(sigcontext)) ||
908         !wine_ldt_is_system(SS_sig(sigcontext)))  /* 16-bit mode */
909     {
910         /*
911          * Win16 or DOS protected mode. Note that during switch
912          * from 16-bit mode to linear mode, CS may be set to system
913          * segment before FS is restored. Fortunately, in this case
914          * SS is still non-system segment. This is why both CS and SS
915          * are checked.
916          */
917         return teb->WOW32Reserved;
918     }
919     return (void *)(ESP_sig(sigcontext) & ~3);
920 }
921
922
923 /***********************************************************************
924  *           save_fpu
925  *
926  * Save the thread FPU context.
927  */
928 static inline void save_fpu( CONTEXT *context )
929 {
930 #ifdef __GNUC__
931     context->ContextFlags |= CONTEXT_FLOATING_POINT;
932     __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
933 #endif
934 }
935
936
937 /***********************************************************************
938  *           save_fpux
939  *
940  * Save the thread FPU extended context.
941  */
942 static inline void save_fpux( CONTEXT *context )
943 {
944 #ifdef __GNUC__
945     /* we have to enforce alignment by hand */
946     char buffer[sizeof(XMM_SAVE_AREA32) + 16];
947     XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
948
949     __asm__ __volatile__( "fxsave %0" : "=m" (*state) );
950     context->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
951     memcpy( context->ExtendedRegisters, state, sizeof(*state) );
952 #endif
953 }
954
955
956 /***********************************************************************
957  *           restore_fpu
958  *
959  * Restore the FPU context to a sigcontext.
960  */
961 static inline void restore_fpu( const CONTEXT *context )
962 {
963     FLOATING_SAVE_AREA float_status = context->FloatSave;
964     /* reset the current interrupt status */
965     float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
966 #ifdef __GNUC__
967     __asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
968 #endif  /* __GNUC__ */
969 }
970
971
972 /***********************************************************************
973  *           restore_fpux
974  *
975  * Restore the FPU extended context to a sigcontext.
976  */
977 static inline void restore_fpux( const CONTEXT *context )
978 {
979 #ifdef __GNUC__
980     /* we have to enforce alignment by hand */
981     char buffer[sizeof(XMM_SAVE_AREA32) + 16];
982     XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
983
984     memcpy( state, context->ExtendedRegisters, sizeof(*state) );
985     /* reset the current interrupt status */
986     state->StatusWord &= state->ControlWord | 0xff80;
987     __asm__ __volatile__( "fxrstor %0" : : "m" (*state) );
988 #endif
989 }
990
991
992 /***********************************************************************
993  *           fpux_to_fpu
994  *
995  * Build a standard FPU context from an extended one.
996  */
997 static void fpux_to_fpu( FLOATING_SAVE_AREA *fpu, const XMM_SAVE_AREA32 *fpux )
998 {
999     unsigned int i, tag, stack_top;
1000
1001     fpu->ControlWord   = fpux->ControlWord | 0xffff0000;
1002     fpu->StatusWord    = fpux->StatusWord | 0xffff0000;
1003     fpu->ErrorOffset   = fpux->ErrorOffset;
1004     fpu->ErrorSelector = fpux->ErrorSelector | (fpux->ErrorOpcode << 16);
1005     fpu->DataOffset    = fpux->DataOffset;
1006     fpu->DataSelector  = fpux->DataSelector;
1007     fpu->Cr0NpxState   = fpux->StatusWord | 0xffff0000;
1008
1009     stack_top = (fpux->StatusWord >> 11) & 7;
1010     fpu->TagWord = 0xffff0000;
1011     for (i = 0; i < 8; i++)
1012     {
1013         memcpy( &fpu->RegisterArea[10 * i], &fpux->FloatRegisters[i], 10 );
1014         if (!(fpux->TagWord & (1 << i))) tag = 3;  /* empty */
1015         else
1016         {
1017             const M128A *reg = &fpux->FloatRegisters[(i - stack_top) & 7];
1018             if ((reg->High & 0x7fff) == 0x7fff)  /* exponent all ones */
1019             {
1020                 tag = 2;  /* special */
1021             }
1022             else if (!(reg->High & 0x7fff))  /* exponent all zeroes */
1023             {
1024                 if (reg->Low) tag = 2;  /* special */
1025                 else tag = 1;  /* zero */
1026             }
1027             else
1028             {
1029                 if (reg->Low >> 63) tag = 0;  /* valid */
1030                 else tag = 2;  /* special */
1031             }
1032         }
1033         fpu->TagWord |= tag << (2 * i);
1034     }
1035 }
1036
1037
1038 /***********************************************************************
1039  *           save_context
1040  *
1041  * Build a context structure from the signal info.
1042  */
1043 static inline void save_context( CONTEXT *context, const SIGCONTEXT *sigcontext, WORD fs, WORD gs )
1044 {
1045     struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1046     FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
1047     XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1048
1049     memset(context, 0, sizeof(*context));
1050     context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
1051     context->Eax          = EAX_sig(sigcontext);
1052     context->Ebx          = EBX_sig(sigcontext);
1053     context->Ecx          = ECX_sig(sigcontext);
1054     context->Edx          = EDX_sig(sigcontext);
1055     context->Esi          = ESI_sig(sigcontext);
1056     context->Edi          = EDI_sig(sigcontext);
1057     context->Ebp          = EBP_sig(sigcontext);
1058     context->EFlags       = EFL_sig(sigcontext);
1059     context->Eip          = EIP_sig(sigcontext);
1060     context->Esp          = ESP_sig(sigcontext);
1061     context->SegCs        = LOWORD(CS_sig(sigcontext));
1062     context->SegDs        = LOWORD(DS_sig(sigcontext));
1063     context->SegEs        = LOWORD(ES_sig(sigcontext));
1064     context->SegFs        = fs;
1065     context->SegGs        = gs;
1066     context->SegSs        = LOWORD(SS_sig(sigcontext));
1067     context->Dr0          = regs->dr0;
1068     context->Dr1          = regs->dr1;
1069     context->Dr2          = regs->dr2;
1070     context->Dr3          = regs->dr3;
1071     context->Dr6          = regs->dr6;
1072     context->Dr7          = regs->dr7;
1073
1074     if (fpu)
1075     {
1076         context->ContextFlags |= CONTEXT_FLOATING_POINT;
1077         context->FloatSave = *fpu;
1078     }
1079     if (fpux)
1080     {
1081         context->ContextFlags |= CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
1082         memcpy( context->ExtendedRegisters, fpux, sizeof(*fpux) );
1083         fpux_support = 1;
1084         if (!fpu) fpux_to_fpu( &context->FloatSave, fpux );
1085     }
1086     if (!fpu && !fpux) save_fpu( context );
1087 }
1088
1089
1090 /***********************************************************************
1091  *           restore_context
1092  *
1093  * Restore the signal info from the context.
1094  */
1095 static inline void restore_context( const CONTEXT *context, SIGCONTEXT *sigcontext )
1096 {
1097     struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1098     FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
1099     XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1100
1101     regs->dr0 = context->Dr0;
1102     regs->dr1 = context->Dr1;
1103     regs->dr2 = context->Dr2;
1104     regs->dr3 = context->Dr3;
1105     regs->dr6 = context->Dr6;
1106     regs->dr7 = context->Dr7;
1107     EAX_sig(sigcontext) = context->Eax;
1108     EBX_sig(sigcontext) = context->Ebx;
1109     ECX_sig(sigcontext) = context->Ecx;
1110     EDX_sig(sigcontext) = context->Edx;
1111     ESI_sig(sigcontext) = context->Esi;
1112     EDI_sig(sigcontext) = context->Edi;
1113     EBP_sig(sigcontext) = context->Ebp;
1114     EFL_sig(sigcontext) = context->EFlags;
1115     EIP_sig(sigcontext) = context->Eip;
1116     ESP_sig(sigcontext) = context->Esp;
1117     CS_sig(sigcontext)  = context->SegCs;
1118     DS_sig(sigcontext)  = context->SegDs;
1119     ES_sig(sigcontext)  = context->SegEs;
1120     SS_sig(sigcontext)  = context->SegSs;
1121 #ifdef GS_sig
1122     GS_sig(sigcontext)  = context->SegGs;
1123 #else
1124     wine_set_gs( context->SegGs );
1125 #endif
1126 #ifdef FS_sig
1127     FS_sig(sigcontext)  = context->SegFs;
1128 #else
1129     wine_set_fs( context->SegFs );
1130 #endif
1131
1132     if (fpu) *fpu = context->FloatSave;
1133     if (fpux) memcpy( fpux, context->ExtendedRegisters, sizeof(*fpux) );
1134     if (!fpu && !fpux) restore_fpu( context );
1135 }
1136
1137
1138 /***********************************************************************
1139  *              RtlCaptureContext (NTDLL.@)
1140  */
1141 void WINAPI __regs_RtlCaptureContext( CONTEXT *context, CONTEXT *regs )
1142 {
1143     *context = *regs;
1144     if (fpux_support) save_fpux( context );
1145     else save_fpu( context );
1146 }
1147 DEFINE_REGS_ENTRYPOINT( RtlCaptureContext, 1 )
1148
1149
1150 /***********************************************************************
1151  *           set_cpu_context
1152  *
1153  * Set the new CPU context. Used by NtSetContextThread.
1154  */
1155 void set_cpu_context( const CONTEXT *context )
1156 {
1157     DWORD flags = context->ContextFlags & ~CONTEXT_i386;
1158
1159     if ((flags & CONTEXT_EXTENDED_REGISTERS) && fpux_support) restore_fpux( context );
1160     else if (flags & CONTEXT_FLOATING_POINT) restore_fpu( context );
1161
1162     if (flags & CONTEXT_DEBUG_REGISTERS)
1163     {
1164         ntdll_get_thread_data()->dr0 = context->Dr0;
1165         ntdll_get_thread_data()->dr1 = context->Dr1;
1166         ntdll_get_thread_data()->dr2 = context->Dr2;
1167         ntdll_get_thread_data()->dr3 = context->Dr3;
1168         ntdll_get_thread_data()->dr6 = context->Dr6;
1169         ntdll_get_thread_data()->dr7 = context->Dr7;
1170     }
1171     if (flags & CONTEXT_FULL)
1172     {
1173         if (!(flags & CONTEXT_CONTROL))
1174             FIXME( "setting partial context (%x) not supported\n", flags );
1175         else if (flags & CONTEXT_SEGMENTS)
1176             __wine_restore_regs( context );
1177         else
1178         {
1179             CONTEXT newcontext = *context;
1180             newcontext.SegDs = wine_get_ds();
1181             newcontext.SegEs = wine_get_es();
1182             newcontext.SegFs = wine_get_fs();
1183             newcontext.SegGs = wine_get_gs();
1184             __wine_restore_regs( &newcontext );
1185         }
1186     }
1187 }
1188
1189
1190 /***********************************************************************
1191  *           set_debug_registers
1192  */
1193 static void set_debug_registers( const CONTEXT *context )
1194 {
1195     DWORD flags = context->ContextFlags & ~CONTEXT_i386;
1196     context_t server_context;
1197
1198     if (!(flags & CONTEXT_DEBUG_REGISTERS)) return;
1199     if (ntdll_get_thread_data()->dr0 == context->Dr0 &&
1200         ntdll_get_thread_data()->dr1 == context->Dr1 &&
1201         ntdll_get_thread_data()->dr2 == context->Dr2 &&
1202         ntdll_get_thread_data()->dr3 == context->Dr3 &&
1203         ntdll_get_thread_data()->dr6 == context->Dr6 &&
1204         ntdll_get_thread_data()->dr7 == context->Dr7) return;
1205
1206     context_to_server( &server_context, context );
1207
1208     SERVER_START_REQ( set_thread_context )
1209     {
1210         req->handle  = wine_server_obj_handle( GetCurrentThread() );
1211         req->suspend = 0;
1212         wine_server_add_data( req, &server_context, sizeof(server_context) );
1213         wine_server_call( req );
1214     }
1215     SERVER_END_REQ;
1216 }
1217
1218
1219 /***********************************************************************
1220  *           copy_context
1221  *
1222  * Copy a register context according to the flags.
1223  */
1224 void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
1225 {
1226     flags &= ~CONTEXT_i386;  /* get rid of CPU id */
1227     if (flags & CONTEXT_INTEGER)
1228     {
1229         to->Eax = from->Eax;
1230         to->Ebx = from->Ebx;
1231         to->Ecx = from->Ecx;
1232         to->Edx = from->Edx;
1233         to->Esi = from->Esi;
1234         to->Edi = from->Edi;
1235     }
1236     if (flags & CONTEXT_CONTROL)
1237     {
1238         to->Ebp    = from->Ebp;
1239         to->Esp    = from->Esp;
1240         to->Eip    = from->Eip;
1241         to->SegCs  = from->SegCs;
1242         to->SegSs  = from->SegSs;
1243         to->EFlags = from->EFlags;
1244     }
1245     if (flags & CONTEXT_SEGMENTS)
1246     {
1247         to->SegDs = from->SegDs;
1248         to->SegEs = from->SegEs;
1249         to->SegFs = from->SegFs;
1250         to->SegGs = from->SegGs;
1251     }
1252     if (flags & CONTEXT_DEBUG_REGISTERS)
1253     {
1254         to->Dr0 = from->Dr0;
1255         to->Dr1 = from->Dr1;
1256         to->Dr2 = from->Dr2;
1257         to->Dr3 = from->Dr3;
1258         to->Dr6 = from->Dr6;
1259         to->Dr7 = from->Dr7;
1260     }
1261     if (flags & CONTEXT_FLOATING_POINT)
1262     {
1263         to->FloatSave = from->FloatSave;
1264     }
1265     if (flags & CONTEXT_EXTENDED_REGISTERS)
1266     {
1267         memcpy( to->ExtendedRegisters, from->ExtendedRegisters, sizeof(to->ExtendedRegisters) );
1268     }
1269 }
1270
1271
1272 /***********************************************************************
1273  *           context_to_server
1274  *
1275  * Convert a register context to the server format.
1276  */
1277 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1278 {
1279     DWORD flags = from->ContextFlags & ~CONTEXT_i386;  /* get rid of CPU id */
1280
1281     memset( to, 0, sizeof(*to) );
1282     to->cpu = CPU_x86;
1283
1284     if (flags & CONTEXT_CONTROL)
1285     {
1286         to->flags |= SERVER_CTX_CONTROL;
1287         to->ctl.i386_regs.ebp    = from->Ebp;
1288         to->ctl.i386_regs.esp    = from->Esp;
1289         to->ctl.i386_regs.eip    = from->Eip;
1290         to->ctl.i386_regs.cs     = from->SegCs;
1291         to->ctl.i386_regs.ss     = from->SegSs;
1292         to->ctl.i386_regs.eflags = from->EFlags;
1293     }
1294     if (flags & CONTEXT_INTEGER)
1295     {
1296         to->flags |= SERVER_CTX_INTEGER;
1297         to->integer.i386_regs.eax = from->Eax;
1298         to->integer.i386_regs.ebx = from->Ebx;
1299         to->integer.i386_regs.ecx = from->Ecx;
1300         to->integer.i386_regs.edx = from->Edx;
1301         to->integer.i386_regs.esi = from->Esi;
1302         to->integer.i386_regs.edi = from->Edi;
1303     }
1304     if (flags & CONTEXT_SEGMENTS)
1305     {
1306         to->flags |= SERVER_CTX_SEGMENTS;
1307         to->seg.i386_regs.ds = from->SegDs;
1308         to->seg.i386_regs.es = from->SegEs;
1309         to->seg.i386_regs.fs = from->SegFs;
1310         to->seg.i386_regs.gs = from->SegGs;
1311     }
1312     if (flags & CONTEXT_FLOATING_POINT)
1313     {
1314         to->flags |= SERVER_CTX_FLOATING_POINT;
1315         to->fp.i386_regs.ctrl     = from->FloatSave.ControlWord;
1316         to->fp.i386_regs.status   = from->FloatSave.StatusWord;
1317         to->fp.i386_regs.tag      = from->FloatSave.TagWord;
1318         to->fp.i386_regs.err_off  = from->FloatSave.ErrorOffset;
1319         to->fp.i386_regs.err_sel  = from->FloatSave.ErrorSelector;
1320         to->fp.i386_regs.data_off = from->FloatSave.DataOffset;
1321         to->fp.i386_regs.data_sel = from->FloatSave.DataSelector;
1322         to->fp.i386_regs.cr0npx   = from->FloatSave.Cr0NpxState;
1323         memcpy( to->fp.i386_regs.regs, from->FloatSave.RegisterArea, sizeof(to->fp.i386_regs.regs) );
1324     }
1325     if (flags & CONTEXT_DEBUG_REGISTERS)
1326     {
1327         to->flags |= SERVER_CTX_DEBUG_REGISTERS;
1328         to->debug.i386_regs.dr0 = from->Dr0;
1329         to->debug.i386_regs.dr1 = from->Dr1;
1330         to->debug.i386_regs.dr2 = from->Dr2;
1331         to->debug.i386_regs.dr3 = from->Dr3;
1332         to->debug.i386_regs.dr6 = from->Dr6;
1333         to->debug.i386_regs.dr7 = from->Dr7;
1334     }
1335     if (flags & CONTEXT_EXTENDED_REGISTERS)
1336     {
1337         to->flags |= SERVER_CTX_EXTENDED_REGISTERS;
1338         memcpy( to->ext.i386_regs, from->ExtendedRegisters, sizeof(to->ext.i386_regs) );
1339     }
1340     return STATUS_SUCCESS;
1341 }
1342
1343
1344 /***********************************************************************
1345  *           context_from_server
1346  *
1347  * Convert a register context from the server format.
1348  */
1349 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
1350 {
1351     if (from->cpu != CPU_x86) return STATUS_INVALID_PARAMETER;
1352
1353     to->ContextFlags = CONTEXT_i386;
1354     if (from->flags & SERVER_CTX_CONTROL)
1355     {
1356         to->ContextFlags |= CONTEXT_CONTROL;
1357         to->Ebp    = from->ctl.i386_regs.ebp;
1358         to->Esp    = from->ctl.i386_regs.esp;
1359         to->Eip    = from->ctl.i386_regs.eip;
1360         to->SegCs  = from->ctl.i386_regs.cs;
1361         to->SegSs  = from->ctl.i386_regs.ss;
1362         to->EFlags = from->ctl.i386_regs.eflags;
1363     }
1364     if (from->flags & SERVER_CTX_INTEGER)
1365     {
1366         to->ContextFlags |= CONTEXT_INTEGER;
1367         to->Eax = from->integer.i386_regs.eax;
1368         to->Ebx = from->integer.i386_regs.ebx;
1369         to->Ecx = from->integer.i386_regs.ecx;
1370         to->Edx = from->integer.i386_regs.edx;
1371         to->Esi = from->integer.i386_regs.esi;
1372         to->Edi = from->integer.i386_regs.edi;
1373     }
1374     if (from->flags & SERVER_CTX_SEGMENTS)
1375     {
1376         to->ContextFlags |= CONTEXT_SEGMENTS;
1377         to->SegDs = from->seg.i386_regs.ds;
1378         to->SegEs = from->seg.i386_regs.es;
1379         to->SegFs = from->seg.i386_regs.fs;
1380         to->SegGs = from->seg.i386_regs.gs;
1381     }
1382     if (from->flags & SERVER_CTX_FLOATING_POINT)
1383     {
1384         to->ContextFlags |= CONTEXT_FLOATING_POINT;
1385         to->FloatSave.ControlWord   = from->fp.i386_regs.ctrl;
1386         to->FloatSave.StatusWord    = from->fp.i386_regs.status;
1387         to->FloatSave.TagWord       = from->fp.i386_regs.tag;
1388         to->FloatSave.ErrorOffset   = from->fp.i386_regs.err_off;
1389         to->FloatSave.ErrorSelector = from->fp.i386_regs.err_sel;
1390         to->FloatSave.DataOffset    = from->fp.i386_regs.data_off;
1391         to->FloatSave.DataSelector  = from->fp.i386_regs.data_sel;
1392         to->FloatSave.Cr0NpxState   = from->fp.i386_regs.cr0npx;
1393         memcpy( to->FloatSave.RegisterArea, from->fp.i386_regs.regs, sizeof(to->FloatSave.RegisterArea) );
1394     }
1395     if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
1396     {
1397         to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1398         to->Dr0 = from->debug.i386_regs.dr0;
1399         to->Dr1 = from->debug.i386_regs.dr1;
1400         to->Dr2 = from->debug.i386_regs.dr2;
1401         to->Dr3 = from->debug.i386_regs.dr3;
1402         to->Dr6 = from->debug.i386_regs.dr6;
1403         to->Dr7 = from->debug.i386_regs.dr7;
1404     }
1405     if (from->flags & SERVER_CTX_EXTENDED_REGISTERS)
1406     {
1407         to->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
1408         memcpy( to->ExtendedRegisters, from->ext.i386_regs, sizeof(to->ExtendedRegisters) );
1409     }
1410     return STATUS_SUCCESS;
1411 }
1412
1413
1414 /***********************************************************************
1415  *           is_privileged_instr
1416  *
1417  * Check if the fault location is a privileged instruction.
1418  * Based on the instruction emulation code in dlls/kernel/instr.c.
1419  */
1420 static inline DWORD is_privileged_instr( CONTEXT86 *context )
1421 {
1422     const BYTE *instr;
1423     unsigned int prefix_count = 0;
1424
1425     if (!wine_ldt_is_system( context->SegCs )) return 0;
1426     instr = (BYTE *)context->Eip;
1427
1428     for (;;) switch(*instr)
1429     {
1430     /* instruction prefixes */
1431     case 0x2e:  /* %cs: */
1432     case 0x36:  /* %ss: */
1433     case 0x3e:  /* %ds: */
1434     case 0x26:  /* %es: */
1435     case 0x64:  /* %fs: */
1436     case 0x65:  /* %gs: */
1437     case 0x66:  /* opcode size */
1438     case 0x67:  /* addr size */
1439     case 0xf0:  /* lock */
1440     case 0xf2:  /* repne */
1441     case 0xf3:  /* repe */
1442         if (++prefix_count >= 15) return EXCEPTION_ILLEGAL_INSTRUCTION;
1443         instr++;
1444         continue;
1445
1446     case 0x0f: /* extended instruction */
1447         switch(instr[1])
1448         {
1449         case 0x20: /* mov crX, reg */
1450         case 0x21: /* mov drX, reg */
1451         case 0x22: /* mov reg, crX */
1452         case 0x23: /* mov reg drX */
1453             return EXCEPTION_PRIV_INSTRUCTION;
1454         }
1455         return 0;
1456     case 0x6c: /* insb (%dx) */
1457     case 0x6d: /* insl (%dx) */
1458     case 0x6e: /* outsb (%dx) */
1459     case 0x6f: /* outsl (%dx) */
1460     case 0xcd: /* int $xx */
1461     case 0xe4: /* inb al,XX */
1462     case 0xe5: /* in (e)ax,XX */
1463     case 0xe6: /* outb XX,al */
1464     case 0xe7: /* out XX,(e)ax */
1465     case 0xec: /* inb (%dx),%al */
1466     case 0xed: /* inl (%dx),%eax */
1467     case 0xee: /* outb %al,(%dx) */
1468     case 0xef: /* outl %eax,(%dx) */
1469     case 0xf4: /* hlt */
1470     case 0xfa: /* cli */
1471     case 0xfb: /* sti */
1472         return EXCEPTION_PRIV_INSTRUCTION;
1473     default:
1474         return 0;
1475     }
1476 }
1477
1478
1479 #include "pshpack1.h"
1480 struct atl_thunk
1481 {
1482     DWORD movl;  /* movl this,4(%esp) */
1483     DWORD this;
1484     BYTE  jmp;   /* jmp func */
1485     int   func;
1486 };
1487 #include "poppack.h"
1488
1489 /**********************************************************************
1490  *              check_atl_thunk
1491  *
1492  * Check if code destination is an ATL thunk, and emulate it if so.
1493  */
1494 static BOOL check_atl_thunk( EXCEPTION_RECORD *rec, CONTEXT *context )
1495 {
1496     const struct atl_thunk *thunk = (const struct atl_thunk *)rec->ExceptionInformation[1];
1497     BOOL ret = FALSE;
1498
1499     __TRY
1500     {
1501         if (thunk->movl == 0x042444c7 && thunk->jmp == 0xe9)
1502         {
1503             *((DWORD *)context->Esp + 1) = thunk->this;
1504             context->Eip = (DWORD_PTR)(&thunk->func + 1) + thunk->func;
1505             TRACE( "emulating ATL thunk at %p, func=%08x arg=%08x\n",
1506                    thunk, context->Eip, *((DWORD *)context->Esp + 1) );
1507             ret = TRUE;
1508         }
1509     }
1510     __EXCEPT_PAGE_FAULT
1511     {
1512         return FALSE;
1513     }
1514     __ENDTRY
1515     return ret;
1516 }
1517
1518
1519 /***********************************************************************
1520  *           setup_exception_record
1521  *
1522  * Setup the exception record and context on the thread stack.
1523  */
1524 static EXCEPTION_RECORD *setup_exception_record( SIGCONTEXT *sigcontext, void *stack_ptr,
1525                                                  WORD fs, WORD gs, raise_func func )
1526 {
1527     struct stack_layout
1528     {
1529         void             *ret_addr;      /* return address from raise_func */
1530         EXCEPTION_RECORD *rec_ptr;       /* first arg for raise_func */
1531         CONTEXT          *context_ptr;   /* second arg for raise_func */
1532         CONTEXT           context;
1533         EXCEPTION_RECORD  rec;
1534         DWORD             ebp;
1535         DWORD             eip;
1536     } *stack = stack_ptr;
1537     DWORD exception_code = 0;
1538
1539     /* stack sanity checks */
1540
1541     if ((char *)stack >= (char *)get_signal_stack() &&
1542         (char *)stack < (char *)get_signal_stack() + signal_stack_size)
1543     {
1544         WINE_ERR( "nested exception on signal stack in thread %04x eip %08x esp %08x stack %p-%p\n",
1545                   GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1546                   (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
1547                   NtCurrentTeb()->Tib.StackBase );
1548         abort_thread(1);
1549     }
1550
1551     if (stack - 1 > stack || /* check for overflow in subtraction */
1552         (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
1553         (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
1554     {
1555         WARN( "exception outside of stack limits in thread %04x eip %08x esp %08x stack %p-%p\n",
1556               GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1557               (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
1558               NtCurrentTeb()->Tib.StackBase );
1559     }
1560     else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
1561     {
1562         /* stack overflow on last page, unrecoverable */
1563         UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
1564         WINE_ERR( "stack overflow %u bytes in thread %04x eip %08x esp %08x stack %p-%p-%p\n",
1565                   diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1566                   (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1567                   NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1568         abort_thread(1);
1569     }
1570     else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
1571     {
1572         /* stack access below stack limit, may be recoverable */
1573         if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
1574         else
1575         {
1576             UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
1577             WINE_ERR( "stack overflow %u bytes in thread %04x eip %08x esp %08x stack %p-%p-%p\n",
1578                       diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1579                       (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1580                       NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1581             abort_thread(1);
1582         }
1583     }
1584
1585     stack--;  /* push the stack_layout structure */
1586 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
1587     VALGRIND_MAKE_MEM_UNDEFINED(stack, sizeof(*stack));
1588 #elif defined(VALGRIND_MAKE_WRITABLE)
1589     VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
1590 #endif
1591     stack->ret_addr     = (void *)0xdeadbabe;  /* raise_func must not return */
1592     stack->rec_ptr      = &stack->rec;
1593     stack->context_ptr  = &stack->context;
1594
1595     stack->rec.ExceptionRecord  = NULL;
1596     stack->rec.ExceptionCode    = exception_code;
1597     stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
1598     stack->rec.ExceptionAddress = (LPVOID)EIP_sig(sigcontext);
1599     stack->rec.NumberParameters = 0;
1600
1601     save_context( &stack->context, sigcontext, fs, gs );
1602
1603     /* now modify the sigcontext to return to the raise function */
1604     ESP_sig(sigcontext) = (DWORD)stack;
1605     EIP_sig(sigcontext) = (DWORD)func;
1606     /* clear single-step, direction, and align check flag */
1607     EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
1608     CS_sig(sigcontext)  = wine_get_cs();
1609     DS_sig(sigcontext)  = wine_get_ds();
1610     ES_sig(sigcontext)  = wine_get_es();
1611     FS_sig(sigcontext)  = wine_get_fs();
1612     GS_sig(sigcontext)  = wine_get_gs();
1613     SS_sig(sigcontext)  = wine_get_ss();
1614
1615     return stack->rec_ptr;
1616 }
1617
1618
1619 /***********************************************************************
1620  *           setup_exception
1621  *
1622  * Setup a proper stack frame for the raise function, and modify the
1623  * sigcontext so that the return from the signal handler will call
1624  * the raise function.
1625  */
1626 static EXCEPTION_RECORD *setup_exception( SIGCONTEXT *sigcontext, raise_func func )
1627 {
1628     WORD fs, gs;
1629     void *stack = init_handler( sigcontext, &fs, &gs );
1630
1631     return setup_exception_record( sigcontext, stack, fs, gs, func );
1632 }
1633
1634
1635 /***********************************************************************
1636  *           get_exception_context
1637  *
1638  * Get a pointer to the context built by setup_exception.
1639  */
1640 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
1641 {
1642     return (CONTEXT *)rec - 1;  /* cf. stack_layout structure */
1643 }
1644
1645
1646 /**********************************************************************
1647  *              get_fpu_code
1648  *
1649  * Get the FPU exception code from the FPU status.
1650  */
1651 static inline DWORD get_fpu_code( const CONTEXT *context )
1652 {
1653     DWORD status = context->FloatSave.StatusWord & ~(context->FloatSave.ControlWord & 0x3f);
1654
1655     if (status & 0x01)  /* IE */
1656     {
1657         if (status & 0x40)  /* SF */
1658             return EXCEPTION_FLT_STACK_CHECK;
1659         else
1660             return EXCEPTION_FLT_INVALID_OPERATION;
1661     }
1662     if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND;  /* DE flag */
1663     if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO;    /* ZE flag */
1664     if (status & 0x08) return EXCEPTION_FLT_OVERFLOW;          /* OE flag */
1665     if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW;         /* UE flag */
1666     if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT;    /* PE flag */
1667     return EXCEPTION_FLT_INVALID_OPERATION;  /* generic error */
1668 }
1669
1670
1671 /**********************************************************************
1672  *              raise_segv_exception
1673  */
1674 static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1675 {
1676     NTSTATUS status;
1677
1678     switch(rec->ExceptionCode)
1679     {
1680     case EXCEPTION_ACCESS_VIOLATION:
1681         if (rec->NumberParameters == 2)
1682         {
1683             if (rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT && check_atl_thunk( rec, context ))
1684                 goto done;
1685             if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
1686                                                              rec->ExceptionInformation[0] )))
1687                 goto done;
1688             /* send EXCEPTION_EXECUTE_FAULT only if data execution prevention is enabled */
1689             if (rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT)
1690             {
1691                 ULONG flags;
1692                 NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
1693                                            &flags, sizeof(flags), NULL );
1694                 if (!(flags & MEM_EXECUTE_OPTION_DISABLE))
1695                     rec->ExceptionInformation[0] = EXCEPTION_READ_FAULT;
1696             }
1697         }
1698         break;
1699     case EXCEPTION_DATATYPE_MISALIGNMENT:
1700         /* FIXME: pass through exception handler first? */
1701         if (context->EFlags & 0x00040000)
1702         {
1703             /* Disable AC flag, return */
1704             context->EFlags &= ~0x00040000;
1705             goto done;
1706         }
1707         break;
1708     }
1709     status = NtRaiseException( rec, context, TRUE );
1710     raise_status( status, rec );
1711 done:
1712     set_cpu_context( context );
1713 }
1714
1715
1716 /**********************************************************************
1717  *              raise_trap_exception
1718  */
1719 static void WINAPI raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1720 {
1721     NTSTATUS status;
1722
1723     if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
1724     {
1725         /* when single stepping can't tell whether this is a hw bp or a
1726          * single step interrupt. try to avoid as much overhead as possible
1727          * and only do a server call if there is any hw bp enabled. */
1728
1729         if( !(context->EFlags & 0x100) || (ntdll_get_thread_data()->dr7 & 0xff) )
1730         {
1731             /* (possible) hardware breakpoint, fetch the debug registers */
1732             context->ContextFlags = CONTEXT_DEBUG_REGISTERS;
1733             NtGetContextThread(GetCurrentThread(), context);
1734             context->ContextFlags |= CONTEXT_FULL;  /* restore flags */
1735         }
1736
1737         context->EFlags &= ~0x100;  /* clear single-step flag */
1738     }
1739
1740     status = NtRaiseException( rec, context, TRUE );
1741     raise_status( status, rec );
1742 }
1743
1744
1745 /**********************************************************************
1746  *              raise_generic_exception
1747  *
1748  * Generic raise function for exceptions that don't need special treatment.
1749  */
1750 static void WINAPI raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1751 {
1752     NTSTATUS status;
1753
1754     status = NtRaiseException( rec, context, TRUE );
1755     raise_status( status, rec );
1756 }
1757
1758
1759 #ifdef __HAVE_VM86
1760 /**********************************************************************
1761  *              raise_vm86_sti_exception
1762  */
1763 static void WINAPI raise_vm86_sti_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1764 {
1765     /* merge_vm86_pending_flags merges the vm86_pending flag in safely */
1766     get_vm86_teb_info()->vm86_pending |= VIP_FLAG;
1767
1768     if (ntdll_get_thread_data()->vm86_ptr)
1769     {
1770         if (((char*)context->Eip >= (char*)vm86_return) &&
1771             ((char*)context->Eip <= (char*)vm86_return_end) &&
1772             (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
1773             /* exiting from VM86, can't throw */
1774             goto done;
1775         }
1776         merge_vm86_pending_flags( rec );
1777     }
1778     else if (get_vm86_teb_info()->dpmi_vif &&
1779              !wine_ldt_is_system(context->SegCs) &&
1780              !wine_ldt_is_system(context->SegSs))
1781     {
1782         /* Executing DPMI code and virtual interrupts are enabled. */
1783         get_vm86_teb_info()->vm86_pending = 0;
1784         NtRaiseException( rec, context, TRUE );
1785     }
1786 done:
1787     set_cpu_context( context );
1788 }
1789
1790
1791 /**********************************************************************
1792  *              usr2_handler
1793  *
1794  * Handler for SIGUSR2.
1795  * We use it to signal that the running __wine_enter_vm86() should
1796  * immediately set VIP_FLAG, causing pending events to be handled
1797  * as early as possible.
1798  */
1799 static void usr2_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1800 {
1801     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_vm86_sti_exception );
1802     rec->ExceptionCode = EXCEPTION_VM86_STI;
1803 }
1804 #endif /* __HAVE_VM86 */
1805
1806
1807 /**********************************************************************
1808  *              segv_handler
1809  *
1810  * Handler for SIGSEGV and related errors.
1811  */
1812 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1813 {
1814     WORD fs, gs;
1815     EXCEPTION_RECORD *rec;
1816     SIGCONTEXT *context = sigcontext;
1817     void *stack = init_handler( sigcontext, &fs, &gs );
1818
1819     /* check for page fault inside the thread stack */
1820     if (get_trap_code(context) == TRAP_x86_PAGEFLT &&
1821         (char *)siginfo->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
1822         (char *)siginfo->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
1823         virtual_handle_stack_fault( siginfo->si_addr ))
1824     {
1825         /* check if this was the last guard page */
1826         if ((char *)siginfo->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
1827         {
1828             rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
1829             rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
1830         }
1831         return;
1832     }
1833
1834     rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
1835     if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
1836
1837     switch(get_trap_code(context))
1838     {
1839     case TRAP_x86_OFLOW:   /* Overflow exception */
1840         rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
1841         break;
1842     case TRAP_x86_BOUND:   /* Bound range exception */
1843         rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
1844         break;
1845     case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
1846         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1847         break;
1848     case TRAP_x86_STKFLT:  /* Stack fault */
1849         rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
1850         break;
1851     case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
1852     case TRAP_x86_PROTFLT:   /* General protection fault */
1853     case TRAP_x86_UNKNOWN:   /* Unknown fault code */
1854         {
1855             WORD err = get_error_code(context);
1856             if (!err && (rec->ExceptionCode = is_privileged_instr( get_exception_context(rec) ))) break;
1857             rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1858             rec->NumberParameters = 2;
1859             rec->ExceptionInformation[0] = 0;
1860             /* if error contains a LDT selector, use that as fault address */
1861             if ((err & 7) == 4 && !wine_ldt_is_system( err | 7 ))
1862                 rec->ExceptionInformation[1] = err & ~7;
1863             else
1864                 rec->ExceptionInformation[1] = 0xffffffff;
1865         }
1866         break;
1867     case TRAP_x86_PAGEFLT:  /* Page fault */
1868         rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1869         rec->NumberParameters = 2;
1870         rec->ExceptionInformation[0] = (get_error_code(context) >> 1) & 0x09;
1871         rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
1872         break;
1873     case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
1874         rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
1875         break;
1876     default:
1877         WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
1878         /* fall through */
1879     case TRAP_x86_NMI:       /* NMI interrupt */
1880     case TRAP_x86_DNA:       /* Device not available exception */
1881     case TRAP_x86_DOUBLEFLT: /* Double fault exception */
1882     case TRAP_x86_TSSFLT:    /* Invalid TSS exception */
1883     case TRAP_x86_MCHK:      /* Machine check exception */
1884     case TRAP_x86_CACHEFLT:  /* Cache flush exception */
1885         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1886         break;
1887     }
1888 }
1889
1890
1891 /**********************************************************************
1892  *              trap_handler
1893  *
1894  * Handler for SIGTRAP.
1895  */
1896 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1897 {
1898     SIGCONTEXT *context = sigcontext;
1899     EXCEPTION_RECORD *rec = setup_exception( context, raise_trap_exception );
1900
1901     switch(get_trap_code(context))
1902     {
1903     case TRAP_x86_TRCTRAP:  /* Single-step exception */
1904         rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
1905         break;
1906     case TRAP_x86_BPTFLT:   /* Breakpoint exception */
1907         rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
1908         /* fall through */
1909     default:
1910         rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1911         break;
1912     }
1913 }
1914
1915
1916 /**********************************************************************
1917  *              fpe_handler
1918  *
1919  * Handler for SIGFPE.
1920  */
1921 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1922 {
1923     CONTEXT *win_context;
1924     SIGCONTEXT *context = sigcontext;
1925     EXCEPTION_RECORD *rec = setup_exception( context, raise_generic_exception );
1926
1927     win_context = get_exception_context( rec );
1928
1929     switch(get_trap_code(context))
1930     {
1931     case TRAP_x86_DIVIDE:   /* Division by zero exception */
1932         rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
1933         break;
1934     case TRAP_x86_FPOPFLT:   /* Coprocessor segment overrun */
1935         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1936         break;
1937     case TRAP_x86_ARITHTRAP:  /* Floating point exception */
1938     case TRAP_x86_UNKNOWN:    /* Unknown fault code */
1939         rec->ExceptionCode = get_fpu_code( win_context );
1940         rec->ExceptionAddress = (LPVOID)win_context->FloatSave.ErrorOffset;
1941         break;
1942     case TRAP_x86_CACHEFLT:  /* SIMD exception */
1943         /* TODO:
1944          * Behaviour only tested for divide-by-zero exceptions
1945          * Check for other SIMD exceptions as well */
1946         if(siginfo->si_code != FPE_FLTDIV)
1947             FIXME("untested SIMD exception: %#x. Might not work correctly\n",
1948                   siginfo->si_code);
1949
1950         rec->ExceptionCode = STATUS_FLOAT_MULTIPLE_TRAPS;
1951         rec->NumberParameters = 1;
1952         /* no idea what meaning is actually behind this but that's what native does */
1953         rec->ExceptionInformation[0] = 0;
1954         break;
1955     default:
1956         WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
1957         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1958         break;
1959     }
1960 }
1961
1962
1963 /**********************************************************************
1964  *              int_handler
1965  *
1966  * Handler for SIGINT.
1967  *
1968  * FIXME: should not be calling external functions on the signal stack.
1969  */
1970 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1971 {
1972     WORD fs, gs;
1973     init_handler( sigcontext, &fs, &gs );
1974     if (!dispatch_signal(SIGINT))
1975     {
1976         EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
1977         rec->ExceptionCode = CONTROL_C_EXIT;
1978     }
1979 }
1980
1981 /**********************************************************************
1982  *              abrt_handler
1983  *
1984  * Handler for SIGABRT.
1985  */
1986 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1987 {
1988     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
1989     rec->ExceptionCode  = EXCEPTION_WINE_ASSERTION;
1990     rec->ExceptionFlags = EH_NONCONTINUABLE;
1991 }
1992
1993
1994 /**********************************************************************
1995  *              quit_handler
1996  *
1997  * Handler for SIGQUIT.
1998  */
1999 static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2000 {
2001     WORD fs, gs;
2002     init_handler( sigcontext, &fs, &gs );
2003     abort_thread(0);
2004 }
2005
2006
2007 /**********************************************************************
2008  *              usr1_handler
2009  *
2010  * Handler for SIGUSR1, used to signal a thread that it got suspended.
2011  */
2012 static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2013 {
2014     CONTEXT context;
2015     WORD fs, gs;
2016
2017     init_handler( sigcontext, &fs, &gs );
2018     save_context( &context, sigcontext, fs, gs );
2019     wait_suspend( &context );
2020     restore_context( &context, sigcontext );
2021 }
2022
2023
2024 /***********************************************************************
2025  *           __wine_set_signal_handler   (NTDLL.@)
2026  */
2027 int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
2028 {
2029     if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
2030     if (handlers[sig] != NULL) return -2;
2031     handlers[sig] = wsh;
2032     return 0;
2033 }
2034
2035
2036 /***********************************************************************
2037  *           locking for LDT routines
2038  */
2039 static RTL_CRITICAL_SECTION ldt_section;
2040 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
2041 {
2042     0, 0, &ldt_section,
2043     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
2044       0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
2045 };
2046 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
2047 static sigset_t ldt_sigset;
2048
2049 static void ldt_lock(void)
2050 {
2051     sigset_t sigset;
2052
2053     pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
2054     RtlEnterCriticalSection( &ldt_section );
2055     if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
2056 }
2057
2058 static void ldt_unlock(void)
2059 {
2060     if (ldt_section.RecursionCount == 1)
2061     {
2062         sigset_t sigset = ldt_sigset;
2063         RtlLeaveCriticalSection( &ldt_section );
2064         pthread_sigmask( SIG_SETMASK, &sigset, NULL );
2065     }
2066     else RtlLeaveCriticalSection( &ldt_section );
2067 }
2068
2069
2070 /**********************************************************************
2071  *              signal_alloc_thread
2072  */
2073 NTSTATUS signal_alloc_thread( TEB **teb )
2074 {
2075     static size_t sigstack_zero_bits;
2076     struct ntdll_thread_data *thread_data;
2077     struct ntdll_thread_data *parent_data = NULL;
2078     SIZE_T size;
2079     void *addr = NULL;
2080     NTSTATUS status;
2081
2082     if (!sigstack_zero_bits)
2083     {
2084         size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2085         /* find the first power of two not smaller than min_size */
2086         sigstack_zero_bits = 12;
2087         while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
2088         signal_stack_mask = (1 << sigstack_zero_bits) - 1;
2089         signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
2090     }
2091     else parent_data = ntdll_get_thread_data();
2092
2093     size = signal_stack_mask + 1;
2094     if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
2095                                             &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
2096     {
2097         *teb = addr;
2098         (*teb)->Tib.Self = &(*teb)->Tib;
2099         (*teb)->Tib.ExceptionList = (void *)~0UL;
2100         thread_data = (struct ntdll_thread_data *)(*teb)->SpareBytes1;
2101         if (!(thread_data->fs = wine_ldt_alloc_fs()))
2102         {
2103             size = 0;
2104             NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
2105             status = STATUS_TOO_MANY_THREADS;
2106         }
2107         if (parent_data)
2108         {
2109             /* inherit debug registers from parent thread */
2110             thread_data->dr0 = parent_data->dr0;
2111             thread_data->dr1 = parent_data->dr1;
2112             thread_data->dr2 = parent_data->dr2;
2113             thread_data->dr3 = parent_data->dr3;
2114             thread_data->dr6 = parent_data->dr6;
2115             thread_data->dr7 = parent_data->dr7;
2116         }
2117
2118     }
2119     return status;
2120 }
2121
2122
2123 /**********************************************************************
2124  *              signal_free_thread
2125  */
2126 void signal_free_thread( TEB *teb )
2127 {
2128     SIZE_T size;
2129     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
2130
2131     if (thread_data) wine_ldt_free_fs( thread_data->fs );
2132     if (teb->DeallocationStack)
2133     {
2134         size = 0;
2135         NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
2136     }
2137     size = 0;
2138     NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2139 }
2140
2141
2142 /**********************************************************************
2143  *              signal_init_thread
2144  */
2145 void signal_init_thread( TEB *teb )
2146 {
2147     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
2148     LDT_ENTRY fs_entry;
2149     stack_t ss;
2150
2151 #ifdef __APPLE__
2152     int mib[2], val = 1;
2153
2154     mib[0] = CTL_KERN;
2155     mib[1] = KERN_THALTSTACK;
2156     sysctl( mib, 2, NULL, NULL, &val, sizeof(val) );
2157 #endif
2158
2159     ss.ss_sp    = (char *)teb + teb_size;
2160     ss.ss_size  = signal_stack_size;
2161     ss.ss_flags = 0;
2162     if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
2163
2164     wine_ldt_set_base( &fs_entry, teb );
2165     wine_ldt_set_limit( &fs_entry, teb_size - 1 );
2166     wine_ldt_set_flags( &fs_entry, WINE_LDT_FLAGS_DATA|WINE_LDT_FLAGS_32BIT );
2167     wine_ldt_init_fs( thread_data->fs, &fs_entry );
2168     thread_data->gs = wine_get_gs();
2169 }
2170
2171 /**********************************************************************
2172  *              signal_init_process
2173  */
2174 void signal_init_process(void)
2175 {
2176     struct sigaction sig_act;
2177
2178     sig_act.sa_mask = server_block_set;
2179     sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
2180 #ifdef SA_ONSTACK
2181     sig_act.sa_flags |= SA_ONSTACK;
2182 #endif
2183
2184     sig_act.sa_sigaction = int_handler;
2185     if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
2186     sig_act.sa_sigaction = fpe_handler;
2187     if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
2188     sig_act.sa_sigaction = abrt_handler;
2189     if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
2190     sig_act.sa_sigaction = quit_handler;
2191     if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
2192     sig_act.sa_sigaction = usr1_handler;
2193     if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
2194
2195     sig_act.sa_sigaction = segv_handler;
2196     if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
2197     if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2198 #ifdef SIGBUS
2199     if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2200 #endif
2201
2202 #ifdef SIGTRAP
2203     sig_act.sa_sigaction = trap_handler;
2204     if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2205 #endif
2206
2207 #ifdef __HAVE_VM86
2208     sig_act.sa_sigaction = usr2_handler;
2209     if (sigaction( SIGUSR2, &sig_act, NULL ) == -1) goto error;
2210 #endif
2211
2212     wine_ldt_init_locking( ldt_lock, ldt_unlock );
2213     return;
2214
2215  error:
2216     perror("sigaction");
2217     exit(1);
2218 }
2219
2220
2221 #ifdef __HAVE_VM86
2222 /**********************************************************************
2223  *              __wine_enter_vm86   (NTDLL.@)
2224  *
2225  * Enter vm86 mode with the specified register context.
2226  */
2227 void __wine_enter_vm86( CONTEXT *context )
2228 {
2229     EXCEPTION_RECORD rec;
2230     int res;
2231     struct vm86plus_struct vm86;
2232
2233     memset( &vm86, 0, sizeof(vm86) );
2234     for (;;)
2235     {
2236         restore_vm86_context( context, &vm86 );
2237
2238         ntdll_get_thread_data()->vm86_ptr = &vm86;
2239         merge_vm86_pending_flags( &rec );
2240
2241         res = vm86_enter( &ntdll_get_thread_data()->vm86_ptr ); /* uses and clears teb->vm86_ptr */
2242         if (res < 0)
2243         {
2244             errno = -res;
2245             return;
2246         }
2247
2248         save_vm86_context( context, &vm86 );
2249
2250         rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
2251         rec.ExceptionRecord  = NULL;
2252         rec.ExceptionAddress = (LPVOID)context->Eip;
2253         rec.NumberParameters = 0;
2254
2255         switch(VM86_TYPE(res))
2256         {
2257         case VM86_UNKNOWN: /* unhandled GP fault - IO-instruction or similar */
2258             rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
2259             break;
2260         case VM86_TRAP: /* return due to DOS-debugger request */
2261             switch(VM86_ARG(res))
2262             {
2263             case TRAP_x86_TRCTRAP:  /* Single-step exception */
2264                 rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
2265                 break;
2266             case TRAP_x86_BPTFLT:   /* Breakpoint exception */
2267                 rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1;  /* back up over the int3 instruction */
2268                 /* fall through */
2269             default:
2270                 rec.ExceptionCode = EXCEPTION_BREAKPOINT;
2271                 break;
2272             }
2273             break;
2274         case VM86_INTx: /* int3/int x instruction (ARG = x) */
2275             rec.ExceptionCode = EXCEPTION_VM86_INTx;
2276             rec.NumberParameters = 1;
2277             rec.ExceptionInformation[0] = VM86_ARG(res);
2278             break;
2279         case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
2280             context->EFlags |= VIF_FLAG;
2281             context->EFlags &= ~VIP_FLAG;
2282             get_vm86_teb_info()->vm86_pending = 0;
2283             rec.ExceptionCode = EXCEPTION_VM86_STI;
2284             break;
2285         case VM86_PICRETURN: /* return due to pending PIC request */
2286             rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
2287             break;
2288         case VM86_SIGNAL: /* cannot happen because vm86_enter handles this case */
2289         default:
2290             WINE_ERR( "unhandled result from vm86 mode %x\n", res );
2291             continue;
2292         }
2293         raise_exception( &rec, context, TRUE );
2294     }
2295 }
2296
2297 #else /* __HAVE_VM86 */
2298 /**********************************************************************
2299  *              __wine_enter_vm86   (NTDLL.@)
2300  */
2301 void __wine_enter_vm86( CONTEXT *context )
2302 {
2303     MESSAGE("vm86 mode not supported on this platform\n");
2304 }
2305 #endif /* __HAVE_VM86 */
2306
2307
2308 /*******************************************************************
2309  *              RtlUnwind (NTDLL.@)
2310  */
2311 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID targetIp,
2312                               PEXCEPTION_RECORD pRecord, PVOID retval, CONTEXT *context )
2313 {
2314     EXCEPTION_RECORD record;
2315     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
2316     DWORD res;
2317
2318     context->Eax = (DWORD)retval;
2319
2320     /* build an exception record, if we do not have one */
2321     if (!pRecord)
2322     {
2323         record.ExceptionCode    = STATUS_UNWIND;
2324         record.ExceptionFlags   = 0;
2325         record.ExceptionRecord  = NULL;
2326         record.ExceptionAddress = (void *)context->Eip;
2327         record.NumberParameters = 0;
2328         pRecord = &record;
2329     }
2330
2331     pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
2332
2333     TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
2334
2335     /* get chain of exception frames */
2336     frame = NtCurrentTeb()->Tib.ExceptionList;
2337     while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
2338     {
2339         /* Check frame address */
2340         if (pEndFrame && (frame > pEndFrame))
2341             raise_status( STATUS_INVALID_UNWIND_TARGET, pRecord );
2342
2343         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
2344             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
2345             (UINT_PTR)frame & 3)
2346             raise_status( STATUS_BAD_STACK, pRecord );
2347
2348         /* Call handler */
2349         TRACE( "calling handler at %p code=%x flags=%x\n",
2350                frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
2351         res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, unwind_handler );
2352         TRACE( "handler at %p returned %x\n", frame->Handler, res );
2353
2354         switch(res)
2355         {
2356         case ExceptionContinueSearch:
2357             break;
2358         case ExceptionCollidedUnwind:
2359             frame = dispatch;
2360             break;
2361         default:
2362             raise_status( STATUS_INVALID_DISPOSITION, pRecord );
2363             break;
2364         }
2365         frame = __wine_pop_frame( frame );
2366     }
2367 }
2368 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )
2369
2370
2371 /*******************************************************************
2372  *              NtRaiseException (NTDLL.@)
2373  */
2374 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
2375 {
2376     NTSTATUS status = raise_exception( rec, context, first_chance );
2377     if (status == STATUS_SUCCESS)
2378     {
2379         set_debug_registers( context );
2380         set_cpu_context( context );
2381     }
2382     return status;
2383 }
2384
2385
2386 /***********************************************************************
2387  *              RtlRaiseException (NTDLL.@)
2388  */
2389 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
2390 {
2391     NTSTATUS status;
2392
2393     rec->ExceptionAddress = (void *)context->Eip;
2394     status = raise_exception( rec, context, TRUE );
2395     if (status != STATUS_SUCCESS) raise_status( status, rec );
2396 }
2397 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 1 )
2398
2399
2400 /*************************************************************************
2401  *              RtlCaptureStackBackTrace (NTDLL.@)
2402  */
2403 USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
2404 {
2405     CONTEXT context;
2406     ULONG i;
2407     ULONG *frame;
2408
2409     RtlCaptureContext( &context );
2410     if (hash) *hash = 0;
2411     frame = (ULONG *)context.Ebp;
2412
2413     while (skip--)
2414     {
2415         if (((void *)frame < NtCurrentTeb()->Tib.StackLimit) ||
2416             ((void *)(frame + 1) >= NtCurrentTeb()->Tib.StackBase)) return 0;
2417         frame = (ULONG *)*frame;
2418     }
2419
2420     for (i = 0; i < count; i++)
2421     {
2422         if (((void *)frame < NtCurrentTeb()->Tib.StackLimit) ||
2423             ((void *)(frame + 1) >= NtCurrentTeb()->Tib.StackBase)) break;
2424         buffer[i] = (void *)frame[1];
2425         if (hash) *hash += frame[1];
2426         frame = (ULONG *)*frame;
2427     }
2428     return i;
2429 }
2430
2431
2432 /* wrapper for apps that don't declare the thread function correctly */
2433 extern void DECLSPEC_NORETURN call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg );
2434 __ASM_GLOBAL_FUNC(call_thread_func,
2435                   "pushl %ebp\n\t"
2436                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2437                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2438                   "movl %esp,%ebp\n\t"
2439                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2440                   "subl $4,%esp\n\t"
2441                   "pushl 12(%ebp)\n\t"
2442                   "call *8(%ebp)\n\t"
2443                   "leal -4(%ebp),%esp\n\t"
2444                   "pushl %eax\n\t"
2445                   "call " __ASM_NAME("exit_thread") "\n\t"
2446                   "int $3" )
2447
2448 /***********************************************************************
2449  *           call_thread_entry_point
2450  */
2451 void call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg )
2452 {
2453     __TRY
2454     {
2455         call_thread_func( entry, arg );
2456     }
2457     __EXCEPT(unhandled_exception_filter)
2458     {
2459         NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
2460     }
2461     __ENDTRY
2462     abort();  /* should not be reached */
2463 }
2464
2465 /***********************************************************************
2466  *           RtlExitUserThread  (NTDLL.@)
2467  */
2468 void WINAPI RtlExitUserThread( ULONG status )
2469 {
2470     exit_thread( status );
2471 }
2472
2473 /***********************************************************************
2474  *           abort_thread
2475  */
2476 void abort_thread( int status )
2477 {
2478     terminate_thread( status );
2479 }
2480
2481 /**********************************************************************
2482  *              DbgBreakPoint   (NTDLL.@)
2483  */
2484 __ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
2485
2486 /**********************************************************************
2487  *              DbgUserBreakPoint   (NTDLL.@)
2488  */
2489 __ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
2490
2491 /**********************************************************************
2492  *           NtCurrentTeb   (NTDLL.@)
2493  */
2494 __ASM_STDCALL_FUNC( NtCurrentTeb, 0, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
2495
2496
2497 /**********************************************************************
2498  *              EXC_CallHandler   (internal)
2499  *
2500  * Some exception handlers depend on EBP to have a fixed position relative to
2501  * the exception frame.
2502  * Shrinker depends on (*1) doing what it does,
2503  * (*2) being the exact instruction it is and (*3) beginning with 0x64
2504  * (i.e. the %fs prefix to the movl instruction). It also depends on the
2505  * function calling the handler having only 5 parameters (*4).
2506  */
2507 __ASM_GLOBAL_FUNC( EXC_CallHandler,
2508                   "pushl %ebp\n\t"
2509                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2510                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2511                   "movl %esp,%ebp\n\t"
2512                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2513                    "pushl %ebx\n\t"
2514                    __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2515                    "movl 28(%ebp), %edx\n\t" /* ugly hack to pass the 6th param needed because of Shrinker */
2516                    "pushl 24(%ebp)\n\t"
2517                    "pushl 20(%ebp)\n\t"
2518                    "pushl 16(%ebp)\n\t"
2519                    "pushl 12(%ebp)\n\t"
2520                    "pushl 8(%ebp)\n\t"
2521                    "call " __ASM_NAME("call_exception_handler") "\n\t"
2522                    "popl %ebx\n\t"
2523                    __ASM_CFI(".cfi_same_value %ebx\n\t")
2524                    "leave\n"
2525                    __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
2526                    __ASM_CFI(".cfi_same_value %ebp\n\t")
2527                    "ret" )
2528 __ASM_GLOBAL_FUNC(call_exception_handler,
2529                   "pushl %ebp\n\t"
2530                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2531                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2532                   "movl %esp,%ebp\n\t"
2533                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2534                   "subl $12,%esp\n\t"
2535                   "pushl 12(%ebp)\n\t"      /* make any exceptions in this... */
2536                   "pushl %edx\n\t"          /* handler be handled by... */
2537                   ".byte 0x64\n\t"
2538                   "pushl (0)\n\t"           /* nested_handler (passed in edx). */
2539                   ".byte 0x64\n\t"
2540                   "movl %esp,(0)\n\t"       /* push the new exception frame onto the exception stack. */
2541                   "pushl 20(%ebp)\n\t"
2542                   "pushl 16(%ebp)\n\t"
2543                   "pushl 12(%ebp)\n\t"
2544                   "pushl 8(%ebp)\n\t"
2545                   "movl 24(%ebp), %ecx\n\t" /* (*1) */
2546                   "call *%ecx\n\t"          /* call handler. (*2) */
2547                   ".byte 0x64\n\t"
2548                   "movl (0), %esp\n\t"      /* restore previous... (*3) */
2549                   ".byte 0x64\n\t"
2550                   "popl (0)\n\t"            /* exception frame. */
2551                   "movl %ebp, %esp\n\t"     /* restore saved stack, in case it was corrupted */
2552                   "popl %ebp\n\t"
2553                    __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
2554                    __ASM_CFI(".cfi_same_value %ebp\n\t")
2555                   "ret $20" )            /* (*4) */
2556
2557 #endif  /* __i386__ */