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