signal_i386.c 101 KB
Newer Older
1 2
/*
 * i386 signal handling routines
3
 *
4
 * Copyright 1999 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22 23
 */

#ifdef __i386__

#include "config.h"
24
#include "wine/port.h"
25 26 27 28

#include <errno.h>
#include <signal.h>
#include <stdlib.h>
29
#include <stdarg.h>
30
#include <stdio.h>
31
#include <sys/types.h>
32 33 34
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
35 36 37 38 39 40 41 42 43 44
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYSCALL_H
# include <syscall.h>
#else
# ifdef HAVE_SYS_SYSCALL_H
#  include <sys/syscall.h>
# endif
#endif
45 46 47
#ifdef HAVE_SYS_VM86_H
# include <sys/vm86.h>
#endif
48 49 50
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
51 52 53
#ifdef HAVE_SYS_SYSCTL_H
# include <sys/sysctl.h>
#endif
54 55 56
#ifdef HAVE_SYS_UCONTEXT_H
# include <sys/ucontext.h>
#endif
57

58 59
#include "ntstatus.h"
#define WIN32_NO_STATUS
60
#include "windef.h"
61
#include "wine/library.h"
62
#include "ntdll_misc.h"
63 64
#include "wine/exception.h"
#include "wine/debug.h"
65

66 67 68 69
#ifdef HAVE_VALGRIND_MEMCHECK_H
#include <valgrind/memcheck.h>
#endif

70 71
#undef ERR  /* Solaris needs to define this */

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
/* not defined for x86, so copy the x86_64 definition */
typedef struct DECLSPEC_ALIGN(16) _M128A
{
    ULONGLONG Low;
    LONGLONG High;
} M128A;

typedef struct
{
    WORD ControlWord;
    WORD StatusWord;
    BYTE TagWord;
    BYTE Reserved1;
    WORD ErrorOpcode;
    DWORD ErrorOffset;
    WORD ErrorSelector;
    WORD Reserved2;
    DWORD DataOffset;
    WORD DataSelector;
    WORD Reserved3;
    DWORD MxCsr;
    DWORD MxCsr_Mask;
    M128A FloatRegisters[8];
    M128A XmmRegisters[16];
    BYTE Reserved4[96];
} XMM_SAVE_AREA32;

99 100 101 102
/***********************************************************************
 * signal context platform-specific definitions
 */

103
#ifdef __linux__
104

105
#ifndef HAVE_SYS_UCONTEXT_H
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

enum
{
    REG_GS, REG_FS, REG_ES, REG_DS, REG_EDI, REG_ESI, REG_EBP, REG_ESP,
    REG_EBX, REG_EDX, REG_ECX, REG_EAX, REG_TRAPNO, REG_ERR, REG_EIP,
    REG_CS, REG_EFL, REG_UESP, REG_SS, NGREG
};

typedef int greg_t;
typedef greg_t gregset_t[NGREG];

struct _libc_fpreg
{
    unsigned short significand[4];
    unsigned short exponent;
};

struct _libc_fpstate
{
    unsigned long cw;
    unsigned long sw;
    unsigned long tag;
    unsigned long ipoff;
    unsigned long cssel;
    unsigned long dataoff;
    unsigned long datasel;
    struct _libc_fpreg _st[8];
    unsigned long status;
};

typedef struct _libc_fpstate* fpregset_t;

typedef struct
{
    gregset_t     gregs;
    fpregset_t    fpregs;
    unsigned long oldmask;
    unsigned long cr2;
} mcontext_t;

146 147 148 149 150
typedef struct ucontext
{
    unsigned long     uc_flags;
    struct ucontext  *uc_link;
    stack_t           uc_stack;
151
    mcontext_t        uc_mcontext;
152
    sigset_t          uc_sigmask;
153
} ucontext_t;
154
#endif /* HAVE_SYS_UCONTEXT_H */
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
#define EAX_sig(context)     ((context)->uc_mcontext.gregs[REG_EAX])
#define EBX_sig(context)     ((context)->uc_mcontext.gregs[REG_EBX])
#define ECX_sig(context)     ((context)->uc_mcontext.gregs[REG_ECX])
#define EDX_sig(context)     ((context)->uc_mcontext.gregs[REG_EDX])
#define ESI_sig(context)     ((context)->uc_mcontext.gregs[REG_ESI])
#define EDI_sig(context)     ((context)->uc_mcontext.gregs[REG_EDI])
#define EBP_sig(context)     ((context)->uc_mcontext.gregs[REG_EBP])
#define ESP_sig(context)     ((context)->uc_mcontext.gregs[REG_ESP])

#define CS_sig(context)      ((context)->uc_mcontext.gregs[REG_CS])
#define DS_sig(context)      ((context)->uc_mcontext.gregs[REG_DS])
#define ES_sig(context)      ((context)->uc_mcontext.gregs[REG_ES])
#define SS_sig(context)      ((context)->uc_mcontext.gregs[REG_SS])
#define FS_sig(context)      ((context)->uc_mcontext.gregs[REG_FS])
#define GS_sig(context)      ((context)->uc_mcontext.gregs[REG_GS])

#define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
#define EIP_sig(context)     ((context)->uc_mcontext.gregs[REG_EIP])
#define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
#define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])

#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)
179

180 181
#define VIF_FLAG 0x00080000
#define VIP_FLAG 0x00100000
182 183 184 185

int vm86_enter( void **vm86_ptr );
void vm86_return(void);
void vm86_return_end(void);
186 187
__ASM_GLOBAL_FUNC(vm86_enter,
                  "pushl %ebp\n\t"
188 189 190 191 192 193
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
                  "movl %esp,%ebp\n\t"
                  __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
                  "pushl %ebx\n\t"
                  __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
194
                  "movl $166,%eax\n\t"  /*SYS_vm86*/
195 196
                  "movl 8(%ebp),%ecx\n\t" /* vm86_ptr */
                  "movl (%ecx),%ecx\n\t"
197 198
                  "movl $1,%ebx\n\t"    /*VM86_ENTER*/
                  "pushl %ecx\n\t"      /* put vm86plus_struct ptr somewhere we can find it */
199
                  "pushl %fs\n\t"
200
                  "pushl %gs\n\t"
201 202
                  "int $0x80\n"
                  ".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 208
                  "popl %ecx\n\t"
                  "popl %ebx\n\t"
209
                  __ASM_CFI(".cfi_same_value %ebx\n\t")
210
                  "popl %ebp\n\t"
211 212
                  __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
                  __ASM_CFI(".cfi_same_value %ebp\n\t")
213 214 215 216 217 218 219 220
                  "testl %eax,%eax\n\t"
                  "jl 0f\n\t"
                  "cmpb $0,%al\n\t" /* VM86_SIGNAL */
                  "je " __ASM_NAME("vm86_enter") "\n\t"
                  "0:\n\t"
                  "movl 4(%esp),%ecx\n\t"  /* vm86_ptr */
                  "movl $0,(%ecx)\n\t"
                  ".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" )
224

225 226 227
#ifdef HAVE_SYS_VM86_H
# define __HAVE_VM86
#endif
228

229 230 231 232 233 234 235 236
#ifdef __ANDROID__
/* custom signal restorer since we may have unmapped the one in vdso, and bionic doesn't check for that */
void rt_sigreturn(void);
__ASM_GLOBAL_FUNC( rt_sigreturn,
                   "movl $173,%eax\n\t"  /* NR_rt_sigreturn */
                   "int $0x80" );
#endif

237
#elif defined (__BSDI__)
238

239
#include <machine/frame.h>
240
typedef struct trapframe ucontext_t;
241

242 243 244 245 246 247 248
#define EAX_sig(context)     ((context)->tf_eax)
#define EBX_sig(context)     ((context)->tf_ebx)
#define ECX_sig(context)     ((context)->tf_ecx)
#define EDX_sig(context)     ((context)->tf_edx)
#define ESI_sig(context)     ((context)->tf_esi)
#define EDI_sig(context)     ((context)->tf_edi)
#define EBP_sig(context)     ((context)->tf_ebp)
249

250 251 252 253 254 255 256 257 258 259
#define CS_sig(context)      ((context)->tf_cs)
#define DS_sig(context)      ((context)->tf_ds)
#define ES_sig(context)      ((context)->tf_es)
#define SS_sig(context)      ((context)->tf_ss)

#define EFL_sig(context)     ((context)->tf_eflags)

#define EIP_sig(context)     (*((unsigned long*)&(context)->tf_eip))
#define ESP_sig(context)     (*((unsigned long*)&(context)->tf_esp))

260 261 262
#define FPU_sig(context)     NULL  /* FIXME */
#define FPUX_sig(context)    NULL  /* FIXME */

263
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
264

265 266
#include <machine/trap.h>

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
#define EAX_sig(context)     ((context)->uc_mcontext.mc_eax)
#define EBX_sig(context)     ((context)->uc_mcontext.mc_ebx)
#define ECX_sig(context)     ((context)->uc_mcontext.mc_ecx)
#define EDX_sig(context)     ((context)->uc_mcontext.mc_edx)
#define ESI_sig(context)     ((context)->uc_mcontext.mc_esi)
#define EDI_sig(context)     ((context)->uc_mcontext.mc_edi)
#define EBP_sig(context)     ((context)->uc_mcontext.mc_ebp)

#define CS_sig(context)      ((context)->uc_mcontext.mc_cs)
#define DS_sig(context)      ((context)->uc_mcontext.mc_ds)
#define ES_sig(context)      ((context)->uc_mcontext.mc_es)
#define FS_sig(context)      ((context)->uc_mcontext.mc_fs)
#define GS_sig(context)      ((context)->uc_mcontext.mc_gs)
#define SS_sig(context)      ((context)->uc_mcontext.mc_ss)

#define TRAP_sig(context)    ((context)->uc_mcontext.mc_trapno)
#define ERROR_sig(context)   ((context)->uc_mcontext.mc_err)
#define EFL_sig(context)     ((context)->uc_mcontext.mc_eflags)

#define EIP_sig(context)     ((context)->uc_mcontext.mc_eip)
#define ESP_sig(context)     ((context)->uc_mcontext.mc_esp)
288

289 290 291
#define FPU_sig(context)     NULL  /* FIXME */
#define FPUX_sig(context)    NULL  /* FIXME */

292
#elif defined (__OpenBSD__)
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

#define EAX_sig(context)     ((context)->sc_eax)
#define EBX_sig(context)     ((context)->sc_ebx)
#define ECX_sig(context)     ((context)->sc_ecx)
#define EDX_sig(context)     ((context)->sc_edx)
#define ESI_sig(context)     ((context)->sc_esi)
#define EDI_sig(context)     ((context)->sc_edi)
#define EBP_sig(context)     ((context)->sc_ebp)

#define CS_sig(context)      ((context)->sc_cs)
#define DS_sig(context)      ((context)->sc_ds)
#define ES_sig(context)      ((context)->sc_es)
#define FS_sig(context)      ((context)->sc_fs)
#define GS_sig(context)      ((context)->sc_gs)
#define SS_sig(context)      ((context)->sc_ss)

#define TRAP_sig(context)    ((context)->sc_trapno)
#define ERROR_sig(context)   ((context)->sc_err)
#define EFL_sig(context)     ((context)->sc_eflags)

#define EIP_sig(context)     ((context)->sc_eip)
#define ESP_sig(context)     ((context)->sc_esp)

#define FPU_sig(context)     NULL  /* FIXME */
#define FPUX_sig(context)    NULL  /* FIXME */

#define T_MCHK T_MACHK
#define T_XMMFLT T_XFTRAP

322
#elif defined(__svr4__) || defined(_SCO_DS) || defined(__sun)
323 324 325

#ifdef _SCO_DS
#include <sys/regset.h>
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
#define gregs regs
#endif

#define EAX_sig(context)     ((context)->uc_mcontext.gregs[EAX])
#define EBX_sig(context)     ((context)->uc_mcontext.gregs[EBX])
#define ECX_sig(context)     ((context)->uc_mcontext.gregs[ECX])
#define EDX_sig(context)     ((context)->uc_mcontext.gregs[EDX])
#define ESI_sig(context)     ((context)->uc_mcontext.gregs[ESI])
#define EDI_sig(context)     ((context)->uc_mcontext.gregs[EDI])
#define EBP_sig(context)     ((context)->uc_mcontext.gregs[EBP])

#define CS_sig(context)      ((context)->uc_mcontext.gregs[CS])
#define DS_sig(context)      ((context)->uc_mcontext.gregs[DS])
#define ES_sig(context)      ((context)->uc_mcontext.gregs[ES])
#define SS_sig(context)      ((context)->uc_mcontext.gregs[SS])

#define FS_sig(context)      ((context)->uc_mcontext.gregs[FS])
#define GS_sig(context)      ((context)->uc_mcontext.gregs[GS])

#define EFL_sig(context)     ((context)->uc_mcontext.gregs[EFL])

#define EIP_sig(context)     ((context)->uc_mcontext.gregs[EIP])
#ifdef UESP
#define ESP_sig(context)     ((context)->uc_mcontext.gregs[UESP])
#elif defined(R_ESP)
#define ESP_sig(context)     ((context)->uc_mcontext.gregs[R_ESP])
#else
#define ESP_sig(context)     ((context)->uc_mcontext.gregs[ESP])
#endif
355 356 357
#ifdef ERR
#define ERROR_sig(context)   ((context)->uc_mcontext.gregs[ERR])
#endif
358 359 360 361
#ifdef TRAPNO
#define TRAP_sig(context)     ((context)->uc_mcontext.gregs[TRAPNO])
#endif

