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