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