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