362 363 364
#define FPU_sig(context)     NULL  /* FIXME */
#define FPUX_sig(context)    NULL  /* FIXME */

365
#elif defined (__APPLE__)
366

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
/* work around silly renaming of struct members in OS X 10.5 */
#if __DARWIN_UNIX03 && defined(_STRUCT_X86_EXCEPTION_STATE32)
#define EAX_sig(context)     ((context)->uc_mcontext->__ss.__eax)
#define EBX_sig(context)     ((context)->uc_mcontext->__ss.__ebx)
#define ECX_sig(context)     ((context)->uc_mcontext->__ss.__ecx)
#define EDX_sig(context)     ((context)->uc_mcontext->__ss.__edx)
#define ESI_sig(context)     ((context)->uc_mcontext->__ss.__esi)
#define EDI_sig(context)     ((context)->uc_mcontext->__ss.__edi)
#define EBP_sig(context)     ((context)->uc_mcontext->__ss.__ebp)
#define CS_sig(context)      ((context)->uc_mcontext->__ss.__cs)
#define DS_sig(context)      ((context)->uc_mcontext->__ss.__ds)
#define ES_sig(context)      ((context)->uc_mcontext->__ss.__es)
#define FS_sig(context)      ((context)->uc_mcontext->__ss.__fs)
#define GS_sig(context)      ((context)->uc_mcontext->__ss.__gs)
#define SS_sig(context)      ((context)->uc_mcontext->__ss.__ss)
#define EFL_sig(context)     ((context)->uc_mcontext->__ss.__eflags)
#define EIP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->__ss.__eip))
#define ESP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->__ss.__esp))
#define TRAP_sig(context)    ((context)->uc_mcontext->__es.__trapno)
#define ERROR_sig(context)   ((context)->uc_mcontext->__es.__err)
387 388
#define FPU_sig(context)     NULL
#define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->__fs.__fpu_fcw)
389
#else
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
#define EAX_sig(context)     ((context)->uc_mcontext->ss.eax)
#define EBX_sig(context)     ((context)->uc_mcontext->ss.ebx)
#define ECX_sig(context)     ((context)->uc_mcontext->ss.ecx)
#define EDX_sig(context)     ((context)->uc_mcontext->ss.edx)
#define ESI_sig(context)     ((context)->uc_mcontext->ss.esi)
#define EDI_sig(context)     ((context)->uc_mcontext->ss.edi)
#define EBP_sig(context)     ((context)->uc_mcontext->ss.ebp)
#define CS_sig(context)      ((context)->uc_mcontext->ss.cs)
#define DS_sig(context)      ((context)->uc_mcontext->ss.ds)
#define ES_sig(context)      ((context)->uc_mcontext->ss.es)
#define FS_sig(context)      ((context)->uc_mcontext->ss.fs)
#define GS_sig(context)      ((context)->uc_mcontext->ss.gs)
#define SS_sig(context)      ((context)->uc_mcontext->ss.ss)
#define EFL_sig(context)     ((context)->uc_mcontext->ss.eflags)
#define EIP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.eip))
#define ESP_sig(context)     (*((unsigned long*)&(context)->uc_mcontext->ss.esp))
#define TRAP_sig(context)    ((context)->uc_mcontext->es.trapno)
#define ERROR_sig(context)   ((context)->uc_mcontext->es.err)
408 409
#define FPU_sig(context)     NULL
#define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&(context)->uc_mcontext->fs.fpu_fcw)
410
#endif
411

412
#elif defined(__NetBSD__)
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

#define EAX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EAX])
#define EBX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EBX])
#define ECX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_ECX])
#define EDX_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EDX])
#define ESI_sig(context)       ((context)->uc_mcontext.__gregs[_REG_ESI])
#define EDI_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EDI])
#define EBP_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EBP])
#define ESP_sig(context)       _UC_MACHINE_SP(context)

#define CS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_CS])
#define DS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_DS])
#define ES_sig(context)        ((context)->uc_mcontext.__gregs[_REG_ES])
#define SS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_SS])
#define FS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_FS])
#define GS_sig(context)        ((context)->uc_mcontext.__gregs[_REG_GS])

#define EFL_sig(context)       ((context)->uc_mcontext.__gregs[_REG_EFL])
#define EIP_sig(context)       _UC_MACHINE_PC(context)
#define TRAP_sig(context)      ((context)->uc_mcontext.__gregs[_REG_TRAPNO])
#define ERROR_sig(context)     ((context)->uc_mcontext.__gregs[_REG_ERR])

#define FPU_sig(context)     NULL
#define FPUX_sig(context)    ((XMM_SAVE_AREA32 *)&((context)->uc_mcontext.__fpregs))

#define T_MCHK T_MCA
#define T_XMMFLT T_XMM

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
#elif defined(__GNU__)

#define EAX_sig(context)     ((context)->uc_mcontext.gregs[REG_EAX])
#define EBX_sig(context)     ((context)->uc_mcontext.gregs[REG_EBX])
#define ECX_sig(context)     ((context)->uc_mcontext.gregs[REG_ECX])
#define EDX_sig(context)     ((context)->uc_mcontext.gregs[REG_EDX])
#define ESI_sig(context)     ((context)->uc_mcontext.gregs[REG_ESI])
#define EDI_sig(context)     ((context)->uc_mcontext.gregs[REG_EDI])
#define EBP_sig(context)     ((context)->uc_mcontext.gregs[REG_EBP])
#define ESP_sig(context)     ((context)->uc_mcontext.gregs[REG_ESP])

#define CS_sig(context)      ((context)->uc_mcontext.gregs[REG_CS])
#define DS_sig(context)      ((context)->uc_mcontext.gregs[REG_DS])
#define ES_sig(context)      ((context)->uc_mcontext.gregs[REG_ES])
#define SS_sig(context)      ((context)->uc_mcontext.gregs[REG_SS])
#define FS_sig(context)      ((context)->uc_mcontext.gregs[REG_FS])
#define GS_sig(context)      ((context)->uc_mcontext.gregs[REG_GS])

#define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
#define EIP_sig(context)     ((context)->uc_mcontext.gregs[REG_EIP])
#define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
#define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])

#define FPU_sig(context)     ((FLOATING_SAVE_AREA *)&(context)->uc_mcontext.fpregs.fp_reg_set.fpchip_state)
#define FPUX_sig(context)    NULL

467 468 469
#else
#error You must define the signal context functions for your platform
#endif /* linux */
470

471
WINE_DEFAULT_DEBUG_CHANNEL(seh);
Patrik Stridvall's avatar
Patrik Stridvall committed
472

473
typedef int (*wine_signal_handler)(unsigned int sig);
474

475
static const size_t teb_size = 4096;  /* we reserve one page for the TEB */
476 477 478
static size_t signal_stack_mask;
static size_t signal_stack_size;

479 480
static wine_signal_handler handlers[256];

481
static BOOL fpux_support;  /* whether the CPU supports extended fpu context */
482

483
extern void DECLSPEC_NORETURN __wine_restore_regs( const CONTEXT *context );
484

485 486 487
enum i386_trap_code
{
    TRAP_x86_UNKNOWN    = -1,  /* Unknown fault (TRAP_sig not defined) */
488
#if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    TRAP_x86_DIVIDE     = T_DIVIDE,     /* Division by zero exception */
    TRAP_x86_TRCTRAP    = T_TRCTRAP,    /* Single-step exception */
    TRAP_x86_NMI        = T_NMI,        /* NMI interrupt */
    TRAP_x86_BPTFLT     = T_BPTFLT,     /* Breakpoint exception */
    TRAP_x86_OFLOW      = T_OFLOW,      /* Overflow exception */
    TRAP_x86_BOUND      = T_BOUND,      /* Bound range exception */
    TRAP_x86_PRIVINFLT  = T_PRIVINFLT,  /* Invalid opcode exception */
    TRAP_x86_DNA        = T_DNA,        /* Device not available exception */
    TRAP_x86_DOUBLEFLT  = T_DOUBLEFLT,  /* Double fault exception */
    TRAP_x86_FPOPFLT    = T_FPOPFLT,    /* Coprocessor segment overrun */
    TRAP_x86_TSSFLT     = T_TSSFLT,     /* Invalid TSS exception */
    TRAP_x86_SEGNPFLT   = T_SEGNPFLT,   /* Segment not present exception */
    TRAP_x86_STKFLT     = T_STKFLT,     /* Stack fault */
    TRAP_x86_PROTFLT    = T_PROTFLT,    /* General protection fault */
    TRAP_x86_PAGEFLT    = T_PAGEFLT,    /* Page fault */
    TRAP_x86_ARITHTRAP  = T_ARITHTRAP,  /* Floating point exception */
    TRAP_x86_ALIGNFLT   = T_ALIGNFLT,   /* Alignment check exception */
    TRAP_x86_MCHK       = T_MCHK,       /* Machine check exception */
    TRAP_x86_CACHEFLT   = T_XMMFLT      /* Cache flush exception */
#else
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    TRAP_x86_DIVIDE     = 0,   /* Division by zero exception */
    TRAP_x86_TRCTRAP    = 1,   /* Single-step exception */
    TRAP_x86_NMI        = 2,   /* NMI interrupt */
    TRAP_x86_BPTFLT     = 3,   /* Breakpoint exception */
    TRAP_x86_OFLOW      = 4,   /* Overflow exception */
    TRAP_x86_BOUND      = 5,   /* Bound range exception */
    TRAP_x86_PRIVINFLT  = 6,   /* Invalid opcode exception */
    TRAP_x86_DNA        = 7,   /* Device not available exception */
    TRAP_x86_DOUBLEFLT  = 8,   /* Double fault exception */
    TRAP_x86_FPOPFLT    = 9,   /* Coprocessor segment overrun */
    TRAP_x86_TSSFLT     = 10,  /* Invalid TSS exception */
    TRAP_x86_SEGNPFLT   = 11,  /* Segment not present exception */
    TRAP_x86_STKFLT     = 12,  /* Stack fault */
    TRAP_x86_PROTFLT    = 13,  /* General protection fault */
    TRAP_x86_PAGEFLT    = 14,  /* Page fault */
    TRAP_x86_ARITHTRAP  = 16,  /* Floating point exception */
    TRAP_x86_ALIGNFLT   = 17,  /* Alignment check exception */
    TRAP_x86_MCHK       = 18,  /* Machine check exception */
527 528
    TRAP_x86_CACHEFLT   = 19   /* SIMD exception (via SIGFPE) if CPU is SSE capable
                                  otherwise Cache flush exception (via SIGSEV) */
529
#endif
530 531
};

532 533 534 535 536 537 538 539 540 541
/* Exception record for handling exceptions happening inside exception handlers */
typedef struct
{
    EXCEPTION_REGISTRATION_RECORD frame;
    EXCEPTION_REGISTRATION_RECORD *prevFrame;
} EXC_NESTED_FRAME;

extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
                              CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
                              PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler );
542

543 544 545
/***********************************************************************
 *           dispatch_signal
 */
546
static inline int dispatch_signal(unsigned int sig)
547 548 549 550 551 552
{
    if (handlers[sig] == NULL) return 0;
    return handlers[sig](sig);
}


553 554 555 556 557
/***********************************************************************
 *           get_trap_code
 *
 * Get the trap code for a signal.
 */
558
static inline enum i386_trap_code get_trap_code( const ucontext_t *sigcontext )
559 560 561 562
{
#ifdef TRAP_sig
    return TRAP_sig(sigcontext);
#else
563
    return TRAP_x86_UNKNOWN;  /* unknown trap code */
564 565
#endif
}
566

567 568 569 570 571
/***********************************************************************
 *           get_error_code
 *
 * Get the error code for a signal.
 */
572
static inline WORD get_error_code( const ucontext_t *sigcontext )
573 574 575 576 577 578 579 580
{
#ifdef ERROR_sig
    return ERROR_sig(sigcontext);
#else
    return 0;
#endif
}

581 582 583 584 585 586 587
/***********************************************************************
 *           get_signal_stack
 *
 * Get the base of the signal stack for the current thread.
 */
static inline void *get_signal_stack(void)
{
588
    return (char *)NtCurrentTeb() + 4096;
589 590 591
}


592 593 594 595 596 597 598 599 600
/***********************************************************************
 *           get_current_teb
 *
 * Get the current teb based on the stack pointer.
 */
static inline TEB *get_current_teb(void)
{
    unsigned long esp;
    __asm__("movl %%esp,%0" : "=g" (esp) );
601
    return (TEB *)(esp & ~signal_stack_mask);
602 603 604
}


605 606 607 608 609 610 611 612 613 614
/*******************************************************************
 *         is_valid_frame
 */
static inline BOOL is_valid_frame( void *frame )
{
    if ((ULONG_PTR)frame & 3) return FALSE;
    return (frame >= NtCurrentTeb()->Tib.StackLimit &&
            (void **)frame < (void **)NtCurrentTeb()->Tib.StackBase - 1);
}

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
/*******************************************************************
 *         raise_handler
 *
 * Handler for exceptions happening inside a handler.
 */
static DWORD raise_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
{
    if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
        return ExceptionContinueSearch;
    /* We shouldn't get here so we store faulty frame in dispatcher */
    *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
    return ExceptionNestedException;
}


