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