signal_x86_64.c 106 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * x86-64 signal handling routines
 *
 * Copyright 1999, 2005 Alexandre Julliard
 *
 * 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 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 */

#ifdef __x86_64__

#include "config.h"
#include "wine/port.h"

#include <assert.h>
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif

#define NONAMELESSUNION
43
#define NONAMELESSSTRUCT
44 45
#include "ntstatus.h"
#define WIN32_NO_STATUS
46 47 48 49 50 51 52 53 54
#include "windef.h"
#include "winternl.h"
#include "wine/library.h"
#include "wine/exception.h"
#include "ntdll_misc.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(seh);

55 56
struct _DISPATCHER_CONTEXT;

57
typedef LONG (WINAPI *PC_LANGUAGE_EXCEPTION_HANDLER)( EXCEPTION_POINTERS *ptrs, ULONG64 frame );
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
typedef EXCEPTION_DISPOSITION (WINAPI *PEXCEPTION_ROUTINE)( EXCEPTION_RECORD *rec,
                                                            ULONG64 frame,
                                                            CONTEXT *context,
                                                            struct _DISPATCHER_CONTEXT *dispatch );

typedef struct _DISPATCHER_CONTEXT
{
    ULONG64               ControlPc;
    ULONG64               ImageBase;
    PRUNTIME_FUNCTION     FunctionEntry;
    ULONG64               EstablisherFrame;
    ULONG64               TargetIp;
    PCONTEXT              ContextRecord;
    PEXCEPTION_ROUTINE    LanguageHandler;
    PVOID                 HandlerData;
    PUNWIND_HISTORY_TABLE HistoryTable;
    ULONG                 ScopeIndex;
} DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;

77 78 79 80 81 82 83 84 85 86 87 88
typedef struct _SCOPE_TABLE
{
    ULONG Count;
    struct
    {
        ULONG BeginAddress;
        ULONG EndAddress;
        ULONG HandlerAddress;
        ULONG JumpTarget;
    } ScopeRecord[1];
} SCOPE_TABLE, *PSCOPE_TABLE;

89 90 91 92 93 94

/***********************************************************************
 * signal context platform-specific definitions
 */
#ifdef linux

95 96 97
#include <asm/prctl.h>
extern int arch_prctl(int func, void *ptr);

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
#define RAX_sig(context)     ((context)->uc_mcontext.gregs[REG_RAX])
#define RBX_sig(context)     ((context)->uc_mcontext.gregs[REG_RBX])
#define RCX_sig(context)     ((context)->uc_mcontext.gregs[REG_RCX])
#define RDX_sig(context)     ((context)->uc_mcontext.gregs[REG_RDX])
#define RSI_sig(context)     ((context)->uc_mcontext.gregs[REG_RSI])
#define RDI_sig(context)     ((context)->uc_mcontext.gregs[REG_RDI])
#define RBP_sig(context)     ((context)->uc_mcontext.gregs[REG_RBP])
#define R8_sig(context)      ((context)->uc_mcontext.gregs[REG_R8])
#define R9_sig(context)      ((context)->uc_mcontext.gregs[REG_R9])
#define R10_sig(context)     ((context)->uc_mcontext.gregs[REG_R10])
#define R11_sig(context)     ((context)->uc_mcontext.gregs[REG_R11])
#define R12_sig(context)     ((context)->uc_mcontext.gregs[REG_R12])
#define R13_sig(context)     ((context)->uc_mcontext.gregs[REG_R13])
#define R14_sig(context)     ((context)->uc_mcontext.gregs[REG_R14])
#define R15_sig(context)     ((context)->uc_mcontext.gregs[REG_R15])

#define CS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 0))
#define GS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 1))
#define FS_sig(context)      (*((WORD *)&(context)->uc_mcontext.gregs[REG_CSGSFS] + 2))

#define RSP_sig(context)     ((context)->uc_mcontext.gregs[REG_RSP])
#define RIP_sig(context)     ((context)->uc_mcontext.gregs[REG_RIP])
#define EFL_sig(context)     ((context)->uc_mcontext.gregs[REG_EFL])
#define TRAP_sig(context)    ((context)->uc_mcontext.gregs[REG_TRAPNO])
#define ERROR_sig(context)   ((context)->uc_mcontext.gregs[REG_ERR])

#define FPU_sig(context)     ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.fpregs))

#endif /* linux */

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
#if defined(__NetBSD__)
# include <sys/ucontext.h>
# include <sys/types.h>
# include <signal.h>

#define RAX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RAX])
#define RBX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RBX])
#define RCX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RCX])
#define RDX_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RDX])
#define RSI_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RSI])
#define RDI_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RDI])
#define RBP_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RBP])
#define R8_sig(context)     ((context)->uc_mcontext.__gregs[_REG_R8])
#define R9_sig(context)     ((context)->uc_mcontext.__gregs[_REG_R9])
#define R10_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R10])
#define R11_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R11])
#define R12_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R12])
#define R13_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R13])
#define R14_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R14])
#define R15_sig(context)    ((context)->uc_mcontext.__gregs[_REG_R15])

#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 FS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_FS])
#define GS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_GS])
#define SS_sig(context)     ((context)->uc_mcontext.__gregs[_REG_SS])

#define EFL_sig(context)    ((context)->uc_mcontext.__gregs[_REG_RFL])

#define RIP_sig(context)    (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_RIP]))
#define RSP_sig(context)    (*((unsigned long*)&(context)->uc_mcontext.__gregs[_REG_URSP]))

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

#define FPU_sig(context)   ((XMM_SAVE_AREA32 *)((context)->uc_mcontext.__fpregs))
#endif /* __NetBSD__ */

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
enum i386_trap_code
{
    TRAP_x86_UNKNOWN    = -1,  /* Unknown fault (TRAP_sig not defined) */
    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 */
    TRAP_x86_CACHEFLT   = 19   /* Cache flush exception */
};
190

191 192 193 194
static const size_t teb_size = 0x2000;  /* we reserve two pages for the TEB */
static size_t signal_stack_size;

typedef void (*raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
195 196 197 198
typedef int (*wine_signal_handler)(unsigned int sig);

static wine_signal_handler handlers[256];

199 200 201 202

/***********************************************************************
 * Definitions for Win32 unwind tables
 */
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 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 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

union handler_data
{
    RUNTIME_FUNCTION chain;
    ULONG handler;
};

struct opcode
{
    BYTE offset;
    BYTE code : 4;
    BYTE info : 4;
};

struct UNWIND_INFO
{
    BYTE version : 3;
    BYTE flags : 5;
    BYTE prolog;
    BYTE count;
    BYTE frame_reg : 4;
    BYTE frame_offset : 4;
    struct opcode opcodes[1];  /* info->count entries */
    /* followed by handler_data */
};

#define UWOP_PUSH_NONVOL     0
#define UWOP_ALLOC_LARGE     1
#define UWOP_ALLOC_SMALL     2
#define UWOP_SET_FPREG       3
#define UWOP_SAVE_NONVOL     4
#define UWOP_SAVE_NONVOL_FAR 5
#define UWOP_SAVE_XMM128     8
#define UWOP_SAVE_XMM128_FAR 9
#define UWOP_PUSH_MACHFRAME  10

static void dump_unwind_info( ULONG64 base, RUNTIME_FUNCTION *function )
{
    static const char * const reg_names[16] =
        { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
          "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15" };

    union handler_data *handler_data;
    struct UNWIND_INFO *info;
    unsigned int i, count;

    TRACE( "**** func %x-%x\n", function->BeginAddress, function->EndAddress );
    for (;;)
    {
        if (function->UnwindData & 1)
        {
            RUNTIME_FUNCTION *next = (RUNTIME_FUNCTION *)((char *)base + (function->UnwindData & ~1));
            TRACE( "unwind info for function %p-%p chained to function %p-%p\n",
                   (char *)base + function->BeginAddress, (char *)base + function->EndAddress,
                   (char *)base + next->BeginAddress, (char *)base + next->EndAddress );
            function = next;
            continue;
        }
        info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);

        TRACE( "unwind info at %p flags %x prolog 0x%x bytes function %p-%p\n",
               info, info->flags, info->prolog,
               (char *)base + function->BeginAddress, (char *)base + function->EndAddress );

        if (info->frame_reg)
            TRACE( "    frame register %s offset 0x%x(%%rsp)\n",
                   reg_names[info->frame_reg], info->frame_offset * 16 );

        for (i = 0; i < info->count; i++)
        {
            TRACE( "    0x%x: ", info->opcodes[i].offset );
            switch (info->opcodes[i].code)
            {
            case UWOP_PUSH_NONVOL:
                TRACE( "pushq %%%s\n", reg_names[info->opcodes[i].info] );
                break;
            case UWOP_ALLOC_LARGE:
                if (info->opcodes[i].info)
                {
                    count = *(DWORD *)&info->opcodes[i+1];
                    i += 2;
                }
                else
                {
                    count = *(USHORT *)&info->opcodes[i+1] * 8;
                    i++;
                }
                TRACE( "subq $0x%x,%%rsp\n", count );
                break;
            case UWOP_ALLOC_SMALL:
                count = (info->opcodes[i].info + 1) * 8;
                TRACE( "subq $0x%x,%%rsp\n", count );
                break;
            case UWOP_SET_FPREG:
                TRACE( "leaq 0x%x(%%rsp),%s\n",
                     info->frame_offset * 16, reg_names[info->frame_reg] );
                break;
            case UWOP_SAVE_NONVOL:
                count = *(USHORT *)&info->opcodes[i+1] * 8;
                TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
                i++;
                break;
            case UWOP_SAVE_NONVOL_FAR:
                count = *(DWORD *)&info->opcodes[i+1];
                TRACE( "movq %%%s,0x%x(%%rsp)\n", reg_names[info->opcodes[i].info], count );
                i += 2;
                break;
            case UWOP_SAVE_XMM128:
                count = *(USHORT *)&info->opcodes[i+1] * 16;
                TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
                i++;
                break;
            case UWOP_SAVE_XMM128_FAR:
                count = *(DWORD *)&info->opcodes[i+1];
                TRACE( "movaps %%xmm%u,0x%x(%%rsp)\n", info->opcodes[i].info, count );
                i += 2;
                break;
            case UWOP_PUSH_MACHFRAME:
                TRACE( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
                break;
            default:
                FIXME( "unknown code %u\n", info->opcodes[i].code );
                break;
            }
        }

        handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];
        if (info->flags & UNW_FLAG_CHAININFO)
        {
            TRACE( "    chained to function %p-%p\n",
                   (char *)base + handler_data->chain.BeginAddress,
                   (char *)base + handler_data->chain.EndAddress );
            function = &handler_data->chain;
            continue;
        }
        if (info->flags & (UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER))
            TRACE( "    handler %p data at %p\n",
                   (char *)base + handler_data->handler, &handler_data->handler + 1 );
        break;
    }
}

345 346 347 348 349 350 351 352 353 354 355 356 357
static void dump_scope_table( ULONG64 base, const SCOPE_TABLE *table )
{
    unsigned int i;

    TRACE( "scope table at %p\n", table );
    for (i = 0; i < table->Count; i++)
        TRACE( "  %u: %lx-%lx handler %lx target %lx\n", i,
               base + table->ScopeRecord[i].BeginAddress,
               base + table->ScopeRecord[i].EndAddress,
               base + table->ScopeRecord[i].HandlerAddress,
               base + table->ScopeRecord[i].JumpTarget );
}

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

/***********************************************************************
 * Definitions for Dwarf unwind tables
 */