/*******************************************************************
 *         unwind_handler
 *
 * Handler for exceptions happening inside an unwind handler.
 */
static DWORD unwind_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
                             CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
{
    if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
        return ExceptionContinueSearch;
    /* We shouldn't get here so we store faulty frame in dispatcher */
    *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
    return ExceptionCollidedUnwind;
}


/**********************************************************************
 *           call_stack_handlers
 *
 * Call the stack handlers chain.
 */
static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
{
    EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
    DWORD res;

    frame = NtCurrentTeb()->Tib.ExceptionList;
    nested_frame = NULL;
    while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
    {
        /* Check frame address */
662
        if (!is_valid_frame( frame ))
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
        {
            rec->ExceptionFlags |= EH_STACK_INVALID;
            break;
        }

        /* Call handler */
        TRACE( "calling handler at %p code=%x flags=%x\n",
               frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
        res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, raise_handler );
        TRACE( "handler at %p returned %x\n", frame->Handler, res );

        if (frame == nested_frame)
        {
            /* no longer nested */
            nested_frame = NULL;
            rec->ExceptionFlags &= ~EH_NESTED_CALL;
        }

        switch(res)
        {
        case ExceptionContinueExecution:
            if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
            return STATUS_NONCONTINUABLE_EXCEPTION;
        case ExceptionContinueSearch:
            break;
        case ExceptionNestedException:
            if (nested_frame < dispatch) nested_frame = dispatch;
            rec->ExceptionFlags |= EH_NESTED_CALL;
            break;
        default:
            return STATUS_INVALID_DISPOSITION;
        }
        frame = frame->Prev;
    }
    return STATUS_UNHANDLED_EXCEPTION;
}


/*******************************************************************
 *		raise_exception
 *
 * Implementation of NtRaiseException.
 */
static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
{
    NTSTATUS status;

    if (first_chance)
    {
        DWORD c;

        TRACE( "code=%x flags=%x addr=%p ip=%08x tid=%04x\n",
               rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
               context->Eip, GetCurrentThreadId() );
        for (c = 0; c < rec->NumberParameters; c++)
            TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
        if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
        {
            if (rec->ExceptionInformation[1] >> 16)
                MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
                         rec->ExceptionAddress,
                         (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
            else
                MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
                         rec->ExceptionAddress,
                         (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
        }
        else
        {
            TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
                  context->Eax, context->Ebx, context->Ecx,
                  context->Edx, context->Esi, context->Edi );
            TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
                  context->Ebp, context->Esp, context->SegCs, context->SegDs,
                  context->SegEs, context->SegFs, context->SegGs, context->EFlags );
        }
        status = send_debug_event( rec, TRUE, context );
        if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
            return STATUS_SUCCESS;

        /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
        if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;

        if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
            return STATUS_SUCCESS;

        if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
            return status;
    }

    /* last chance exception */

    status = send_debug_event( rec, FALSE, context );
    if (status != DBG_CONTINUE)
    {
        if (rec->ExceptionFlags & EH_STACK_INVALID)
            WINE_ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
        else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
            WINE_ERR("Process attempted to continue execution after noncontinuable exception.\n");
        else
            WINE_ERR("Unhandled exception code %x flags %x addr %p\n",
                     rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
765
        NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
766 767 768 769 770
    }
    return STATUS_SUCCESS;
}


771
#ifdef __HAVE_VM86
772 773 774 775 776 777 778
/***********************************************************************
 *           save_vm86_context
 *
 * Set the register values from a vm86 structure.
 */
static void save_vm86_context( CONTEXT *context, const struct vm86plus_struct *vm86 )
{
779
    context->ContextFlags = CONTEXT_FULL;
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    context->Eax    = vm86->regs.eax;
    context->Ebx    = vm86->regs.ebx;
    context->Ecx    = vm86->regs.ecx;
    context->Edx    = vm86->regs.edx;
    context->Esi    = vm86->regs.esi;
    context->Edi    = vm86->regs.edi;
    context->Esp    = vm86->regs.esp;
    context->Ebp    = vm86->regs.ebp;
    context->Eip    = vm86->regs.eip;
    context->SegCs  = vm86->regs.cs;
    context->SegDs  = vm86->regs.ds;
    context->SegEs  = vm86->regs.es;
    context->SegFs  = vm86->regs.fs;
    context->SegGs  = vm86->regs.gs;
    context->SegSs  = vm86->regs.ss;
    context->EFlags = vm86->regs.eflags;
}


/***********************************************************************
 *           restore_vm86_context
 *
 * Build a vm86 structure from the register values.
 */
static void restore_vm86_context( const CONTEXT *context, struct vm86plus_struct *vm86 )
{
    vm86->regs.eax    = context->Eax;
    vm86->regs.ebx    = context->Ebx;
    vm86->regs.ecx    = context->Ecx;
    vm86->regs.edx    = context->Edx;
    vm86->regs.esi    = context->Esi;
    vm86->regs.edi    = context->Edi;
    vm86->regs.esp    = context->Esp;
    vm86->regs.ebp    = context->Ebp;
    vm86->regs.eip    = context->Eip;
    vm86->regs.cs     = context->SegCs;
    vm86->regs.ds     = context->SegDs;
    vm86->regs.es     = context->SegEs;
    vm86->regs.fs     = context->SegFs;
    vm86->regs.gs     = context->SegGs;
    vm86->regs.ss     = context->SegSs;
    vm86->regs.eflags = context->EFlags;
}
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841


/**********************************************************************
 *		merge_vm86_pending_flags
 *
 * Merges TEB.vm86_ptr and TEB.vm86_pending VIP flags and
 * raises exception if there are pending events and VIF flag
 * has been turned on.
 *
 * Called from __wine_enter_vm86 because vm86_enter
 * doesn't check for pending events. 
 *
 * Called from raise_vm86_sti_exception to check for
 * pending events in a signal safe way.
 */
static void merge_vm86_pending_flags( EXCEPTION_RECORD *rec )
{
    BOOL check_pending = TRUE;
    struct vm86plus_struct *vm86 =
842
        (struct vm86plus_struct*)(ntdll_get_thread_data()->vm86_ptr);
843 844 845 846 847 848

    /*
     * In order to prevent a race when SIGUSR2 occurs while
     * we are returning from exception handler, pending events
     * will be rechecked after each raised exception.
     */
849
    while (check_pending && get_vm86_teb_info()->vm86_pending)
850 851
    {
        check_pending = FALSE;
852
        ntdll_get_thread_data()->vm86_ptr = NULL;
853 854 855 856 857 858
            
        /*
         * If VIF is set, throw exception.
         * Note that SIGUSR2 may turn VIF flag off so
         * VIF check must occur only when TEB.vm86_ptr is NULL.
         */
859
        if (vm86->regs.eflags & VIF_FLAG)
860 861 862 863 864 865 866 867 868 869
        {
            CONTEXT vcontext;
            save_vm86_context( &vcontext, vm86 );
            
            rec->ExceptionCode    = EXCEPTION_VM86_STI;
            rec->ExceptionFlags   = EXCEPTION_CONTINUABLE;
            rec->ExceptionRecord  = NULL;
            rec->NumberParameters = 0;
            rec->ExceptionAddress = (LPVOID)vcontext.Eip;

870
            vcontext.EFlags &= ~VIP_FLAG;
871
            get_vm86_teb_info()->vm86_pending = 0;
872
            raise_exception( rec, &vcontext, TRUE );
873 874 875 876 877

            restore_vm86_context( &vcontext, vm86 );
            check_pending = TRUE;
        }

878
        ntdll_get_thread_data()->vm86_ptr = vm86;
879 880 881 882 883 884 885
    }

    /*
     * Merge VIP flags in a signal safe way. This requires
     * that the following operation compiles into atomic
     * instruction.
     */
886
    vm86->regs.eflags |= get_vm86_teb_info()->vm86_pending;
887
}
888
#endif /* __HAVE_VM86 */
889 890


891 892 893 894 895 896 897 898 899 900 901 902
#ifdef __sun

/* We have to workaround two Solaris breakages:
 * - Solaris doesn't restore %ds and %es before calling the signal handler so exceptions in 16-bit
 *   code crash badly.
 * - Solaris inserts a libc trampoline to call our handler, but the trampoline expects that registers
 *   are setup correctly. So we need to insert our own trampoline below the libc trampoline to set %gs.
 */

extern int sigaction_syscall( int sig, const struct sigaction *new, struct sigaction *old );
__ASM_GLOBAL_FUNC( sigaction_syscall,
                  "movl $0x62,%eax\n\t"
903 904
                  "int $0x91\n\t"
                  "ret" )
905 906 907 908 909 910 911 912 913 914

/* assume the same libc handler is used for all signals */
static void (*libc_sigacthandler)( int signal, siginfo_t *siginfo, void *context );

static void wine_sigacthandler( int signal, siginfo_t *siginfo, void *sigcontext )
{
    struct ntdll_thread_data *thread_data;

    __asm__ __volatile__("mov %ss,%ax; mov %ax,%ds; mov %ax,%es");

915
    thread_data = (struct ntdll_thread_data *)get_current_teb()->SpareBytes1;
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    wine_set_fs( thread_data->fs );
    wine_set_gs( thread_data->gs );

    libc_sigacthandler( signal, siginfo, sigcontext );
}

static int solaris_sigaction( int sig, const struct sigaction *new, struct sigaction *old )
{
    struct sigaction real_act;

    if (sigaction( sig, new, old ) == -1) return -1;

    /* retrieve the real handler and flags with a direct syscall */
    sigaction_syscall( sig, NULL, &real_act );
    libc_sigacthandler = real_act.sa_sigaction;
    real_act.sa_sigaction = wine_sigacthandler;
    sigaction_syscall( sig, &real_act, NULL );
    return 0;
}
#define sigaction(sig,new,old) solaris_sigaction(sig,new,old)

#endif

939 940
typedef void (WINAPI *raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );

941 942 943 944 945 946 947 948 949
extern void clear_alignment_flag(void);
__ASM_GLOBAL_FUNC( clear_alignment_flag,
                   "pushfl\n\t"
                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                   "andl $~0x40000,(%esp)\n\t"
                   "popfl\n\t"
                   __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
                   "ret" )

950

951 952 953 954
/***********************************************************************
 *           init_handler
 *
 * Handler initialization when the full context is not needed.
955
 * Return the stack pointer to use for pushing the exception data.
956
 */
957
static inline void *init_handler( const ucontext_t *sigcontext, WORD *fs, WORD *gs )
958
{
959
    TEB *teb = get_current_teb();
960

961 962
    clear_alignment_flag();

963 964 965 966 967 968 969 970 971 972 973 974
    /* get %fs and %gs at time of the fault */
#ifdef FS_sig
    *fs = LOWORD(FS_sig(sigcontext));
#else
    *fs = wine_get_fs();
#endif
#ifdef GS_sig
    *gs = LOWORD(GS_sig(sigcontext));
#else
    *gs = wine_get_gs();
#endif

975
#ifndef __sun  /* see above for Solaris handling */
976
    {
977
        struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
978 979 980
        wine_set_fs( thread_data->fs );
        wine_set_gs( thread_data->gs );
    }
981
#endif
982

983 984
    if (!wine_ldt_is_system(CS_sig(sigcontext)) ||
        !wine_ldt_is_system(SS_sig(sigcontext)))  /* 16-bit mode */
985
    {
986 987 988 989 990 991 992
        /*
         * Win16 or DOS protected mode. Note that during switch
         * from 16-bit mode to linear mode, CS may be set to system
         * segment before FS is restored. Fortunately, in this case
         * SS is still non-system segment. This is why both CS and SS
         * are checked.
         */
993
        return teb->WOW32Reserved;
994
    }
995
    return (void *)(ESP_sig(sigcontext) & ~3);
996 997 998
}


999 1000 1001 1002 1003
/***********************************************************************
 *           save_fpu
 *
 * Save the thread FPU context.
 */
1004
static inline void save_fpu( CONTEXT *context )
1005 1006 1007 1008 1009 1010 1011 1012
{
#ifdef __GNUC__
    context->ContextFlags |= CONTEXT_FLOATING_POINT;
    __asm__ __volatile__( "fnsave %0; fwait" : "=m" (context->FloatSave) );
#endif
}


1013 1014 1015
/***********************************************************************
 *           restore_fpu
 *
1016
 * Restore the FPU context to a sigcontext.
1017
 */
1018
static inline void restore_fpu( const CONTEXT *context )
1019
{
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 1026 1027 1028
#endif  /* __GNUC__ */
}


1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
/***********************************************************************
 *           restore_fpux
 *
 * Restore the FPU extended context to a sigcontext.
 */
static inline void restore_fpux( const CONTEXT *context )
{
#ifdef __GNUC__
    /* we have to enforce alignment by hand */
    char buffer[sizeof(XMM_SAVE_AREA32) + 16];
    XMM_SAVE_AREA32 *state = (XMM_SAVE_AREA32 *)(((ULONG_PTR)buffer + 15) & ~15);

    memcpy( state, context->ExtendedRegisters, sizeof(*state) );
    /* reset the current interrupt status */
    state->StatusWord &= state->ControlWord | 0xff80;
    __asm__ __volatile__( "fxrstor %0" : : "m" (*state) );
#endif
}


1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
/***********************************************************************
 *           fpux_to_fpu
 *
 * Build a standard FPU context from an extended one.
 */
static void fpux_to_fpu( FLOATING_SAVE_AREA *fpu, const XMM_SAVE_AREA32 *fpux )
{
    unsigned int i, tag, stack_top;

    fpu->ControlWord   = fpux->ControlWord | 0xffff0000;
    fpu->StatusWord    = fpux->StatusWord | 0xffff0000;
    fpu->ErrorOffset   = fpux->ErrorOffset;
    fpu->ErrorSelector = fpux->ErrorSelector | (fpux->ErrorOpcode << 16);
    fpu->DataOffset    = fpux->DataOffset;
    fpu->DataSelector  = fpux->DataSelector;
    fpu->Cr0NpxState   = fpux->StatusWord | 0xffff0000;

    stack_top = (fpux->StatusWord >> 11) & 7;
    fpu->TagWord = 0xffff0000;
    for (i = 0; i < 8; i++)
    {
        memcpy( &fpu->RegisterArea[10 * i], &fpux->FloatRegisters[i], 10 );
        if (!(fpux->TagWord & (1 << i))) tag = 3;  /* empty */
        else
        {
            const M128A *reg = &fpux->FloatRegisters[(i - stack_top) & 7];
            if ((reg->High & 0x7fff) == 0x7fff)  /* exponent all ones */
            {
                tag = 2;  /* special */
            }
            else if (!(reg->High & 0x7fff))  /* exponent all zeroes */
            {
                if (reg->Low) tag = 2;  /* special */
                else tag = 1;  /* zero */
            }
            else
            {
                if (reg->Low >> 63) tag = 0;  /* valid */
                else tag = 2;  /* special */
            }
        }
        fpu->TagWord |= tag << (2 * i);
    }
}


1095 1096 1097 1098 1099
/***********************************************************************
 *           save_context
 *
 * Build a context structure from the signal info.
 */
1100
static inline void save_context( CONTEXT *context, const ucontext_t *sigcontext, WORD fs, WORD gs )
1101
{
1102
    struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1103 1104
    FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
    XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1105

1106
    memset(context, 0, sizeof(*context));
1107
    context->ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    context->Eax          = EAX_sig(sigcontext);
    context->Ebx          = EBX_sig(sigcontext);
    context->Ecx          = ECX_sig(sigcontext);
    context->Edx          = EDX_sig(sigcontext);
    context->Esi          = ESI_sig(sigcontext);
    context->Edi          = EDI_sig(sigcontext);
    context->Ebp          = EBP_sig(sigcontext);
    context->EFlags       = EFL_sig(sigcontext);
    context->Eip          = EIP_sig(sigcontext);
    context->Esp          = ESP_sig(sigcontext);
    context->SegCs        = LOWORD(CS_sig(sigcontext));
    context->SegDs        = LOWORD(DS_sig(sigcontext));
    context->SegEs        = LOWORD(ES_sig(sigcontext));
    context->SegFs        = fs;
    context->SegGs        = gs;
    context->SegSs        = LOWORD(SS_sig(sigcontext));
1124 1125 1126 1127 1128 1129
    context->Dr0          = regs->dr0;
    context->Dr1          = regs->dr1;
    context->Dr2          = regs->dr2;
    context->Dr3          = regs->dr3;
    context->Dr6          = regs->dr6;
    context->Dr7          = regs->dr7;
1130

1131
    if (fpu)
1132 1133
    {
        context->ContextFlags |= CONTEXT_FLOATING_POINT;
1134
        context->FloatSave = *fpu;
1135
    }
1136
    if (fpux)
1137
    {
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 );
1142
    }
1143
    if (!fpu && !fpux) save_fpu( context );
1144 1145 1146 1147 1148 1149 1150 1151
}


