mfplat: Read queue subscriber within the critical section.
[wine/zf.git] / dlls / ntdll / unix / signal_i386.c
blob655fd69ee73c026f62f84dff08b1e666a8f1a188
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 #if 0
22 #pragma makedep unix
23 #endif
25 #ifdef __i386__
27 #include "config.h"
28 #include "wine/port.h"
30 #include <errno.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <sys/types.h>
36 #include <assert.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #ifdef HAVE_SYS_PARAM_H
41 # include <sys/param.h>
42 #endif
43 #ifdef HAVE_SYSCALL_H
44 # include <syscall.h>
45 #else
46 # ifdef HAVE_SYS_SYSCALL_H
47 # include <sys/syscall.h>
48 # endif
49 #endif
50 #ifdef HAVE_SYS_SIGNAL_H
51 # include <sys/signal.h>
52 #endif
53 #ifdef HAVE_SYS_UCONTEXT_H
54 # include <sys/ucontext.h>
55 #endif
57 #include "ntstatus.h"
58 #define WIN32_NO_STATUS
59 #include "windef.h"
60 #include "winternl.h"
61 #include "ddk/wdm.h"
62 #include "wine/asm.h"
63 #include "wine/exception.h"
64 #include "unix_private.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(seh);
69 #undef ERR /* Solaris needs to define this */
71 /***********************************************************************
72 * signal context platform-specific definitions
75 #ifdef __linux__
77 #ifndef HAVE_SYS_UCONTEXT_H
79 enum
81 REG_GS, REG_FS, REG_ES, REG_DS, REG_EDI, REG_ESI, REG_EBP, REG_ESP,
82 REG_EBX, REG_EDX, REG_ECX, REG_EAX, REG_TRAPNO, REG_ERR, REG_EIP,
83 REG_CS, REG_EFL, REG_UESP, REG_SS, NGREG
86 typedef int greg_t;
87 typedef greg_t gregset_t[NGREG];
89 struct _libc_fpreg
91 unsigned short significand[4];
92 unsigned short exponent;
95 struct _libc_fpstate
97 unsigned long cw;
98 unsigned long sw;
99 unsigned long tag;
100 unsigned long ipoff;
101 unsigned long cssel;
102 unsigned long dataoff;
103 unsigned long datasel;
104 struct _libc_fpreg _st[8];
105 unsigned long status;
108 typedef struct _libc_fpstate* fpregset_t;
110 typedef struct
112 gregset_t gregs;
113 fpregset_t fpregs;
114 unsigned long oldmask;
115 unsigned long cr2;
116 } mcontext_t;
118 typedef struct ucontext
120 unsigned long uc_flags;
121 struct ucontext *uc_link;
122 stack_t uc_stack;
123 mcontext_t uc_mcontext;
124 sigset_t uc_sigmask;
125 } ucontext_t;
126 #endif /* HAVE_SYS_UCONTEXT_H */
128 #ifndef FP_XSTATE_MAGIC1
129 #define FP_XSTATE_MAGIC1 0x46505853
130 #endif
132 #define EAX_sig(context) ((context)->uc_mcontext.gregs[REG_EAX])
133 #define EBX_sig(context) ((context)->uc_mcontext.gregs[REG_EBX])
134 #define ECX_sig(context) ((context)->uc_mcontext.gregs[REG_ECX])
135 #define EDX_sig(context) ((context)->uc_mcontext.gregs[REG_EDX])
136 #define ESI_sig(context) ((context)->uc_mcontext.gregs[REG_ESI])
137 #define EDI_sig(context) ((context)->uc_mcontext.gregs[REG_EDI])
138 #define EBP_sig(context) ((context)->uc_mcontext.gregs[REG_EBP])
139 #define ESP_sig(context) ((context)->uc_mcontext.gregs[REG_ESP])
141 #define CS_sig(context) ((context)->uc_mcontext.gregs[REG_CS])
142 #define DS_sig(context) ((context)->uc_mcontext.gregs[REG_DS])
143 #define ES_sig(context) ((context)->uc_mcontext.gregs[REG_ES])
144 #define SS_sig(context) ((context)->uc_mcontext.gregs[REG_SS])
145 #define FS_sig(context) ((context)->uc_mcontext.gregs[REG_FS])
146 #define GS_sig(context) ((context)->uc_mcontext.gregs[REG_GS])
148 #define EFL_sig(context) ((context)->uc_mcontext.gregs[REG_EFL])
149 #define EIP_sig(context) ((context)->uc_mcontext.gregs[REG_EIP])
150 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[REG_TRAPNO])
151 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[REG_ERR])
153 #define FPU_sig(context) ((FLOATING_SAVE_AREA*)((context)->uc_mcontext.fpregs))
154 #define FPUX_sig(context) (FPU_sig(context) && !((context)->uc_mcontext.fpregs->status >> 16) ? (XSAVE_FORMAT *)(FPU_sig(context) + 1) : NULL)
155 #define XState_sig(fpu) (((unsigned int *)fpu->Reserved4)[12] == FP_XSTATE_MAGIC1 ? (XSTATE *)(fpu + 1) : NULL)
157 #ifdef __ANDROID__
158 /* custom signal restorer since we may have unmapped the one in vdso, and bionic doesn't check for that */
159 void rt_sigreturn(void);
160 __ASM_GLOBAL_FUNC( rt_sigreturn,
161 "movl $173,%eax\n\t" /* NR_rt_sigreturn */
162 "int $0x80" );
163 #endif
165 struct modify_ldt_s
167 unsigned int entry_number;
168 void *base_addr;
169 unsigned int limit;
170 unsigned int seg_32bit : 1;
171 unsigned int contents : 2;
172 unsigned int read_exec_only : 1;
173 unsigned int limit_in_pages : 1;
174 unsigned int seg_not_present : 1;
175 unsigned int usable : 1;
176 unsigned int garbage : 25;
179 static inline int modify_ldt( int func, struct modify_ldt_s *ptr, unsigned long count )
181 return syscall( 123 /* SYS_modify_ldt */, func, ptr, count );
184 static inline int set_thread_area( struct modify_ldt_s *ptr )
186 return syscall( 243 /* SYS_set_thread_area */, ptr );
189 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
191 #include <machine/trap.h>
192 #include <machine/segments.h>
193 #include <machine/sysarch.h>
195 #define EAX_sig(context) ((context)->uc_mcontext.mc_eax)
196 #define EBX_sig(context) ((context)->uc_mcontext.mc_ebx)
197 #define ECX_sig(context) ((context)->uc_mcontext.mc_ecx)
198 #define EDX_sig(context) ((context)->uc_mcontext.mc_edx)
199 #define ESI_sig(context) ((context)->uc_mcontext.mc_esi)
200 #define EDI_sig(context) ((context)->uc_mcontext.mc_edi)
201 #define EBP_sig(context) ((context)->uc_mcontext.mc_ebp)
203 #define CS_sig(context) ((context)->uc_mcontext.mc_cs)
204 #define DS_sig(context) ((context)->uc_mcontext.mc_ds)
205 #define ES_sig(context) ((context)->uc_mcontext.mc_es)
206 #define FS_sig(context) ((context)->uc_mcontext.mc_fs)
207 #define GS_sig(context) ((context)->uc_mcontext.mc_gs)
208 #define SS_sig(context) ((context)->uc_mcontext.mc_ss)
210 #define TRAP_sig(context) ((context)->uc_mcontext.mc_trapno)
211 #define ERROR_sig(context) ((context)->uc_mcontext.mc_err)
212 #define EFL_sig(context) ((context)->uc_mcontext.mc_eflags)
214 #define EIP_sig(context) ((context)->uc_mcontext.mc_eip)
215 #define ESP_sig(context) ((context)->uc_mcontext.mc_esp)
217 #define FPU_sig(context) NULL /* FIXME */
218 #define FPUX_sig(context) NULL /* FIXME */
219 #define XState_sig(context) NULL /* FIXME */
221 #elif defined (__OpenBSD__)
223 #include <machine/segments.h>
224 #include <machine/sysarch.h>
226 #define EAX_sig(context) ((context)->sc_eax)
227 #define EBX_sig(context) ((context)->sc_ebx)
228 #define ECX_sig(context) ((context)->sc_ecx)
229 #define EDX_sig(context) ((context)->sc_edx)
230 #define ESI_sig(context) ((context)->sc_esi)
231 #define EDI_sig(context) ((context)->sc_edi)
232 #define EBP_sig(context) ((context)->sc_ebp)
234 #define CS_sig(context) ((context)->sc_cs)
235 #define DS_sig(context) ((context)->sc_ds)
236 #define ES_sig(context) ((context)->sc_es)
237 #define FS_sig(context) ((context)->sc_fs)
238 #define GS_sig(context) ((context)->sc_gs)
239 #define SS_sig(context) ((context)->sc_ss)
241 #define TRAP_sig(context) ((context)->sc_trapno)
242 #define ERROR_sig(context) ((context)->sc_err)
243 #define EFL_sig(context) ((context)->sc_eflags)
245 #define EIP_sig(context) ((context)->sc_eip)
246 #define ESP_sig(context) ((context)->sc_esp)
248 #define FPU_sig(context) NULL /* FIXME */
249 #define FPUX_sig(context) NULL /* FIXME */
250 #define XState_sig(context) NULL /* FIXME */
252 #define T_MCHK T_MACHK
253 #define T_XMMFLT T_XFTRAP
255 #elif defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
257 #if defined(_SCO_DS) || defined(__sun)
258 #include <sys/regset.h>
259 #endif
261 #ifdef _SCO_DS
262 #define gregs regs
263 #endif
265 #define EAX_sig(context) ((context)->uc_mcontext.gregs[EAX])
266 #define EBX_sig(context) ((context)->uc_mcontext.gregs[EBX])
267 #define ECX_sig(context) ((context)->uc_mcontext.gregs[ECX])
268 #define EDX_sig(context) ((context)->uc_mcontext.gregs[EDX])
269 #define ESI_sig(context) ((context)->uc_mcontext.gregs[ESI])
270 #define EDI_sig(context) ((context)->uc_mcontext.gregs[EDI])
271 #define EBP_sig(context) ((context)->uc_mcontext.gregs[EBP])
273 #define CS_sig(context) ((context)->uc_mcontext.gregs[CS])
274 #define DS_sig(context) ((context)->uc_mcontext.gregs[DS])
275 #define ES_sig(context) ((context)->uc_mcontext.gregs[ES])
276 #define SS_sig(context) ((context)->uc_mcontext.gregs[SS])
278 #define FS_sig(context) ((context)->uc_mcontext.gregs[FS])
279 #define GS_sig(context) ((context)->uc_mcontext.gregs[GS])
281 #define EFL_sig(context) ((context)->uc_mcontext.gregs[EFL])
283 #define EIP_sig(context) ((context)->uc_mcontext.gregs[EIP])
284 #ifdef UESP
285 #define ESP_sig(context) ((context)->uc_mcontext.gregs[UESP])
286 #elif defined(R_ESP)
287 #define ESP_sig(context) ((context)->uc_mcontext.gregs[R_ESP])
288 #else
289 #define ESP_sig(context) ((context)->uc_mcontext.gregs[ESP])
290 #endif
291 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[ERR])
292 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[TRAPNO])
294 #define FPU_sig(context) NULL /* FIXME */
295 #define FPUX_sig(context) NULL /* FIXME */
296 #define XState_sig(context) NULL /* FIXME */
298 #elif defined (__APPLE__)
300 #include <i386/user_ldt.h>
302 /* work around silly renaming of struct members in OS X 10.5 */
303 #if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32)
304 #define EAX_sig(context) ((context)->uc_mcontext->__ss.__eax)
305 #define EBX_sig(context) ((context)->uc_mcontext->__ss.__ebx)
306 #define ECX_sig(context) ((context)->uc_mcontext->__ss.__ecx)
307 #define EDX_sig(context) ((context)->uc_mcontext->__ss.__edx)
308 #define ESI_sig(context) ((context)->uc_mcontext->__ss.__esi)
309 #define EDI_sig(context) ((context)->uc_mcontext->__ss.__edi)
310 #define EBP_sig(context) ((context)->uc_mcontext->__ss.__ebp)
311 #define CS_sig(context) ((context)->uc_mcontext->__ss.__cs)
312 #define DS_sig(context) ((context)->uc_mcontext->__ss.__ds)
313 #define ES_sig(context) ((context)->uc_mcontext->__ss.__es)
314 #define FS_sig(context) ((context)->uc_mcontext->__ss.__fs)
315 #define GS_sig(context) ((context)->uc_mcontext->__ss.__gs)
316 #define SS_sig(context) ((context)->uc_mcontext->__ss.__ss)
317 #define EFL_sig(context) ((context)->uc_mcontext->__ss.__eflags)
318 #define EIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__eip))
319 #define ESP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->__ss.__esp))
320 #define TRAP_sig(context) ((context)->uc_mcontext->__es.__trapno)
321 #define ERROR_sig(context) ((context)->uc_mcontext->__es.__err)
322 #define FPU_sig(context) NULL
323 #define FPUX_sig(context) ((XSAVE_FORMAT *)&(context)->uc_mcontext->__fs.__fpu_fcw)
324 #define XState_sig(context) NULL /* FIXME */
325 #else
326 #define EAX_sig(context) ((context)->uc_mcontext->ss.eax)
327 #define EBX_sig(context) ((context)->uc_mcontext->ss.ebx)
328 #define ECX_sig(context) ((context)->uc_mcontext->ss.ecx)
329 #define EDX_sig(context) ((context)->uc_mcontext->ss.edx)
330 #define ESI_sig(context) ((context)->uc_mcontext->ss.esi)
331 #define EDI_sig(context) ((context)->uc_mcontext->ss.edi)
332 #define EBP_sig(context) ((context)->uc_mcontext->ss.ebp)
333 #define CS_sig(context) ((context)->uc_mcontext->ss.cs)
334 #define DS_sig(context) ((context)->uc_mcontext->ss.ds)
335 #define ES_sig(context) ((context)->uc_mcontext->ss.es)
336 #define FS_sig(context) ((context)->uc_mcontext->ss.fs)
337 #define GS_sig(context) ((context)->uc_mcontext->ss.gs)
338 #define SS_sig(context) ((context)->uc_mcontext->ss.ss)
339 #define EFL_sig(context) ((context)->uc_mcontext->ss.eflags)
340 #define EIP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->ss.eip))
341 #define ESP_sig(context) (*((unsigned long*)&(context)->uc_mcontext->ss.esp))
342 #define TRAP_sig(context) ((context)->uc_mcontext->es.trapno)
343 #define ERROR_sig(context) ((context)->uc_mcontext->es.err)
344 #define FPU_sig(context) NULL
345 #define FPUX_sig(context) ((XSAVE_FORMAT *)&(context)->uc_mcontext->fs.fpu_fcw)
346 #define XState_sig(context) NULL /* FIXME */
347 #endif
349 #elif defined(__NetBSD__)
351 #include <machine/segments.h>
352 #include <machine/sysarch.h>
354 #define EAX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EAX])
355 #define EBX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EBX])
356 #define ECX_sig(context) ((context)->uc_mcontext.__gregs[_REG_ECX])
357 #define EDX_sig(context) ((context)->uc_mcontext.__gregs[_REG_EDX])
358 #define ESI_sig(context) ((context)->uc_mcontext.__gregs[_REG_ESI])
359 #define EDI_sig(context) ((context)->uc_mcontext.__gregs[_REG_EDI])
360 #define EBP_sig(context) ((context)->uc_mcontext.__gregs[_REG_EBP])
361 #define ESP_sig(context) _UC_MACHINE_SP(context)
363 #define CS_sig(context) ((context)->uc_mcontext.__gregs[_REG_CS])
364 #define DS_sig(context) ((context)->uc_mcontext.__gregs[_REG_DS])
365 #define ES_sig(context) ((context)->uc_mcontext.__gregs[_REG_ES])
366 #define SS_sig(context) ((context)->uc_mcontext.__gregs[_REG_SS])
367 #define FS_sig(context) ((context)->uc_mcontext.__gregs[_REG_FS])
368 #define GS_sig(context) ((context)->uc_mcontext.__gregs[_REG_GS])
370 #define EFL_sig(context) ((context)->uc_mcontext.__gregs[_REG_EFL])
371 #define EIP_sig(context) _UC_MACHINE_PC(context)
372 #define TRAP_sig(context) ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
373 #define ERROR_sig(context) ((context)->uc_mcontext.__gregs[_REG_ERR])
375 #define FPU_sig(context) NULL
376 #define FPUX_sig(context) ((XSAVE_FORMAT *)&((context)->uc_mcontext.__fpregs))
377 #define XState_sig(context) NULL /* FIXME */
379 #define T_MCHK T_MCA
380 #define T_XMMFLT T_XMM
382 #elif defined(__GNU__)
384 #include <mach/i386/mach_i386.h>
385 #include <mach/mach_traps.h>
387 #define EAX_sig(context) ((context)->uc_mcontext.gregs[REG_EAX])
388 #define EBX_sig(context) ((context)->uc_mcontext.gregs[REG_EBX])
389 #define ECX_sig(context) ((context)->uc_mcontext.gregs[REG_ECX])
390 #define EDX_sig(context) ((context)->uc_mcontext.gregs[REG_EDX])
391 #define ESI_sig(context) ((context)->uc_mcontext.gregs[REG_ESI])
392 #define EDI_sig(context) ((context)->uc_mcontext.gregs[REG_EDI])
393 #define EBP_sig(context) ((context)->uc_mcontext.gregs[REG_EBP])
394 #define ESP_sig(context) ((context)->uc_mcontext.gregs[REG_ESP])
396 #define CS_sig(context) ((context)->uc_mcontext.gregs[REG_CS])
397 #define DS_sig(context) ((context)->uc_mcontext.gregs[REG_DS])
398 #define ES_sig(context) ((context)->uc_mcontext.gregs[REG_ES])
399 #define SS_sig(context) ((context)->uc_mcontext.gregs[REG_SS])
400 #define FS_sig(context) ((context)->uc_mcontext.gregs[REG_FS])
401 #define GS_sig(context) ((context)->uc_mcontext.gregs[REG_GS])
403 #define EFL_sig(context) ((context)->uc_mcontext.gregs[REG_EFL])
404 #define EIP_sig(context) ((context)->uc_mcontext.gregs[REG_EIP])
405 #define TRAP_sig(context) ((context)->uc_mcontext.gregs[REG_TRAPNO])
406 #define ERROR_sig(context) ((context)->uc_mcontext.gregs[REG_ERR])
408 #define FPU_sig(context) ((FLOATING_SAVE_AREA *)&(context)->uc_mcontext.fpregs.fp_reg_set.fpchip_state)
409 #define FPUX_sig(context) NULL
410 #define XState_sig(context) NULL /* FIXME */
412 #else
413 #error You must define the signal context functions for your platform
414 #endif /* linux */
416 static ULONG first_ldt_entry = 32;
418 enum i386_trap_code
420 #if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
421 TRAP_x86_DIVIDE = T_DIVIDE, /* Division by zero exception */
422 TRAP_x86_TRCTRAP = T_TRCTRAP, /* Single-step exception */
423 TRAP_x86_NMI = T_NMI, /* NMI interrupt */
424 TRAP_x86_BPTFLT = T_BPTFLT, /* Breakpoint exception */
425 TRAP_x86_OFLOW = T_OFLOW, /* Overflow exception */
426 TRAP_x86_BOUND = T_BOUND, /* Bound range exception */
427 TRAP_x86_PRIVINFLT = T_PRIVINFLT, /* Invalid opcode exception */
428 TRAP_x86_DNA = T_DNA, /* Device not available exception */
429 TRAP_x86_DOUBLEFLT = T_DOUBLEFLT, /* Double fault exception */
430 TRAP_x86_FPOPFLT = T_FPOPFLT, /* Coprocessor segment overrun */
431 TRAP_x86_TSSFLT = T_TSSFLT, /* Invalid TSS exception */
432 TRAP_x86_SEGNPFLT = T_SEGNPFLT, /* Segment not present exception */
433 TRAP_x86_STKFLT = T_STKFLT, /* Stack fault */
434 TRAP_x86_PROTFLT = T_PROTFLT, /* General protection fault */
435 TRAP_x86_PAGEFLT = T_PAGEFLT, /* Page fault */
436 TRAP_x86_ARITHTRAP = T_ARITHTRAP, /* Floating point exception */
437 TRAP_x86_ALIGNFLT = T_ALIGNFLT, /* Alignment check exception */
438 TRAP_x86_MCHK = T_MCHK, /* Machine check exception */
439 TRAP_x86_CACHEFLT = T_XMMFLT /* Cache flush exception */
440 #else
441 TRAP_x86_DIVIDE = 0, /* Division by zero exception */
442 TRAP_x86_TRCTRAP = 1, /* Single-step exception */
443 TRAP_x86_NMI = 2, /* NMI interrupt */
444 TRAP_x86_BPTFLT = 3, /* Breakpoint exception */
445 TRAP_x86_OFLOW = 4, /* Overflow exception */
446 TRAP_x86_BOUND = 5, /* Bound range exception */
447 TRAP_x86_PRIVINFLT = 6, /* Invalid opcode exception */
448 TRAP_x86_DNA = 7, /* Device not available exception */
449 TRAP_x86_DOUBLEFLT = 8, /* Double fault exception */
450 TRAP_x86_FPOPFLT = 9, /* Coprocessor segment overrun */
451 TRAP_x86_TSSFLT = 10, /* Invalid TSS exception */
452 TRAP_x86_SEGNPFLT = 11, /* Segment not present exception */
453 TRAP_x86_STKFLT = 12, /* Stack fault */
454 TRAP_x86_PROTFLT = 13, /* General protection fault */
455 TRAP_x86_PAGEFLT = 14, /* Page fault */
456 TRAP_x86_ARITHTRAP = 16, /* Floating point exception */
457 TRAP_x86_ALIGNFLT = 17, /* Alignment check exception */
458 TRAP_x86_MCHK = 18, /* Machine check exception */
459 TRAP_x86_CACHEFLT = 19 /* SIMD exception (via SIGFPE) if CPU is SSE capable
460 otherwise Cache flush exception (via SIGSEV) */
461 #endif
464 struct syscall_xsave
466 union
468 XSAVE_FORMAT xsave;
469 FLOATING_SAVE_AREA fsave;
470 } u;
471 struct
473 ULONG64 mask;
474 ULONG64 compaction_mask;
475 ULONG64 reserved[6];
476 M128A ymm_high[8];
477 } xstate;
480 C_ASSERT( sizeof(struct syscall_xsave) == 0x2c0 );
482 struct syscall_frame
484 DWORD eflags; /* 00 */
485 DWORD eip; /* 04 */
486 DWORD esp; /* 08 */
487 WORD cs; /* 0c */
488 WORD ss; /* 0e */
489 WORD ds; /* 10 */
490 WORD es; /* 12 */
491 WORD fs; /* 14 */
492 WORD gs; /* 16 */
493 DWORD eax; /* 18 */
494 DWORD ebx; /* 1c */
495 DWORD ecx; /* 20 */
496 DWORD edx; /* 24 */
497 DWORD edi; /* 28 */
498 DWORD esi; /* 2c */
499 DWORD ebp; /* 30 */
502 C_ASSERT( sizeof(struct syscall_frame) == 0x34 );
504 struct x86_thread_data
506 DWORD fs; /* 1d4 TEB selector */
507 DWORD gs; /* 1d8 libc selector; update winebuild if you move this! */
508 DWORD dr0; /* 1dc debug registers */
509 DWORD dr1; /* 1e0 */
510 DWORD dr2; /* 1e4 */
511 DWORD dr3; /* 1e8 */
512 DWORD dr6; /* 1ec */
513 DWORD dr7; /* 1f0 */
514 void *exit_frame; /* 1f4 exit frame pointer */
515 struct syscall_frame *syscall_frame; /* 1f8 frame pointer on syscall entry */
518 C_ASSERT( sizeof(struct x86_thread_data) <= sizeof(((struct ntdll_thread_data *)0)->cpu_data) );
519 C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, gs ) == 0x1d8 );
520 C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, exit_frame ) == 0x1f4 );
521 C_ASSERT( offsetof( TEB, GdiTebBatch ) + offsetof( struct x86_thread_data, syscall_frame ) == 0x1f8 );
523 static void *syscall_dispatcher;
525 static inline struct x86_thread_data *x86_thread_data(void)
527 return (struct x86_thread_data *)ntdll_get_thread_data()->cpu_data;
530 void *get_syscall_frame(void)
532 return x86_thread_data()->syscall_frame;
535 void set_syscall_frame(void *frame)
537 x86_thread_data()->syscall_frame = frame;
540 static struct syscall_xsave *get_syscall_xsave( struct syscall_frame *frame )
542 return (struct syscall_xsave *)((ULONG_PTR)((struct syscall_xsave *)frame - 1) & ~63);
545 static inline WORD get_cs(void) { WORD res; __asm__( "movw %%cs,%0" : "=r" (res) ); return res; }
546 static inline WORD get_ds(void) { WORD res; __asm__( "movw %%ds,%0" : "=r" (res) ); return res; }
547 static inline WORD get_fs(void) { WORD res; __asm__( "movw %%fs,%0" : "=r" (res) ); return res; }
548 static inline WORD get_gs(void) { WORD res; __asm__( "movw %%gs,%0" : "=r" (res) ); return res; }
549 static inline void set_fs( WORD val ) { __asm__( "mov %0,%%fs" :: "r" (val)); }
550 static inline void set_gs( WORD val ) { __asm__( "mov %0,%%gs" :: "r" (val)); }
553 /***********************************************************************
554 * unwind_builtin_dll
556 NTSTATUS CDECL unwind_builtin_dll( ULONG type, struct _DISPATCHER_CONTEXT *dispatch, CONTEXT *context )
558 return STATUS_UNSUCCESSFUL;
562 /***********************************************************************
563 * is_gdt_sel
565 static inline int is_gdt_sel( WORD sel )
567 return !(sel & 4);
571 /***********************************************************************
572 * ldt_is_system
574 static inline int ldt_is_system( WORD sel )
576 return is_gdt_sel( sel ) || ((sel >> 3) < first_ldt_entry);
580 /***********************************************************************
581 * get_current_teb
583 * Get the current teb based on the stack pointer.
585 static inline TEB *get_current_teb(void)
587 unsigned long esp;
588 __asm__("movl %%esp,%0" : "=g" (esp) );
589 return (TEB *)((esp & ~signal_stack_mask) + teb_offset);
593 #ifdef __sun
595 /* We have to workaround two Solaris breakages:
596 * - Solaris doesn't restore %ds and %es before calling the signal handler so exceptions in 16-bit
597 * code crash badly.
598 * - Solaris inserts a libc trampoline to call our handler, but the trampoline expects that registers
599 * are setup correctly. So we need to insert our own trampoline below the libc trampoline to set %gs.
602 extern int sigaction_syscall( int sig, const struct sigaction *new, struct sigaction *old );
603 __ASM_GLOBAL_FUNC( sigaction_syscall,
604 "movl $0x62,%eax\n\t"
605 "int $0x91\n\t"
606 "ret" )
608 /* assume the same libc handler is used for all signals */
609 static void (*libc_sigacthandler)( int signal, siginfo_t *siginfo, void *context );
611 static void wine_sigacthandler( int signal, siginfo_t *siginfo, void *sigcontext )
613 struct x86_thread_data *thread_data;
615 __asm__ __volatile__("mov %ss,%ax; mov %ax,%ds; mov %ax,%es");
617 thread_data = (struct x86_thread_data *)get_current_teb()->GdiTebBatch;
618 set_fs( thread_data->fs );
619 set_gs( thread_data->gs );
621 libc_sigacthandler( signal, siginfo, sigcontext );
624 static int solaris_sigaction( int sig, const struct sigaction *new, struct sigaction *old )
626 struct sigaction real_act;
628 if (sigaction( sig, new, old ) == -1) return -1;
630 /* retrieve the real handler and flags with a direct syscall */
631 sigaction_syscall( sig, NULL, &real_act );
632 libc_sigacthandler = real_act.sa_sigaction;
633 real_act.sa_sigaction = wine_sigacthandler;
634 sigaction_syscall( sig, &real_act, NULL );
635 return 0;
637 #define sigaction(sig,new,old) solaris_sigaction(sig,new,old)
639 #endif
641 extern void clear_alignment_flag(void);
642 __ASM_GLOBAL_FUNC( clear_alignment_flag,
643 "pushfl\n\t"
644 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
645 "andl $~0x40000,(%esp)\n\t"
646 "popfl\n\t"
647 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
648 "ret" )
651 /***********************************************************************
652 * init_handler
654 * Handler initialization when the full context is not needed.
655 * Return the stack pointer to use for pushing the exception data.
657 static inline void *init_handler( const ucontext_t *sigcontext )
659 TEB *teb = get_current_teb();
661 clear_alignment_flag();
663 #ifndef __sun /* see above for Solaris handling */
665 struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
666 set_fs( thread_data->fs );
667 set_gs( thread_data->gs );
669 #endif
671 if (!ldt_is_system(CS_sig(sigcontext)) || !ldt_is_system(SS_sig(sigcontext))) /* 16-bit mode */
674 * Win16 or DOS protected mode. Note that during switch
675 * from 16-bit mode to linear mode, CS may be set to system
676 * segment before FS is restored. Fortunately, in this case
677 * SS is still non-system segment. This is why both CS and SS
678 * are checked.
680 return teb->SystemReserved1[0];
682 return (void *)(ESP_sig(sigcontext) & ~3);
686 /***********************************************************************
687 * save_fpu
689 * Save the thread FPU context.
691 static inline void save_fpu( CONTEXT *context )
693 struct
695 DWORD ControlWord;
696 DWORD StatusWord;
697 DWORD TagWord;
698 DWORD ErrorOffset;
699 DWORD ErrorSelector;
700 DWORD DataOffset;
701 DWORD DataSelector;
703 float_status;
705 context->ContextFlags |= CONTEXT_FLOATING_POINT;
706 __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
708 /* Reset unmasked exceptions status to avoid firing an exception. */
709 memcpy(&float_status, &context->FloatSave, sizeof(float_status));
710 float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
712 __asm__ __volatile__( "fldenv %0" : : "m" (float_status) );
716 /***********************************************************************
717 * restore_fpu
719 * Restore the x87 FPU context
721 static inline void restore_fpu( const CONTEXT *context )
723 FLOATING_SAVE_AREA float_status = context->FloatSave;
724 /* reset the current interrupt status */
725 float_status.StatusWord &= float_status.ControlWord | 0xffffff80;
726 __asm__ __volatile__( "frstor %0; fwait" : : "m" (float_status) );
730 /***********************************************************************
731 * fpux_to_fpu
733 * Build a standard FPU context from an extended one.
735 static void fpux_to_fpu( FLOATING_SAVE_AREA *fpu, const XSAVE_FORMAT *fpux )
737 unsigned int i, tag, stack_top;
739 fpu->ControlWord = fpux->ControlWord | 0xffff0000;
740 fpu->StatusWord = fpux->StatusWord | 0xffff0000;
741 fpu->ErrorOffset = fpux->ErrorOffset;
742 fpu->ErrorSelector = fpux->ErrorSelector | (fpux->ErrorOpcode << 16);
743 fpu->DataOffset = fpux->DataOffset;
744 fpu->DataSelector = fpux->DataSelector;
745 fpu->Cr0NpxState = fpux->StatusWord | 0xffff0000;
747 stack_top = (fpux->StatusWord >> 11) & 7;
748 fpu->TagWord = 0xffff0000;
749 for (i = 0; i < 8; i++)
751 memcpy( &fpu->RegisterArea[10 * i], &fpux->FloatRegisters[i], 10 );
752 if (!(fpux->TagWord & (1 << i))) tag = 3; /* empty */
753 else
755 const M128A *reg = &fpux->FloatRegisters[(i - stack_top) & 7];
756 if ((reg->High & 0x7fff) == 0x7fff) /* exponent all ones */
758 tag = 2; /* special */
760 else if (!(reg->High & 0x7fff)) /* exponent all zeroes */
762 if (reg->Low) tag = 2; /* special */
763 else tag = 1; /* zero */
765 else
767 if (reg->Low >> 63) tag = 0; /* valid */
768 else tag = 2; /* special */
771 fpu->TagWord |= tag << (2 * i);
776 /***********************************************************************
777 * fpu_to_fpux
779 * Fill extended FPU context from standard one.
781 static void fpu_to_fpux( XSAVE_FORMAT *fpux, const FLOATING_SAVE_AREA *fpu )
783 unsigned int i;
785 fpux->ControlWord = fpu->ControlWord;
786 fpux->StatusWord = fpu->StatusWord;
787 fpux->ErrorOffset = fpu->ErrorOffset;
788 fpux->ErrorSelector = fpu->ErrorSelector;
789 fpux->ErrorOpcode = fpu->ErrorSelector >> 16;
790 fpux->DataOffset = fpu->DataOffset;
791 fpux->DataSelector = fpu->DataSelector;
792 fpux->TagWord = 0;
793 for (i = 0; i < 8; i++)
795 if (((fpu->TagWord >> (i * 2)) & 3) != 3)
796 fpux->TagWord |= 1 << i;
797 memcpy( &fpux->FloatRegisters[i], &fpu->RegisterArea[10 * i], 10 );
802 /***********************************************************************
803 * save_context
805 * Build a context structure from the signal info.
807 static inline void save_context( struct xcontext *xcontext, const ucontext_t *sigcontext )
809 FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
810 XSAVE_FORMAT *fpux = FPUX_sig(sigcontext);
811 CONTEXT *context = &xcontext->c;
813 memset(context, 0, sizeof(*context));
814 context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
815 context->Eax = EAX_sig(sigcontext);
816 context->Ebx = EBX_sig(sigcontext);
817 context->Ecx = ECX_sig(sigcontext);
818 context->Edx = EDX_sig(sigcontext);
819 context->Esi = ESI_sig(sigcontext);
820 context->Edi = EDI_sig(sigcontext);
821 context->Ebp = EBP_sig(sigcontext);
822 context->EFlags = EFL_sig(sigcontext);
823 context->Eip = EIP_sig(sigcontext);
824 context->Esp = ESP_sig(sigcontext);
825 context->SegCs = LOWORD(CS_sig(sigcontext));
826 context->SegDs = LOWORD(DS_sig(sigcontext));
827 context->SegEs = LOWORD(ES_sig(sigcontext));
828 context->SegFs = LOWORD(FS_sig(sigcontext));
829 context->SegGs = LOWORD(GS_sig(sigcontext));
830 context->SegSs = LOWORD(SS_sig(sigcontext));
831 context->Dr0 = x86_thread_data()->dr0;
832 context->Dr1 = x86_thread_data()->dr1;
833 context->Dr2 = x86_thread_data()->dr2;
834 context->Dr3 = x86_thread_data()->dr3;
835 context->Dr6 = x86_thread_data()->dr6;
836 context->Dr7 = x86_thread_data()->dr7;
838 if (fpu)
840 context->ContextFlags |= CONTEXT_FLOATING_POINT;
841 context->FloatSave = *fpu;
843 if (fpux)
845 XSTATE *xs;
847 context->ContextFlags |= CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
848 memcpy( context->ExtendedRegisters, fpux, sizeof(*fpux) );
849 if (!fpu) fpux_to_fpu( &context->FloatSave, fpux );
850 if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xs = XState_sig(fpux)))
852 context_init_xstate( context, xs );
853 xcontext->host_compaction_mask = xs->CompactionMask;
856 if (!fpu && !fpux) save_fpu( context );
860 /***********************************************************************
861 * restore_context
863 * Restore the signal info from the context.
865 static inline void restore_context( const struct xcontext *xcontext, ucontext_t *sigcontext )
867 FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
868 XSAVE_FORMAT *fpux = FPUX_sig(sigcontext);
869 const CONTEXT *context = &xcontext->c;
871 x86_thread_data()->dr0 = context->Dr0;
872 x86_thread_data()->dr1 = context->Dr1;
873 x86_thread_data()->dr2 = context->Dr2;
874 x86_thread_data()->dr3 = context->Dr3;
875 x86_thread_data()->dr6 = context->Dr6;
876 x86_thread_data()->dr7 = context->Dr7;
877 EAX_sig(sigcontext) = context->Eax;
878 EBX_sig(sigcontext) = context->Ebx;
879 ECX_sig(sigcontext) = context->Ecx;
880 EDX_sig(sigcontext) = context->Edx;
881 ESI_sig(sigcontext) = context->Esi;
882 EDI_sig(sigcontext) = context->Edi;
883 EBP_sig(sigcontext) = context->Ebp;
884 EFL_sig(sigcontext) = context->EFlags;
885 EIP_sig(sigcontext) = context->Eip;
886 ESP_sig(sigcontext) = context->Esp;
887 CS_sig(sigcontext) = context->SegCs;
888 DS_sig(sigcontext) = context->SegDs;
889 ES_sig(sigcontext) = context->SegEs;
890 FS_sig(sigcontext) = context->SegFs;
891 GS_sig(sigcontext) = context->SegGs;
892 SS_sig(sigcontext) = context->SegSs;
894 if (fpu) *fpu = context->FloatSave;
895 if (fpux)
897 XSTATE *src_xs, *dst_xs;
899 memcpy( fpux, context->ExtendedRegisters, sizeof(*fpux) );
901 if ((dst_xs = XState_sig(fpux)) && (src_xs = xstate_from_context( context )))
903 memcpy( &dst_xs->YmmContext, &src_xs->YmmContext, sizeof(dst_xs->YmmContext) );
904 dst_xs->Mask |= src_xs->Mask;
905 dst_xs->CompactionMask = xcontext->host_compaction_mask;
908 if (!fpu && !fpux) restore_fpu( context );
912 /***********************************************************************
913 * set_full_cpu_context
915 * Set the new CPU context.
917 extern void set_full_cpu_context(void);
918 __ASM_GLOBAL_FUNC( set_full_cpu_context,
919 "movl %fs:0x1f8,%ecx\n\t"
920 "movl $0,%fs:0x1f8\n\t" /* x86_thread_data()->syscall_frame = NULL */
921 "movw 0x16(%ecx),%gs\n\t" /* SegGs */
922 "movw 0x14(%ecx),%fs\n\t" /* SegFs */
923 "movw 0x12(%ecx),%es\n\t" /* SegEs */
924 "movl 0x1c(%ecx),%ebx\n\t" /* Ebx */
925 "movl 0x28(%ecx),%edi\n\t" /* Edi */
926 "movl 0x2c(%ecx),%esi\n\t" /* Esi */
927 "movl 0x30(%ecx),%ebp\n\t" /* Ebp */
928 "movw %ss,%ax\n\t"
929 "cmpw 0x0e(%ecx),%ax\n\t" /* SegSs */
930 "jne 1f\n\t"
931 /* As soon as we have switched stacks the context structure could
932 * be invalid (when signal handlers are executed for example). Copy
933 * values on the target stack before changing ESP. */
934 "movl 0x08(%ecx),%eax\n\t" /* Esp */
935 "leal -4*4(%eax),%eax\n\t"
936 "movl (%ecx),%edx\n\t" /* EFlags */
937 "movl %edx,3*4(%eax)\n\t"
938 "movl 0x0c(%ecx),%edx\n\t" /* SegCs */
939 "movl %edx,2*4(%eax)\n\t"
940 "movl 0x04(%ecx),%edx\n\t" /* Eip */
941 "movl %edx,1*4(%eax)\n\t"
942 "movl 0x18(%ecx),%edx\n\t" /* Eax */
943 "movl %edx,0*4(%eax)\n\t"
944 "pushl 0x10(%ecx)\n\t" /* SegDs */
945 "movl 0x24(%ecx),%edx\n\t" /* Edx */
946 "movl 0x20(%ecx),%ecx\n\t" /* Ecx */
947 "popl %ds\n\t"
948 "movl %eax,%esp\n\t"
949 "popl %eax\n\t"
950 "iret\n"
951 /* Restore the context when the stack segment changes. We can't use
952 * the same code as above because we do not know if the stack segment
953 * is 16 or 32 bit, and 'movl' will throw an exception when we try to
954 * access memory above the limit. */
955 "1:\n\t"
956 "movl 0x24(%ecx),%edx\n\t" /* Edx */
957 "movl 0x18(%ecx),%eax\n\t" /* Eax */
958 "movw 0x0e(%ecx),%ss\n\t" /* SegSs */
959 "movl 0x08(%ecx),%esp\n\t" /* Esp */
960 "pushl 0x00(%ecx)\n\t" /* EFlags */
961 "pushl 0x0c(%ecx)\n\t" /* SegCs */
962 "pushl 0x04(%ecx)\n\t" /* Eip */
963 "pushl 0x10(%ecx)\n\t" /* SegDs */
964 "movl 0x20(%ecx),%ecx\n\t" /* Ecx */
965 "popl %ds\n\t"
966 "iret" )
969 /***********************************************************************
970 * signal_restore_full_cpu_context
972 * Restore full context from syscall frame
974 void signal_restore_full_cpu_context(void)
976 struct syscall_xsave *xsave = get_syscall_xsave( get_syscall_frame() );
978 if (cpu_info.FeatureSet & CPU_FEATURE_XSAVE)
980 __asm__ volatile( "xrstor %0" : : "m"(*xsave), "a" (7), "d" (0) );
982 else if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
984 __asm__ volatile( "fxrstor %0" : : "m"(xsave->u.xsave) );
986 else
988 __asm__ volatile( "frstor %0; fwait" : : "m" (xsave->u.fsave) );
990 set_full_cpu_context();
994 /***********************************************************************
995 * get_server_context_flags
997 * Convert CPU-specific flags to generic server flags
999 static unsigned int get_server_context_flags( DWORD flags )
1001 unsigned int ret = 0;
1003 flags &= ~CONTEXT_i386; /* get rid of CPU id */
1004 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
1005 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
1006 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
1007 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
1008 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
1009 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
1010 if (flags & CONTEXT_XSTATE) ret |= SERVER_CTX_YMM_REGISTERS;
1011 return ret;
1015 /***********************************************************************
1016 * context_to_server
1018 * Convert a register context to the server format.
1020 NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
1022 DWORD flags = from->ContextFlags & ~CONTEXT_i386; /* get rid of CPU id */
1024 memset( to, 0, sizeof(*to) );
1025 to->cpu = CPU_x86;
1027 if (flags & CONTEXT_CONTROL)
1029 to->flags |= SERVER_CTX_CONTROL;
1030 to->ctl.i386_regs.ebp = from->Ebp;
1031 to->ctl.i386_regs.esp = from->Esp;
1032 to->ctl.i386_regs.eip = from->Eip;
1033 to->ctl.i386_regs.cs = from->SegCs;
1034 to->ctl.i386_regs.ss = from->SegSs;
1035 to->ctl.i386_regs.eflags = from->EFlags;
1037 if (flags & CONTEXT_INTEGER)
1039 to->flags |= SERVER_CTX_INTEGER;
1040 to->integer.i386_regs.eax = from->Eax;
1041 to->integer.i386_regs.ebx = from->Ebx;
1042 to->integer.i386_regs.ecx = from->Ecx;
1043 to->integer.i386_regs.edx = from->Edx;
1044 to->integer.i386_regs.esi = from->Esi;
1045 to->integer.i386_regs.edi = from->Edi;
1047 if (flags & CONTEXT_SEGMENTS)
1049 to->flags |= SERVER_CTX_SEGMENTS;
1050 to->seg.i386_regs.ds = from->SegDs;
1051 to->seg.i386_regs.es = from->SegEs;
1052 to->seg.i386_regs.fs = from->SegFs;
1053 to->seg.i386_regs.gs = from->SegGs;
1055 if (flags & CONTEXT_FLOATING_POINT)
1057 to->flags |= SERVER_CTX_FLOATING_POINT;
1058 to->fp.i386_regs.ctrl = from->FloatSave.ControlWord;
1059 to->fp.i386_regs.status = from->FloatSave.StatusWord;
1060 to->fp.i386_regs.tag = from->FloatSave.TagWord;
1061 to->fp.i386_regs.err_off = from->FloatSave.ErrorOffset;
1062 to->fp.i386_regs.err_sel = from->FloatSave.ErrorSelector;
1063 to->fp.i386_regs.data_off = from->FloatSave.DataOffset;
1064 to->fp.i386_regs.data_sel = from->FloatSave.DataSelector;
1065 to->fp.i386_regs.cr0npx = from->FloatSave.Cr0NpxState;
1066 memcpy( to->fp.i386_regs.regs, from->FloatSave.RegisterArea, sizeof(to->fp.i386_regs.regs) );
1068 if (flags & CONTEXT_DEBUG_REGISTERS)
1070 to->flags |= SERVER_CTX_DEBUG_REGISTERS;
1071 to->debug.i386_regs.dr0 = from->Dr0;
1072 to->debug.i386_regs.dr1 = from->Dr1;
1073 to->debug.i386_regs.dr2 = from->Dr2;
1074 to->debug.i386_regs.dr3 = from->Dr3;
1075 to->debug.i386_regs.dr6 = from->Dr6;
1076 to->debug.i386_regs.dr7 = from->Dr7;
1078 if (flags & CONTEXT_EXTENDED_REGISTERS)
1080 to->flags |= SERVER_CTX_EXTENDED_REGISTERS;
1081 memcpy( to->ext.i386_regs, from->ExtendedRegisters, sizeof(to->ext.i386_regs) );
1083 xstate_to_server( to, xstate_from_context( from ) );
1084 return STATUS_SUCCESS;
1088 /***********************************************************************
1089 * context_from_server
1091 * Convert a register context from the server format.
1093 NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
1095 if (from->cpu != CPU_x86) return STATUS_INVALID_PARAMETER;
1097 to->ContextFlags = CONTEXT_i386 | (to->ContextFlags & 0x40);
1098 if (from->flags & SERVER_CTX_CONTROL)
1100 to->ContextFlags |= CONTEXT_CONTROL;
1101 to->Ebp = from->ctl.i386_regs.ebp;
1102 to->Esp = from->ctl.i386_regs.esp;
1103 to->Eip = from->ctl.i386_regs.eip;
1104 to->SegCs = from->ctl.i386_regs.cs;
1105 to->SegSs = from->ctl.i386_regs.ss;
1106 to->EFlags = from->ctl.i386_regs.eflags;
1108 if (from->flags & SERVER_CTX_INTEGER)
1110 to->ContextFlags |= CONTEXT_INTEGER;
1111 to->Eax = from->integer.i386_regs.eax;
1112 to->Ebx = from->integer.i386_regs.ebx;
1113 to->Ecx = from->integer.i386_regs.ecx;
1114 to->Edx = from->integer.i386_regs.edx;
1115 to->Esi = from->integer.i386_regs.esi;
1116 to->Edi = from->integer.i386_regs.edi;
1118 if (from->flags & SERVER_CTX_SEGMENTS)
1120 to->ContextFlags |= CONTEXT_SEGMENTS;
1121 to->SegDs = from->seg.i386_regs.ds;
1122 to->SegEs = from->seg.i386_regs.es;
1123 to->SegFs = from->seg.i386_regs.fs;
1124 to->SegGs = from->seg.i386_regs.gs;
1126 if (from->flags & SERVER_CTX_FLOATING_POINT)
1128 to->ContextFlags |= CONTEXT_FLOATING_POINT;
1129 to->FloatSave.ControlWord = from->fp.i386_regs.ctrl;
1130 to->FloatSave.StatusWord = from->fp.i386_regs.status;
1131 to->FloatSave.TagWord = from->fp.i386_regs.tag;
1132 to->FloatSave.ErrorOffset = from->fp.i386_regs.err_off;
1133 to->FloatSave.ErrorSelector = from->fp.i386_regs.err_sel;
1134 to->FloatSave.DataOffset = from->fp.i386_regs.data_off;
1135 to->FloatSave.DataSelector = from->fp.i386_regs.data_sel;
1136 to->FloatSave.Cr0NpxState = from->fp.i386_regs.cr0npx;
1137 memcpy( to->FloatSave.RegisterArea, from->fp.i386_regs.regs, sizeof(to->FloatSave.RegisterArea) );
1139 if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
1141 to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
1142 to->Dr0 = from->debug.i386_regs.dr0;
1143 to->Dr1 = from->debug.i386_regs.dr1;
1144 to->Dr2 = from->debug.i386_regs.dr2;
1145 to->Dr3 = from->debug.i386_regs.dr3;
1146 to->Dr6 = from->debug.i386_regs.dr6;
1147 to->Dr7 = from->debug.i386_regs.dr7;
1149 if (from->flags & SERVER_CTX_EXTENDED_REGISTERS)
1151 to->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
1152 memcpy( to->ExtendedRegisters, from->ext.i386_regs, sizeof(to->ExtendedRegisters) );
1154 xstate_from_server( xstate_from_context( to ), from );
1155 return STATUS_SUCCESS;
1159 /***********************************************************************
1160 * NtSetContextThread (NTDLL.@)
1161 * ZwSetContextThread (NTDLL.@)
1163 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
1165 NTSTATUS ret = STATUS_SUCCESS;
1166 struct syscall_frame *frame = x86_thread_data()->syscall_frame;
1167 DWORD flags = context->ContextFlags & ~CONTEXT_i386;
1168 BOOL self = (handle == GetCurrentThread());
1169 XSTATE *xs;
1171 /* debug registers require a server call */
1172 if (self && (flags & CONTEXT_DEBUG_REGISTERS))
1173 self = (x86_thread_data()->dr0 == context->Dr0 &&
1174 x86_thread_data()->dr1 == context->Dr1 &&
1175 x86_thread_data()->dr2 == context->Dr2 &&
1176 x86_thread_data()->dr3 == context->Dr3 &&
1177 x86_thread_data()->dr6 == context->Dr6 &&
1178 x86_thread_data()->dr7 == context->Dr7);
1180 if (!self)
1182 context_t server_context;
1183 context_to_server( &server_context, context );
1184 ret = set_thread_context( handle, &server_context, &self );
1185 if (ret || !self) return ret;
1186 if (flags & CONTEXT_DEBUG_REGISTERS)
1188 x86_thread_data()->dr0 = context->Dr0;
1189 x86_thread_data()->dr1 = context->Dr1;
1190 x86_thread_data()->dr2 = context->Dr2;
1191 x86_thread_data()->dr3 = context->Dr3;
1192 x86_thread_data()->dr6 = context->Dr6;
1193 x86_thread_data()->dr7 = context->Dr7;
1197 if (flags & CONTEXT_INTEGER)
1199 frame->eax = context->Eax;
1200 frame->ebx = context->Ebx;
1201 frame->ecx = context->Ecx;
1202 frame->edx = context->Edx;
1203 frame->esi = context->Esi;
1204 frame->edi = context->Edi;
1206 if (flags & CONTEXT_CONTROL)
1208 frame->esp = context->Esp;
1209 frame->ebp = context->Ebp;
1210 frame->eip = context->Eip;
1211 frame->eflags = context->EFlags;
1212 frame->cs = context->SegCs;
1213 frame->ss = context->SegSs;
1215 if (flags & CONTEXT_SEGMENTS)
1217 frame->ds = context->SegDs;
1218 frame->es = context->SegEs;
1219 frame->fs = context->SegFs;
1220 frame->gs = context->SegGs;
1222 if (flags & CONTEXT_EXTENDED_REGISTERS)
1224 struct syscall_xsave *xsave = get_syscall_xsave( frame );
1225 memcpy( &xsave->u.xsave, context->ExtendedRegisters, sizeof(xsave->u.xsave) );
1226 /* reset the current interrupt status */
1227 xsave->u.xsave.StatusWord &= xsave->u.xsave.ControlWord | 0xff80;
1228 xsave->xstate.mask |= XSTATE_MASK_LEGACY;
1230 else if (flags & CONTEXT_FLOATING_POINT)
1232 struct syscall_xsave *xsave = get_syscall_xsave( frame );
1233 if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
1235 fpu_to_fpux( &xsave->u.xsave, &context->FloatSave );
1237 else
1239 xsave->u.fsave = context->FloatSave;
1241 xsave->xstate.mask |= XSTATE_MASK_LEGACY_FLOATING_POINT;
1243 if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xs = xstate_from_context( context )))
1245 struct syscall_xsave *xsave = get_syscall_xsave( frame );
1246 CONTEXT_EX *context_ex = (CONTEXT_EX *)(context + 1);
1248 if (context_ex->XState.Length < offsetof(XSTATE, YmmContext)
1249 || context_ex->XState.Length > sizeof(XSTATE))
1250 return STATUS_INVALID_PARAMETER;
1252 if (xs->Mask & XSTATE_MASK_GSSE)
1254 if (context_ex->XState.Length < sizeof(XSTATE))
1255 return STATUS_BUFFER_OVERFLOW;
1257 xsave->xstate.mask |= XSTATE_MASK_GSSE;
1258 memcpy( &xsave->xstate.ymm_high, &xs->YmmContext, sizeof(xsave->xstate.ymm_high) );
1260 else
1261 xsave->xstate.mask &= ~XSTATE_MASK_GSSE;
1264 return STATUS_SUCCESS;
1268 /***********************************************************************
1269 * NtGetContextThread (NTDLL.@)
1270 * ZwGetContextThread (NTDLL.@)
1272 * Note: we use a small assembly wrapper to save the necessary registers
1273 * in case we are fetching the context of the current thread.
1275 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1277 struct syscall_frame *frame = x86_thread_data()->syscall_frame;
1278 DWORD needed_flags = context->ContextFlags & ~CONTEXT_i386;
1279 BOOL self = (handle == GetCurrentThread());
1280 NTSTATUS ret;
1282 /* debug registers require a server call */
1283 if (needed_flags & CONTEXT_DEBUG_REGISTERS) self = FALSE;
1285 if (!self)
1287 context_t server_context;
1288 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
1290 if ((ret = get_thread_context( handle, &server_context, server_flags, &self ))) return ret;
1291 if ((ret = context_from_server( context, &server_context ))) return ret;
1292 needed_flags &= ~context->ContextFlags;
1295 if (self)
1297 struct syscall_xsave *xsave = get_syscall_xsave( frame );
1298 XSTATE *xstate;
1299 if (needed_flags & CONTEXT_INTEGER)
1301 context->Eax = frame->eax;
1302 context->Ebx = frame->ebx;
1303 context->Ecx = frame->ecx;
1304 context->Edx = frame->edx;
1305 context->Esi = frame->esi;
1306 context->Edi = frame->edi;
1307 context->ContextFlags |= CONTEXT_INTEGER;
1309 if (needed_flags & CONTEXT_CONTROL)
1311 context->Esp = frame->esp;
1312 context->Ebp = frame->ebp;
1313 context->Eip = frame->eip;
1314 context->EFlags = frame->eflags;
1315 context->SegCs = frame->cs;
1316 context->SegSs = frame->ss;
1317 context->ContextFlags |= CONTEXT_CONTROL;
1319 if (needed_flags & CONTEXT_SEGMENTS)
1321 context->SegDs = frame->ds;
1322 context->SegEs = frame->es;
1323 context->SegFs = frame->fs;
1324 context->SegGs = frame->gs;
1325 context->ContextFlags |= CONTEXT_SEGMENTS;
1327 if (needed_flags & CONTEXT_FLOATING_POINT)
1329 if (!(cpu_info.FeatureSet & CPU_FEATURE_FXSR))
1331 context->FloatSave = xsave->u.fsave;
1333 else if (!xstate_compaction_enabled ||
1334 (xsave->xstate.mask & XSTATE_MASK_LEGACY_FLOATING_POINT))
1336 fpux_to_fpu( &context->FloatSave, &xsave->u.xsave );
1338 else
1340 memset( &context->FloatSave, 0, sizeof(context->FloatSave) );
1341 context->FloatSave.ControlWord = 0x37f;
1343 context->ContextFlags |= CONTEXT_FLOATING_POINT;
1345 if (needed_flags & CONTEXT_EXTENDED_REGISTERS)
1347 XSAVE_FORMAT *xs = (XSAVE_FORMAT *)context->ExtendedRegisters;
1349 if (!xstate_compaction_enabled ||
1350 (xsave->xstate.mask & XSTATE_MASK_LEGACY_FLOATING_POINT))
1352 memcpy( xs, &xsave->u.xsave, FIELD_OFFSET( XSAVE_FORMAT, MxCsr ));
1353 memcpy( xs->FloatRegisters, xsave->u.xsave.FloatRegisters,
1354 sizeof( xs->FloatRegisters ));
1356 else
1358 memset( xs, 0, FIELD_OFFSET( XSAVE_FORMAT, MxCsr ));
1359 memset( xs->FloatRegisters, 0, sizeof( xs->FloatRegisters ));
1360 xs->ControlWord = 0x37f;
1363 if (!xstate_compaction_enabled || (xsave->xstate.mask & XSTATE_MASK_LEGACY_SSE))
1365 memcpy( xs->XmmRegisters, xsave->u.xsave.XmmRegisters, sizeof( xs->XmmRegisters ));
1366 xs->MxCsr = xsave->u.xsave.MxCsr;
1367 xs->MxCsr_Mask = xsave->u.xsave.MxCsr_Mask;
1369 else
1371 memset( xs->XmmRegisters, 0, sizeof( xs->XmmRegisters ));
1372 xs->MxCsr = 0x1f80;
1373 xs->MxCsr_Mask = 0x2ffff;
1376 context->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
1378 /* update the cached version of the debug registers */
1379 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1381 x86_thread_data()->dr0 = context->Dr0;
1382 x86_thread_data()->dr1 = context->Dr1;
1383 x86_thread_data()->dr2 = context->Dr2;
1384 x86_thread_data()->dr3 = context->Dr3;
1385 x86_thread_data()->dr6 = context->Dr6;
1386 x86_thread_data()->dr7 = context->Dr7;
1388 if ((cpu_info.FeatureSet & CPU_FEATURE_AVX) && (xstate = xstate_from_context( context )))
1390 struct syscall_xsave *xsave = get_syscall_xsave( frame );
1391 CONTEXT_EX *context_ex = (CONTEXT_EX *)(context + 1);
1392 unsigned int mask;
1394 if (context_ex->XState.Length < offsetof(XSTATE, YmmContext)
1395 || context_ex->XState.Length > sizeof(XSTATE))
1396 return STATUS_INVALID_PARAMETER;
1398 mask = (xstate_compaction_enabled ? xstate->CompactionMask : xstate->Mask) & XSTATE_MASK_GSSE;
1399 xstate->Mask = xsave->xstate.mask & mask;
1400 xstate->CompactionMask = xstate_compaction_enabled ? (0x8000000000000000 | mask) : 0;
1401 memset( xstate->Reserved, 0, sizeof(xstate->Reserved) );
1402 if (xstate->Mask)
1404 if (context_ex->XState.Length < sizeof(XSTATE))
1405 return STATUS_BUFFER_OVERFLOW;
1407 memcpy( &xstate->YmmContext, xsave->xstate.ymm_high, sizeof(xsave->xstate.ymm_high) );
1412 if (context->ContextFlags & (CONTEXT_INTEGER & ~CONTEXT_i386))
1413 TRACE( "%p: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n", handle,
1414 context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi );
1415 if (context->ContextFlags & (CONTEXT_CONTROL & ~CONTEXT_i386))
1416 TRACE( "%p: ebp=%08x esp=%08x eip=%08x cs=%04x ss=%04x flags=%08x\n", handle,
1417 context->Ebp, context->Esp, context->Eip, context->SegCs, context->SegSs, context->EFlags );
1418 if (context->ContextFlags & (CONTEXT_SEGMENTS & ~CONTEXT_i386))
1419 TRACE( "%p: ds=%04x es=%04x fs=%04x gs=%04x\n", handle,
1420 context->SegDs, context->SegEs, context->SegFs, context->SegGs );
1421 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1422 TRACE( "%p: dr0=%08x dr1=%08x dr2=%08x dr3=%08x dr6=%08x dr7=%08x\n", handle,
1423 context->Dr0, context->Dr1, context->Dr2, context->Dr3, context->Dr6, context->Dr7 );
1425 return STATUS_SUCCESS;
1429 /***********************************************************************
1430 * is_privileged_instr
1432 * Check if the fault location is a privileged instruction.
1433 * Based on the instruction emulation code in dlls/kernel/instr.c.
1435 static inline DWORD is_privileged_instr( CONTEXT *context )
1437 BYTE instr[16];
1438 unsigned int i, len, prefix_count = 0;
1440 if (!ldt_is_system( context->SegCs )) return 0;
1441 len = virtual_uninterrupted_read_memory( (BYTE *)context->Eip, instr, sizeof(instr) );
1443 for (i = 0; i < len; i++) switch (instr[i])
1445 /* instruction prefixes */
1446 case 0x2e: /* %cs: */
1447 case 0x36: /* %ss: */
1448 case 0x3e: /* %ds: */
1449 case 0x26: /* %es: */
1450 case 0x64: /* %fs: */
1451 case 0x65: /* %gs: */
1452 case 0x66: /* opcode size */
1453 case 0x67: /* addr size */
1454 case 0xf0: /* lock */
1455 case 0xf2: /* repne */
1456 case 0xf3: /* repe */
1457 if (++prefix_count >= 15) return EXCEPTION_ILLEGAL_INSTRUCTION;
1458 continue;
1460 case 0x0f: /* extended instruction */
1461 if (i == len - 1) return 0;
1462 switch(instr[i + 1])
1464 case 0x20: /* mov crX, reg */
1465 case 0x21: /* mov drX, reg */
1466 case 0x22: /* mov reg, crX */
1467 case 0x23: /* mov reg drX */
1468 return EXCEPTION_PRIV_INSTRUCTION;
1470 return 0;
1471 case 0x6c: /* insb (%dx) */
1472 case 0x6d: /* insl (%dx) */
1473 case 0x6e: /* outsb (%dx) */
1474 case 0x6f: /* outsl (%dx) */
1475 case 0xcd: /* int $xx */
1476 case 0xe4: /* inb al,XX */
1477 case 0xe5: /* in (e)ax,XX */
1478 case 0xe6: /* outb XX,al */
1479 case 0xe7: /* out XX,(e)ax */
1480 case 0xec: /* inb (%dx),%al */
1481 case 0xed: /* inl (%dx),%eax */
1482 case 0xee: /* outb %al,(%dx) */
1483 case 0xef: /* outl %eax,(%dx) */
1484 case 0xf4: /* hlt */
1485 case 0xfa: /* cli */
1486 case 0xfb: /* sti */
1487 return EXCEPTION_PRIV_INSTRUCTION;
1488 default:
1489 return 0;
1491 return 0;
1495 /***********************************************************************
1496 * check_invalid_gs
1498 * Check for fault caused by invalid %gs value (some copy protection schemes mess with it).
1500 static inline BOOL check_invalid_gs( ucontext_t *sigcontext, CONTEXT *context )
1502 unsigned int prefix_count = 0;
1503 const BYTE *instr = (BYTE *)context->Eip;
1504 WORD system_gs = x86_thread_data()->gs;
1506 if (context->SegGs == system_gs) return FALSE;
1507 if (!ldt_is_system( context->SegCs )) return FALSE;
1508 /* only handle faults in system libraries */
1509 if (virtual_is_valid_code_address( instr, 1 )) return FALSE;
1511 for (;;) switch(*instr)
1513 /* instruction prefixes */
1514 case 0x2e: /* %cs: */
1515 case 0x36: /* %ss: */
1516 case 0x3e: /* %ds: */
1517 case 0x26: /* %es: */
1518 case 0x64: /* %fs: */
1519 case 0x66: /* opcode size */
1520 case 0x67: /* addr size */
1521 case 0xf0: /* lock */
1522 case 0xf2: /* repne */
1523 case 0xf3: /* repe */
1524 if (++prefix_count >= 15) return FALSE;
1525 instr++;
1526 continue;
1527 case 0x65: /* %gs: */
1528 TRACE( "%04x/%04x at %p, fixing up\n", context->SegGs, system_gs, instr );
1529 GS_sig(sigcontext) = system_gs;
1530 return TRUE;
1531 default:
1532 return FALSE;
1537 #include "pshpack1.h"
1538 union atl_thunk
1540 struct
1542 DWORD movl; /* movl this,4(%esp) */
1543 DWORD this;
1544 BYTE jmp; /* jmp func */
1545 int func;
1546 } t1;
1547 struct
1549 BYTE movl; /* movl this,ecx */
1550 DWORD this;
1551 BYTE jmp; /* jmp func */
1552 int func;
1553 } t2;
1554 struct
1556 BYTE movl1; /* movl this,edx */
1557 DWORD this;
1558 BYTE movl2; /* movl func,ecx */
1559 DWORD func;
1560 WORD jmp; /* jmp ecx */
1561 } t3;
1562 struct
1564 BYTE movl1; /* movl this,ecx */
1565 DWORD this;
1566 BYTE movl2; /* movl func,eax */
1567 DWORD func;
1568 WORD jmp; /* jmp eax */
1569 } t4;
1570 struct
1572 DWORD inst1; /* pop ecx
1573 * pop eax
1574 * push ecx
1575 * jmp 4(%eax) */
1576 WORD inst2;
1577 } t5;
1579 #include "poppack.h"
1581 /**********************************************************************
1582 * check_atl_thunk
1584 * Check if code destination is an ATL thunk, and emulate it if so.
1586 static BOOL check_atl_thunk( ucontext_t *sigcontext, EXCEPTION_RECORD *rec, CONTEXT *context )
1588 const union atl_thunk *thunk = (const union atl_thunk *)rec->ExceptionInformation[1];
1589 union atl_thunk thunk_copy;
1590 SIZE_T thunk_len;
1592 thunk_len = virtual_uninterrupted_read_memory( thunk, &thunk_copy, sizeof(*thunk) );
1593 if (!thunk_len) return FALSE;
1595 if (thunk_len >= sizeof(thunk_copy.t1) && thunk_copy.t1.movl == 0x042444c7 &&
1596 thunk_copy.t1.jmp == 0xe9)
1598 if (!virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
1599 &thunk_copy.t1.this, sizeof(DWORD) ))
1601 EIP_sig(sigcontext) = (DWORD_PTR)(&thunk->t1.func + 1) + thunk_copy.t1.func;
1602 TRACE( "emulating ATL thunk type 1 at %p, func=%08x arg=%08x\n",
1603 thunk, EIP_sig(sigcontext), thunk_copy.t1.this );
1604 return TRUE;
1607 else if (thunk_len >= sizeof(thunk_copy.t2) && thunk_copy.t2.movl == 0xb9 &&
1608 thunk_copy.t2.jmp == 0xe9)
1610 ECX_sig(sigcontext) = thunk_copy.t2.this;
1611 EIP_sig(sigcontext) = (DWORD_PTR)(&thunk->t2.func + 1) + thunk_copy.t2.func;
1612 TRACE( "emulating ATL thunk type 2 at %p, func=%08x ecx=%08x\n",
1613 thunk, EIP_sig(sigcontext), ECX_sig(sigcontext) );
1614 return TRUE;
1616 else if (thunk_len >= sizeof(thunk_copy.t3) && thunk_copy.t3.movl1 == 0xba &&
1617 thunk_copy.t3.movl2 == 0xb9 &&
1618 thunk_copy.t3.jmp == 0xe1ff)
1620 EDX_sig(sigcontext) = thunk_copy.t3.this;
1621 ECX_sig(sigcontext) = thunk_copy.t3.func;
1622 EIP_sig(sigcontext) = thunk_copy.t3.func;
1623 TRACE( "emulating ATL thunk type 3 at %p, func=%08x ecx=%08x edx=%08x\n",
1624 thunk, EIP_sig(sigcontext), ECX_sig(sigcontext), EDX_sig(sigcontext) );
1625 return TRUE;
1627 else if (thunk_len >= sizeof(thunk_copy.t4) && thunk_copy.t4.movl1 == 0xb9 &&
1628 thunk_copy.t4.movl2 == 0xb8 &&
1629 thunk_copy.t4.jmp == 0xe0ff)
1631 ECX_sig(sigcontext) = thunk_copy.t4.this;
1632 EAX_sig(sigcontext) = thunk_copy.t4.func;
1633 EIP_sig(sigcontext) = thunk_copy.t4.func;
1634 TRACE( "emulating ATL thunk type 4 at %p, func=%08x eax=%08x ecx=%08x\n",
1635 thunk, EIP_sig(sigcontext), EAX_sig(sigcontext), ECX_sig(sigcontext) );
1636 return TRUE;
1638 else if (thunk_len >= sizeof(thunk_copy.t5) && thunk_copy.t5.inst1 == 0xff515859 &&
1639 thunk_copy.t5.inst2 == 0x0460)
1641 DWORD func, sp[2];
1642 if (virtual_uninterrupted_read_memory( (DWORD *)context->Esp, sp, sizeof(sp) ) == sizeof(sp) &&
1643 virtual_uninterrupted_read_memory( (DWORD *)sp[1] + 1, &func, sizeof(DWORD) ) == sizeof(DWORD) &&
1644 !virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1, &sp[0], sizeof(sp[0]) ))
1646 ECX_sig(sigcontext) = sp[0];
1647 EAX_sig(sigcontext) = sp[1];
1648 ESP_sig(sigcontext) += sizeof(DWORD);
1649 EIP_sig(sigcontext) = func;
1650 TRACE( "emulating ATL thunk type 5 at %p, func=%08x eax=%08x ecx=%08x esp=%08x\n",
1651 thunk, EIP_sig(sigcontext), EAX_sig(sigcontext),
1652 ECX_sig(sigcontext), ESP_sig(sigcontext) );
1653 return TRUE;
1657 return FALSE;
1661 /***********************************************************************
1662 * setup_exception_record
1664 * Setup the exception record and context on the thread stack.
1666 static void *setup_exception_record( ucontext_t *sigcontext, EXCEPTION_RECORD *rec, struct xcontext *xcontext )
1668 void *stack = init_handler( sigcontext );
1670 rec->ExceptionAddress = (void *)EIP_sig( sigcontext );
1671 save_context( xcontext, sigcontext );
1672 return stack;
1675 /***********************************************************************
1676 * setup_raise_exception
1678 * Change context to setup a call to a raise exception function.
1680 static void setup_raise_exception( ucontext_t *sigcontext, void *stack_ptr,
1681 EXCEPTION_RECORD *rec, struct xcontext *xcontext )
1683 CONTEXT *context = &xcontext->c;
1684 size_t stack_size;
1685 XSTATE *src_xs;
1687 struct stack_layout
1689 EXCEPTION_RECORD *rec_ptr; /* first arg for KiUserExceptionDispatcher */
1690 CONTEXT *context_ptr; /* second arg for KiUserExceptionDispatcher */
1691 CONTEXT context;
1692 CONTEXT_EX context_ex;
1693 EXCEPTION_RECORD rec;
1694 DWORD ebp;
1695 DWORD eip;
1696 char xstate[0];
1697 } *stack;
1699 C_ASSERT( (offsetof(struct stack_layout, xstate) == sizeof(struct stack_layout)) );
1701 NTSTATUS status = send_debug_event( rec, context, TRUE );
1703 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
1705 restore_context( xcontext, sigcontext );
1706 return;
1709 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
1710 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
1712 stack_size = sizeof(*stack);
1713 if ((src_xs = xstate_from_context( context )))
1715 stack_size += (ULONG_PTR)stack_ptr - (((ULONG_PTR)stack_ptr
1716 - sizeof(XSTATE)) & ~(ULONG_PTR)63);
1719 stack = virtual_setup_exception( stack_ptr, stack_size, rec );
1720 stack->rec = *rec;
1721 stack->context = *context;
1723 if (src_xs)
1725 XSTATE *dst_xs = (XSTATE *)stack->xstate;
1727 assert(!((ULONG_PTR)dst_xs & 63));
1728 context_init_xstate( &stack->context, stack->xstate );
1729 memset( dst_xs, 0, offsetof(XSTATE, YmmContext) );
1730 dst_xs->CompactionMask = xstate_compaction_enabled ? 0x8000000000000004 : 0;
1731 if (src_xs->Mask & 4)
1733 dst_xs->Mask = 4;
1734 memcpy( &dst_xs->YmmContext, &src_xs->YmmContext, sizeof(dst_xs->YmmContext) );
1738 stack->rec_ptr = &stack->rec;
1739 stack->context_ptr = &stack->context;
1740 ESP_sig(sigcontext) = (DWORD)stack;
1741 EIP_sig(sigcontext) = (DWORD)pKiUserExceptionDispatcher;
1742 /* clear single-step, direction, and align check flag */
1743 EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
1744 CS_sig(sigcontext) = get_cs();
1745 DS_sig(sigcontext) = get_ds();
1746 ES_sig(sigcontext) = get_ds();
1747 FS_sig(sigcontext) = get_fs();
1748 GS_sig(sigcontext) = get_gs();
1749 SS_sig(sigcontext) = get_ds();
1753 /***********************************************************************
1754 * setup_exception
1756 * Do the full setup to raise an exception from an exception record.
1758 static void setup_exception( ucontext_t *sigcontext, EXCEPTION_RECORD *rec )
1760 struct xcontext xcontext;
1761 void *stack = setup_exception_record( sigcontext, rec, &xcontext );
1763 setup_raise_exception( sigcontext, stack, rec, &xcontext );
1766 /* stack layout when calling an user apc function.
1767 * FIXME: match Windows ABI. */
1768 struct apc_stack_layout
1770 void *context_ptr;
1771 void *ctx;
1772 void *arg1;
1773 void *arg2;
1774 void *func;
1775 CONTEXT context;
1778 struct apc_stack_layout * WINAPI setup_user_apc_dispatcher_stack( CONTEXT *context, struct apc_stack_layout *stack,
1779 void *ctx, void *arg1, void *arg2, void *func )
1781 CONTEXT c;
1783 if (!context)
1785 c.ContextFlags = CONTEXT_FULL;
1786 NtGetContextThread( GetCurrentThread(), &c );
1787 c.Eax = STATUS_USER_APC;
1788 context = &c;
1790 memmove( &stack->context, context, sizeof(stack->context) );
1791 stack->context_ptr = &stack->context;
1792 stack->ctx = ctx;
1793 stack->arg1 = arg1;
1794 stack->arg2 = arg2;
1795 stack->func = func;
1796 return stack;
1799 C_ASSERT( sizeof(struct apc_stack_layout) == 0x2e0 );
1800 C_ASSERT( offsetof(struct apc_stack_layout, context) == 20 );
1802 /***********************************************************************
1803 * call_user_apc_dispatcher
1805 __ASM_GLOBAL_FUNC( call_user_apc_dispatcher,
1806 "movl 4(%esp),%esi\n\t" /* context_ptr */
1807 "movl 24(%esp),%edi\n\t" /* dispatcher */
1808 "leal 4(%esp),%ebp\n\t"
1809 "test %esi,%esi\n\t"
1810 "jz 1f\n\t"
1811 "movl 0xc4(%esi),%eax\n\t" /* context_ptr->Esp */
1812 "jmp 2f\n\t"
1813 "1:\tmovl %fs:0x1f8,%eax\n\t" /* x86_thread_data()->syscall_frame */
1814 "leal 0x38(%eax),%eax\n\t" /* &x86_thread_data()->syscall_frame->ret_addr */
1815 "2:\tsubl $0x2e0,%eax\n\t" /* sizeof(struct apc_stack_layout) */
1816 "movl %ebp,%esp\n\t" /* pop return address */
1817 "cmpl %esp,%eax\n\t"
1818 "cmovbl %eax,%esp\n\t"
1819 "pushl 16(%ebp)\n\t" /* func */
1820 "pushl 12(%ebp)\n\t" /* arg2 */
1821 "pushl 8(%ebp)\n\t" /* arg1 */
1822 "pushl 4(%ebp)\n\t" /* ctx */
1823 "pushl %eax\n\t"
1824 "pushl %esi\n\t"
1825 "call " __ASM_STDCALL("setup_user_apc_dispatcher_stack",24) "\n\t"
1826 "movl $0,%fs:0x1f8\n\t" /* x86_thread_data()->syscall_frame = NULL */
1827 "movl %eax,%esp\n\t"
1828 "leal 20(%eax),%esi\n\t"
1829 "movl 0xb4(%esi),%ebp\n\t" /* context.Ebp */
1830 "pushl 0xb8(%esi)\n\t" /* context.Eip */
1831 "jmp *%edi\n" )
1834 /***********************************************************************
1835 * call_raise_user_exception_dispatcher
1837 void WINAPI call_raise_user_exception_dispatcher( NTSTATUS (WINAPI *dispatcher)(void) )
1839 x86_thread_data()->syscall_frame->eip = (DWORD)dispatcher;
1843 /***********************************************************************
1844 * call_user_exception_dispatcher
1846 __ASM_GLOBAL_FUNC( call_user_exception_dispatcher,
1847 "movl 4(%esp),%edx\n\t" /* rec */
1848 "movl 8(%esp),%ecx\n\t" /* context */
1849 "cmpl $0x80000003,(%edx)\n\t" /* rec->ExceptionCode */
1850 "jne 1f\n\t"
1851 "decl 0xb8(%ecx)\n" /* context->Eip */
1852 "1:\tmovl %fs:0x1f8,%eax\n\t" /* x86_thread_data()->syscall_frame */
1853 "movl 0x1c(%eax),%ebx\n\t" /* frame->ebx */
1854 "movl 0x28(%eax),%edi\n\t" /* frame->edi */
1855 "movl 0x2c(%eax),%esi\n\t" /* frame->esi */
1856 "movl 0x30(%eax),%ebp\n\t" /* frame->ebp */
1857 "movl %edx,0x30(%eax)\n\t"
1858 "movl %ecx,0x34(%eax)\n\t"
1859 "movl 12(%esp),%edx\n\t" /* dispatcher */
1860 "movl $0,%fs:0x1f8\n\t"
1861 "leal 0x30(%eax),%esp\n\t"
1862 "jmp *%edx" )
1864 /**********************************************************************
1865 * get_fpu_code
1867 * Get the FPU exception code from the FPU status.
1869 static inline DWORD get_fpu_code( const CONTEXT *context )
1871 DWORD status = context->FloatSave.StatusWord & ~(context->FloatSave.ControlWord & 0x3f);
1873 if (status & 0x01) /* IE */
1875 if (status & 0x40) /* SF */
1876 return EXCEPTION_FLT_STACK_CHECK;
1877 else
1878 return EXCEPTION_FLT_INVALID_OPERATION;
1880 if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND; /* DE flag */
1881 if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO; /* ZE flag */
1882 if (status & 0x08) return EXCEPTION_FLT_OVERFLOW; /* OE flag */
1883 if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW; /* UE flag */
1884 if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT; /* PE flag */
1885 return EXCEPTION_FLT_INVALID_OPERATION; /* generic error */
1889 /***********************************************************************
1890 * handle_interrupt
1892 * Handle an interrupt.
1894 static BOOL handle_interrupt( unsigned int interrupt, ucontext_t *sigcontext, void *stack,
1895 EXCEPTION_RECORD *rec, struct xcontext *xcontext )
1897 CONTEXT *context = &xcontext->c;
1899 switch(interrupt)
1901 case 0x2d:
1902 if (!is_wow64)
1904 /* On Wow64, the upper DWORD of Rax contains garbage, and the debug
1905 * service is usually not recognized when called from usermode. */
1906 switch (context->Eax)
1908 case 1: /* BREAKPOINT_PRINT */
1909 case 3: /* BREAKPOINT_LOAD_SYMBOLS */
1910 case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
1911 case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
1912 EIP_sig(sigcontext) += 3;
1913 return TRUE;
1916 context->Eip += 3;
1917 rec->ExceptionCode = EXCEPTION_BREAKPOINT;
1918 rec->ExceptionAddress = (void *)context->Eip;
1919 rec->NumberParameters = is_wow64 ? 1 : 3;
1920 rec->ExceptionInformation[0] = context->Eax;
1921 rec->ExceptionInformation[1] = context->Ecx;
1922 rec->ExceptionInformation[2] = context->Edx;
1923 setup_raise_exception( sigcontext, stack, rec, xcontext );
1924 return TRUE;
1925 default:
1926 return FALSE;
1931 /***********************************************************************
1932 * handle_syscall_fault
1934 * Handle a page fault happening during a system call.
1936 static BOOL handle_syscall_fault( ucontext_t *sigcontext, void *stack_ptr,
1937 EXCEPTION_RECORD *rec, CONTEXT *context )
1939 struct syscall_frame *frame = x86_thread_data()->syscall_frame;
1940 __WINE_FRAME *wine_frame = (__WINE_FRAME *)NtCurrentTeb()->Tib.ExceptionList;
1941 DWORD i;
1943 if (!frame) return FALSE;
1945 TRACE( "code=%x flags=%x addr=%p ip=%08x tid=%04x\n",
1946 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
1947 context->Eip, GetCurrentThreadId() );
1948 for (i = 0; i < rec->NumberParameters; i++)
1949 TRACE( " info[%d]=%08lx\n", i, rec->ExceptionInformation[i] );
1950 TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
1951 context->Eax, context->Ebx, context->Ecx,
1952 context->Edx, context->Esi, context->Edi );
1953 TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
1954 context->Ebp, context->Esp, context->SegCs, context->SegDs,
1955 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
1957 if ((char *)wine_frame < (char *)frame)
1959 /* stack frame for calling __wine_longjmp */
1960 struct
1962 int retval;
1963 __wine_jmp_buf *jmp;
1964 void *retaddr;
1965 } *stack;
1967 TRACE( "returning to handler\n" );
1968 stack = virtual_setup_exception( stack_ptr, sizeof(*stack), rec );
1969 stack->retval = 1;
1970 stack->jmp = &wine_frame->jmp;
1971 stack->retaddr = (void *)0xdeadbabe;
1972 ESP_sig(sigcontext) = (DWORD)stack;
1973 EIP_sig(sigcontext) = (DWORD)__wine_longjmp;
1975 else
1977 TRACE( "returning to user mode ip=%08x ret=%08x\n", frame->eip, rec->ExceptionCode );
1978 EAX_sig(sigcontext) = rec->ExceptionCode;
1979 EBX_sig(sigcontext) = frame->ebx;
1980 ESI_sig(sigcontext) = frame->esi;
1981 EDI_sig(sigcontext) = frame->edi;
1982 EBP_sig(sigcontext) = frame->ebp;
1983 ESP_sig(sigcontext) = frame->esp;
1984 EIP_sig(sigcontext) = frame->eip;
1985 x86_thread_data()->syscall_frame = NULL;
1987 return TRUE;
1991 /**********************************************************************
1992 * segv_handler
1994 * Handler for SIGSEGV and related errors.
1996 static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
1998 EXCEPTION_RECORD rec = { 0 };
1999 struct xcontext xcontext;
2000 ucontext_t *ucontext = sigcontext;
2001 void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
2003 switch (TRAP_sig(ucontext))
2005 case TRAP_x86_OFLOW: /* Overflow exception */
2006 rec.ExceptionCode = EXCEPTION_INT_OVERFLOW;
2007 break;
2008 case TRAP_x86_BOUND: /* Bound range exception */
2009 rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2010 break;
2011 case TRAP_x86_PRIVINFLT: /* Invalid opcode exception */
2012 rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2013 break;
2014 case TRAP_x86_STKFLT: /* Stack fault */
2015 rec.ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2016 break;
2017 case TRAP_x86_SEGNPFLT: /* Segment not present exception */
2018 case TRAP_x86_PROTFLT: /* General protection fault */
2020 WORD err = ERROR_sig(ucontext);
2021 if (!err && (rec.ExceptionCode = is_privileged_instr( &xcontext.c ))) break;
2022 if ((err & 7) == 2 && handle_interrupt( err >> 3, ucontext, stack, &rec, &xcontext )) return;
2023 rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2024 rec.NumberParameters = 2;
2025 rec.ExceptionInformation[0] = 0;
2026 /* if error contains a LDT selector, use that as fault address */
2027 if ((err & 7) == 4 && !ldt_is_system( err | 7 )) rec.ExceptionInformation[1] = err & ~7;
2028 else
2030 rec.ExceptionInformation[1] = 0xffffffff;
2031 if (check_invalid_gs( ucontext, &xcontext.c )) return;
2034 break;
2035 case TRAP_x86_PAGEFLT: /* Page fault */
2036 rec.NumberParameters = 2;
2037 rec.ExceptionInformation[0] = (ERROR_sig(ucontext) >> 1) & 0x09;
2038 rec.ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2039 rec.ExceptionCode = virtual_handle_fault( siginfo->si_addr, rec.ExceptionInformation[0], stack );
2040 if (!rec.ExceptionCode) return;
2041 if (rec.ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
2042 rec.ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT)
2044 ULONG flags;
2045 NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
2046 &flags, sizeof(flags), NULL );
2047 if (!(flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION) &&
2048 check_atl_thunk( ucontext, &rec, &xcontext.c ))
2049 return;
2051 /* send EXCEPTION_EXECUTE_FAULT only if data execution prevention is enabled */
2052 if (!(flags & MEM_EXECUTE_OPTION_DISABLE)) rec.ExceptionInformation[0] = EXCEPTION_READ_FAULT;
2054 break;
2055 case TRAP_x86_ALIGNFLT: /* Alignment check exception */
2056 /* FIXME: pass through exception handler first? */
2057 if (xcontext.c.EFlags & 0x00040000)
2059 EFL_sig(ucontext) &= ~0x00040000; /* disable AC flag */
2060 return;
2062 rec.ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2063 break;
2064 default:
2065 WINE_ERR( "Got unexpected trap %d\n", TRAP_sig(ucontext) );
2066 /* fall through */
2067 case TRAP_x86_NMI: /* NMI interrupt */
2068 case TRAP_x86_DNA: /* Device not available exception */
2069 case TRAP_x86_DOUBLEFLT: /* Double fault exception */
2070 case TRAP_x86_TSSFLT: /* Invalid TSS exception */
2071 case TRAP_x86_MCHK: /* Machine check exception */
2072 case TRAP_x86_CACHEFLT: /* Cache flush exception */
2073 rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2074 break;
2076 if (handle_syscall_fault( ucontext, stack, &rec, &xcontext.c )) return;
2077 setup_raise_exception( ucontext, stack, &rec, &xcontext );
2081 /**********************************************************************
2082 * trap_handler
2084 * Handler for SIGTRAP.
2086 static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2088 EXCEPTION_RECORD rec = { 0 };
2089 struct xcontext xcontext;
2090 ucontext_t *ucontext = sigcontext;
2091 void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
2093 switch (TRAP_sig(ucontext))
2095 case TRAP_x86_TRCTRAP: /* Single-step exception */
2096 rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
2097 /* when single stepping can't tell whether this is a hw bp or a
2098 * single step interrupt. try to avoid as much overhead as possible
2099 * and only do a server call if there is any hw bp enabled. */
2100 if (!(xcontext.c.EFlags & 0x100) || (xcontext.c.Dr7 & 0xff))
2102 /* (possible) hardware breakpoint, fetch the debug registers */
2103 DWORD saved_flags = xcontext.c.ContextFlags;
2104 xcontext.c.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2105 NtGetContextThread( GetCurrentThread(), &xcontext.c );
2106 xcontext.c.ContextFlags |= saved_flags; /* restore flags */
2108 xcontext.c.EFlags &= ~0x100; /* clear single-step flag */
2109 break;
2110 case TRAP_x86_BPTFLT: /* Breakpoint exception */
2111 rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1; /* back up over the int3 instruction */
2112 /* fall through */
2113 default:
2114 rec.ExceptionCode = EXCEPTION_BREAKPOINT;
2115 rec.NumberParameters = is_wow64 ? 1 : 3;
2116 rec.ExceptionInformation[0] = 0;
2117 rec.ExceptionInformation[1] = 0; /* FIXME */
2118 rec.ExceptionInformation[2] = 0; /* FIXME */
2119 break;
2121 setup_raise_exception( sigcontext, stack, &rec, &xcontext );
2125 /**********************************************************************
2126 * fpe_handler
2128 * Handler for SIGFPE.
2130 static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2132 EXCEPTION_RECORD rec = { 0 };
2133 struct xcontext xcontext;
2134 ucontext_t *ucontext = sigcontext;
2135 void *stack = setup_exception_record( sigcontext, &rec, &xcontext );
2137 switch (TRAP_sig(ucontext))
2139 case TRAP_x86_DIVIDE: /* Division by zero exception */
2140 rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2141 break;
2142 case TRAP_x86_FPOPFLT: /* Coprocessor segment overrun */
2143 rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2144 break;
2145 case TRAP_x86_ARITHTRAP: /* Floating point exception */
2146 rec.ExceptionCode = get_fpu_code( &xcontext.c );
2147 rec.ExceptionAddress = (void *)xcontext.c.FloatSave.ErrorOffset;
2148 break;
2149 case TRAP_x86_CACHEFLT: /* SIMD exception */
2150 /* TODO:
2151 * Behaviour only tested for divide-by-zero exceptions
2152 * Check for other SIMD exceptions as well */
2153 if(siginfo->si_code != FPE_FLTDIV && siginfo->si_code != FPE_FLTINV)
2154 FIXME("untested SIMD exception: %#x. Might not work correctly\n",
2155 siginfo->si_code);
2157 rec.ExceptionCode = STATUS_FLOAT_MULTIPLE_TRAPS;
2158 rec.NumberParameters = 1;
2159 /* no idea what meaning is actually behind this but that's what native does */
2160 rec.ExceptionInformation[0] = 0;
2161 break;
2162 default:
2163 WINE_ERR( "Got unexpected trap %d\n", TRAP_sig(ucontext) );
2164 rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2165 break;
2167 setup_raise_exception( sigcontext, stack, &rec, &xcontext );
2171 /**********************************************************************
2172 * int_handler
2174 * Handler for SIGINT.
2176 static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2178 EXCEPTION_RECORD rec = { CONTROL_C_EXIT };
2180 setup_exception( sigcontext, &rec );
2183 /**********************************************************************
2184 * abrt_handler
2186 * Handler for SIGABRT.
2188 static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2190 EXCEPTION_RECORD rec = { EXCEPTION_WINE_ASSERTION, EH_NONCONTINUABLE };
2192 setup_exception( sigcontext, &rec );
2196 /**********************************************************************
2197 * quit_handler
2199 * Handler for SIGQUIT.
2201 static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2203 init_handler( sigcontext );
2204 abort_thread(0);
2208 /**********************************************************************
2209 * usr1_handler
2211 * Handler for SIGUSR1, used to signal a thread that it got suspended.
2213 static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2215 struct xcontext xcontext;
2217 init_handler( sigcontext );
2218 if (x86_thread_data()->syscall_frame)
2220 DECLSPEC_ALIGN(64) XSTATE xs;
2221 xcontext.c.ContextFlags = CONTEXT_FULL;
2222 context_init_xstate( &xcontext.c, &xs );
2224 NtGetContextThread( GetCurrentThread(), &xcontext.c );
2225 wait_suspend( &xcontext.c );
2226 NtSetContextThread( GetCurrentThread(), &xcontext.c );
2228 else
2230 save_context( &xcontext, sigcontext );
2231 wait_suspend( &xcontext.c );
2232 restore_context( &xcontext, sigcontext );
2237 /***********************************************************************
2238 * LDT support
2241 #define LDT_SIZE 8192
2243 #define LDT_FLAGS_DATA 0x13 /* Data segment */
2244 #define LDT_FLAGS_CODE 0x1b /* Code segment */
2245 #define LDT_FLAGS_32BIT 0x40 /* Segment is 32-bit (code or stack) */
2246 #define LDT_FLAGS_ALLOCATED 0x80 /* Segment is allocated */
2248 struct ldt_copy
2250 void *base[LDT_SIZE];
2251 unsigned int limit[LDT_SIZE];
2252 unsigned char flags[LDT_SIZE];
2253 } __wine_ldt_copy;
2255 static WORD gdt_fs_sel;
2256 static pthread_mutex_t ldt_mutex = PTHREAD_MUTEX_INITIALIZER;
2257 static const LDT_ENTRY null_entry;
2259 static inline void *ldt_get_base( LDT_ENTRY ent )
2261 return (void *)(ent.BaseLow |
2262 (ULONG_PTR)ent.HighWord.Bits.BaseMid << 16 |
2263 (ULONG_PTR)ent.HighWord.Bits.BaseHi << 24);
2266 static inline unsigned int ldt_get_limit( LDT_ENTRY ent )
2268 unsigned int limit = ent.LimitLow | (ent.HighWord.Bits.LimitHi << 16);
2269 if (ent.HighWord.Bits.Granularity) limit = (limit << 12) | 0xfff;
2270 return limit;
2273 static LDT_ENTRY ldt_make_entry( void *base, unsigned int limit, unsigned char flags )
2275 LDT_ENTRY entry;
2277 entry.BaseLow = (WORD)(ULONG_PTR)base;
2278 entry.HighWord.Bits.BaseMid = (BYTE)((ULONG_PTR)base >> 16);
2279 entry.HighWord.Bits.BaseHi = (BYTE)((ULONG_PTR)base >> 24);
2280 if ((entry.HighWord.Bits.Granularity = (limit >= 0x100000))) limit >>= 12;
2281 entry.LimitLow = (WORD)limit;
2282 entry.HighWord.Bits.LimitHi = limit >> 16;
2283 entry.HighWord.Bits.Dpl = 3;
2284 entry.HighWord.Bits.Pres = 1;
2285 entry.HighWord.Bits.Type = flags;
2286 entry.HighWord.Bits.Sys = 0;
2287 entry.HighWord.Bits.Reserved_0 = 0;
2288 entry.HighWord.Bits.Default_Big = (flags & LDT_FLAGS_32BIT) != 0;
2289 return entry;
2292 static void ldt_set_entry( WORD sel, LDT_ENTRY entry )
2294 int index = sel >> 3;
2296 #ifdef linux
2297 struct modify_ldt_s ldt_info = { index };
2299 ldt_info.base_addr = ldt_get_base( entry );
2300 ldt_info.limit = entry.LimitLow | (entry.HighWord.Bits.LimitHi << 16);
2301 ldt_info.seg_32bit = entry.HighWord.Bits.Default_Big;
2302 ldt_info.contents = (entry.HighWord.Bits.Type >> 2) & 3;
2303 ldt_info.read_exec_only = !(entry.HighWord.Bits.Type & 2);
2304 ldt_info.limit_in_pages = entry.HighWord.Bits.Granularity;
2305 ldt_info.seg_not_present = !entry.HighWord.Bits.Pres;
2306 ldt_info.usable = entry.HighWord.Bits.Sys;
2307 if (modify_ldt( 0x11, &ldt_info, sizeof(ldt_info) ) < 0) perror( "modify_ldt" );
2308 #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__)
2309 /* The kernel will only let us set LDTs with user priority level */
2310 if (entry.HighWord.Bits.Pres && entry.HighWord.Bits.Dpl != 3) entry.HighWord.Bits.Dpl = 3;
2311 if (i386_set_ldt(index, (union descriptor *)&entry, 1) < 0)
2313 perror("i386_set_ldt");
2314 fprintf( stderr, "Did you reconfigure the kernel with \"options USER_LDT\"?\n" );
2315 exit(1);
2317 #elif defined(__svr4__) || defined(_SCO_DS)
2318 struct ssd ldt_mod;
2320 ldt_mod.sel = sel;
2321 ldt_mod.bo = (unsigned long)ldt_get_base( entry );
2322 ldt_mod.ls = entry.LimitLow | (entry.HighWord.Bits.LimitHi << 16);
2323 ldt_mod.acc1 = entry.HighWord.Bytes.Flags1;
2324 ldt_mod.acc2 = entry.HighWord.Bytes.Flags2 >> 4;
2325 if (sysi86(SI86DSCR, &ldt_mod) == -1) perror("sysi86");
2326 #elif defined(__APPLE__)
2327 if (i386_set_ldt(index, (union ldt_entry *)&entry, 1) < 0) perror("i386_set_ldt");
2328 #elif defined(__GNU__)
2329 if (i386_set_ldt(mach_thread_self(), sel, (descriptor_list_t)&entry, 1) != KERN_SUCCESS)
2330 perror("i386_set_ldt");
2331 #else
2332 fprintf( stderr, "No LDT support on this platform\n" );
2333 exit(1);
2334 #endif
2336 __wine_ldt_copy.base[index] = ldt_get_base( entry );
2337 __wine_ldt_copy.limit[index] = ldt_get_limit( entry );
2338 __wine_ldt_copy.flags[index] = (entry.HighWord.Bits.Type |
2339 (entry.HighWord.Bits.Default_Big ? LDT_FLAGS_32BIT : 0) |
2340 LDT_FLAGS_ALLOCATED);
2343 static void ldt_set_fs( WORD sel, TEB *teb )
2345 if (sel == gdt_fs_sel)
2347 #ifdef __linux__
2348 struct modify_ldt_s ldt_info = { sel >> 3 };
2350 ldt_info.base_addr = teb;
2351 ldt_info.limit = page_size - 1;
2352 ldt_info.seg_32bit = 1;
2353 if (set_thread_area( &ldt_info ) < 0) perror( "set_thread_area" );
2354 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__DragonFly__)
2355 i386_set_fsbase( teb );
2356 #endif
2358 set_fs( sel );
2362 /**********************************************************************
2363 * get_thread_ldt_entry
2365 NTSTATUS get_thread_ldt_entry( HANDLE handle, void *data, ULONG len, ULONG *ret_len )
2367 THREAD_DESCRIPTOR_INFORMATION *info = data;
2368 NTSTATUS status = STATUS_SUCCESS;
2370 if (len < sizeof(*info)) return STATUS_INFO_LENGTH_MISMATCH;
2371 if (info->Selector >> 16) return STATUS_UNSUCCESSFUL;
2373 if (is_gdt_sel( info->Selector ))
2375 if (!(info->Selector & ~3))
2376 info->Entry = null_entry;
2377 else if ((info->Selector | 3) == get_cs())
2378 info->Entry = ldt_make_entry( 0, ~0u, LDT_FLAGS_CODE | LDT_FLAGS_32BIT );
2379 else if ((info->Selector | 3) == get_ds())
2380 info->Entry = ldt_make_entry( 0, ~0u, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
2381 else if ((info->Selector | 3) == get_fs())
2382 info->Entry = ldt_make_entry( NtCurrentTeb(), 0xfff, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
2383 else
2384 return STATUS_UNSUCCESSFUL;
2386 else
2388 SERVER_START_REQ( get_selector_entry )
2390 req->handle = wine_server_obj_handle( handle );
2391 req->entry = info->Selector >> 3;
2392 status = wine_server_call( req );
2393 if (!status)
2395 if (reply->flags)
2396 info->Entry = ldt_make_entry( (void *)reply->base, reply->limit, reply->flags );
2397 else
2398 status = STATUS_UNSUCCESSFUL;
2401 SERVER_END_REQ;
2403 if (status == STATUS_SUCCESS && ret_len)
2404 /* yes, that's a bit strange, but it's the way it is */
2405 *ret_len = sizeof(info->Entry);
2407 return status;
2411 /******************************************************************************
2412 * NtSetLdtEntries (NTDLL.@)
2413 * ZwSetLdtEntries (NTDLL.@)
2415 NTSTATUS WINAPI NtSetLdtEntries( ULONG sel1, LDT_ENTRY entry1, ULONG sel2, LDT_ENTRY entry2 )
2417 sigset_t sigset;
2419 if (sel1 >> 16 || sel2 >> 16) return STATUS_INVALID_LDT_DESCRIPTOR;
2420 if (sel1 && (sel1 >> 3) < first_ldt_entry) return STATUS_INVALID_LDT_DESCRIPTOR;
2421 if (sel2 && (sel2 >> 3) < first_ldt_entry) return STATUS_INVALID_LDT_DESCRIPTOR;
2423 server_enter_uninterrupted_section( &ldt_mutex, &sigset );
2424 if (sel1) ldt_set_entry( sel1, entry1 );
2425 if (sel2) ldt_set_entry( sel2, entry2 );
2426 server_leave_uninterrupted_section( &ldt_mutex, &sigset );
2427 return STATUS_SUCCESS;
2431 /**********************************************************************
2432 * signal_init_threading
2434 void signal_init_threading(void)
2436 #ifdef __linux__
2437 /* the preloader may have allocated it already */
2438 gdt_fs_sel = get_fs();
2439 if (!gdt_fs_sel || !is_gdt_sel( gdt_fs_sel ))
2441 struct modify_ldt_s ldt_info = { -1 };
2443 ldt_info.seg_32bit = 1;
2444 ldt_info.usable = 1;
2445 if (set_thread_area( &ldt_info ) >= 0) gdt_fs_sel = (ldt_info.entry_number << 3) | 3;
2446 else gdt_fs_sel = 0;
2448 #elif defined(__FreeBSD__) || defined (__FreeBSD_kernel__)
2449 gdt_fs_sel = GSEL( GUFS_SEL, SEL_UPL );
2450 #endif
2454 /**********************************************************************
2455 * signal_alloc_thread
2457 NTSTATUS signal_alloc_thread( TEB *teb )
2459 struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
2461 if (!gdt_fs_sel)
2463 static int first_thread = 1;
2464 sigset_t sigset;
2465 int idx;
2466 LDT_ENTRY entry = ldt_make_entry( teb, page_size - 1, LDT_FLAGS_DATA | LDT_FLAGS_32BIT );
2468 if (first_thread) /* no locking for first thread */
2470 /* leave some space if libc is using the LDT for %gs */
2471 if (!is_gdt_sel( get_gs() )) first_ldt_entry = 512;
2472 idx = first_ldt_entry;
2473 ldt_set_entry( (idx << 3) | 7, entry );
2474 first_thread = 0;
2476 else
2478 server_enter_uninterrupted_section( &ldt_mutex, &sigset );
2479 for (idx = first_ldt_entry; idx < LDT_SIZE; idx++)
2481 if (__wine_ldt_copy.flags[idx]) continue;
2482 ldt_set_entry( (idx << 3) | 7, entry );
2483 break;
2485 server_leave_uninterrupted_section( &ldt_mutex, &sigset );
2486 if (idx == LDT_SIZE) return STATUS_TOO_MANY_THREADS;
2488 thread_data->fs = (idx << 3) | 7;
2490 else thread_data->fs = gdt_fs_sel;
2492 teb->WOW32Reserved = syscall_dispatcher;
2493 return STATUS_SUCCESS;
2497 /**********************************************************************
2498 * signal_free_thread
2500 void signal_free_thread( TEB *teb )
2502 struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
2503 sigset_t sigset;
2505 if (gdt_fs_sel) return;
2507 server_enter_uninterrupted_section( &ldt_mutex, &sigset );
2508 __wine_ldt_copy.flags[thread_data->fs >> 3] = 0;
2509 server_leave_uninterrupted_section( &ldt_mutex, &sigset );
2513 /**********************************************************************
2514 * signal_init_thread
2516 void signal_init_thread( TEB *teb )
2518 const WORD fpu_cw = 0x27f;
2519 struct x86_thread_data *thread_data = (struct x86_thread_data *)&teb->GdiTebBatch;
2521 ldt_set_fs( thread_data->fs, teb );
2522 thread_data->gs = get_gs();
2524 __asm__ volatile ("fninit; fldcw %0" : : "m" (fpu_cw));
2528 /**********************************************************************
2529 * signal_init_process
2531 void signal_init_process(void)
2533 struct sigaction sig_act;
2535 sig_act.sa_mask = server_block_set;
2536 sig_act.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
2537 #ifdef __ANDROID__
2538 sig_act.sa_flags |= SA_RESTORER;
2539 sig_act.sa_restorer = rt_sigreturn;
2540 #endif
2541 sig_act.sa_sigaction = int_handler;
2542 if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
2543 sig_act.sa_sigaction = fpe_handler;
2544 if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
2545 sig_act.sa_sigaction = abrt_handler;
2546 if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
2547 sig_act.sa_sigaction = quit_handler;
2548 if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
2549 sig_act.sa_sigaction = usr1_handler;
2550 if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
2551 sig_act.sa_sigaction = trap_handler;
2552 if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2553 sig_act.sa_sigaction = segv_handler;
2554 if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
2555 if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2556 if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2557 return;
2559 error:
2560 perror("sigaction");
2561 exit(1);
2565 /**********************************************************************
2566 * signal_init_syscalls
2568 void *signal_init_syscalls(void)
2570 extern void __wine_syscall_dispatcher_fxsave(void) DECLSPEC_HIDDEN;
2571 extern void __wine_syscall_dispatcher_xsave(void) DECLSPEC_HIDDEN;
2572 extern void __wine_syscall_dispatcher_xsavec(void) DECLSPEC_HIDDEN;
2574 if (xstate_compaction_enabled)
2575 syscall_dispatcher = __wine_syscall_dispatcher_xsavec;
2576 else if (cpu_info.FeatureSet & CPU_FEATURE_XSAVE)
2577 syscall_dispatcher = __wine_syscall_dispatcher_xsave;
2578 else if (cpu_info.FeatureSet & CPU_FEATURE_FXSR)
2579 syscall_dispatcher = __wine_syscall_dispatcher_fxsave;
2580 else
2581 syscall_dispatcher = __wine_syscall_dispatcher;
2583 return NtCurrentTeb()->WOW32Reserved = syscall_dispatcher;
2587 /***********************************************************************
2588 * init_thread_context
2590 static void init_thread_context( CONTEXT *context, LPTHREAD_START_ROUTINE entry, void *arg )
2592 context->SegCs = get_cs();
2593 context->SegDs = get_ds();
2594 context->SegEs = get_ds();
2595 context->SegFs = get_fs();
2596 context->SegGs = get_gs();
2597 context->SegSs = get_ds();
2598 context->EFlags = 0x202;
2599 context->Eax = (DWORD)entry;
2600 context->Ebx = (DWORD)arg;
2601 context->Esp = (DWORD)NtCurrentTeb()->Tib.StackBase - 16;
2602 context->Eip = (DWORD)pRtlUserThreadStart;
2603 context->FloatSave.ControlWord = 0x27f;
2604 ((XSAVE_FORMAT *)context->ExtendedRegisters)->ControlWord = 0x27f;
2605 ((XSAVE_FORMAT *)context->ExtendedRegisters)->MxCsr = 0x1f80;
2609 /***********************************************************************
2610 * get_initial_context
2612 PCONTEXT DECLSPEC_HIDDEN get_initial_context( LPTHREAD_START_ROUTINE entry, void *arg, BOOL suspend )
2614 CONTEXT *ctx;
2616 if (suspend)
2618 CONTEXT context = { CONTEXT_ALL };
2620 init_thread_context( &context, entry, arg );
2621 wait_suspend( &context );
2622 ctx = (CONTEXT *)((ULONG_PTR)context.Esp & ~15) - 1;
2623 *ctx = context;
2625 else
2627 ctx = (CONTEXT *)((char *)NtCurrentTeb()->Tib.StackBase - 16) - 1;
2628 init_thread_context( ctx, entry, arg );
2630 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2631 ctx->ContextFlags = CONTEXT_FULL | CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS;
2632 return ctx;
2636 /***********************************************************************
2637 * signal_start_thread
2639 __ASM_GLOBAL_FUNC( signal_start_thread,
2640 "pushl %ebp\n\t"
2641 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
2642 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2643 "movl %esp,%ebp\n\t"
2644 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
2645 "pushl %ebx\n\t"
2646 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2647 "pushl %esi\n\t"
2648 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
2649 "pushl %edi\n\t"
2650 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
2651 /* store exit frame */
2652 "movl %ebp,%fs:0x1f4\n\t" /* x86_thread_data()->exit_frame */
2653 /* switch to thread stack */
2654 "movl %fs:4,%eax\n\t" /* NtCurrentTeb()->StackBase */
2655 "leal -0x1004(%eax),%esp\n\t"
2656 /* attach dlls */
2657 "pushl 16(%ebp)\n\t" /* suspend */
2658 "pushl 12(%ebp)\n\t" /* arg */
2659 "pushl 8(%ebp)\n\t" /* entry */
2660 "call " __ASM_NAME("get_initial_context") "\n\t"
2661 "movl %eax,(%esp)\n\t" /* context */
2662 "movl 20(%ebp),%edx\n\t" /* thunk */
2663 "xorl %ebp,%ebp\n\t"
2664 "pushl $0\n\t"
2665 "jmp *%edx" )
2668 /***********************************************************************
2669 * signal_exit_thread
2671 __ASM_GLOBAL_FUNC( signal_exit_thread,
2672 "movl 8(%esp),%ecx\n\t"
2673 /* fetch exit frame */
2674 "movl %fs:0x1f4,%edx\n\t" /* x86_thread_data()->exit_frame */
2675 "testl %edx,%edx\n\t"
2676 "jnz 1f\n\t"
2677 "jmp *%ecx\n\t"
2678 /* switch to exit frame stack */
2679 "1:\tmovl 4(%esp),%eax\n\t"
2680 "movl $0,%fs:0x1f4\n\t"
2681 "movl %edx,%ebp\n\t"
2682 __ASM_CFI(".cfi_def_cfa %ebp,4\n\t")
2683 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
2684 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
2685 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
2686 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
2687 "leal -20(%ebp),%esp\n\t"
2688 "pushl %eax\n\t"
2689 "call *%ecx" )
2691 /**********************************************************************
2692 * NtCurrentTeb (NTDLL.@)
2694 __ASM_STDCALL_FUNC( NtCurrentTeb, 0, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
2696 #endif /* __i386__ */