enum dwarf_call_frame_info
{
    DW_CFA_advance_loc = 0x40,
    DW_CFA_offset = 0x80,
    DW_CFA_restore = 0xc0,
    DW_CFA_nop = 0x00,
    DW_CFA_set_loc = 0x01,
    DW_CFA_advance_loc1 = 0x02,
    DW_CFA_advance_loc2 = 0x03,
    DW_CFA_advance_loc4 = 0x04,
    DW_CFA_offset_extended = 0x05,
    DW_CFA_restore_extended = 0x06,
    DW_CFA_undefined = 0x07,
    DW_CFA_same_value = 0x08,
    DW_CFA_register = 0x09,
    DW_CFA_remember_state = 0x0a,
    DW_CFA_restore_state = 0x0b,
    DW_CFA_def_cfa = 0x0c,
    DW_CFA_def_cfa_register = 0x0d,
    DW_CFA_def_cfa_offset = 0x0e,
    DW_CFA_def_cfa_expression = 0x0f,
    DW_CFA_expression = 0x10,
    DW_CFA_offset_extended_sf = 0x11,
    DW_CFA_def_cfa_sf = 0x12,
    DW_CFA_def_cfa_offset_sf = 0x13,
    DW_CFA_val_offset = 0x14,
    DW_CFA_val_offset_sf = 0x15,
    DW_CFA_val_expression = 0x16,
};

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 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 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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
enum dwarf_operation
{
    DW_OP_addr                 = 0x03,
    DW_OP_deref                = 0x06,
    DW_OP_const1u              = 0x08,
    DW_OP_const1s              = 0x09,
    DW_OP_const2u              = 0x0a,
    DW_OP_const2s              = 0x0b,
    DW_OP_const4u              = 0x0c,
    DW_OP_const4s              = 0x0d,
    DW_OP_const8u              = 0x0e,
    DW_OP_const8s              = 0x0f,
    DW_OP_constu               = 0x10,
    DW_OP_consts               = 0x11,
    DW_OP_dup                  = 0x12,
    DW_OP_drop                 = 0x13,
    DW_OP_over                 = 0x14,
    DW_OP_pick                 = 0x15,
    DW_OP_swap                 = 0x16,
    DW_OP_rot                  = 0x17,
    DW_OP_xderef               = 0x18,
    DW_OP_abs                  = 0x19,
    DW_OP_and                  = 0x1a,
    DW_OP_div                  = 0x1b,
    DW_OP_minus                = 0x1c,
    DW_OP_mod                  = 0x1d,
    DW_OP_mul                  = 0x1e,
    DW_OP_neg                  = 0x1f,
    DW_OP_not                  = 0x20,
    DW_OP_or                   = 0x21,
    DW_OP_plus                 = 0x22,
    DW_OP_plus_uconst          = 0x23,
    DW_OP_shl                  = 0x24,
    DW_OP_shr                  = 0x25,
    DW_OP_shra                 = 0x26,
    DW_OP_xor                  = 0x27,
    DW_OP_bra                  = 0x28,
    DW_OP_eq                   = 0x29,
    DW_OP_ge                   = 0x2a,
    DW_OP_gt                   = 0x2b,
    DW_OP_le                   = 0x2c,
    DW_OP_lt                   = 0x2d,
    DW_OP_ne                   = 0x2e,
    DW_OP_skip                 = 0x2f,
    DW_OP_lit0                 = 0x30,
    DW_OP_lit1                 = 0x31,
    DW_OP_lit2                 = 0x32,
    DW_OP_lit3                 = 0x33,
    DW_OP_lit4                 = 0x34,
    DW_OP_lit5                 = 0x35,
    DW_OP_lit6                 = 0x36,
    DW_OP_lit7                 = 0x37,
    DW_OP_lit8                 = 0x38,
    DW_OP_lit9                 = 0x39,
    DW_OP_lit10                = 0x3a,
    DW_OP_lit11                = 0x3b,
    DW_OP_lit12                = 0x3c,
    DW_OP_lit13                = 0x3d,
    DW_OP_lit14                = 0x3e,
    DW_OP_lit15                = 0x3f,
    DW_OP_lit16                = 0x40,
    DW_OP_lit17                = 0x41,
    DW_OP_lit18                = 0x42,
    DW_OP_lit19                = 0x43,
    DW_OP_lit20                = 0x44,
    DW_OP_lit21                = 0x45,
    DW_OP_lit22                = 0x46,
    DW_OP_lit23                = 0x47,
    DW_OP_lit24                = 0x48,
    DW_OP_lit25                = 0x49,
    DW_OP_lit26                = 0x4a,
    DW_OP_lit27                = 0x4b,
    DW_OP_lit28                = 0x4c,
    DW_OP_lit29                = 0x4d,
    DW_OP_lit30                = 0x4e,
    DW_OP_lit31                = 0x4f,
    DW_OP_reg0                 = 0x50,
    DW_OP_reg1                 = 0x51,
    DW_OP_reg2                 = 0x52,
    DW_OP_reg3                 = 0x53,
    DW_OP_reg4                 = 0x54,
    DW_OP_reg5                 = 0x55,
    DW_OP_reg6                 = 0x56,
    DW_OP_reg7                 = 0x57,
    DW_OP_reg8                 = 0x58,
    DW_OP_reg9                 = 0x59,
    DW_OP_reg10                = 0x5a,
    DW_OP_reg11                = 0x5b,
    DW_OP_reg12                = 0x5c,
    DW_OP_reg13                = 0x5d,
    DW_OP_reg14                = 0x5e,
    DW_OP_reg15                = 0x5f,
    DW_OP_reg16                = 0x60,
    DW_OP_reg17                = 0x61,
    DW_OP_reg18                = 0x62,
    DW_OP_reg19                = 0x63,
    DW_OP_reg20                = 0x64,
    DW_OP_reg21                = 0x65,
    DW_OP_reg22                = 0x66,
    DW_OP_reg23                = 0x67,
    DW_OP_reg24                = 0x68,
    DW_OP_reg25                = 0x69,
    DW_OP_reg26                = 0x6a,
    DW_OP_reg27                = 0x6b,
    DW_OP_reg28                = 0x6c,
    DW_OP_reg29                = 0x6d,
    DW_OP_reg30                = 0x6e,
    DW_OP_reg31                = 0x6f,
    DW_OP_breg0                = 0x70,
    DW_OP_breg1                = 0x71,
    DW_OP_breg2                = 0x72,
    DW_OP_breg3                = 0x73,
    DW_OP_breg4                = 0x74,
    DW_OP_breg5                = 0x75,
    DW_OP_breg6                = 0x76,
    DW_OP_breg7                = 0x77,
    DW_OP_breg8                = 0x78,
    DW_OP_breg9                = 0x79,
    DW_OP_breg10               = 0x7a,
    DW_OP_breg11               = 0x7b,
    DW_OP_breg12               = 0x7c,
    DW_OP_breg13               = 0x7d,
    DW_OP_breg14               = 0x7e,
    DW_OP_breg15               = 0x7f,
    DW_OP_breg16               = 0x80,
    DW_OP_breg17               = 0x81,
    DW_OP_breg18               = 0x82,
    DW_OP_breg19               = 0x83,
    DW_OP_breg20               = 0x84,
    DW_OP_breg21               = 0x85,
    DW_OP_breg22               = 0x86,
    DW_OP_breg23               = 0x87,
    DW_OP_breg24               = 0x88,
    DW_OP_breg25               = 0x89,
    DW_OP_breg26               = 0x8a,
    DW_OP_breg27               = 0x8b,
    DW_OP_breg28               = 0x8c,
    DW_OP_breg29               = 0x8d,
    DW_OP_breg30               = 0x8e,
    DW_OP_breg31               = 0x8f,
    DW_OP_regx                 = 0x90,
    DW_OP_fbreg                = 0x91,
    DW_OP_bregx                = 0x92,
    DW_OP_piece                = 0x93,
    DW_OP_deref_size           = 0x94,
    DW_OP_xderef_size          = 0x95,
    DW_OP_nop                  = 0x96,
    DW_OP_push_object_address  = 0x97,
    DW_OP_call2                = 0x98,
    DW_OP_call4                = 0x99,
    DW_OP_call_ref             = 0x9a,
    DW_OP_form_tls_address     = 0x9b,
    DW_OP_call_frame_cfa       = 0x9c,
    DW_OP_bit_piece            = 0x9d,
    DW_OP_lo_user              = 0xe0,
    DW_OP_hi_user              = 0xff,
    DW_OP_GNU_push_tls_address = 0xe0,
    DW_OP_GNU_uninit           = 0xf0,
    DW_OP_GNU_encoded_addr     = 0xf1,
};

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
#define DW_EH_PE_native   0x00
#define DW_EH_PE_leb128   0x01
#define DW_EH_PE_data2    0x02
#define DW_EH_PE_data4    0x03
#define DW_EH_PE_data8    0x04
#define DW_EH_PE_signed   0x08
#define DW_EH_PE_abs      0x00
#define DW_EH_PE_pcrel    0x10
#define DW_EH_PE_textrel  0x20
#define DW_EH_PE_datarel  0x30
#define DW_EH_PE_funcrel  0x40
#define DW_EH_PE_aligned  0x50
#define DW_EH_PE_indirect 0x80
#define DW_EH_PE_omit     0xff

struct dwarf_eh_bases
{
    void *tbase;
    void *dbase;
    void *func;
};

struct dwarf_cie
{
    unsigned int  length;
    int           id;
    unsigned char version;
    unsigned char augmentation[1];
};

struct dwarf_fde
{
    unsigned int length;
    unsigned int cie_offset;
};

extern const struct dwarf_fde *_Unwind_Find_FDE (void *, struct dwarf_eh_bases *);

592 593 594 595 596
static unsigned char dwarf_get_u1( const unsigned char **p )
{
    return *(*p)++;
}

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 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 662 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
static unsigned short dwarf_get_u2( const unsigned char **p )
{
    unsigned int ret = (*p)[0] | ((*p)[1] << 8);
    (*p) += 2;
    return ret;
}

static unsigned int dwarf_get_u4( const unsigned char **p )
{
    unsigned int ret = (*p)[0] | ((*p)[1] << 8) | ((*p)[2] << 16) | ((*p)[3] << 24);
    (*p) += 4;
    return ret;
}

static ULONG64 dwarf_get_u8( const unsigned char **p )
{
    ULONG64 low  = dwarf_get_u4( p );
    ULONG64 high = dwarf_get_u4( p );
    return low | (high << 32);
}

static ULONG_PTR dwarf_get_uleb128( const unsigned char **p )
{
    ULONG_PTR ret = 0;
    unsigned int shift = 0;
    unsigned char byte;

    do
    {
        byte = **p;
        ret |= (ULONG_PTR)(byte & 0x7f) << shift;
        shift += 7;
        (*p)++;
    } while (byte & 0x80);
    return ret;
}

static LONG_PTR dwarf_get_sleb128( const unsigned char **p )
{
    ULONG_PTR ret = 0;
    unsigned int shift = 0;
    unsigned char byte;

    do
    {
        byte = **p;
        ret |= (ULONG_PTR)(byte & 0x7f) << shift;
        shift += 7;
        (*p)++;
    } while (byte & 0x80);

    if ((shift < 8 * sizeof(ret)) && (byte & 0x40)) ret |= -((ULONG_PTR)1 << shift);
    return ret;
}

static ULONG_PTR dwarf_get_ptr( const unsigned char **p, unsigned char encoding )
{
    ULONG_PTR base;

    if (encoding == DW_EH_PE_omit) return 0;

    switch (encoding & 0xf0)
    {
    case DW_EH_PE_abs:
        base = 0;
        break;
    case DW_EH_PE_pcrel:
        base = (ULONG_PTR)*p;
        break;
    default:
        FIXME( "unsupported encoding %02x\n", encoding );
        return 0;
    }

    switch (encoding & 0x0f)
    {
    case DW_EH_PE_native:
        return base + dwarf_get_u8( p );
    case DW_EH_PE_leb128:
        return base + dwarf_get_uleb128( p );
    case DW_EH_PE_data2:
        return base + dwarf_get_u2( p );
    case DW_EH_PE_data4:
        return base + dwarf_get_u4( p );
    case DW_EH_PE_data8:
        return base + dwarf_get_u8( p );
    case DW_EH_PE_signed|DW_EH_PE_leb128:
        return base + dwarf_get_sleb128( p );
    case DW_EH_PE_signed|DW_EH_PE_data2:
        return base + (signed short)dwarf_get_u2( p );
    case DW_EH_PE_signed|DW_EH_PE_data4:
        return base + (signed int)dwarf_get_u4( p );
    case DW_EH_PE_signed|DW_EH_PE_data8:
        return base + (LONG64)dwarf_get_u8( p );
    default:
        FIXME( "unsupported encoding %02x\n", encoding );
        return 0;
    }
}

enum reg_rule
{
699 700 701 702 703 704 705
    RULE_UNSET,          /* not set at all */
    RULE_UNDEFINED,      /* undefined value */
    RULE_SAME,           /* same value as previous frame */
    RULE_CFA_OFFSET,     /* stored at cfa offset */
    RULE_OTHER_REG,      /* stored in other register */
    RULE_EXPRESSION,     /* address specified by expression */
    RULE_VAL_EXPRESSION  /* value specified by expression */
706 707 708 709 710 711 712 713 714 715
};

#define NB_FRAME_REGS 41

struct frame_info
{
    ULONG_PTR     ip;
    ULONG_PTR     code_align;
    LONG_PTR      data_align;
    ULONG_PTR     cfa_offset;
716
    enum reg_rule cfa_rule;
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 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 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
    unsigned char cfa_reg;
    unsigned char retaddr_reg;
    unsigned char fde_encoding;
    unsigned char signal_frame;
    enum reg_rule rules[NB_FRAME_REGS];
    ULONG64       regs[NB_FRAME_REGS];
};

static const char *dwarf_reg_names[NB_FRAME_REGS] =
{
/*  0-7  */ "%rax", "%rdx", "%rcx", "%rbx", "%rsi", "%rdi", "%rbp", "%rsp",
/*  8-16 */ "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "%rip",
/* 17-24 */ "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
/* 25-32 */ "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15",
/* 33-40 */ "%st0", "%st1", "%st2", "%st3", "%st4", "%st5", "%st6", "%st7"
};

static int valid_reg( ULONG_PTR reg )
{
    if (reg >= NB_FRAME_REGS) FIXME( "unsupported reg %lx\n", reg );
    return (reg < NB_FRAME_REGS);
}

