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