/***********************************************************************
 *           restore_context
 *
 * Restore the signal info from the context.
 */
1152
static inline void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1153
{
1154
    struct ntdll_thread_data * const regs = ntdll_get_thread_data();
1155 1156
    FLOATING_SAVE_AREA *fpu = FPU_sig(sigcontext);
    XMM_SAVE_AREA32 *fpux = FPUX_sig(sigcontext);
1157 1158 1159 1160 1161 1162 1163

    regs->dr0 = context->Dr0;
    regs->dr1 = context->Dr1;
    regs->dr2 = context->Dr2;
    regs->dr3 = context->Dr3;
    regs->dr6 = context->Dr6;
    regs->dr7 = context->Dr7;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    EAX_sig(sigcontext) = context->Eax;
    EBX_sig(sigcontext) = context->Ebx;
    ECX_sig(sigcontext) = context->Ecx;
    EDX_sig(sigcontext) = context->Edx;
    ESI_sig(sigcontext) = context->Esi;
    EDI_sig(sigcontext) = context->Edi;
    EBP_sig(sigcontext) = context->Ebp;
    EFL_sig(sigcontext) = context->EFlags;
    EIP_sig(sigcontext) = context->Eip;
    ESP_sig(sigcontext) = context->Esp;
    CS_sig(sigcontext)  = context->SegCs;
    DS_sig(sigcontext)  = context->SegDs;
    ES_sig(sigcontext)  = context->SegEs;
    SS_sig(sigcontext)  = context->SegSs;
#ifdef GS_sig
    GS_sig(sigcontext)  = context->SegGs;
#else
    wine_set_gs( context->SegGs );
#endif
#ifdef FS_sig
    FS_sig(sigcontext)  = context->SegFs;
#else
    wine_set_fs( context->SegFs );
#endif
1188

1189 1190 1191
    if (fpu) *fpu = context->FloatSave;
    if (fpux) memcpy( fpux, context->ExtendedRegisters, sizeof(*fpux) );
    if (!fpu && !fpux) restore_fpu( context );
1192 1193 1194
}


1195
/***********************************************************************
1196
 *		RtlCaptureContext (NTDLL.@)
1197
 */
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
__ASM_STDCALL_FUNC( RtlCaptureContext, 4,
                    "pushl %eax\n\t"
                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                    "movl 8(%esp),%eax\n\t"    /* context */
                    "movl $0x10007,(%eax)\n\t" /* context->ContextFlags */
                    "movw %gs,0x8c(%eax)\n\t"  /* context->SegGs */
                    "movw %fs,0x90(%eax)\n\t"  /* context->SegFs */
                    "movw %es,0x94(%eax)\n\t"  /* context->SegEs */
                    "movw %ds,0x98(%eax)\n\t"  /* context->SegDs */
                    "movl %edi,0x9c(%eax)\n\t" /* context->Edi */
                    "movl %esi,0xa0(%eax)\n\t" /* context->Esi */
                    "movl %ebx,0xa4(%eax)\n\t" /* context->Ebx */
                    "movl %edx,0xa8(%eax)\n\t" /* context->Edx */
                    "movl %ecx,0xac(%eax)\n\t" /* context->Ecx */
                    "movl %ebp,0xb4(%eax)\n\t" /* context->Ebp */
                    "movl 4(%esp),%edx\n\t"
                    "movl %edx,0xb8(%eax)\n\t" /* context->Eip */
                    "movw %cs,0xbc(%eax)\n\t"  /* context->SegCs */
                    "pushfl\n\t"
                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                    "popl 0xc0(%eax)\n\t"      /* context->EFlags */
                    __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
                    "leal 8(%esp),%edx\n\t"
                    "movl %edx,0xc4(%eax)\n\t" /* context->Esp */
                    "movw %ss,0xc8(%eax)\n\t"  /* context->SegSs */
                    "popl 0xb0(%eax)\n\t"      /* context->Eax */
                    __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
                    "ret $4" )
1226 1227


1228 1229 1230
/***********************************************************************
 *           set_cpu_context
 *
1231
 * Set the new CPU context. Used by NtSetContextThread.
1232
 */
1233
void set_cpu_context( const CONTEXT *context )
1234 1235 1236
{
    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 );
1239

1240 1241
    if (flags & CONTEXT_DEBUG_REGISTERS)
    {
1242 1243 1244 1245 1246 1247
        ntdll_get_thread_data()->dr0 = context->Dr0;
        ntdll_get_thread_data()->dr1 = context->Dr1;
        ntdll_get_thread_data()->dr2 = context->Dr2;
        ntdll_get_thread_data()->dr3 = context->Dr3;
        ntdll_get_thread_data()->dr6 = context->Dr6;
        ntdll_get_thread_data()->dr7 = context->Dr7;
1248
    }
1249 1250
    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 1256 1257 1258 1259 1260 1261
        else
        {
            CONTEXT newcontext = *context;
            newcontext.SegDs = wine_get_ds();
            newcontext.SegEs = wine_get_es();
            newcontext.SegFs = wine_get_fs();
            newcontext.SegGs = wine_get_gs();
1262
            __wine_restore_regs( &newcontext );
1263
        }
1264
    }
1265 1266 1267
}


1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
/***********************************************************************
 *           set_debug_registers
 */
static void set_debug_registers( const CONTEXT *context )
{
    DWORD flags = context->ContextFlags & ~CONTEXT_i386;
    context_t server_context;

    if (!(flags & CONTEXT_DEBUG_REGISTERS)) return;
    if (ntdll_get_thread_data()->dr0 == context->Dr0 &&
        ntdll_get_thread_data()->dr1 == context->Dr1 &&
        ntdll_get_thread_data()->dr2 == context->Dr2 &&
        ntdll_get_thread_data()->dr3 == context->Dr3 &&
        ntdll_get_thread_data()->dr6 == context->Dr6 &&
        ntdll_get_thread_data()->dr7 == context->Dr7) return;

    context_to_server( &server_context, context );

    SERVER_START_REQ( set_thread_context )
    {
        req->handle  = wine_server_obj_handle( GetCurrentThread() );
        req->suspend = 0;
        wine_server_add_data( req, &server_context, sizeof(server_context) );
        wine_server_call( req );
    }
    SERVER_END_REQ;
}


1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
/***********************************************************************
 *           copy_context
 *
 * Copy a register context according to the flags.
 */
void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
{
    flags &= ~CONTEXT_i386;  /* get rid of CPU id */
    if (flags & CONTEXT_INTEGER)
    {
        to->Eax = from->Eax;
        to->Ebx = from->Ebx;
        to->Ecx = from->Ecx;
        to->Edx = from->Edx;
        to->Esi = from->Esi;
        to->Edi = from->Edi;
    }
    if (flags & CONTEXT_CONTROL)
    {
        to->Ebp    = from->Ebp;
        to->Esp    = from->Esp;
        to->Eip    = from->Eip;
        to->SegCs  = from->SegCs;
        to->SegSs  = from->SegSs;
        to->EFlags = from->EFlags;
    }
    if (flags & CONTEXT_SEGMENTS)
    {
        to->SegDs = from->SegDs;
        to->SegEs = from->SegEs;
        to->SegFs = from->SegFs;
        to->SegGs = from->SegGs;
    }
    if (flags & CONTEXT_DEBUG_REGISTERS)
    {
        to->Dr0 = from->Dr0;
        to->Dr1 = from->Dr1;
        to->Dr2 = from->Dr2;
        to->Dr3 = from->Dr3;
        to->Dr6 = from->Dr6;
        to->Dr7 = from->Dr7;
    }
    if (flags & CONTEXT_FLOATING_POINT)
    {
        to->FloatSave = from->FloatSave;
    }
    if (flags & CONTEXT_EXTENDED_REGISTERS)
    {
        memcpy( to->ExtendedRegisters, from->ExtendedRegisters, sizeof(to->ExtendedRegisters) );
    }
}


1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
/***********************************************************************
 *           context_to_server
 *
 * Convert a register context to the server format.
 */
NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
{
    DWORD flags = from->ContextFlags & ~CONTEXT_i386;  /* get rid of CPU id */

    memset( to, 0, sizeof(*to) );
    to->cpu = CPU_x86;

    if (flags & CONTEXT_CONTROL)
    {
        to->flags |= SERVER_CTX_CONTROL;
        to->ctl.i386_regs.ebp    = from->Ebp;
        to->ctl.i386_regs.esp    = from->Esp;
        to->ctl.i386_regs.eip    = from->Eip;
        to->ctl.i386_regs.cs     = from->SegCs;
        to->ctl.i386_regs.ss     = from->SegSs;
        to->ctl.i386_regs.eflags = from->EFlags;
    }
    if (flags & CONTEXT_INTEGER)
    {
        to->flags |= SERVER_CTX_INTEGER;
        to->integer.i386_regs.eax = from->Eax;
        to->integer.i386_regs.ebx = from->Ebx;
        to->integer.i386_regs.ecx = from->Ecx;
        to->integer.i386_regs.edx = from->Edx;
        to->integer.i386_regs.esi = from->Esi;
        to->integer.i386_regs.edi = from->Edi;
    }
    if (flags & CONTEXT_SEGMENTS)
    {
        to->flags |= SERVER_CTX_SEGMENTS;
        to->seg.i386_regs.ds = from->SegDs;
        to->seg.i386_regs.es = from->SegEs;
        to->seg.i386_regs.fs = from->SegFs;
        to->seg.i386_regs.gs = from->SegGs;
    }
    if (flags & CONTEXT_FLOATING_POINT)
    {
        to->flags |= SERVER_CTX_FLOATING_POINT;
        to->fp.i386_regs.ctrl     = from->FloatSave.ControlWord;
        to->fp.i386_regs.status   = from->FloatSave.StatusWord;
        to->fp.i386_regs.tag      = from->FloatSave.TagWord;
        to->fp.i386_regs.err_off  = from->FloatSave.ErrorOffset;
        to->fp.i386_regs.err_sel  = from->FloatSave.ErrorSelector;
        to->fp.i386_regs.data_off = from->FloatSave.DataOffset;
        to->fp.i386_regs.data_sel = from->FloatSave.DataSelector;
        to->fp.i386_regs.cr0npx   = from->FloatSave.Cr0NpxState;
        memcpy( to->fp.i386_regs.regs, from->FloatSave.RegisterArea, sizeof(to->fp.i386_regs.regs) );
    }
    if (flags & CONTEXT_DEBUG_REGISTERS)
    {
        to->flags |= SERVER_CTX_DEBUG_REGISTERS;
        to->debug.i386_regs.dr0 = from->Dr0;
        to->debug.i386_regs.dr1 = from->Dr1;
        to->debug.i386_regs.dr2 = from->Dr2;
        to->debug.i386_regs.dr3 = from->Dr3;
        to->debug.i386_regs.dr6 = from->Dr6;
        to->debug.i386_regs.dr7 = from->Dr7;
    }
    if (flags & CONTEXT_EXTENDED_REGISTERS)
    {
        to->flags |= SERVER_CTX_EXTENDED_REGISTERS;
        memcpy( to->ext.i386_regs, from->ExtendedRegisters, sizeof(to->ext.i386_regs) );
    }
    return STATUS_SUCCESS;
}


