Cleaned up a bit, removed todos for OpenThread, avoid TerminateThread
[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
25 #include <errno.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <unistd.h>
30
31 #ifdef HAVE_SYS_PARAM_H
32 # include <sys/param.h>
33 #endif
34 #ifdef HAVE_SYSCALL_H
35 # include <syscall.h>
36 #else
37 # ifdef HAVE_SYS_SYSCALL_H
38 #  include <sys/syscall.h>
39 # endif
40 #endif
41
42 #ifdef HAVE_SYS_VM86_H
43 # include <sys/vm86.h>
44 #endif
45
46 #ifdef HAVE_SYS_SIGNAL_H
47 # include <sys/signal.h>
48 #endif
49
50 #include "ntddk.h"
51 #include "winnt.h"
52
53 #include "selectors.h"
54
55 /***********************************************************************
56  * signal context platform-specific definitions
57  */
58
59 #ifdef linux
60 typedef struct
61 {
62     unsigned short sc_gs, __gsh;
63     unsigned short sc_fs, __fsh;
64     unsigned short sc_es, __esh;
65     unsigned short sc_ds, __dsh;
66     unsigned long sc_edi;
67     unsigned long sc_esi;
68     unsigned long sc_ebp;
69     unsigned long sc_esp;
70     unsigned long sc_ebx;
71     unsigned long sc_edx;
72     unsigned long sc_ecx;
73     unsigned long sc_eax;
74     unsigned long sc_trapno;
75     unsigned long sc_err;
76     unsigned long sc_eip;
77     unsigned short sc_cs, __csh;
78     unsigned long sc_eflags;
79     unsigned long esp_at_signal;
80     unsigned short sc_ss, __ssh;
81     unsigned long i387;
82     unsigned long oldmask;
83     unsigned long cr2;
84 } SIGCONTEXT;
85
86 #define HANDLER_DEF(name) void name( int __signal, SIGCONTEXT __context )
87 #define HANDLER_CONTEXT (&__context)
88
89 /* this is the sigaction structure from the Linux 2.1.20 kernel.  */
90 struct kernel_sigaction
91 {
92     void (*ksa_handler)();
93     unsigned long ksa_mask;
94     unsigned long ksa_flags;
95     void *ksa_restorer;
96 };
97
98 /* Similar to the sigaction function in libc, except it leaves alone the
99    restorer field, which is used to specify the signal stack address */
100 static inline int wine_sigaction( int sig, struct kernel_sigaction *new,
101                                   struct kernel_sigaction *old )
102 {
103     __asm__ __volatile__( "pushl %%ebx\n\t"
104                           "movl %2,%%ebx\n\t"
105                           "int $0x80\n\t"
106                           "popl %%ebx"
107                           : "=a" (sig)
108                           : "0" (SYS_sigaction), "r" (sig), "c" (new), "d" (old) );
109     if (sig>=0) return 0;
110     errno = -sig;
111     return -1;
112 }
113
114 #ifdef HAVE_SIGALTSTACK
115 /* direct syscall for sigaltstack to work around glibc 2.0 brain-damage */
116 static inline int wine_sigaltstack( const struct sigaltstack *new,
117                                     struct sigaltstack *old )
118 {
119     int ret;
120     __asm__ __volatile__( "pushl %%ebx\n\t"
121                           "movl %2,%%ebx\n\t"
122                           "int $0x80\n\t"
123                           "popl %%ebx"
124                           : "=a" (ret)
125                           : "0" (SYS_sigaltstack), "r" (new), "c" (old) );
126     if (ret >= 0) return 0;
127     errno = -ret;
128     return -1;
129 }
130 #endif
131
132 #define VM86_EAX 0 /* the %eax value while vm86_enter is executing */
133
134 int vm86_enter( void **vm86_ptr );
135 void vm86_return(void);
136 void vm86_return_end(void);
137 __ASM_GLOBAL_FUNC(vm86_enter,
138                   "pushl %ebp\n\t"
139                   "movl %esp, %ebp\n\t"
140                   "movl $166,%eax\n\t"  /*SYS_vm86*/
141                   "movl 8(%ebp),%ecx\n\t" /* vm86_ptr */
142                   "movl (%ecx),%ecx\n\t"
143                   "pushl %ebx\n\t"
144                   "movl $1,%ebx\n\t"    /*VM86_ENTER*/
145                   "pushl %ecx\n\t"      /* put vm86plus_struct ptr somewhere we can find it */
146                   "pushl %fs\n\t"
147                   "int $0x80\n"
148                   ".globl " __ASM_NAME("vm86_return") "\n\t"
149                   ".type " __ASM_NAME("vm86_return") ",@function\n"
150                   __ASM_NAME("vm86_return") ":\n\t"
151                   "popl %fs\n\t"
152                   "popl %ecx\n\t"
153                   "popl %ebx\n\t"
154                   "popl %ebp\n\t"
155                   "testl %eax,%eax\n\t"
156                   "jl 0f\n\t"
157                   "cmpb $0,%al\n\t" /* VM86_SIGNAL */
158                   "je " __ASM_NAME("vm86_enter") "\n\t"
159                   "0:\n\t"
160                   "movl 4(%esp),%ecx\n\t"  /* vm86_ptr */
161                   "movl $0,(%ecx)\n\t"
162                   ".globl " __ASM_NAME("vm86_return_end") "\n\t"
163                   ".type " __ASM_NAME("vm86_return_end") ",@function\n"
164                   __ASM_NAME("vm86_return_end") ":\n\t"
165                   "ret" );
166
167 #define __HAVE_VM86
168
169 #endif  /* linux */
170
171 #ifdef BSDI
172
173 #define EAX_sig(context)     ((context)->tf_eax)
174 #define EBX_sig(context)     ((context)->tf_ebx)
175 #define ECX_sig(context)     ((context)->tf_ecx)
176 #define EDX_sig(context)     ((context)->tf_edx)
177 #define ESI_sig(context)     ((context)->tf_esi)
178 #define EDI_sig(context)     ((context)->tf_edi)
179 #define EBP_sig(context)     ((context)->tf_ebp)
180                             
181 #define CS_sig(context)      ((context)->tf_cs)
182 #define DS_sig(context)      ((context)->tf_ds)
183 #define ES_sig(context)      ((context)->tf_es)
184 #define SS_sig(context)      ((context)->tf_ss)
185
186 #include <machine/frame.h>
187 typedef struct trapframe SIGCONTEXT;
188
189 #define HANDLER_DEF(name) void name( int __signal, int code, SIGCONTEXT *__context )
190 #define HANDLER_CONTEXT __context
191
192 #define EFL_sig(context)     ((context)->tf_eflags)
193
194 #define EIP_sig(context)     (*((unsigned long*)&(context)->tf_eip))
195 #define ESP_sig(context)     (*((unsigned long*)&(context)->tf_esp))
196
197 #endif /* bsdi */
198
199 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
200
201 typedef struct sigcontext SIGCONTEXT;
202
203 #define HANDLER_DEF(name) void name( int __signal, int code, SIGCONTEXT *__context )
204 #define HANDLER_CONTEXT __context
205
206 #endif  /* FreeBSD */
207
208 #if defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
209
210 #ifdef _SCO_DS
211 #include <sys/regset.h>
212 #endif
213 /* Solaris kludge */
214 #undef ERR
215 #include <sys/ucontext.h>
216 #undef ERR
217 typedef struct ucontext SIGCONTEXT;
218
219 #define HANDLER_DEF(name) void name( int __signal, void *__siginfo, SIGCONTEXT *__context )
220 #define HANDLER_CONTEXT __context
221
222 #endif  /* svr4 || SCO_DS */
223
224 #ifdef __EMX__
225
226 typedef struct
227 {
228     unsigned long ContextFlags;
229     FLOATING_SAVE_AREA sc_float;
230     unsigned long sc_gs;
231     unsigned long sc_fs;
232     unsigned long sc_es;
233     unsigned long sc_ds;
234     unsigned long sc_edi;
235     unsigned long sc_esi;
236     unsigned long sc_eax;
237     unsigned long sc_ebx;
238     unsigned long sc_ecx;
239     unsigned long sc_edx;
240     unsigned long sc_ebp;
241     unsigned long sc_eip;
242     unsigned long sc_cs;
243     unsigned long sc_eflags;
244     unsigned long sc_esp;
245     unsigned long sc_ss;
246 } SIGCONTEXT;
247
248 #endif  /* __EMX__ */
249
250
251 #if defined(linux) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMX__)
252
253 #define EAX_sig(context)     ((context)->sc_eax)
254 #define EBX_sig(context)     ((context)->sc_ebx)
255 #define ECX_sig(context)     ((context)->sc_ecx)
256 #define EDX_sig(context)     ((context)->sc_edx)
257 #define ESI_sig(context)     ((context)->sc_esi)
258 #define EDI_sig(context)     ((context)->sc_edi)
259 #define EBP_sig(context)     ((context)->sc_ebp)
260                             
261 #define CS_sig(context)      ((context)->sc_cs)
262 #define DS_sig(context)      ((context)->sc_ds)
263 #define ES_sig(context)      ((context)->sc_es)
264 #define SS_sig(context)      ((context)->sc_ss)
265                             
266 /* FS and GS are now in the sigcontext struct of FreeBSD, but not 
267  * saved by the exception handling. duh.
268  * Actually they are in -current (have been for a while), and that
269  * patch now finally has been MFC'd to -stable too (Nov 15 1999).
270  * If you're running a system from the -stable branch older than that,
271  * like a 3.3-RELEASE, grab the patch from the ports tree:
272  * ftp://ftp.freebsd.org/pub/FreeBSD/FreeBSD-current/ports/emulators/wine/files/patch-3.3-sys-fsgs
273  * (If its not yet there when you look, go here:
274  * http://www.jelal.kn-bremen.de/freebsd/ports/emulators/wine/files/ )
275  */
276 #ifdef __FreeBSD__
277 #define FS_sig(context)      ((context)->sc_fs)
278 #define GS_sig(context)      ((context)->sc_gs)
279 #endif
280
281 #ifdef linux
282 #define FS_sig(context)      ((context)->sc_fs)
283 #define GS_sig(context)      ((context)->sc_gs)
284 #define CR2_sig(context)     ((context)->cr2)
285 #define TRAP_sig(context)    ((context)->sc_trapno)
286 #define ERROR_sig(context)   ((context)->sc_err)
287 #define FPU_sig(context)     ((FLOATING_SAVE_AREA*)((context)->i387))
288 #endif
289
290 #ifndef __FreeBSD__
291 #define EFL_sig(context)     ((context)->sc_eflags)
292 #else                       
293 #define EFL_sig(context)     ((context)->sc_efl)
294 /* FreeBSD, see i386/i386/traps.c::trap_pfault va->err kludge  */
295 #define CR2_sig(context)     ((context)->sc_err)
296 #define TRAP_sig(context)    ((context)->sc_trapno)
297 #endif                      
298
299 #define EIP_sig(context)     (*((unsigned long*)&(context)->sc_eip))
300 #define ESP_sig(context)     (*((unsigned long*)&(context)->sc_esp))
301
302 #endif  /* linux || __NetBSD__ || __FreeBSD__ || __OpenBSD__ */
303
304 #if defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
305
306 #ifdef _SCO_DS
307 #define gregs regs
308 #endif
309
310 #define EAX_sig(context)     ((context)->uc_mcontext.gregs[EAX])
311 #define EBX_sig(context)     ((context)->uc_mcontext.gregs[EBX])
312 #define ECX_sig(context)     ((context)->uc_mcontext.gregs[ECX])
313 #define EDX_sig(context)     ((context)->uc_mcontext.gregs[EDX])
314 #define ESI_sig(context)     ((context)->uc_mcontext.gregs[ESI])
315 #define EDI_sig(context)     ((context)->uc_mcontext.gregs[EDI])
316 #define EBP_sig(context)     ((context)->uc_mcontext.gregs[EBP])
317                             
318 #define CS_sig(context)      ((context)->uc_mcontext.gregs[CS])
319 #define DS_sig(context)      ((context)->uc_mcontext.gregs[DS])
320 #define ES_sig(context)      ((context)->uc_mcontext.gregs[ES])
321 #define SS_sig(context)      ((context)->uc_mcontext.gregs[SS])
322                             
323 #define FS_sig(context)      ((context)->uc_mcontext.gregs[FS])
324 #define GS_sig(context)      ((context)->uc_mcontext.gregs[GS])
325
326 #define EFL_sig(context)     ((context)->uc_mcontext.gregs[EFL])
327                             
328 #define EIP_sig(context)     ((context)->uc_mcontext.gregs[EIP])
329 #ifdef R_ESP
330 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[R_ESP])
331 #else
332 #define ESP_sig(context)     ((context)->uc_mcontext.gregs[ESP])
333 #endif
334 #ifdef TRAPNO
335 #define TRAP_sig(context)     ((context)->uc_mcontext.gregs[TRAPNO])
336 #endif
337
338 #endif  /* svr4 || SCO_DS */
339
340
341 /* exception code definitions (already defined by FreeBSD/NetBSD) */
342 #if !defined(__FreeBSD__) && !defined(__NetBSD__) /* FIXME: other BSDs? */
343 #define T_DIVIDE        0   /* Division by zero exception */
344 #define T_TRCTRAP       1   /* Single-step exception */
345 #define T_NMI           2   /* NMI interrupt */
346 #define T_BPTFLT        3   /* Breakpoint exception */
347 #define T_OFLOW         4   /* Overflow exception */
348 #define T_BOUND         5   /* Bound range exception */
349 #define T_PRIVINFLT     6   /* Invalid opcode exception */
350 #define T_DNA           7   /* Device not available exception */
351 #define T_DOUBLEFLT     8   /* Double fault exception */
352 #define T_FPOPFLT       9   /* Coprocessor segment overrun */
353 #define T_TSSFLT        10  /* Invalid TSS exception */
354 #define T_SEGNPFLT      11  /* Segment not present exception */
355 #define T_STKFLT        12  /* Stack fault */
356 #define T_PROTFLT       13  /* General protection fault */
357 #define T_PAGEFLT       14  /* Page fault */
358 #define T_RESERVED      15  /* Unknown exception */
359 #define T_ARITHTRAP     16  /* Floating point exception */
360 #define T_ALIGNFLT      17  /* Alignment check exception */
361 #define T_MCHK          18  /* Machine check exception */
362 #define T_CACHEFLT      19  /* Cache flush exception */
363 #endif
364 #if defined(__NetBSD__)
365 #define T_MCHK          19  /* Machine check exception */
366 #endif
367
368 #define T_UNKNOWN     (-1)  /* Unknown fault (TRAP_sig not defined) */
369
370 #include "wine/exception.h"
371 #include "winnt.h"
372 #include "stackframe.h"
373 #include "global.h"
374 #include "miscemu.h"
375 #include "ntddk.h"
376 #include "syslevel.h"
377 #include "wine/debug.h"
378
379 WINE_DEFAULT_DEBUG_CHANNEL(seh);
380
381 static sigset_t all_sigs;
382
383
384 /***********************************************************************
385  *           get_trap_code
386  *
387  * Get the trap code for a signal.
388  */
389 static inline int get_trap_code( const SIGCONTEXT *sigcontext )
390 {
391 #ifdef TRAP_sig
392     return TRAP_sig(sigcontext);
393 #else
394     return T_UNKNOWN;  /* unknown trap code */
395 #endif
396 }
397
398 /***********************************************************************
399  *           get_error_code
400  *
401  * Get the error code for a signal.
402  */
403 static inline int get_error_code( const SIGCONTEXT *sigcontext )
404 {
405 #ifdef ERROR_sig
406     return ERROR_sig(sigcontext);
407 #else
408     return 0;
409 #endif
410 }
411
412 /***********************************************************************
413  *           get_cr2_value
414  *
415  * Get the CR2 value for a signal.
416  */
417 static inline void *get_cr2_value( const SIGCONTEXT *sigcontext )
418 {
419 #ifdef CR2_sig
420     return (void *)CR2_sig(sigcontext);
421 #else
422     return NULL;
423 #endif
424 }
425
426
427 #ifdef __HAVE_VM86
428 /***********************************************************************
429  *           save_vm86_context
430  *
431  * Set the register values from a vm86 structure.
432  */
433 static void save_vm86_context( CONTEXT *context, const struct vm86plus_struct *vm86 )
434 {
435     context->Eax    = vm86->regs.eax;
436     context->Ebx    = vm86->regs.ebx;
437     context->Ecx    = vm86->regs.ecx;
438     context->Edx    = vm86->regs.edx;
439     context->Esi    = vm86->regs.esi;
440     context->Edi    = vm86->regs.edi;
441     context->Esp    = vm86->regs.esp;
442     context->Ebp    = vm86->regs.ebp;
443     context->Eip    = vm86->regs.eip;
444     context->SegCs  = vm86->regs.cs;
445     context->SegDs  = vm86->regs.ds;
446     context->SegEs  = vm86->regs.es;
447     context->SegFs  = vm86->regs.fs;
448     context->SegGs  = vm86->regs.gs;
449     context->SegSs  = vm86->regs.ss;
450     context->EFlags = vm86->regs.eflags;
451 }
452
453
454 /***********************************************************************
455  *           restore_vm86_context
456  *
457  * Build a vm86 structure from the register values.
458  */
459 static void restore_vm86_context( const CONTEXT *context, struct vm86plus_struct *vm86 )
460 {
461     vm86->regs.eax    = context->Eax;
462     vm86->regs.ebx    = context->Ebx;
463     vm86->regs.ecx    = context->Ecx;
464     vm86->regs.edx    = context->Edx;
465     vm86->regs.esi    = context->Esi;
466     vm86->regs.edi    = context->Edi;
467     vm86->regs.esp    = context->Esp;
468     vm86->regs.ebp    = context->Ebp;
469     vm86->regs.eip    = context->Eip;
470     vm86->regs.cs     = context->SegCs;
471     vm86->regs.ds     = context->SegDs;
472     vm86->regs.es     = context->SegEs;
473     vm86->regs.fs     = context->SegFs;
474     vm86->regs.gs     = context->SegGs;
475     vm86->regs.ss     = context->SegSs;
476     vm86->regs.eflags = context->EFlags;
477 }
478 #endif /* __HAVE_VM86 */
479
480
481 /***********************************************************************
482  *           save_context
483  *
484  * Set the register values from a sigcontext. 
485  */
486 static void save_context( CONTEXT *context, const SIGCONTEXT *sigcontext )
487 {
488     WORD fs;
489     /* get %fs at time of the fault */
490 #ifdef FS_sig
491     fs = FS_sig(sigcontext);
492 #else
493     fs = __get_fs();
494 #endif
495     context->SegFs = fs;
496
497     /* now restore a proper %fs for the fault handler */
498     if (!IS_SELECTOR_SYSTEM(CS_sig(sigcontext)))  /* 16-bit mode */
499     {
500         fs = SYSLEVEL_Win16CurrentTeb;
501     }
502 #ifdef __HAVE_VM86
503     else if ((void *)EIP_sig(sigcontext) == vm86_return)  /* vm86 mode */
504     {
505         /* fetch the saved %fs on the stack */
506         fs = *(unsigned int *)ESP_sig(sigcontext);
507         if (EAX_sig(sigcontext) == VM86_EAX) {
508             struct vm86plus_struct *vm86;
509             __set_fs(fs);
510             /* retrieve pointer to vm86plus struct that was stored in vm86_enter
511              * (but we could also get if from teb->vm86_ptr) */
512             vm86 = *(struct vm86plus_struct **)(ESP_sig(sigcontext) + sizeof(int));
513             /* get context from vm86 struct */
514             save_vm86_context( context, vm86 );
515             return;
516         }
517     }
518 #endif  /* __HAVE_VM86 */
519
520     __set_fs(fs);
521
522     context->Eax    = EAX_sig(sigcontext);
523     context->Ebx    = EBX_sig(sigcontext);
524     context->Ecx    = ECX_sig(sigcontext);
525     context->Edx    = EDX_sig(sigcontext);
526     context->Esi    = ESI_sig(sigcontext);
527     context->Edi    = EDI_sig(sigcontext);
528     context->Ebp    = EBP_sig(sigcontext);
529     context->EFlags = EFL_sig(sigcontext);
530     context->Eip    = EIP_sig(sigcontext);
531     context->Esp    = ESP_sig(sigcontext);
532     context->SegCs  = LOWORD(CS_sig(sigcontext));
533     context->SegDs  = LOWORD(DS_sig(sigcontext));
534     context->SegEs  = LOWORD(ES_sig(sigcontext));
535     context->SegSs  = LOWORD(SS_sig(sigcontext));
536 #ifdef GS_sig
537     context->SegGs  = LOWORD(GS_sig(sigcontext));
538 #else
539     context->SegGs  = __get_gs();
540 #endif
541 }
542
543
544 /***********************************************************************
545  *           restore_context
546  *
547  * Build a sigcontext from the register values.
548  */
549 static void restore_context( const CONTEXT *context, SIGCONTEXT *sigcontext )
550 {
551 #ifdef __HAVE_VM86
552     /* check if exception occurred in vm86 mode */
553     if ((void *)EIP_sig(sigcontext) == vm86_return &&
554         IS_SELECTOR_SYSTEM(CS_sig(sigcontext)) &&
555         EAX_sig(sigcontext) == VM86_EAX)
556     {
557         /* retrieve pointer to vm86plus struct that was stored in vm86_enter
558          * (but we could also get it from teb->vm86_ptr) */
559         struct vm86plus_struct *vm86 = *(struct vm86plus_struct **)(ESP_sig(sigcontext) + sizeof(int));
560         restore_vm86_context( context, vm86 );
561         return;
562     }
563 #endif /* __HAVE_VM86 */
564
565     EAX_sig(sigcontext) = context->Eax;
566     EBX_sig(sigcontext) = context->Ebx;
567     ECX_sig(sigcontext) = context->Ecx;
568     EDX_sig(sigcontext) = context->Edx;
569     ESI_sig(sigcontext) = context->Esi;
570     EDI_sig(sigcontext) = context->Edi;
571     EBP_sig(sigcontext) = context->Ebp;
572     EFL_sig(sigcontext) = context->EFlags;
573     EIP_sig(sigcontext) = context->Eip;
574     ESP_sig(sigcontext) = context->Esp;
575     CS_sig(sigcontext)  = context->SegCs;
576     DS_sig(sigcontext)  = context->SegDs;
577     ES_sig(sigcontext)  = context->SegEs;
578     SS_sig(sigcontext)  = context->SegSs;
579 #ifdef FS_sig
580     FS_sig(sigcontext)  = context->SegFs;
581 #else
582     __set_fs( context->SegFs );
583 #endif
584 #ifdef GS_sig
585     GS_sig(sigcontext)  = context->SegGs;
586 #else
587     __set_gs( context->SegGs );
588 #endif
589 }
590
591
592 /***********************************************************************
593  *           save_fpu
594  *
595  * Set the FPU context from a sigcontext. 
596  */
597 inline static void save_fpu( CONTEXT *context, const SIGCONTEXT *sigcontext )
598 {
599 #ifdef FPU_sig
600     if (FPU_sig(sigcontext))
601     {
602         context->FloatSave = *FPU_sig(sigcontext);
603         return;
604     }
605 #endif  /* FPU_sig */
606 #ifdef __GNUC__
607     __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
608 #endif  /* __GNUC__ */
609 }
610
611
612 /***********************************************************************
613  *           restore_fpu
614  *
615  * Restore the FPU context to a sigcontext. 
616  */
617 inline static void restore_fpu( CONTEXT *context, const SIGCONTEXT *sigcontext )
618 {
619     /* reset the current interrupt status */
620     context->FloatSave.StatusWord &= context->FloatSave.ControlWord | 0xffffff80;
621 #ifdef FPU_sig
622     if (FPU_sig(sigcontext))
623     {
624         *FPU_sig(sigcontext) = context->FloatSave;
625         return;
626     }
627 #endif  /* FPU_sig */
628 #ifdef __GNUC__
629     /* avoid nested exceptions */
630     __asm__ __volatile__( "frstor %0; fwait" : : "m" (context->FloatSave) );
631 #endif  /* __GNUC__ */
632 }
633
634
635 /**********************************************************************
636  *              get_fpu_code
637  *
638  * Get the FPU exception code from the FPU status.
639  */
640 static inline DWORD get_fpu_code( const CONTEXT *context )
641 {
642     DWORD status = context->FloatSave.StatusWord;
643
644     if (status & 0x01)  /* IE */
645     {
646         if (status & 0x40)  /* SF */
647             return EXCEPTION_FLT_STACK_CHECK;
648         else
649             return EXCEPTION_FLT_INVALID_OPERATION;
650     }
651     if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND;  /* DE flag */
652     if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO;    /* ZE flag */
653     if (status & 0x08) return EXCEPTION_FLT_OVERFLOW;          /* OE flag */
654     if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW;         /* UE flag */
655     if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT;    /* PE flag */
656     return EXCEPTION_FLT_INVALID_OPERATION;  /* generic error */
657 }
658
659
660 /***********************************************************************
661  *           SIGNAL_Unblock
662  *
663  * Unblock signals. Called from EXC_RtlRaiseException.
664  */
665 void SIGNAL_Unblock( void )
666 {
667     sigprocmask( SIG_UNBLOCK, &all_sigs, NULL );
668 }
669
670
671 /**********************************************************************
672  *              do_segv
673  *
674  * Implementation of SIGSEGV handler.
675  */
676 static void do_segv( CONTEXT *context, int trap_code, void *cr2, int err_code )
677 {
678     EXCEPTION_RECORD rec;
679     DWORD page_fault_code = EXCEPTION_ACCESS_VIOLATION;
680
681 #ifdef CR2_sig
682     /* we want the page-fault case to be fast */
683     if (trap_code == T_PAGEFLT)
684         if (!(page_fault_code = VIRTUAL_HandleFault( cr2 ))) return;
685 #endif
686
687     rec.ExceptionRecord  = NULL;
688     rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
689     rec.ExceptionAddress = (LPVOID)context->Eip;
690     rec.NumberParameters = 0;
691
692     switch(trap_code)
693     {
694     case T_OFLOW:   /* Overflow exception */
695         rec.ExceptionCode = EXCEPTION_INT_OVERFLOW;
696         break;
697     case T_BOUND:   /* Bound range exception */
698         rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
699         break;
700     case T_PRIVINFLT:   /* Invalid opcode exception */
701         rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
702         break;
703     case T_STKFLT:  /* Stack fault */
704         rec.ExceptionCode = EXCEPTION_STACK_OVERFLOW;
705         break;
706     case T_SEGNPFLT:  /* Segment not present exception */
707     case T_PROTFLT:   /* General protection fault */
708     case T_UNKNOWN:   /* Unknown fault code */
709         if (INSTR_EmulateInstruction( context )) return;
710         rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
711         break;
712     case T_PAGEFLT:  /* Page fault */
713 #ifdef CR2_sig
714         rec.NumberParameters = 2;
715         rec.ExceptionInformation[0] = (err_code & 2) != 0;
716         rec.ExceptionInformation[1] = (DWORD)cr2;
717 #endif /* CR2_sig */
718         rec.ExceptionCode = page_fault_code;
719         break;
720     case T_ALIGNFLT:  /* Alignment check exception */
721         /* FIXME: pass through exception handler first? */
722         if (context->EFlags & 0x00040000)
723         {
724             /* Disable AC flag, return */
725             context->EFlags &= ~0x00040000;
726             return;
727         }
728         rec.ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
729         break;
730     default:
731         ERR( "Got unexpected trap %d\n", trap_code );
732         /* fall through */
733     case T_NMI:       /* NMI interrupt */
734     case T_DNA:       /* Device not available exception */
735     case T_DOUBLEFLT: /* Double fault exception */
736     case T_TSSFLT:    /* Invalid TSS exception */
737     case T_RESERVED:  /* Unknown exception */
738     case T_MCHK:      /* Machine check exception */
739 #ifdef T_CACHEFLT
740     case T_CACHEFLT:  /* Cache flush exception */
741 #endif
742         rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
743         break;
744     }
745     EXC_RtlRaiseException( &rec, context );
746 }
747
748
749 /**********************************************************************
750  *              do_trap
751  *
752  * Implementation of SIGTRAP handler.
753  */
754 static void do_trap( CONTEXT *context, int trap_code )
755 {
756     EXCEPTION_RECORD rec;
757
758     rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
759     rec.ExceptionRecord  = NULL;
760     rec.ExceptionAddress = (LPVOID)context->Eip;
761     rec.NumberParameters = 0;
762
763     switch(trap_code)
764     {
765     case T_TRCTRAP:  /* Single-step exception */
766         rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
767         context->EFlags &= ~0x100;  /* clear single-step flag */
768         break;
769     case T_BPTFLT:   /* Breakpoint exception */
770         rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1;  /* back up over the int3 instruction */
771         /* fall through */
772     default:
773         rec.ExceptionCode = EXCEPTION_BREAKPOINT;
774         break;
775     }
776     EXC_RtlRaiseException( &rec, context );
777 }
778
779
780 /**********************************************************************
781  *              do_fpe
782  *
783  * Implementation of SIGFPE handler
784  */
785 static void do_fpe( CONTEXT *context, int trap_code )
786 {
787     EXCEPTION_RECORD rec;
788
789     switch(trap_code)
790     {
791     case T_DIVIDE:   /* Division by zero exception */
792         rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
793         break;
794     case T_FPOPFLT:   /* Coprocessor segment overrun */
795         rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
796         break;
797     case T_ARITHTRAP:  /* Floating point exception */
798     case T_UNKNOWN:    /* Unknown fault code */
799         rec.ExceptionCode = get_fpu_code( context );
800         break;
801     default:
802         ERR( "Got unexpected trap %d\n", trap_code );
803         rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
804         break;
805     }
806     rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
807     rec.ExceptionRecord  = NULL;
808     rec.ExceptionAddress = (LPVOID)context->Eip;
809     rec.NumberParameters = 0;
810     EXC_RtlRaiseException( &rec, context );
811 }
812
813
814 #ifdef __HAVE_VM86
815 /**********************************************************************
816  *              set_vm86_pend
817  *
818  * Handler for SIGUSR2, which we use to set the vm86 pending flag.
819  */
820 static void set_vm86_pend( CONTEXT *context )
821 {
822     EXCEPTION_RECORD rec;
823     TEB *teb = NtCurrentTeb();
824     struct vm86plus_struct *vm86 = (struct vm86plus_struct*)(teb->vm86_ptr);
825
826     rec.ExceptionCode           = EXCEPTION_VM86_STI;
827     rec.ExceptionFlags          = EXCEPTION_CONTINUABLE;
828     rec.ExceptionRecord         = NULL;
829     rec.NumberParameters        = 1;
830     rec.ExceptionInformation[0] = 0;
831
832     /* __wine_enter_vm86() merges the vm86_pending flag in safely */
833     teb->vm86_pending |= VIP_MASK;
834     /* see if we were in VM86 mode */
835     if (context->EFlags & 0x00020000)
836     {
837         /* seems so, also set flag in signal context */
838         if (context->EFlags & VIP_MASK) return;
839         context->EFlags |= VIP_MASK;
840         vm86->regs.eflags |= VIP_MASK; /* no exception recursion */
841         if (context->EFlags & VIF_MASK) {
842             /* VIF is set, throw exception */
843             teb->vm86_pending = 0;
844             teb->vm86_ptr = NULL;
845             rec.ExceptionAddress = (LPVOID)context->Eip;
846             EXC_RtlRaiseException( &rec, context );
847             teb->vm86_ptr = vm86;
848         }
849     }
850     else if (vm86)
851     {
852         /* not in VM86, but possibly setting up for it */
853         if (vm86->regs.eflags & VIP_MASK) return;
854         vm86->regs.eflags |= VIP_MASK;
855         if (((char*)context->Eip >= (char*)vm86_return) &&
856             ((char*)context->Eip <= (char*)vm86_return_end) &&
857             (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
858             /* exiting from VM86, can't throw */
859             return;
860         }
861         if (vm86->regs.eflags & VIF_MASK) {
862             /* VIF is set, throw exception */
863             CONTEXT vcontext;
864             teb->vm86_pending = 0;
865             teb->vm86_ptr = NULL;
866             save_vm86_context( &vcontext, vm86 );
867             rec.ExceptionAddress = (LPVOID)vcontext.Eip;
868             EXC_RtlRaiseException( &rec, &vcontext );
869             teb->vm86_ptr = vm86;
870             restore_vm86_context( &vcontext, vm86 );
871         }
872     }
873 }
874
875
876 /**********************************************************************
877  *              usr2_handler
878  *
879  * Handler for SIGUSR2.
880  * We use it to signal that the running __wine_enter_vm86() should
881  * immediately set VIP_MASK, causing pending events to be handled
882  * as early as possible.
883  */
884 static HANDLER_DEF(usr2_handler)
885 {
886     CONTEXT context;
887
888     save_context( &context, HANDLER_CONTEXT );
889     set_vm86_pend( &context );
890     restore_context( &context, HANDLER_CONTEXT );
891 }
892
893
894 /**********************************************************************
895  *              alrm_handler
896  *
897  * Handler for SIGALRM.
898  * Increases the alarm counter and sets the vm86 pending flag.
899  */
900 static HANDLER_DEF(alrm_handler)
901 {
902     CONTEXT context;
903
904     save_context( &context, HANDLER_CONTEXT );
905     NtCurrentTeb()->alarms++;
906     set_vm86_pend( &context );
907     restore_context( &context, HANDLER_CONTEXT );
908 }
909 #endif /* __HAVE_VM86 */
910
911
912 /**********************************************************************
913  *              segv_handler
914  *
915  * Handler for SIGSEGV and related errors.
916  */
917 static HANDLER_DEF(segv_handler)
918 {
919     CONTEXT context;
920     save_context( &context, HANDLER_CONTEXT );
921     do_segv( &context, get_trap_code(HANDLER_CONTEXT),
922              get_cr2_value(HANDLER_CONTEXT), get_error_code(HANDLER_CONTEXT) );
923     restore_context( &context, HANDLER_CONTEXT );
924 }
925
926
927 /**********************************************************************
928  *              trap_handler
929  *
930  * Handler for SIGTRAP.
931  */
932 static HANDLER_DEF(trap_handler)
933 {
934     CONTEXT context;
935     save_context( &context, HANDLER_CONTEXT );
936     do_trap( &context, get_trap_code(HANDLER_CONTEXT) );
937     restore_context( &context, HANDLER_CONTEXT );
938 }
939
940
941 /**********************************************************************
942  *              fpe_handler
943  *
944  * Handler for SIGFPE.
945  */
946 static HANDLER_DEF(fpe_handler)
947 {
948     CONTEXT context;
949     save_fpu( &context, HANDLER_CONTEXT );
950     save_context( &context, HANDLER_CONTEXT );
951     do_fpe( &context, get_trap_code(HANDLER_CONTEXT) );
952     restore_context( &context, HANDLER_CONTEXT );
953     restore_fpu( &context, HANDLER_CONTEXT );
954 }
955
956
957 /**********************************************************************
958  *              int_handler
959  *
960  * Handler for SIGINT.
961  */
962 static HANDLER_DEF(int_handler)
963 {
964     EXCEPTION_RECORD rec;
965     CONTEXT context;
966
967     save_context( &context, HANDLER_CONTEXT );
968     rec.ExceptionCode    = CONTROL_C_EXIT;
969     rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
970     rec.ExceptionRecord  = NULL;
971     rec.ExceptionAddress = (LPVOID)context.Eip;
972     rec.NumberParameters = 0;
973     EXC_RtlRaiseException( &rec, &context );
974     restore_context( &context, HANDLER_CONTEXT );
975 }
976
977
978 /***********************************************************************
979  *           set_handler
980  *
981  * Set a signal handler
982  */
983 static int set_handler( int sig, int have_sigaltstack, void (*func)() )
984 {
985     struct sigaction sig_act;
986
987 #ifdef linux
988     if (!have_sigaltstack && NtCurrentTeb()->signal_stack)
989     {
990         struct kernel_sigaction sig_act;
991         sig_act.ksa_handler = func;
992         sig_act.ksa_flags   = SA_RESTART;
993         sig_act.ksa_mask    = (1 << (SIGINT-1)) |
994                               (1 << (SIGALRM-1));
995         /* point to the top of the stack */
996         sig_act.ksa_restorer = (char *)NtCurrentTeb()->signal_stack + SIGNAL_STACK_SIZE;
997         return wine_sigaction( sig, &sig_act, NULL );
998     }
999 #endif  /* linux */
1000     sig_act.sa_handler = func;
1001     sigemptyset( &sig_act.sa_mask );
1002     sigaddset( &sig_act.sa_mask, SIGINT );
1003     sigaddset( &sig_act.sa_mask, SIGALRM );
1004
1005 #ifdef linux
1006     sig_act.sa_flags = SA_RESTART;
1007 #elif defined (__svr4__) || defined(_SCO_DS)
1008     sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
1009 #else
1010     sig_act.sa_flags = 0;
1011 #endif
1012
1013 #ifdef SA_ONSTACK
1014     if (have_sigaltstack) sig_act.sa_flags |= SA_ONSTACK;
1015 #endif
1016     return sigaction( sig, &sig_act, NULL );
1017 }
1018
1019
1020 /**********************************************************************
1021  *              SIGNAL_Init
1022  */
1023 BOOL SIGNAL_Init(void)
1024 {
1025     int have_sigaltstack = 0;
1026
1027 #ifdef HAVE_SIGALTSTACK
1028     struct sigaltstack ss;
1029     if ((ss.ss_sp = NtCurrentTeb()->signal_stack))
1030     {
1031         ss.ss_size  = SIGNAL_STACK_SIZE;
1032         ss.ss_flags = 0;
1033         if (!sigaltstack(&ss, NULL)) have_sigaltstack = 1;
1034 #ifdef linux
1035         /* sigaltstack may fail because the kernel is too old, or
1036            because glibc is brain-dead. In the latter case a
1037            direct system call should succeed. */
1038         else if (!wine_sigaltstack(&ss, NULL)) have_sigaltstack = 1;
1039 #endif  /* linux */
1040     }
1041 #endif  /* HAVE_SIGALTSTACK */
1042
1043     sigfillset( &all_sigs );
1044
1045     /* automatic child reaping to avoid zombies */
1046     signal( SIGCHLD, SIG_IGN );
1047
1048     if (set_handler( SIGINT,  have_sigaltstack, (void (*)())int_handler ) == -1) goto error;
1049     if (set_handler( SIGFPE,  have_sigaltstack, (void (*)())fpe_handler ) == -1) goto error;
1050     if (set_handler( SIGSEGV, have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1051     if (set_handler( SIGILL,  have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1052 #ifdef SIGBUS
1053     if (set_handler( SIGBUS,  have_sigaltstack, (void (*)())segv_handler ) == -1) goto error;
1054 #endif
1055 #ifdef SIGTRAP
1056     if (set_handler( SIGTRAP, have_sigaltstack, (void (*)())trap_handler ) == -1) goto error;
1057 #endif
1058
1059 #ifdef __HAVE_VM86
1060     if (set_handler( SIGALRM, have_sigaltstack, (void (*)())alrm_handler ) == -1) goto error;
1061     if (set_handler( SIGUSR2, have_sigaltstack, (void (*)())usr2_handler ) == -1) goto error;
1062 #endif
1063
1064     return TRUE;
1065
1066  error:
1067     perror("sigaction");
1068     return FALSE;
1069 }
1070
1071
1072 /**********************************************************************
1073  *              SIGNAL_Reset
1074  */
1075 void SIGNAL_Reset(void)
1076 {
1077     sigset_t block_set;
1078
1079     /* block the async signals */
1080     sigemptyset( &block_set );
1081     sigaddset( &block_set, SIGALRM );
1082     sigaddset( &block_set, SIGIO );
1083     sigaddset( &block_set, SIGHUP );
1084     sigaddset( &block_set, SIGUSR2 );
1085     sigprocmask( SIG_BLOCK, &block_set, NULL );
1086
1087     /* restore default handlers */
1088     signal( SIGINT, SIG_DFL );
1089     signal( SIGFPE, SIG_DFL );
1090     signal( SIGSEGV, SIG_DFL );
1091     signal( SIGILL, SIG_DFL );
1092 #ifdef SIGBUS
1093     signal( SIGBUS, SIG_DFL );
1094 #endif
1095 #ifdef SIGTRAP
1096     signal( SIGTRAP, SIG_DFL );
1097 #endif
1098 }
1099
1100
1101 #ifdef __HAVE_VM86
1102 /**********************************************************************
1103  *              __wine_enter_vm86
1104  *
1105  * Enter vm86 mode with the specified register context.
1106  */
1107 void __wine_enter_vm86( CONTEXT *context )
1108 {
1109     EXCEPTION_RECORD rec;
1110     TEB *teb = NtCurrentTeb();
1111     int res;
1112     struct vm86plus_struct vm86;
1113
1114     memset( &vm86, 0, sizeof(vm86) );
1115     for (;;)
1116     {
1117         restore_vm86_context( context, &vm86 );
1118         /* Linux doesn't preserve pending flag (VIP_MASK) on return,
1119          * so save it on entry, just in case */
1120         teb->vm86_pending |= (context->EFlags & VIP_MASK);
1121         /* Work around race conditions with signal handler
1122          * (avoiding sigprocmask for performance reasons) */
1123         teb->vm86_ptr = &vm86;
1124         vm86.regs.eflags |= teb->vm86_pending;
1125         /* Check for VIF|VIP here, since vm86_enter doesn't */
1126         if ((vm86.regs.eflags & (VIF_MASK|VIP_MASK)) == (VIF_MASK|VIP_MASK)) {
1127             teb->vm86_ptr = NULL;
1128             teb->vm86_pending = 0;
1129             context->EFlags |= VIP_MASK;
1130             rec.ExceptionCode = EXCEPTION_VM86_STI;
1131             rec.ExceptionInformation[0] = 0;
1132             goto cancel_vm86;
1133         }
1134
1135         do
1136         {
1137             res = vm86_enter( &teb->vm86_ptr ); /* uses and clears teb->vm86_ptr */
1138             if (res < 0)
1139             {
1140                 errno = -res;
1141                 return;
1142             }
1143         } while (VM86_TYPE(res) == VM86_SIGNAL);
1144
1145         save_vm86_context( context, &vm86 );
1146         context->EFlags |= teb->vm86_pending;
1147
1148         switch(VM86_TYPE(res))
1149         {
1150         case VM86_UNKNOWN: /* unhandled GP fault - IO-instruction or similar */
1151             do_segv( context, T_PROTFLT, 0, 0 );
1152             continue;
1153         case VM86_TRAP: /* return due to DOS-debugger request */
1154             do_trap( context, VM86_ARG(res) );
1155             continue;
1156         case VM86_INTx: /* int3/int x instruction (ARG = x) */
1157             rec.ExceptionCode = EXCEPTION_VM86_INTx;
1158             break;
1159         case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
1160             teb->vm86_pending = 0;
1161             rec.ExceptionCode = EXCEPTION_VM86_STI;
1162             break;
1163         case VM86_PICRETURN: /* return due to pending PIC request */
1164             rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
1165             break;
1166         default:
1167             ERR( "unhandled result from vm86 mode %x\n", res );
1168             continue;
1169         }
1170         rec.ExceptionInformation[0] = VM86_ARG(res);
1171 cancel_vm86:
1172         rec.ExceptionFlags          = EXCEPTION_CONTINUABLE;
1173         rec.ExceptionRecord         = NULL;
1174         rec.ExceptionAddress        = (LPVOID)context->Eip;
1175         rec.NumberParameters        = 1;
1176         EXC_RtlRaiseException( &rec, context );
1177     }
1178 }
1179
1180 #else /* __HAVE_VM86 */
1181 void __wine_enter_vm86( CONTEXT *context )
1182 {
1183     MESSAGE("vm86 mode not supported on this platform\n");
1184 }
1185 #endif /* __HAVE_VM86 */
1186
1187 /**********************************************************************
1188  *              DbgBreakPoint   (NTDLL.@)
1189  */
1190 __ASM_GLOBAL_FUNC( DbgBreakPoint, "int $3; ret");
1191
1192 /**********************************************************************
1193  *              DbgUserBreakPoint   (NTDLL.@)
1194  */
1195 __ASM_GLOBAL_FUNC( DbgUserBreakPoint, "int $3; ret");
1196
1197 #endif  /* __i386__ */