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