/***********************************************************************
 *           context_from_server
 *
 * Convert a register context from the server format.
 */
NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
{
    if (from->cpu != CPU_x86) return STATUS_INVALID_PARAMETER;

    to->ContextFlags = CONTEXT_i386;
    if (from->flags & SERVER_CTX_CONTROL)
    {
        to->ContextFlags |= CONTEXT_CONTROL;
        to->Ebp    = from->ctl.i386_regs.ebp;
        to->Esp    = from->ctl.i386_regs.esp;
        to->Eip    = from->ctl.i386_regs.eip;
        to->SegCs  = from->ctl.i386_regs.cs;
        to->SegSs  = from->ctl.i386_regs.ss;
        to->EFlags = from->ctl.i386_regs.eflags;
    }
    if (from->flags & SERVER_CTX_INTEGER)
    {
        to->ContextFlags |= CONTEXT_INTEGER;
        to->Eax = from->integer.i386_regs.eax;
        to->Ebx = from->integer.i386_regs.ebx;
        to->Ecx = from->integer.i386_regs.ecx;
        to->Edx = from->integer.i386_regs.edx;
        to->Esi = from->integer.i386_regs.esi;
        to->Edi = from->integer.i386_regs.edi;
    }
    if (from->flags & SERVER_CTX_SEGMENTS)
    {
        to->ContextFlags |= CONTEXT_SEGMENTS;
        to->SegDs = from->seg.i386_regs.ds;
        to->SegEs = from->seg.i386_regs.es;
        to->SegFs = from->seg.i386_regs.fs;
        to->SegGs = from->seg.i386_regs.gs;
    }
    if (from->flags & SERVER_CTX_FLOATING_POINT)
    {
        to->ContextFlags |= CONTEXT_FLOATING_POINT;
        to->FloatSave.ControlWord   = from->fp.i386_regs.ctrl;
        to->FloatSave.StatusWord    = from->fp.i386_regs.status;
        to->FloatSave.TagWord       = from->fp.i386_regs.tag;
        to->FloatSave.ErrorOffset   = from->fp.i386_regs.err_off;
        to->FloatSave.ErrorSelector = from->fp.i386_regs.err_sel;
        to->FloatSave.DataOffset    = from->fp.i386_regs.data_off;
        to->FloatSave.DataSelector  = from->fp.i386_regs.data_sel;
        to->FloatSave.Cr0NpxState   = from->fp.i386_regs.cr0npx;
        memcpy( to->FloatSave.RegisterArea, from->fp.i386_regs.regs, sizeof(to->FloatSave.RegisterArea) );
    }
    if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
    {
        to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
        to->Dr0 = from->debug.i386_regs.dr0;
        to->Dr1 = from->debug.i386_regs.dr1;
        to->Dr2 = from->debug.i386_regs.dr2;
        to->Dr3 = from->debug.i386_regs.dr3;
        to->Dr6 = from->debug.i386_regs.dr6;
        to->Dr7 = from->debug.i386_regs.dr7;
    }
    if (from->flags & SERVER_CTX_EXTENDED_REGISTERS)
    {
        to->ContextFlags |= CONTEXT_EXTENDED_REGISTERS;
        memcpy( to->ExtendedRegisters, from->ext.i386_regs, sizeof(to->ExtendedRegisters) );
    }
    return STATUS_SUCCESS;
}


1492 1493 1494 1495 1496 1497
/***********************************************************************
 *           is_privileged_instr
 *
 * Check if the fault location is a privileged instruction.
 * Based on the instruction emulation code in dlls/kernel/instr.c.
 */
1498
static inline DWORD is_privileged_instr( CONTEXT *context )
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
{
    const BYTE *instr;
    unsigned int prefix_count = 0;

    if (!wine_ldt_is_system( context->SegCs )) return 0;
    instr = (BYTE *)context->Eip;

    for (;;) switch(*instr)
    {
    /* instruction prefixes */
    case 0x2e:  /* %cs: */
    case 0x36:  /* %ss: */
    case 0x3e:  /* %ds: */
    case 0x26:  /* %es: */
    case 0x64:  /* %fs: */
    case 0x65:  /* %gs: */
    case 0x66:  /* opcode size */
    case 0x67:  /* addr size */
    case 0xf0:  /* lock */
    case 0xf2:  /* repne */
    case 0xf3:  /* repe */
1520
        if (++prefix_count >= 15) return EXCEPTION_ILLEGAL_INSTRUCTION;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
        instr++;
        continue;

    case 0x0f: /* extended instruction */
        switch(instr[1])
        {
        case 0x20: /* mov crX, reg */
        case 0x21: /* mov drX, reg */
        case 0x22: /* mov reg, crX */
        case 0x23: /* mov reg drX */
1531
            return EXCEPTION_PRIV_INSTRUCTION;
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        }
        return 0;
    case 0x6c: /* insb (%dx) */
    case 0x6d: /* insl (%dx) */
    case 0x6e: /* outsb (%dx) */
    case 0x6f: /* outsl (%dx) */
    case 0xcd: /* int $xx */
    case 0xe4: /* inb al,XX */
    case 0xe5: /* in (e)ax,XX */
    case 0xe6: /* outb XX,al */
    case 0xe7: /* out XX,(e)ax */
    case 0xec: /* inb (%dx),%al */
    case 0xed: /* inl (%dx),%eax */
    case 0xee: /* outb %al,(%dx) */
    case 0xef: /* outl %eax,(%dx) */
    case 0xf4: /* hlt */
    case 0xfa: /* cli */
    case 0xfb: /* sti */
1550
        return EXCEPTION_PRIV_INSTRUCTION;
1551 1552 1553 1554 1555
    default:
        return 0;
    }
}

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

/***********************************************************************
 *           handle_interrupt
 *
 * Handle an interrupt.
 */
static inline BOOL handle_interrupt( unsigned int interrupt, EXCEPTION_RECORD *rec, CONTEXT *context )
{
    switch(interrupt)
    {
    case 0x2d:
        context->Eip += 3;
        rec->ExceptionCode = EXCEPTION_BREAKPOINT;
        rec->ExceptionAddress = (void *)context->Eip;
        rec->NumberParameters = is_wow64 ? 1 : 3;
        rec->ExceptionInformation[0] = context->Eax;
        rec->ExceptionInformation[1] = context->Ecx;
        rec->ExceptionInformation[2] = context->Edx;
        return TRUE;
    default:
        return FALSE;
    }
}


1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
/***********************************************************************
 *           check_invalid_gs
 *
 * Check for fault caused by invalid %gs value (some copy protection schemes mess with it).
 */
static inline BOOL check_invalid_gs( CONTEXT *context )
{
    unsigned int prefix_count = 0;
    const BYTE *instr = (BYTE *)context->Eip;
    WORD system_gs = ntdll_get_thread_data()->gs;

    if (context->SegGs == system_gs) return FALSE;
    if (!wine_ldt_is_system( context->SegCs )) return FALSE;
    /* only handle faults in system libraries */
    if (virtual_is_valid_code_address( instr, 1 )) return FALSE;

    for (;;) switch(*instr)
    {
    /* instruction prefixes */
    case 0x2e:  /* %cs: */
    case 0x36:  /* %ss: */
    case 0x3e:  /* %ds: */
    case 0x26:  /* %es: */
    case 0x64:  /* %fs: */
    case 0x66:  /* opcode size */
    case 0x67:  /* addr size */
    case 0xf0:  /* lock */
    case 0xf2:  /* repne */
    case 0xf3:  /* repe */
        if (++prefix_count >= 15) return FALSE;
        instr++;
        continue;
    case 0x65:  /* %gs: */
        TRACE( "%04x/%04x at %p, fixing up\n", context->SegGs, system_gs, instr );
        context->SegGs = system_gs;
        return TRUE;
    default:
        return FALSE;
    }
}

1622

1623
#include "pshpack1.h"
1624
union atl_thunk
1625
{
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    struct
    {
        DWORD movl;  /* movl this,4(%esp) */
        DWORD this;
        BYTE  jmp;   /* jmp func */
        int   func;
    } t1;
    struct
    {
        BYTE  movl;  /* movl this,ecx */
        DWORD this;
        BYTE  jmp;   /* jmp func */
        int   func;
    } t2;
1640 1641 1642 1643 1644 1645 1646 1647
    struct
    {
        BYTE  movl1; /* movl this,edx */
        DWORD this;
        BYTE  movl2; /* movl func,ecx */
        DWORD func;
        WORD  jmp;   /* jmp ecx */
    } t3;
1648 1649 1650 1651 1652 1653 1654 1655
    struct
    {
        BYTE  movl1; /* movl this,ecx */
        DWORD this;
        BYTE  movl2; /* movl func,eax */
        DWORD func;
        WORD  jmp;   /* jmp eax */
    } t4;
1656 1657 1658 1659 1660 1661 1662 1663
    struct
    {
        DWORD inst1; /* pop ecx
                      * pop eax
                      * push ecx
                      * jmp 4(%eax) */
        WORD  inst2;
    } t5;
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
};
#include "poppack.h"

/**********************************************************************
 *		check_atl_thunk
 *
 * Check if code destination is an ATL thunk, and emulate it if so.
 */
static BOOL check_atl_thunk( EXCEPTION_RECORD *rec, CONTEXT *context )
{
1674 1675 1676
    const union atl_thunk *thunk = (const union atl_thunk *)rec->ExceptionInformation[1];
    union atl_thunk thunk_copy;
    SIZE_T thunk_len;
1677

1678 1679
    thunk_len = virtual_uninterrupted_read_memory( thunk, &thunk_copy, sizeof(*thunk) );
    if (!thunk_len) return FALSE;
1680

1681 1682
    if (thunk_len >= sizeof(thunk_copy.t1) && thunk_copy.t1.movl == 0x042444c7 &&
                                              thunk_copy.t1.jmp == 0xe9)
1683
    {
1684
        if (virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
1685
            &thunk_copy.t1.this, sizeof(DWORD) ) == sizeof(DWORD))
1686
        {
1687 1688 1689 1690
            context->Eip = (DWORD_PTR)(&thunk->t1.func + 1) + thunk_copy.t1.func;
            TRACE( "emulating ATL thunk type 1 at %p, func=%08x arg=%08x\n",
                   thunk, context->Eip, thunk_copy.t1.this );
            return TRUE;
1691 1692
        }
    }
1693 1694 1695 1696 1697 1698 1699 1700 1701
    else if (thunk_len >= sizeof(thunk_copy.t2) && thunk_copy.t2.movl == 0xb9 &&
                                                   thunk_copy.t2.jmp == 0xe9)
    {
        context->Ecx = thunk_copy.t2.this;
        context->Eip = (DWORD_PTR)(&thunk->t2.func + 1) + thunk_copy.t2.func;
        TRACE( "emulating ATL thunk type 2 at %p, func=%08x ecx=%08x\n",
               thunk, context->Eip, context->Ecx );
        return TRUE;
    }
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    else if (thunk_len >= sizeof(thunk_copy.t3) && thunk_copy.t3.movl1 == 0xba &&
                                                   thunk_copy.t3.movl2 == 0xb9 &&
                                                   thunk_copy.t3.jmp == 0xe1ff)
    {
        context->Edx = thunk_copy.t3.this;
        context->Ecx = thunk_copy.t3.func;
        context->Eip = thunk_copy.t3.func;
        TRACE( "emulating ATL thunk type 3 at %p, func=%08x ecx=%08x edx=%08x\n",
               thunk, context->Eip, context->Ecx, context->Edx );
        return TRUE;
    }
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    else if (thunk_len >= sizeof(thunk_copy.t4) && thunk_copy.t4.movl1 == 0xb9 &&
                                                   thunk_copy.t4.movl2 == 0xb8 &&
                                                   thunk_copy.t4.jmp == 0xe0ff)
    {
        context->Ecx = thunk_copy.t4.this;
        context->Eax = thunk_copy.t4.func;
        context->Eip = thunk_copy.t4.func;
        TRACE( "emulating ATL thunk type 4 at %p, func=%08x eax=%08x ecx=%08x\n",
               thunk, context->Eip, context->Eax, context->Ecx );
        return TRUE;
    }
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
    else if (thunk_len >= sizeof(thunk_copy.t5) && thunk_copy.t5.inst1 == 0xff515859 &&
                                                   thunk_copy.t5.inst2 == 0x0460)
    {
        DWORD func, stack[2];
        if (virtual_uninterrupted_read_memory( (DWORD *)context->Esp,
            stack, sizeof(stack) ) == sizeof(stack) &&
            virtual_uninterrupted_read_memory( (DWORD *)stack[1] + 1,
            &func, sizeof(DWORD) ) == sizeof(DWORD) &&
            virtual_uninterrupted_write_memory( (DWORD *)context->Esp + 1,
            &stack[0], sizeof(stack[0]) ) == sizeof(stack[0]))
        {
            context->Ecx = stack[0];
            context->Eax = stack[1];
            context->Esp = context->Esp + sizeof(DWORD);
            context->Eip = func;
            TRACE( "emulating ATL thunk type 5 at %p, func=%08x eax=%08x ecx=%08x esp=%08x\n",
                   thunk, context->Eip, context->Eax, context->Ecx, context->Esp );
            return TRUE;
        }
    }