static void execute_cfa_instructions( const unsigned char *ptr, const unsigned char *end,
                                      ULONG_PTR last_ip, struct frame_info *info )
{
    while (ptr < end && info->ip < last_ip + info->signal_frame)
    {
        enum dwarf_call_frame_info op = *ptr++;

        if (op & 0xc0)
        {
            switch (op & 0xc0)
            {
            case DW_CFA_advance_loc:
            {
                ULONG_PTR offset = (op & 0x3f) * info->code_align;
                TRACE( "%lx: DW_CFA_advance_loc %lu\n", info->ip, offset );
                info->ip += offset;
                break;
            }
            case DW_CFA_offset:
            {
                ULONG_PTR reg = op & 0x3f;
                LONG_PTR offset = dwarf_get_uleb128( &ptr ) * info->data_align;
                if (!valid_reg( reg )) break;
                TRACE( "%lx: DW_CFA_offset %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
                info->regs[reg]  = offset;
                info->rules[reg] = RULE_CFA_OFFSET;
                break;
            }
            case DW_CFA_restore:
            {
                ULONG_PTR reg = op & 0x3f;
                if (!valid_reg( reg )) break;
                TRACE( "%lx: DW_CFA_restore %s\n", info->ip, dwarf_reg_names[reg] );
                info->rules[reg] = RULE_UNSET;
                break;
            }
            }
        }
        else switch (op)
        {
        case DW_CFA_nop:
            break;
        case DW_CFA_set_loc:
        {
            ULONG_PTR loc = dwarf_get_ptr( &ptr, info->fde_encoding );
            TRACE( "%lx: DW_CFA_set_loc %lx\n", info->ip, loc );
            info->ip = loc;
            break;
        }
        case DW_CFA_advance_loc1:
        {
            ULONG_PTR offset = *ptr++ * info->code_align;
            TRACE( "%lx: DW_CFA_advance_loc1 %lu\n", info->ip, offset );
            info->ip += offset;
            break;
        }
        case DW_CFA_advance_loc2:
        {
            ULONG_PTR offset = dwarf_get_u2( &ptr ) * info->code_align;
            TRACE( "%lx: DW_CFA_advance_loc2 %lu\n", info->ip, offset );
            info->ip += offset;
            break;
        }
        case DW_CFA_advance_loc4:
        {
            ULONG_PTR offset = dwarf_get_u4( &ptr ) * info->code_align;
            TRACE( "%lx: DW_CFA_advance_loc4 %lu\n", info->ip, offset );
            info->ip += offset;
            break;
        }
        case DW_CFA_offset_extended:
811
        case DW_CFA_offset_extended_sf:
812 813
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
814 815
            LONG_PTR offset = (op == DW_CFA_offset_extended) ? dwarf_get_uleb128( &ptr ) * info->data_align
                                                             : dwarf_get_sleb128( &ptr ) * info->data_align;
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_offset_extended %s, %ld\n", info->ip, dwarf_reg_names[reg], offset );
            info->regs[reg]  = offset;
            info->rules[reg] = RULE_CFA_OFFSET;
            break;
        }
        case DW_CFA_restore_extended:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_restore_extended %s\n", info->ip, dwarf_reg_names[reg] );
            info->rules[reg] = RULE_UNSET;
            break;
        }
        case DW_CFA_undefined:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_undefined %s\n", info->ip, dwarf_reg_names[reg] );
            info->rules[reg] = RULE_UNDEFINED;
            break;
        }
        case DW_CFA_same_value:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_same_value %s\n", info->ip, dwarf_reg_names[reg] );
            info->regs[reg]  = reg;
            info->rules[reg] = RULE_SAME;
            break;
        }
        case DW_CFA_register:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            ULONG_PTR reg2 = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg ) || !valid_reg( reg2 )) break;
            TRACE( "%lx: DW_CFA_register %s == %s\n", info->ip, dwarf_reg_names[reg], dwarf_reg_names[reg2] );
            info->regs[reg]  = reg2;
            info->rules[reg] = RULE_OTHER_REG;
            break;
        }
        case DW_CFA_remember_state:
            FIXME( "%lx: DW_CFA_remember_state not implemented\n", info->ip );
            break;
        case DW_CFA_restore_state:
            FIXME( "%lx: DW_CFA_restore_state not implemented\n", info->ip );
            break;
        case DW_CFA_def_cfa:
864
        case DW_CFA_def_cfa_sf:
865 866
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
867 868
            ULONG_PTR offset = (op == DW_CFA_def_cfa) ? dwarf_get_uleb128( &ptr )
                                                      : dwarf_get_sleb128( &ptr ) * info->data_align;
869 870 871 872
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_def_cfa %s, %lu\n", info->ip, dwarf_reg_names[reg], offset );
            info->cfa_reg    = reg;
            info->cfa_offset = offset;
873
            info->cfa_rule   = RULE_CFA_OFFSET;
874 875 876 877 878 879 880 881
            break;
        }
        case DW_CFA_def_cfa_register:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_def_cfa_register %s\n", info->ip, dwarf_reg_names[reg] );
            info->cfa_reg = reg;
882
            info->cfa_rule = RULE_CFA_OFFSET;
883 884 885
            break;
        }
        case DW_CFA_def_cfa_offset:
886
        case DW_CFA_def_cfa_offset_sf:
887
        {
888 889
            ULONG_PTR offset = (op == DW_CFA_def_cfa_offset) ? dwarf_get_uleb128( &ptr )
                                                             : dwarf_get_sleb128( &ptr ) * info->data_align;
890 891
            TRACE( "%lx: DW_CFA_def_cfa_offset %lu\n", info->ip, offset );
            info->cfa_offset = offset;
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
            info->cfa_rule = RULE_CFA_OFFSET;
            break;
        }
        case DW_CFA_def_cfa_expression:
        {
            ULONG_PTR expr = (ULONG_PTR)ptr;
            ULONG_PTR len = dwarf_get_uleb128( &ptr );
            TRACE( "%lx: DW_CFA_def_cfa_expression %lx-%lx\n", info->ip, expr, expr+len );
            info->cfa_offset = expr;
            info->cfa_rule = RULE_VAL_EXPRESSION;
            ptr += len;
            break;
        }
        case DW_CFA_expression:
        case DW_CFA_val_expression:
        {
            ULONG_PTR reg = dwarf_get_uleb128( &ptr );
            ULONG_PTR expr = (ULONG_PTR)ptr;
            ULONG_PTR len = dwarf_get_uleb128( &ptr );
            if (!valid_reg( reg )) break;
            TRACE( "%lx: DW_CFA_%sexpression %s %lx-%lx\n",
                   info->ip, (op == DW_CFA_expression) ? "" : "val_", dwarf_reg_names[reg], expr, expr+len );
            info->regs[reg]  = expr;
            info->rules[reg] = (op == DW_CFA_expression) ? RULE_EXPRESSION : RULE_VAL_EXPRESSION;
            ptr += len;
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
            break;
        }
        default:
            FIXME( "%lx: unknown CFA opcode %02x\n", info->ip, op );
            break;
        }
    }
}

/* retrieve a context register from its dwarf number */
static void *get_context_reg( CONTEXT *context, ULONG_PTR dw_reg )
{
    switch (dw_reg)
    {
    case 0:  return &context->Rax;
    case 1:  return &context->Rdx;
    case 2:  return &context->Rcx;
    case 3:  return &context->Rbx;
    case 4:  return &context->Rsi;
    case 5:  return &context->Rdi;
    case 6:  return &context->Rbp;
    case 7:  return &context->Rsp;
    case 8:  return &context->R8;
    case 9:  return &context->R9;
    case 10: return &context->R10;
    case 11: return &context->R11;
    case 12: return &context->R12;
    case 13: return &context->R13;
    case 14: return &context->R14;
    case 15: return &context->R15;
    case 16: return &context->Rip;
    case 17: return &context->u.s.Xmm0;
    case 18: return &context->u.s.Xmm1;
    case 19: return &context->u.s.Xmm2;
    case 20: return &context->u.s.Xmm3;
    case 21: return &context->u.s.Xmm4;
    case 22: return &context->u.s.Xmm5;
    case 23: return &context->u.s.Xmm6;
    case 24: return &context->u.s.Xmm7;
    case 25: return &context->u.s.Xmm8;
    case 26: return &context->u.s.Xmm9;
    case 27: return &context->u.s.Xmm10;
    case 28: return &context->u.s.Xmm11;
    case 29: return &context->u.s.Xmm12;
    case 30: return &context->u.s.Xmm13;
    case 31: return &context->u.s.Xmm14;
    case 32: return &context->u.s.Xmm15;
    case 33: return &context->u.s.Legacy[0];
    case 34: return &context->u.s.Legacy[1];
    case 35: return &context->u.s.Legacy[2];
    case 36: return &context->u.s.Legacy[3];
    case 37: return &context->u.s.Legacy[4];
    case 38: return &context->u.s.Legacy[5];
    case 39: return &context->u.s.Legacy[6];
    case 40: return &context->u.s.Legacy[7];
    default: return NULL;
    }
}

/* set a context register from its dwarf number */
static void set_context_reg( CONTEXT *context, ULONG_PTR dw_reg, void *val )
{
    switch (dw_reg)
    {
    case 0:  context->Rax = *(ULONG64 *)val; break;
    case 1:  context->Rdx = *(ULONG64 *)val; break;
    case 2:  context->Rcx = *(ULONG64 *)val; break;
    case 3:  context->Rbx = *(ULONG64 *)val; break;
    case 4:  context->Rsi = *(ULONG64 *)val; break;
    case 5:  context->Rdi = *(ULONG64 *)val; break;
    case 6:  context->Rbp = *(ULONG64 *)val; break;
    case 7:  context->Rsp = *(ULONG64 *)val; break;
    case 8:  context->R8  = *(ULONG64 *)val; break;
    case 9:  context->R9  = *(ULONG64 *)val; break;
    case 10: context->R10 = *(ULONG64 *)val; break;
    case 11: context->R11 = *(ULONG64 *)val; break;
    case 12: context->R12 = *(ULONG64 *)val; break;
    case 13: context->R13 = *(ULONG64 *)val; break;
    case 14: context->R14 = *(ULONG64 *)val; break;
    case 15: context->R15 = *(ULONG64 *)val; break;
    case 16: context->Rip = *(ULONG64 *)val; break;
    case 17: context->u.s.Xmm0  = *(M128A *)val; break;
    case 18: context->u.s.Xmm1  = *(M128A *)val; break;
    case 19: context->u.s.Xmm2  = *(M128A *)val; break;
    case 20: context->u.s.Xmm3  = *(M128A *)val; break;
    case 21: context->u.s.Xmm4  = *(M128A *)val; break;
    case 22: context->u.s.Xmm5  = *(M128A *)val; break;
    case 23: context->u.s.Xmm6  = *(M128A *)val; break;
    case 24: context->u.s.Xmm7  = *(M128A *)val; break;
    case 25: context->u.s.Xmm8  = *(M128A *)val; break;
    case 26: context->u.s.Xmm9  = *(M128A *)val; break;
    case 27: context->u.s.Xmm10 = *(M128A *)val; break;
    case 28: context->u.s.Xmm11 = *(M128A *)val; break;
    case 29: context->u.s.Xmm12 = *(M128A *)val; break;
    case 30: context->u.s.Xmm13 = *(M128A *)val; break;
    case 31: context->u.s.Xmm14 = *(M128A *)val; break;
    case 32: context->u.s.Xmm15 = *(M128A *)val; break;
    case 33: context->u.s.Legacy[0] = *(M128A *)val; break;
    case 34: context->u.s.Legacy[1] = *(M128A *)val; break;
    case 35: context->u.s.Legacy[2] = *(M128A *)val; break;
    case 36: context->u.s.Legacy[3] = *(M128A *)val; break;
    case 37: context->u.s.Legacy[4] = *(M128A *)val; break;
    case 38: context->u.s.Legacy[5] = *(M128A *)val; break;
    case 39: context->u.s.Legacy[6] = *(M128A *)val; break;
    case 40: context->u.s.Legacy[7] = *(M128A *)val; break;
    }
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 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 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
static ULONG_PTR eval_expression( const unsigned char *p, CONTEXT *context )
{
    ULONG_PTR reg, tmp, stack[64];
    int sp = -1;
    ULONG_PTR len = dwarf_get_uleb128(&p);
    const unsigned char *end = p + len;

    while (p < end)
    {
        unsigned char opcode = dwarf_get_u1(&p);

        if (opcode >= DW_OP_lit0 && opcode <= DW_OP_lit31)
            stack[++sp] = opcode - DW_OP_lit0;
        else if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31)
            stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_reg0 );
        else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31)
            stack[++sp] = *(ULONG_PTR *)get_context_reg( context, opcode - DW_OP_breg0 ) + dwarf_get_sleb128(&p);
        else switch (opcode)
        {
        case DW_OP_nop:         break;
        case DW_OP_addr:        stack[++sp] = dwarf_get_u8(&p); break;
        case DW_OP_const1u:     stack[++sp] = dwarf_get_u1(&p); break;
        case DW_OP_const1s:     stack[++sp] = (signed char)dwarf_get_u1(&p); break;
        case DW_OP_const2u:     stack[++sp] = dwarf_get_u2(&p); break;
        case DW_OP_const2s:     stack[++sp] = (short)dwarf_get_u2(&p); break;
        case DW_OP_const4u:     stack[++sp] = dwarf_get_u4(&p); break;
        case DW_OP_const4s:     stack[++sp] = (signed int)dwarf_get_u4(&p); break;
        case DW_OP_const8u:     stack[++sp] = dwarf_get_u8(&p); break;
        case DW_OP_const8s:     stack[++sp] = (LONG_PTR)dwarf_get_u8(&p); break;
        case DW_OP_constu:      stack[++sp] = dwarf_get_uleb128(&p); break;
        case DW_OP_consts:      stack[++sp] = dwarf_get_sleb128(&p); break;
        case DW_OP_deref:       stack[sp] = *(ULONG_PTR *)stack[sp]; break;
        case DW_OP_dup:         stack[sp + 1] = stack[sp]; sp++; break;
        case DW_OP_drop:        sp--; break;
        case DW_OP_over:        stack[sp + 1] = stack[sp - 1]; sp++; break;
        case DW_OP_pick:        stack[sp + 1] = stack[sp - dwarf_get_u1(&p)]; sp++; break;
        case DW_OP_swap:        tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = tmp; break;
        case DW_OP_rot:         tmp = stack[sp]; stack[sp] = stack[sp-1]; stack[sp-1] = stack[sp-2]; stack[sp-2] = tmp; break;
        case DW_OP_abs:         stack[sp] = labs(stack[sp]); break;
        case DW_OP_neg:         stack[sp] = -stack[sp]; break;
        case DW_OP_not:         stack[sp] = ~stack[sp]; break;
        case DW_OP_and:         stack[sp-1] &= stack[sp]; sp--; break;
        case DW_OP_or:          stack[sp-1] |= stack[sp]; sp--; break;
        case DW_OP_minus:       stack[sp-1] -= stack[sp]; sp--; break;
        case DW_OP_mul:         stack[sp-1] *= stack[sp]; sp--; break;
        case DW_OP_plus:        stack[sp-1] += stack[sp]; sp--; break;
        case DW_OP_xor:         stack[sp-1] ^= stack[sp]; sp--; break;
        case DW_OP_shl:         stack[sp-1] <<= stack[sp]; sp--; break;
        case DW_OP_shr:         stack[sp-1] >>= stack[sp]; sp--; break;
        case DW_OP_plus_uconst: stack[sp] += dwarf_get_uleb128(&p); break;
        case DW_OP_shra:        stack[sp-1] = (LONG_PTR)stack[sp-1] / (1 << stack[sp]); sp--; break;
        case DW_OP_div:         stack[sp-1] = (LONG_PTR)stack[sp-1] / (LONG_PTR)stack[sp]; sp--; break;
        case DW_OP_mod:         stack[sp-1] = (LONG_PTR)stack[sp-1] % (LONG_PTR)stack[sp]; sp--; break;
        case DW_OP_ge:          stack[sp-1] = ((LONG_PTR)stack[sp-1] >= (LONG_PTR)stack[sp]); sp--; break;
        case DW_OP_gt:          stack[sp-1] = ((LONG_PTR)stack[sp-1] >  (LONG_PTR)stack[sp]); sp--; break;
        case DW_OP_le:          stack[sp-1] = ((LONG_PTR)stack[sp-1] <= (LONG_PTR)stack[sp]); sp--; break;
        case DW_OP_lt:          stack[sp-1] = ((LONG_PTR)stack[sp-1] <  (LONG_PTR)stack[sp]); sp--; break;
        case DW_OP_eq:          stack[sp-1] = (stack[sp-1] == stack[sp]); sp--; break;
        case DW_OP_ne:          stack[sp-1] = (stack[sp-1] != stack[sp]); sp--; break;
        case DW_OP_skip:        tmp = (short)dwarf_get_u2(&p); p += tmp; break;
        case DW_OP_bra:         tmp = (short)dwarf_get_u2(&p); if (!stack[sp--]) p += tmp; break;
        case DW_OP_GNU_encoded_addr: tmp = *p++; stack[++sp] = dwarf_get_ptr( &p, tmp ); break;
        case DW_OP_regx:        stack[++sp] = *(ULONG_PTR *)get_context_reg( context, dwarf_get_uleb128(&p) ); break;
        case DW_OP_bregx:
            reg = dwarf_get_uleb128(&p);
            tmp = dwarf_get_sleb128(&p);
            stack[++sp] = *(ULONG_PTR *)get_context_reg( context, reg ) + tmp;
            break;
        case DW_OP_deref_size:
            switch (*p++)
            {
            case 1: stack[sp] = *(unsigned char *)stack[sp]; break;
            case 2: stack[sp] = *(unsigned short *)stack[sp]; break;
            case 4: stack[sp] = *(unsigned int *)stack[sp]; break;
            case 8: stack[sp] = *(ULONG_PTR *)stack[sp]; break;
            }
            break;
        default:
            FIXME( "unhandled opcode %02x\n", opcode );
        }
    }
    return stack[sp];
}

