ntdll: Added sysctl to make the signal stack per-thread on MacOS.
[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 "windef.h"
59 #include "thread.h"
60 #include "wine/library.h"
61 #include "ntdll_misc.h"
62
63 #ifdef HAVE_VALGRIND_MEMCHECK_H
64 #include <valgrind/memcheck.h>
65 #endif
66
67 /***********************************************************************
68  * signal context platform-specific definitions
69  */
70
71 #ifdef linux
72
73 typedef ucontext_t SIGCONTEXT;
74
75 #define EAX_sig(context)     ((context)->uc_mcontext.gregs[REG_EAX])
76 #define EBX_sig(context)     ((context)->uc_mcontext.gregs[REG_EBX])
77 #define ECX_sig(context)     ((context)->uc_mcontext.gregs[REG_ECX])
78 #define EDX_sig(context)     ((context)->uc_mcontext.gregs[REG_EDX])
79 #define ESI_sig(context)     ((context)->uc_mcontext.gregs[REG_ESI])
80 #define EDI_sig(context)     ((context)->uc_mcontext.gregs[REG_EDI])
81 #define EBP_sig(context)     ((context)->uc_mcontext.gregs[REG_EBP])
82 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[REG_ESP])
83
84 #define CS_sig(context)      ((context)->uc_mcontext.gregs[REG_CS])
85 #define DS_sig(context)      ((context)->uc_mcontext.gregs[REG_DS])
86 #define ES_sig(context)      ((context)->uc_mcontext.gregs[REG_ES])
87 #define SS_sig(context)      ((context)->uc_mcontext.gregs[REG_SS])
88 #define FS_sig(context)      ((context)->uc_mcontext.gregs[REG_FS])
89 #define GS_sig(context)      ((context)->uc_mcontext.gregs[REG_GS])
90
91 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
92 #define EIP_sig(context)     ((context)->uc_mcontext.gregs[REG_EIP])
93 #define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
94 #define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])
95
96 #define FPU_sig(context)     ((FLOATING_SAVE_AREA*)((context)->uc_mcontext.fpregs))
97
98 #define VM86_EAX 0 /* the %eax value while vm86_enter is executing */
99
100 int vm86_enter( void **vm86_ptr );
101 void vm86_return(void);
102 void vm86_return_end(void);
103 __ASM_GLOBAL_FUNC(vm86_enter,
104                   "pushl %ebp\n\t"
105                   "movl %esp, %ebp\n\t"
106                   "movl $166,%eax\n\t"  /*SYS_vm86*/
107                   "movl 8(%ebp),%ecx\n\t" /* vm86_ptr */
108                   "movl (%ecx),%ecx\n\t"
109                   "pushl %ebx\n\t"
110                   "movl $1,%ebx\n\t"    /*VM86_ENTER*/
111                   "pushl %ecx\n\t"      /* put vm86plus_struct ptr somewhere we can find it */
112                   "pushl %fs\n\t"
113                   "pushl %gs\n\t"
114                   "int $0x80\n"
115                   ".globl " __ASM_NAME("vm86_return") "\n\t"
116                   __ASM_FUNC("vm86_return") "\n"
117                   __ASM_NAME("vm86_return") ":\n\t"
118                   "popl %gs\n\t"
119                   "popl %fs\n\t"
120                   "popl %ecx\n\t"
121                   "popl %ebx\n\t"
122                   "popl %ebp\n\t"
123                   "testl %eax,%eax\n\t"
124                   "jl 0f\n\t"
125                   "cmpb $0,%al\n\t" /* VM86_SIGNAL */
126                   "je " __ASM_NAME("vm86_enter") "\n\t"
127                   "0:\n\t"
128                   "movl 4(%esp),%ecx\n\t"  /* vm86_ptr */
129                   "movl $0,(%ecx)\n\t"
130                   ".globl " __ASM_NAME("vm86_return_end") "\n\t"
131                   __ASM_FUNC("vm86_return_end") "\n"
132                   __ASM_NAME("vm86_return_end") ":\n\t"
133                   "ret" );
134
135 #ifdef HAVE_SYS_VM86_H
136 # define __HAVE_VM86
137 #endif
138
139 #endif  /* linux */
140
141 #ifdef BSDI
142
143 #include <machine/frame.h>
144 typedef struct trapframe SIGCONTEXT;
145
146 #define EAX_sig(context)     ((context)->tf_eax)
147 #define EBX_sig(context)     ((context)->tf_ebx)
148 #define ECX_sig(context)     ((context)->tf_ecx)
149 #define EDX_sig(context)     ((context)->tf_edx)
150 #define ESI_sig(context)     ((context)->tf_esi)
151 #define EDI_sig(context)     ((context)->tf_edi)
152 #define EBP_sig(context)     ((context)->tf_ebp)
153
154 #define CS_sig(context)      ((context)->tf_cs)
155 #define DS_sig(context)      ((context)->tf_ds)
156 #define ES_sig(context)      ((context)->tf_es)
157 #define SS_sig(context)      ((context)->tf_ss)
158
159 #define EFL_sig(context)     ((context)->tf_eflags)
160
161 #define EIP_sig(context)     (*((unsigned long*)&(context)->tf_eip))
162 #define ESP_sig(context)     (*((unsigned long*)&(context)->tf_esp))
163
164 #endif /* bsdi */
165
166 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
167
168 typedef struct sigcontext SIGCONTEXT;
169
170 #define EAX_sig(context)     ((context)->sc_eax)
171 #define EBX_sig(context)     ((context)->sc_ebx)
172 #define ECX_sig(context)     ((context)->sc_ecx)
173 #define EDX_sig(context)     ((context)->sc_edx)
174 #define ESI_sig(context)     ((context)->sc_esi)
175 #define EDI_sig(context)     ((context)->sc_edi)
176 #define EBP_sig(context)     ((context)->sc_ebp)
177
178 #define CS_sig(context)      ((context)->sc_cs)
179 #define DS_sig(context)      ((context)->sc_ds)
180 #define ES_sig(context)      ((context)->sc_es)
181 #define FS_sig(context)      ((context)->sc_fs)
182 #define GS_sig(context)      ((context)->sc_gs)
183 #define SS_sig(context)      ((context)->sc_ss)
184
185 #define TRAP_sig(context)    ((context)->sc_trapno)
186 #define ERROR_sig(context)   ((context)->sc_err)
187 #define EFL_sig(context)     ((context)->sc_eflags)
188
189 #define EIP_sig(context)     ((context)->sc_eip)
190 #define ESP_sig(context)     ((context)->sc_esp)
191
192 #endif  /* *BSD */
193
194 #if defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
195
196 #ifdef _SCO_DS
197 #include <sys/regset.h>
198 #endif
199 /* Solaris kludge */
200 #undef ERR
201 #include <sys/ucontext.h>
202 #undef ERR
203 typedef struct ucontext SIGCONTEXT;
204
205 #ifdef _SCO_DS
206 #define gregs regs
207 #endif
208
209 #define EAX_sig(context)     ((context)->uc_mcontext.gregs[EAX])
210 #define EBX_sig(context)     ((context)->uc_mcontext.gregs[EBX])
211 #define ECX_sig(context)     ((context)->uc_mcontext.gregs[ECX])
212 #define EDX_sig(context)     ((context)->uc_mcontext.gregs[EDX])
213 #define ESI_sig(context)     ((context)->uc_mcontext.gregs[ESI])
214 #define EDI_sig(context)     ((context)->uc_mcontext.gregs[EDI])
215 #define EBP_sig(context)     ((context)->uc_mcontext.gregs[EBP])
216
217 #define CS_sig(context)      ((context)->uc_mcontext.gregs[CS])
218 #define DS_sig(context)      ((context)->uc_mcontext.gregs[DS])
219 #define ES_sig(context)      ((context)->uc_mcontext.gregs[ES])
220 #define SS_sig(context)      ((context)->uc_mcontext.gregs[SS])
221
222 #define FS_sig(context)      ((context)->uc_mcontext.gregs[FS])
223 #define GS_sig(context)      ((context)->uc_mcontext.gregs[GS])
224
225 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[EFL])
226
227 #define EIP_sig(context)     ((context)->uc_mcontext.gregs[EIP])
228 #ifdef UESP
229 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[UESP])
230 #elif defined(R_ESP)
231 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[R_ESP])
232 #else
233 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[ESP])
234 #endif
235 #ifdef TRAPNO
236 #define TRAP_sig(context)     ((context)->uc_mcontext.gregs[TRAPNO])
237 #endif
238
239 #endif  /* svr4 || SCO_DS */
240
241 #ifdef __APPLE__
242 # include <sys/ucontext.h>
243
244 typedef ucontext_t SIGCONTEXT;
245
246 #define EAX_sig(context)     ((context)->uc_mcontext->ss.eax)
247 #define EBX_sig(context)     ((context)->uc_mcontext->ss.ebx)
248 #define ECX_sig(context)     ((context)->uc_mcontext->ss.ecx)
249 #define EDX_sig(context)     ((context)->uc_mcontext->ss.edx)
250 #define ESI_sig(context)     ((context)->uc_mcontext->ss.esi)
251 #define EDI_sig(context)     ((context)->uc_mcontext->ss.edi)
252 #define EBP_sig(context)     ((context)->uc_mcontext->ss.ebp)
253
254 #define CS_sig(context)      ((context)->uc_mcontext->ss.cs)
255 #define DS_sig(context)      ((context)->uc_mcontext->ss.ds)
256 #define ES_sig(context)      ((context)->uc_mcontext->ss.es)
257 #define FS_sig(context)      ((context)->uc_mcontext->ss.fs)
258 #define GS_sig(context)      ((context)->uc_mcontext->ss.gs)
259 #define SS_sig(context)      ((context)->uc_mcontext->ss.ss)
260
261 #define EFL_sig(context)     ((context)->uc_mcontext->ss.eflags)
262
263 #define EIP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.eip))
264 #define ESP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.esp))
265
266 #define TRAP_sig(context)    ((context)->uc_mcontext->es.trapno)
267 #define ERROR_sig(context)   ((context)->uc_mcontext->es.err)
268
269 #endif /* __APPLE__ */
270
271 #include "wine/exception.h"
272 #include "wine/debug.h"
273
274 WINE_DEFAULT_DEBUG_CHANNEL(seh);
275
276 typedef int (*wine_signal_handler)(unsigned int sig);
277
278 static size_t signal_stack_mask;
279 static size_t signal_stack_size;
280
281 static wine_signal_handler handlers[256];
282
283 extern void DECLSPEC_NORETURN __wine_call_from_32_restore_regs( const CONTEXT *context );
284
285 enum i386_trap_code
286 {
287     TRAP_x86_UNKNOWN    = -1,  /* Unknown fault (TRAP_sig not defined) */
288 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
289     TRAP_x86_DIVIDE     = T_DIVIDE,     /* Division by zero exception */
290     TRAP_x86_TRCTRAP    = T_TRCTRAP,    /* Single-step exception */
291     TRAP_x86_NMI        = T_NMI,        /* NMI interrupt */
292     TRAP_x86_BPTFLT     = T_BPTFLT,     /* Breakpoint exception */
293     TRAP_x86_OFLOW      = T_OFLOW,      /* Overflow exception */
294     TRAP_x86_BOUND      = T_BOUND,      /* Bound range exception */
295     TRAP_x86_PRIVINFLT  = T_PRIVINFLT,  /* Invalid opcode exception */
296     TRAP_x86_DNA        = T_DNA,        /* Device not available exception */
297     TRAP_x86_DOUBLEFLT  = T_DOUBLEFLT,  /* Double fault exception */
298     TRAP_x86_FPOPFLT    = T_FPOPFLT,    /* Coprocessor segment overrun */
299     TRAP_x86_TSSFLT     = T_TSSFLT,     /* Invalid TSS exception */
300     TRAP_x86_SEGNPFLT   = T_SEGNPFLT,   /* Segment not present exception */
301     TRAP_x86_STKFLT     = T_STKFLT,     /* Stack fault */
302     TRAP_x86_PROTFLT    = T_PROTFLT,    /* General protection fault */
303     TRAP_x86_PAGEFLT    = T_PAGEFLT,    /* Page fault */
304     TRAP_x86_ARITHTRAP  = T_ARITHTRAP,  /* Floating point exception */
305     TRAP_x86_ALIGNFLT   = T_ALIGNFLT,   /* Alignment check exception */
306     TRAP_x86_MCHK       = T_MCHK,       /* Machine check exception */
307     TRAP_x86_CACHEFLT   = T_XMMFLT      /* Cache flush exception */
308 #else
309     TRAP_x86_DIVIDE     = 0,   /* Division by zero exception */
310     TRAP_x86_TRCTRAP    = 1,   /* Single-step exception */
311     TRAP_x86_NMI        = 2,   /* NMI interrupt */
312     TRAP_x86_BPTFLT     = 3,   /* Breakpoint exception */
313     TRAP_x86_OFLOW      = 4,   /* Overflow exception */
314     TRAP_x86_BOUND      = 5,   /* Bound range exception */
315     TRAP_x86_PRIVINFLT  = 6,   /* Invalid opcode exception */
316     TRAP_x86_DNA        = 7,   /* Device not available exception */
317     TRAP_x86_DOUBLEFLT  = 8,   /* Double fault exception */
318     TRAP_x86_FPOPFLT    = 9,   /* Coprocessor segment overrun */
319     TRAP_x86_TSSFLT     = 10,  /* Invalid TSS exception */
320     TRAP_x86_SEGNPFLT   = 11,  /* Segment not present exception */
321     TRAP_x86_STKFLT     = 12,  /* Stack fault */
322     TRAP_x86_PROTFLT    = 13,  /* General protection fault */
323     TRAP_x86_PAGEFLT    = 14,  /* Page fault */
324     TRAP_x86_ARITHTRAP  = 16,  /* Floating point exception */
325     TRAP_x86_ALIGNFLT   = 17,  /* Alignment check exception */
326     TRAP_x86_MCHK       = 18,  /* Machine check exception */
327     TRAP_x86_CACHEFLT   = 19   /* Cache flush exception */
328 #endif
329 };
330
331
332 /***********************************************************************
333  *           dispatch_signal
334  */
335 inline static int dispatch_signal(unsigned int sig)
336 {
337     if (handlers[sig] == NULL) return 0;
338     return handlers[sig](sig);
339 }
340
341
342 /***********************************************************************
343  *           get_trap_code
344  *
345  * Get the trap code for a signal.
346  */
347 static inline enum i386_trap_code get_trap_code( const SIGCONTEXT *sigcontext )
348 {
349 #ifdef TRAP_sig
350     return TRAP_sig(sigcontext);
351 #else
352     return TRAP_x86_UNKNOWN;  /* unknown trap code */
353 #endif
354 }
355
356 /***********************************************************************
357  *           get_error_code
358  *
359  * Get the error code for a signal.
360  */
361 static inline WORD get_error_code( const SIGCONTEXT *sigcontext )
362 {
363 #ifdef ERROR_sig
364     return ERROR_sig(sigcontext);
365 #else
366     return 0;
367 #endif
368 }
369
370 /***********************************************************************
371  *           get_signal_stack
372  *
373  * Get the base of the signal stack for the current thread.
374  */
375 static inline void *get_signal_stack(void)
376 {
377     return (char *)NtCurrentTeb() + 4096;
378 }
379
380
381 /***********************************************************************
382  *           get_current_teb
383  *
384  * Get the current teb based on the stack pointer.
385  */
386 static inline TEB *get_current_teb(void)
387 {
388     unsigned long esp;
389     __asm__("movl %%esp,%0" : "=g" (esp) );
390     return (TEB *)(esp & ~signal_stack_mask);
391 }
392
393
394 #ifdef __HAVE_VM86
395 /***********************************************************************
396  *           save_vm86_context
397  *
398  * Set the register values from a vm86 structure.
399  */
400 static void save_vm86_context( CONTEXT *context, const struct vm86plus_struct *vm86 )
401 {
402     context->ContextFlags = CONTEXT_FULL;
403     context->Eax    = vm86->regs.eax;
404     context->Ebx    = vm86->regs.ebx;
405     context->Ecx    = vm86->regs.ecx;
406     context->Edx    = vm86->regs.edx;
407     context->Esi    = vm86->regs.esi;
408     context->Edi    = vm86->regs.edi;
409     context->Esp    = vm86->regs.esp;
410     context->Ebp    = vm86->regs.ebp;
411     context->Eip    = vm86->regs.eip;
412     context->SegCs  = vm86->regs.cs;
413     context->SegDs  = vm86->regs.ds;
414     context->SegEs  = vm86->regs.es;
415     context->SegFs  = vm86->regs.fs;
416     context->SegGs  = vm86->regs.gs;
417     context->SegSs  = vm86->regs.ss;
418     context->EFlags = vm86->regs.eflags;
419 }
420
421
422 /***********************************************************************
423  *           restore_vm86_context
424  *
425  * Build a vm86 structure from the register values.
426  */
427 static void restore_vm86_context( const CONTEXT *context, struct vm86plus_struct *vm86 )
428 {
429     vm86->regs.eax    = context->Eax;
430     vm86->regs.ebx    = context->Ebx;
431     vm86->regs.ecx    = context->Ecx;
432     vm86->regs.edx    = context->Edx;
433     vm86->regs.esi    = context->Esi;
434     vm86->regs.edi    = context->Edi;
435     vm86->regs.esp    = context->Esp;
436     vm86->regs.ebp    = context->Ebp;
437     vm86->regs.eip    = context->Eip;
438     vm86->regs.cs     = context->SegCs;
439     vm86->regs.ds     = context->SegDs;
440     vm86->regs.es     = context->SegEs;
441     vm86->regs.fs     = context->SegFs;
442     vm86->regs.gs     = context->SegGs;
443     vm86->regs.ss     = context->SegSs;
444     vm86->regs.eflags = context->EFlags;
445 }
446
447
448 /**********************************************************************
449  *              merge_vm86_pending_flags
450  *
451  * Merges TEB.vm86_ptr and TEB.vm86_pending VIP flags and
452  * raises exception if there are pending events and VIF flag
453  * has been turned on.
454  *
455  * Called from __wine_enter_vm86 because vm86_enter
456  * doesn't check for pending events. 
457  *
458  * Called from raise_vm86_sti_exception to check for
459  * pending events in a signal safe way.
460  */
461 static void merge_vm86_pending_flags( EXCEPTION_RECORD *rec )
462 {
463     BOOL check_pending = TRUE;
464     struct vm86plus_struct *vm86 =
465         (struct vm86plus_struct*)(ntdll_get_thread_data()->vm86_ptr);
466
467     /*
468      * In order to prevent a race when SIGUSR2 occurs while
469      * we are returning from exception handler, pending events
470      * will be rechecked after each raised exception.
471      */
472     while (check_pending && NtCurrentTeb()->vm86_pending)
473     {
474         check_pending = FALSE;
475         ntdll_get_thread_data()->vm86_ptr = NULL;
476             
477         /*
478          * If VIF is set, throw exception.
479          * Note that SIGUSR2 may turn VIF flag off so
480          * VIF check must occur only when TEB.vm86_ptr is NULL.
481          */
482         if (vm86->regs.eflags & VIF_MASK)
483         {
484             CONTEXT vcontext;
485             save_vm86_context( &vcontext, vm86 );
486             
487             rec->ExceptionCode    = EXCEPTION_VM86_STI;
488             rec->ExceptionFlags   = EXCEPTION_CONTINUABLE;
489             rec->ExceptionRecord  = NULL;
490             rec->NumberParameters = 0;
491             rec->ExceptionAddress = (LPVOID)vcontext.Eip;
492
493             vcontext.EFlags &= ~VIP_MASK;
494             NtCurrentTeb()->vm86_pending = 0;
495             __regs_RtlRaiseException( rec, &vcontext );
496
497             restore_vm86_context( &vcontext, vm86 );
498             check_pending = TRUE;
499         }
500
501         ntdll_get_thread_data()->vm86_ptr = vm86;
502     }
503
504     /*
505      * Merge VIP flags in a signal safe way. This requires
506      * that the following operation compiles into atomic
507      * instruction.
508      */
509     vm86->regs.eflags |= NtCurrentTeb()->vm86_pending;
510 }
511 #endif /* __HAVE_VM86 */
512
513
514 typedef void (WINAPI *raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
515
516
517 /***********************************************************************
518  *           init_handler
519  *
520  * Handler initialization when the full context is not needed.
521  */
522 inline static void *init_handler( const SIGCONTEXT *sigcontext, WORD *fs, WORD *gs )
523 {
524     void *stack = (void *)ESP_sig(sigcontext);
525     TEB *teb = get_current_teb();
526     struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
527
528     /* get %fs and %gs at time of the fault */
529 #ifdef FS_sig
530     *fs = LOWORD(FS_sig(sigcontext));
531 #else
532     *fs = wine_get_fs();
533 #endif
534 #ifdef GS_sig
535     *gs = LOWORD(GS_sig(sigcontext));
536 #else
537     *gs = wine_get_gs();
538 #endif
539
540     wine_set_fs( thread_regs->fs );
541
542     /* now restore a proper %gs for the fault handler */
543     if (!wine_ldt_is_system(CS_sig(sigcontext)) ||
544         !wine_ldt_is_system(SS_sig(sigcontext)))  /* 16-bit mode */
545     {
546         /*
547          * Win16 or DOS protected mode. Note that during switch
548          * from 16-bit mode to linear mode, CS may be set to system
549          * segment before FS is restored. Fortunately, in this case
550          * SS is still non-system segment. This is why both CS and SS
551          * are checked.
552          */
553         wine_set_gs( thread_regs->gs );
554         stack = teb->WOW32Reserved;
555     }
556 #ifdef __HAVE_VM86
557     else if ((void *)EIP_sig(sigcontext) == vm86_return)  /* vm86 mode */
558     {
559         unsigned int *int_stack = stack;
560         /* fetch the saved %gs from the stack */
561         wine_set_gs( int_stack[0] );
562     }
563 #endif
564     else  /* 32-bit mode */
565     {
566 #ifdef GS_sig
567         wine_set_gs( GS_sig(sigcontext) );
568 #endif
569     }
570     return stack;
571 }
572
573
574 /***********************************************************************
575  *           save_fpu
576  *
577  * Save the thread FPU context.
578  */
579 inline static void save_fpu( CONTEXT *context )
580 {
581 #ifdef __GNUC__
582     context->ContextFlags |= CONTEXT_FLOATING_POINT;
583     __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
584 #endif
585 }
586
587
588 /***********************************************************************
589  *           restore_fpu
590  *
591  * Restore the FPU context to a sigcontext.
592  */
593 inline static void restore_fpu( const CONTEXT *context )
594 {
595     FLOATING_SAVE_AREA float_status = context->FloatSave;
596     /* reset the current interrupt status */
597     float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
598 #ifdef __GNUC__
599     __asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
600 #endif  /* __GNUC__ */
601 }
602
603
604 /***********************************************************************
605  *           save_context
606  *
607  * Build a context structure from the signal info.
608  */
609 inline static void save_context( CONTEXT *context, const SIGCONTEXT *sigcontext, WORD fs, WORD gs )
610 {
611     struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
612
613     memset(context, 0, sizeof(*context));
614     context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
615     context->Eax          = EAX_sig(sigcontext);
616     context->Ebx          = EBX_sig(sigcontext);
617     context->Ecx          = ECX_sig(sigcontext);
618     context->Edx          = EDX_sig(sigcontext);
619     context->Esi          = ESI_sig(sigcontext);
620     context->Edi          = EDI_sig(sigcontext);
621     context->Ebp          = EBP_sig(sigcontext);
622     context->EFlags       = EFL_sig(sigcontext);
623     context->Eip          = EIP_sig(sigcontext);
624     context->Esp          = ESP_sig(sigcontext);
625     context->SegCs        = LOWORD(CS_sig(sigcontext));
626     context->SegDs        = LOWORD(DS_sig(sigcontext));
627     context->SegEs        = LOWORD(ES_sig(sigcontext));
628     context->SegFs        = fs;
629     context->SegGs        = gs;
630     context->SegSs        = LOWORD(SS_sig(sigcontext));
631     context->Dr0          = regs->dr0;
632     context->Dr1          = regs->dr1;
633     context->Dr2          = regs->dr2;
634     context->Dr3          = regs->dr3;
635     context->Dr6          = regs->dr6;
636     context->Dr7          = regs->dr7;
637
638 #ifdef FPU_sig
639     if (FPU_sig(sigcontext))
640     {
641         context->ContextFlags |= CONTEXT_FLOATING_POINT;
642         context->FloatSave = *FPU_sig(sigcontext);
643     }
644     else
645 #endif
646     {
647         save_fpu( context );
648     }
649 }
650
651
652 /***********************************************************************
653  *           restore_context
654  *
655  * Restore the signal info from the context.
656  */
657 inline static void restore_context( const CONTEXT *context, SIGCONTEXT *sigcontext )
658 {
659     struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
660
661     regs->dr0 = context->Dr0;
662     regs->dr1 = context->Dr1;
663     regs->dr2 = context->Dr2;
664     regs->dr3 = context->Dr3;
665     regs->dr6 = context->Dr6;
666     regs->dr7 = context->Dr7;
667     EAX_sig(sigcontext) = context->Eax;
668     EBX_sig(sigcontext) = context->Ebx;
669     ECX_sig(sigcontext) = context->Ecx;
670     EDX_sig(sigcontext) = context->Edx;
671     ESI_sig(sigcontext) = context->Esi;
672     EDI_sig(sigcontext) = context->Edi;
673     EBP_sig(sigcontext) = context->Ebp;
674     EFL_sig(sigcontext) = context->EFlags;
675     EIP_sig(sigcontext) = context->Eip;
676     ESP_sig(sigcontext) = context->Esp;
677     CS_sig(sigcontext)  = context->SegCs;
678     DS_sig(sigcontext)  = context->SegDs;
679     ES_sig(sigcontext)  = context->SegEs;
680     SS_sig(sigcontext)  = context->SegSs;
681 #ifdef GS_sig
682     GS_sig(sigcontext)  = context->SegGs;
683 #else
684     wine_set_gs( context->SegGs );
685 #endif
686 #ifdef FS_sig
687     FS_sig(sigcontext)  = context->SegFs;
688 #else
689     wine_set_fs( context->SegFs );
690 #endif
691
692 #ifdef FPU_sig
693     if (FPU_sig(sigcontext))
694     {
695         *FPU_sig(sigcontext) = context->FloatSave;
696     }
697     else
698 #endif
699     {
700         restore_fpu( context );
701     }
702 }
703
704
705 /***********************************************************************
706  *              get_cpu_context
707  *
708  * Register function to get the context of the current thread.
709  */
710 void WINAPI __regs_get_cpu_context( CONTEXT *context, CONTEXT *regs )
711 {
712     *context = *regs;
713     save_fpu( context );
714 }
715 DEFINE_REGS_ENTRYPOINT( get_cpu_context, 4, 4 );
716
717
718 /***********************************************************************
719  *           set_cpu_context
720  *
721  * Set the new CPU context. Used by NtSetContextThread.
722  */
723 void set_cpu_context( const CONTEXT *context )
724 {
725     DWORD flags = context->ContextFlags & ~CONTEXT_i386;
726
727     if (flags & CONTEXT_FLOATING_POINT) restore_fpu( context );
728
729     if (flags & CONTEXT_DEBUG_REGISTERS)
730     {
731         struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
732         regs->dr0 = context->Dr0;
733         regs->dr1 = context->Dr1;
734         regs->dr2 = context->Dr2;
735         regs->dr3 = context->Dr3;
736         regs->dr6 = context->Dr6;
737         regs->dr7 = context->Dr7;
738     }
739     if (flags & CONTEXT_FULL)
740     {
741         if ((flags & CONTEXT_FULL) != (CONTEXT_FULL & ~CONTEXT_i386))
742             FIXME( "setting partial context (%lx) not supported\n", flags );
743         else
744             __wine_call_from_32_restore_regs( context );
745     }
746 }
747
748
749 /***********************************************************************
750  *           is_privileged_instr
751  *
752  * Check if the fault location is a privileged instruction.
753  * Based on the instruction emulation code in dlls/kernel/instr.c.
754  */
755 static inline int is_privileged_instr( CONTEXT86 *context )
756 {
757     const BYTE *instr;
758     unsigned int prefix_count = 0;
759
760     if (!wine_ldt_is_system( context->SegCs )) return 0;
761     instr = (BYTE *)context->Eip;
762
763     for (;;) switch(*instr)
764     {
765     /* instruction prefixes */
766     case 0x2e:  /* %cs: */
767     case 0x36:  /* %ss: */
768     case 0x3e:  /* %ds: */
769     case 0x26:  /* %es: */
770     case 0x64:  /* %fs: */
771     case 0x65:  /* %gs: */
772     case 0x66:  /* opcode size */
773     case 0x67:  /* addr size */
774     case 0xf0:  /* lock */
775     case 0xf2:  /* repne */
776     case 0xf3:  /* repe */
777         if (++prefix_count >= 15) return 0;
778         instr++;
779         continue;
780
781     case 0x0f: /* extended instruction */
782         switch(instr[1])
783         {
784         case 0x20: /* mov crX, reg */
785         case 0x21: /* mov drX, reg */
786         case 0x22: /* mov reg, crX */
787         case 0x23: /* mov reg drX */
788             return 1;
789         }
790         return 0;
791     case 0x6c: /* insb (%dx) */
792     case 0x6d: /* insl (%dx) */
793     case 0x6e: /* outsb (%dx) */
794     case 0x6f: /* outsl (%dx) */
795     case 0xcd: /* int $xx */
796     case 0xe4: /* inb al,XX */
797     case 0xe5: /* in (e)ax,XX */
798     case 0xe6: /* outb XX,al */
799     case 0xe7: /* out XX,(e)ax */
800     case 0xec: /* inb (%dx),%al */
801     case 0xed: /* inl (%dx),%eax */
802     case 0xee: /* outb %al,(%dx) */
803     case 0xef: /* outl %eax,(%dx) */
804     case 0xf4: /* hlt */
805     case 0xfa: /* cli */
806     case 0xfb: /* sti */
807         return 1;
808     default:
809         return 0;
810     }
811 }
812
813
814 #include "pshpack1.h"
815 struct atl_thunk
816 {
817     DWORD movl;  /* movl this,4(%esp) */
818     DWORD this;
819     BYTE  jmp;   /* jmp func */
820     int   func;
821 };
822 #include "poppack.h"
823
824 /**********************************************************************
825  *              check_atl_thunk
826  *
827  * Check if code destination is an ATL thunk, and emulate it if so.
828  */
829 static BOOL check_atl_thunk( EXCEPTION_RECORD *rec, CONTEXT *context )
830 {
831     struct atl_thunk *thunk = (struct atl_thunk *)rec->ExceptionInformation[1];
832
833     if (thunk->movl != 0x042444c7 || thunk->jmp != 0xe9) return FALSE;
834     *((DWORD *)context->Esp + 1) = thunk->this;
835     context->Eip = (DWORD_PTR)(&thunk->func + 1) + thunk->func;
836     TRACE( "emulating ATL thunk at %p, func=%08lx arg=%08lx\n",
837            thunk, context->Eip, *((DWORD *)context->Esp + 1) );
838     return TRUE;
839 }
840
841
842 /***********************************************************************
843  *           setup_exception
844  *
845  * Setup a proper stack frame for the raise function, and modify the
846  * sigcontext so that the return from the signal handler will call
847  * the raise function.
848  */
849 static EXCEPTION_RECORD *setup_exception( SIGCONTEXT *sigcontext, raise_func func )
850 {
851     struct stack_layout
852     {
853         void             *ret_addr;      /* return address from raise_func */
854         EXCEPTION_RECORD *rec_ptr;       /* first arg for raise_func */
855         CONTEXT          *context_ptr;   /* second arg for raise_func */
856         CONTEXT           context;
857         EXCEPTION_RECORD  rec;
858         DWORD             ebp;
859         DWORD             eip;
860     } *stack;
861
862     WORD fs, gs;
863
864     stack = init_handler( sigcontext, &fs, &gs );
865
866     /* stack sanity checks */
867
868     if ((char *)stack >= (char *)get_signal_stack() &&
869         (char *)stack < (char *)get_signal_stack() + signal_stack_size)
870     {
871         ERR( "nested exception on signal stack in thread %04lx eip %08x esp %08x stack %p-%p\n",
872              GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
873              (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
874              NtCurrentTeb()->Tib.StackBase );
875         server_abort_thread(1);
876     }
877
878     if (stack - 1 > stack || /* check for overflow in subtraction */
879         (char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit ||
880         (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
881     {
882         UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)stack;
883         if (diff < 4096)
884         {
885             ERR( "stack overflow %u bytes in thread %04lx eip %08x esp %08x stack %p-%p\n",
886                  diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
887                  (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
888                  NtCurrentTeb()->Tib.StackBase );
889             server_abort_thread(1);
890         }
891         else WARN( "exception outside of stack limits in thread %04lx eip %08x esp %08x stack %p-%p\n",
892                    GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
893                    (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
894                    NtCurrentTeb()->Tib.StackBase );
895     }
896
897     stack--;  /* push the stack_layout structure */
898 #ifdef HAVE_VALGRIND_MEMCHECK_H
899     VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
900 #endif
901     stack->ret_addr     = (void *)0xdeadbabe;  /* raise_func must not return */
902     stack->rec_ptr      = &stack->rec;
903     stack->context_ptr  = &stack->context;
904
905     stack->rec.ExceptionRecord  = NULL;
906     stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
907     stack->rec.ExceptionAddress = (LPVOID)EIP_sig(sigcontext);
908     stack->rec.NumberParameters = 0;
909
910     save_context( &stack->context, sigcontext, fs, gs );
911
912     /* now modify the sigcontext to return to the raise function */
913     ESP_sig(sigcontext) = (DWORD)stack;
914     EIP_sig(sigcontext) = (DWORD)func;
915     EFL_sig(sigcontext) &= ~0x100;  /* clear single-step flag */
916     CS_sig(sigcontext)  = wine_get_cs();
917     DS_sig(sigcontext)  = wine_get_ds();
918     ES_sig(sigcontext)  = wine_get_es();
919     FS_sig(sigcontext)  = wine_get_fs();
920     GS_sig(sigcontext)  = wine_get_gs();
921     SS_sig(sigcontext)  = wine_get_ss();
922
923     return stack->rec_ptr;
924 }
925
926
927 /***********************************************************************
928  *           get_exception_context
929  *
930  * Get a pointer to the context built by setup_exception.
931  */
932 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
933 {
934     return (CONTEXT *)rec - 1;  /* cf. stack_layout structure */
935 }
936
937
938 /**********************************************************************
939  *              get_fpu_code
940  *
941  * Get the FPU exception code from the FPU status.
942  */
943 static inline DWORD get_fpu_code( const CONTEXT *context )
944 {
945     DWORD status = context->FloatSave.StatusWord;
946
947     if (status & 0x01)  /* IE */
948     {
949         if (status & 0x40)  /* SF */
950             return EXCEPTION_FLT_STACK_CHECK;
951         else
952             return EXCEPTION_FLT_INVALID_OPERATION;
953     }
954     if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND;  /* DE flag */
955     if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO;    /* ZE flag */
956     if (status & 0x08) return EXCEPTION_FLT_OVERFLOW;          /* OE flag */
957     if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW;         /* UE flag */
958     if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT;    /* PE flag */
959     return EXCEPTION_FLT_INVALID_OPERATION;  /* generic error */
960 }
961
962
963 /**********************************************************************
964  *              raise_segv_exception
965  */
966 static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
967 {
968     switch(rec->ExceptionCode)
969     {
970     case EXCEPTION_ACCESS_VIOLATION:
971         if (rec->NumberParameters == 2)
972         {
973             if ((rec->ExceptionInformation[0] == 8) && check_atl_thunk( rec, context )) goto done;
974             rec->ExceptionCode = VIRTUAL_HandleFault( (void *)rec->ExceptionInformation[1] );
975         }
976         break;
977     case EXCEPTION_DATATYPE_MISALIGNMENT:
978         /* FIXME: pass through exception handler first? */
979         if (context->EFlags & 0x00040000)
980         {
981             /* Disable AC flag, return */
982             context->EFlags &= ~0x00040000;
983             goto done;
984         }
985         break;
986     }
987     __regs_RtlRaiseException( rec, context );
988 done:
989     NtSetContextThread( GetCurrentThread(), context );
990 }
991
992
993 /**********************************************************************
994  *              raise_trap_exception
995  */
996 static void WINAPI raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
997 {
998     if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
999     {
1000         if (context->EFlags & 0x100)
1001         {
1002             context->EFlags &= ~0x100;  /* clear single-step flag */
1003         }
1004         else  /* hardware breakpoint, fetch the debug registers */
1005         {
1006             context->ContextFlags = CONTEXT_DEBUG_REGISTERS;
1007             NtGetContextThread(GetCurrentThread(), context);
1008             /* do we really have a bp from a debug register ?
1009              * if not, then someone did a kill(SIGTRAP) on us, and we
1010              * shall return a breakpoint, not a single step exception
1011              */
1012             if (!(context->Dr6 & 0xf)) rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1013             context->ContextFlags |= CONTEXT_FULL;  /* restore flags */
1014         }
1015     }
1016
1017     __regs_RtlRaiseException( rec, context );
1018     NtSetContextThread( GetCurrentThread(), context );
1019 }
1020
1021
1022 /**********************************************************************
1023  *              raise_exception
1024  *
1025  * Generic raise function for exceptions that don't need special treatment.
1026  */
1027 static void WINAPI raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1028 {
1029     __regs_RtlRaiseException( rec, context );
1030     NtSetContextThread( GetCurrentThread(), context );
1031 }
1032
1033
1034 #ifdef __HAVE_VM86
1035 /**********************************************************************
1036  *              raise_vm86_sti_exception
1037  */
1038 static void WINAPI raise_vm86_sti_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1039 {
1040     /* merge_vm86_pending_flags merges the vm86_pending flag in safely */
1041     NtCurrentTeb()->vm86_pending |= VIP_MASK;
1042
1043     if (ntdll_get_thread_data()->vm86_ptr)
1044     {
1045         if (((char*)context->Eip >= (char*)vm86_return) &&
1046             ((char*)context->Eip <= (char*)vm86_return_end) &&
1047             (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
1048             /* exiting from VM86, can't throw */
1049             goto done;
1050         }
1051         merge_vm86_pending_flags( rec );
1052     }
1053     else if (NtCurrentTeb()->dpmi_vif &&
1054              !wine_ldt_is_system(context->SegCs) &&
1055              !wine_ldt_is_system(context->SegSs))
1056     {
1057         /* Executing DPMI code and virtual interrupts are enabled. */
1058         NtCurrentTeb()->vm86_pending = 0;
1059         __regs_RtlRaiseException( rec, context );
1060     }
1061 done:
1062     NtSetContextThread( GetCurrentThread(), context );
1063 }
1064
1065
1066 /**********************************************************************
1067  *              usr2_handler
1068  *
1069  * Handler for SIGUSR2.
1070  * We use it to signal that the running __wine_enter_vm86() should
1071  * immediately set VIP_MASK, causing pending events to be handled
1072  * as early as possible.
1073  */
1074 static void usr2_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1075 {
1076     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_vm86_sti_exception );
1077     rec->ExceptionCode = EXCEPTION_VM86_STI;
1078 }
1079 #endif /* __HAVE_VM86 */
1080
1081
1082 /**********************************************************************
1083  *              segv_handler
1084  *
1085  * Handler for SIGSEGV and related errors.
1086  */
1087 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1088 {
1089     SIGCONTEXT *context = sigcontext;
1090     EXCEPTION_RECORD *rec = setup_exception( context, raise_segv_exception );
1091
1092     switch(get_trap_code(context))
1093     {
1094     case TRAP_x86_OFLOW:   /* Overflow exception */
1095         rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
1096         break;
1097     case TRAP_x86_BOUND:   /* Bound range exception */
1098         rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
1099         break;
1100     case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
1101         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1102         break;
1103     case TRAP_x86_STKFLT:  /* Stack fault */
1104         rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
1105         break;
1106     case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
1107     case TRAP_x86_PROTFLT:   /* General protection fault */
1108     case TRAP_x86_UNKNOWN:   /* Unknown fault code */
1109         if (!get_error_code(context) && is_privileged_instr( get_exception_context(rec) ))
1110             rec->ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
1111         else
1112         {
1113             WORD err = get_error_code(context);
1114             rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1115             rec->NumberParameters = 2;
1116             rec->ExceptionInformation[0] = 0;
1117             /* if error contains a LDT selector, use that as fault address */
1118             rec->ExceptionInformation[1] = (err & 7) == 4 ? (err & ~7) : 0xffffffff;
1119         }
1120         break;
1121     case TRAP_x86_PAGEFLT:  /* Page fault */
1122         rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1123         rec->NumberParameters = 2;
1124         rec->ExceptionInformation[0] = (get_error_code(context) >> 1) & 0x09;
1125         rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
1126         break;
1127     case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
1128         rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
1129         break;
1130     default:
1131         ERR( "Got unexpected trap %d\n", get_trap_code(context) );
1132         /* fall through */
1133     case TRAP_x86_NMI:       /* NMI interrupt */
1134     case TRAP_x86_DNA:       /* Device not available exception */
1135     case TRAP_x86_DOUBLEFLT: /* Double fault exception */
1136     case TRAP_x86_TSSFLT:    /* Invalid TSS exception */
1137     case TRAP_x86_MCHK:      /* Machine check exception */
1138     case TRAP_x86_CACHEFLT:  /* Cache flush exception */
1139         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1140         break;
1141     }
1142 }
1143
1144
1145 /**********************************************************************
1146  *              trap_handler
1147  *
1148  * Handler for SIGTRAP.
1149  */
1150 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1151 {
1152     SIGCONTEXT *context = sigcontext;
1153     EXCEPTION_RECORD *rec = setup_exception( context, raise_trap_exception );
1154
1155     switch(get_trap_code(context))
1156     {
1157     case TRAP_x86_TRCTRAP:  /* Single-step exception */
1158         rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
1159         break;
1160     case TRAP_x86_BPTFLT:   /* Breakpoint exception */
1161         rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
1162         /* fall through */
1163     default:
1164         rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1165         break;
1166     }
1167 }
1168
1169
1170 /**********************************************************************
1171  *              fpe_handler
1172  *
1173  * Handler for SIGFPE.
1174  */
1175 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1176 {
1177     CONTEXT *win_context;
1178     SIGCONTEXT *context = sigcontext;
1179     EXCEPTION_RECORD *rec = setup_exception( context, raise_exception );
1180
1181     win_context = get_exception_context( rec );
1182
1183     switch(get_trap_code(context))
1184     {
1185     case TRAP_x86_DIVIDE:   /* Division by zero exception */
1186         rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
1187         break;
1188     case TRAP_x86_FPOPFLT:   /* Coprocessor segment overrun */
1189         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1190         break;
1191     case TRAP_x86_ARITHTRAP:  /* Floating point exception */
1192     case TRAP_x86_UNKNOWN:    /* Unknown fault code */
1193         rec->ExceptionCode = get_fpu_code( win_context );
1194         break;
1195     default:
1196         ERR( "Got unexpected trap %d\n", get_trap_code(context) );
1197         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1198         break;
1199     }
1200 }
1201
1202
1203 /**********************************************************************
1204  *              int_handler
1205  *
1206  * Handler for SIGINT.
1207  *
1208  * FIXME: should not be calling external functions on the signal stack.
1209  */
1210 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1211 {
1212     WORD fs, gs;
1213     init_handler( sigcontext, &fs, &gs );
1214     if (!dispatch_signal(SIGINT))
1215     {
1216         EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_exception );
1217         rec->ExceptionCode = CONTROL_C_EXIT;
1218     }
1219 }
1220
1221 /**********************************************************************
1222  *              abrt_handler
1223  *
1224  * Handler for SIGABRT.
1225  */
1226 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1227 {
1228     EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_exception );
1229     rec->ExceptionCode  = EXCEPTION_WINE_ASSERTION;
1230     rec->ExceptionFlags = EH_NONCONTINUABLE;
1231 }
1232
1233
1234 /**********************************************************************
1235  *              term_handler
1236  *
1237  * Handler for SIGTERM.
1238  */
1239 static void term_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1240 {
1241     WORD fs, gs;
1242     init_handler( sigcontext, &fs, &gs );
1243     server_abort_thread(0);
1244 }
1245
1246
1247 /**********************************************************************
1248  *              usr1_handler
1249  *
1250  * Handler for SIGUSR1, used to signal a thread that it got suspended.
1251  */
1252 static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1253 {
1254     CONTEXT context;
1255     WORD fs, gs;
1256
1257     init_handler( sigcontext, &fs, &gs );
1258     save_context( &context, sigcontext, fs, gs );
1259     wait_suspend( &context );
1260     restore_context( &context, sigcontext );
1261 }
1262
1263
1264 /**********************************************************************
1265  *              get_signal_stack_total_size
1266  *
1267  * Retrieve the size to allocate for the signal stack, including the TEB at the bottom.
1268  * Must be a power of two.
1269  */
1270 size_t get_signal_stack_total_size(void)
1271 {
1272     static const size_t teb_size = 4096;  /* we reserve one page for the TEB */
1273
1274     if (!signal_stack_size)
1275     {
1276         size_t size = 4096, min_size = teb_size + max( MINSIGSTKSZ, 4096 );
1277         /* find the first power of two not smaller than min_size */
1278         while (size < min_size) size *= 2;
1279         signal_stack_mask = size - 1;
1280         signal_stack_size = size - teb_size;
1281     }
1282     return signal_stack_size + teb_size;
1283 }
1284
1285
1286 /***********************************************************************
1287  *           __wine_set_signal_handler   (NTDLL.@)
1288  */
1289 int __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
1290 {
1291     if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
1292     if (handlers[sig] != NULL) return -2;
1293     handlers[sig] = wsh;
1294     return 0;
1295 }
1296
1297
1298 /**********************************************************************
1299  *              SIGNAL_Init
1300  */
1301 BOOL SIGNAL_Init(void)
1302 {
1303     struct sigaction sig_act;
1304
1305 #ifdef HAVE_SIGALTSTACK
1306     struct sigaltstack ss;
1307
1308 #ifdef __APPLE__
1309     int mib[2], val = 1;
1310
1311     mib[0] = CTL_KERN;
1312     mib[1] = KERN_THALTSTACK;
1313     sysctl( mib, 2, NULL, NULL, &val, sizeof(val) );
1314 #endif
1315
1316     ss.ss_sp    = get_signal_stack();
1317     ss.ss_size  = signal_stack_size;
1318     ss.ss_flags = 0;
1319     if (sigaltstack(&ss, NULL) == -1)
1320     {
1321         perror( "sigaltstack" );
1322         return FALSE;
1323     }
1324 #endif  /* HAVE_SIGALTSTACK */
1325
1326     sigemptyset( &sig_act.sa_mask );
1327     sigaddset( &sig_act.sa_mask, SIGINT );
1328     sigaddset( &sig_act.sa_mask, SIGUSR1 );
1329     sigaddset( &sig_act.sa_mask, SIGUSR2 );
1330     sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
1331
1332 #ifdef SA_ONSTACK
1333     sig_act.sa_flags |= SA_ONSTACK;
1334 #endif
1335
1336     sig_act.sa_sigaction = int_handler;
1337     if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
1338     sig_act.sa_sigaction = fpe_handler;
1339     if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
1340     sig_act.sa_sigaction = abrt_handler;
1341     if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
1342     sig_act.sa_sigaction = term_handler;
1343     if (sigaction( SIGTERM, &sig_act, NULL ) == -1) goto error;
1344     sig_act.sa_sigaction = usr1_handler;
1345     if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
1346
1347     sig_act.sa_sigaction = segv_handler;
1348     if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
1349     if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
1350 #ifdef SIGBUS
1351     if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
1352 #endif
1353
1354 #ifdef SIGTRAP
1355     sig_act.sa_sigaction = trap_handler;
1356     if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
1357 #endif
1358
1359 #ifdef __HAVE_VM86
1360     sig_act.sa_sigaction = usr2_handler;
1361     if (sigaction( SIGUSR2, &sig_act, NULL ) == -1) goto error;
1362 #endif
1363
1364     return TRUE;
1365
1366  error:
1367     perror("sigaction");
1368     return FALSE;
1369 }
1370
1371
1372 #ifdef __HAVE_VM86
1373 /**********************************************************************
1374  *              __wine_enter_vm86   (NTDLL.@)
1375  *
1376  * Enter vm86 mode with the specified register context.
1377  */
1378 void __wine_enter_vm86( CONTEXT *context )
1379 {
1380     EXCEPTION_RECORD rec;
1381     int res;
1382     struct vm86plus_struct vm86;
1383
1384     memset( &vm86, 0, sizeof(vm86) );
1385     for (;;)
1386     {
1387         restore_vm86_context( context, &vm86 );
1388
1389         ntdll_get_thread_data()->vm86_ptr = &vm86;
1390         merge_vm86_pending_flags( &rec );
1391
1392         res = vm86_enter( &ntdll_get_thread_data()->vm86_ptr ); /* uses and clears teb->vm86_ptr */
1393         if (res < 0)
1394         {
1395             errno = -res;
1396             return;
1397         }
1398
1399         save_vm86_context( context, &vm86 );
1400
1401         rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
1402         rec.ExceptionRecord  = NULL;
1403         rec.ExceptionAddress = (LPVOID)context->Eip;
1404         rec.NumberParameters = 0;
1405
1406         switch(VM86_TYPE(res))
1407         {
1408         case VM86_UNKNOWN: /* unhandled GP fault - IO-instruction or similar */
1409             rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
1410             raise_segv_exception( &rec, context );
1411             continue;
1412         case VM86_TRAP: /* return due to DOS-debugger request */
1413             switch(VM86_ARG(res))
1414             {
1415             case TRAP_x86_TRCTRAP:  /* Single-step exception */
1416                 rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
1417                 break;
1418             case TRAP_x86_BPTFLT:   /* Breakpoint exception */
1419                 rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1;  /* back up over the int3 instruction */
1420                 /* fall through */
1421             default:
1422                 rec.ExceptionCode = EXCEPTION_BREAKPOINT;
1423                 break;
1424             }
1425             break;
1426         case VM86_INTx: /* int3/int x instruction (ARG = x) */
1427             rec.ExceptionCode = EXCEPTION_VM86_INTx;
1428             rec.NumberParameters = 1;
1429             rec.ExceptionInformation[0] = VM86_ARG(res);
1430             break;
1431         case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
1432             context->EFlags |= VIF_MASK;
1433             context->EFlags &= ~VIP_MASK;
1434             NtCurrentTeb()->vm86_pending = 0;
1435             rec.ExceptionCode = EXCEPTION_VM86_STI;
1436             break;
1437         case VM86_PICRETURN: /* return due to pending PIC request */
1438             rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
1439             break;
1440         case VM86_SIGNAL: /* cannot happen because vm86_enter handles this case */
1441         default:
1442             ERR( "unhandled result from vm86 mode %x\n", res );
1443             continue;
1444         }
1445         __regs_RtlRaiseException( &rec, context );
1446     }
1447 }
1448
1449 #else /* __HAVE_VM86 */
1450 /**********************************************************************
1451  *              __wine_enter_vm86   (NTDLL.@)
1452  */
1453 void __wine_enter_vm86( CONTEXT *context )
1454 {
1455     MESSAGE("vm86 mode not supported on this platform\n");
1456 }
1457 #endif /* __HAVE_VM86 */
1458
1459 /**********************************************************************
1460  *              DbgBreakPoint   (NTDLL.@)
1461  */
1462 __ASM_GLOBAL_FUNC( DbgBreakPoint, "int $3; ret");
1463
1464 /**********************************************************************
1465  *              DbgUserBreakPoint   (NTDLL.@)
1466  */
1467 __ASM_GLOBAL_FUNC( DbgUserBreakPoint, "int $3; ret");
1468
1469
1470 /**********************************************************************
1471  *              EXC_CallHandler   (internal)
1472  *
1473  * Some exception handlers depend on EBP to have a fixed position relative to
1474  * the exception frame.
1475  * Shrinker depends on (*1) doing what it does,
1476  * (*2) being the exact instruction it is and (*3) beginning with 0x64
1477  * (i.e. the %fs prefix to the movl instruction). It also depends on the
1478  * function calling the handler having only 5 parameters (*4).
1479  */
1480 __ASM_GLOBAL_FUNC( EXC_CallHandler,
1481 "       pushl   %ebp\n"
1482 "       movl    %esp, %ebp\n"
1483 "       subl    $4,%esp\n"
1484 "       movl    28(%ebp), %edx\n" /* ugly hack to pass the 6th param needed because of Shrinker */
1485 "       pushl   24(%ebp)\n"
1486 "       pushl   20(%ebp)\n"
1487 "       pushl   16(%ebp)\n"
1488 "       pushl   12(%ebp)\n"
1489 "       pushl   8(%ebp)\n"
1490 "       call    " __ASM_NAME("call_exception_handler") "\n"
1491 "       leave\n"
1492 "       ret\n"
1493 );
1494 __ASM_GLOBAL_FUNC(call_exception_handler,
1495 "       pushl   %ebp\n"
1496 "       movl    %esp, %ebp\n"
1497 "       subl    $12,%esp\n"
1498 "       pushl   12(%ebp)\n"       /* make any exceptions in this... */
1499 "       pushl   %edx\n"           /* handler be handled by... */
1500 "       .byte   0x64\n"
1501 "       pushl   (0)\n"            /* nested_handler (passed in edx). */
1502 "       .byte   0x64\n"
1503 "       movl    %esp,(0)\n"       /* push the new exception frame onto the exception stack. */
1504 "       pushl   20(%ebp)\n"
1505 "       pushl   16(%ebp)\n"
1506 "       pushl   12(%ebp)\n"
1507 "       pushl   8(%ebp)\n"
1508 "       movl    24(%ebp), %ecx\n" /* (*1) */
1509 "       call    *%ecx\n"          /* call handler. (*2) */
1510 "       .byte   0x64\n"
1511 "       movl    (0), %esp\n"      /* restore previous... (*3) */
1512 "       .byte   0x64\n"
1513 "       popl    (0)\n"            /* exception frame. */
1514 "       movl    %ebp, %esp\n"     /* restore saved stack, in case it was corrupted */
1515 "       popl    %ebp\n"
1516 "       ret     $20\n"            /* (*4) */
1517 );
1518 #endif  /* __i386__ */