1744

1745
    return FALSE;
1746 1747 1748
}


1749
/***********************************************************************
1750
 *           setup_exception_record
1751
 *
1752
 * Setup the exception record and context on the thread stack.
1753
 */
1754
static EXCEPTION_RECORD *setup_exception_record( ucontext_t *sigcontext, void *stack_ptr,
1755
                                                 WORD fs, WORD gs, raise_func func )
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
{
    struct stack_layout
    {
        void             *ret_addr;      /* return address from raise_func */
        EXCEPTION_RECORD *rec_ptr;       /* first arg for raise_func */
        CONTEXT          *context_ptr;   /* second arg for raise_func */
        CONTEXT           context;
        EXCEPTION_RECORD  rec;
        DWORD             ebp;
        DWORD             eip;
1766
    } *stack = stack_ptr;
1767
    DWORD exception_code = 0;
1768 1769 1770

    /* stack sanity checks */

1771
    if ((char *)stack >= (char *)get_signal_stack() &&
1772
        (char *)stack < (char *)get_signal_stack() + signal_stack_size)
1773
    {
1774 1775 1776 1777
        WINE_ERR( "nested exception on signal stack in thread %04x eip %08x esp %08x stack %p-%p\n",
                  GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
                  (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
                  NtCurrentTeb()->Tib.StackBase );
1778
        abort_thread(1);
1779 1780
    }

1781
    if (stack - 1 > stack || /* check for overflow in subtraction */
1782
        (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
1783 1784
        (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
    {
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
        WARN( "exception outside of stack limits in thread %04x eip %08x esp %08x stack %p-%p\n",
              GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
              (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->Tib.StackLimit,
              NtCurrentTeb()->Tib.StackBase );
    }
    else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->DeallocationStack + 4096)
    {
        /* stack overflow on last page, unrecoverable */
        UINT diff = (char *)NtCurrentTeb()->DeallocationStack + 4096 - (char *)(stack - 1);
        WINE_ERR( "stack overflow %u bytes in thread %04x eip %08x esp %08x stack %p-%p-%p\n",
                  diff, GetCurrentThreadId(), (unsigned int) EIP_sig(sigcontext),
                  (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
                  NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1798
        abort_thread(1);
1799 1800 1801 1802 1803 1804
    }
    else if ((char *)(stack - 1) < (char *)NtCurrentTeb()->Tib.StackLimit)
    {
        /* stack access below stack limit, may be recoverable */
        if (virtual_handle_stack_fault( stack - 1 )) exception_code = EXCEPTION_STACK_OVERFLOW;
        else
1805
        {
1806 1807
            UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
            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 1810
                      (unsigned int) ESP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
                      NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1811
            abort_thread(1);
1812
        }
1813 1814 1815
    }

    stack--;  /* push the stack_layout structure */
1816 1817 1818
#if defined(VALGRIND_MAKE_MEM_UNDEFINED)
    VALGRIND_MAKE_MEM_UNDEFINED(stack, sizeof(*stack));
#elif defined(VALGRIND_MAKE_WRITABLE)
1819 1820
    VALGRIND_MAKE_WRITABLE(stack, sizeof(*stack));
#endif
1821
    stack->ret_addr     = (void *)0xdeadbabe;  /* raise_func must not return */
1822 1823 1824 1825
    stack->rec_ptr      = &stack->rec;
    stack->context_ptr  = &stack->context;

    stack->rec.ExceptionRecord  = NULL;
1826
    stack->rec.ExceptionCode    = exception_code;
1827 1828 1829 1830
    stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
    stack->rec.ExceptionAddress = (LPVOID)EIP_sig(sigcontext);
    stack->rec.NumberParameters = 0;

1831
    save_context( &stack->context, sigcontext, fs, gs );
1832 1833 1834 1835

    /* now modify the sigcontext to return to the raise function */
    ESP_sig(sigcontext) = (DWORD)stack;
    EIP_sig(sigcontext) = (DWORD)func;
1836 1837
    /* clear single-step, direction, and align check flag */
    EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
    CS_sig(sigcontext)  = wine_get_cs();
    DS_sig(sigcontext)  = wine_get_ds();
    ES_sig(sigcontext)  = wine_get_es();
    FS_sig(sigcontext)  = wine_get_fs();
    GS_sig(sigcontext)  = wine_get_gs();
    SS_sig(sigcontext)  = wine_get_ss();

    return stack->rec_ptr;
}


1849 1850 1851 1852 1853 1854 1855
/***********************************************************************
 *           setup_exception
 *
 * Setup a proper stack frame for the raise function, and modify the
 * sigcontext so that the return from the signal handler will call
 * the raise function.
 */
1856
static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
1857 1858 1859 1860 1861 1862 1863 1864
{
    WORD fs, gs;
    void *stack = init_handler( sigcontext, &fs, &gs );

    return setup_exception_record( sigcontext, stack, fs, gs, func );
}


1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
/***********************************************************************
 *           get_exception_context
 *
 * Get a pointer to the context built by setup_exception.
 */
static inline CONTEXT *get_exception_context( EXCEPTION_RECORD *rec )
{
    return (CONTEXT *)rec - 1;  /* cf. stack_layout structure */
}


1876 1877 1878 1879 1880 1881 1882
/**********************************************************************
 *		get_fpu_code
 *
 * Get the FPU exception code from the FPU status.
 */
static inline DWORD get_fpu_code( const CONTEXT *context )
{
1883
    DWORD status = context->FloatSave.StatusWord & ~(context->FloatSave.ControlWord & 0x3f);
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901

    if (status & 0x01)  /* IE */
    {
        if (status & 0x40)  /* SF */
            return EXCEPTION_FLT_STACK_CHECK;
        else
            return EXCEPTION_FLT_INVALID_OPERATION;
    }
    if (status & 0x02) return EXCEPTION_FLT_DENORMAL_OPERAND;  /* DE flag */
    if (status & 0x04) return EXCEPTION_FLT_DIVIDE_BY_ZERO;    /* ZE flag */
    if (status & 0x08) return EXCEPTION_FLT_OVERFLOW;          /* OE flag */
    if (status & 0x10) return EXCEPTION_FLT_UNDERFLOW;         /* UE flag */
    if (status & 0x20) return EXCEPTION_FLT_INEXACT_RESULT;    /* PE flag */
    return EXCEPTION_FLT_INVALID_OPERATION;  /* generic error */
}


/**********************************************************************
1902
 *		raise_segv_exception
1903
 */
1904
static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1905
{
1906 1907
    NTSTATUS status;

1908
    switch(rec->ExceptionCode)
1909
    {
1910 1911
    case EXCEPTION_ACCESS_VIOLATION:
        if (rec->NumberParameters == 2)
1912
        {
1913 1914
            if (rec->ExceptionInformation[1] == 0xffffffff && check_invalid_gs( context ))
                goto done;
1915
            if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
1916
                                                             rec->ExceptionInformation[0], FALSE )))
1917
                goto done;
1918 1919
            if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION &&
                rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT)
1920 1921
            {
                ULONG flags;
1922 1923 1924 1925
                NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
                                           &flags, sizeof(flags), NULL );

                if (!(flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION) && check_atl_thunk( rec, context ))
1926 1927 1928
                    goto done;

                /* send EXCEPTION_EXECUTE_FAULT only if data execution prevention is enabled */
1929 1930 1931
                if (!(flags & MEM_EXECUTE_OPTION_DISABLE))
                    rec->ExceptionInformation[0] = EXCEPTION_READ_FAULT;
            }
1932
        }
1933
        break;
1934
    case EXCEPTION_DATATYPE_MISALIGNMENT:
1935
        /* FIXME: pass through exception handler first? */
1936
        if (context->EFlags & 0x00040000)
1937 1938
        {
            /* Disable AC flag, return */
1939
            context->EFlags &= ~0x00040000;
1940
            goto done;
1941
        }
1942
        break;
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
    case EXCEPTION_BREAKPOINT:
        if (!is_wow64)
        {
            /* On Wow64, the upper DWORD of Rax contains garbage, and the debug
             * service is usually not recognized when called from usermode. */
            switch (rec->ExceptionInformation[0])
            {
                case 1: /* BREAKPOINT_PRINT */
                case 3: /* BREAKPOINT_LOAD_SYMBOLS */
                case 4: /* BREAKPOINT_UNLOAD_SYMBOLS */
                case 5: /* BREAKPOINT_COMMAND_STRING (>= Win2003) */
                    goto done;
            }
        }
        break;
1958
    }
1959
    status = NtRaiseException( rec, context, TRUE );
1960
    raise_status( status, rec );
1961
done:
1962
    set_cpu_context( context );
1963 1964 1965 1966
}


/**********************************************************************
1967
 *		raise_trap_exception
1968
 */
1969
static void WINAPI raise_trap_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
1970
{
1971 1972
    NTSTATUS status;

1973
    if (rec->ExceptionCode == EXCEPTION_SINGLE_STEP)
1974
    {
1975 1976 1977 1978
        /* when single stepping can't tell whether this is a hw bp or a
         * single step interrupt. try to avoid as much overhead as possible
         * and only do a server call if there is any hw bp enabled. */

1979
        if( !(context->EFlags & 0x100) || (ntdll_get_thread_data()->dr7 & 0xff) )
1980
        {
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 */
1986
        }
1987 1988

        context->EFlags &= ~0x100;  /* clear single-step flag */
1989
    }
1990

1991
    status = NtRaiseException( rec, context, TRUE );
1992
    raise_status( status, rec );
1993 1994 1995 1996
}


/**********************************************************************
1997
 *		raise_generic_exception
1998 1999
 *
 * Generic raise function for exceptions that don't need special treatment.
2000
 */
2001
static void WINAPI raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2002
{
2003 2004 2005
    NTSTATUS status;

    status = NtRaiseException( rec, context, TRUE );
2006
    raise_status( status, rec );
2007 2008 2009
}


2010
#ifdef __HAVE_VM86
2011
/**********************************************************************
2012
 *		raise_vm86_sti_exception
2013
 */
2014
static void WINAPI raise_vm86_sti_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
2015
{
2016
    /* merge_vm86_pending_flags merges the vm86_pending flag in safely */
2017
    get_vm86_teb_info()->vm86_pending |= VIP_FLAG;
2018

2019
    if (ntdll_get_thread_data()->vm86_ptr)
2020
    {
2021 2022 2023 2024
        if (((char*)context->Eip >= (char*)vm86_return) &&
            ((char*)context->Eip <= (char*)vm86_return_end) &&
            (VM86_TYPE(context->Eax) != VM86_SIGNAL)) {
            /* exiting from VM86, can't throw */
2025
            goto done;
2026
        }
2027
        merge_vm86_pending_flags( rec );
2028
    }
2029
    else if (get_vm86_teb_info()->dpmi_vif &&
2030 2031
             !wine_ldt_is_system(context->SegCs) &&
             !wine_ldt_is_system(context->SegSs))
2032 2033
    {
        /* Executing DPMI code and virtual interrupts are enabled. */
2034
        get_vm86_teb_info()->vm86_pending = 0;
2035
        NtRaiseException( rec, context, TRUE );
2036
    }
2037
done:
2038
    set_cpu_context( context );
2039 2040 2041
}


2042 2043 2044 2045 2046
/**********************************************************************
 *		usr2_handler
 *
 * Handler for SIGUSR2.
 * We use it to signal that the running __wine_enter_vm86() should
2047
 * immediately set VIP_FLAG, causing pending events to be handled
2048 2049
 * as early as possible.
 */
2050
static void usr2_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2051
{
2052
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_vm86_sti_exception );
2053
    rec->ExceptionCode = EXCEPTION_VM86_STI;
2054
}
2055
#endif /* __HAVE_VM86 */
2056 2057


2058 2059 2060 2061 2062
/**********************************************************************
 *		segv_handler
 *
 * Handler for SIGSEGV and related errors.
 */
