ntdll: Fix debug exceptions from VM86.
[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  * Set the FPU context from a sigcontext.
710  */
711 inline static void save_fpu( CONTEXT *context, const SIGCONTEXT *sigcontext )
712 {
713     context->ContextFlags |= CONTEXT86_FLOATING_POINT;
714 #ifdef FPU_sig
715     if (FPU_sig(sigcontext))
716     {
717         context->FloatSave = *FPU_sig(sigcontext);
718         return;
719     }
720 #endif  /* FPU_sig */
721 #ifdef __GNUC__
722     __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
723 #endif  /* __GNUC__ */
724 }
725
726
727 /***********************************************************************
728  *           restore_fpu
729  *
730  * Restore the FPU context to a sigcontext.
731  */
732 inline static void restore_fpu( const CONTEXT *context )
733 {
734     FLOATING_SAVE_AREA float_status = context->FloatSave;
735     /* reset the current interrupt status */
736     float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
737 #ifdef __GNUC__
738     __asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
739 #endif  /* __GNUC__ */
740 }
741
742
743 /***********************************************************************
744  *           save_context
745  *
746  * Build a context structure from the signal info.
747  */
748 inline static void save_context( CONTEXT *context, const SIGCONTEXT *sigcontext, WORD fs, WORD gs )
749 {
750     struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
751
752     memset(context, 0, sizeof(*context));
753     context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
754     context->Eax          = EAX_sig(sigcontext);
755     context->Ebx          = EBX_sig(sigcontext);
756     context->Ecx          = ECX_sig(sigcontext);
757     context->Edx          = EDX_sig(sigcontext);
758     context->Esi          = ESI_sig(sigcontext);
759     context->Edi          = EDI_sig(sigcontext);
760     context->Ebp          = EBP_sig(sigcontext);
761     context->EFlags       = EFL_sig(sigcontext);
762     context->Eip          = EIP_sig(sigcontext);
763     context->Esp          = ESP_sig(sigcontext);
764     context->SegCs        = LOWORD(CS_sig(sigcontext));
765     context->SegDs        = LOWORD(DS_sig(sigcontext));
766     context->SegEs        = LOWORD(ES_sig(sigcontext));
767     context->SegFs        = fs;
768     context->SegGs        = gs;
769     context->SegSs        = LOWORD(SS_sig(sigcontext));
770     context->Dr0          = regs->dr0;
771     context->Dr1          = regs->dr1;
772     context->Dr2          = regs->dr2;
773     context->Dr3          = regs->dr3;
774     context->Dr6          = regs->dr6;
775     context->Dr7          = regs->dr7;
776 }
777
778
779 /***********************************************************************
780  *           restore_context
781  *
782  * Restore the signal info from the context.
783  */
784 inline static void restore_context( const CONTEXT *context, SIGCONTEXT *sigcontext )
785 {
786     struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
787
788     regs->dr0 = context->Dr0;
789     regs->dr1 = context->Dr1;
790     regs->dr2 = context->Dr2;
791     regs->dr3 = context->Dr3;
792     regs->dr6 = context->Dr6;
793     regs->dr7 = context->Dr7;
794     EAX_sig(sigcontext) = context->Eax;
795     EBX_sig(sigcontext) = context->Ebx;
796     ECX_sig(sigcontext) = context->Ecx;
797     EDX_sig(sigcontext) = context->Edx;
798     ESI_sig(sigcontext) = context->Esi;
799     EDI_sig(sigcontext) = context->Edi;
800     EBP_sig(sigcontext) = context->Ebp;
801     EFL_sig(sigcontext) = context->EFlags;
802     EIP_sig(sigcontext) = context->Eip;
803     ESP_sig(sigcontext) = context->Esp;
804     CS_sig(sigcontext)  = context->SegCs;
805     DS_sig(sigcontext)  = context->SegDs;
806     ES_sig(sigcontext)  = context->SegEs;
807     SS_sig(sigcontext)  = context->SegSs;
808 #ifdef GS_sig
809     GS_sig(sigcontext)  = context->SegGs;
810 #else
811     wine_set_gs( context->SegGs );
812 #endif
813 #ifdef FS_sig
814     FS_sig(sigcontext)  = context->SegFs;
815 #else
816     wine_set_fs( context->SegFs );
817 #endif
818 }
819
820
821 /***********************************************************************
822  *           set_cpu_context
823  *
824  * Set the new CPU context. Used by NtSetContextThread.
825  */
826 void set_cpu_context( const CONTEXT *context )
827 {
828     DWORD flags = context->ContextFlags & ~CONTEXT_i386;
829
830     if (flags & CONTEXT_FLOATING_POINT) restore_fpu( context );
831
832     if (flags & CONTEXT_DEBUG_REGISTERS)
833     {
834         struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
835         regs->dr0 = context->Dr0;
836         regs->dr1 = context->Dr1;
837         regs->dr2 = context->Dr2;
838         regs->dr3 = context->Dr3;
839         regs->dr6 = context->Dr6;
840         regs->dr7 = context->Dr7;
841     }
842     if (flags & CONTEXT_FULL)
843     {
844         if ((flags & CONTEXT_FULL) != (CONTEXT_FULL & ~CONTEXT_i386))
845             FIXME( "setting partial context (%lx) not supported\n", flags );
846         else
847             __wine_call_from_32_restore_regs( context );
848     }
849 }
850
851
852 /***********************************************************************
853  *           is_privileged_instr
854  *
855  * Check if the fault location is a privileged instruction.
856  * Based on the instruction emulation code in dlls/kernel/instr.c.
857  */
858 static inline int is_privileged_instr( CONTEXT86 *context )
859 {
860     const BYTE *instr;
861     unsigned int prefix_count = 0;
862
863     if (!wine_ldt_is_system( context->SegCs )) return 0;
864     instr = (BYTE *)context->Eip;
865
866     for (;;) switch(*instr)
867     {
868     /* instruction prefixes */
869     case 0x2e:  /* %cs: */
870     case 0x36:  /* %ss: */
871     case 0x3e:  /* %ds: */
872     case 0x26:  /* %es: */
873     case 0x64:  /* %fs: */
874     case 0x65:  /* %gs: */
875     case 0x66:  /* opcode size */
876     case 0x67:  /* addr size */
877     case 0xf0:  /* lock */
878     case 0xf2:  /* repne */
879     case 0xf3:  /* repe */
880         if (++prefix_count >= 15) return 0;
881         instr++;
882         continue;
883
884     case 0x0f: /* extended instruction */
885         switch(instr[1])
886         {
887         case 0x20: /* mov crX, reg */
888         case 0x21: /* mov drX, reg */
889         case 0x22: /* mov reg, crX */
890         case 0x23: /* mov reg drX */
891             return 1;
892         }
893         return 0;
894     case 0x6c: /* insb (%dx) */
895     case 0x6d: /* insl (%dx) */
896     case 0x6e: /* outsb (%dx) */
897     case 0x6f: /* outsl (%dx) */
898     case 0xcd: /* int $xx */
899     case 0xe4: /* inb al,XX */
900     case 0xe5: /* in (e)ax,XX */
901     case 0xe6: /* outb XX,al */
902     case 0xe7: /* out XX,(e)ax */
903     case 0xec: /* inb (%dx),%al */
904     case 0xed: /* inl (%dx),%eax */
905     case 0xee: /* outb %al,(%dx) */
906     case 0xef: /* outl %eax,(%dx) */
907     case 0xf4: /* hlt */
908     case 0xfa: /* cli */
909     case 0xfb: /* sti */
910         return 1;
911     default:
912         return 0;
913     }
914 }
915
916
917 #include "pshpack1.h"
918 struct atl_thunk
919 {
920     DWORD movl;  /* movl this,4(%esp) */
921     DWORD this;
922     BYTE  jmp;   /* jmp func */
923     int   func;
924 };
925 #include "poppack.h"
926
927 /**********************************************************************
928  *              check_atl_thunk
929  *
930  * Check if code destination is an ATL thunk, and emulate it if so.
931  */
932 static BOOL check_atl_thunk( EXCEPTION_RECORD *rec, CONTEXT *context )
933 {
934     struct atl_thunk *thunk = (struct atl_thunk *)rec->ExceptionInformation[1];
935
936     if (thunk->movl != 0x042444c7 || thunk->jmp != 0xe9) return FALSE;
937     *((DWORD *)context->Esp + 1) = thunk->this;
938     context->Eip = (DWORD_PTR)(&thunk->func + 1) + thunk->func;
939     TRACE( "emulating ATL thunk at %p, func=%08lx arg=%08lx\n",
940            thunk, context->Eip, *((DWORD *)context->Esp + 1) );
941     return TRUE;
942 }
943
944
945 /***********************************************************************
946  *           setup_exception
947  *
948  * Setup a proper stack frame for the raise function, and modify the
949  * sigcontext so that the return from the signal handler will call
950  * the raise function.
951  */
952 static EXCEPTION_RECORD *setup_exception( SIGCONTEXT *sigcontext, raise_func func )
953 {
954     struct stack_layout
955     {
956         void             *ret_addr;      /* return address from raise_func */
957         EXCEPTION_RECORD *rec_ptr;       /* first arg for raise_func */
958         CONTEXT          *context_ptr;   /* second arg for raise_func */
959         CONTEXT           context;
960         EXCEPTION_RECORD  rec;
961         DWORD             ebp;
962         DWORD             eip;
963     } *stack;
964
965     WORD fs, gs;
966
967     stack = init_handler( sigcontext, &fs, &gs );
968
969     /* stack sanity checks */
970
971     if ((char *)stack >= (char *)get_signal_stack() &&
972         (char *)stack < (char *)get_signal_stack() + signal_stack_size)
973     {
974         ERR( "nested exception on signal stack in thread %04lx eip %08lx esp %08lx stack %p-%p\n",
975              GetCurrentThreadId(), EIP_sig(sigcontext), ESP_sig(sigcontext),
976              NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
977         server_abort_thread(1);
978     }
979
980     if (stack - 1 > stack || /* check for overflow in subtraction */
981         (char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit ||
982         (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
983     {
984         UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)stack;
985         if (diff < 4096)
986         {
987             ERR( "stack overflow %u bytes in thread %04lx eip %08lx esp %08lx stack %p-%p\n",
988                  diff, GetCurrentThreadId(), EIP_sig(sigcontext), ESP_sig(sigcontext),
989                  NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
990             server_abort_thread(1);
991         }
992         else WARN( "exception outside of stack limits in thread %04lx eip %08lx esp %08lx stack %p-%p\n",
993                    GetCurrentThreadId(), EIP_sig(sigcontext), ESP_sig(sigcontext),
994                    NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
995     }
996
997     stack--;  /* push the stack_layout structure */
998 #ifdef HAVE_VALGRIND_MEMCHECK_H
999     VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
1000 #endif
1001     stack->ret_addr     = (void *)0xdeadbabe;  /* raise_func must not return */
1002     stack->rec_ptr      = &stack->rec;
1003     stack->context_ptr  = &stack->context;
1004
1005     stack->rec.ExceptionRecord  = NULL;
1006     stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
1007     stack->rec.ExceptionAddress = (LPVOID)EIP_sig(sigcontext);
1008     stack->rec.NumberParameters = 0;
1009
1010     save_context( &stack->context, sigcontext, fs, gs );
1011
1012     /* now modify the sigcontext to return to the raise function */
1013     ESP_sig(sigcontext) = (DWORD)stack;
1014     EIP_sig(sigcontext) = (DWORD)func;
1015     EFL_sig(sigcontext) &= ~0x100;  /* clear single-step flag */
1016     CS_sig(sigcontext)  = wine_get_cs();
1017     DS_sig(sigcontext)  = wine_get_ds();
1018     ES_sig(sigcontext)  = wine_get_es();
1019     FS_sig(sigcontext)  = wine_get_fs();
1020     GS_sig(sigcontext)  = wine_get_gs();
1021     SS_sig(sigcontext)  = wine_get_ss();
1022
1023     return stack->rec_ptr;
1024 }
1025
1026
1027 /***********************************************************************
1028  *           get_exception_context
1029  *
1030  * Get a pointer to the context built by setup_exception.
1031  */
1032 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
1033 {
1034     return (CONTEXT *)rec - 1;  /* cf. stack_layout structure */
1035 }
1036
1037
1038 /**********************************************************************
1039  *              get_fpu_code
1040  *
1041  * Get the FPU exception code from the FPU status.
1042  */
1043 static inline DWORD get_fpu_code( const CONTEXT *context )
1044 {
1045     DWORD status = context->FloatSave.StatusWord;
1046
1047     if (status & 0x01)  /* IE */
1048     {
1049         if (status & 0x40)  /* SF */
1050             return EXCEPTION_FLT_STACK_CHECK;
1051         else
1052             return EXCEPTION_FLT_INVALID_OPERATION;
1053     }
1054     if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND;  /* DE flag */
1055     if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO;    /* ZE flag */
1056     if (status & 0x08) return EXCEPTION_FLT_OVERFLOW;          /* OE flag */
1057     if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW;         /* UE flag */
1058     if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT;    /* PE flag */
1059     return EXCEPTION_FLT_INVALID_OPERATION;  /* generic error */
1060 }
1061
1062
1063 /**********************************************************************
1064  *              raise_segv_exception
1065  */
1066 static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1067 {
1068     switch(rec->ExceptionCode)
1069     {
1070     case EXCEPTION_ACCESS_VIOLATION:
1071         if (rec->NumberParameters == 2)
1072         {
1073             if ((rec->ExceptionInformation[0] == 8) && check_atl_thunk( rec, context )) goto done;
1074             rec->ExceptionCode = VIRTUAL_HandleFault( (void *)rec->ExceptionInformation[1] );
1075         }
1076         break;
1077     case EXCEPTION_DATATYPE_MISALIGNMENT:
1078         /* FIXME: pass through exception handler first? */
1079         if (context->EFlags & 0x00040000)
1080         {
1081             /* Disable AC flag, return */
1082             context->EFlags &= ~0x00040000;
1083             goto done;
1084         }
1085         break;
1086     }
1087     __regs_RtlRaiseException( rec, context );
1088 done:
1089     NtSetContextThread( GetCurrentThread(), context );
1090 }
1091
1092
1093 /**********************************************************************
1094  *              raise_trap_exception
1095  */
1096 static void WINAPI raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1097 {
1098     if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
1099     {
1100         if (context->EFlags & 0x100)
1101         {
1102             context->EFlags &= ~0x100;  /* clear single-step flag */
1103         }
1104         else  /* hardware breakpoint, fetch the debug registers */
1105         {
1106             context->ContextFlags = CONTEXT_DEBUG_REGISTERS;
1107             NtGetContextThread(GetCurrentThread(), context);
1108             /* do we really have a bp from a debug register ?
1109              * if not, then someone did a kill(SIGTRAP) on us, and we
1110              * shall return a breakpoint, not a single step exception
1111              */
1112             if (!(context->Dr6 & 0xf)) rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1113             context->ContextFlags |= CONTEXT_FULL;  /* restore flags */
1114         }
1115     }
1116
1117     __regs_RtlRaiseException( rec, context );
1118     NtSetContextThread( GetCurrentThread(), context );
1119 }
1120
1121
1122 /**********************************************************************
1123  *              raise_exception
1124  *
1125  * Generic raise function for exceptions that don't need special treatment.
1126  */
1127 static void WINAPI raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1128 {
1129     __regs_RtlRaiseException( rec, context );
1130     NtSetContextThread( GetCurrentThread(), context );
1131 }
1132
1133
1134 #ifdef __HAVE_VM86
1135 /**********************************************************************
1136  *              raise_vm86_sti_exception
1137  */
1138 static void WINAPI raise_vm86_sti_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1139 {
1140     /* merge_vm86_pending_flags merges the vm86_pending flag in safely */
1141     NtCurrentTeb()->vm86_pending |= VIP_MASK;
1142
1143     if (ntdll_get_thread_data()->vm86_ptr)
1144     {
1145         if (((char*)context->Eip >= (char*)vm86_return) &&
1146             ((char*)context->Eip <= (char*)vm86_return_end) &&
1147             (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
1148             /* exiting from VM86, can't throw */
1149             goto done;
1150         }
1151         merge_vm86_pending_flags( rec );
1152     }
1153     else if (NtCurrentTeb()->dpmi_vif &&
1154              !wine_ldt_is_system(context->SegCs) &&
1155              !wine_ldt_is_system(context->SegSs))
1156     {
1157         /* Executing DPMI code and virtual interrupts are enabled. */
1158         NtCurrentTeb()->vm86_pending = 0;
1159         __regs_RtlRaiseException( rec, context );
1160     }
1161 done:
1162     NtSetContextThread( GetCurrentThread(), context );
1163 }
1164
1165
1166 /**********************************************************************
1167  *              usr2_handler
1168  *
1169  * Handler for SIGUSR2.
1170  * We use it to signal that the running __wine_enter_vm86() should
1171  * immediately set VIP_MASK, causing pending events to be handled
1172  * as early as possible.
1173  */
1174 static HANDLER_DEF(usr2_handler)
1175 {
1176     EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_vm86_sti_exception );
1177     rec->ExceptionCode = EXCEPTION_VM86_STI;
1178 }
1179 #endif /* __HAVE_VM86 */
1180
1181
1182 /**********************************************************************
1183  *              segv_handler
1184  *
1185  * Handler for SIGSEGV and related errors.
1186  */
1187 static HANDLER_DEF(segv_handler)
1188 {
1189     EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_segv_exception );
1190
1191     switch(get_trap_code(HANDLER_CONTEXT))
1192     {
1193     case TRAP_x86_OFLOW:   /* Overflow exception */
1194         rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
1195         break;
1196     case TRAP_x86_BOUND:   /* Bound range exception */
1197         rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
1198         break;
1199     case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
1200         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1201         break;
1202     case TRAP_x86_STKFLT:  /* Stack fault */
1203         rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
1204         break;
1205     case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
1206     case TRAP_x86_PROTFLT:   /* General protection fault */
1207     case TRAP_x86_UNKNOWN:   /* Unknown fault code */
1208         if (!get_error_code(HANDLER_CONTEXT) && is_privileged_instr( get_exception_context(rec) ))
1209             rec->ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
1210         else
1211         {
1212             WORD err = get_error_code(HANDLER_CONTEXT);
1213             rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1214             rec->NumberParameters = 2;
1215             rec->ExceptionInformation[0] = 0;
1216             /* if error contains a LDT selector, use that as fault address */
1217             rec->ExceptionInformation[1] = (err & 7) == 4 ? (err & ~7) : 0xffffffff;
1218         }
1219         break;
1220     case TRAP_x86_PAGEFLT:  /* Page fault */
1221         rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
1222 #ifdef FAULT_ADDRESS
1223         rec->NumberParameters = 2;
1224         rec->ExceptionInformation[0] = (get_error_code(HANDLER_CONTEXT) >> 1) & 0x09;
1225         rec->ExceptionInformation[1] = (ULONG_PTR)FAULT_ADDRESS;
1226 #endif
1227         break;
1228     case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
1229         rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
1230         break;
1231     default:
1232         ERR( "Got unexpected trap %d\n", get_trap_code(HANDLER_CONTEXT) );
1233         /* fall through */
1234     case TRAP_x86_NMI:       /* NMI interrupt */
1235     case TRAP_x86_DNA:       /* Device not available exception */
1236     case TRAP_x86_DOUBLEFLT: /* Double fault exception */
1237     case TRAP_x86_TSSFLT:    /* Invalid TSS exception */
1238     case TRAP_x86_MCHK:      /* Machine check exception */
1239     case TRAP_x86_CACHEFLT:  /* Cache flush exception */
1240         rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
1241         break;
1242     }
1243 }
1244
1245
1246 /**********************************************************************
1247  *              trap_handler
1248  *
1249  * Handler for SIGTRAP.
1250  */
1251 static HANDLER_DEF(trap_handler)
1252 {
1253     EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_trap_exception );
1254
1255     switch(get_trap_code(HANDLER_CONTEXT))
1256     {
1257     case TRAP_x86_TRCTRAP:  /* Single-step exception */
1258         rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
1259         break;
1260     case TRAP_x86_BPTFLT:   /* Breakpoint exception */
1261         rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
1262         /* fall through */
1263     default:
1264         rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1265         break;
1266     }
1267 }
1268
1269
1270 /**********************************************************************
1271  *              fpe_handler
1272  *
1273  * Handler for SIGFPE.
1274  */
1275 static HANDLER_DEF(fpe_handler)
1276 {
1277     EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_exception );
1278     CONTEXT *context;
1279
1280     context = get_exception_context( rec );
1281     save_fpu( context, HANDLER_CONTEXT );
1282
1283     switch(get_trap_code(HANDLER_CONTEXT))
1284     {
1285     case TRAP_x86_DIVIDE:   /* Division by zero exception */
1286         rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
1287         break;
1288     case TRAP_x86_FPOPFLT:   /* Coprocessor segment overrun */
1289         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1290         break;
1291     case TRAP_x86_ARITHTRAP:  /* Floating point exception */
1292     case TRAP_x86_UNKNOWN:    /* Unknown fault code */
1293         rec->ExceptionCode = get_fpu_code( context );
1294         break;
1295     default:
1296         ERR( "Got unexpected trap %d\n", get_trap_code(HANDLER_CONTEXT) );
1297         rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
1298         break;
1299     }
1300 }
1301
1302
1303 /**********************************************************************
1304  *              int_handler
1305  *
1306  * Handler for SIGINT.
1307  *
1308  * FIXME: should not be calling external functions on the signal stack.
1309  */
1310 static HANDLER_DEF(int_handler)
1311 {
1312     WORD fs, gs;
1313     init_handler( HANDLER_CONTEXT, &fs, &gs );
1314     if (!dispatch_signal(SIGINT))
1315     {
1316         EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_exception );
1317         rec->ExceptionCode = CONTROL_C_EXIT;
1318     }
1319 }
1320
1321 /**********************************************************************
1322  *              abrt_handler
1323  *
1324  * Handler for SIGABRT.
1325  */
1326 static HANDLER_DEF(abrt_handler)
1327 {
1328     EXCEPTION_RECORD *rec = setup_exception( HANDLER_CONTEXT, raise_exception );
1329     rec->ExceptionCode  = EXCEPTION_WINE_ASSERTION;
1330     rec->ExceptionFlags = EH_NONCONTINUABLE;
1331 }
1332
1333
1334 /**********************************************************************
1335  *              term_handler
1336  *
1337  * Handler for SIGTERM.
1338  */
1339 static HANDLER_DEF(term_handler)
1340 {
1341     WORD fs, gs;
1342     init_handler( HANDLER_CONTEXT, &fs, &gs );
1343     server_abort_thread(0);
1344 }
1345
1346
1347 /**********************************************************************
1348  *              usr1_handler
1349  *
1350  * Handler for SIGUSR1, used to signal a thread that it got suspended.
1351  */
1352 static HANDLER_DEF(usr1_handler)
1353 {
1354     WORD fs, gs;
1355     CONTEXT context;
1356
1357     init_handler( HANDLER_CONTEXT, &fs, &gs );
1358     save_context( &context, HANDLER_CONTEXT, fs, gs );
1359     wait_suspend( &context );
1360     restore_context( &context, HANDLER_CONTEXT );
1361 }
1362
1363
1364 /**********************************************************************
1365  *              get_signal_stack_total_size
1366  *
1367  * Retrieve the size to allocate for the signal stack, including the TEB at the bottom.
1368  * Must be a power of two.
1369  */
1370 size_t get_signal_stack_total_size(void)
1371 {
1372     static const size_t teb_size = 4096;  /* we reserve one page for the TEB */
1373
1374     if (!signal_stack_size)
1375     {
1376         size_t size = 4096, min_size = teb_size + max( MINSIGSTKSZ, 4096 );
1377         /* find the first power of two not smaller than min_size */
1378         while (size < min_size) size *= 2;
1379         signal_stack_mask = size - 1;
1380         signal_stack_size = size - teb_size;
1381     }
1382     return signal_stack_size + teb_size;
1383 }
1384
1385
1386 /***********************************************************************
1387  *           set_handler
1388  *
1389  * Set a signal handler
1390  */
1391 static int set_handler( int sig, int have_sigaltstack, void (*func)() )
1392 {
1393     struct sigaction sig_act;
1394
1395 #ifdef linux
1396     if (!have_sigaltstack)
1397     {
1398         struct kernel_sigaction sig_act;
1399         sig_act.ksa_handler = func;
1400         sig_act.ksa_flags   = SA_RESTART;
1401         sig_act.ksa_mask    = (1 << (SIGINT-1)) |
1402                               (1 << (SIGUSR1-1)) |
1403                               (1 << (SIGUSR2-1));
1404         /* point to the top of the signal stack */
1405         sig_act.ksa_restorer = (char *)get_signal_stack() + signal_stack_size;
1406         return wine_sigaction( sig, &sig_act, NULL );
1407     }
1408 #endif  /* linux */
1409     sig_act.sa_handler = func;
1410     sigemptyset( &sig_act.sa_mask );
1411     sigaddset( &sig_act.sa_mask, SIGINT );
1412     sigaddset( &sig_act.sa_mask, SIGUSR1 );
1413     sigaddset( &sig_act.sa_mask, SIGUSR2 );
1414
1415 #if defined(linux) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
1416     sig_act.sa_flags = SA_RESTART;
1417 #elif defined (__svr4__) || defined(_SCO_DS) || defined(__APPLE__)
1418     sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
1419 #else
1420     sig_act.sa_flags = 0;
1421 #endif
1422
1423 #ifdef SA_ONSTACK
1424     if (have_sigaltstack) sig_act.sa_flags |= SA_ONSTACK;
1425 #endif
1426     return sigaction( sig, &sig_act, NULL );
1427 }
1428
1429
1430 /***********************************************************************
1431  *           __wine_set_signal_handler   (NTDLL.@)
1432  */
1433 int __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
1434 {
1435     if (sig > sizeof(handlers) / sizeof(handlers[0])) return -1;
1436     if (handlers[sig] != NULL) return -2;
1437     handlers[sig] = wsh;
1438     return 0;
1439 }
1440
1441
1442 /**********************************************************************
1443  *              SIGNAL_Init
1444  */
1445 BOOL SIGNAL_Init(void)
1446 {
1447     int have_sigaltstack = 0;
1448
1449 #ifdef HAVE_SIGALTSTACK
1450     struct sigaltstack ss;
1451     ss.ss_sp    = get_signal_stack();
1452     ss.ss_size  = signal_stack_size;
1453     ss.ss_flags = 0;
1454     if (!sigaltstack(&ss, NULL)) have_sigaltstack = 1;
1455 #ifdef linux
1456     /* sigaltstack may fail because the kernel is too old, or
1457        because glibc is brain-dead. In the latter case a
1458        direct system call should succeed. */
1459     else if (!wine_sigaltstack(&ss, NULL)) have_sigaltstack = 1;
1460 #endif  /* linux */
1461 #endif  /* HAVE_SIGALTSTACK */
1462
1463     if (set_handler( SIGINT,  have_sigaltstack, (void (*)())int_handler ) == -1) goto error;
1464     if (set_handler( SIGFPE,  have_sigaltstack, (void (*)())fpe_handler ) == -1) goto error;
1465     if (set_handler( SIGSEGV, have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1466     if (set_handler( SIGILL,  have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1467     if (set_handler( SIGABRT, have_sigaltstack, (void (*)())abrt_handler ) == -1) goto error;
1468     if (set_handler( SIGTERM, have_sigaltstack, (void (*)())term_handler ) == -1) goto error;
1469     if (set_handler( SIGUSR1, have_sigaltstack, (void (*)())usr1_handler ) == -1) goto error;
1470 #ifdef SIGBUS
1471     if (set_handler( SIGBUS,  have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1472 #endif
1473 #ifdef SIGTRAP
1474     if (set_handler( SIGTRAP, have_sigaltstack, (void (*)())trap_handler ) == -1) goto error;
1475 #endif
1476
1477 #ifdef __HAVE_VM86
1478     if (set_handler( SIGUSR2, have_sigaltstack, (void (*)())usr2_handler ) == -1) goto error;
1479 #endif
1480
1481     return TRUE;
1482
1483  error:
1484     perror("sigaction");
1485     return FALSE;
1486 }
1487
1488
1489 #ifdef __HAVE_VM86
1490 /**********************************************************************
1491  *              __wine_enter_vm86   (NTDLL.@)
1492  *
1493  * Enter vm86 mode with the specified register context.
1494  */
1495 void __wine_enter_vm86( CONTEXT *context )
1496 {
1497     EXCEPTION_RECORD rec;
1498     int res;
1499     struct vm86plus_struct vm86;
1500
1501     memset( &vm86, 0, sizeof(vm86) );
1502     for (;;)
1503     {
1504         restore_vm86_context( context, &vm86 );
1505
1506         ntdll_get_thread_data()->vm86_ptr = &vm86;
1507         merge_vm86_pending_flags( &rec );
1508
1509         res = vm86_enter( &ntdll_get_thread_data()->vm86_ptr ); /* uses and clears teb->vm86_ptr */
1510         if (res < 0)
1511         {
1512             errno = -res;
1513             return;
1514         }
1515
1516         save_vm86_context( context, &vm86 );
1517
1518         rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
1519         rec.ExceptionRecord  = NULL;
1520         rec.ExceptionAddress = (LPVOID)context->Eip;
1521         rec.NumberParameters = 0;
1522
1523         switch(VM86_TYPE(res))
1524         {
1525         case VM86_UNKNOWN: /* unhandled GP fault - IO-instruction or similar */
1526             rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
1527             raise_segv_exception( &rec, context );
1528             continue;
1529         case VM86_TRAP: /* return due to DOS-debugger request */
1530             switch(VM86_ARG(res))
1531             {
1532             case TRAP_x86_TRCTRAP:  /* Single-step exception */
1533                 rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
1534                 break;
1535             case TRAP_x86_BPTFLT:   /* Breakpoint exception */
1536                 rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1;  /* back up over the int3 instruction */
1537                 /* fall through */
1538             default:
1539                 rec.ExceptionCode = EXCEPTION_BREAKPOINT;
1540                 break;
1541             }
1542             break;
1543         case VM86_INTx: /* int3/int x instruction (ARG = x) */
1544             rec.ExceptionCode = EXCEPTION_VM86_INTx;
1545             rec.NumberParameters = 1;
1546             rec.ExceptionInformation[0] = VM86_ARG(res);
1547             break;
1548         case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
1549             context->EFlags |= VIF_MASK;
1550             context->EFlags &= ~VIP_MASK;
1551             NtCurrentTeb()->vm86_pending = 0;
1552             rec.ExceptionCode = EXCEPTION_VM86_STI;
1553             break;
1554         case VM86_PICRETURN: /* return due to pending PIC request */
1555             rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
1556             break;
1557         case VM86_SIGNAL: /* cannot happen because vm86_enter handles this case */
1558         default:
1559             ERR( "unhandled result from vm86 mode %x\n", res );
1560             continue;
1561         }
1562         __regs_RtlRaiseException( &rec, context );
1563     }
1564 }
1565
1566 #else /* __HAVE_VM86 */
1567 /**********************************************************************
1568  *              __wine_enter_vm86   (NTDLL.@)
1569  */
1570 void __wine_enter_vm86( CONTEXT *context )
1571 {
1572     MESSAGE("vm86 mode not supported on this platform\n");
1573 }
1574 #endif /* __HAVE_VM86 */
1575
1576 /**********************************************************************
1577  *              DbgBreakPoint   (NTDLL.@)
1578  */
1579 __ASM_GLOBAL_FUNC( DbgBreakPoint, "int $3; ret");
1580
1581 /**********************************************************************
1582  *              DbgUserBreakPoint   (NTDLL.@)
1583  */
1584 __ASM_GLOBAL_FUNC( DbgUserBreakPoint, "int $3; ret");
1585
1586
1587 /**********************************************************************
1588  *              EXC_CallHandler   (internal)
1589  *
1590  * Some exception handlers depend on EBP to have a fixed position relative to
1591  * the exception frame.
1592  * Shrinker depends on (*1) doing what it does,
1593  * (*2) being the exact instruction it is and (*3) beginning with 0x64
1594  * (i.e. the %fs prefix to the movl instruction). It also depends on the
1595  * function calling the handler having only 5 parameters (*4).
1596  */
1597 __ASM_GLOBAL_FUNC( EXC_CallHandler,
1598 "       pushl   %ebp\n"
1599 "       movl    %esp, %ebp\n"
1600 "       subl    $4,%esp\n"
1601 "       movl    28(%ebp), %edx\n" /* ugly hack to pass the 6th param needed because of Shrinker */
1602 "       pushl   24(%ebp)\n"
1603 "       pushl   20(%ebp)\n"
1604 "       pushl   16(%ebp)\n"
1605 "       pushl   12(%ebp)\n"
1606 "       pushl   8(%ebp)\n"
1607 "       call    " __ASM_NAME("call_exception_handler") "\n"
1608 "       leave\n"
1609 "       ret\n"
1610 );
1611 __ASM_GLOBAL_FUNC(call_exception_handler,
1612 "       pushl   %ebp\n"
1613 "       movl    %esp, %ebp\n"
1614 "       subl    $12,%esp\n"
1615 "       pushl   12(%ebp)\n"       /* make any exceptions in this... */
1616 "       pushl   %edx\n"           /* handler be handled by... */
1617 "       .byte   0x64\n"
1618 "       pushl   (0)\n"            /* nested_handler (passed in edx). */
1619 "       .byte   0x64\n"
1620 "       movl    %esp,(0)\n"       /* push the new exception frame onto the exception stack. */
1621 "       pushl   20(%ebp)\n"
1622 "       pushl   16(%ebp)\n"
1623 "       pushl   12(%ebp)\n"
1624 "       pushl   8(%ebp)\n"
1625 "       movl    24(%ebp), %ecx\n" /* (*1) */
1626 "       call    *%ecx\n"          /* call handler. (*2) */
1627 "       .byte   0x64\n"
1628 "       movl    (0), %esp\n"      /* restore previous... (*3) */
1629 "       .byte   0x64\n"
1630 "       popl    (0)\n"            /* exception frame. */
1631 "       movl    %ebp, %esp\n"     /* restore saved stack, in case it was corrupted */
1632 "       popl    %ebp\n"
1633 "       ret     $20\n"            /* (*4) */
1634 );
1635 #endif  /* __i386__ */