1109
/* apply the computed frame info to the actual context */
1110
static void apply_frame_info( CONTEXT *context, struct frame_info *info )
1111 1112
{
    unsigned int i;
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    ULONG_PTR cfa, value;
    CONTEXT new_context = *context;

    switch (info->cfa_rule)
    {
    case RULE_EXPRESSION:
        cfa = *(ULONG_PTR *)eval_expression( (const unsigned char *)info->cfa_offset, context );
        break;
    case RULE_VAL_EXPRESSION:
        cfa = eval_expression( (const unsigned char *)info->cfa_offset, context );
        break;
    default:
        cfa = *(ULONG_PTR *)get_context_reg( context, info->cfa_reg ) + info->cfa_offset;
        break;
    }
    if (!cfa) return;
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

    for (i = 0; i < NB_FRAME_REGS; i++)
    {
        switch (info->rules[i])
        {
        case RULE_UNSET:
        case RULE_UNDEFINED:
        case RULE_SAME:
            break;
        case RULE_CFA_OFFSET:
1139
            set_context_reg( &new_context, i, (char *)cfa + info->regs[i] );
1140 1141
            break;
        case RULE_OTHER_REG:
1142 1143 1144 1145 1146 1147 1148 1149 1150
            set_context_reg( &new_context, i, get_context_reg( context, info->regs[i] ));
            break;
        case RULE_EXPRESSION:
            value = eval_expression( (const unsigned char *)info->regs[i], context );
            set_context_reg( &new_context, i, (void *)value );
            break;
        case RULE_VAL_EXPRESSION:
            value = eval_expression( (const unsigned char *)info->regs[i], context );
            set_context_reg( &new_context, i, &value );
1151 1152 1153
            break;
        }
    }
1154 1155
    new_context.Rsp = cfa;
    *context = new_context;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
}


/***********************************************************************
 *           dwarf_virtual_unwind
 *
 * Equivalent of RtlVirtualUnwind for builtin modules.
 */
static NTSTATUS dwarf_virtual_unwind( ULONG64 ip, ULONG64 *frame,CONTEXT *context,
                                      const struct dwarf_fde *fde, const struct dwarf_eh_bases *bases,
                                      PEXCEPTION_ROUTINE *handler, void **handler_data )
{
    const struct dwarf_cie *cie;
    const unsigned char *ptr, *augmentation, *end;
1170
    ULONG_PTR len, code_end;
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    struct frame_info info;
    int aug_z_format = 0;
    unsigned char lsda_encoding = DW_EH_PE_omit;

    memset( &info, 0, sizeof(info) );
    info.ip = (ULONG_PTR)bases->func;
    *handler = NULL;

    cie = (const struct dwarf_cie *)((const char *)&fde->cie_offset - fde->cie_offset);

    /* parse the CIE first */

    if (cie->version != 1)
    {
        FIXME( "unknown CIE version %u at %p\n", cie->version, cie );
        return STATUS_INVALID_DISPOSITION;
    }
    ptr = cie->augmentation + strlen((const char *)cie->augmentation) + 1;

    info.code_align = dwarf_get_uleb128( &ptr );
    info.data_align = dwarf_get_sleb128( &ptr );
    info.retaddr_reg = *ptr++;
1193
    info.cfa_rule = RULE_CFA_OFFSET;
1194 1195 1196 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 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

    TRACE( "function %lx base %p cie %p len %x id %x version %x aug '%s' code_align %lu data_align %ld retaddr %s\n",
           ip, bases->func, cie, cie->length, cie->id, cie->version, cie->augmentation,
           info.code_align, info.data_align, dwarf_reg_names[info.retaddr_reg] );

    end = NULL;
    for (augmentation = cie->augmentation; *augmentation; augmentation++)
    {
        switch (*augmentation)
        {
        case 'z':
            len = dwarf_get_uleb128( &ptr );
            end = ptr + len;
            aug_z_format = 1;
            continue;
        case 'L':
            lsda_encoding = *ptr++;
            continue;
        case 'P':
        {
            unsigned char encoding = *ptr++;
            *handler = (void *)dwarf_get_ptr( &ptr, encoding );
            continue;
        }
        case 'R':
            info.fde_encoding = *ptr++;
            continue;
        case 'S':
            info.signal_frame = 1;
            continue;
        }
        FIXME( "unknown augmentation '%c'\n", *augmentation );
        if (!end) return STATUS_INVALID_DISPOSITION;  /* cannot continue */
        break;
    }
    if (end) ptr = end;

    end = (const unsigned char *)(&cie->length + 1) + cie->length;
    execute_cfa_instructions( ptr, end, ip, &info );

    ptr = (const unsigned char *)(fde + 1);
    info.ip = dwarf_get_ptr( &ptr, info.fde_encoding );  /* fde code start */
    code_end = info.ip + dwarf_get_ptr( &ptr, info.fde_encoding & 0x0f );  /* fde code length */

    if (aug_z_format)  /* get length of augmentation data */
    {
        len = dwarf_get_uleb128( &ptr );
        end = ptr + len;
    }
    else end = NULL;

    *handler_data = (void *)dwarf_get_ptr( &ptr, lsda_encoding );
    if (end) ptr = end;

    end = (const unsigned char *)(&fde->length + 1) + fde->length;
    TRACE( "fde %p len %x personality %p lsda %p code %lx-%lx\n",
           fde, fde->length, *handler, *handler_data, info.ip, code_end );
    execute_cfa_instructions( ptr, end, ip, &info );
1252 1253
    apply_frame_info( context, &info );
    *frame = context->Rsp;
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

    TRACE( "next function rip=%016lx\n", context->Rip );
    TRACE( "  rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
           context->Rax, context->Rbx, context->Rcx, context->Rdx );
    TRACE( "  rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
           context->Rsi, context->Rdi, context->Rbp, context->Rsp );
    TRACE( "   r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
           context->R8, context->R9, context->R10, context->R11 );
    TRACE( "  r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
           context->R12, context->R13, context->R14, context->R15 );

    return STATUS_SUCCESS;
}


1269 1270 1271
/***********************************************************************
 *           dispatch_signal
 */
1272
static inline int dispatch_signal(unsigned int sig)
1273 1274 1275 1276 1277
{
    if (handlers[sig] == NULL) return 0;
    return handlers[sig](sig);
}

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
/***********************************************************************
 *           get_signal_stack
 *
 * Get the base of the signal stack for the current thread.
 */
static inline void *get_signal_stack(void)
{
    return (char *)NtCurrentTeb() + teb_size;
}

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
/***********************************************************************
 *           is_inside_signal_stack
 *
 * Check if pointer is inside the signal stack.
 */
static inline int is_inside_signal_stack( void *ptr )
{
    return ((char *)ptr >= (char *)get_signal_stack() &&
            (char *)ptr < (char *)get_signal_stack() + signal_stack_size);
}

1299 1300 1301 1302 1303
/***********************************************************************
 *           save_context
 *
 * Set the register values from a sigcontext.
 */
1304
static void save_context( CONTEXT *context, const ucontext_t *sigcontext )
1305
{
1306
    context->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    context->Rax    = RAX_sig(sigcontext);
    context->Rcx    = RCX_sig(sigcontext);
    context->Rdx    = RDX_sig(sigcontext);
    context->Rbx    = RBX_sig(sigcontext);
    context->Rsp    = RSP_sig(sigcontext);
    context->Rbp    = RBP_sig(sigcontext);
    context->Rsi    = RSI_sig(sigcontext);
    context->Rdi    = RDI_sig(sigcontext);
    context->R8     = R8_sig(sigcontext);
    context->R9     = R9_sig(sigcontext);
    context->R10    = R10_sig(sigcontext);
    context->R11    = R11_sig(sigcontext);
    context->R12    = R12_sig(sigcontext);
    context->R13    = R13_sig(sigcontext);
    context->R14    = R14_sig(sigcontext);
    context->R15    = R15_sig(sigcontext);
    context->Rip    = RIP_sig(sigcontext);
    context->SegCs  = CS_sig(sigcontext);
    context->SegFs  = FS_sig(sigcontext);
    context->SegGs  = GS_sig(sigcontext);
    context->EFlags = EFL_sig(sigcontext);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
#ifdef DS_sig
    context->SegDs  = DS_sig(sigcontext);
#else
    __asm__("movw %%ds,%0" : "=m" (context->SegDs));
#endif
#ifdef ES_sig
    context->SegEs  = ES_sig(sigcontext);
#else
    __asm__("movw %%es,%0" : "=m" (context->SegEs));
#endif
#ifdef SS_sig
    context->SegSs  = SS_sig(sigcontext);
#else
    __asm__("movw %%ss,%0" : "=m" (context->SegSs));
#endif
1343 1344 1345 1346
    if (FPU_sig(sigcontext))
    {
        context->ContextFlags |= CONTEXT_FLOATING_POINT;
        context->u.FltSave = *FPU_sig(sigcontext);
1347
        context->MxCsr = context->u.FltSave.MxCsr;
1348
    }
1349 1350 1351 1352 1353 1354 1355 1356
}


/***********************************************************************
 *           restore_context
 *
 * Build a sigcontext from the register values.
 */
1357
static void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
{
    RAX_sig(sigcontext) = context->Rax;
    RCX_sig(sigcontext) = context->Rcx;
    RDX_sig(sigcontext) = context->Rdx;
    RBX_sig(sigcontext) = context->Rbx;
    RSP_sig(sigcontext) = context->Rsp;
    RBP_sig(sigcontext) = context->Rbp;
    RSI_sig(sigcontext) = context->Rsi;
    RDI_sig(sigcontext) = context->Rdi;
    R8_sig(sigcontext)  = context->R8;
    R9_sig(sigcontext)  = context->R9;
    R10_sig(sigcontext) = context->R10;
    R11_sig(sigcontext) = context->R11;
    R12_sig(sigcontext) = context->R12;
    R13_sig(sigcontext) = context->R13;
    R14_sig(sigcontext) = context->R14;
    R15_sig(sigcontext) = context->R15;
    RIP_sig(sigcontext) = context->Rip;
    CS_sig(sigcontext)  = context->SegCs;
    FS_sig(sigcontext)  = context->SegFs;
    GS_sig(sigcontext)  = context->SegGs;
    EFL_sig(sigcontext) = context->EFlags;
1380 1381 1382 1383 1384 1385 1386 1387 1388
#ifdef DS_sig
    DS_sig(sigcontext) = context->SegDs;
#endif
#ifdef ES_sig
    ES_sig(sigcontext) = context->SegEs;
#endif
#ifdef SS_sig
    SS_sig(sigcontext) = context->SegSs;
#endif
1389 1390 1391 1392
    if (FPU_sig(sigcontext)) *FPU_sig(sigcontext) = context->u.FltSave;
}


1393
/***********************************************************************
1394
 *		RtlCaptureContext (NTDLL.@)
1395
 */