2063
static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2064
{
2065 2066
    WORD fs, gs;
    EXCEPTION_RECORD *rec;
2067
    ucontext_t *context = sigcontext;
2068 2069
    void *stack = init_handler( sigcontext, &fs, &gs );

2070 2071 2072 2073 2074 2075 2076 2077 2078
    /* check for exceptions on the signal stack caused by write watches */
    if (get_trap_code(context) == TRAP_x86_PAGEFLT &&
        (char *)stack >= (char *)get_signal_stack() &&
        (char *)stack < (char *)get_signal_stack() + signal_stack_size &&
        !virtual_handle_fault( siginfo->si_addr, (get_error_code(context) >> 1) & 0x09, TRUE ))
    {
        return;
    }

2079 2080 2081 2082 2083
    /* check for page fault inside the thread stack */
    if (get_trap_code(context) == TRAP_x86_PAGEFLT &&
        (char *)siginfo->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
        (char *)siginfo->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
        virtual_handle_stack_fault( siginfo->si_addr ))
2084 2085 2086 2087 2088 2089 2090
    {
        /* check if this was the last guard page */
        if ((char *)siginfo->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
        {
            rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
            rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
        }
2091
        return;
2092
    }
2093 2094

    rec = setup_exception_record( context, stack, fs, gs, raise_segv_exception );
2095
    if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
2096

2097
    switch(get_trap_code(context))
2098
    {
2099
    case TRAP_x86_OFLOW:   /* Overflow exception */
2100 2101
        rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
        break;
2102
    case TRAP_x86_BOUND:   /* Bound range exception */
2103 2104
        rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
        break;
2105
    case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
2106 2107
        rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
        break;
2108
    case TRAP_x86_STKFLT:  /* Stack fault */
2109 2110
        rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
        break;
2111 2112 2113
    case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
    case TRAP_x86_PROTFLT:   /* General protection fault */
    case TRAP_x86_UNKNOWN:   /* Unknown fault code */
2114
        {
2115
            CONTEXT *win_context = get_exception_context( rec );
2116
            WORD err = get_error_code(context);
2117 2118
            if (!err && (rec->ExceptionCode = is_privileged_instr( win_context ))) break;
            if ((err & 7) == 2 && handle_interrupt( err >> 3, rec, win_context )) break;
2119 2120 2121 2122
            rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
            rec->NumberParameters = 2;
            rec->ExceptionInformation[0] = 0;
            /* if error contains a LDT selector, use that as fault address */
2123 2124 2125 2126
            if ((err & 7) == 4 && !wine_ldt_is_system( err | 7 ))
                rec->ExceptionInformation[1] = err & ~7;
            else
                rec->ExceptionInformation[1] = 0xffffffff;
2127
        }
2128
        break;
2129
    case TRAP_x86_PAGEFLT:  /* Page fault */
2130 2131
        rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
        rec->NumberParameters = 2;
2132 2133
        rec->ExceptionInformation[0] = (get_error_code(context) >> 1) & 0x09;
        rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2134
        break;
2135
    case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
2136 2137 2138
        rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
        break;
    default:
2139
        WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
2140
        /* fall through */
2141 2142 2143 2144 2145 2146
    case TRAP_x86_NMI:       /* NMI interrupt */
    case TRAP_x86_DNA:       /* Device not available exception */
    case TRAP_x86_DOUBLEFLT: /* Double fault exception */
    case TRAP_x86_TSSFLT:    /* Invalid TSS exception */
    case TRAP_x86_MCHK:      /* Machine check exception */
    case TRAP_x86_CACHEFLT:  /* Cache flush exception */
2147 2148 2149
        rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
        break;
    }
2150 2151 2152 2153 2154 2155 2156 2157
}


/**********************************************************************
 *		trap_handler
 *
 * Handler for SIGTRAP.
 */
2158
static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2159
{
2160
    ucontext_t *context = sigcontext;
2161
    EXCEPTION_RECORD *rec = setup_exception( context, raise_trap_exception );
2162

2163
    switch(get_trap_code(context))
2164
    {
2165
    case TRAP_x86_TRCTRAP:  /* Single-step exception */
2166 2167
        rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
        break;
2168
    case TRAP_x86_BPTFLT:   /* Breakpoint exception */
2169 2170 2171 2172
        rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
        /* fall through */
    default:
        rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2173 2174 2175 2176
        rec->NumberParameters = is_wow64 ? 1 : 3;
        rec->ExceptionInformation[0] = 0;
        rec->ExceptionInformation[1] = 0; /* FIXME */
        rec->ExceptionInformation[2] = 0; /* FIXME */
2177 2178
        break;
    }
2179 2180 2181 2182 2183 2184 2185 2186
}


/**********************************************************************
 *		fpe_handler
 *
 * Handler for SIGFPE.
 */
2187
static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2188
{
2189
    CONTEXT *win_context;
2190
    ucontext_t *context = sigcontext;
2191
    EXCEPTION_RECORD *rec = setup_exception( context, raise_generic_exception );
2192

2193
    win_context = get_exception_context( rec );
2194

2195
    switch(get_trap_code(context))
2196
    {
2197
    case TRAP_x86_DIVIDE:   /* Division by zero exception */
2198 2199
        rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
        break;
2200
    case TRAP_x86_FPOPFLT:   /* Coprocessor segment overrun */
2201 2202
        rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
        break;
2203 2204
    case TRAP_x86_ARITHTRAP:  /* Floating point exception */
    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 2209 2210 2211
    case TRAP_x86_CACHEFLT:  /* SIMD exception */
        /* TODO:
         * Behaviour only tested for divide-by-zero exceptions
         * Check for other SIMD exceptions as well */
2212
        if(siginfo->si_code != FPE_FLTDIV && siginfo->si_code != FPE_FLTINV)
2213 2214 2215 2216 2217
            FIXME("untested SIMD exception: %#x. Might not work correctly\n",
                  siginfo->si_code);

        rec->ExceptionCode = STATUS_FLOAT_MULTIPLE_TRAPS;
        rec->NumberParameters = 1;
2218
        /* no idea what meaning is actually behind this but that's what native does */
2219 2220
        rec->ExceptionInformation[0] = 0;
        break;
2221
    default:
2222
        WINE_ERR( "Got unexpected trap %d\n", get_trap_code(context) );
2223 2224 2225
        rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
        break;
    }
2226 2227 2228 2229 2230 2231 2232
}


/**********************************************************************
 *		int_handler
 *
 * Handler for SIGINT.
2233 2234
 *
 * FIXME: should not be calling external functions on the signal stack.
2235
 */
2236
static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2237
{
2238
    WORD fs, gs;
2239
    init_handler( sigcontext, &fs, &gs );
2240
    if (!dispatch_signal(SIGINT))
2241
    {
2242
        EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2243
        rec->ExceptionCode = CONTROL_C_EXIT;
2244
    }
2245 2246
}

2247 2248 2249 2250 2251
/**********************************************************************
 *		abrt_handler
 *
 * Handler for SIGABRT.
 */
2252
static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2253
{
2254
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2255 2256
    rec->ExceptionCode  = EXCEPTION_WINE_ASSERTION;
    rec->ExceptionFlags = EH_NONCONTINUABLE;
2257 2258
}

2259

2260
/**********************************************************************
2261
 *		quit_handler
2262
 *
2263
 * Handler for SIGQUIT.
2264
 */
2265
static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2266
{
2267
    WORD fs, gs;
2268
    init_handler( sigcontext, &fs, &gs );
2269
    abort_thread(0);
2270 2271 2272
}


2273 2274 2275 2276 2277
/**********************************************************************
 *		usr1_handler
 *
 * Handler for SIGUSR1, used to signal a thread that it got suspended.
 */
2278
static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2279
{
2280
    CONTEXT context;
2281
    WORD fs, gs;
2282

2283 2284
    init_handler( sigcontext, &fs, &gs );
    save_context( &context, sigcontext, fs, gs );
2285
    wait_suspend( &context );
2286
    restore_context( &context, sigcontext );
2287 2288 2289
}


2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
/***********************************************************************
 *           __wine_set_signal_handler   (NTDLL.@)
 */
int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
{
    if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
    if (handlers[sig] != NULL) return -2;
    handlers[sig] = wsh;
    return 0;
}


2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
/***********************************************************************
 *           locking for LDT routines
 */
static RTL_CRITICAL_SECTION ldt_section;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &ldt_section,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
};
static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
static sigset_t ldt_sigset;

static void ldt_lock(void)
{
    sigset_t sigset;

    pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
    RtlEnterCriticalSection( &ldt_section );
    if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
}

static void ldt_unlock(void)
{
    if (ldt_section.RecursionCount == 1)
    {
        sigset_t sigset = ldt_sigset;
        RtlLeaveCriticalSection( &ldt_section );
        pthread_sigmask( SIG_SETMASK, &sigset, NULL );
    }
    else RtlLeaveCriticalSection( &ldt_section );
}


2336
/**********************************************************************
2337
 *		signal_alloc_thread
2338
 */
2339
NTSTATUS signal_alloc_thread( TEB **teb )
2340
{
2341 2342
    static size_t sigstack_zero_bits;
    struct ntdll_thread_data *thread_data;
2343
    struct ntdll_thread_data *parent_data = NULL;
2344 2345 2346 2347 2348
    SIZE_T size;
    void *addr = NULL;
    NTSTATUS status;

    if (!sigstack_zero_bits)
2349
    {
2350
        size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2351
        /* find the first power of two not smaller than min_size */
2352 2353 2354 2355
        sigstack_zero_bits = 12;
        while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
        signal_stack_mask = (1 << sigstack_zero_bits) - 1;
        signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
2356
    }
2357
    else parent_data = ntdll_get_thread_data();
2358 2359 2360 2361 2362 2363 2364 2365

    size = signal_stack_mask + 1;
    if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
                                            &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
    {
        *teb = addr;
        (*teb)->Tib.Self = &(*teb)->Tib;
        (*teb)->Tib.ExceptionList = (void *)~0UL;
2366
        thread_data = (struct ntdll_thread_data *)(*teb)->SpareBytes1;
2367 2368 2369 2370 2371 2372
        if (!(thread_data->fs = wine_ldt_alloc_fs()))
        {
            size = 0;
            NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
            status = STATUS_TOO_MANY_THREADS;
        }
2373
        if (parent_data)
2374 2375
        {
            /* inherit debug registers from parent thread */
2376 2377 2378 2379 2380 2381
            thread_data->dr0 = parent_data->dr0;
            thread_data->dr1 = parent_data->dr1;
            thread_data->dr2 = parent_data->dr2;
            thread_data->dr3 = parent_data->dr3;
            thread_data->dr6 = parent_data->dr6;
            thread_data->dr7 = parent_data->dr7;
2382 2383
        }

2384 2385
    }
    return status;
2386 2387 2388
}


2389 2390
/**********************************************************************
 *		signal_free_thread
2391
 */
2392
void signal_free_thread( TEB *teb )
2393
{
2394
    SIZE_T size;
2395
    struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
2396 2397 2398 2399 2400 2401 2402 2403 2404

    if (thread_data) wine_ldt_free_fs( thread_data->fs );
    if (teb->DeallocationStack)
    {
        size = 0;
        NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
    }
    size = 0;
    NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2405 2406 2407
}


2408
/**********************************************************************
2409
 *		signal_init_thread
2410
 */
2411
void signal_init_thread( TEB *teb )
2412
{
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;
2417 2418 2419 2420 2421 2422 2423 2424 2425

#ifdef __APPLE__
    int mib[2], val = 1;

    mib[0] = CTL_KERN;
    mib[1] = KERN_THALTSTACK;
    sysctl( mib, 2, NULL, NULL, &val, sizeof(val) );
#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" );
2430

2431 2432 2433 2434 2435
    wine_ldt_set_base( &fs_entry, teb );
    wine_ldt_set_limit( &fs_entry, teb_size - 1 );
    wine_ldt_set_flags( &fs_entry, WINE_LDT_FLAGS_DATA|WINE_LDT_FLAGS_32BIT );
    wine_ldt_init_fs( thread_data->fs, &fs_entry );
    thread_data->gs = wine_get_gs();
2436 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
2442 2443 2444 2445 2446 2447 2448 2449
}

/**********************************************************************
 *		signal_init_process
 */
void signal_init_process(void)
{
    struct sigaction sig_act;
2450

2451
    sig_act.sa_mask = server_block_set;
2452 2453 2454 2455
    sig_act.sa_flags = SA_SIGINFO | SA_RESTART;
#ifdef SA_ONSTACK
    sig_act.sa_flags |= SA_ONSTACK;
#endif
2456 2457 2458 2459
#ifdef __ANDROID__
    sig_act.sa_flags |= SA_RESTORER;
    sig_act.sa_restorer = rt_sigreturn;
#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 2467
    sig_act.sa_sigaction = quit_handler;
    if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
2468
    sig_act.sa_sigaction = usr1_handler;
2469 2470
    if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;

2471
    sig_act.sa_sigaction = segv_handler;
2472 2473
    if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
    if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2474
#ifdef SIGBUS
2475
    if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2476
#endif
2477

2478
#ifdef SIGTRAP
2479
    sig_act.sa_sigaction = trap_handler;
2480
    if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2481
#endif
2482

2483
#ifdef __HAVE_VM86
2484
    sig_act.sa_sigaction = usr2_handler;
2485
    if (sigaction( SIGUSR2, &sig_act, NULL ) == -1) goto error;
2486 2487
#endif

2488
    wine_ldt_init_locking( ldt_lock, ldt_unlock );
2489
    return;
2490 2491 2492

 error:
    perror("sigaction");
2493
    exit(1);
2494 2495
}

2496

