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