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