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