2497
#ifdef __HAVE_VM86
2498
/**********************************************************************
2499
 *		__wine_enter_vm86   (NTDLL.@)
2500 2501 2502 2503 2504 2505 2506 2507 2508
 *
 * Enter vm86 mode with the specified register context.
 */
void __wine_enter_vm86( CONTEXT *context )
{
    EXCEPTION_RECORD rec;
    int res;
    struct vm86plus_struct vm86;

2509
    memset( &vm86, 0, sizeof(vm86) );
2510 2511
    for (;;)
    {
2512
        restore_vm86_context( context, &vm86 );
2513

2514
        ntdll_get_thread_data()->vm86_ptr = &vm86;
2515
        merge_vm86_pending_flags( &rec );
2516

2517
        res = vm86_enter( &ntdll_get_thread_data()->vm86_ptr ); /* uses and clears teb->vm86_ptr */
2518
        if (res < 0)
2519
        {
2520 2521 2522
            errno = -res;
            return;
        }
2523

2524
        save_vm86_context( context, &vm86 );
2525

2526 2527 2528 2529 2530
        rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
        rec.ExceptionRecord  = NULL;
        rec.ExceptionAddress = (LPVOID)context->Eip;
        rec.NumberParameters = 0;

2531 2532 2533
        switch(VM86_TYPE(res))
        {
        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 2538
            switch(VM86_ARG(res))
            {
2539
            case TRAP_x86_TRCTRAP:  /* Single-step exception */
2540 2541
                rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
                break;
2542
            case TRAP_x86_BPTFLT:   /* Breakpoint exception */
2543 2544 2545 2546 2547 2548
                rec.ExceptionAddress = (char *)rec.ExceptionAddress - 1;  /* back up over the int3 instruction */
                /* fall through */
            default:
                rec.ExceptionCode = EXCEPTION_BREAKPOINT;
                break;
            }
2549
            break;
2550 2551
        case VM86_INTx: /* int3/int x instruction (ARG = x) */
            rec.ExceptionCode = EXCEPTION_VM86_INTx;
2552 2553
            rec.NumberParameters = 1;
            rec.ExceptionInformation[0] = VM86_ARG(res);
2554 2555
            break;
        case VM86_STI: /* sti/popf/iret instruction enabled virtual interrupts */
2556 2557
            context->EFlags |= VIF_FLAG;
            context->EFlags &= ~VIP_FLAG;
2558
            get_vm86_teb_info()->vm86_pending = 0;
2559 2560 2561 2562 2563
            rec.ExceptionCode = EXCEPTION_VM86_STI;
            break;
        case VM86_PICRETURN: /* return due to pending PIC request */
            rec.ExceptionCode = EXCEPTION_VM86_PICRETURN;
            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 2568
            continue;
        }
2569
        raise_exception( &rec, context, TRUE );
2570 2571 2572
    }
}

2573
#else /* __HAVE_VM86 */
2574 2575 2576
/**********************************************************************
 *		__wine_enter_vm86   (NTDLL.@)
 */
2577 2578 2579 2580
void __wine_enter_vm86( CONTEXT *context )
{
    MESSAGE("vm86 mode not supported on this platform\n");
}
2581
#endif /* __HAVE_VM86 */
2582

2583

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
/*******************************************************************
 *		RtlUnwind (NTDLL.@)
 */
void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID targetIp,
                              PEXCEPTION_RECORD pRecord, PVOID retval, CONTEXT *context )
{
    EXCEPTION_RECORD record;
    EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
    DWORD res;

    context->Eax = (DWORD)retval;

    /* build an exception record, if we do not have one */
    if (!pRecord)
    {
        record.ExceptionCode    = STATUS_UNWIND;
        record.ExceptionFlags   = 0;
        record.ExceptionRecord  = NULL;
        record.ExceptionAddress = (void *)context->Eip;
        record.NumberParameters = 0;
        pRecord = &record;
    }

    pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);

    TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );

    /* get chain of exception frames */
    frame = NtCurrentTeb()->Tib.ExceptionList;
    while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
    {
        /* Check frame address */
        if (pEndFrame && (frame > pEndFrame))
            raise_status( STATUS_INVALID_UNWIND_TARGET, pRecord );

2619
        if (!is_valid_frame( frame )) raise_status( STATUS_BAD_STACK, pRecord );
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649

        /* Call handler */
        TRACE( "calling handler at %p code=%x flags=%x\n",
               frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
        res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, unwind_handler );
        TRACE( "handler at %p returned %x\n", frame->Handler, res );

        switch(res)
        {
        case ExceptionContinueSearch:
            break;
        case ExceptionCollidedUnwind:
            frame = dispatch;
            break;
        default:
            raise_status( STATUS_INVALID_DISPOSITION, pRecord );
            break;
        }
        frame = __wine_pop_frame( frame );
    }
}
DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )


/*******************************************************************
 *		NtRaiseException (NTDLL.@)
 */
NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
{
    NTSTATUS status = raise_exception( rec, context, first_chance );
2650 2651 2652 2653 2654
    if (status == STATUS_SUCCESS)
    {
        set_debug_registers( context );
        set_cpu_context( context );
    }
2655 2656 2657 2658
    return status;
}


2659 2660 2661 2662 2663
/***********************************************************************
 *		RtlRaiseException (NTDLL.@)
 */
void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
{
2664 2665 2666 2667
    NTSTATUS status;

    rec->ExceptionAddress = (void *)context->Eip;
    status = raise_exception( rec, context, TRUE );
2668 2669 2670 2671 2672
    if (status != STATUS_SUCCESS) raise_status( status, rec );
}
DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 1 )


2673 2674 2675 2676 2677
/*************************************************************************
 *		RtlCaptureStackBackTrace (NTDLL.@)
 */
USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
{
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    CONTEXT context;
    ULONG i;
    ULONG *frame;

    RtlCaptureContext( &context );
    if (hash) *hash = 0;
    frame = (ULONG *)context.Ebp;

    while (skip--)
    {
2688
        if (!is_valid_frame( frame )) return 0;
2689 2690 2691 2692 2693
        frame = (ULONG *)*frame;
    }

    for (i = 0; i < count; i++)
    {
2694
        if (!is_valid_frame( frame )) break;
2695 2696 2697 2698 2699
        buffer[i] = (void *)frame[1];
        if (hash) *hash += frame[1];
        frame = (ULONG *)*frame;
    }
    return i;
2700 2701 2702
}


2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
__ASM_GLOBAL_FUNC( call_thread_entry_point,
                   "pushl %ebp\n\t"
                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
                   "movl %esp,%ebp\n\t"
                   __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
                   "pushl %ebx\n\t"
                   __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
                   "pushl %esi\n\t"
                   __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
                   "pushl %edi\n\t"
                   __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
                   "pushl %ebp\n\t"
                   "pushl 12(%ebp)\n\t"
                   "pushl 8(%ebp)\n\t"
                   "call " __ASM_NAME("call_thread_func") );

extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
__ASM_GLOBAL_FUNC( call_thread_exit_func,
                   "movl 4(%esp),%eax\n\t"
                   "movl 8(%esp),%ecx\n\t"
                   "movl 12(%esp),%ebp\n\t"
                   __ASM_CFI(".cfi_def_cfa %ebp,4\n\t")
                   __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
                   __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
                   __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
                   __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
                   "leal -20(%ebp),%esp\n\t"
                   "pushl %eax\n\t"
                   "call *%ecx" );

2735
/* wrapper for apps that don't declare the thread function correctly */
2736 2737
extern void DECLSPEC_NORETURN call_thread_func_wrapper( LPTHREAD_START_ROUTINE entry, void *arg );
__ASM_GLOBAL_FUNC(call_thread_func_wrapper,
2738
                  "pushl %ebp\n\t"
2739 2740
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  __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 2744 2745 2746 2747
                  "subl $4,%esp\n\t"
                  "pushl 12(%ebp)\n\t"
                  "call *8(%ebp)\n\t"
                  "leal -4(%ebp),%esp\n\t"
                  "pushl %eax\n\t"
2748
                  "call " __ASM_NAME("exit_thread") "\n\t"
2749 2750 2751
                  "int $3" )

/***********************************************************************
2752
 *           call_thread_func
2753
 */
2754
void call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
2755
{
2756
    ntdll_get_thread_data()->exit_frame = frame;
2757 2758
    __TRY
    {
2759
        call_thread_func_wrapper( entry, arg );
2760 2761 2762 2763 2764 2765 2766 2767 2768
    }
    __EXCEPT(unhandled_exception_filter)
    {
        NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
    }
    __ENDTRY
    abort();  /* should not be reached */
}

2769 2770 2771 2772 2773
/***********************************************************************
 *           RtlExitUserThread  (NTDLL.@)
 */
void WINAPI RtlExitUserThread( ULONG status )
{
2774 2775
    if (!ntdll_get_thread_data()->exit_frame) exit_thread( status );
    call_thread_exit_func( status, exit_thread, ntdll_get_thread_data()->exit_frame );
2776
}
2777

2778 2779 2780 2781 2782
/***********************************************************************
 *           abort_thread
 */
void abort_thread( int status )
{
2783 2784
    if (!ntdll_get_thread_data()->exit_frame) terminate_thread( status );
    call_thread_exit_func( status, terminate_thread, ntdll_get_thread_data()->exit_frame );
2785 2786
}

2787
/**********************************************************************
2788
 *		DbgBreakPoint   (NTDLL.@)
2789
 */
2790
__ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
2791 2792

/**********************************************************************
2793
 *		DbgUserBreakPoint   (NTDLL.@)
2794
 */
2795
__ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
2796

2797 2798 2799
/**********************************************************************
 *           NtCurrentTeb   (NTDLL.@)
 */
2800
__ASM_STDCALL_FUNC( NtCurrentTeb, 0, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
2801

2802

2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
/**************************************************************************
 *           _chkstk   (NTDLL.@)
 */
__ASM_STDCALL_FUNC( _chkstk, 0,
                   "negl %eax\n\t"
                   "addl %esp,%eax\n\t"
                   "xchgl %esp,%eax\n\t"
                   "movl 0(%eax),%eax\n\t"  /* copy return address from old location */
                   "movl %eax,0(%esp)\n\t"
                   "ret" )

/**************************************************************************
 *           _alloca_probe   (NTDLL.@)
 */
__ASM_STDCALL_FUNC( _alloca_probe, 0,
                   "negl %eax\n\t"
                   "addl %esp,%eax\n\t"
                   "xchgl %esp,%eax\n\t"
                   "movl 0(%eax),%eax\n\t"  /* copy return address from old location */
                   "movl %eax,0(%esp)\n\t"
                   "ret" )


2826 2827
/**********************************************************************
 *		EXC_CallHandler   (internal)
2828 2829 2830 2831 2832 2833 2834
 *
 * Some exception handlers depend on EBP to have a fixed position relative to
 * the exception frame.
 * Shrinker depends on (*1) doing what it does,
 * (*2) being the exact instruction it is and (*3) beginning with 0x64
 * (i.e. the %fs prefix to the movl instruction). It also depends on the
 * function calling the handler having only 5 parameters (*4).
2835 2836
 */
__ASM_GLOBAL_FUNC( EXC_CallHandler,
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
                  "pushl %ebp\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
                  "movl %esp,%ebp\n\t"
                  __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
                   "pushl %ebx\n\t"
                   __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
                   "movl 28(%ebp), %edx\n\t" /* ugly hack to pass the 6th param needed because of Shrinker */
                   "pushl 24(%ebp)\n\t"
                   "pushl 20(%ebp)\n\t"
                   "pushl 16(%ebp)\n\t"
                   "pushl 12(%ebp)\n\t"
                   "pushl 8(%ebp)\n\t"
                   "call " __ASM_NAME("call_exception_handler") "\n\t"
                   "popl %ebx\n\t"
                   __ASM_CFI(".cfi_same_value %ebx\n\t")
                   "leave\n"
                   __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
                   __ASM_CFI(".cfi_same_value %ebp\n\t")
                   "ret" )
2857
__ASM_GLOBAL_FUNC(call_exception_handler,
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
                  "pushl %ebp\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
                  "movl %esp,%ebp\n\t"
                  __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
                  "subl $12,%esp\n\t"
                  "pushl 12(%ebp)\n\t"      /* make any exceptions in this... */
                  "pushl %edx\n\t"          /* handler be handled by... */
                  ".byte 0x64\n\t"
                  "pushl (0)\n\t"           /* nested_handler (passed in edx). */
                  ".byte 0x64\n\t"
                  "movl %esp,(0)\n\t"       /* push the new exception frame onto the exception stack. */
                  "pushl 20(%ebp)\n\t"
                  "pushl 16(%ebp)\n\t"
                  "pushl 12(%ebp)\n\t"
                  "pushl 8(%ebp)\n\t"
                  "movl 24(%ebp), %ecx\n\t" /* (*1) */
                  "call *%ecx\n\t"          /* call handler. (*2) */
                  ".byte 0x64\n\t"
                  "movl (0), %esp\n\t"      /* restore previous... (*3) */
                  ".byte 0x64\n\t"
                  "popl (0)\n\t"            /* exception frame. */
                  "movl %ebp, %esp\n\t"     /* restore saved stack, in case it was corrupted */
                  "popl %ebp\n\t"
                   __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
                   __ASM_CFI(".cfi_same_value %ebp\n\t")
                  "ret $20" )            /* (*4) */

2886
#endif  /* __i386__ */