1396
void WINAPI __regs_RtlCaptureContext( CONTEXT *context, CONTEXT *regs )
1397
{
1398
    *context = *regs;
1399
}
1400
DEFINE_REGS_ENTRYPOINT( RtlCaptureContext, 1 )
1401 1402


1403 1404 1405 1406 1407 1408 1409
/***********************************************************************
 *           set_cpu_context
 *
 * Set the new CPU context.
 */
void set_cpu_context( const CONTEXT *context )
{
1410 1411
    extern void CDECL __wine_restore_regs( const CONTEXT * ) DECLSPEC_NORETURN;
    __wine_restore_regs( context );
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
/***********************************************************************
 *           copy_context
 *
 * Copy a register context according to the flags.
 */
void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
{
    flags &= ~CONTEXT_AMD64;  /* get rid of CPU id */
    if (flags & CONTEXT_CONTROL)
    {
        to->Rbp    = from->Rbp;
        to->Rip    = from->Rip;
        to->Rsp    = from->Rsp;
        to->SegCs  = from->SegCs;
        to->SegSs  = from->SegSs;
        to->EFlags = from->EFlags;
    }
    if (flags & CONTEXT_INTEGER)
    {
        to->Rax = from->Rax;
        to->Rcx = from->Rcx;
        to->Rdx = from->Rdx;
        to->Rbx = from->Rbx;
        to->Rsi = from->Rsi;
        to->Rdi = from->Rdi;
        to->R8  = from->R8;
        to->R9  = from->R9;
        to->R10 = from->R10;
        to->R11 = from->R11;
        to->R12 = from->R12;
        to->R13 = from->R13;
        to->R14 = from->R14;
        to->R15 = from->R15;
    }
    if (flags & CONTEXT_SEGMENTS)
    {
        to->SegDs = from->SegDs;
        to->SegEs = from->SegEs;
        to->SegFs = from->SegFs;
        to->SegGs = from->SegGs;
    }
    if (flags & CONTEXT_FLOATING_POINT)
    {
1458
        to->MxCsr = from->MxCsr;
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
        to->u.FltSave = from->u.FltSave;
    }
    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;
    }
}


1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 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 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
/***********************************************************************
 *           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_AMD64;  /* get rid of CPU id */

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

    if (flags & CONTEXT_CONTROL)
    {
        to->flags |= SERVER_CTX_CONTROL;
        to->ctl.x86_64_regs.rbp   = from->Rbp;
        to->ctl.x86_64_regs.rip   = from->Rip;
        to->ctl.x86_64_regs.rsp   = from->Rsp;
        to->ctl.x86_64_regs.cs    = from->SegCs;
        to->ctl.x86_64_regs.ss    = from->SegSs;
        to->ctl.x86_64_regs.flags = from->EFlags;
    }
    if (flags & CONTEXT_INTEGER)
    {
        to->flags |= SERVER_CTX_INTEGER;
        to->integer.x86_64_regs.rax = from->Rax;
        to->integer.x86_64_regs.rcx = from->Rcx;
        to->integer.x86_64_regs.rdx = from->Rdx;
        to->integer.x86_64_regs.rbx = from->Rbx;
        to->integer.x86_64_regs.rsi = from->Rsi;
        to->integer.x86_64_regs.rdi = from->Rdi;
        to->integer.x86_64_regs.r8  = from->R8;
        to->integer.x86_64_regs.r9  = from->R9;
        to->integer.x86_64_regs.r10 = from->R10;
        to->integer.x86_64_regs.r11 = from->R11;
        to->integer.x86_64_regs.r12 = from->R12;
        to->integer.x86_64_regs.r13 = from->R13;
        to->integer.x86_64_regs.r14 = from->R14;
        to->integer.x86_64_regs.r15 = from->R15;
    }
    if (flags & CONTEXT_SEGMENTS)
    {
        to->flags |= SERVER_CTX_SEGMENTS;
        to->seg.x86_64_regs.ds = from->SegDs;
        to->seg.x86_64_regs.es = from->SegEs;
        to->seg.x86_64_regs.fs = from->SegFs;
        to->seg.x86_64_regs.gs = from->SegGs;
    }
    if (flags & CONTEXT_FLOATING_POINT)
    {
        to->flags |= SERVER_CTX_FLOATING_POINT;
        memcpy( to->fp.x86_64_regs.fpregs, &from->u.FltSave, sizeof(to->fp.x86_64_regs.fpregs) );
    }
    if (flags & CONTEXT_DEBUG_REGISTERS)
    {
        to->flags |= SERVER_CTX_DEBUG_REGISTERS;
        to->debug.x86_64_regs.dr0 = from->Dr0;
        to->debug.x86_64_regs.dr1 = from->Dr1;
        to->debug.x86_64_regs.dr2 = from->Dr2;
        to->debug.x86_64_regs.dr3 = from->Dr3;
        to->debug.x86_64_regs.dr6 = from->Dr6;
        to->debug.x86_64_regs.dr7 = from->Dr7;
    }
    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_64) return STATUS_INVALID_PARAMETER;

    to->ContextFlags = CONTEXT_AMD64;
    if (from->flags & SERVER_CTX_CONTROL)
    {
        to->ContextFlags |= CONTEXT_CONTROL;
        to->Rbp    = from->ctl.x86_64_regs.rbp;
        to->Rip    = from->ctl.x86_64_regs.rip;
        to->Rsp    = from->ctl.x86_64_regs.rsp;
        to->SegCs  = from->ctl.x86_64_regs.cs;
        to->SegSs  = from->ctl.x86_64_regs.ss;
        to->EFlags = from->ctl.x86_64_regs.flags;
    }

    if (from->flags & SERVER_CTX_INTEGER)
    {
        to->ContextFlags |= CONTEXT_INTEGER;
        to->Rax = from->integer.x86_64_regs.rax;
        to->Rcx = from->integer.x86_64_regs.rcx;
        to->Rdx = from->integer.x86_64_regs.rdx;
        to->Rbx = from->integer.x86_64_regs.rbx;
        to->Rsi = from->integer.x86_64_regs.rsi;
        to->Rdi = from->integer.x86_64_regs.rdi;
        to->R8  = from->integer.x86_64_regs.r8;
        to->R9  = from->integer.x86_64_regs.r9;
        to->R10 = from->integer.x86_64_regs.r10;
        to->R11 = from->integer.x86_64_regs.r11;
        to->R12 = from->integer.x86_64_regs.r12;
        to->R13 = from->integer.x86_64_regs.r13;
        to->R14 = from->integer.x86_64_regs.r14;
        to->R15 = from->integer.x86_64_regs.r15;
    }
    if (from->flags & SERVER_CTX_SEGMENTS)
    {
        to->ContextFlags |= CONTEXT_SEGMENTS;
        to->SegDs = from->seg.x86_64_regs.ds;
        to->SegEs = from->seg.x86_64_regs.es;
        to->SegFs = from->seg.x86_64_regs.fs;
        to->SegGs = from->seg.x86_64_regs.gs;
    }
    if (from->flags & SERVER_CTX_FLOATING_POINT)
    {
        to->ContextFlags |= CONTEXT_FLOATING_POINT;
        memcpy( &to->u.FltSave, from->fp.x86_64_regs.fpregs, sizeof(from->fp.x86_64_regs.fpregs) );
1591
        to->MxCsr = to->u.FltSave.MxCsr;
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
    }
    if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
    {
        to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
        to->Dr0 = from->debug.x86_64_regs.dr0;
        to->Dr1 = from->debug.x86_64_regs.dr1;
        to->Dr2 = from->debug.x86_64_regs.dr2;
        to->Dr3 = from->debug.x86_64_regs.dr3;
        to->Dr6 = from->debug.x86_64_regs.dr6;
        to->Dr7 = from->debug.x86_64_regs.dr7;
    }
    return STATUS_SUCCESS;
}


1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
extern void raise_func_trampoline( EXCEPTION_RECORD *rec, CONTEXT *context, raise_func func );
__ASM_GLOBAL_FUNC( raise_func_trampoline,
                   ".cfi_signal_frame\n\t"
                   ".cfi_def_cfa %rbp,144\n\t"  /* red zone + rip + rbp */
                   ".cfi_rel_offset %rip,8\n\t"
                   ".cfi_rel_offset %rbp,0\n\t"
                   "call *%rdx\n\t"
                   "int $3")

/***********************************************************************
 *           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.
 */
static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
{
    struct stack_layout
    {
        CONTEXT           context;
        EXCEPTION_RECORD  rec;
        ULONG64           rbp;
        ULONG64           rip;
        ULONG64           red_zone[16];
    } *stack;
    ULONG64 *rsp_ptr;
    DWORD exception_code = 0;

    stack = (struct stack_layout *)(RSP_sig(sigcontext) & ~15);

    /* stack sanity checks */

1640
    if (is_inside_signal_stack( stack ))
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    {
        ERR( "nested exception on signal stack in thread %04x eip %016lx esp %016lx stack %p-%p\n",
             GetCurrentThreadId(), RIP_sig(sigcontext), RSP_sig(sigcontext),
             NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
        abort_thread(1);
    }

    if (stack - 1 > stack || /* check for overflow in subtraction */
        (char *)stack <= (char *)NtCurrentTeb()->DeallocationStack ||
        (char *)stack > (char *)NtCurrentTeb()->Tib.StackBase)
    {
        WARN( "exception outside of stack limits in thread %04x eip %016lx esp %016lx stack %p-%p\n",
              GetCurrentThreadId(), RIP_sig(sigcontext), RSP_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);
        ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
             diff, GetCurrentThreadId(), RIP_sig(sigcontext),
             RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
             NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
        abort_thread(1);
    }
    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
        {
            UINT diff = (char *)NtCurrentTeb()->Tib.StackLimit - (char *)(stack - 1);
            ERR( "stack overflow %u bytes in thread %04x eip %016lx esp %016lx stack %p-%p-%p\n",
                 diff, GetCurrentThreadId(), RIP_sig(sigcontext),
                 RSP_sig(sigcontext), NtCurrentTeb()->DeallocationStack,
                 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
            abort_thread(1);
        }
    }

    stack--;  /* push the stack_layout structure */
    stack->rec.ExceptionRecord  = NULL;
    stack->rec.ExceptionCode    = exception_code;
    stack->rec.ExceptionFlags   = EXCEPTION_CONTINUABLE;
    stack->rec.ExceptionAddress = (void *)RIP_sig(sigcontext);
    stack->rec.NumberParameters = 0;
    save_context( &stack->context, sigcontext );

    /* store return address and %rbp without aligning, so that the offset is fixed */
    rsp_ptr = (ULONG64 *)RSP_sig(sigcontext) - 16;
    *(--rsp_ptr) = RIP_sig(sigcontext);
    *(--rsp_ptr) = RBP_sig(sigcontext);

    /* now modify the sigcontext to return to the raise function */
    RIP_sig(sigcontext) = (ULONG_PTR)raise_func_trampoline;
    RDI_sig(sigcontext) = (ULONG_PTR)&stack->rec;
    RSI_sig(sigcontext) = (ULONG_PTR)&stack->context;
    RDX_sig(sigcontext) = (ULONG_PTR)func;
    RBP_sig(sigcontext) = (ULONG_PTR)rsp_ptr;
    RSP_sig(sigcontext) = (ULONG_PTR)stack;
    /* clear single-step, direction, and align check flag */
    EFL_sig(sigcontext) &= ~(0x100|0x400|0x40000);

    return &stack->rec;
}


1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
/**********************************************************************
 *           find_function_info
 */
static RUNTIME_FUNCTION *find_function_info( ULONG64 pc, HMODULE module,
                                             RUNTIME_FUNCTION *func, ULONG size )
{
    int min = 0;
    int max = size/sizeof(*func) - 1;

    while (min <= max)
    {
        int pos = (min + max) / 2;
        if ((char *)pc < (char *)module + func[pos].BeginAddress) max = pos - 1;
        else if ((char *)pc >= (char *)module + func[pos].EndAddress) min = pos + 1;
        else
        {
            func += pos;
            while (func->UnwindData & 1)  /* follow chained entry */
                func = (RUNTIME_FUNCTION *)((char *)module + (func->UnwindData & ~1));
            return func;
        }
    }
    return NULL;
}

1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767

/**********************************************************************
 *           call_handler
 *
 * Call a single exception handler.
 * FIXME: Handle nested exceptions.
 */
static NTSTATUS call_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch, CONTEXT *orig_context )
{
    DWORD res;

    dispatch->ControlPc = dispatch->ContextRecord->Rip;

    TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
           dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
    res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
    TRACE( "handler at %p returned %u\n", dispatch->LanguageHandler, res );

    switch (res)
    {
    case ExceptionContinueExecution:
        if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
        *orig_context = *dispatch->ContextRecord;
        return STATUS_SUCCESS;
    case ExceptionContinueSearch:
        break;
    case ExceptionNestedException:
        break;
    default:
        return STATUS_INVALID_DISPOSITION;
    }
    return STATUS_UNHANDLED_EXCEPTION;
}


1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
/**********************************************************************
 *           call_teb_handler
 *
 * Call a single exception handler from the TEB chain.
 * FIXME: Handle nested exceptions.
 */
static NTSTATUS call_teb_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
                                  EXCEPTION_REGISTRATION_RECORD *teb_frame, CONTEXT *orig_context )
{
    EXCEPTION_REGISTRATION_RECORD *dispatcher;
    DWORD res;

    TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatcher=%p)\n",
           teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, &dispatcher );
    res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, &dispatcher );
    TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );

    switch (res)
    {
    case ExceptionContinueExecution:
        if (rec->ExceptionFlags & EH_NONCONTINUABLE) return STATUS_NONCONTINUABLE_EXCEPTION;
        *orig_context = *dispatch->ContextRecord;
        return STATUS_SUCCESS;
    case ExceptionContinueSearch:
        break;
    case ExceptionNestedException:
        break;
    default:
        return STATUS_INVALID_DISPOSITION;
    }
    return STATUS_UNHANDLED_EXCEPTION;
}


