include: Add constants for CryptProtectMemory/CryptUnprotectMemory.
[wine.git] / dlls / ntdll / signal_i386.c
blob59dca6cfca08b587241c97a4412827c177e0618a
1 /*
2 * i386 signal handling routines
4 * Copyright 1999 Alexandre Julliard
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.
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.
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
21 #ifdef __i386__
23 #include "config.h"
24 #include "wine/port.h"
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 #ifdef HAVE_SYS_PARAM_H
36 # include <sys/param.h>
37 #endif
38 #ifdef HAVE_SYSCALL_H
39 # include <syscall.h>
40 #else
41 # ifdef HAVE_SYS_SYSCALL_H
42 # include <sys/syscall.h>
43 # endif
44 #endif
45 #ifdef HAVE_SYS_VM86_H
46 # include <sys/vm86.h>
47 #endif
48 #ifdef HAVE_SYS_SIGNAL_H
49 # include <sys/signal.h>
50 #endif
51 #ifdef HAVE_SYS_SYSCTL_H
52 # include <sys/sysctl.h>
53 #endif
54 #ifdef HAVE_SYS_UCONTEXT_H
55 # include <sys/ucontext.h>
56 #endif
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "windef.h"
61 #include "wine/library.h"
62 #include "ntdll_misc.h"
63 #include "wine/exception.h"
64 #include "wine/debug.h"
66 #ifdef HAVE_VALGRIND_MEMCHECK_H
67 #include <valgrind/memcheck.h>
68 #endif
70 #undef ERR /* Solaris needs to define this */
72 /* not defined for x86, so copy the x86_64 definition */
73 typedef struct DECLSPEC_ALIGN(16) _M128A
75 ULONGLONG Low;
76 LONGLONG High;
77 } M128A;
79 typedef struct
81 WORD ControlWord;
82 WORD StatusWord;
83 BYTE TagWord;
84 BYTE Reserved1;
85 WORD ErrorOpcode;
86 DWORD ErrorOffset;
87 WORD ErrorSelector;
88 WORD Reserved2;
89 DWORD DataOffset;
90 WORD DataSelector;
91 WORD Reserved3;
92 DWORD MxCsr;
93 DWORD MxCsr_Mask;
94 M128A FloatRegisters[8];
95 M128A XmmRegisters[16];
96 BYTE Reserved4[96];
97 } XMM_SAVE_AREA32;
99 /***********************************************************************
100 * signal context platform-specific definitions
103 #ifdef __linux__
105 #ifndef HAVE_SYS_UCONTEXT_H
107 enum
109 REG_GS, REG_FS, REG_ES, REG_DS, REG_EDI, REG_ESI, REG_EBP, REG_ESP,
110 REG_EBX, REG_EDX, REG_ECX, REG_EAX, REG_TRAPNO, REG_ERR, REG_EIP,
111 REG_CS, REG_EFL, REG_UESP, REG_SS, NGREG
114 typedef int greg_t;
115 typedef greg_t gregset_t[NGREG];
117 struct _libc_fpreg
119 unsigned short significand[4];
120 unsigned short exponent;
123 struct _libc_fpstate
125 unsigned long cw;
126 unsigned long sw;
127 unsigned long tag;
128 unsigned long ipoff;
129 unsigned long cssel;
130 unsigned long dataoff;
131 unsigned long datasel;
132 struct _libc_fpreg _st[8];
133 unsigned long status;
136 typedef struct _libc_fpstate* fpregset_t;
138 typedef struct
140 gregset_t gregs;
141 fpregset_t fpregs;
142 unsigned long oldmask;
143 unsigned long cr2;
144 } mcontext_t;
146 typedef struct ucontext
148 unsigned long uc_flags;
149 struct ucontext *uc_link;
150 stack_t uc_stack;
151 mcontext_t uc_mcontext;
152 sigset_t uc_sigmask;
153 } ucontext_t;
154 #endif /* HAVE_SYS_UCONTEXT_H */
156 #define EAX_sig(context) ((context)->uc_mcontext.gregs[REG_EAX])
157 #define EBX_sig(context) ((context)->uc_mcontext.gregs[REG_EBX])
158 #define ECX_sig(context) ((context)->uc_mcontext.gregs[REG_ECX])
159 #define EDX_sig(context) ((context)->uc_mcontext.gregs[REG_EDX])
160 #define ESI_sig(context) ((context)->uc_mcontext.gregs[REG_ESI])
161 #define EDI_sig(context) ((context)->uc_mcontext.gregs[REG_EDI])
162 #define EBP_sig(context) ((context)->uc_mcontext.gregs[REG_EBP])
163 #define ESP_sig(context) ((context)->uc_mcontext.gregs[REG_ESP])
165 #define CS_sig(context) ((context)->uc_mcontext.gregs[REG_CS])
166 #define DS_sig(context) ((context)->uc_mcontext.gregs[REG_DS])
167 #define ES_sig(context) ((context)->uc_mcontext.gregs[REG_ES])
168 #define SS_sig(context) ((context)->uc_mcontext.gregs[REG_SS])
169 #define FS_sig(context) ((context)->uc_mcontext.gregs[REG_FS])
170 #define GS_sig(context) ((context)->uc_mcontext.gregs[REG_GS])
172 #define EFL_sig(context) ((context)->uc_mcontext.gregs[REG_EFL])
173 #define EIP_sig(context) ((context)->uc_mcontext.gregs[REG_EIP])
174 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[REG_TRAPNO])
175 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[REG_ERR])
177 #define FPU_sig(context) ((FLOATING_SAVE_AREA*)((context)->uc_mcontext.fpregs))
178 #define FPUX_sig(context) (FPU_sig(context) && !((context)->uc_mcontext.fpregs->status >> 16) ? (XMM_SAVE_AREA32 *)(FPU_sig(context) + 1) : NULL)
180 #define VIF_FLAG 0x00080000
181 #define VIP_FLAG 0x00100000
183 int vm86_enter( void **vm86_ptr );
184 void vm86_return(void);
185 void vm86_return_end(void);
186 __ASM_GLOBAL_FUNC(vm86_enter,
187 "pushl %ebp\n\t"
188 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
189 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
190 "movl %esp,%ebp\n\t"
191 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
192 "pushl %ebx\n\t"
193 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
194 "movl $166,%eax\n\t" /*SYS_vm86*/
195 "movl 8(%ebp),%ecx\n\t" /* vm86_ptr */
196 "movl (%ecx),%ecx\n\t"
197 "movl $1,%ebx\n\t" /*VM86_ENTER*/
198 "pushl %ecx\n\t" /* put vm86plus_struct ptr somewhere we can find it */
199 "pushl %fs\n\t"
200 "pushl %gs\n\t"
201 "int $0x80\n"
202 ".globl " __ASM_NAME("vm86_return") "\n\t"
203 __ASM_FUNC("vm86_return") "\n"
204 __ASM_NAME("vm86_return") ":\n\t"
205 "popl %gs\n\t"
206 "popl %fs\n\t"
207 "popl %ecx\n\t"
208 "popl %ebx\n\t"
209 __ASM_CFI(".cfi_same_value %ebx\n\t")
210 "popl %ebp\n\t"
211 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
212 __ASM_CFI(".cfi_same_value %ebp\n\t")
213 "testl %eax,%eax\n\t"
214 "jl 0f\n\t"
215 "cmpb $0,%al\n\t" /* VM86_SIGNAL */
216 "je " __ASM_NAME("vm86_enter") "\n\t"
217 "0:\n\t"
218 "movl 4(%esp),%ecx\n\t" /* vm86_ptr */
219 "movl $0,(%ecx)\n\t"
220 ".globl " __ASM_NAME("vm86_return_end") "\n\t"
221 __ASM_FUNC("vm86_return_end") "\n"
222 __ASM_NAME("vm86_return_end") ":\n\t"
223 "ret" )
225 #ifdef HAVE_SYS_VM86_H
226 # define __HAVE_VM86
227 #endif
229 #ifdef __ANDROID__
230 /* custom signal restorer since we may have unmapped the one in vdso, and bionic doesn't check for that */
231 void rt_sigreturn(void);
232 __ASM_GLOBAL_FUNC( rt_sigreturn,
233 "movl $173,%eax\n\t" /* NR_rt_sigreturn */
234 "int $0x80" );
235 #endif
237 #elif defined (__BSDI__)
239 #include <machine/frame.h>
240 typedef struct trapframe ucontext_t;
242 #define EAX_sig(context) ((context)->tf_eax)
243 #define EBX_sig(context) ((context)->tf_ebx)
244 #define ECX_sig(context) ((context)->tf_ecx)
245 #define EDX_sig(context) ((context)->tf_edx)
246 #define ESI_sig(context) ((context)->tf_esi)
247 #define EDI_sig(context) ((context)->tf_edi)
248 #define EBP_sig(context) ((context)->tf_ebp)
250 #define CS_sig(context) ((context)->tf_cs)
251 #define DS_sig(context) ((context)->tf_ds)
252 #define ES_sig(context) ((context)->tf_es)
253 #define SS_sig(context) ((context)->tf_ss)
255 #define EFL_sig(context) ((context)->tf_eflags)
257 #define EIP_sig(context) (*((unsigned long*)&(context)->tf_eip))
258 #define ESP_sig(context) (*((unsigned long*)&(context)->tf_esp))
260 #define FPU_sig(context) NULL /* FIXME */
261 #define FPUX_sig(context) NULL /* FIXME */
263 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
265 #include <machine/trap.h>
267 #define EAX_sig(context) ((context)->uc_mcontext.mc_eax)
268 #define EBX_sig(context) ((context)->uc_mcontext.mc_ebx)
269 #define ECX_sig(context) ((context)->uc_mcontext.mc_ecx)
270 #define EDX_sig(context) ((context)->uc_mcontext.mc_edx)
271 #define ESI_sig(context) ((context)->uc_mcontext.mc_esi)
272 #define EDI_sig(context) ((context)->uc_mcontext.mc_edi)
273 #define EBP_sig(context) ((context)->uc_mcontext.mc_ebp)
275 #define CS_sig(context) ((context)->uc_mcontext.mc_cs)
276 #define DS_sig(context) ((context)->uc_mcontext.mc_ds)
277 #define ES_sig(context) ((context)->uc_mcontext.mc_es)
278 #define FS_sig(context) ((context)->uc_mcontext.mc_fs)
279 #define GS_sig(context) ((context)->uc_mcontext.mc_gs)
280 #define SS_sig(context) ((context)->uc_mcontext.mc_ss)
282 #define TRAP_sig(context) ((context)->uc_mcontext.mc_trapno)
283 #define ERROR_sig(context) ((context)->uc_mcontext.mc_err)
284 #define EFL_sig(context) ((context)->uc_mcontext.mc_eflags)
286 #define EIP_sig(context) ((context)->uc_mcontext.mc_eip)
287 #define ESP_sig(context) ((context)->uc_mcontext.mc_esp)
289 #define FPU_sig(context) NULL /* FIXME */
290 #define FPUX_sig(context) NULL /* FIXME */
292 #elif defined (__OpenBSD__)
294 #define EAX_sig(context) ((context)->sc_eax)
295 #define EBX_sig(context) ((context)->sc_ebx)
296 #define ECX_sig(context) ((context)->sc_ecx)
297 #define EDX_sig(context) ((context)->sc_edx)
298 #define ESI_sig(context) ((context)->sc_esi)
299 #define EDI_sig(context) ((context)->sc_edi)
300 #define EBP_sig(context) ((context)->sc_ebp)
302 #define CS_sig(context) ((context)->sc_cs)
303 #define DS_sig(context) ((context)->sc_ds)
304 #define ES_sig(context) ((context)->sc_es)
305 #define FS_sig(context) ((context)->sc_fs)
306 #define GS_sig(context) ((context)->sc_gs)
307 #define SS_sig(context) ((context)->sc_ss)
309 #define TRAP_sig(context) ((context)->sc_trapno)
310 #define ERROR_sig(context) ((context)->sc_err)
311 #define EFL_sig(context) ((context)->sc_eflags)
313 #define EIP_sig(context) ((context)->sc_eip)
314 #define ESP_sig(context) ((context)->sc_esp)
316 #define FPU_sig(context) NULL /* FIXME */
317 #define FPUX_sig(context) NULL /* FIXME */
319 #define T_MCHK T_MACHK
320 #define T_XMMFLT T_XFTRAP
322 #elif defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
324 #ifdef _SCO_DS
325 #include <sys/regset.h>
326 #define gregs regs
327 #endif
329 #define EAX_sig(context) ((context)->uc_mcontext.gregs[EAX])
330 #define EBX_sig(context) ((context)->uc_mcontext.gregs[EBX])
331 #define ECX_sig(context) ((context)->uc_mcontext.gregs[ECX])
332 #define EDX_sig(context) ((context)->uc_mcontext.gregs[EDX])
333 #define ESI_sig(context) ((context)->uc_mcontext.gregs[ESI])
334 #define EDI_sig(context) ((context)->uc_mcontext.gregs[EDI])
335 #define EBP_sig(context) ((context)->uc_mcontext.gregs[EBP])
337 #define CS_sig(context) ((context)->uc_mcontext.gregs[CS])
338 #define DS_sig(context) ((context)->uc_mcontext.gregs[DS])
339 #define ES_sig(context) ((context)->uc_mcontext.gregs[ES])
340 #define SS_sig(context) ((context)->uc_mcontext.gregs[SS])
342 #define FS_sig(context) ((context)->uc_mcontext.gregs[FS])
343 #define GS_sig(context) ((context)->uc_mcontext.gregs[GS])
345 #define EFL_sig(context) ((context)->uc_mcontext.gregs[EFL])
347 #define EIP_sig(context) ((context)->uc_mcontext.gregs[EIP])
348 #ifdef UESP
349 #define ESP_sig(context) ((context)->uc_mcontext.gregs[UESP])
350 #elif defined(R_ESP)
351 #define ESP_sig(context) ((context)->uc_mcontext.gregs[R_ESP])
352 #else
353 #define ESP_sig(context) ((context)->uc_mcontext.gregs[ESP])
354 #endif
355 #ifdef ERR
356 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[ERR])
357 #endif
358 #ifdef TRAPNO
359 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[TRAPNO])
360 #endif
362 #define FPU_sig(context) NULL /* FIXME */
363 #define FPUX_sig(context) NULL /* FIXME */
365 #elif defined (__APPLE__)
367 /* work around silly renaming of struct members in OS X 10.5 */
368 #if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32)
369 #define EAX_sig(context) ((context)->uc_mcontext->__ss.__eax)
370 #define EBX_sig(context) ((context)->uc_mcontext->__ss.__ebx)
371 #define ECX_sig(context) ((context)->uc_mcontext->__ss.__ecx)
372 #define EDX_sig(context) ((context)->uc_mcontext->__ss.__edx)
373 #define ESI_sig(context) ((context)->uc_mcontext->__ss.__esi)
374 #define EDI_sig(context) ((context)->uc_mcontext->__ss.__edi)
375 #define EBP_sig(context) ((context)->uc_mcontext->__ss.__ebp)
376 #define CS_sig(context) ((context)->uc_mcontext->__ss.__cs)
377 #define DS_sig(context) ((context)->uc_mcontext->__ss.__ds)
378 #define ES_sig(context) ((context)->uc_mcontext->__ss.__es)
379 #define FS_sig(context) ((context)->uc_mcontext->__ss.__fs)
380 #define GS_sig(context) ((context)->uc_mcontext->__ss.__gs)
381 #define SS_sig(context) ((context)->uc_mcontext->__ss.__ss)
382 #define EFL_sig(context) ((context)->uc_mcontext->__ss.__eflags)
383 #define EIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__eip))
384 #define ESP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__esp))
385 #define TRAP_sig(context) ((context)->uc_mcontext->__es.__trapno)
386 #define ERROR_sig(context) ((context)->uc_mcontext->__es.__err)
387 #define FPU_sig(context) NULL
388 #define FPUX_sig(context) ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->__fs.__fpu_fcw)
389 #else
390 #define EAX_sig(context) ((context)->uc_mcontext->ss.eax)
391 #define EBX_sig(context) ((context)->uc_mcontext->ss.ebx)
392 #define ECX_sig(context) ((context)->uc_mcontext->ss.ecx)
393 #define EDX_sig(context) ((context)->uc_mcontext->ss.edx)
394 #define ESI_sig(context) ((context)->uc_mcontext->ss.esi)
395 #define EDI_sig(context) ((context)->uc_mcontext->ss.edi)
396 #define EBP_sig(context) ((context)->uc_mcontext->ss.ebp)
397 #define CS_sig(context) ((context)->uc_mcontext->ss.cs)
398 #define DS_sig(context) ((context)->uc_mcontext->ss.ds)
399 #define ES_sig(context) ((context)->uc_mcontext->ss.es)
400 #define FS_sig(context) ((context)->uc_mcontext->ss.fs)
401 #define GS_sig(context) ((context)->uc_mcontext->ss.gs)
402 #define SS_sig(context) ((context)->uc_mcontext->ss.ss)
403 #define EFL_sig(context) ((context)->uc_mcontext->ss.eflags)
404 #define EIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->ss.eip))
405 #define ESP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->ss.esp))
406 #define TRAP_sig(context) ((context)->uc_mcontext->es.trapno)
407 #define ERROR_sig(context) ((context)->uc_mcontext->es.err)
408 #define FPU_sig(context) NULL
409 #define FPUX_sig(context) ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->fs.fpu_fcw)
410 #endif
412 #elif defined(__NetBSD__)
414 #define EAX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EAX])
415 #define EBX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EBX])
416 #define ECX_sig(context) ((context)->uc_mcontext.__gregs[_REG_ECX])
417 #define EDX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EDX])
418 #define ESI_sig(context) ((context)->uc_mcontext.__gregs[_REG_ESI])
419 #define EDI_sig(context) ((context)->uc_mcontext.__gregs[_REG_EDI])
420 #define EBP_sig(context) ((context)->uc_mcontext.__gregs[_REG_EBP])
421 #define ESP_sig(context) _UC_MACHINE_SP(context)
423 #define CS_sig(context) ((context)->uc_mcontext.__gregs[_REG_CS])
424 #define DS_sig(context) ((context)->uc_mcontext.__gregs[_REG_DS])
425 #define ES_sig(context) ((context)->uc_mcontext.__gregs[_REG_ES])
426 #define SS_sig(context) ((context)->uc_mcontext.__gregs[_REG_SS])
427 #define FS_sig(context) ((context)->uc_mcontext.__gregs[_REG_FS])
428 #define GS_sig(context) ((context)->uc_mcontext.__gregs[_REG_GS])
430 #define EFL_sig(context) ((context)->uc_mcontext.__gregs[_REG_EFL])
431 #define EIP_sig(context) _UC_MACHINE_PC(context)
432 #define TRAP_sig(context) ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
433 #define ERROR_sig(context) ((context)->uc_mcontext.__gregs[_REG_ERR])
435 #define FPU_sig(context) NULL
436 #define FPUX_sig(context) ((XMM_SAVE_AREA32 *)&((context)->uc_mcontext.__fpregs))
438 #define T_MCHK T_MCA
439 #define T_XMMFLT T_XMM
441 #elif defined(__GNU__)
443 #define EAX_sig(context) ((context)->uc_mcontext.gregs[REG_EAX])
444 #define EBX_sig(context) ((context)->uc_mcontext.gregs[REG_EBX])
445 #define ECX_sig(context) ((context)->uc_mcontext.gregs[REG_ECX])
446 #define EDX_sig(context) ((context)->uc_mcontext.gregs[REG_EDX])
447 #define ESI_sig(context) ((context)->uc_mcontext.gregs[REG_ESI])
448 #define EDI_sig(context) ((context)->uc_mcontext.gregs[REG_EDI])
449 #define EBP_sig(context) ((context)->uc_mcontext.gregs[REG_EBP])
450 #define ESP_sig(context) ((context)->uc_mcontext.gregs[REG_ESP])
452 #define CS_sig(context) ((context)->uc_mcontext.gregs[REG_CS])
453 #define DS_sig(context) ((context)->uc_mcontext.gregs[REG_DS])
454 #define ES_sig(context) ((context)->uc_mcontext.gregs[REG_ES])
455 #define SS_sig(context) ((context)->uc_mcontext.gregs[REG_SS])
456 #define FS_sig(context) ((context)->uc_mcontext.gregs[REG_FS])
457 #define GS_sig(context) ((context)->uc_mcontext.gregs[REG_GS])
459 #define EFL_sig(context) ((context)->uc_mcontext.gregs[REG_EFL])
460 #define EIP_sig(context) ((context)->uc_mcontext.gregs[REG_EIP])
461 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[REG_TRAPNO])
462 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[REG_ERR])
464 #define FPU_sig(context) ((FLOATING_SAVE_AREA *)&(context)->uc_mcontext.fpregs.fp_reg_set.fpchip_state)
465 #define FPUX_sig(context) NULL
467 #else
468 #error You must define the signal context functions for your platform
469 #endif /* linux */
471 WINE_DEFAULT_DEBUG_CHANNEL(seh);
473 typedef int (*wine_signal_handler)(unsigned int sig);
475 static const size_t teb_size = 4096; /* we reserve one page for the TEB */
476 static size_t signal_stack_mask;
477 static size_t signal_stack_size;
479 static wine_signal_handler handlers[256];
481 static BOOL fpux_support; /* whether the CPU supports extended fpu context */
483 extern void DECLSPEC_NORETURN __wine_restore_regs( const CONTEXT *context );
485 enum i386_trap_code
487 TRAP_x86_UNKNOWN = -1, /* Unknown fault (TRAP_sig not defined) */
488 #if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
489 TRAP_x86_DIVIDE = T_DIVIDE, /* Division by zero exception */
490 TRAP_x86_TRCTRAP = T_TRCTRAP, /* Single-step exception */
491 TRAP_x86_NMI = T_NMI, /* NMI interrupt */
492 TRAP_x86_BPTFLT = T_BPTFLT, /* Breakpoint exception */
493 TRAP_x86_OFLOW = T_OFLOW, /* Overflow exception */
494 TRAP_x86_BOUND = T_BOUND, /* Bound range exception */
495 TRAP_x86_PRIVINFLT = T_PRIVINFLT, /* Invalid opcode exception */
496 TRAP_x86_DNA = T_DNA, /* Device not available exception */
497 TRAP_x86_DOUBLEFLT = T_DOUBLEFLT, /* Double fault exception */
498 TRAP_x86_FPOPFLT = T_FPOPFLT, /* Coprocessor segment overrun */
499 TRAP_x86_TSSFLT = T_TSSFLT, /* Invalid TSS exception */
500 TRAP_x86_SEGNPFLT = T_SEGNPFLT, /* Segment not present exception */
501 TRAP_x86_STKFLT = T_STKFLT, /* Stack fault */
502 TRAP_x86_PROTFLT = T_PROTFLT, /* General protection fault */
503 TRAP_x86_PAGEFLT = T_PAGEFLT, /* Page fault */
504 TRAP_x86_ARITHTRAP = T_ARITHTRAP, /* Floating point exception */
505 TRAP_x86_ALIGNFLT = T_ALIGNFLT, /* Alignment check exception */
506 TRAP_x86_MCHK = T_MCHK, /* Machine check exception */
507 TRAP_x86_CACHEFLT = T_XMMFLT /* Cache flush exception */
508 #else
509 TRAP_x86_DIVIDE = 0, /* Division by zero exception */
510 TRAP_x86_TRCTRAP = 1, /* Single-step exception */
511 TRAP_x86_NMI = 2, /* NMI interrupt */
512 TRAP_x86_BPTFLT = 3, /* Breakpoint exception */
513 TRAP_x86_OFLOW = 4, /* Overflow exception */
514 TRAP_x86_BOUND = 5, /* Bound range exception */
515 TRAP_x86_PRIVINFLT = 6, /* Invalid opcode exception */
516 TRAP_x86_DNA = 7, /* Device not available exception */
517 TRAP_x86_DOUBLEFLT = 8, /* Double fault exception */
518 TRAP_x86_FPOPFLT = 9, /* Coprocessor segment overrun */
519 TRAP_x86_TSSFLT = 10, /* Invalid TSS exception */
520 TRAP_x86_SEGNPFLT = 11, /* Segment not present exception */
521 TRAP_x86_STKFLT = 12, /* Stack fault */
522 TRAP_x86_PROTFLT = 13, /* General protection fault */
523 TRAP_x86_PAGEFLT = 14, /* Page fault */
524 TRAP_x86_ARITHTRAP = 16, /* Floating point exception */
525 TRAP_x86_ALIGNFLT = 17, /* Alignment check exception */
526 TRAP_x86_MCHK = 18, /* Machine check exception */
527 TRAP_x86_CACHEFLT = 19 /* SIMD exception (via SIGFPE) if CPU is SSE capable
528 otherwise Cache flush exception (via SIGSEV) */
529 #endif
532 /* Exception record for handling exceptions happening inside exception handlers */
533 typedef struct
535 EXCEPTION_REGISTRATION_RECORD frame;
536 EXCEPTION_REGISTRATION_RECORD *prevFrame;
537 } EXC_NESTED_FRAME;
539 extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
540 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
541 PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler );
543 /***********************************************************************
544 * dispatch_signal
546 static inline int dispatch_signal(unsigned int sig)
548 if (handlers[sig] == NULL) return 0;
549 return handlers[sig](sig);
553 /***********************************************************************
554 * get_trap_code
556 * Get the trap code for a signal.
558 static inline enum i386_trap_code get_trap_code( const ucontext_t *sigcontext )
560 #ifdef TRAP_sig
561 return TRAP_sig(sigcontext);
562 #else
563 return TRAP_x86_UNKNOWN; /* unknown trap code */
564 #endif
567 /***********************************************************************
568 * get_error_code
570 * Get the error code for a signal.
572 static inline WORD get_error_code( const ucontext_t *sigcontext )
574 #ifdef ERROR_sig
575 return ERROR_sig(sigcontext);
576 #else
577 return 0;
578 #endif
581 /***********************************************************************
582 * get_signal_stack
584 * Get the base of the signal stack for the current thread.
586 static inline void *get_signal_stack(void)
588 return (char *)NtCurrentTeb() + 4096;
592 /***********************************************************************
593 * get_current_teb
595 * Get the current teb based on the stack pointer.
597 static inline TEB *get_current_teb(void)
599 unsigned long esp;
600 __asm__("movl %%esp,%0" : "=g" (esp) );
601 return (TEB *)(esp & ~signal_stack_mask);
605 /*******************************************************************
606 * is_valid_frame
608 static inline BOOL is_valid_frame( void *frame )
610 if ((ULONG_PTR)frame & 3) return FALSE;
611 return (frame >= NtCurrentTeb()->Tib.StackLimit &&
612 (void **)frame < (void **)NtCurrentTeb()->Tib.StackBase - 1);
615 /*******************************************************************
616 * raise_handler
618 * Handler for exceptions happening inside a handler.
620 static DWORD raise_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
621 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
623 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
624 return ExceptionContinueSearch;
625 /* We shouldn't get here so we store faulty frame in dispatcher */
626 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
627 return ExceptionNestedException;
631 /*******************************************************************
632 * unwind_handler
634 * Handler for exceptions happening inside an unwind handler.
636 static DWORD unwind_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
637 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
639 if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
640 return ExceptionContinueSearch;
641 /* We shouldn't get here so we store faulty frame in dispatcher */
642 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
643 return ExceptionCollidedUnwind;
647 /**********************************************************************
648 * call_stack_handlers
650 * Call the stack handlers chain.
652 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
654 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
655 DWORD res;
657 frame = NtCurrentTeb()->Tib.ExceptionList;
658 nested_frame = NULL;
659 while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
661 /* Check frame address */
662 if (!is_valid_frame( frame ))
664 rec->ExceptionFlags |= EH_STACK_INVALID;
665 break;
668 /* Call handler */
669 TRACE( "calling handler at %p code=%x flags=%x\n",
670 frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
671 res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, raise_handler );
672 TRACE( "handler at %p returned %x\n", frame->Handler, res );
674 if (frame == nested_frame)
676 /* no longer nested */
677 nested_frame = NULL;
678 rec->ExceptionFlags &= ~EH_NESTED_CALL;
681 switch(res)
683 case ExceptionContinueExecution:
684 if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
685 return STATUS_NONCONTINUABLE_EXCEPTION;
686 case ExceptionContinueSearch:
687 break;
688 case ExceptionNestedException:
689 if (nested_frame < dispatch) nested_frame = dispatch;
690 rec->ExceptionFlags |= EH_NESTED_CALL;
691 break;
692 default:
693 return STATUS_INVALID_DISPOSITION;
695 frame = frame->Prev;
697 return STATUS_UNHANDLED_EXCEPTION;
701 /*******************************************************************
702 * raise_exception
704 * Implementation of NtRaiseException.
706 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
708 NTSTATUS status;
710 if (first_chance)
712 DWORD c;
714 TRACE( "code=%x flags=%x addr=%p ip=%08x tid=%04x\n",
715 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
716 context->Eip, GetCurrentThreadId() );
717 for (c = 0; c < rec->NumberParameters; c++)
718 TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
719 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
721 if (rec->ExceptionInformation[1] >> 16)
722 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
723 rec->ExceptionAddress,
724 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
725 else
726 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
727 rec->ExceptionAddress,
728 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
730 else
732 TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
733 context->Eax, context->Ebx, context->Ecx,
734 context->Edx, context->Esi, context->Edi );
735 TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
736 context->Ebp, context->Esp, context->SegCs, context->SegDs,
737 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
739 status = send_debug_event( rec, TRUE, context );
740 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
741 return STATUS_SUCCESS;
743 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
744 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
746 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
747 return STATUS_SUCCESS;
749 if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
750 return status;
753 /* last chance exception */
755 status = send_debug_event( rec, FALSE, context );
756 if (status != DBG_CONTINUE)
758 if (rec->ExceptionFlags & EH_STACK_INVALID)
759 WINE_ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
760 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
761 WINE_ERR("Process attempted to continue execution after noncontinuable exception.\n");
762 else
763 WINE_ERR("Unhandled exception code %x flags %x addr %p\n",
764 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
765 NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
767 return STATUS_SUCCESS;
771 #ifdef __HAVE_VM86
772 /***********************************************************************
773 * save_vm86_context
775 * Set the register values from a vm86 structure.
777 static void save_vm86_context( CONTEXT *context, const struct vm86plus_struct *vm86 )
779 context->ContextFlags = CONTEXT_FULL;
780 context->Eax = vm86->regs.eax;
781 context->Ebx = vm86->regs.ebx;
782 context->Ecx = vm86->regs.ecx;
783 context->Edx = vm86->regs.edx;
784 context->Esi = vm86->regs.esi;
785 context->Edi = vm86->regs.edi;
786 context->Esp = vm86->regs.esp;
787 context->Ebp = vm86->regs.ebp;
788 context->Eip = vm86->regs.eip;
789 context->SegCs = vm86->regs.cs;
790 context->SegDs = vm86->regs.ds;
791 context->SegEs = vm86->regs.es;
792 context->SegFs = vm86->regs.fs;
793 context->SegGs = vm86->regs.gs;
794 context->SegSs = vm86->regs.ss;
795 context->EFlags = vm86->regs.eflags;
799 /***********************************************************************
800 * restore_vm86_context
802 * Build a vm86 structure from the register values.
804 static void restore_vm86_context( const CONTEXT *context, struct vm86plus_struct *vm86 )
806 vm86->regs.eax = context->Eax;
807 vm86->regs.ebx = context->Ebx;
808 vm86->regs.ecx = context->Ecx;
809 vm86->regs.edx = context->Edx;
810 vm86->regs.esi = context->Esi;
811 vm86->regs.edi = context->Edi;
812 vm86->regs.esp = context->Esp;
813 vm86->regs.ebp = context->Ebp;
814 vm86->regs.eip = context->Eip;
815 vm86->regs.cs = context->SegCs;
816 vm86->regs.ds = context->SegDs;
817 vm86->regs.es = context->SegEs;
818 vm86->regs.fs = context->SegFs;
819 vm86->regs.gs = context->SegGs;
820 vm86->regs.ss = context->SegSs;
821 vm86->regs.eflags = context->EFlags;
825 /**********************************************************************
826 * merge_vm86_pending_flags
828 * Merges TEB.vm86_ptr and TEB.vm86_pending VIP flags and
829 * raises exception if there are pending events and VIF flag
830 * has been turned on.
832 * Called from __wine_enter_vm86 because vm86_enter
833 * doesn't check for pending events.
835 * Called from raise_vm86_sti_exception to check for
836 * pending events in a signal safe way.
838 static void merge_vm86_pending_flags( EXCEPTION_RECORD *rec )
840 BOOL check_pending = TRUE;
841 struct vm86plus_struct *vm86 =
842 (struct vm86plus_struct*)(ntdll_get_thread_data()->vm86_ptr);
845 * In order to prevent a race when SIGUSR2 occurs while
846 * we are returning from exception handler, pending events
847 * will be rechecked after each raised exception.
849 while (check_pending && get_vm86_teb_info()->vm86_pending)
851 check_pending = FALSE;
852 ntdll_get_thread_data()->vm86_ptr = NULL;
855 * If VIF is set, throw exception.
856 * Note that SIGUSR2 may turn VIF flag off so
857 * VIF check must occur only when TEB.vm86_ptr is NULL.
859 if (vm86->regs.eflags & VIF_FLAG)
861 CONTEXT vcontext;
862 save_vm86_context( &vcontext, vm86 );
864 rec->ExceptionCode = EXCEPTION_VM86_STI;
865 rec->ExceptionFlags = EXCEPTION_CONTINUABLE;
866 rec->ExceptionRecord = NULL;
867 rec->NumberParameters = 0;
868 rec->ExceptionAddress = (LPVOID)vcontext.Eip;
870 vcontext.EFlags &= ~VIP_FLAG;
871 get_vm86_teb_info()->vm86_pending = 0;
872 raise_exception( rec, &vcontext, TRUE );
874 restore_vm86_context( &vcontext, vm86 );
875 check_pending = TRUE;
878 ntdll_get_thread_data()->vm86_ptr = vm86;
882 * Merge VIP flags in a signal safe way. This requires
883 * that the following operation compiles into atomic
884 * instruction.
886 vm86->regs.eflags |= get_vm86_teb_info()->vm86_pending;
888 #endif /* __HAVE_VM86 */
891 #ifdef __sun
893 /* We have to workaround two Solaris breakages:
894 * - Solaris doesn't restore %ds and %es before calling the signal handler so exceptions in 16-bit
895 * code crash badly.
896 * - Solaris inserts a libc trampoline to call our handler, but the trampoline expects that registers
897 * are setup correctly. So we need to insert our own trampoline below the libc trampoline to set %gs.
900 extern int sigaction_syscall( int sig, const struct sigaction *new, struct sigaction *old );
901 __ASM_GLOBAL_FUNC( sigaction_syscall,
902 "movl $0x62,%eax\n\t"
903 "int $0x91\n\t"
904 "ret" )
906 /* assume the same libc handler is used for all signals */
907 static void (*libc_sigacthandler)( int signal, siginfo_t *siginfo, void *context );
909 static void wine_sigacthandler( int signal, siginfo_t *siginfo, void *sigcontext )
911 struct ntdll_thread_data *thread_data;
913 __asm__ __volatile__("mov %ss,%ax; mov %ax,%ds; mov %ax,%es");
915 thread_data = (struct ntdll_thread_data *)get_current_teb()->SpareBytes1;
916 wine_set_fs( thread_data->fs );
917 wine_set_gs( thread_data->gs );
919 libc_sigacthandler( signal, siginfo, sigcontext );
922 static int solaris_sigaction( int sig, const struct sigaction *new, struct sigaction *old )
924 struct sigaction real_act;
926 if (sigaction( sig, new, old ) == -1) return -1;
928 /* retrieve the real handler and flags with a direct syscall */
929 sigaction_syscall( sig, NULL, &real_act );
930 libc_sigacthandler = real_act.sa_sigaction;
931 real_act.sa_sigaction = wine_sigacthandler;
932 sigaction_syscall( sig, &real_act, NULL );
933 return 0;
935 #define sigaction(sig,new,old) solaris_sigaction(sig,new,old)
937 #endif
939 typedef void (WINAPI *raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
941 extern void clear_alignment_flag(void);
942 __ASM_GLOBAL_FUNC( clear_alignment_flag,
943 "pushfl\n\t"
944 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
945 "andl $~0x40000,(%esp)\n\t"
946 "popfl\n\t"
947 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
948 "ret" )
951 /***********************************************************************
952 * init_handler
954 * Handler initialization when the full context is not needed.
955 * Return the stack pointer to use for pushing the exception data.
957 static inline void *init_handler( const ucontext_t *sigcontext, WORD *fs, WORD *gs )
959 TEB *teb = get_current_teb();
961 clear_alignment_flag();
963 /* get %fs and %gs at time of the fault */
964 #ifdef FS_sig
965 *fs = LOWORD(FS_sig(sigcontext));
966 #else
967 *fs = wine_get_fs();
968 #endif
969 #ifdef GS_sig
970 *gs = LOWORD(GS_sig(sigcontext));
971 #else
972 *gs = wine_get_gs();
973 #endif
975 #ifndef __sun /* see above for Solaris handling */
977 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
978 wine_set_fs( thread_data->fs );
979 wine_set_gs( thread_data->gs );
981 #endif
983 if (!wine_ldt_is_system(CS_sig(sigcontext)) ||
984 !wine_ldt_is_system(SS_sig(sigcontext))) /* 16-bit mode */
987 * Win16 or DOS protected mode. Note that during switch
988 * from 16-bit mode to linear mode, CS may be set to system
989 * segment before FS is restored. Fortunately, in this case
990 * SS is still non-system segment. This is why both CS and SS
991 * are checked.
993 return teb->WOW32Reserved;
995 return (void *)(ESP_sig(sigcontext) & ~3);
999 /***********************************************************************
1000 * save_fpu
1002 * Save the thread FPU context.
1004 static inline void save_fpu( CONTEXT *context )
1006 #ifdef __GNUC__
1007 context->ContextFlags |= CONTEXT_FLOATING_POINT;
1008 __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
1009 #endif
1013 /***********************************************************************
1014 * restore_fpu
1016 * Restore the FPU context to a sigcontext.
1018 static inline void restore_fpu( const CONTEXT *context )
1020 FLOATING_SAVE_AREA float_status = context->FloatSave;
1021 /* reset the current interrupt status */
1022 float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
1023 #ifdef __GNUC__
1024 __asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
1025 #endif /* __GNUC__ */
1029 /***********************************************************************
1030 * restore_fpux
1032 * Restore the FPU extended context to a sigcontext.
1034 static inline void restore_fpux( const CONTEXT *context )
1036 #ifdef __GNUC__
1037 /* we have to enforce alignment by hand */
1038 char buffer[sizeof(XMM_SAVE_AREA32) + 16];
1039 XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);
1041 memcpy( state, context->ExtendedRegisters, sizeof(*state) );
1042 /* reset the current interrupt status */
1043 state->StatusWord &= state->ControlWord | 0xff80;
1044 __asm__ __volatile__( "fxrstor %0" : : "m" (*state) );
1045 #endif
1049 /***********************************************************************
1050 * fpux_to_fpu
1052 * Build a standard FPU context from an extended one.
1054 static void fpux_to_fpu( FLOATING_SAVE_AREA *fpu, const XMM_SAVE_AREA32 *fpux )
1056 unsigned int i, tag, stack_top;
1058 fpu->ControlWord = fpux->ControlWord | 0xffff0000;
1059 fpu->StatusWord = fpux->StatusWord | 0xffff0000;
1060 fpu->ErrorOffset = fpux->ErrorOffset;
1061 fpu->ErrorSelector = fpux->ErrorSelector | (fpux->ErrorOpcode << 16);
1062 fpu->DataOffset = fpux->DataOffset;
1063 fpu->DataSelector = fpux->DataSelector;
1064 fpu->Cr0NpxState = fpux->StatusWord | 0xffff0000;
1066 stack_top = (fpux->StatusWord >> 11) & 7;
1067 fpu->TagWord = 0xffff0000;
1068 for (i = 0; i < 8; i++)
1070 memcpy( &fpu->RegisterArea[10 * i], &fpux->FloatRegisters[i], 10 );
1071 if (!(fpux->TagWord & (1 << i))) tag = 3; /* empty */
1072 else
1074 const M128A *reg = &fpux->FloatRegisters[(i - stack_top) & 7];
1075 if ((reg->High & 0x7fff) == 0x7fff) /* exponent all ones */
1077 tag = 2; /* special */
1079 else if (!(reg->High & 0x7fff)) /* exponent all zeroes */
1081 if (reg->Low) tag = 2; /* special */
1082 else tag = 1; /* zero */
1084 else
1086 if (reg->Low >> 63) tag = 0; /* valid */
1087 else tag = 2; /* special */
1090 fpu->TagWord |= tag << (2 * i);
1095 /***********************************************************************
1096 * save_context
1098 * Build a context structure from the signal info.
1100 static inline void save_context( CONTEXT *context, const ucontext_t *sigcontext, WORD fs, WORD gs )
1102 struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1103 FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
1104 XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1106 memset(context, 0, sizeof(*context));
1107 context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
1108 context->Eax = EAX_sig(sigcontext);
1109 context->Ebx = EBX_sig(sigcontext);
1110 context->Ecx = ECX_sig(sigcontext);
1111 context->Edx = EDX_sig(sigcontext);
1112 context->Esi = ESI_sig(sigcontext);
1113 context->Edi = EDI_sig(sigcontext);
1114 context->Ebp = EBP_sig(sigcontext);
1115 context->EFlags = EFL_sig(sigcontext);
1116 context->Eip = EIP_sig(sigcontext);
1117 context->Esp = ESP_sig(sigcontext);
1118 context->SegCs = LOWORD(CS_sig(sigcontext));
1119 context->SegDs = LOWORD(DS_sig(sigcontext));
1120 context->SegEs = LOWORD(ES_sig(sigcontext));
1121 context->SegFs = fs;
1122 context->SegGs = gs;
1123 context->SegSs = LOWORD(SS_sig(sigcontext));
1124 context->Dr0 = regs->dr0;
1125 context->Dr1 = regs->dr1;
1126 context->Dr2 = regs->dr2;
1127 context->Dr3 = regs->dr3;
1128 context->Dr6 = regs->dr6;
1129 context->Dr7 = regs->dr7;
1131 if (fpu)
1133 context->ContextFlags |= CONTEXT_FLOATING_POINT;
1134 context->FloatSave = *fpu;
1136 if (fpux)
1138 context->ContextFlags |= CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
1139 memcpy( context->ExtendedRegisters, fpux, sizeof(*fpux) );
1140 fpux_support = TRUE;
1141 if (!fpu) fpux_to_fpu( &context->FloatSave, fpux );
1143 if (!fpu && !fpux) save_fpu( context );
1147 /***********************************************************************
1148 * restore_context
1150 * Restore the signal info from the context.
1152 static inline void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1154 struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1155 FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
1156 XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1158 regs->dr0 = context->Dr0;
1159 regs->dr1 = context->Dr1;
1160 regs->dr2 = context->Dr2;
1161 regs->dr3 = context->Dr3;
1162 regs->dr6 = context->Dr6;
1163 regs->dr7 = context->Dr7;
1164 EAX_sig(sigcontext) = context->Eax;
1165 EBX_sig(sigcontext) = context->Ebx;
1166 ECX_sig(sigcontext) = context->Ecx;
1167 EDX_sig(sigcontext) = context->Edx;
1168 ESI_sig(sigcontext) = context->Esi;
1169 EDI_sig(sigcontext) = context->Edi;
1170 EBP_sig(sigcontext) = context->Ebp;
1171 EFL_sig(sigcontext) = context->EFlags;
1172 EIP_sig(sigcontext) = context->Eip;
1173 ESP_sig(sigcontext) = context->Esp;
1174 CS_sig(sigcontext) = context->SegCs;
1175 DS_sig(sigcontext) = context->SegDs;
1176 ES_sig(sigcontext) = context->SegEs;
1177 SS_sig(sigcontext) = context->SegSs;
1178 #ifdef GS_sig
1179 GS_sig(sigcontext) = context->SegGs;
1180 #else
1181 wine_set_gs( context->SegGs );
1182 #endif
1183 #ifdef FS_sig
1184 FS_sig(sigcontext) = context->SegFs;
1185 #else
1186 wine_set_fs( context->SegFs );
1187 #endif
1189 if (fpu) *fpu = context->FloatSave;
1190 if (fpux) memcpy( fpux, context->ExtendedRegisters, sizeof(*fpux) );
1191 if (!fpu && !fpux) restore_fpu( context );
1195 /***********************************************************************
1196 * RtlCaptureContext (NTDLL.@)
1198 __ASM_STDCALL_FUNC( RtlCaptureContext, 4,
1199 "pushl %eax\n\t"
1200 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1201 "movl 8(%esp),%eax\n\t" /* context */
1202 "movl $0x10007,(%eax)\n\t" /* context->ContextFlags */
1203 "movw %gs,0x8c(%eax)\n\t" /* context->SegGs */
1204 "movw %fs,0x90(%eax)\n\t" /* context->SegFs */
1205 "movw %es,0x94(%eax)\n\t" /* context->SegEs */
1206 "movw %ds,0x98(%eax)\n\t" /* context->SegDs */
1207 "movl %edi,0x9c(%eax)\n\t" /* context->Edi */
1208 "movl %esi,0xa0(%eax)\n\t" /* context->Esi */
1209 "movl %ebx,0xa4(%eax)\n\t" /* context->Ebx */
1210 "movl %edx,0xa8(%eax)\n\t" /* context->Edx */
1211 "movl %ecx,0xac(%eax)\n\t" /* context->Ecx */
1212 "movl %ebp,0xb4(%eax)\n\t" /* context->Ebp */
1213 "movl 4(%esp),%edx\n\t"
1214 "movl %edx,0xb8(%eax)\n\t" /* context->Eip */
1215 "movw %cs,0xbc(%eax)\n\t" /* context->SegCs */
1216 "pushfl\n\t"
1217 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1218 "popl 0xc0(%eax)\n\t" /* context->EFlags */
1219 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
1220 "leal 8(%esp),%edx\n\t"
1221 "movl %edx,0xc4(%eax)\n\t" /* context->Esp */
1222 "movw %ss,0xc8(%eax)\n\t" /* context->SegSs */
1223 "popl 0xb0(%eax)\n\t" /* context->Eax */
1224 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
1225 "ret $4" )
1228 /***********************************************************************
1229 * set_cpu_context
1231 * Set the new CPU context. Used by NtSetContextThread.
1233 void set_cpu_context( const CONTEXT *context )
1235 DWORD flags = context->ContextFlags & ~CONTEXT_i386;
1237 if ((flags & CONTEXT_EXTENDED_REGISTERS) && fpux_support) restore_fpux( context );
1238 else if (flags & CONTEXT_FLOATING_POINT) restore_fpu( context );
1240 if (flags & CONTEXT_DEBUG_REGISTERS)
1242 ntdll_get_thread_data()->dr0 = context->Dr0;
1243 ntdll_get_thread_data()->dr1 = context->Dr1;
1244 ntdll_get_thread_data()->dr2 = context->Dr2;
1245 ntdll_get_thread_data()->dr3 = context->Dr3;
1246 ntdll_get_thread_data()->dr6 = context->Dr6;
1247 ntdll_get_thread_data()->dr7 = context->Dr7;
1249 if (flags & CONTEXT_FULL)
1251 if (!(flags & CONTEXT_CONTROL))
1252 FIXME( "setting partial context (%x) not supported\n", flags );
1253 else if (flags & CONTEXT_SEGMENTS)
1254 __wine_restore_regs( context );
1255 else
1257 CONTEXT newcontext = *context;
1258 newcontext.SegDs = wine_get_ds();
1259 newcontext.SegEs = wine_get_es();
1260 newcontext.SegFs = wine_get_fs();
1261 newcontext.SegGs = wine_get_gs();
1262 __wine_restore_regs( &newcontext );
1268 /***********************************************************************
1269 * set_debug_registers
1271 static void set_debug_registers( const CONTEXT *context )
1273 DWORD flags = context->ContextFlags & ~CONTEXT_i386;
1274 context_t server_context;
1276 if (!(flags & CONTEXT_DEBUG_REGISTERS)) return;
1277 if (ntdll_get_thread_data()->dr0 == context->Dr0 &&
1278 ntdll_get_thread_data()->dr1 == context->Dr1 &&
1279 ntdll_get_thread_data()->dr2 == context->Dr2 &&
1280 ntdll_get_thread_data()->dr3 == context->Dr3 &&
1281 ntdll_get_thread_data()->dr6 == context->Dr6 &&
1282 ntdll_get_thread_data()->dr7 == context->Dr7) return;
1284 context_to_server( &server_context, context );
1286 SERVER_START_REQ( set_thread_context )
1288 req->handle = wine_server_obj_handle( GetCurrentThread() );
1289 req->suspend = 0;
1290 wine_server_add_data( req, &server_context, sizeof(server_context) );
1291 wine_server_call( req );
1293 SERVER_END_REQ;
1297 /***********************************************************************
1298 * copy_context
1300 * Copy a register context according to the flags.
1302 void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
1304 flags &= ~CONTEXT_i386; /* get rid of CPU id */
1305 if (flags & CONTEXT_INTEGER)
1307 to->Eax = from->Eax;
1308 to->Ebx = from->Ebx;
1309 to->Ecx = from->Ecx;
1310 to->Edx = from->Edx;
1311 to->Esi = from->Esi;
1312 to->Edi = from->Edi;
1314 if (flags & CONTEXT_CONTROL)
1316 to->Ebp = from->Ebp;
1317 to->Esp = from->Esp;
1318 to->Eip = from->Eip;
1319 to->SegCs = from->SegCs;
1320 to->SegSs = from->SegSs;
1321 to->EFlags = from->EFlags;
1323 if (flags & CONTEXT_SEGMENTS)
1325 to->SegDs = from->SegDs;
1326 to->SegEs = from->SegEs;
1327 to->SegFs = from->SegFs;
1328 to->SegGs = from->SegGs;
1330 if (flags & CONTEXT_DEBUG_REGISTERS)
1332 to->Dr0 = from->Dr0;
1333 to->Dr1 = from->Dr1;
1334 to->Dr2 = from->Dr2;
1335 to->Dr3 = from->Dr3;
1336 to->Dr6 = from->Dr6;
1337 to->Dr7 = from->Dr7;
1339 if (flags & CONTEXT_FLOATING_POINT)
1341 to->FloatSave = from->FloatSave;
1343 if (flags & CONTEXT_EXTENDED_REGISTERS)
1345 memcpy( to->ExtendedRegisters, from->ExtendedRegisters, sizeof(to->ExtendedRegisters) );
1350 /***********************************************************************
1351 * context_to_server
1353 * Convert a register context to the server format.
1355 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1357 DWORD flags = from->ContextFlags & ~CONTEXT_i386; /* get rid of CPU id */
1359 memset( to, 0, sizeof(*to) );
1360 to->cpu = CPU_x86;
1362 if (flags & CONTEXT_CONTROL)
1364 to->flags |= SERVER_CTX_CONTROL;
1365 to->ctl.i386_regs.ebp = from->Ebp;
1366 to->ctl.i386_regs.esp = from->Esp;
1367 to->ctl.i386_regs.eip = from->Eip;
1368 to->ctl.i386_regs.cs = from->SegCs;
1369 to->ctl.i386_regs.ss = from->SegSs;
1370 to->ctl.i386_regs.eflags = from->EFlags;
1372 if (flags & CONTEXT_INTEGER)
1374 to->flags |= SERVER_CTX_INTEGER;
1375 to->integer.i386_regs.eax = from->Eax;
1376 to->integer.i386_regs.ebx = from->Ebx;
1377 to->integer.i386_regs.ecx = from->Ecx;
1378 to->integer.i386_regs.edx = from->Edx;
1379 to->integer.i386_regs.esi = from->Esi;
1380 to->integer.i386_regs.edi = from->Edi;
1382 if (flags & CONTEXT_SEGMENTS)
1384 to->flags |= SERVER_CTX_SEGMENTS;
1385 to->seg.i386_regs.ds = from->SegDs;
1386 to->seg.i386_regs.es = from->SegEs;
1387 to->seg.i386_regs.fs = from->SegFs;
1388 to->seg.i386_regs.gs = from->SegGs;
1390 if (flags & CONTEXT_FLOATING_POINT)
1392 to->flags |= SERVER_CTX_FLOATING_POINT;
1393 to->fp.i386_regs.ctrl = from->FloatSave.ControlWord;
1394 to->fp.i386_regs.status = from->FloatSave.StatusWord;
1395 to->fp.i386_regs.tag = from->FloatSave.TagWord;
1396 to->fp.i386_regs.err_off = from->FloatSave.ErrorOffset;
1397 to->fp.i386_regs.err_sel = from->FloatSave.ErrorSelector;
1398 to->fp.i386_regs.data_off = from->FloatSave.DataOffset;
1399 to->fp.i386_regs.data_sel = from->FloatSave.DataSelector;
1400 to->fp.i386_regs.cr0npx = from->FloatSave.Cr0NpxState;
1401 memcpy( to->fp.i386_regs.regs, from->FloatSave.RegisterArea, sizeof(to->fp.i386_regs.regs) );
1403 if (flags & CONTEXT_DEBUG_REGISTERS)
1405 to->flags |= SERVER_CTX_DEBUG_REGISTERS;
1406 to->debug.i386_regs.dr0 = from->Dr0;
1407 to->debug.i386_regs.dr1 = from->Dr1;
1408 to->debug.i386_regs.dr2 = from->Dr2;
1409 to->debug.i386_regs.dr3 = from->Dr3;
1410 to->debug.i386_regs.dr6 = from->Dr6;
1411 to->debug.i386_regs.dr7 = from->Dr7;
1413 if (flags & CONTEXT_EXTENDED_REGISTERS)
1415 to->flags |= SERVER_CTX_EXTENDED_REGISTERS;
1416 memcpy( to->ext.i386_regs, from->ExtendedRegisters, sizeof(to->ext.i386_regs) );
1418 return STATUS_SUCCESS;
1422 /***********************************************************************
1423 * context_from_server
1425 * Convert a register context from the server format.
1427 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
1429 if (from->cpu != CPU_x86) return STATUS_INVALID_PARAMETER;
1431 to->ContextFlags = CONTEXT_i386;
1432 if (from->flags & SERVER_CTX_CONTROL)
1434 to->ContextFlags |= CONTEXT_CONTROL;
1435 to->Ebp = from->ctl.i386_regs.ebp;
1436 to->Esp = from->ctl.i386_regs.esp;
1437 to->Eip = from->ctl.i386_regs.eip;
1438 to->SegCs = from->ctl.i386_regs.cs;
1439 to->SegSs = from->ctl.i386_regs.ss;
1440 to->EFlags = from->ctl.i386_regs.eflags;
1442 if (from->flags & SERVER_CTX_INTEGER)
1444 to->ContextFlags |= CONTEXT_INTEGER;
1445 to->Eax = from->integer.i386_regs.eax;
1446 to->Ebx = from->integer.i386_regs.ebx;
1447 to->Ecx = from->integer.i386_regs.ecx;
1448 to->Edx = from->integer.i386_regs.edx;
1449 to->Esi = from->integer.i386_regs.esi;
1450 to->Edi = from->integer.i386_regs.edi;
1452 if (from->flags & SERVER_CTX_SEGMENTS)
1454 to->ContextFlags |= CONTEXT_SEGMENTS;
1455 to->SegDs = from->seg.i386_regs.ds;
1456 to->SegEs = from->seg.i386_regs.es;
1457 to->SegFs = from->seg.i386_regs.fs;
1458 to->SegGs = from->seg.i386_regs.gs;
1460 if (from->flags & SERVER_CTX_FLOATING_POINT)
1462 to->ContextFlags |= CONTEXT_FLOATING_POINT;
1463 to->FloatSave.ControlWord = from->fp.i386_regs.ctrl;
1464 to->FloatSave.StatusWord = from->fp.i386_regs.status;
1465 to->FloatSave.TagWord = from->fp.i386_regs.tag;
1466 to->FloatSave.ErrorOffset = from->fp.i386_regs.err_off;
1467 to->FloatSave.ErrorSelector = from->fp.i386_regs.err_sel;
1468 to->FloatSave.DataOffset = from->fp.i386_regs.data_off;
1469 to->FloatSave.DataSelector = from->fp.i386_regs.data_sel;
1470 to->FloatSave.Cr0NpxState = from->fp.i386_regs.cr0npx;
1471 memcpy( to->FloatSave.RegisterArea, from->fp.i386_regs.regs, sizeof(to->FloatSave.RegisterArea) );
1473 if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
1475 to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1476 to->Dr0 = from->debug.i386_regs.dr0;
1477 to->Dr1 = from->debug.i386_regs.dr1;
1478 to->Dr2 = from->debug.i386_regs.dr2;
1479 to->Dr3 = from->debug.i386_regs.dr3;
1480 to->Dr6 = from->debug.i386_regs.dr6;
1481 to->Dr7 = from->debug.i386_regs.dr7;
1483 if (from->flags & SERVER_CTX_EXTENDED_REGISTERS)
1485 to->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
1486 memcpy( to->ExtendedRegisters, from->ext.i386_regs, sizeof(to->ExtendedRegisters) );
1488 return STATUS_SUCCESS;
1492 /***********************************************************************
1493 * is_privileged_instr
1495 * Check if the fault location is a privileged instruction.
1496 * Based on the instruction emulation code in dlls/kernel/instr.c.
1498 static inline DWORD is_privileged_instr( CONTEXT *context )
1500 const BYTE *instr;
1501 unsigned int prefix_count = 0;
1503 if (!wine_ldt_is_system( context->SegCs )) return 0;
1504 instr = (BYTE *)context->Eip;
1506 for (;;) switch(*instr)
1508 /* instruction prefixes */
1509 case 0x2e: /* %cs: */
1510 case 0x36: /* %ss: */
1511 case 0x3e: /* %ds: */
1512 case 0x26: /* %es: */
1513 case 0x64: /* %fs: */
1514 case 0x65: /* %gs: */
1515 case 0x66: /* opcode size */
1516 case 0x67: /* addr size */
1517 case 0xf0: /* lock */
1518 case 0xf2: /* repne */
1519 case 0xf3: /* repe */
1520 if (++prefix_count >= 15) return EXCEPTION_ILLEGAL_INSTRUCTION;
1521 instr++;
1522 continue;
1524 case 0x0f: /* extended instruction */
1525 switch(instr[1])
1527 case 0x20: /* mov crX, reg */
1528 case 0x21: /* mov drX, reg */
1529 case 0x22: /* mov reg, crX */
1530 case 0x23: /* mov reg drX */
1531 return EXCEPTION_PRIV_INSTRUCTION;
1533 return 0;
1534 case 0x6c: /* insb (%dx) */
1535 case 0x6d: /* insl (%dx) */
1536 case 0x6e: /* outsb (%dx) */
1537 case 0x6f: /* outsl (%dx) */
1538 case 0xcd: /* int $xx */
1539 case 0xe4: /* inb al,XX */
1540 case 0xe5: /* in (e)ax,XX */
1541 case 0xe6: /* outb XX,al */
1542 case 0xe7: /* out XX,(e)ax */
1543 case 0xec: /* inb (%dx),%al */
1544 case 0xed: /* inl (%dx),%eax */
1545 case 0xee: /* outb %al,(%dx) */
1546 case 0xef: /* outl %eax,(%dx) */
1547 case 0xf4: /* hlt */
1548 case 0xfa: /* cli */
1549 case 0xfb: /* sti */
1550 return EXCEPTION_PRIV_INSTRUCTION;
1551 default:
1552 return 0;
1557 /***********************************************************************
1558 * handle_interrupt
1560 * Handle an interrupt.
1562 static inline BOOL handle_interrupt( unsigned int interrupt, EXCEPTION_RECORD *rec, CONTEXT *context )
1564 switch(interrupt)
1566 case 0x2d:
1567 context->Eip += 3;
1568 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1569 rec->ExceptionAddress = (void *)context->Eip;
1570 rec->NumberParameters = is_wow64 ? 1 : 3;
1571 rec->ExceptionInformation[0] = context->Eax;
1572 rec->ExceptionInformation[1] = context->Ecx;
1573 rec->ExceptionInformation[2] = context->Edx;
1574 return TRUE;
1575 default:
1576 return FALSE;
1581 /***********************************************************************
1582 * check_invalid_gs
1584 * Check for fault caused by invalid %gs value (some copy protection schemes mess with it).
1586 static inline BOOL check_invalid_gs( CONTEXT *context )
1588 unsigned int prefix_count = 0;
1589 const BYTE *instr = (BYTE *)context->Eip;
1590 WORD system_gs = ntdll_get_thread_data()->gs;
1592 if (context->SegGs == system_gs) return FALSE;
1593 if (!wine_ldt_is_system( context->SegCs )) return FALSE;
1594 /* only handle faults in system libraries */
1595 if (virtual_is_valid_code_address( instr, 1 )) return FALSE;
1597 for (;;) switch(*instr)
1599 /* instruction prefixes */
1600 case 0x2e: /* %cs: */
1601 case 0x36: /* %ss: */
1602 case 0x3e: /* %ds: */
1603 case 0x26: /* %es: */
1604 case 0x64: /* %fs: */
1605 case 0x66: /* opcode size */
1606 case 0x67: /* addr size */
1607 case 0xf0: /* lock */
1608 case 0xf2: /* repne */
1609 case 0xf3: /* repe */
1610 if (++prefix_count >= 15) return FALSE;
1611 instr++;
1612 continue;
1613 case 0x65: /* %gs: */
1614 TRACE( "%04x/%04x at %p, fixing up\n", context->SegGs, system_gs, instr );
1615 context->SegGs = system_gs;
1616 return TRUE;
1617 default:
1618 return FALSE;
1623 #include "pshpack1.h"
1624 union atl_thunk
1626 struct
1628 DWORD movl; /* movl this,4(%esp) */
1629 DWORD this;
1630 BYTE jmp; /* jmp func */
1631 int func;
1632 } t1;
1633 struct
1635 BYTE movl; /* movl this,ecx */
1636 DWORD this;
1637 BYTE jmp; /* jmp func */
1638 int func;
1639 } t2;
1640 struct
1642 BYTE movl1; /* movl this,edx */
1643 DWORD this;
1644 BYTE movl2; /* movl func,ecx */
1645 DWORD func;
1646 WORD jmp; /* jmp ecx */
1647 } t3;
1648 struct
1650 BYTE movl1; /* movl this,ecx */
1651 DWORD this;
1652 BYTE movl2; /* movl func,eax */
1653 DWORD func;
1654 WORD jmp; /* jmp eax */
1655 } t4;
1656 struct
1658 DWORD inst1; /* pop ecx
1659 * pop eax
1660 * push ecx
1661 * jmp 4(%eax) */
1662 WORD inst2;
1663 } t5;
1665 #include "poppack.h"
1667 /**********************************************************************
1668 * check_atl_thunk
1670 * Check if code destination is an ATL thunk, and emulate it if so.
1672 static BOOL check_atl_thunk( EXCEPTION_RECORD *rec, CONTEXT *context )
1674 const union atl_thunk *thunk = (const union atl_thunk *)rec->ExceptionInformation[1];
1675 union atl_thunk thunk_copy;
1676 SIZE_T thunk_len;
1678 thunk_len = virtual_uninterrupted_read_memory( thunk, &thunk_copy, sizeof(*thunk) );
1679 if (!thunk_len) return FALSE;
1681 if (thunk_len >= sizeof(thunk_copy.t1) && thunk_copy.t1.movl == 0x042444c7 &&
1682 thunk_copy.t1.jmp == 0xe9)
1684 if (virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
1685 &thunk_copy.t1.this, sizeof(DWORD) ) == sizeof(DWORD))
1687 context->Eip = (DWORD_PTR)(&thunk->t1.func + 1) + thunk_copy.t1.func;
1688 TRACE( "emulating ATL thunk type 1 at %p, func=%08x arg=%08x\n",
1689 thunk, context->Eip, thunk_copy.t1.this );
1690 return TRUE;
1693 else if (thunk_len >= sizeof(thunk_copy.t2) && thunk_copy.t2.movl == 0xb9 &&
1694 thunk_copy.t2.jmp == 0xe9)
1696 context->Ecx = thunk_copy.t2.this;
1697 context->Eip = (DWORD_PTR)(&thunk->t2.func + 1) + thunk_copy.t2.func;
1698 TRACE( "emulating ATL thunk type 2 at %p, func=%08x ecx=%08x\n",
1699 thunk, context->Eip, context->Ecx );
1700 return TRUE;
1702 else if (thunk_len >= sizeof(thunk_copy.t3) && thunk_copy.t3.movl1 == 0xba &&
1703 thunk_copy.t3.movl2 == 0xb9 &&
1704 thunk_copy.t3.jmp == 0xe1ff)
1706 context->Edx = thunk_copy.t3.this;
1707 context->Ecx = thunk_copy.t3.func;
1708 context->Eip = thunk_copy.t3.func;
1709 TRACE( "emulating ATL thunk type 3 at %p, func=%08x ecx=%08x edx=%08x\n",
1710 thunk, context->Eip, context->Ecx, context->Edx );
1711 return TRUE;
1713 else if (thunk_len >= sizeof(thunk_copy.t4) && thunk_copy.t4.movl1 == 0xb9 &&
1714 thunk_copy.t4.movl2 == 0xb8 &&
1715 thunk_copy.t4.jmp == 0xe0ff)
1717 context->Ecx = thunk_copy.t4.this;
1718 context->Eax = thunk_copy.t4.func;
1719 context->Eip = thunk_copy.t4.func;
1720 TRACE( "emulating ATL thunk type 4 at %p, func=%08x eax=%08x ecx=%08x\n",
1721 thunk, context->Eip, context->Eax, context->Ecx );
1722 return TRUE;
1724 else if (thunk_len >= sizeof(thunk_copy.t5) && thunk_copy.t5.inst1 == 0xff515859 &&
1725 thunk_copy.t5.inst2 == 0x0460)
1727 DWORD func, stack[2];
1728 if (virtual_uninterrupted_read_memory( (DWORD *)context->Esp,
1729 stack, sizeof(stack) ) == sizeof(stack) &&
1730 virtual_uninterrupted_read_memory( (DWORD *)stack[1] + 1,
1731 &func, sizeof(DWORD) ) == sizeof(DWORD) &&
1732 virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
1733 &stack[0], sizeof(stack[0]) ) == sizeof(stack[0]))
1735 context->Ecx = stack[0];
1736 context->Eax = stack[1];
1737 context->Esp = context->Esp + sizeof(DWORD);
1738 context->Eip = func;
1739 TRACE( "emulating ATL thunk type 5 at %p, func=%08x eax=%08x ecx=%08x esp=%08x\n",
1740 thunk, context->Eip, context->Eax, context->Ecx, context->Esp );
1741 return TRUE;
1745 return FALSE;
1749 /***********************************************************************
1750 * setup_exception_record
1752 * Setup the exception record and context on the thread stack.
1754 static EXCEPTION_RECORD *setup_exception_record( ucontext_t *sigcontext, void *stack_ptr,
1755 WORD fs, WORD gs, raise_func func )
1757 struct stack_layout
1759 void *ret_addr; /* return address from raise_func */
1760 EXCEPTION_RECORD *rec_ptr; /* first arg for raise_func */
1761 CONTEXT *context_ptr; /* second arg for raise_func */
1762 CONTEXT context;
1763 EXCEPTION_RECORD rec;
1764 DWORD ebp;
1765 DWORD eip;
1766 } *stack = stack_ptr;
1767 DWORD exception_code = 0;
1769 /* stack sanity checks */
1771 if ((char *)stack >= (char *)get_signal_stack() &&
1772 (char *)stack < (char *)get_signal_stack() + signal_stack_size)
1774 WINE_ERR( "nested exception on signal stack in thread %04x eip %08x esp %08x stack %p-%p\n",
1775 GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1776 (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
1777 NtCurrentTeb()->Tib.StackBase );
1778 abort_thread(1);
1781 if (stack - 1 > stack || /* check for overflow in subtraction */
1782 (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
1783 (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
1785 WARN( "exception outside of stack limits in thread %04x eip %08x esp %08x stack %p-%p\n",
1786 GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1787 (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
1788 NtCurrentTeb()->Tib.StackBase );
1790 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
1792 /* stack overflow on last page, unrecoverable */
1793 UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
1794 WINE_ERR( "stack overflow %u bytes in thread %04x eip %08x esp %08x stack %p-%p-%p\n",
1795 diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1796 (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1797 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1798 abort_thread(1);
1800 else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
1802 /* stack access below stack limit, may be recoverable */
1803 if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
1804 else
1806 UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
1807 WINE_ERR( "stack overflow %u bytes in thread %04x eip %08x esp %08x stack %p-%p-%p\n",
1808 diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
1809 (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
1810 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1811 abort_thread(1);
1815 stack--; /* push the stack_layout structure */
1816 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
1817 VALGRIND_MAKE_MEM_UNDEFINED(stack, sizeof(*stack));
1818 #elif defined(VALGRIND_MAKE_WRITABLE)
1819 VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
1820 #endif
1821 stack->ret_addr = (void *)0xdeadbabe; /* raise_func must not return */
1822 stack->rec_ptr = &stack->rec;
1823 stack->context_ptr = &stack->context;
1825 stack->rec.ExceptionRecord = NULL;
1826 stack->rec.ExceptionCode = exception_code;
1827 stack->rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
1828 stack->rec.ExceptionAddress = (LPVOID)EIP_sig(sigcontext);
1829 stack->rec.NumberParameters = 0;
1831 save_context( &stack->context, sigcontext, fs, gs );
1833 /* now modify the sigcontext to return to the raise function */
1834 ESP_sig(sigcontext) = (DWORD)stack;
1835 EIP_sig(sigcontext) = (DWORD)func;
1836 /* clear single-step, direction, and align check flag */
1837 EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
1838 CS_sig(sigcontext) = wine_get_cs();
1839 DS_sig(sigcontext) = wine_get_ds();
1840 ES_sig(sigcontext) = wine_get_es();
1841 FS_sig(sigcontext) = wine_get_fs();
1842 GS_sig(sigcontext) = wine_get_gs();
1843 SS_sig(sigcontext) = wine_get_ss();
1845 return stack->rec_ptr;
1849 /***********************************************************************
1850 * setup_exception
1852 * Setup a proper stack frame for the raise function, and modify the
1853 * sigcontext so that the return from the signal handler will call
1854 * the raise function.
1856 static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
1858 WORD fs, gs;
1859 void *stack = init_handler( sigcontext, &fs, &gs );
1861 return setup_exception_record( sigcontext, stack, fs, gs, func );
1865 /***********************************************************************
1866 * get_exception_context
1868 * Get a pointer to the context built by setup_exception.
1870 static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
1872 return (CONTEXT *)rec - 1; /* cf. stack_layout structure */
1876 /**********************************************************************
1877 * get_fpu_code
1879 * Get the FPU exception code from the FPU status.
1881 static inline DWORD get_fpu_code( const CONTEXT *context )
1883 DWORD status = context->FloatSave.StatusWord & ~(context->FloatSave.ControlWord & 0x3f);
1885 if (status & 0x01) /* IE */
1887 if (status & 0x40) /* SF */
1888 return EXCEPTION_FLT_STACK_CHECK;
1889 else
1890 return EXCEPTION_FLT_INVALID_OPERATION;
1892 if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND; /* DE flag */
1893 if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO; /* ZE flag */
1894 if (status & 0x08) return EXCEPTION_FLT_OVERFLOW; /* OE flag */
1895 if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW; /* UE flag */
1896 if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT; /* PE flag */
1897 return EXCEPTION_FLT_INVALID_OPERATION; /* generic error */
1901 /**********************************************************************
1902 * raise_segv_exception
1904 static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1906 NTSTATUS status;
1908 switch(rec->ExceptionCode)
1910 case EXCEPTION_ACCESS_VIOLATION:
1911 if (rec->NumberParameters == 2)
1913 if (rec->ExceptionInformation[1] == 0xffffffff && check_invalid_gs( context ))
1914 goto done;
1915 if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
1916 rec->ExceptionInformation[0], FALSE )))
1917 goto done;
1918 if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
1919 rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT)
1921 ULONG flags;
1922 NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
1923 &flags, sizeof(flags), NULL );
1925 if (!(flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION) && check_atl_thunk( rec, context ))
1926 goto done;
1928 /* send EXCEPTION_EXECUTE_FAULT only if data execution prevention is enabled */
1929 if (!(flags & MEM_EXECUTE_OPTION_DISABLE))
1930 rec->ExceptionInformation[0] = EXCEPTION_READ_FAULT;
1933 break;
1934 case EXCEPTION_DATATYPE_MISALIGNMENT:
1935 /* FIXME: pass through exception handler first? */
1936 if (context->EFlags & 0x00040000)
1938 /* Disable AC flag, return */
1939 context->EFlags &= ~0x00040000;
1940 goto done;
1942 break;
1943 case EXCEPTION_BREAKPOINT:
1944 if (!is_wow64)
1946 /* On Wow64, the upper DWORD of Rax contains garbage, and the debug
1947 * service is usually not recognized when called from usermode. */
1948 switch (rec->ExceptionInformation[0])
1950 case 1: /* BREAKPOINT_PRINT */
1951 case 3: /* BREAKPOINT_LOAD_SYMBOLS */
1952 case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
1953 case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
1954 goto done;
1957 break;
1959 status = NtRaiseException( rec, context, TRUE );
1960 raise_status( status, rec );
1961 done:
1962 set_cpu_context( context );
1966 /**********************************************************************
1967 * raise_trap_exception
1969 static void WINAPI raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1971 NTSTATUS status;
1973 if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
1975 /* when single stepping can't tell whether this is a hw bp or a
1976 * single step interrupt. try to avoid as much overhead as possible
1977 * and only do a server call if there is any hw bp enabled. */
1979 if( !(context->EFlags & 0x100) || (ntdll_get_thread_data()->dr7 & 0xff) )
1981 /* (possible) hardware breakpoint, fetch the debug registers */
1982 DWORD saved_flags = context->ContextFlags;
1983 context->ContextFlags = CONTEXT_DEBUG_REGISTERS;
1984 NtGetContextThread(GetCurrentThread(), context);
1985 context->ContextFlags |= saved_flags; /* restore flags */
1988 context->EFlags &= ~0x100; /* clear single-step flag */
1991 status = NtRaiseException( rec, context, TRUE );
1992 raise_status( status, rec );
1996 /**********************************************************************
1997 * raise_generic_exception
1999 * Generic raise function for exceptions that don't need special treatment.
2001 static void WINAPI raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2003 NTSTATUS status;
2005 status = NtRaiseException( rec, context, TRUE );
2006 raise_status( status, rec );
2010 #ifdef __HAVE_VM86
2011 /**********************************************************************
2012 * raise_vm86_sti_exception
2014 static void WINAPI raise_vm86_sti_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2016 /* merge_vm86_pending_flags merges the vm86_pending flag in safely */
2017 get_vm86_teb_info()->vm86_pending |= VIP_FLAG;
2019 if (ntdll_get_thread_data()->vm86_ptr)
2021 if (((char*)context->Eip >= (char*)vm86_return) &&
2022 ((char*)context->Eip <= (char*)vm86_return_end) &&
2023 (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
2024 /* exiting from VM86, can't throw */
2025 goto done;
2027 merge_vm86_pending_flags( rec );
2029 else if (get_vm86_teb_info()->dpmi_vif &&
2030 !wine_ldt_is_system(context->SegCs) &&
2031 !wine_ldt_is_system(context->SegSs))
2033 /* Executing DPMI code and virtual interrupts are enabled. */
2034 get_vm86_teb_info()->vm86_pending = 0;
2035 NtRaiseException( rec, context, TRUE );
2037 done:
2038 set_cpu_context( context );
2042 /**********************************************************************
2043 * usr2_handler
2045 * Handler for SIGUSR2.
2046 * We use it to signal that the running __wine_enter_vm86() should
2047 * immediately set VIP_FLAG, causing pending events to be handled
2048 * as early as possible.
2050 static void usr2_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2052 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_vm86_sti_exception );
2053 rec->ExceptionCode = EXCEPTION_VM86_STI;
2055 #endif /* __HAVE_VM86 */
2058 /**********************************************************************
2059 * segv_handler
2061 * Handler for SIGSEGV and related errors.
2063 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2065 WORD fs, gs;
2066 EXCEPTION_RECORD *rec;
2067 ucontext_t *context = sigcontext;
2068 void *stack = init_handler( sigcontext, &fs, &gs );
2070 /* check for exceptions on the signal stack caused by write watches */
2071 if (get_trap_code(context) == TRAP_x86_PAGEFLT &&
2072 (char *)stack >= (char *)get_signal_stack() &&
2073 (char *)stack < (char *)get_signal_stack() + signal_stack_size &&
2074 !virtual_handle_fault( siginfo->si_addr, (get_error_code(context) >> 1) & 0x09, TRUE ))
2076 return;
2079 /* check for page fault inside the thread stack */
2080 if (get_trap_code(context) == TRAP_x86_PAGEFLT &&
2081 (char *)siginfo->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
2082 (char *)siginfo->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
2083 virtual_handle_stack_fault( siginfo->si_addr ))
2085 /* check if this was the last guard page */
2086 if ((char *)siginfo->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
2088 rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
2089 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2091 return;
2094 rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
2095 if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
2097 switch(get_trap_code(context))
2099 case TRAP_x86_OFLOW: /* Overflow exception */
2100 rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2101 break;
2102 case TRAP_x86_BOUND: /* Bound range exception */
2103 rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2104 break;
2105 case TRAP_x86_PRIVINFLT: /* Invalid opcode exception */
2106 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2107 break;
2108 case TRAP_x86_STKFLT: /* Stack fault */
2109 rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2110 break;
2111 case TRAP_x86_SEGNPFLT: /* Segment not present exception */
2112 case TRAP_x86_PROTFLT: /* General protection fault */
2113 case TRAP_x86_UNKNOWN: /* Unknown fault code */
2115 CONTEXT *win_context = get_exception_context( rec );
2116 WORD err = get_error_code(context);
2117 if (!err && (rec->ExceptionCode = is_privileged_instr( win_context ))) break;
2118 if ((err & 7) == 2 && handle_interrupt( err >> 3, rec, win_context )) break;
2119 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2120 rec->NumberParameters = 2;
2121 rec->ExceptionInformation[0] = 0;
2122 /* if error contains a LDT selector, use that as fault address */
2123 if ((err & 7) == 4 && !wine_ldt_is_system( err | 7 ))
2124 rec->ExceptionInformation[1] = err & ~7;
2125 else
2126 rec->ExceptionInformation[1] = 0xffffffff;
2128 break;
2129 case TRAP_x86_PAGEFLT: /* Page fault */
2130 rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2131 rec->NumberParameters = 2;
2132 rec->ExceptionInformation[0] = (get_error_code(context) >> 1) & 0x09;
2133 rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2134 break;
2135 case TRAP_x86_ALIGNFLT: /* Alignment check exception */
2136 rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2137 break;
2138 default:
2139 WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
2140 /* fall through */
2141 case TRAP_x86_NMI: /* NMI interrupt */
2142 case TRAP_x86_DNA: /* Device not available exception */
2143 case TRAP_x86_DOUBLEFLT: /* Double fault exception */
2144 case TRAP_x86_TSSFLT: /* Invalid TSS exception */
2145 case TRAP_x86_MCHK: /* Machine check exception */
2146 case TRAP_x86_CACHEFLT: /* Cache flush exception */
2147 rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2148 break;
2153 /**********************************************************************
2154 * trap_handler
2156 * Handler for SIGTRAP.
2158 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2160 ucontext_t *context = sigcontext;
2161 EXCEPTION_RECORD *rec = setup_exception( context, raise_trap_exception );
2163 switch(get_trap_code(context))
2165 case TRAP_x86_TRCTRAP: /* Single-step exception */
2166 rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
2167 break;
2168 case TRAP_x86_BPTFLT: /* Breakpoint exception */
2169 rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1; /* back up over the int3 instruction */
2170 /* fall through */
2171 default:
2172 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2173 rec->NumberParameters = is_wow64 ? 1 : 3;
2174 rec->ExceptionInformation[0] = 0;
2175 rec->ExceptionInformation[1] = 0; /* FIXME */
2176 rec->ExceptionInformation[2] = 0; /* FIXME */
2177 break;
2182 /**********************************************************************
2183 * fpe_handler
2185 * Handler for SIGFPE.
2187 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2189 CONTEXT *win_context;
2190 ucontext_t *context = sigcontext;
2191 EXCEPTION_RECORD *rec = setup_exception( context, raise_generic_exception );
2193 win_context = get_exception_context( rec );
2195 switch(get_trap_code(context))
2197 case TRAP_x86_DIVIDE: /* Division by zero exception */
2198 rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2199 break;
2200 case TRAP_x86_FPOPFLT: /* Coprocessor segment overrun */
2201 rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2202 break;
2203 case TRAP_x86_ARITHTRAP: /* Floating point exception */
2204 case TRAP_x86_UNKNOWN: /* Unknown fault code */
2205 rec->ExceptionCode = get_fpu_code( win_context );
2206 rec->ExceptionAddress = (LPVOID)win_context->FloatSave.ErrorOffset;
2207 break;
2208 case TRAP_x86_CACHEFLT: /* SIMD exception */
2209 /* TODO:
2210 * Behaviour only tested for divide-by-zero exceptions
2211 * Check for other SIMD exceptions as well */
2212 if(siginfo->si_code != FPE_FLTDIV && siginfo->si_code != FPE_FLTINV)
2213 FIXME("untested SIMD exception: %#x. Might not work correctly\n",
2214 siginfo->si_code);
2216 rec->ExceptionCode = STATUS_FLOAT_MULTIPLE_TRAPS;
2217 rec->NumberParameters = 1;
2218 /* no idea what meaning is actually behind this but that's what native does */
2219 rec->ExceptionInformation[0] = 0;
2220 break;
2221 default:
2222 WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
2223 rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2224 break;
2229 /**********************************************************************
2230 * int_handler
2232 * Handler for SIGINT.
2234 * FIXME: should not be calling external functions on the signal stack.
2236 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2238 WORD fs, gs;
2239 init_handler( sigcontext, &fs, &gs );
2240 if (!dispatch_signal(SIGINT))
2242 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2243 rec->ExceptionCode = CONTROL_C_EXIT;
2247 /**********************************************************************
2248 * abrt_handler
2250 * Handler for SIGABRT.
2252 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2254 EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2255 rec->ExceptionCode = EXCEPTION_WINE_ASSERTION;
2256 rec->ExceptionFlags = EH_NONCONTINUABLE;
2260 /**********************************************************************
2261 * quit_handler
2263 * Handler for SIGQUIT.
2265 static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2267 WORD fs, gs;
2268 init_handler( sigcontext, &fs, &gs );
2269 abort_thread(0);
2273 /**********************************************************************
2274 * usr1_handler
2276 * Handler for SIGUSR1, used to signal a thread that it got suspended.
2278 static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2280 CONTEXT context;
2281 WORD fs, gs;
2283 init_handler( sigcontext, &fs, &gs );
2284 save_context( &context, sigcontext, fs, gs );
2285 wait_suspend( &context );
2286 restore_context( &context, sigcontext );
2290 /***********************************************************************
2291 * __wine_set_signal_handler (NTDLL.@)
2293 int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
2295 if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
2296 if (handlers[sig] != NULL) return -2;
2297 handlers[sig] = wsh;
2298 return 0;
2302 /***********************************************************************
2303 * locking for LDT routines
2305 static RTL_CRITICAL_SECTION ldt_section;
2306 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
2308 0, 0, &ldt_section,
2309 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
2310 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
2312 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
2313 static sigset_t ldt_sigset;
2315 static void ldt_lock(void)
2317 sigset_t sigset;
2319 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
2320 RtlEnterCriticalSection( &ldt_section );
2321 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
2324 static void ldt_unlock(void)
2326 if (ldt_section.RecursionCount == 1)
2328 sigset_t sigset = ldt_sigset;
2329 RtlLeaveCriticalSection( &ldt_section );
2330 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
2332 else RtlLeaveCriticalSection( &ldt_section );
2336 /**********************************************************************
2337 * signal_alloc_thread
2339 NTSTATUS signal_alloc_thread( TEB **teb )
2341 static size_t sigstack_zero_bits;
2342 struct ntdll_thread_data *thread_data;
2343 struct ntdll_thread_data *parent_data = NULL;
2344 SIZE_T size;
2345 void *addr = NULL;
2346 NTSTATUS status;
2348 if (!sigstack_zero_bits)
2350 size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2351 /* find the first power of two not smaller than min_size */
2352 sigstack_zero_bits = 12;
2353 while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
2354 signal_stack_mask = (1 << sigstack_zero_bits) - 1;
2355 signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
2357 else parent_data = ntdll_get_thread_data();
2359 size = signal_stack_mask + 1;
2360 if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
2361 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
2363 *teb = addr;
2364 (*teb)->Tib.Self = &(*teb)->Tib;
2365 (*teb)->Tib.ExceptionList = (void *)~0UL;
2366 thread_data = (struct ntdll_thread_data *)(*teb)->SpareBytes1;
2367 if (!(thread_data->fs = wine_ldt_alloc_fs()))
2369 size = 0;
2370 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
2371 status = STATUS_TOO_MANY_THREADS;
2373 if (parent_data)
2375 /* inherit debug registers from parent thread */
2376 thread_data->dr0 = parent_data->dr0;
2377 thread_data->dr1 = parent_data->dr1;
2378 thread_data->dr2 = parent_data->dr2;
2379 thread_data->dr3 = parent_data->dr3;
2380 thread_data->dr6 = parent_data->dr6;
2381 thread_data->dr7 = parent_data->dr7;
2385 return status;
2389 /**********************************************************************
2390 * signal_free_thread
2392 void signal_free_thread( TEB *teb )
2394 SIZE_T size;
2395 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
2397 if (thread_data) wine_ldt_free_fs( thread_data->fs );
2398 if (teb->DeallocationStack)
2400 size = 0;
2401 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
2403 size = 0;
2404 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2408 /**********************************************************************
2409 * signal_init_thread
2411 void signal_init_thread( TEB *teb )
2413 const WORD fpu_cw = 0x27f;
2414 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
2415 LDT_ENTRY fs_entry;
2416 stack_t ss;
2418 #ifdef __APPLE__
2419 int mib[2], val = 1;
2421 mib[0] = CTL_KERN;
2422 mib[1] = KERN_THALTSTACK;
2423 sysctl( mib, 2, NULL, NULL, &val, sizeof(val) );
2424 #endif
2426 ss.ss_sp = (char *)teb + teb_size;
2427 ss.ss_size = signal_stack_size;
2428 ss.ss_flags = 0;
2429 if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
2431 wine_ldt_set_base( &fs_entry, teb );
2432 wine_ldt_set_limit( &fs_entry, teb_size - 1 );
2433 wine_ldt_set_flags( &fs_entry, WINE_LDT_FLAGS_DATA|WINE_LDT_FLAGS_32BIT );
2434 wine_ldt_init_fs( thread_data->fs, &fs_entry );
2435 thread_data->gs = wine_get_gs();
2437 #ifdef __GNUC__
2438 __asm__ volatile ("fninit; fldcw %0" : : "m" (fpu_cw));
2439 #else
2440 FIXME("FPU setup not implemented for this platform.\n");
2441 #endif
2444 /**********************************************************************
2445 * signal_init_process
2447 void signal_init_process(void)
2449 struct sigaction sig_act;
2451 sig_act.sa_mask = server_block_set;
2452 sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
2453 #ifdef SA_ONSTACK
2454 sig_act.sa_flags |= SA_ONSTACK;
2455 #endif
2456 #ifdef __ANDROID__
2457 sig_act.sa_flags |= SA_RESTORER;
2458 sig_act.sa_restorer = rt_sigreturn;
2459 #endif
2460 sig_act.sa_sigaction = int_handler;
2461 if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
2462 sig_act.sa_sigaction = fpe_handler;
2463 if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
2464 sig_act.sa_sigaction = abrt_handler;
2465 if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
2466 sig_act.sa_sigaction = quit_handler;
2467 if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
2468 sig_act.sa_sigaction = usr1_handler;
2469 if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
2471 sig_act.sa_sigaction = segv_handler;
2472 if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
2473 if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2474 #ifdef SIGBUS
2475 if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2476 #endif
2478 #ifdef SIGTRAP
2479 sig_act.sa_sigaction = trap_handler;
2480 if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2481 #endif
2483 #ifdef __HAVE_VM86
2484 sig_act.sa_sigaction = usr2_handler;
2485 if (sigaction( SIGUSR2, &sig_act, NULL ) == -1) goto error;
2486 #endif
2488 wine_ldt_init_locking( ldt_lock, ldt_unlock );
2489 return;
2491 error:
2492 perror("sigaction");
2493 exit(1);
2497 #ifdef __HAVE_VM86
2498 /**********************************************************************
2499 * __wine_enter_vm86 (NTDLL.@)
2501 * Enter vm86 mode with the specified register context.
2503 void __wine_enter_vm86( CONTEXT *context )
2505 EXCEPTION_RECORD rec;
2506 int res;
2507 struct vm86plus_struct vm86;
2509 memset( &vm86, 0, sizeof(vm86) );
2510 for (;;)
2512 restore_vm86_context( context, &vm86 );
2514 ntdll_get_thread_data()->vm86_ptr = &vm86;
2515 merge_vm86_pending_flags( &rec );
2517 res = vm86_enter( &ntdll_get_thread_data()->vm86_ptr ); /* uses and clears teb->vm86_ptr */
2518 if (res < 0)
2520 errno = -res;
2521 return;
2524 save_vm86_context( context, &vm86 );
2526 rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
2527 rec.ExceptionRecord = NULL;
2528 rec.ExceptionAddress = (LPVOID)context->Eip;
2529 rec.NumberParameters = 0;
2531 switch(VM86_TYPE(res))
2533 case VM86_UNKNOWN: /* unhandled GP fault - IO-instruction or similar */
2534 rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION;
2535 break;
2536 case VM86_TRAP: /* return due to DOS-debugger request */
2537 switch(VM86_ARG(res))
2539 case TRAP_x86_TRCTRAP: /* Single-step exception */
2540 rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
2541 break;
2542 case TRAP_x86_BPTFLT: /* Breakpoint exception */
2543 rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1; /* back up over the int3 instruction */
2544 /* fall through */
2545 default:
2546 rec.ExceptionCode = EXCEPTION_BREAKPOINT;
2547 break;
2549 break;
2550 case VM86_INTx: /* int3/int x instruction (ARG = x) */
2551 rec.ExceptionCode = EXCEPTION_VM86_INTx;
2552 rec.NumberParameters = 1;
2553 rec.ExceptionInformation[0] = VM86_ARG(res);
2554 break;
2555 case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
2556 context->EFlags |= VIF_FLAG;
2557 context->EFlags &= ~VIP_FLAG;
2558 get_vm86_teb_info()->vm86_pending = 0;
2559 rec.ExceptionCode = EXCEPTION_VM86_STI;
2560 break;
2561 case VM86_PICRETURN: /* return due to pending PIC request */
2562 rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
2563 break;
2564 case VM86_SIGNAL: /* cannot happen because vm86_enter handles this case */
2565 default:
2566 WINE_ERR( "unhandled result from vm86 mode %x\n", res );
2567 continue;
2569 raise_exception( &rec, context, TRUE );
2573 #else /* __HAVE_VM86 */
2574 /**********************************************************************
2575 * __wine_enter_vm86 (NTDLL.@)
2577 void __wine_enter_vm86( CONTEXT *context )
2579 MESSAGE("vm86 mode not supported on this platform\n");
2581 #endif /* __HAVE_VM86 */
2584 /*******************************************************************
2585 * RtlUnwind (NTDLL.@)
2587 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID targetIp,
2588 PEXCEPTION_RECORD pRecord, PVOID retval, CONTEXT *context )
2590 EXCEPTION_RECORD record;
2591 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
2592 DWORD res;
2594 context->Eax = (DWORD)retval;
2596 /* build an exception record, if we do not have one */
2597 if (!pRecord)
2599 record.ExceptionCode = STATUS_UNWIND;
2600 record.ExceptionFlags = 0;
2601 record.ExceptionRecord = NULL;
2602 record.ExceptionAddress = (void *)context->Eip;
2603 record.NumberParameters = 0;
2604 pRecord = &record;
2607 pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
2609 TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
2611 /* get chain of exception frames */
2612 frame = NtCurrentTeb()->Tib.ExceptionList;
2613 while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
2615 /* Check frame address */
2616 if (pEndFrame && (frame > pEndFrame))
2617 raise_status( STATUS_INVALID_UNWIND_TARGET, pRecord );
2619 if (!is_valid_frame( frame )) raise_status( STATUS_BAD_STACK, pRecord );
2621 /* Call handler */
2622 TRACE( "calling handler at %p code=%x flags=%x\n",
2623 frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
2624 res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, unwind_handler );
2625 TRACE( "handler at %p returned %x\n", frame->Handler, res );
2627 switch(res)
2629 case ExceptionContinueSearch:
2630 break;
2631 case ExceptionCollidedUnwind:
2632 frame = dispatch;
2633 break;
2634 default:
2635 raise_status( STATUS_INVALID_DISPOSITION, pRecord );
2636 break;
2638 frame = __wine_pop_frame( frame );
2641 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )
2644 /*******************************************************************
2645 * NtRaiseException (NTDLL.@)
2647 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
2649 NTSTATUS status = raise_exception( rec, context, first_chance );
2650 if (status == STATUS_SUCCESS)
2652 set_debug_registers( context );
2653 set_cpu_context( context );
2655 return status;
2659 /***********************************************************************
2660 * RtlRaiseException (NTDLL.@)
2662 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
2664 NTSTATUS status;
2666 rec->ExceptionAddress = (void *)context->Eip;
2667 status = raise_exception( rec, context, TRUE );
2668 if (status != STATUS_SUCCESS) raise_status( status, rec );
2670 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 1 )
2673 /*************************************************************************
2674 * RtlCaptureStackBackTrace (NTDLL.@)
2676 USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
2678 CONTEXT context;
2679 ULONG i;
2680 ULONG *frame;
2682 RtlCaptureContext( &context );
2683 if (hash) *hash = 0;
2684 frame = (ULONG *)context.Ebp;
2686 while (skip--)
2688 if (!is_valid_frame( frame )) return 0;
2689 frame = (ULONG *)*frame;
2692 for (i = 0; i < count; i++)
2694 if (!is_valid_frame( frame )) break;
2695 buffer[i] = (void *)frame[1];
2696 if (hash) *hash += frame[1];
2697 frame = (ULONG *)*frame;
2699 return i;
2703 extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
2704 __ASM_GLOBAL_FUNC( call_thread_entry_point,
2705 "pushl %ebp\n\t"
2706 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2707 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2708 "movl %esp,%ebp\n\t"
2709 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2710 "pushl %ebx\n\t"
2711 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2712 "pushl %esi\n\t"
2713 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
2714 "pushl %edi\n\t"
2715 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
2716 "pushl %ebp\n\t"
2717 "pushl 12(%ebp)\n\t"
2718 "pushl 8(%ebp)\n\t"
2719 "call " __ASM_NAME("call_thread_func") );
2721 extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
2722 __ASM_GLOBAL_FUNC( call_thread_exit_func,
2723 "movl 4(%esp),%eax\n\t"
2724 "movl 8(%esp),%ecx\n\t"
2725 "movl 12(%esp),%ebp\n\t"
2726 __ASM_CFI(".cfi_def_cfa %ebp,4\n\t")
2727 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2728 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2729 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
2730 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
2731 "leal -20(%ebp),%esp\n\t"
2732 "pushl %eax\n\t"
2733 "call *%ecx" );
2735 /* wrapper for apps that don't declare the thread function correctly */
2736 extern void DECLSPEC_NORETURN call_thread_func_wrapper( LPTHREAD_START_ROUTINE entry, void *arg );
2737 __ASM_GLOBAL_FUNC(call_thread_func_wrapper,
2738 "pushl %ebp\n\t"
2739 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2740 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2741 "movl %esp,%ebp\n\t"
2742 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2743 "subl $4,%esp\n\t"
2744 "pushl 12(%ebp)\n\t"
2745 "call *8(%ebp)\n\t"
2746 "leal -4(%ebp),%esp\n\t"
2747 "pushl %eax\n\t"
2748 "call " __ASM_NAME("exit_thread") "\n\t"
2749 "int $3" )
2751 /***********************************************************************
2752 * call_thread_func
2754 void call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
2756 ntdll_get_thread_data()->exit_frame = frame;
2757 __TRY
2759 call_thread_func_wrapper( entry, arg );
2761 __EXCEPT(unhandled_exception_filter)
2763 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
2765 __ENDTRY
2766 abort(); /* should not be reached */
2769 /***********************************************************************
2770 * RtlExitUserThread (NTDLL.@)
2772 void WINAPI RtlExitUserThread( ULONG status )
2774 if (!ntdll_get_thread_data()->exit_frame) exit_thread( status );
2775 call_thread_exit_func( status, exit_thread, ntdll_get_thread_data()->exit_frame );
2778 /***********************************************************************
2779 * abort_thread
2781 void abort_thread( int status )
2783 if (!ntdll_get_thread_data()->exit_frame) terminate_thread( status );
2784 call_thread_exit_func( status, terminate_thread, ntdll_get_thread_data()->exit_frame );
2787 /**********************************************************************
2788 * DbgBreakPoint (NTDLL.@)
2790 __ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
2792 /**********************************************************************
2793 * DbgUserBreakPoint (NTDLL.@)
2795 __ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
2797 /**********************************************************************
2798 * NtCurrentTeb (NTDLL.@)
2800 __ASM_STDCALL_FUNC( NtCurrentTeb, 0, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
2803 /**************************************************************************
2804 * _chkstk (NTDLL.@)
2806 __ASM_STDCALL_FUNC( _chkstk, 0,
2807 "negl %eax\n\t"
2808 "addl %esp,%eax\n\t"
2809 "xchgl %esp,%eax\n\t"
2810 "movl 0(%eax),%eax\n\t" /* copy return address from old location */
2811 "movl %eax,0(%esp)\n\t"
2812 "ret" )
2814 /**************************************************************************
2815 * _alloca_probe (NTDLL.@)
2817 __ASM_STDCALL_FUNC( _alloca_probe, 0,
2818 "negl %eax\n\t"
2819 "addl %esp,%eax\n\t"
2820 "xchgl %esp,%eax\n\t"
2821 "movl 0(%eax),%eax\n\t" /* copy return address from old location */
2822 "movl %eax,0(%esp)\n\t"
2823 "ret" )
2826 /**********************************************************************
2827 * EXC_CallHandler (internal)
2829 * Some exception handlers depend on EBP to have a fixed position relative to
2830 * the exception frame.
2831 * Shrinker depends on (*1) doing what it does,
2832 * (*2) being the exact instruction it is and (*3) beginning with 0x64
2833 * (i.e. the %fs prefix to the movl instruction). It also depends on the
2834 * function calling the handler having only 5 parameters (*4).
2836 __ASM_GLOBAL_FUNC( EXC_CallHandler,
2837 "pushl %ebp\n\t"
2838 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2839 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2840 "movl %esp,%ebp\n\t"
2841 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2842 "pushl %ebx\n\t"
2843 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2844 "movl 28(%ebp), %edx\n\t" /* ugly hack to pass the 6th param needed because of Shrinker */
2845 "pushl 24(%ebp)\n\t"
2846 "pushl 20(%ebp)\n\t"
2847 "pushl 16(%ebp)\n\t"
2848 "pushl 12(%ebp)\n\t"
2849 "pushl 8(%ebp)\n\t"
2850 "call " __ASM_NAME("call_exception_handler") "\n\t"
2851 "popl %ebx\n\t"
2852 __ASM_CFI(".cfi_same_value %ebx\n\t")
2853 "leave\n"
2854 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
2855 __ASM_CFI(".cfi_same_value %ebp\n\t")
2856 "ret" )
2857 __ASM_GLOBAL_FUNC(call_exception_handler,
2858 "pushl %ebp\n\t"
2859 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2860 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2861 "movl %esp,%ebp\n\t"
2862 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2863 "subl $12,%esp\n\t"
2864 "pushl 12(%ebp)\n\t" /* make any exceptions in this... */
2865 "pushl %edx\n\t" /* handler be handled by... */
2866 ".byte 0x64\n\t"
2867 "pushl (0)\n\t" /* nested_handler (passed in edx). */
2868 ".byte 0x64\n\t"
2869 "movl %esp,(0)\n\t" /* push the new exception frame onto the exception stack. */
2870 "pushl 20(%ebp)\n\t"
2871 "pushl 16(%ebp)\n\t"
2872 "pushl 12(%ebp)\n\t"
2873 "pushl 8(%ebp)\n\t"
2874 "movl 24(%ebp), %ecx\n\t" /* (*1) */
2875 "call *%ecx\n\t" /* call handler. (*2) */
2876 ".byte 0x64\n\t"
2877 "movl (0), %esp\n\t" /* restore previous... (*3) */
2878 ".byte 0x64\n\t"
2879 "popl (0)\n\t" /* exception frame. */
2880 "movl %ebp, %esp\n\t" /* restore saved stack, in case it was corrupted */
2881 "popl %ebp\n\t"
2882 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
2883 __ASM_CFI(".cfi_same_value %ebp\n\t")
2884 "ret $20" ) /* (*4) */
2886 #endif /* __i386__ */