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