1802 1803 1804 1805 1806
/**********************************************************************
 *           call_stack_handlers
 *
 * Call the stack handlers chain.
 */
1807
static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *orig_context )
1808
{
1809
    EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
1810
    UNWIND_HISTORY_TABLE table;
1811
    RUNTIME_FUNCTION *dir;
1812 1813 1814 1815
    DISPATCHER_CONTEXT dispatch;
    CONTEXT context, new_context;
    LDR_MODULE *module;
    DWORD size;
1816
    NTSTATUS status;
1817 1818

    context = *orig_context;
1819 1820 1821 1822
    dispatch.TargetIp      = 0;
    dispatch.ContextRecord = &context;
    dispatch.HistoryTable  = &table;
    dispatch.ScopeIndex    = 0; /* FIXME */
1823 1824
    for (;;)
    {
1825 1826
        new_context = context;

1827 1828
        /* FIXME: should use the history table to make things faster */

1829 1830 1831 1832 1833
        dir = NULL;
        module = NULL;
        dispatch.ImageBase = 0;

        if (!LdrFindEntryForAddress( (void *)context.Rip, &module ))
1834
        {
1835 1836 1837 1838 1839 1840 1841 1842 1843
            if (!(dir = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
                                                      IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )) &&
                !(module->Flags & LDR_WINE_INTERNAL))
            {
                ERR( "module %s doesn't contain exception data, can't dispatch exception\n",
                     debugstr_w(module->BaseDllName.Buffer) );
                break;
            }
            dispatch.ImageBase = (ULONG64)module->BaseAddress;
1844
        }
1845 1846

        if (!dir)
1847
        {
1848 1849 1850 1851
            struct dwarf_eh_bases bases;
            const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context.Rip - 1), &bases );
            if (!fde)
            {
1852 1853 1854 1855
                /* assume leaf function */
                context.Rip = *(ULONG64 *)context.Rsp;
                context.Rsp += sizeof(ULONG64);
                continue;
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
            }
            status = dwarf_virtual_unwind( context.Rip, &dispatch.EstablisherFrame, &new_context,
                                           fde, &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
            if (status != STATUS_SUCCESS) return status;
            dispatch.FunctionEntry = NULL;
            if (dispatch.LanguageHandler && !module)
            {
                FIXME( "calling personality routine in system library not supported yet\n" );
                dispatch.LanguageHandler = NULL;
            }
1866
        }
1867
        else
1868
        {
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
            if (!(dispatch.FunctionEntry = find_function_info( context.Rip, module->BaseAddress,
                                                               dir, size )))
            {
                /* leaf function */
                context.Rip = *(ULONG64 *)context.Rsp;
                context.Rsp += sizeof(ULONG64);
                continue;
            }
            dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, dispatch.ImageBase,
                                                         context.Rip, dispatch.FunctionEntry,
                                                         &new_context, &dispatch.HandlerData,
                                                         &dispatch.EstablisherFrame, NULL );
1881 1882
        }

1883
        if (!dispatch.EstablisherFrame) break;
1884

1885 1886 1887
        if ((dispatch.EstablisherFrame & 7) ||
            dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
            dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
1888
        {
1889 1890
            ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
                 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
1891 1892 1893 1894
            rec->ExceptionFlags |= EH_STACK_INVALID;
            break;
        }

1895
        if (dispatch.LanguageHandler)
1896
        {
1897 1898
            status = call_handler( rec, &dispatch, orig_context );
            if (status != STATUS_UNHANDLED_EXCEPTION) return status;
1899
        }
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
        /* hack: call wine handlers registered in the tib list */
        else while ((ULONG64)teb_frame < new_context.Rsp)
        {
            TRACE( "found wine frame %p rsp %lx handler %p\n",
                   teb_frame, new_context.Rsp, teb_frame->Handler );
            dispatch.EstablisherFrame = (ULONG64)teb_frame;
            context = *orig_context;
            status = call_teb_handler( rec, &dispatch, teb_frame, orig_context );
            if (status != STATUS_UNHANDLED_EXCEPTION) return status;
            teb_frame = teb_frame->Prev;
        }
1911 1912

        if (new_context.Rsp == (ULONG64)NtCurrentTeb()->Tib.StackBase) break;
1913 1914
        context = new_context;
    }
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
    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=%lx tid=%04x\n",
               rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
               context->Rip, GetCurrentThreadId() );
1935
        for (c = 0; c < min( EXCEPTION_MAXIMUM_PARAMETERS, rec->NumberParameters ); c++)
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
            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(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
                  context->Rax, context->Rbx, context->Rcx, context->Rdx );
            TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
                  context->Rsi, context->Rdi, context->Rbp, context->Rsp );
            TRACE("  r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
                  context->R8, context->R9, context->R10, context->R11 );
            TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
                  context->R12, context->R13, context->R14, context->R15 );
        }
        status = send_debug_event( rec, TRUE, context );
        if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
            return STATUS_SUCCESS;

        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)
            ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
        else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
            ERR("Process attempted to continue execution after noncontinuable exception.\n");
        else
            ERR("Unhandled exception code %x flags %x addr %p\n",
                rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
        NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
    }
    return STATUS_SUCCESS;
}


1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
/**********************************************************************
 *		raise_segv_exception
 */
static void raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
{
    NTSTATUS status;

    switch(rec->ExceptionCode)
    {
    case EXCEPTION_ACCESS_VIOLATION:
        if (rec->NumberParameters == 2)
        {
            if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
                                                             rec->ExceptionInformation[0] )))
                set_cpu_context( context );
        }
        break;
    }
    status = raise_exception( rec, context, TRUE );
    if (status) raise_status( status, rec );
2008
    set_cpu_context( context );
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
}


/**********************************************************************
 *		raise_generic_exception
 *
 * Generic raise function for exceptions that don't need special treatment.
 */
static void raise_generic_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
{
    NTSTATUS status = raise_exception( rec, context, TRUE );
    if (status) raise_status( status, rec );
2021
    set_cpu_context( context );
2022 2023 2024
}


2025 2026 2027 2028 2029
/**********************************************************************
 *		segv_handler
 *
 * Handler for SIGSEGV and related errors.
 */
2030
static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2031
{
2032
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_segv_exception );
2033
    ucontext_t *ucontext = sigcontext;
2034

2035
    switch(TRAP_sig(ucontext))
2036
    {
2037
    case TRAP_x86_OFLOW:   /* Overflow exception */
2038
        rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2039
        break;
2040
    case TRAP_x86_BOUND:   /* Bound range exception */
2041
        rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2042
        break;
2043
    case TRAP_x86_PRIVINFLT:   /* Invalid opcode exception */
2044
        rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2045
        break;
2046
    case TRAP_x86_STKFLT:  /* Stack fault */
2047
        rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
2048
        break;
2049 2050 2051
    case TRAP_x86_SEGNPFLT:  /* Segment not present exception */
    case TRAP_x86_PROTFLT:   /* General protection fault */
    case TRAP_x86_UNKNOWN:   /* Unknown fault code */
2052 2053
        rec->ExceptionCode = ERROR_sig(ucontext) ? EXCEPTION_ACCESS_VIOLATION : EXCEPTION_PRIV_INSTRUCTION;
        rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
2054
        break;
2055
    case TRAP_x86_PAGEFLT:  /* Page fault */
2056 2057 2058 2059
        rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
        rec->NumberParameters = 2;
        rec->ExceptionInformation[0] = (ERROR_sig(ucontext) & 2) != 0;
        rec->ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr;
2060
        break;
2061
    case TRAP_x86_ALIGNFLT:  /* Alignment check exception */
2062
        rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
2063 2064
        break;
    default:
2065
        ERR( "Got unexpected trap %ld\n", TRAP_sig(ucontext) );
2066
        /* fall through */
2067 2068 2069 2070 2071 2072
    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 */
2073
        rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
2074 2075 2076 2077 2078 2079 2080 2081 2082
        break;
    }
}

/**********************************************************************
 *		trap_handler
 *
 * Handler for SIGTRAP.
 */
2083
static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2084
{
2085
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2086

2087
    switch (siginfo->si_code)
2088 2089
    {
    case TRAP_TRACE:  /* Single-step exception */
2090
        rec->ExceptionCode = EXCEPTION_SINGLE_STEP;
2091 2092
        break;
    case TRAP_BRKPT:   /* Breakpoint exception */
2093
        rec->ExceptionAddress = (char *)rec->ExceptionAddress - 1;  /* back up over the int3 instruction */
2094 2095
        /* fall through */
    default:
2096
        rec->ExceptionCode = EXCEPTION_BREAKPOINT;
2097 2098 2099 2100 2101 2102 2103 2104 2105
        break;
    }
}

/**********************************************************************
 *		fpe_handler
 *
 * Handler for SIGFPE.
 */
2106
static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2107
{
2108
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
2109

2110
    switch (siginfo->si_code)
2111 2112
    {
    case FPE_FLTSUB:
2113
        rec->ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
2114 2115
        break;
    case FPE_INTDIV:
2116
        rec->ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
2117 2118
        break;
    case FPE_INTOVF:
2119
        rec->ExceptionCode = EXCEPTION_INT_OVERFLOW;
2120 2121
        break;
    case FPE_FLTDIV:
2122
        rec->ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO;
2123 2124
        break;
    case FPE_FLTOVF:
2125
        rec->ExceptionCode = EXCEPTION_FLT_OVERFLOW;
2126 2127
        break;
    case FPE_FLTUND:
2128
        rec->ExceptionCode = EXCEPTION_FLT_UNDERFLOW;
2129 2130
        break;
    case FPE_FLTRES:
2131
        rec->ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT;
2132 2133 2134
        break;
    case FPE_FLTINV:
    default:
2135
        rec->ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
2136 2137 2138 2139 2140 2141 2142 2143 2144
        break;
    }
}

/**********************************************************************
 *		int_handler
 *
 * Handler for SIGINT.
 */
2145
static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2146 2147 2148
{
    if (!dispatch_signal(SIGINT))
    {
2149 2150
        EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
        rec->ExceptionCode = CONTROL_C_EXIT;
2151 2152 2153 2154 2155 2156 2157 2158 2159
    }
}


/**********************************************************************
 *		abrt_handler
 *
 * Handler for SIGABRT.
 */
2160
static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
2161
{
2162 2163 2164
    EXCEPTION_RECORD *rec = setup_exception( sigcontext, raise_generic_exception );
    rec->ExceptionCode = EXCEPTION_WINE_ASSERTION;
    rec->ExceptionFlags = EH_NONCONTINUABLE;
2165 2166 2167 2168
}


/**********************************************************************
2169
 *		quit_handler
2170
 *
2171
 * Handler for SIGQUIT.
2172
 */
2173
static void quit_handler( int signal, siginfo_t *siginfo, void *ucontext )
2174
{
2175
    abort_thread(0);
2176 2177 2178 2179 2180 2181 2182 2183
}


/**********************************************************************
 *		usr1_handler
 *
 * Handler for SIGUSR1, used to signal a thread that it got suspended.
 */
2184
static void usr1_handler( int signal, siginfo_t *siginfo, void *ucontext )
2185
{
2186
    CONTEXT context;
2187

2188
    save_context( &context, ucontext );
2189
    wait_suspend( &context );
2190
    restore_context( &context, ucontext );
2191 2192 2193
}


2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
/***********************************************************************
 *           __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;
}


2206
/**********************************************************************
2207
 *		signal_alloc_thread
2208
 */
2209
NTSTATUS signal_alloc_thread( TEB **teb )
2210
{
2211 2212 2213 2214 2215
    static size_t sigstack_zero_bits;
    SIZE_T size;
    NTSTATUS status;

    if (!sigstack_zero_bits)
2216
    {
2217
        size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
2218
        /* find the first power of two not smaller than min_size */
2219 2220 2221 2222
        sigstack_zero_bits = 12;
        while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
        signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
        assert( sizeof(TEB) <= teb_size );
2223
    }
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233

    size = 1 << sigstack_zero_bits;
    *teb = NULL;
    if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)teb, sigstack_zero_bits,
                                            &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
    {
        (*teb)->Tib.Self = &(*teb)->Tib;
        (*teb)->Tib.ExceptionList = (void *)~0UL;
    }
    return status;
2234 2235 2236
}


2237 2238
/**********************************************************************
 *		signal_free_thread
2239
 */
2240
void signal_free_thread( TEB *teb )
2241
{
2242 2243 2244 2245 2246 2247 2248 2249 2250
    SIZE_T size;

    if (teb->DeallocationStack)
    {
        size = 0;
        NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
    }
    size = 0;
    NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
2251 2252 2253 2254
}


/**********************************************************************
2255
 *		signal_init_thread
2256
 */
2257
void signal_init_thread( TEB *teb )
2258
{
2259 2260
    stack_t ss;

2261 2262 2263 2264 2265
#ifdef __linux__
    arch_prctl( ARCH_SET_GS, teb );
#else
# error Please define setting %gs for your architecture
#endif
2266 2267 2268 2269 2270

    ss.ss_sp    = (char *)teb + teb_size;
    ss.ss_size  = signal_stack_size;
    ss.ss_flags = 0;
    if (sigaltstack(&ss, NULL) == -1) perror( "sigaltstack" );
2271 2272 2273 2274 2275 2276
}

/**********************************************************************
 *		signal_init_process
 */
void signal_init_process(void)
2277
{
2278 2279 2280
    struct sigaction sig_act;

    sig_act.sa_mask = server_block_set;
2281
    sig_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296

    sig_act.sa_sigaction = int_handler;
    if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
    sig_act.sa_sigaction = fpe_handler;
    if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
    sig_act.sa_sigaction = abrt_handler;
    if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
    sig_act.sa_sigaction = quit_handler;
    if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
    sig_act.sa_sigaction = usr1_handler;
    if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;

    sig_act.sa_sigaction = segv_handler;
    if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
    if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
2297
#ifdef SIGBUS
2298
    if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
2299
#endif
2300

2301
#ifdef SIGTRAP
2302 2303
    sig_act.sa_sigaction = trap_handler;
    if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
2304
#endif
2305
    return;
2306 2307 2308

 error:
    perror("sigaction");
2309
    exit(1);
2310 2311 2312
}


2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
/**********************************************************************
 *              RtlAddFunctionTable   (NTDLL.@)
 */
BOOLEAN CDECL RtlAddFunctionTable( RUNTIME_FUNCTION *table, DWORD count, DWORD64 addr )
{
    FIXME( "%p %u %lx: stub\n", table, count, addr );
    return FALSE;
}


/**********************************************************************
 *              RtlDeleteFunctionTable   (NTDLL.@)
 */
BOOLEAN CDECL RtlDeleteFunctionTable( RUNTIME_FUNCTION *table )
{
    FIXME( "%p: stub\n", table );
    return FALSE;
}


2333 2334 2335
/**********************************************************************
 *              RtlLookupFunctionEntry   (NTDLL.@)
 */
2336
PRUNTIME_FUNCTION WINAPI RtlLookupFunctionEntry( ULONG64 pc, ULONG64 *base, UNWIND_HISTORY_TABLE *table )
2337
{
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
    LDR_MODULE *module;
    RUNTIME_FUNCTION *func;
    ULONG size;

    /* FIXME: should use the history table to make things faster */

    if (LdrFindEntryForAddress( (void *)pc, &module ))
    {
        WARN( "module not found for %lx\n", pc );
        return NULL;
    }
    if (!(func = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
                                               IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )))
    {
        WARN( "no exception table found in module %p pc %lx\n", module->BaseAddress, pc );
        return NULL;
    }
    func = find_function_info( pc, module->BaseAddress, func, size );
    if (func) *base = (ULONG64)module->BaseAddress;
    return func;
2358 2359
}

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
static ULONG64 get_int_reg( CONTEXT *context, int reg )
{
    return *(&context->Rax + reg);
}

static void set_int_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, ULONG64 val )
{
    *(&context->Rax + reg) = val;
    if (ctx_ptr) ctx_ptr->u2.IntegerContext[reg] = &context->Rax + reg;
}

static void set_float_reg( CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr, int reg, M128A val )
{
    *(&context->u.s.Xmm0 + reg) = val;
    if (ctx_ptr) ctx_ptr->u1.FloatingContext[reg] = &context->u.s.Xmm0 + reg;
}

static int get_opcode_size( struct opcode op )
{
    switch (op.code)
    {
    case UWOP_ALLOC_LARGE:
        return 2 + (op.info != 0);
    case UWOP_SAVE_NONVOL:
    case UWOP_SAVE_XMM128:
        return 2;
    case UWOP_SAVE_NONVOL_FAR:
    case UWOP_SAVE_XMM128_FAR:
        return 3;
    default:
        return 1;
    }
}
2393

2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
static BOOL is_inside_epilog( BYTE *pc )
{
    /* add or lea must be the first instruction, and it must have a rex.W prefix */
    if ((pc[0] & 0xf8) == 0x48)
    {
        switch (pc[1])
        {
        case 0x81: /* add $nnnn,%rsp */
            if (pc[0] == 0x48 && pc[2] == 0xc4)
            {
                pc += 7;
                break;
            }
            return FALSE;
        case 0x83: /* add $n,%rsp */
            if (pc[0] == 0x48 && pc[2] == 0xc4)
            {
                pc += 4;
                break;
            }
            return FALSE;
        case 0x8d: /* lea n(reg),%rsp */
            if (pc[0] & 0x06) return FALSE;  /* rex.RX must be cleared */
            if (((pc[2] >> 3) & 7) != 4) return FALSE;  /* dest reg mus be %rsp */
            if ((pc[2] & 7) == 4) return FALSE;  /* no SIB byte allowed */
            if ((pc[2] >> 6) == 1)  /* 8-bit offset */
            {
                pc += 4;
                break;
            }
            if ((pc[2] >> 6) == 2)  /* 32-bit offset */
            {
                pc += 7;
                break;
            }
            return FALSE;
        }
    }

    /* now check for various pop instructions */

    for (;;)
    {
        BYTE rex = 0;

        if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f;  /* rex prefix */

        switch (*pc)
        {
        case 0x58: /* pop %rax/%r8 */
        case 0x59: /* pop %rcx/%r9 */
        case 0x5a: /* pop %rdx/%r10 */
        case 0x5b: /* pop %rbx/%r11 */
        case 0x5c: /* pop %rsp/%r12 */
        case 0x5d: /* pop %rbp/%r13 */
        case 0x5e: /* pop %rsi/%r14 */
        case 0x5f: /* pop %rdi/%r15 */
            pc++;
            continue;
        case 0xc2: /* ret $nn */
        case 0xc3: /* ret */
            return TRUE;
        /* FIXME: add various jump instructions */
        }
        return FALSE;
    }
}

/* execute a function epilog, which must have been validated with is_inside_epilog() */
static void interpret_epilog( BYTE *pc, CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
{
    for (;;)
    {
        BYTE rex = 0;

        if ((*pc & 0xf0) == 0x40) rex = *pc++ & 0x0f;  /* rex prefix */

        switch (*pc)
        {
        case 0x58: /* pop %rax/r8 */
        case 0x59: /* pop %rcx/r9 */
        case 0x5a: /* pop %rdx/r10 */
        case 0x5b: /* pop %rbx/r11 */
        case 0x5c: /* pop %rsp/r12 */
        case 0x5d: /* pop %rbp/r13 */
        case 0x5e: /* pop %rsi/r14 */
        case 0x5f: /* pop %rdi/r15 */
            set_int_reg( context, ctx_ptr, *pc - 0x58 + (rex & 1) * 8, *(ULONG64 *)context->Rsp );
            context->Rsp += sizeof(ULONG64);
            pc++;
            continue;
        case 0x81: /* add $nnnn,%rsp */
            context->Rsp += *(LONG *)(pc + 2);
            pc += 2 + sizeof(LONG);
            continue;
        case 0x83: /* add $n,%rsp */
            context->Rsp += (signed char)pc[2];
            pc += 3;
            continue;
        case 0x8d:
            if ((pc[1] >> 6) == 1)  /* lea n(reg),%rsp */
            {
                context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + (signed char)pc[2];
                pc += 3;
            }
            else  /* lea nnnn(reg),%rsp */
            {
                context->Rsp = get_int_reg( context, (pc[1] & 7) + (rex & 1) * 8 ) + *(LONG *)(pc + 2);
                pc += 2 + sizeof(LONG);
            }
            continue;
        case 0xc2: /* ret $nn */
            context->Rip = *(ULONG64 *)context->Rsp;
            context->Rsp += sizeof(ULONG64) + *(WORD *)(pc + 1);
            return;
        case 0xc3: /* ret */
            context->Rip = *(ULONG64 *)context->Rsp;
            context->Rsp += sizeof(ULONG64);
            return;
        /* FIXME: add various jump instructions */
        }
        return;
    }
}

2519 2520 2521
/**********************************************************************
 *              RtlVirtualUnwind   (NTDLL.@)
 */
2522 2523 2524 2525
PVOID WINAPI RtlVirtualUnwind( ULONG type, ULONG64 base, ULONG64 pc,
                               RUNTIME_FUNCTION *function, CONTEXT *context,
                               PVOID *data, ULONG64 *frame_ret,
                               KNONVOLATILE_CONTEXT_POINTERS *ctx_ptr )
2526
{
2527 2528 2529 2530 2531 2532
    union handler_data *handler_data;
    ULONG64 frame, off;
    struct UNWIND_INFO *info;
    unsigned int i, prolog_offset;

    TRACE( "type %x rip %lx rsp %lx\n", type, pc, context->Rsp );
2533
    if (TRACE_ON(seh)) dump_unwind_info( base, function );
2534

2535
    frame = *frame_ret = context->Rsp;
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
    for (;;)
    {
        info = (struct UNWIND_INFO *)((char *)base + function->UnwindData);
        handler_data = (union handler_data *)&info->opcodes[(info->count + 1) & ~1];

        if (info->version != 1)
        {
            FIXME( "unknown unwind info version %u at %p\n", info->version, info );
            return NULL;
        }

        if (info->frame_reg)
            frame = get_int_reg( context, info->frame_reg ) - info->frame_offset * 16;

        /* check if in prolog */
        if (pc >= base + function->BeginAddress && pc < base + function->BeginAddress + info->prolog)
        {
            prolog_offset = pc - base - function->BeginAddress;
        }
        else
        {
            prolog_offset = ~0;
2558 2559 2560 2561 2562 2563
            if (is_inside_epilog( (BYTE *)pc ))
            {
                interpret_epilog( (BYTE *)pc, context, ctx_ptr );
                *frame_ret = frame;
                return NULL;
            }
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
        }

        for (i = 0; i < info->count; i += get_opcode_size(info->opcodes[i]))
        {
            if (prolog_offset < info->opcodes[i].offset) continue; /* skip it */

            switch (info->opcodes[i].code)
            {
            case UWOP_PUSH_NONVOL:  /* pushq %reg */
                set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)context->Rsp );
                context->Rsp += sizeof(ULONG64);
                break;
            case UWOP_ALLOC_LARGE:  /* subq $nn,%rsp */
                if (info->opcodes[i].info) context->Rsp += *(DWORD *)&info->opcodes[i+1];
                else context->Rsp += *(USHORT *)&info->opcodes[i+1] * 8;
                break;
            case UWOP_ALLOC_SMALL:  /* subq $n,%rsp */
                context->Rsp += (info->opcodes[i].info + 1) * 8;
                break;
            case UWOP_SET_FPREG:  /* leaq nn(%rsp),%framereg */
2584
                context->Rsp = *frame_ret = frame;
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 2619 2620 2621 2622 2623
                break;
            case UWOP_SAVE_NONVOL:  /* movq %reg,n(%rsp) */
                off = frame + *(USHORT *)&info->opcodes[i+1] * 8;
                set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)off );
                break;
            case UWOP_SAVE_NONVOL_FAR:  /* movq %reg,nn(%rsp) */
                off = frame + *(DWORD *)&info->opcodes[i+1];
                set_int_reg( context, ctx_ptr, info->opcodes[i].info, *(ULONG64 *)off );
                break;
            case UWOP_SAVE_XMM128:  /* movaps %xmmreg,n(%rsp) */
                off = frame + *(USHORT *)&info->opcodes[i+1] * 16;
                set_float_reg( context, ctx_ptr, info->opcodes[i].info, *(M128A *)off );
                break;
            case UWOP_SAVE_XMM128_FAR:  /* movaps %xmmreg,nn(%rsp) */
                off = frame + *(DWORD *)&info->opcodes[i+1];
                set_float_reg( context, ctx_ptr, info->opcodes[i].info, *(M128A *)off );
                break;
            case UWOP_PUSH_MACHFRAME:
                FIXME( "PUSH_MACHFRAME %u\n", info->opcodes[i].info );
                break;
            default:
                FIXME( "unknown code %u\n", info->opcodes[i].code );
                break;
            }
        }

        if (!(info->flags & UNW_FLAG_CHAININFO)) break;
        function = &handler_data->chain;  /* restart with the chained info */
    }

    /* now pop return address */
    context->Rip = *(ULONG64 *)context->Rsp;
    context->Rsp += sizeof(ULONG64);

    if (!(info->flags & type)) return NULL;  /* no matching handler */
    if (prolog_offset != ~0) return NULL;  /* inside prolog */

    *data = &handler_data->handler + 1;
    return (char *)base + handler_data->handler;
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 2650 2651 2652 2653 2654 2655 2656 2657
/**********************************************************************
 *           call_unwind_handler
 *
 * Call a single unwind handler.
 * FIXME: Handle nested exceptions.
 */
static void call_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch )
{
    DWORD res;

    dispatch->ControlPc = dispatch->ContextRecord->Rip;

    TRACE( "calling handler %p (rec=%p, frame=0x%lx context=%p, dispatch=%p)\n",
         dispatch->LanguageHandler, rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
    res = dispatch->LanguageHandler( rec, dispatch->EstablisherFrame, dispatch->ContextRecord, dispatch );
    TRACE( "handler %p returned %x\n", dispatch->LanguageHandler, res );

    switch (res)
    {
    case ExceptionContinueSearch:
        break;
    case ExceptionCollidedUnwind:
        FIXME( "ExceptionCollidedUnwind not supported yet\n" );
        break;
    default:
        raise_status( STATUS_INVALID_DISPOSITION, rec );
        break;
    }
}


2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
/**********************************************************************
 *           call_teb_unwind_handler
 *
 * Call a single unwind handler from the TEB chain.
 * FIXME: Handle nested exceptions.
 */
static void call_teb_unwind_handler( EXCEPTION_RECORD *rec, DISPATCHER_CONTEXT *dispatch,
                                     EXCEPTION_REGISTRATION_RECORD *teb_frame )
{
    EXCEPTION_REGISTRATION_RECORD *dispatcher;
    DWORD res;

    TRACE( "calling TEB handler %p (rec=%p, frame=%p context=%p, dispatcher=%p)\n",
           teb_frame->Handler, rec, teb_frame, dispatch->ContextRecord, &dispatcher );
    res = teb_frame->Handler( rec, teb_frame, dispatch->ContextRecord, &dispatcher );
    TRACE( "handler at %p returned %u\n", teb_frame->Handler, res );

    switch (res)
    {
    case ExceptionContinueSearch:
        break;
    case ExceptionCollidedUnwind:
        FIXME( "ExceptionCollidedUnwind not supported yet\n" );
        break;
    default:
        raise_status( STATUS_INVALID_DISPOSITION, rec );
        break;
    }
}


2689
/*******************************************************************
2690
 *		RtlUnwindEx (NTDLL.@)
2691
 */
2692
void WINAPI RtlUnwindEx( ULONG64 end_frame, ULONG64 target_ip, EXCEPTION_RECORD *rec,
2693
                         ULONG64 retval, CONTEXT *orig_context, UNWIND_HISTORY_TABLE *table )
2694
{
2695
    EXCEPTION_REGISTRATION_RECORD *teb_frame = NtCurrentTeb()->Tib.ExceptionList;
2696
    EXCEPTION_RECORD record;
2697
    RUNTIME_FUNCTION *dir;
2698
    DISPATCHER_CONTEXT dispatch;
2699
    CONTEXT context, new_context;
2700
    LDR_MODULE *module;
2701
    NTSTATUS status;
2702
    DWORD size;
2703 2704

    /* build an exception record, if we do not have one */
2705
    if (!rec)
2706 2707 2708 2709
    {
        record.ExceptionCode    = STATUS_UNWIND;
        record.ExceptionFlags   = 0;
        record.ExceptionRecord  = NULL;
2710
        record.ExceptionAddress = (void *)orig_context->Rip;
2711
        record.NumberParameters = 0;
2712
        rec = &record;
2713 2714
    }

2715 2716
    rec->ExceptionFlags |= EH_UNWINDING | (end_frame ? 0 : EH_EXIT_UNWIND);

2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
    TRACE( "code=%x flags=%x end_frame=%lx target_ip=%lx rip=%016lx\n",
           rec->ExceptionCode, rec->ExceptionFlags, end_frame, target_ip, orig_context->Rip );
    TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
          orig_context->Rax, orig_context->Rbx, orig_context->Rcx, orig_context->Rdx );
    TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
          orig_context->Rsi, orig_context->Rdi, orig_context->Rbp, orig_context->Rsp );
    TRACE("  r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n",
          orig_context->R8, orig_context->R9, orig_context->R10, orig_context->R11 );
    TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
          orig_context->R12, orig_context->R13, orig_context->R14, orig_context->R15 );
2727

2728 2729 2730 2731 2732 2733 2734
    context = *orig_context;
    dispatch.EstablisherFrame = context.Rsp;
    dispatch.TargetIp         = target_ip;
    dispatch.ContextRecord    = &context;
    dispatch.HistoryTable     = table;

    while (dispatch.EstablisherFrame != end_frame)
2735
    {
2736 2737
        new_context = context;

2738 2739
        /* FIXME: should use the history table to make things faster */

2740 2741 2742 2743 2744 2745
        dir = NULL;
        module = NULL;
        dispatch.ImageBase = 0;
        dispatch.ScopeIndex = 0; /* FIXME */

        if (!LdrFindEntryForAddress( (void *)context.Rip, &module ))
2746
        {
2747 2748 2749 2750 2751 2752 2753 2754 2755
            if (!(dir = RtlImageDirectoryEntryToData( module->BaseAddress, TRUE,
                                                      IMAGE_DIRECTORY_ENTRY_EXCEPTION, &size )) &&
                !(module->Flags & LDR_WINE_INTERNAL))
            {
                ERR( "module %s doesn't contain exception data, can't unwind exception\n",
                     debugstr_w(module->BaseDllName.Buffer) );
                raise_status( STATUS_BAD_FUNCTION_TABLE, rec );
            }
            dispatch.ImageBase = (ULONG64)module->BaseAddress;
2756
        }
2757 2758

        if (!dir)
2759
        {
2760 2761 2762 2763
            struct dwarf_eh_bases bases;
            const struct dwarf_fde *fde = _Unwind_Find_FDE( (void *)(context.Rip - 1), &bases );
            if (!fde)
            {
2764 2765 2766 2767
                /* assume leaf function */
                context.Rip = *(ULONG64 *)context.Rsp;
                context.Rsp += sizeof(ULONG64);
                continue;
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
            }
            dispatch.FunctionEntry = NULL;
            status = dwarf_virtual_unwind( context.Rip, &dispatch.EstablisherFrame, &new_context, fde,
                                           &bases, &dispatch.LanguageHandler, &dispatch.HandlerData );
            if (status != STATUS_SUCCESS) raise_status( status, rec );
            if (dispatch.LanguageHandler && !module)
            {
                FIXME( "calling personality routine in system library not supported yet\n" );
                dispatch.LanguageHandler = NULL;
            }
2778
        }
2779
        else
2780
        {
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
            if (!(dispatch.FunctionEntry = find_function_info( context.Rip, module->BaseAddress,
                                                               dir, size )))
            {
                /* leaf function */
                context.Rip = *(ULONG64 *)context.Rsp;
                context.Rsp += sizeof(ULONG64);
                continue;
            }
            dispatch.LanguageHandler = RtlVirtualUnwind( UNW_FLAG_UHANDLER, dispatch.ImageBase,
                                                         context.Rip, dispatch.FunctionEntry,
                                                         &new_context, &dispatch.HandlerData,
                                                         &dispatch.EstablisherFrame, NULL );
2793 2794
        }

2795
        if (!dispatch.EstablisherFrame) break;
2796

2797 2798 2799 2800 2801 2802 2803 2804
        if (is_inside_signal_stack( (void *)dispatch.EstablisherFrame ))
        {
            TRACE( "frame %lx is inside signal stack (%p-%p)\n", dispatch.EstablisherFrame,
                   get_signal_stack(), (char *)get_signal_stack() + signal_stack_size );
            context = new_context;
            continue;
        }

2805 2806 2807
        if ((dispatch.EstablisherFrame & 7) ||
            dispatch.EstablisherFrame < (ULONG64)NtCurrentTeb()->Tib.StackLimit ||
            dispatch.EstablisherFrame > (ULONG64)NtCurrentTeb()->Tib.StackBase)
2808
        {
2809 2810 2811 2812
            ERR( "invalid frame %lx (%p-%p)\n", dispatch.EstablisherFrame,
                 NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase );
            rec->ExceptionFlags |= EH_STACK_INVALID;
            break;
2813 2814
        }

2815
        if (dispatch.LanguageHandler)
2816
        {
2817
            if (end_frame && (dispatch.EstablisherFrame > end_frame))
2818
            {
2819 2820
                ERR( "invalid end frame %lx/%lx\n", dispatch.EstablisherFrame, end_frame );
                raise_status( STATUS_INVALID_UNWIND_TARGET, rec );
2821
            }
2822
            call_unwind_handler( rec, &dispatch );
2823
        }
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
        else  /* hack: call builtin handlers registered in the tib list */
        {
            while ((ULONG64)teb_frame < new_context.Rsp && (ULONG64)teb_frame < end_frame)
            {
                TRACE( "found builtin frame %p handler %p\n", teb_frame, teb_frame->Handler );
                dispatch.EstablisherFrame = (ULONG64)teb_frame;
                call_teb_unwind_handler( rec, &dispatch, teb_frame );
                teb_frame = __wine_pop_frame( teb_frame );
            }
            if ((ULONG64)teb_frame == end_frame && end_frame < new_context.Rsp) break;
            dispatch.EstablisherFrame = new_context.Rsp;
        }
2836 2837

        context = new_context;
2838
    }
2839 2840 2841 2842
    context.Rax = retval;
    context.Rip = target_ip;
    TRACE( "returning to %lx stack %lx\n", context.Rip, context.Rsp );
    set_cpu_context( &context );
2843
}
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853


/*******************************************************************
 *		RtlUnwind (NTDLL.@)
 */
void WINAPI __regs_RtlUnwind( ULONG64 frame, ULONG64 target_ip, EXCEPTION_RECORD *rec,
                              ULONG64 retval, CONTEXT *context )
{
    RtlUnwindEx( frame, target_ip, rec, retval, context, NULL );
}
2854 2855 2856
DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )


2857 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 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
/*******************************************************************
 *		__C_specific_handler (NTDLL.@)
 */
EXCEPTION_DISPOSITION WINAPI __C_specific_handler( EXCEPTION_RECORD *rec,
                                                   ULONG64 frame,
                                                   CONTEXT *context,
                                                   struct _DISPATCHER_CONTEXT *dispatch )
{
    SCOPE_TABLE *table = dispatch->HandlerData;
    ULONG i;

    TRACE( "%p %lx %p %p\n", rec, frame, context, dispatch );
    if (TRACE_ON(seh)) dump_scope_table( dispatch->ImageBase, table );

    if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))  /* FIXME */
        return ExceptionContinueSearch;

    for (i = 0; i < table->Count; i++)
    {
        if (context->Rip >= dispatch->ImageBase + table->ScopeRecord[i].BeginAddress &&
            context->Rip < dispatch->ImageBase + table->ScopeRecord[i].EndAddress)
        {
            if (!table->ScopeRecord[i].JumpTarget) continue;
            if (table->ScopeRecord[i].HandlerAddress != EXCEPTION_EXECUTE_HANDLER)
            {
                EXCEPTION_POINTERS ptrs;
                PC_LANGUAGE_EXCEPTION_HANDLER filter;

                filter = (PC_LANGUAGE_EXCEPTION_HANDLER)(dispatch->ImageBase + table->ScopeRecord[i].HandlerAddress);
                ptrs.ExceptionRecord = rec;
                ptrs.ContextRecord = context;
                TRACE( "calling filter %p ptrs %p frame %lx\n", filter, &ptrs, frame );
                switch (filter( &ptrs, frame ))
                {
                case EXCEPTION_EXECUTE_HANDLER:
                    break;
                case EXCEPTION_CONTINUE_SEARCH:
                    continue;
                case EXCEPTION_CONTINUE_EXECUTION:
                    return ExceptionContinueExecution;
                }
            }
            TRACE( "unwinding to target %lx\n", dispatch->ImageBase + table->ScopeRecord[i].JumpTarget );
            RtlUnwindEx( frame, dispatch->ImageBase + table->ScopeRecord[i].JumpTarget,
                         rec, 0, context, dispatch->HistoryTable );
        }
    }
    return ExceptionContinueSearch;
}


2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
/*******************************************************************
 *		NtRaiseException (NTDLL.@)
 */
NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
{
    NTSTATUS status = raise_exception( rec, context, first_chance );
    if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
    return status;
}


2919 2920 2921 2922 2923
/***********************************************************************
 *		RtlRaiseException (NTDLL.@)
 */
void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
{
2924 2925 2926 2927
    NTSTATUS status;

    rec->ExceptionAddress = (void *)context->Rip;
    status = raise_exception( rec, context, TRUE );
2928 2929 2930 2931 2932
    if (status != STATUS_SUCCESS) raise_status( status, rec );
}
DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 1 )


2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
/*************************************************************************
 *		RtlCaptureStackBackTrace (NTDLL.@)
 */
USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
{
    FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash );
    return 0;
}


2943 2944 2945 2946
/***********************************************************************
 *           call_thread_func
 */
void call_thread_func( LPTHREAD_START_ROUTINE entry, void *arg, void *frame )
2947
{
2948 2949
    ntdll_get_thread_data()->exit_frame = frame;
    __TRY
2950
    {
2951
        RtlExitUserThread( entry( arg ));
2952
    }
2953
    __EXCEPT(unhandled_exception_filter)
2954
    {
2955
        NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
2956
    }
2957 2958
    __ENDTRY
    abort();  /* should not be reached */
2959 2960
}

2961 2962 2963 2964 2965 2966
extern void DECLSPEC_NORETURN call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg );
__ASM_GLOBAL_FUNC( call_thread_entry_point,
                   "subq $8,%rsp\n\t"
                   ".cfi_adjust_cfa_offset 8\n\t"
                   "movq %rsp,%rdx\n\t"
                   "call " __ASM_NAME("call_thread_func") );
2967

2968 2969 2970 2971 2972 2973
extern void DECLSPEC_NORETURN call_thread_exit_func( int status, void (*func)(int), void *frame );
__ASM_GLOBAL_FUNC( call_thread_exit_func,
                   "subq $8,%rsp\n\t"
                   ".cfi_adjust_cfa_offset 8\n\t"
                   "movq %rdx,%rsp\n\t"
                   "call *%rsi" );
2974

2975 2976 2977 2978 2979
/***********************************************************************
 *           RtlExitUserThread  (NTDLL.@)
 */
void WINAPI RtlExitUserThread( ULONG status )
{
2980 2981
    if (!ntdll_get_thread_data()->exit_frame) exit_thread( status );
    call_thread_exit_func( status, exit_thread, ntdll_get_thread_data()->exit_frame );
2982 2983
}

2984 2985 2986 2987 2988
/***********************************************************************
 *           abort_thread
 */
void abort_thread( int status )
{
2989 2990
    if (!ntdll_get_thread_data()->exit_frame) terminate_thread( status );
    call_thread_exit_func( status, terminate_thread, ntdll_get_thread_data()->exit_frame );
2991
}
2992

2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
/**********************************************************************
 *              __wine_enter_vm86   (NTDLL.@)
 */
void __wine_enter_vm86( CONTEXT *context )
{
    MESSAGE("vm86 mode not supported on this platform\n");
}

/**********************************************************************
 *		DbgBreakPoint   (NTDLL.@)
 */
3004
__ASM_STDCALL_FUNC( DbgBreakPoint, 0, "int $3; ret")
3005 3006 3007 3008

/**********************************************************************
 *		DbgUserBreakPoint   (NTDLL.@)
 */
3009
__ASM_STDCALL_FUNC( DbgUserBreakPoint, 0, "int $3; ret")
3010 3011

#endif  /* __x86_64__ */