1 /*
2  * Unit test suite for ntdll exceptions
3  *
4  * Copyright 2005 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20 
21 #include "ntdll_test.h"
22 
23 #include <wine/exception.h>
24 
25 static void *code_mem;
26 
27 static NTSTATUS  (WINAPI *pNtGetContextThread)(HANDLE,CONTEXT*);
28 static NTSTATUS  (WINAPI *pNtSetContextThread)(HANDLE,CONTEXT*);
29 static NTSTATUS  (WINAPI *pRtlRaiseException)(EXCEPTION_RECORD *rec);
30 static PVOID     (WINAPI *pRtlUnwind)(PVOID, PVOID, PEXCEPTION_RECORD, PVOID);
31 static VOID      (WINAPI *pRtlCaptureContext)(CONTEXT*);
32 static PVOID     (WINAPI *pRtlAddVectoredExceptionHandler)(ULONG first, PVECTORED_EXCEPTION_HANDLER func);
33 static ULONG     (WINAPI *pRtlRemoveVectoredExceptionHandler)(PVOID handler);
34 static PVOID     (WINAPI *pRtlAddVectoredContinueHandler)(ULONG first, PVECTORED_EXCEPTION_HANDLER func);
35 static ULONG     (WINAPI *pRtlRemoveVectoredContinueHandler)(PVOID handler);
36 static NTSTATUS  (WINAPI *pNtReadVirtualMemory)(HANDLE, const void*, void*, SIZE_T, SIZE_T*);
37 static NTSTATUS  (WINAPI *pNtTerminateProcess)(HANDLE handle, LONG exit_code);
38 static NTSTATUS  (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
39 static NTSTATUS  (WINAPI *pNtSetInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG);
40 static BOOL      (WINAPI *pIsWow64Process)(HANDLE, PBOOL);
41 static NTSTATUS  (WINAPI *pNtClose)(HANDLE);
42 
43 #if defined(__x86_64__)
44 typedef struct
45 {
46     ULONG Count;
47     struct
48     {
49         ULONG BeginAddress;
50         ULONG EndAddress;
51         ULONG HandlerAddress;
52         ULONG JumpTarget;
53     } ScopeRecord[1];
54 } SCOPE_TABLE;
55 
56 typedef struct
57 {
58     ULONG64               ControlPc;
59     ULONG64               ImageBase;
60     PRUNTIME_FUNCTION     FunctionEntry;
61     ULONG64               EstablisherFrame;
62     ULONG64               TargetIp;
63     PCONTEXT              ContextRecord;
64     void* /*PEXCEPTION_ROUTINE*/ LanguageHandler;
65     PVOID                 HandlerData;
66     PUNWIND_HISTORY_TABLE HistoryTable;
67     ULONG                 ScopeIndex;
68 } DISPATCHER_CONTEXT;
69 
70 typedef struct _SETJMP_FLOAT128
71 {
72     unsigned __int64 DECLSPEC_ALIGN(16) Part[2];
73 } SETJMP_FLOAT128;
74 
75 typedef struct _JUMP_BUFFER
76 {
77     unsigned __int64 Frame;
78     unsigned __int64 Rbx;
79     unsigned __int64 Rsp;
80     unsigned __int64 Rbp;
81     unsigned __int64 Rsi;
82     unsigned __int64 Rdi;
83     unsigned __int64 R12;
84     unsigned __int64 R13;
85     unsigned __int64 R14;
86     unsigned __int64 R15;
87     unsigned __int64 Rip;
88     unsigned __int64 Spare;
89     SETJMP_FLOAT128  Xmm6;
90     SETJMP_FLOAT128  Xmm7;
91     SETJMP_FLOAT128  Xmm8;
92     SETJMP_FLOAT128  Xmm9;
93     SETJMP_FLOAT128  Xmm10;
94     SETJMP_FLOAT128  Xmm11;
95     SETJMP_FLOAT128  Xmm12;
96     SETJMP_FLOAT128  Xmm13;
97     SETJMP_FLOAT128  Xmm14;
98     SETJMP_FLOAT128  Xmm15;
99 } _JUMP_BUFFER;
100 
101 static BOOLEAN   (CDECL *pRtlAddFunctionTable)(RUNTIME_FUNCTION*, DWORD, DWORD64);
102 static BOOLEAN   (CDECL *pRtlDeleteFunctionTable)(RUNTIME_FUNCTION*);
103 static BOOLEAN   (CDECL *pRtlInstallFunctionTableCallback)(DWORD64, DWORD64, DWORD, PGET_RUNTIME_FUNCTION_CALLBACK, PVOID, PCWSTR);
104 static PRUNTIME_FUNCTION (WINAPI *pRtlLookupFunctionEntry)(ULONG64, ULONG64*, UNWIND_HISTORY_TABLE*);
105 static EXCEPTION_DISPOSITION (WINAPI *p__C_specific_handler)(EXCEPTION_RECORD*, ULONG64, CONTEXT*, DISPATCHER_CONTEXT*);
106 static VOID      (WINAPI *pRtlCaptureContext)(CONTEXT*);
107 static VOID      (CDECL *pRtlRestoreContext)(CONTEXT*, EXCEPTION_RECORD*);
108 static VOID      (CDECL *pRtlUnwindEx)(VOID*, VOID*, EXCEPTION_RECORD*, VOID*, CONTEXT*, UNWIND_HISTORY_TABLE*);
109 static int       (CDECL *p_setjmp)(_JUMP_BUFFER*);
110 #endif
111 
112 #ifdef __i386__
113 
114 #ifndef __WINE_WINTRNL_H
115 #define ProcessExecuteFlags 0x22
116 #define MEM_EXECUTE_OPTION_DISABLE   0x01
117 #define MEM_EXECUTE_OPTION_ENABLE    0x02
118 #define MEM_EXECUTE_OPTION_PERMANENT 0x08
119 #endif
120 
121 static int      my_argc;
122 static char**   my_argv;
123 static int      test_stage;
124 
125 static BOOL is_wow64;
126 
127 /* Test various instruction combinations that cause a protection fault on the i386,
128  * and check what the resulting exception looks like.
129  */
130 
131 static const struct exception
132 {
133     BYTE     code[18];      /* asm code */
134     BYTE     offset;        /* offset of faulting instruction */
135     BYTE     length;        /* length of faulting instruction */
136     BOOL     wow64_broken;  /* broken on Wow64, should be skipped */
137     NTSTATUS status;        /* expected status code */
138     DWORD    nb_params;     /* expected number of parameters */
139     DWORD    params[4];     /* expected parameters */
140     NTSTATUS alt_status;    /* alternative status code */
141     DWORD    alt_nb_params; /* alternative number of parameters */
142     DWORD    alt_params[4]; /* alternative parameters */
143 } exceptions[] =
144 {
145 /* 0 */
146     /* test some privileged instructions */
147     { { 0xfb, 0xc3 },  /* 0: sti; ret */
148       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
149     { { 0x6c, 0xc3 },  /* 1: insb (%dx); ret */
150       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
151     { { 0x6d, 0xc3 },  /* 2: insl (%dx); ret */
152       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
153     { { 0x6e, 0xc3 },  /* 3: outsb (%dx); ret */
154       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
155     { { 0x6f, 0xc3 },  /* 4: outsl (%dx); ret */
156       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
157 /* 5 */
158     { { 0xe4, 0x11, 0xc3 },  /* 5: inb $0x11,%al; ret */
159       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
160     { { 0xe5, 0x11, 0xc3 },  /* 6: inl $0x11,%eax; ret */
161       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
162     { { 0xe6, 0x11, 0xc3 },  /* 7: outb %al,$0x11; ret */
163       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
164     { { 0xe7, 0x11, 0xc3 },  /* 8: outl %eax,$0x11; ret */
165       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
166     { { 0xed, 0xc3 },  /* 9: inl (%dx),%eax; ret */
167       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
168 /* 10 */
169     { { 0xee, 0xc3 },  /* 10: outb %al,(%dx); ret */
170       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
171     { { 0xef, 0xc3 },  /* 11: outl %eax,(%dx); ret */
172       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
173     { { 0xf4, 0xc3 },  /* 12: hlt; ret */
174       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
175     { { 0xfa, 0xc3 },  /* 13: cli; ret */
176       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
177 
178     /* test long jump to invalid selector */
179     { { 0xea, 0, 0, 0, 0, 0, 0, 0xc3 },  /* 14: ljmp $0,$0; ret */
180       0, 7, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
181 
182 /* 15 */
183     /* test iret to invalid selector */
184     { { 0x6a, 0x00, 0x6a, 0x00, 0x6a, 0x00, 0xcf, 0x83, 0xc4, 0x0c, 0xc3 },
185       /* 15: pushl $0; pushl $0; pushl $0; iret; addl $12,%esp; ret */
186       6, 1, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
187 
188     /* test loading an invalid selector */
189     { { 0xb8, 0xef, 0xbe, 0x00, 0x00, 0x8e, 0xe8, 0xc3 },  /* 16: mov $beef,%ax; mov %ax,%gs; ret */
190       5, 2, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xbee8 } }, /* 0xbee8 or 0xffffffff */
191 
192     /* test accessing a zero selector (%es broken on Wow64) */
193     { { 0x06, 0x31, 0xc0, 0x8e, 0xc0, 0x26, 0xa1, 0, 0, 0, 0, 0x07, 0xc3 },
194        /* push %es; xor %eax,%eax; mov %ax,%es; mov %es:(0),%ax; pop %es; ret */
195       5, 6, TRUE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
196     { { 0x0f, 0xa8, 0x31, 0xc0, 0x8e, 0xe8, 0x65, 0xa1, 0, 0, 0, 0, 0x0f, 0xa9, 0xc3 },
197       /* push %gs; xor %eax,%eax; mov %ax,%gs; mov %gs:(0),%ax; pop %gs; ret */
198       6, 6, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
199 
200     /* test moving %cs -> %ss */
201     { { 0x0e, 0x17, 0x58, 0xc3 },  /* pushl %cs; popl %ss; popl %eax; ret */
202       1, 1, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
203 
204 /* 20 */
205     /* test overlong instruction (limit is 15 bytes, 5 on Win7) */
206     { { 0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0xfa,0xc3 },
207       0, 16, TRUE, STATUS_ILLEGAL_INSTRUCTION, 0, { 0 },
208       STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
209     { { 0x64,0x64,0x64,0x64,0xfa,0xc3 },
210       0, 5, TRUE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
211 
212     /* test invalid interrupt */
213     { { 0xcd, 0xff, 0xc3 },   /* int $0xff; ret */
214       0, 2, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
215 
216     /* test moves to/from Crx */
217     { { 0x0f, 0x20, 0xc0, 0xc3 },  /* movl %cr0,%eax; ret */
218       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
219     { { 0x0f, 0x20, 0xe0, 0xc3 },  /* movl %cr4,%eax; ret */
220       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
221 /* 25 */
222     { { 0x0f, 0x22, 0xc0, 0xc3 },  /* movl %eax,%cr0; ret */
223       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
224     { { 0x0f, 0x22, 0xe0, 0xc3 },  /* movl %eax,%cr4; ret */
225       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
226 
227     /* test moves to/from Drx */
228     { { 0x0f, 0x21, 0xc0, 0xc3 },  /* movl %dr0,%eax; ret */
229       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
230     { { 0x0f, 0x21, 0xc8, 0xc3 },  /* movl %dr1,%eax; ret */
231       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
232     { { 0x0f, 0x21, 0xf8, 0xc3 },  /* movl %dr7,%eax; ret */
233       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
234 /* 30 */
235     { { 0x0f, 0x23, 0xc0, 0xc3 },  /* movl %eax,%dr0; ret */
236       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
237     { { 0x0f, 0x23, 0xc8, 0xc3 },  /* movl %eax,%dr1; ret */
238       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
239     { { 0x0f, 0x23, 0xf8, 0xc3 },  /* movl %eax,%dr7; ret */
240       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
241 
242     /* test memory reads */
243     { { 0xa1, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffc,%eax; ret */
244       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffc } },
245     { { 0xa1, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffd,%eax; ret */
246       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffd } },
247 /* 35 */
248     { { 0xa1, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffe,%eax; ret */
249       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffe } },
250     { { 0xa1, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xffffffff,%eax; ret */
251       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
252 
253     /* test memory writes */
254     { { 0xa3, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffc; ret */
255       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffc } },
256     { { 0xa3, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffd; ret */
257       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffd } },
258     { { 0xa3, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffe; ret */
259       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffe } },
260 /* 40 */
261     { { 0xa3, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xffffffff; ret */
262       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xffffffff } },
263 
264     /* test exception with cleared %ds and %es (broken on Wow64) */
265     { { 0x1e, 0x06, 0x31, 0xc0, 0x8e, 0xd8, 0x8e, 0xc0, 0xfa, 0x07, 0x1f, 0xc3 },
266           /* push %ds; push %es; xorl %eax,%eax; mov %ax,%ds; mov %ax,%es; cli; pop %es; pop %ds; ret */
267       8, 1, TRUE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
268 
269     { { 0xf1, 0x90, 0xc3 },  /* icebp; nop; ret */
270       1, 1, FALSE, STATUS_SINGLE_STEP, 0 },
271     { { 0xb8, 0xb8, 0xb8, 0xb8, 0xb8,          /* mov $0xb8b8b8b8, %eax */
272         0xb9, 0xb9, 0xb9, 0xb9, 0xb9,          /* mov $0xb9b9b9b9, %ecx */
273         0xba, 0xba, 0xba, 0xba, 0xba,          /* mov $0xbabababa, %edx */
274         0xcd, 0x2d, 0xc3 },                    /* int $0x2d; ret */
275       17, 0, FALSE, STATUS_BREAKPOINT, 3, { 0xb8b8b8b8, 0xb9b9b9b9, 0xbabababa } },
276 };
277 
278 static int got_exception;
279 static BOOL have_vectored_api;
280 
281 static void run_exception_test(void *handler, const void* context,
282                                const void *code, unsigned int code_size,
283                                DWORD access)
284 {
285     struct {
286         EXCEPTION_REGISTRATION_RECORD frame;
287         const void *context;
288     } exc_frame;
289     void (*func)(void) = code_mem;
290     DWORD oldaccess, oldaccess2;
291 
292     exc_frame.frame.Handler = handler;
293     exc_frame.frame.Prev = NtCurrentTeb()->Tib.ExceptionList;
294     exc_frame.context = context;
295 
296     memcpy(code_mem, code, code_size);
297     if(access)
298         VirtualProtect(code_mem, code_size, access, &oldaccess);
299 
300     NtCurrentTeb()->Tib.ExceptionList = &exc_frame.frame;
301     func();
302     NtCurrentTeb()->Tib.ExceptionList = exc_frame.frame.Prev;
303 
304     if(access)
305         VirtualProtect(code_mem, code_size, oldaccess, &oldaccess2);
306 }
307 
308 static LONG CALLBACK rtlraiseexception_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
309 {
310     PCONTEXT context = ExceptionInfo->ContextRecord;
311     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
312     trace("vect. handler %08x addr:%p context.Eip:%x\n", rec->ExceptionCode,
313           rec->ExceptionAddress, context->Eip);
314 
315     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
316        rec->ExceptionAddress, (char *)code_mem + 0xb);
317 
318     if (NtCurrentTeb()->Peb->BeingDebugged)
319         ok((void *)context->Eax == pRtlRaiseException ||
320            broken( is_wow64 && context->Eax == 0xf00f00f1 ), /* broken on vista */
321            "debugger managed to modify Eax to %x should be %p\n",
322            context->Eax, pRtlRaiseException);
323 
324     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
325      * even if raised by RtlRaiseException
326      */
327     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
328     {
329         ok(context->Eip == (DWORD)code_mem + 0xa ||
330            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
331            "Eip at %x instead of %x or %x\n", context->Eip,
332            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
333     }
334     else
335     {
336         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
337            context->Eip, (DWORD)code_mem + 0xb);
338     }
339 
340     /* test if context change is preserved from vectored handler to stack handlers */
341     context->Eax = 0xf00f00f0;
342     return EXCEPTION_CONTINUE_SEARCH;
343 }
344 
345 static DWORD rtlraiseexception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
346                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
347 {
348     trace( "exception: %08x flags:%x addr:%p context: Eip:%x\n",
349            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Eip );
350 
351     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
352        rec->ExceptionAddress, (char *)code_mem + 0xb);
353 
354     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
355      * even if raised by RtlRaiseException
356      */
357     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
358     {
359         ok(context->Eip == (DWORD)code_mem + 0xa ||
360            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
361            "Eip at %x instead of %x or %x\n", context->Eip,
362            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
363     }
364     else
365     {
366         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
367            context->Eip, (DWORD)code_mem + 0xb);
368     }
369 
370     if(have_vectored_api)
371         ok(context->Eax == 0xf00f00f0, "Eax is %x, should have been set to 0xf00f00f0 in vectored handler\n",
372            context->Eax);
373 
374     /* give the debugger a chance to examine the state a second time */
375     /* without the exception handler changing Eip */
376     if (test_stage == 2)
377         return ExceptionContinueSearch;
378 
379     /* Eip in context is decreased by 1
380      * Increase it again, else execution will continue in the middle of an instruction */
381     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT && (context->Eip == (DWORD)code_mem + 0xa))
382         context->Eip += 1;
383     return ExceptionContinueExecution;
384 }
385 
386 
387 static const BYTE call_one_arg_code[] = {
388         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
389         0x50,                   /* push %eax */
390         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
391         0xff, 0xd0,             /* call *%eax */
392         0x90,                   /* nop */
393         0x90,                   /* nop */
394         0x90,                   /* nop */
395         0x90,                   /* nop */
396         0xc3,                   /* ret */
397 };
398 
399 
400 static void run_rtlraiseexception_test(DWORD exceptioncode)
401 {
402     EXCEPTION_REGISTRATION_RECORD frame;
403     EXCEPTION_RECORD record;
404     PVOID vectored_handler = NULL;
405 
406     void (*func)(void* function, EXCEPTION_RECORD* record) = code_mem;
407 
408     record.ExceptionCode = exceptioncode;
409     record.ExceptionFlags = 0;
410     record.ExceptionRecord = NULL;
411     record.ExceptionAddress = NULL; /* does not matter, copied return address */
412     record.NumberParameters = 0;
413 
414     frame.Handler = rtlraiseexception_handler;
415     frame.Prev = NtCurrentTeb()->Tib.ExceptionList;
416 
417     memcpy(code_mem, call_one_arg_code, sizeof(call_one_arg_code));
418 
419     NtCurrentTeb()->Tib.ExceptionList = &frame;
420     if (have_vectored_api)
421     {
422         vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &rtlraiseexception_vectored_handler);
423         ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
424     }
425 
426     func(pRtlRaiseException, &record);
427     ok( record.ExceptionAddress == (char *)code_mem + 0x0b,
428         "address set to %p instead of %p\n", record.ExceptionAddress, (char *)code_mem + 0x0b );
429 
430     if (have_vectored_api)
431         pRtlRemoveVectoredExceptionHandler(vectored_handler);
432     NtCurrentTeb()->Tib.ExceptionList = frame.Prev;
433 }
434 
435 static void test_rtlraiseexception(void)
436 {
437     if (!pRtlRaiseException)
438     {
439         skip("RtlRaiseException not found\n");
440         return;
441     }
442 
443     /* test without debugger */
444     run_rtlraiseexception_test(0x12345);
445     run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
446     run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
447 }
448 
449 static DWORD unwind_expected_eax;
450 
451 static DWORD unwind_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
452                              CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
453 {
454     trace("exception: %08x flags:%x addr:%p context: Eip:%x\n",
455           rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Eip);
456 
457     ok(rec->ExceptionCode == STATUS_UNWIND, "ExceptionCode is %08x instead of %08x\n",
458        rec->ExceptionCode, STATUS_UNWIND);
459     ok(rec->ExceptionAddress == (char *)code_mem + 0x22, "ExceptionAddress at %p instead of %p\n",
460        rec->ExceptionAddress, (char *)code_mem + 0x22);
461     ok(context->Eax == unwind_expected_eax, "context->Eax is %08x instead of %08x\n",
462        context->Eax, unwind_expected_eax);
463 
464     context->Eax += 1;
465     return ExceptionContinueSearch;
466 }
467 
468 static const BYTE call_unwind_code[] = {
469     0x55,                           /* push %ebp */
470     0x53,                           /* push %ebx */
471     0x56,                           /* push %esi */
472     0x57,                           /* push %edi */
473     0xe8, 0x00, 0x00, 0x00, 0x00,   /* call 0 */
474     0x58,                           /* 0: pop %eax */
475     0x05, 0x1e, 0x00, 0x00, 0x00,   /* add $0x1e,%eax */
476     0xff, 0x74, 0x24, 0x20,         /* push 0x20(%esp) */
477     0xff, 0x74, 0x24, 0x20,         /* push 0x20(%esp) */
478     0x50,                           /* push %eax */
479     0xff, 0x74, 0x24, 0x24,         /* push 0x24(%esp) */
480     0x8B, 0x44, 0x24, 0x24,         /* mov 0x24(%esp),%eax */
481     0xff, 0xd0,                     /* call *%eax */
482     0x5f,                           /* pop %edi */
483     0x5e,                           /* pop %esi */
484     0x5b,                           /* pop %ebx */
485     0x5d,                           /* pop %ebp */
486     0xc3,                           /* ret */
487     0xcc,                           /* int $3 */
488 };
489 
490 static void test_unwind(void)
491 {
492     EXCEPTION_REGISTRATION_RECORD frames[2], *frame2 = &frames[0], *frame1 = &frames[1];
493     DWORD (*func)(void* function, EXCEPTION_REGISTRATION_RECORD *pEndFrame, EXCEPTION_RECORD* record, DWORD retval) = code_mem;
494     DWORD retval;
495 
496     memcpy(code_mem, call_unwind_code, sizeof(call_unwind_code));
497 
498     /* add first unwind handler */
499     frame1->Handler = unwind_handler;
500     frame1->Prev = NtCurrentTeb()->Tib.ExceptionList;
501     NtCurrentTeb()->Tib.ExceptionList = frame1;
502 
503     /* add second unwind handler */
504     frame2->Handler = unwind_handler;
505     frame2->Prev = NtCurrentTeb()->Tib.ExceptionList;
506     NtCurrentTeb()->Tib.ExceptionList = frame2;
507 
508     /* test unwind to current frame */
509     unwind_expected_eax = 0xDEAD0000;
510     retval = func(pRtlUnwind, frame2, NULL, 0xDEAD0000);
511     ok(retval == 0xDEAD0000, "RtlUnwind returned eax %08x instead of %08x\n", retval, 0xDEAD0000);
512     ok(NtCurrentTeb()->Tib.ExceptionList == frame2, "Exception record points to %p instead of %p\n",
513        NtCurrentTeb()->Tib.ExceptionList, frame2);
514 
515     /* unwind to frame1 */
516     unwind_expected_eax = 0xDEAD0000;
517     retval = func(pRtlUnwind, frame1, NULL, 0xDEAD0000);
518     ok(retval == 0xDEAD0001, "RtlUnwind returned eax %08x instead of %08x\n", retval, 0xDEAD0001);
519     ok(NtCurrentTeb()->Tib.ExceptionList == frame1, "Exception record points to %p instead of %p\n",
520        NtCurrentTeb()->Tib.ExceptionList, frame1);
521 
522     /* restore original handler */
523     NtCurrentTeb()->Tib.ExceptionList = frame1->Prev;
524 }
525 
526 static DWORD handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
527                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
528 {
529     const struct exception *except = *(const struct exception **)(frame + 1);
530     unsigned int i, parameter_count, entry = except - exceptions;
531 
532     got_exception++;
533     trace( "exception %u: %x flags:%x addr:%p\n",
534            entry, rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
535 
536     ok( rec->ExceptionCode == except->status ||
537         (except->alt_status != 0 && rec->ExceptionCode == except->alt_status),
538         "%u: Wrong exception code %x/%x\n", entry, rec->ExceptionCode, except->status );
539     ok( context->Eip == (DWORD_PTR)code_mem + except->offset,
540         "%u: Unexpected eip %#x/%#lx\n", entry,
541         context->Eip, (DWORD_PTR)code_mem + except->offset );
542     ok( rec->ExceptionAddress == (char*)context->Eip ||
543         (rec->ExceptionCode == STATUS_BREAKPOINT && rec->ExceptionAddress == (char*)context->Eip + 1),
544         "%u: Unexpected exception address %p/%p\n", entry,
545         rec->ExceptionAddress, (char*)context->Eip );
546 
547     if (except->status == STATUS_BREAKPOINT && is_wow64)
548         parameter_count = 1;
549     else if (except->alt_status == 0 || rec->ExceptionCode != except->alt_status)
550         parameter_count = except->nb_params;
551     else
552         parameter_count = except->alt_nb_params;
553 
554     ok( rec->NumberParameters == parameter_count,
555         "%u: Unexpected parameter count %u/%u\n", entry, rec->NumberParameters, parameter_count );
556 
557     /* Most CPUs (except Intel Core apparently) report a segment limit violation */
558     /* instead of page faults for accesses beyond 0xffffffff */
559     if (except->nb_params == 2 && except->params[1] >= 0xfffffffd)
560     {
561         if (rec->ExceptionInformation[0] == 0 && rec->ExceptionInformation[1] == 0xffffffff)
562             goto skip_params;
563     }
564 
565     /* Seems that both 0xbee8 and 0xfffffffff can be returned in windows */
566     if (except->nb_params == 2 && rec->NumberParameters == 2
567         && except->params[1] == 0xbee8 && rec->ExceptionInformation[1] == 0xffffffff
568         && except->params[0] == rec->ExceptionInformation[0])
569     {
570         goto skip_params;
571     }
572 
573     if (except->alt_status == 0 || rec->ExceptionCode != except->alt_status)
574     {
575         for (i = 0; i < rec->NumberParameters; i++)
576             ok( rec->ExceptionInformation[i] == except->params[i],
577                 "%u: Wrong parameter %d: %lx/%x\n",
578                 entry, i, rec->ExceptionInformation[i], except->params[i] );
579     }
580     else
581     {
582         for (i = 0; i < rec->NumberParameters; i++)
583             ok( rec->ExceptionInformation[i] == except->alt_params[i],
584                 "%u: Wrong parameter %d: %lx/%x\n",
585                 entry, i, rec->ExceptionInformation[i], except->alt_params[i] );
586     }
587 
588 skip_params:
589     /* don't handle exception if it's not the address we expected */
590     if (context->Eip != (DWORD_PTR)code_mem + except->offset) return ExceptionContinueSearch;
591 
592     context->Eip += except->length;
593     return ExceptionContinueExecution;
594 }
595 
596 static void test_prot_fault(void)
597 {
598     unsigned int i;
599 
600     for (i = 0; i < sizeof(exceptions)/sizeof(exceptions[0]); i++)
601     {
602         if (is_wow64 && exceptions[i].wow64_broken && !strcmp( winetest_platform, "windows" ))
603         {
604             skip( "Exception %u broken on Wow64\n", i );
605             continue;
606         }
607         got_exception = 0;
608         run_exception_test(handler, &exceptions[i], &exceptions[i].code,
609                            sizeof(exceptions[i].code), 0);
610         if (!i && !got_exception)
611         {
612             trace( "No exception, assuming win9x, no point in testing further\n" );
613             break;
614         }
615         ok( got_exception == (exceptions[i].status != 0),
616             "%u: bad exception count %d\n", i, got_exception );
617     }
618 }
619 
620 struct dbgreg_test {
621     DWORD dr0, dr1, dr2, dr3, dr6, dr7;
622 };
623 
624 /* test handling of debug registers */
625 static DWORD dreg_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
626                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
627 {
628     const struct dbgreg_test *test = *(const struct dbgreg_test **)(frame + 1);
629 
630     context->Eip += 2;	/* Skips the popl (%eax) */
631     context->Dr0 = test->dr0;
632     context->Dr1 = test->dr1;
633     context->Dr2 = test->dr2;
634     context->Dr3 = test->dr3;
635     context->Dr6 = test->dr6;
636     context->Dr7 = test->dr7;
637     return ExceptionContinueExecution;
638 }
639 
640 #define CHECK_DEBUG_REG(n, m) \
641     ok((ctx.Dr##n & m) == test->dr##n, "(%d) failed to set debug register " #n " to %x, got %x\n", \
642        test_num, test->dr##n, ctx.Dr##n)
643 
644 static void check_debug_registers(int test_num, const struct dbgreg_test *test)
645 {
646     CONTEXT ctx;
647     NTSTATUS status;
648 
649     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
650     status = pNtGetContextThread(GetCurrentThread(), &ctx);
651     ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %x\n", status);
652 
653     CHECK_DEBUG_REG(0, ~0);
654     CHECK_DEBUG_REG(1, ~0);
655     CHECK_DEBUG_REG(2, ~0);
656     CHECK_DEBUG_REG(3, ~0);
657     CHECK_DEBUG_REG(6, 0x0f);
658     CHECK_DEBUG_REG(7, ~0xdc00);
659 }
660 
661 static const BYTE segfault_code[5] = {
662 	0x31, 0xc0, /* xor    %eax,%eax */
663 	0x8f, 0x00, /* popl   (%eax) - cause exception */
664         0xc3        /* ret */
665 };
666 
667 /* test the single step exception behaviour */
668 static DWORD single_step_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
669                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
670 {
671     got_exception++;
672     ok (!(context->EFlags & 0x100), "eflags has single stepping bit set\n");
673 
674     if( got_exception < 3)
675         context->EFlags |= 0x100;  /* single step until popf instruction */
676     else {
677         /* show that the last single step exception on the popf instruction
678          * (which removed the TF bit), still is a EXCEPTION_SINGLE_STEP exception */
679         ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
680             "exception is not EXCEPTION_SINGLE_STEP: %x\n", rec->ExceptionCode);
681     }
682 
683     return ExceptionContinueExecution;
684 }
685 
686 static const BYTE single_stepcode[] = {
687     0x9c,		/* pushf */
688     0x58,		/* pop   %eax */
689     0x0d,0,1,0,0,	/* or    $0x100,%eax */
690     0x50,		/* push   %eax */
691     0x9d,		/* popf    */
692     0x35,0,1,0,0,	/* xor    $0x100,%eax */
693     0x50,		/* push   %eax */
694     0x9d,		/* popf    */
695     0xc3
696 };
697 
698 /* Test the alignment check (AC) flag handling. */
699 static const BYTE align_check_code[] = {
700     0x55,                  	/* push   %ebp */
701     0x89,0xe5,             	/* mov    %esp,%ebp */
702     0x9c,                  	/* pushf   */
703     0x58,                  	/* pop    %eax */
704     0x0d,0,0,4,0,       	/* or     $0x40000,%eax */
705     0x50,                  	/* push   %eax */
706     0x9d,                  	/* popf    */
707     0x89,0xe0,                  /* mov %esp, %eax */
708     0x8b,0x40,0x1,              /* mov 0x1(%eax), %eax - cause exception */
709     0x9c,                  	/* pushf   */
710     0x58,                  	/* pop    %eax */
711     0x35,0,0,4,0,       	/* xor    $0x40000,%eax */
712     0x50,                  	/* push   %eax */
713     0x9d,                  	/* popf    */
714     0x5d,                  	/* pop    %ebp */
715     0xc3,                  	/* ret     */
716 };
717 
718 static DWORD align_check_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
719                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
720 {
721     ok (!(context->EFlags & 0x40000), "eflags has AC bit set\n");
722     got_exception++;
723     return ExceptionContinueExecution;
724 }
725 
726 /* Test the direction flag handling. */
727 static const BYTE direction_flag_code[] = {
728     0x55,                  	/* push   %ebp */
729     0x89,0xe5,             	/* mov    %esp,%ebp */
730     0xfd,                  	/* std */
731     0xfa,                  	/* cli - cause exception */
732     0x5d,                  	/* pop    %ebp */
733     0xc3,                  	/* ret     */
734 };
735 
736 static DWORD direction_flag_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
737                                      CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
738 {
739 #ifdef __GNUC__
740     unsigned int flags;
741     __asm__("pushfl; popl %0; cld" : "=r" (flags) );
742     /* older windows versions don't clear DF properly so don't test */
743     if (flags & 0x400) trace( "eflags has DF bit set\n" );
744 #endif
745     ok( context->EFlags & 0x400, "context eflags has DF bit cleared\n" );
746     got_exception++;
747     context->Eip++;  /* skip cli */
748     context->EFlags &= ~0x400;  /* make sure it is cleared on return */
749     return ExceptionContinueExecution;
750 }
751 
752 /* test single stepping over hardware breakpoint */
753 static DWORD bpx_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
754                           CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
755 {
756     got_exception++;
757     ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
758         "wrong exception code: %x\n", rec->ExceptionCode);
759 
760     if(got_exception == 1) {
761         /* hw bp exception on first nop */
762         ok( context->Eip == (DWORD)code_mem, "eip is wrong:  %x instead of %x\n",
763                                              context->Eip, (DWORD)code_mem);
764         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
765         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
766         context->Dr0 = context->Dr0 + 1;  /* set hw bp again on next instruction */
767         context->EFlags |= 0x100;       /* enable single stepping */
768     } else if(  got_exception == 2) {
769         /* single step exception on second nop */
770         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
771                                                  context->Eip, (DWORD)code_mem + 1);
772         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
773        /* depending on the win version the B0 bit is already set here as well
774         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n"); */
775         context->EFlags |= 0x100;
776     } else if( got_exception == 3) {
777         /* hw bp exception on second nop */
778         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
779                                                  context->Eip, (DWORD)code_mem + 1);
780         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
781         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
782         context->Dr0 = 0;       /* clear breakpoint */
783         context->EFlags |= 0x100;
784     } else {
785         /* single step exception on ret */
786         ok( context->Eip == (DWORD)code_mem + 2, "eip is wrong: %x instead of %x\n",
787                                                  context->Eip, (DWORD)code_mem + 2);
788         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n");
789         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
790     }
791 
792     context->Dr6 = 0;  /* clear status register */
793     return ExceptionContinueExecution;
794 }
795 
796 static const BYTE dummy_code[] = { 0x90, 0x90, 0xc3 };  /* nop, nop, ret */
797 
798 /* test int3 handling */
799 static DWORD int3_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
800                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
801 {
802     ok( rec->ExceptionAddress == code_mem, "exception address not at: %p, but at %p\n",
803                                            code_mem,  rec->ExceptionAddress);
804     ok( context->Eip == (DWORD)code_mem, "eip not at: %p, but at %#x\n", code_mem, context->Eip);
805     if(context->Eip == (DWORD)code_mem) context->Eip++; /* skip breakpoint */
806 
807     return ExceptionContinueExecution;
808 }
809 
810 static const BYTE int3_code[] = { 0xCC, 0xc3 };  /* int 3, ret */
811 
812 static DWORD WINAPI hw_reg_exception_thread( void *arg )
813 {
814     int expect = (ULONG_PTR)arg;
815     got_exception = 0;
816     run_exception_test( bpx_handler, NULL, dummy_code, sizeof(dummy_code), 0 );
817     ok( got_exception == expect, "expected %u exceptions, got %d\n", expect, got_exception );
818     return 0;
819 }
820 
821 static void test_exceptions(void)
822 {
823     CONTEXT ctx;
824     NTSTATUS res;
825     struct dbgreg_test dreg_test;
826     HANDLE h;
827 
828     if (!pNtGetContextThread || !pNtSetContextThread)
829     {
830         skip( "NtGetContextThread/NtSetContextThread not found\n" );
831         return;
832     }
833 
834     /* test handling of debug registers */
835     memset(&dreg_test, 0, sizeof(dreg_test));
836 
837     dreg_test.dr0 = 0x42424240;
838     dreg_test.dr2 = 0x126bb070;
839     dreg_test.dr3 = 0x0badbad0;
840     dreg_test.dr7 = 0xffff0115;
841     run_exception_test(dreg_handler, &dreg_test, &segfault_code, sizeof(segfault_code), 0);
842     check_debug_registers(1, &dreg_test);
843 
844     dreg_test.dr0 = 0x42424242;
845     dreg_test.dr2 = 0x100f0fe7;
846     dreg_test.dr3 = 0x0abebabe;
847     dreg_test.dr7 = 0x115;
848     run_exception_test(dreg_handler, &dreg_test, &segfault_code, sizeof(segfault_code), 0);
849     check_debug_registers(2, &dreg_test);
850 
851     /* test single stepping behavior */
852     got_exception = 0;
853     run_exception_test(single_step_handler, NULL, &single_stepcode, sizeof(single_stepcode), 0);
854     ok(got_exception == 3, "expected 3 single step exceptions, got %d\n", got_exception);
855 
856     /* test alignment exceptions */
857     got_exception = 0;
858     run_exception_test(align_check_handler, NULL, align_check_code, sizeof(align_check_code), 0);
859     ok(got_exception == 0, "got %d alignment faults, expected 0\n", got_exception);
860 
861     /* test direction flag */
862     got_exception = 0;
863     run_exception_test(direction_flag_handler, NULL, direction_flag_code, sizeof(direction_flag_code), 0);
864     ok(got_exception == 1, "got %d exceptions, expected 1\n", got_exception);
865 
866     /* test single stepping over hardware breakpoint */
867     memset(&ctx, 0, sizeof(ctx));
868     ctx.Dr0 = (DWORD) code_mem;  /* set hw bp on first nop */
869     ctx.Dr7 = 3;
870     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
871     res = pNtSetContextThread( GetCurrentThread(), &ctx);
872     ok( res == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", res);
873 
874     got_exception = 0;
875     run_exception_test(bpx_handler, NULL, dummy_code, sizeof(dummy_code), 0);
876     ok( got_exception == 4,"expected 4 exceptions, got %d\n", got_exception);
877 
878     /* test int3 handling */
879     run_exception_test(int3_handler, NULL, int3_code, sizeof(int3_code), 0);
880 
881     /* test that hardware breakpoints are not inherited by created threads */
882     res = pNtSetContextThread( GetCurrentThread(), &ctx );
883     ok( res == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", res );
884 
885     h = CreateThread( NULL, 0, hw_reg_exception_thread, 0, 0, NULL );
886     WaitForSingleObject( h, 10000 );
887     CloseHandle( h );
888 
889     h = CreateThread( NULL, 0, hw_reg_exception_thread, (void *)4, CREATE_SUSPENDED, NULL );
890     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
891     res = pNtGetContextThread( h, &ctx );
892     ok( res == STATUS_SUCCESS, "NtGetContextThread failed with %x\n", res );
893     ok( ctx.Dr0 == 0, "dr0 %x\n", ctx.Dr0 );
894     ok( ctx.Dr7 == 0, "dr7 %x\n", ctx.Dr7 );
895     ctx.Dr0 = (DWORD)code_mem;
896     ctx.Dr7 = 3;
897     res = pNtSetContextThread( h, &ctx );
898     ok( res == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", res );
899     ResumeThread( h );
900     WaitForSingleObject( h, 10000 );
901     CloseHandle( h );
902 
903     ctx.Dr0 = 0;
904     ctx.Dr7 = 0;
905     res = pNtSetContextThread( GetCurrentThread(), &ctx );
906     ok( res == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", res );
907 }
908 
909 static void test_debugger(void)
910 {
911     char cmdline[MAX_PATH];
912     PROCESS_INFORMATION pi;
913     STARTUPINFOA si = { 0 };
914     DEBUG_EVENT de;
915     DWORD continuestatus;
916     PVOID code_mem_address = NULL;
917     NTSTATUS status;
918     SIZE_T size_read;
919     BOOL ret;
920     int counter = 0;
921     si.cb = sizeof(si);
922 
923     if(!pNtGetContextThread || !pNtSetContextThread || !pNtReadVirtualMemory || !pNtTerminateProcess)
924     {
925         skip("NtGetContextThread, NtSetContextThread, NtReadVirtualMemory or NtTerminateProcess not found\n");
926         return;
927     }
928 
929     sprintf(cmdline, "%s %s %s %p", my_argv[0], my_argv[1], "debuggee", &test_stage);
930     ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi);
931     ok(ret, "could not create child process error: %u\n", GetLastError());
932     if (!ret)
933         return;
934 
935     do
936     {
937         continuestatus = DBG_CONTINUE;
938         ok(WaitForDebugEvent(&de, INFINITE), "reading debug event\n");
939 
940         if (de.dwThreadId != pi.dwThreadId)
941         {
942             trace("event %d not coming from main thread, ignoring\n", de.dwDebugEventCode);
943             ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
944             continue;
945         }
946 
947         if (de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
948         {
949             if(de.u.CreateProcessInfo.lpBaseOfImage != NtCurrentTeb()->Peb->ImageBaseAddress)
950             {
951                 skip("child process loaded at different address, terminating it\n");
952                 pNtTerminateProcess(pi.hProcess, 0);
953             }
954         }
955         else if (de.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
956         {
957             CONTEXT ctx;
958             int stage;
959 
960             counter++;
961             status = pNtReadVirtualMemory(pi.hProcess, &code_mem, &code_mem_address,
962                                           sizeof(code_mem_address), &size_read);
963             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
964             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
965                                           sizeof(stage), &size_read);
966             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
967 
968             ctx.ContextFlags = CONTEXT_FULL;
969             status = pNtGetContextThread(pi.hThread, &ctx);
970             ok(!status, "NtGetContextThread failed with 0x%x\n", status);
971 
972             trace("exception 0x%x at %p firstchance=%d Eip=0x%x, Eax=0x%x\n",
973                   de.u.Exception.ExceptionRecord.ExceptionCode,
974                   de.u.Exception.ExceptionRecord.ExceptionAddress, de.u.Exception.dwFirstChance, ctx.Eip, ctx.Eax);
975 
976             if (counter > 100)
977             {
978                 ok(FALSE, "got way too many exceptions, probably caught in an infinite loop, terminating child\n");
979                 pNtTerminateProcess(pi.hProcess, 1);
980             }
981             else if (counter >= 2) /* skip startup breakpoint */
982             {
983                 if (stage == 1)
984                 {
985                     ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at %x instead of %p\n",
986                        ctx.Eip, (char *)code_mem_address + 0xb);
987                     /* setting the context from debugger does not affect the context, the exception handlers gets */
988                     /* uncomment once wine is fixed */
989                     /* ctx.Eip = 0x12345; */
990                     ctx.Eax = 0xf00f00f1;
991 
992                     /* let the debuggee handle the exception */
993                     continuestatus = DBG_EXCEPTION_NOT_HANDLED;
994                 }
995                 else if (stage == 2)
996                 {
997                     if (de.u.Exception.dwFirstChance)
998                     {
999                         /* debugger gets first chance exception with unmodified ctx.Eip */
1000                         ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
1001                             ctx.Eip, (char *)code_mem_address + 0xb);
1002 
1003                         /* setting the context from debugger does not affect the context, the exception handlers gets */
1004                         /* uncomment once wine is fixed */
1005                         /* ctx.Eip = 0x12345; */
1006                         ctx.Eax = 0xf00f00f1;
1007 
1008                         /* pass exception to debuggee
1009                          * exception will not be handled and
1010                          * a second chance exception will be raised */
1011                         continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1012                     }
1013                     else
1014                     {
1015                         /* debugger gets context after exception handler has played with it */
1016                         /* ctx.Eip is the same value the exception handler got */
1017                         if (de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
1018                         {
1019                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xa ||
1020                                broken(is_wow64 && (char *)ctx.Eip == (char *)code_mem_address + 0xb),
1021                                "Eip at 0x%x instead of %p\n",
1022                                 ctx.Eip, (char *)code_mem_address + 0xa);
1023                             /* need to fixup Eip for debuggee */
1024                             if ((char *)ctx.Eip == (char *)code_mem_address + 0xa)
1025                                 ctx.Eip += 1;
1026                         }
1027                         else
1028                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
1029                                 ctx.Eip, (char *)code_mem_address + 0xb);
1030                         /* here we handle exception */
1031                     }
1032                 }
1033                 else if (stage == 7 || stage == 8)
1034                 {
1035                     ok(de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT,
1036                        "expected EXCEPTION_BREAKPOINT, got %08x\n", de.u.Exception.ExceptionRecord.ExceptionCode);
1037                     ok((char *)ctx.Eip == (char *)code_mem_address + 0x1d,
1038                        "expected Eip = %p, got 0x%x\n", (char *)code_mem_address + 0x1d, ctx.Eip);
1039 
1040                     if (stage == 8) continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1041                 }
1042                 else if (stage == 9 || stage == 10)
1043                 {
1044                     ok(de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT,
1045                        "expected EXCEPTION_BREAKPOINT, got %08x\n", de.u.Exception.ExceptionRecord.ExceptionCode);
1046                     ok((char *)ctx.Eip == (char *)code_mem_address + 2,
1047                        "expected Eip = %p, got 0x%x\n", (char *)code_mem_address + 2, ctx.Eip);
1048 
1049                     if (stage == 10) continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1050                 }
1051                 else if (stage == 11 || stage == 12)
1052                 {
1053                     ok(de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_INVALID_HANDLE,
1054                        "unexpected exception code %08x, expected %08x\n", de.u.Exception.ExceptionRecord.ExceptionCode,
1055                        EXCEPTION_INVALID_HANDLE);
1056                     ok(de.u.Exception.ExceptionRecord.NumberParameters == 0,
1057                        "unexpected number of parameters %d, expected 0\n", de.u.Exception.ExceptionRecord.NumberParameters);
1058 
1059                     if (stage == 12) continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1060                 }
1061                 else
1062                     ok(FALSE, "unexpected stage %x\n", stage);
1063 
1064                 status = pNtSetContextThread(pi.hThread, &ctx);
1065                 ok(!status, "NtSetContextThread failed with 0x%x\n", status);
1066             }
1067         }
1068         else if (de.dwDebugEventCode == OUTPUT_DEBUG_STRING_EVENT)
1069         {
1070             int stage;
1071 #ifdef __REACTOS__
1072             /* This will catch our DPRINTs, such as
1073              * "WARNING:  RtlpDphTargetDllsLogicInitialize at ..\..\lib\rtl\heappage.c:1283 is UNIMPLEMENTED!"
1074              * so we need a full-size buffer to avoid a stack overflow
1075              */
1076             char buffer[513];
1077 #else
1078             char buffer[64];
1079 #endif
1080 
1081             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
1082                                           sizeof(stage), &size_read);
1083             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
1084 
1085             ok(!de.u.DebugString.fUnicode, "unexpected unicode debug string event\n");
1086             ok(de.u.DebugString.nDebugStringLength < sizeof(buffer) - 1, "buffer not large enough to hold %d bytes\n",
1087                de.u.DebugString.nDebugStringLength);
1088 
1089             memset(buffer, 0, sizeof(buffer));
1090             status = pNtReadVirtualMemory(pi.hProcess, de.u.DebugString.lpDebugStringData, buffer,
1091                                           de.u.DebugString.nDebugStringLength, &size_read);
1092             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
1093 
1094             if (stage == 3 || stage == 4)
1095                 ok(!strcmp(buffer, "Hello World"), "got unexpected debug string '%s'\n", buffer);
1096             else /* ignore unrelated debug strings like 'SHIMVIEW: ShimInfo(Complete)' */
1097                 ok(strstr(buffer, "SHIMVIEW") != NULL, "unexpected stage %x, got debug string event '%s'\n", stage, buffer);
1098 
1099             if (stage == 4) continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1100         }
1101         else if (de.dwDebugEventCode == RIP_EVENT)
1102         {
1103             int stage;
1104 
1105             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
1106                                           sizeof(stage), &size_read);
1107             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
1108 
1109             if (stage == 5 || stage == 6)
1110             {
1111                 ok(de.u.RipInfo.dwError == 0x11223344, "got unexpected rip error code %08x, expected %08x\n",
1112                    de.u.RipInfo.dwError, 0x11223344);
1113                 ok(de.u.RipInfo.dwType  == 0x55667788, "got unexpected rip type %08x, expected %08x\n",
1114                    de.u.RipInfo.dwType, 0x55667788);
1115             }
1116             else
1117                 ok(FALSE, "unexpected stage %x\n", stage);
1118 
1119             if (stage == 6) continuestatus = DBG_EXCEPTION_NOT_HANDLED;
1120         }
1121 
1122         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, continuestatus);
1123 
1124     } while (de.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
1125 
1126     winetest_wait_child_process( pi.hProcess );
1127     ret = CloseHandle(pi.hThread);
1128     ok(ret, "error %u\n", GetLastError());
1129     ret = CloseHandle(pi.hProcess);
1130     ok(ret, "error %u\n", GetLastError());
1131 
1132     return;
1133 }
1134 
1135 static DWORD simd_fault_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
1136                                  CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
1137 {
1138     int *stage = *(int **)(frame + 1);
1139 
1140     got_exception++;
1141 
1142     if( *stage == 1) {
1143         /* fault while executing sse instruction */
1144         context->Eip += 3; /* skip addps */
1145         return ExceptionContinueExecution;
1146     }
1147     else if ( *stage == 2 || *stage == 3 ) {
1148         /* stage 2 - divide by zero fault */
1149         /* stage 3 - invalid operation fault */
1150         if( rec->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION)
1151             skip("system doesn't support SIMD exceptions\n");
1152         else {
1153             ok( rec->ExceptionCode ==  STATUS_FLOAT_MULTIPLE_TRAPS,
1154                 "exception code: %#x, should be %#x\n",
1155                 rec->ExceptionCode,  STATUS_FLOAT_MULTIPLE_TRAPS);
1156             ok( rec->NumberParameters == 1 || broken(is_wow64 && rec->NumberParameters == 2),
1157                 "# of params: %i, should be 1\n",
1158                 rec->NumberParameters);
1159             if( rec->NumberParameters == 1 )
1160                 ok( rec->ExceptionInformation[0] == 0, "param #1: %lx, should be 0\n", rec->ExceptionInformation[0]);
1161         }
1162         context->Eip += 3; /* skip divps */
1163     }
1164     else
1165         ok(FALSE, "unexpected stage %x\n", *stage);
1166 
1167     return ExceptionContinueExecution;
1168 }
1169 
1170 static const BYTE simd_exception_test[] = {
1171     0x83, 0xec, 0x4,                     /* sub $0x4, %esp       */
1172     0x0f, 0xae, 0x1c, 0x24,              /* stmxcsr (%esp)       */
1173     0x8b, 0x04, 0x24,                    /* mov    (%esp),%eax   * store mxcsr */
1174     0x66, 0x81, 0x24, 0x24, 0xff, 0xfd,  /* andw $0xfdff,(%esp)  * enable divide by */
1175     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       * zero exceptions  */
1176     0x6a, 0x01,                          /* push   $0x1          */
1177     0x6a, 0x01,                          /* push   $0x1          */
1178     0x6a, 0x01,                          /* push   $0x1          */
1179     0x6a, 0x01,                          /* push   $0x1          */
1180     0x0f, 0x10, 0x0c, 0x24,              /* movups (%esp),%xmm1  * fill dividend  */
1181     0x0f, 0x57, 0xc0,                    /* xorps  %xmm0,%xmm0   * clear divisor  */
1182     0x0f, 0x5e, 0xc8,                    /* divps  %xmm0,%xmm1   * generate fault */
1183     0x83, 0xc4, 0x10,                    /* add    $0x10,%esp    */
1184     0x89, 0x04, 0x24,                    /* mov    %eax,(%esp)   * restore to old mxcsr */
1185     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       */
1186     0x83, 0xc4, 0x04,                    /* add    $0x4,%esp     */
1187     0xc3,                                /* ret */
1188 };
1189 
1190 static const BYTE simd_exception_test2[] = {
1191     0x83, 0xec, 0x4,                     /* sub $0x4, %esp       */
1192     0x0f, 0xae, 0x1c, 0x24,              /* stmxcsr (%esp)       */
1193     0x8b, 0x04, 0x24,                    /* mov    (%esp),%eax   * store mxcsr */
1194     0x66, 0x81, 0x24, 0x24, 0x7f, 0xff,  /* andw $0xff7f,(%esp)  * enable invalid       */
1195     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       * operation exceptions */
1196     0x0f, 0x57, 0xc9,                    /* xorps  %xmm1,%xmm1   * clear dividend */
1197     0x0f, 0x57, 0xc0,                    /* xorps  %xmm0,%xmm0   * clear divisor  */
1198     0x0f, 0x5e, 0xc8,                    /* divps  %xmm0,%xmm1   * generate fault */
1199     0x89, 0x04, 0x24,                    /* mov    %eax,(%esp)   * restore to old mxcsr */
1200     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       */
1201     0x83, 0xc4, 0x04,                    /* add    $0x4,%esp     */
1202     0xc3,                                /* ret */
1203 };
1204 
1205 static const BYTE sse_check[] = {
1206     0x0f, 0x58, 0xc8,                    /* addps  %xmm0,%xmm1 */
1207     0xc3,                                /* ret */
1208 };
1209 
1210 static void test_simd_exceptions(void)
1211 {
1212     int stage;
1213 
1214     /* test if CPU & OS can do sse */
1215     stage = 1;
1216     got_exception = 0;
1217     run_exception_test(simd_fault_handler, &stage, sse_check, sizeof(sse_check), 0);
1218     if(got_exception) {
1219         skip("system doesn't support SSE\n");
1220         return;
1221     }
1222 
1223     /* generate a SIMD exception */
1224     stage = 2;
1225     got_exception = 0;
1226     run_exception_test(simd_fault_handler, &stage, simd_exception_test,
1227                        sizeof(simd_exception_test), 0);
1228     ok(got_exception == 1, "got exception: %i, should be 1\n", got_exception);
1229 
1230     /* generate a SIMD exception, test FPE_FLTINV */
1231     stage = 3;
1232     got_exception = 0;
1233     run_exception_test(simd_fault_handler, &stage, simd_exception_test2,
1234                        sizeof(simd_exception_test2), 0);
1235     ok(got_exception == 1, "got exception: %i, should be 1\n", got_exception);
1236 }
1237 
1238 struct fpu_exception_info
1239 {
1240     DWORD exception_code;
1241     DWORD exception_offset;
1242     DWORD eip_offset;
1243 };
1244 
1245 static DWORD fpu_exception_handler(EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
1246         CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher)
1247 {
1248     struct fpu_exception_info *info = *(struct fpu_exception_info **)(frame + 1);
1249 
1250     info->exception_code = rec->ExceptionCode;
1251     info->exception_offset = (BYTE *)rec->ExceptionAddress - (BYTE *)code_mem;
1252     info->eip_offset = context->Eip - (DWORD)code_mem;
1253 
1254     ++context->Eip;
1255     return ExceptionContinueExecution;
1256 }
1257 
1258 static void test_fpu_exceptions(void)
1259 {
1260     static const BYTE fpu_exception_test_ie[] =
1261     {
1262         0x83, 0xec, 0x04,                   /* sub $0x4,%esp        */
1263         0x66, 0xc7, 0x04, 0x24, 0xfe, 0x03, /* movw $0x3fe,(%esp)   */
1264         0x9b, 0xd9, 0x7c, 0x24, 0x02,       /* fstcw 0x2(%esp)      */
1265         0xd9, 0x2c, 0x24,                   /* fldcw (%esp)         */
1266         0xd9, 0xee,                         /* fldz                 */
1267         0xd9, 0xe8,                         /* fld1                 */
1268         0xde, 0xf1,                         /* fdivp                */
1269         0xdd, 0xd8,                         /* fstp %st(0)          */
1270         0xdd, 0xd8,                         /* fstp %st(0)          */
1271         0x9b,                               /* fwait                */
1272         0xdb, 0xe2,                         /* fnclex               */
1273         0xd9, 0x6c, 0x24, 0x02,             /* fldcw 0x2(%esp)      */
1274         0x83, 0xc4, 0x04,                   /* add $0x4,%esp        */
1275         0xc3,                               /* ret                  */
1276     };
1277 
1278     static const BYTE fpu_exception_test_de[] =
1279     {
1280         0x83, 0xec, 0x04,                   /* sub $0x4,%esp        */
1281         0x66, 0xc7, 0x04, 0x24, 0xfb, 0x03, /* movw $0x3fb,(%esp)   */
1282         0x9b, 0xd9, 0x7c, 0x24, 0x02,       /* fstcw 0x2(%esp)      */
1283         0xd9, 0x2c, 0x24,                   /* fldcw (%esp)         */
1284         0xdd, 0xd8,                         /* fstp %st(0)          */
1285         0xd9, 0xee,                         /* fldz                 */
1286         0xd9, 0xe8,                         /* fld1                 */
1287         0xde, 0xf1,                         /* fdivp                */
1288         0x9b,                               /* fwait                */
1289         0xdb, 0xe2,                         /* fnclex               */
1290         0xdd, 0xd8,                         /* fstp %st(0)          */
1291         0xdd, 0xd8,                         /* fstp %st(0)          */
1292         0xd9, 0x6c, 0x24, 0x02,             /* fldcw 0x2(%esp)      */
1293         0x83, 0xc4, 0x04,                   /* add $0x4,%esp        */
1294         0xc3,                               /* ret                  */
1295     };
1296 
1297     struct fpu_exception_info info;
1298 
1299     memset(&info, 0, sizeof(info));
1300     run_exception_test(fpu_exception_handler, &info, fpu_exception_test_ie, sizeof(fpu_exception_test_ie), 0);
1301     ok(info.exception_code == EXCEPTION_FLT_STACK_CHECK,
1302             "Got exception code %#x, expected EXCEPTION_FLT_STACK_CHECK\n", info.exception_code);
1303     ok(info.exception_offset == 0x19 ||
1304        broken( info.exception_offset == info.eip_offset ),
1305        "Got exception offset %#x, expected 0x19\n", info.exception_offset);
1306     ok(info.eip_offset == 0x1b, "Got EIP offset %#x, expected 0x1b\n", info.eip_offset);
1307 
1308     memset(&info, 0, sizeof(info));
1309     run_exception_test(fpu_exception_handler, &info, fpu_exception_test_de, sizeof(fpu_exception_test_de), 0);
1310     ok(info.exception_code == EXCEPTION_FLT_DIVIDE_BY_ZERO,
1311             "Got exception code %#x, expected EXCEPTION_FLT_DIVIDE_BY_ZERO\n", info.exception_code);
1312     ok(info.exception_offset == 0x17 ||
1313        broken( info.exception_offset == info.eip_offset ),
1314        "Got exception offset %#x, expected 0x17\n", info.exception_offset);
1315     ok(info.eip_offset == 0x19, "Got EIP offset %#x, expected 0x19\n", info.eip_offset);
1316 }
1317 
1318 struct dpe_exception_info {
1319     BOOL exception_caught;
1320     DWORD exception_info;
1321 };
1322 
1323 static DWORD dpe_exception_handler(EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
1324         CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher)
1325 {
1326     DWORD old_prot;
1327     struct dpe_exception_info *info = *(struct dpe_exception_info **)(frame + 1);
1328 
1329     ok(rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION,
1330        "Exception code %08x\n", rec->ExceptionCode);
1331     ok(rec->NumberParameters == 2,
1332        "Parameter count: %d\n", rec->NumberParameters);
1333     ok((LPVOID)rec->ExceptionInformation[1] == code_mem,
1334        "Exception address: %p, expected %p\n",
1335        (LPVOID)rec->ExceptionInformation[1], code_mem);
1336 
1337     info->exception_info = rec->ExceptionInformation[0];
1338     info->exception_caught = TRUE;
1339 
1340     VirtualProtect(code_mem, 1, PAGE_EXECUTE_READWRITE, &old_prot);
1341     return ExceptionContinueExecution;
1342 }
1343 
1344 static void test_dpe_exceptions(void)
1345 {
1346     static const BYTE single_ret[] = {0xC3};
1347     struct dpe_exception_info info;
1348     NTSTATUS stat;
1349     BOOL has_hw_support;
1350     BOOL is_permanent = FALSE, can_test_without = TRUE, can_test_with = TRUE;
1351     DWORD val;
1352     ULONG len;
1353 
1354     /* Query DEP with len too small */
1355     stat = pNtQueryInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val - 1, &len);
1356     if(stat == STATUS_INVALID_INFO_CLASS)
1357     {
1358         skip("This software platform does not support DEP\n");
1359         return;
1360     }
1361     ok(stat == STATUS_INFO_LENGTH_MISMATCH, "buffer too small: %08x\n", stat);
1362 
1363     /* Query DEP */
1364     stat = pNtQueryInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val, &len);
1365     ok(stat == STATUS_SUCCESS, "querying DEP: status %08x\n", stat);
1366     if(stat == STATUS_SUCCESS)
1367     {
1368         ok(len == sizeof val, "returned length: %d\n", len);
1369         if(val & MEM_EXECUTE_OPTION_PERMANENT)
1370         {
1371             skip("toggling DEP impossible - status locked\n");
1372             is_permanent = TRUE;
1373             if(val & MEM_EXECUTE_OPTION_DISABLE)
1374                 can_test_without = FALSE;
1375             else
1376                 can_test_with = FALSE;
1377         }
1378     }
1379 
1380     if(!is_permanent)
1381     {
1382         /* Enable DEP */
1383         val = MEM_EXECUTE_OPTION_DISABLE;
1384         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1385         ok(stat == STATUS_SUCCESS, "enabling DEP: status %08x\n", stat);
1386     }
1387 
1388     if(can_test_with)
1389     {
1390         /* Try access to locked page with DEP on*/
1391         info.exception_caught = FALSE;
1392         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_NOACCESS);
1393         ok(info.exception_caught == TRUE, "Execution of disabled memory succeeded\n");
1394         ok(info.exception_info == EXCEPTION_READ_FAULT ||
1395            info.exception_info == EXCEPTION_EXECUTE_FAULT,
1396               "Access violation type: %08x\n", (unsigned)info.exception_info);
1397         has_hw_support = info.exception_info == EXCEPTION_EXECUTE_FAULT;
1398         trace("DEP hardware support: %s\n", has_hw_support?"Yes":"No");
1399 
1400         /* Try execution of data with DEP on*/
1401         info.exception_caught = FALSE;
1402         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_READWRITE);
1403         if(has_hw_support)
1404         {
1405             ok(info.exception_caught == TRUE, "Execution of data memory succeeded\n");
1406             ok(info.exception_info == EXCEPTION_EXECUTE_FAULT,
1407                   "Access violation type: %08x\n", (unsigned)info.exception_info);
1408         }
1409         else
1410             ok(info.exception_caught == FALSE, "Execution trapped without hardware support\n");
1411     }
1412     else
1413         skip("DEP is in AlwaysOff state\n");
1414 
1415     if(!is_permanent)
1416     {
1417         /* Disable DEP */
1418         val = MEM_EXECUTE_OPTION_ENABLE;
1419         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1420         ok(stat == STATUS_SUCCESS, "disabling DEP: status %08x\n", stat);
1421     }
1422 
1423     /* page is read without exec here */
1424     if(can_test_without)
1425     {
1426         /* Try execution of data with DEP off */
1427         info.exception_caught = FALSE;
1428         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_READWRITE);
1429         ok(info.exception_caught == FALSE, "Execution trapped with DEP turned off\n");
1430 
1431         /* Try access to locked page with DEP off - error code is different than
1432            with hardware DEP on */
1433         info.exception_caught = FALSE;
1434         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_NOACCESS);
1435         ok(info.exception_caught == TRUE, "Execution of disabled memory succeeded\n");
1436         ok(info.exception_info == EXCEPTION_READ_FAULT,
1437               "Access violation type: %08x\n", (unsigned)info.exception_info);
1438     }
1439     else
1440         skip("DEP is in AlwaysOn state\n");
1441 
1442     if(!is_permanent)
1443     {
1444         /* Turn off DEP permanently */
1445         val = MEM_EXECUTE_OPTION_ENABLE | MEM_EXECUTE_OPTION_PERMANENT;
1446         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1447         ok(stat == STATUS_SUCCESS, "disabling DEP permanently: status %08x\n", stat);
1448     }
1449 
1450     /* Try to turn off DEP */
1451     val = MEM_EXECUTE_OPTION_ENABLE;
1452     stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1453     ok(stat == STATUS_ACCESS_DENIED, "disabling DEP while permanent: status %08x\n", stat);
1454 
1455     /* Try to turn on DEP */
1456     val = MEM_EXECUTE_OPTION_DISABLE;
1457     stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1458     ok(stat == STATUS_ACCESS_DENIED, "enabling DEP while permanent: status %08x\n", stat);
1459 }
1460 
1461 static void test_thread_context(void)
1462 {
1463     CONTEXT context;
1464     NTSTATUS status;
1465     struct expected
1466     {
1467         DWORD Eax, Ebx, Ecx, Edx, Esi, Edi, Ebp, Esp, Eip,
1468             SegCs, SegDs, SegEs, SegFs, SegGs, SegSs, EFlags, prev_frame;
1469     } expect;
1470     NTSTATUS (*func_ptr)( struct expected *res, void *func, void *arg1, void *arg2 ) = (void *)code_mem;
1471 
1472     static const BYTE call_func[] =
1473     {
1474         0x55,             /* pushl  %ebp */
1475         0x89, 0xe5,       /* mov    %esp,%ebp */
1476         0x50,             /* pushl  %eax ; add a bit of offset to the stack */
1477         0x50,             /* pushl  %eax */
1478         0x50,             /* pushl  %eax */
1479         0x50,             /* pushl  %eax */
1480         0x8b, 0x45, 0x08, /* mov    0x8(%ebp),%eax */
1481         0x8f, 0x00,       /* popl   (%eax) */
1482         0x89, 0x58, 0x04, /* mov    %ebx,0x4(%eax) */
1483         0x89, 0x48, 0x08, /* mov    %ecx,0x8(%eax) */
1484         0x89, 0x50, 0x0c, /* mov    %edx,0xc(%eax) */
1485         0x89, 0x70, 0x10, /* mov    %esi,0x10(%eax) */
1486         0x89, 0x78, 0x14, /* mov    %edi,0x14(%eax) */
1487         0x89, 0x68, 0x18, /* mov    %ebp,0x18(%eax) */
1488         0x89, 0x60, 0x1c, /* mov    %esp,0x1c(%eax) */
1489         0xff, 0x75, 0x04, /* pushl  0x4(%ebp) */
1490         0x8f, 0x40, 0x20, /* popl   0x20(%eax) */
1491         0x8c, 0x48, 0x24, /* mov    %cs,0x24(%eax) */
1492         0x8c, 0x58, 0x28, /* mov    %ds,0x28(%eax) */
1493         0x8c, 0x40, 0x2c, /* mov    %es,0x2c(%eax) */
1494         0x8c, 0x60, 0x30, /* mov    %fs,0x30(%eax) */
1495         0x8c, 0x68, 0x34, /* mov    %gs,0x34(%eax) */
1496         0x8c, 0x50, 0x38, /* mov    %ss,0x38(%eax) */
1497         0x9c,             /* pushf */
1498         0x8f, 0x40, 0x3c, /* popl   0x3c(%eax) */
1499         0xff, 0x75, 0x00, /* pushl  0x0(%ebp) ; previous stack frame */
1500         0x8f, 0x40, 0x40, /* popl   0x40(%eax) */
1501         0x8b, 0x00,       /* mov    (%eax),%eax */
1502         0xff, 0x75, 0x14, /* pushl  0x14(%ebp) */
1503         0xff, 0x75, 0x10, /* pushl  0x10(%ebp) */
1504         0xff, 0x55, 0x0c, /* call   *0xc(%ebp) */
1505         0xc9,             /* leave */
1506         0xc3,             /* ret */
1507     };
1508 
1509     memcpy( func_ptr, call_func, sizeof(call_func) );
1510 
1511 #define COMPARE(reg) \
1512     ok( context.reg == expect.reg, "wrong " #reg " %08x/%08x\n", context.reg, expect.reg )
1513 
1514     memset( &context, 0xcc, sizeof(context) );
1515     memset( &expect, 0xcc, sizeof(expect) );
1516     func_ptr( &expect, pRtlCaptureContext, &context, 0 );
1517     trace( "expect: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x ebp=%08x esp=%08x "
1518            "eip=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x flags=%08x prev=%08x\n",
1519            expect.Eax, expect.Ebx, expect.Ecx, expect.Edx, expect.Esi, expect.Edi,
1520            expect.Ebp, expect.Esp, expect.Eip, expect.SegCs, expect.SegDs, expect.SegEs,
1521            expect.SegFs, expect.SegGs, expect.SegSs, expect.EFlags, expect.prev_frame );
1522     trace( "actual: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x ebp=%08x esp=%08x "
1523            "eip=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x flags=%08x\n",
1524            context.Eax, context.Ebx, context.Ecx, context.Edx, context.Esi, context.Edi,
1525            context.Ebp, context.Esp, context.Eip, context.SegCs, context.SegDs, context.SegEs,
1526            context.SegFs, context.SegGs, context.SegSs, context.EFlags );
1527 
1528     ok( context.ContextFlags == (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS) ||
1529         broken( context.ContextFlags == 0xcccccccc ),  /* <= vista */
1530         "wrong flags %08x\n", context.ContextFlags );
1531     COMPARE( Eax );
1532     COMPARE( Ebx );
1533     COMPARE( Ecx );
1534     COMPARE( Edx );
1535     COMPARE( Esi );
1536     COMPARE( Edi );
1537     COMPARE( Eip );
1538     COMPARE( SegCs );
1539     COMPARE( SegDs );
1540     COMPARE( SegEs );
1541     COMPARE( SegFs );
1542     COMPARE( SegGs );
1543     COMPARE( SegSs );
1544     COMPARE( EFlags );
1545     /* Ebp is from the previous stackframe */
1546     ok( context.Ebp == expect.prev_frame, "wrong Ebp %08x/%08x\n", context.Ebp, expect.prev_frame );
1547     /* Esp is the value on entry to the previous stackframe */
1548     ok( context.Esp == expect.Ebp + 8, "wrong Esp %08x/%08x\n", context.Esp, expect.Ebp + 8 );
1549 
1550     memset( &context, 0xcc, sizeof(context) );
1551     memset( &expect, 0xcc, sizeof(expect) );
1552     context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
1553     status = func_ptr( &expect, pNtGetContextThread, (void *)GetCurrentThread(), &context );
1554     ok( status == STATUS_SUCCESS, "NtGetContextThread failed %08x\n", status );
1555     trace( "expect: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x ebp=%08x esp=%08x "
1556            "eip=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x flags=%08x prev=%08x\n",
1557            expect.Eax, expect.Ebx, expect.Ecx, expect.Edx, expect.Esi, expect.Edi,
1558            expect.Ebp, expect.Esp, expect.Eip, expect.SegCs, expect.SegDs, expect.SegEs,
1559            expect.SegFs, expect.SegGs, expect.SegSs, expect.EFlags, expect.prev_frame );
1560     trace( "actual: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x ebp=%08x esp=%08x "
1561            "eip=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x flags=%08x\n",
1562            context.Eax, context.Ebx, context.Ecx, context.Edx, context.Esi, context.Edi,
1563            context.Ebp, context.Esp, context.Eip, context.SegCs, context.SegDs, context.SegEs,
1564            context.SegFs, context.SegGs, context.SegSs, context.EFlags );
1565     /* Eax, Ecx, Edx, EFlags are not preserved */
1566     COMPARE( Ebx );
1567     COMPARE( Esi );
1568     COMPARE( Edi );
1569     COMPARE( Ebp );
1570     /* Esp is the stack upon entry to NtGetContextThread */
1571     ok( context.Esp == expect.Esp - 12 || context.Esp == expect.Esp - 16,
1572         "wrong Esp %08x/%08x\n", context.Esp, expect.Esp );
1573     /* Eip is somewhere close to the NtGetContextThread implementation */
1574     ok( (char *)context.Eip >= (char *)pNtGetContextThread - 0x10000 &&
1575         (char *)context.Eip <= (char *)pNtGetContextThread + 0x10000,
1576         "wrong Eip %08x/%08x\n", context.Eip, (DWORD)pNtGetContextThread );
1577     ok( *(WORD *)context.Eip == 0xc483 || *(WORD *)context.Eip == 0x08c2 || *(WORD *)context.Eip == 0x8dc3,
1578         "expected 0xc483 or 0x08c2 or 0x8dc3, got %04x\n", *(WORD *)context.Eip );
1579     /* segment registers clear the high word */
1580     ok( context.SegCs == LOWORD(expect.SegCs), "wrong SegCs %08x/%08x\n", context.SegCs, expect.SegCs );
1581     ok( context.SegDs == LOWORD(expect.SegDs), "wrong SegDs %08x/%08x\n", context.SegDs, expect.SegDs );
1582     ok( context.SegEs == LOWORD(expect.SegEs), "wrong SegEs %08x/%08x\n", context.SegEs, expect.SegEs );
1583     ok( context.SegFs == LOWORD(expect.SegFs), "wrong SegFs %08x/%08x\n", context.SegFs, expect.SegFs );
1584     ok( context.SegGs == LOWORD(expect.SegGs), "wrong SegGs %08x/%08x\n", context.SegGs, expect.SegGs );
1585     ok( context.SegSs == LOWORD(expect.SegSs), "wrong SegSs %08x/%08x\n", context.SegSs, expect.SegGs );
1586 #undef COMPARE
1587 }
1588 
1589 #elif defined(__x86_64__)
1590 
1591 #define is_wow64 0
1592 
1593 #define UNW_FLAG_NHANDLER  0
1594 #define UNW_FLAG_EHANDLER  1
1595 #define UNW_FLAG_UHANDLER  2
1596 #define UNW_FLAG_CHAININFO 4
1597 
1598 #define UWOP_PUSH_NONVOL     0
1599 #define UWOP_ALLOC_LARGE     1
1600 #define UWOP_ALLOC_SMALL     2
1601 #define UWOP_SET_FPREG       3
1602 #define UWOP_SAVE_NONVOL     4
1603 #define UWOP_SAVE_NONVOL_FAR 5
1604 #define UWOP_SAVE_XMM128     8
1605 #define UWOP_SAVE_XMM128_FAR 9
1606 #define UWOP_PUSH_MACHFRAME  10
1607 
1608 struct results
1609 {
1610     int rip_offset;   /* rip offset from code start */
1611     int rbp_offset;   /* rbp offset from stack pointer */
1612     int handler;      /* expect handler to be set? */
1613     int rip;          /* expected final rip value */
1614     int frame;        /* expected frame return value */
1615     int regs[8][2];   /* expected values for registers */
1616 };
1617 
1618 struct unwind_test
1619 {
1620     const BYTE *function;
1621     size_t function_size;
1622     const BYTE *unwind_info;
1623     const struct results *results;
1624     unsigned int nb_results;
1625 };
1626 
1627 enum regs
1628 {
1629     rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
1630     r8,  r9,  r10, r11, r12, r13, r14, r15
1631 };
1632 
1633 static const char * const reg_names[16] =
1634 {
1635     "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
1636     "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15"
1637 };
1638 
1639 #define UWOP(code,info) (UWOP_##code | ((info) << 4))
1640 
1641 static void call_virtual_unwind( int testnum, const struct unwind_test *test )
1642 {
1643     static const int code_offset = 1024;
1644     static const int unwind_offset = 2048;
1645     void *handler, *data;
1646     CONTEXT context;
1647     RUNTIME_FUNCTION runtime_func;
1648     KNONVOLATILE_CONTEXT_POINTERS ctx_ptr;
1649     UINT i, j, k;
1650     ULONG64 fake_stack[256];
1651     ULONG64 frame, orig_rip, orig_rbp, unset_reg;
1652     UINT unwind_size = 4 + 2 * test->unwind_info[2] + 8;
1653 
1654     memcpy( (char *)code_mem + code_offset, test->function, test->function_size );
1655     memcpy( (char *)code_mem + unwind_offset, test->unwind_info, unwind_size );
1656 
1657     runtime_func.BeginAddress = code_offset;
1658     runtime_func.EndAddress = code_offset + test->function_size;
1659     runtime_func.UnwindData = unwind_offset;
1660 
1661     trace( "code: %p stack: %p\n", code_mem, fake_stack );
1662 
1663     for (i = 0; i < test->nb_results; i++)
1664     {
1665         memset( &ctx_ptr, 0, sizeof(ctx_ptr) );
1666         memset( &context, 0x55, sizeof(context) );
1667         memset( &unset_reg, 0x55, sizeof(unset_reg) );
1668         for (j = 0; j < 256; j++) fake_stack[j] = j * 8;
1669 
1670         context.Rsp = (ULONG_PTR)fake_stack;
1671         context.Rbp = (ULONG_PTR)fake_stack + test->results[i].rbp_offset;
1672         orig_rbp = context.Rbp;
1673         orig_rip = (ULONG64)code_mem + code_offset + test->results[i].rip_offset;
1674 
1675         trace( "%u/%u: rip=%p (%02x) rbp=%p rsp=%p\n", testnum, i,
1676                (void *)orig_rip, *(BYTE *)orig_rip, (void *)orig_rbp, (void *)context.Rsp );
1677 
1678         data = (void *)0xdeadbeef;
1679         handler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, (ULONG64)code_mem, orig_rip,
1680                                     &runtime_func, &context, &data, &frame, &ctx_ptr );
1681         if (test->results[i].handler)
1682         {
1683             ok( (char *)handler == (char *)code_mem + 0x200,
1684                 "%u/%u: wrong handler %p/%p\n", testnum, i, handler, (char *)code_mem + 0x200 );
1685             if (handler) ok( *(DWORD *)data == 0x08070605,
1686                              "%u/%u: wrong handler data %p\n", testnum, i, data );
1687         }
1688         else
1689         {
1690             ok( handler == NULL, "%u/%u: handler %p instead of NULL\n", testnum, i, handler );
1691             ok( data == (void *)0xdeadbeef, "%u/%u: handler data set to %p\n", testnum, i, data );
1692         }
1693 
1694         ok( context.Rip == test->results[i].rip, "%u/%u: wrong rip %p/%x\n",
1695             testnum, i, (void *)context.Rip, test->results[i].rip );
1696         ok( frame == (ULONG64)fake_stack + test->results[i].frame, "%u/%u: wrong frame %p/%p\n",
1697             testnum, i, (void *)frame, (char *)fake_stack + test->results[i].frame );
1698 
1699         for (j = 0; j < 16; j++)
1700         {
1701             static const UINT nb_regs = sizeof(test->results[i].regs) / sizeof(test->results[i].regs[0]);
1702 
1703             for (k = 0; k < nb_regs; k++)
1704             {
1705                 if (test->results[i].regs[k][0] == -1)
1706                 {
1707                     k = nb_regs;
1708                     break;
1709                 }
1710                 if (test->results[i].regs[k][0] == j) break;
1711             }
1712 
1713             if (j == rsp)  /* rsp is special */
1714             {
1715                 ok( !ctx_ptr.u2.IntegerContext[j],
1716                     "%u/%u: rsp should not be set in ctx_ptr\n", testnum, i );
1717                 ok( context.Rsp == (ULONG64)fake_stack + test->results[i].regs[k][1],
1718                     "%u/%u: register rsp wrong %p/%p\n",
1719                     testnum, i, (void *)context.Rsp, (char *)fake_stack + test->results[i].regs[k][1] );
1720                 continue;
1721             }
1722 
1723             if (ctx_ptr.u2.IntegerContext[j])
1724             {
1725                 ok( k < nb_regs, "%u/%u: register %s should not be set to %lx\n",
1726                     testnum, i, reg_names[j], *(&context.Rax + j) );
1727                 if (k < nb_regs)
1728                     ok( *(&context.Rax + j) == test->results[i].regs[k][1],
1729                         "%u/%u: register %s wrong %p/%x\n",
1730                         testnum, i, reg_names[j], (void *)*(&context.Rax + j), test->results[i].regs[k][1] );
1731             }
1732             else
1733             {
1734                 ok( k == nb_regs, "%u/%u: register %s should be set\n", testnum, i, reg_names[j] );
1735                 if (j == rbp)
1736                     ok( context.Rbp == orig_rbp, "%u/%u: register rbp wrong %p/unset\n",
1737                         testnum, i, (void *)context.Rbp );
1738                 else
1739                     ok( *(&context.Rax + j) == unset_reg,
1740                         "%u/%u: register %s wrong %p/unset\n",
1741                         testnum, i, reg_names[j], (void *)*(&context.Rax + j));
1742             }
1743         }
1744     }
1745 }
1746 
1747 static void test_virtual_unwind(void)
1748 {
1749     static const BYTE function_0[] =
1750     {
1751         0xff, 0xf5,                                  /* 00: push %rbp */
1752         0x48, 0x81, 0xec, 0x10, 0x01, 0x00, 0x00,    /* 02: sub $0x110,%rsp */
1753         0x48, 0x8d, 0x6c, 0x24, 0x30,                /* 09: lea 0x30(%rsp),%rbp */
1754         0x48, 0x89, 0x9d, 0xf0, 0x00, 0x00, 0x00,    /* 0e: mov %rbx,0xf0(%rbp) */
1755         0x48, 0x89, 0xb5, 0xf8, 0x00, 0x00, 0x00,    /* 15: mov %rsi,0xf8(%rbp) */
1756         0x90,                                        /* 1c: nop */
1757         0x48, 0x8b, 0x9d, 0xf0, 0x00, 0x00, 0x00,    /* 1d: mov 0xf0(%rbp),%rbx */
1758         0x48, 0x8b, 0xb5, 0xf8, 0x00, 0x00, 0x00,    /* 24: mov 0xf8(%rbp),%rsi */
1759         0x48, 0x8d, 0xa5, 0xe0, 0x00, 0x00, 0x00,    /* 2b: lea 0xe0(%rbp),%rsp */
1760         0x5d,                                        /* 32: pop %rbp */
1761         0xc3                                         /* 33: ret */
1762     };
1763 
1764     static const BYTE unwind_info_0[] =
1765     {
1766         1 | (UNW_FLAG_EHANDLER << 3),  /* version + flags */
1767         0x1c,                          /* prolog size */
1768         8,                             /* opcode count */
1769         (0x03 << 4) | rbp,             /* frame reg rbp offset 0x30 */
1770 
1771         0x1c, UWOP(SAVE_NONVOL, rsi), 0x25, 0, /* 1c: mov %rsi,0x128(%rsp) */
1772         0x15, UWOP(SAVE_NONVOL, rbx), 0x24, 0, /* 15: mov %rbx,0x120(%rsp) */
1773         0x0e, UWOP(SET_FPREG, rbp),            /* 0e: lea 0x30(%rsp),rbp */
1774         0x09, UWOP(ALLOC_LARGE, 0), 0x22, 0,   /* 09: sub $0x110,%rsp */
1775         0x02, UWOP(PUSH_NONVOL, rbp),          /* 02: push %rbp */
1776 
1777         0x00, 0x02, 0x00, 0x00,  /* handler */
1778         0x05, 0x06, 0x07, 0x08,  /* data */
1779     };
1780 
1781     static const struct results results_0[] =
1782     {
1783       /* offset  rbp   handler  rip   frame   registers */
1784         { 0x00,  0x40,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1785         { 0x02,  0x40,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbp,0x000}, {-1,-1} }},
1786         { 0x09,  0x40,  FALSE, 0x118, 0x000, { {rsp,0x120}, {rbp,0x110}, {-1,-1} }},
1787         { 0x0e,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {-1,-1} }},
1788         { 0x15,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {-1,-1} }},
1789         { 0x1c,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1790         { 0x1d,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1791         { 0x24,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1792         { 0x2b,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {-1,-1}}},
1793         { 0x32,  0x40,  FALSE, 0x008, 0x010, { {rsp,0x010}, {rbp,0x000}, {-1,-1}}},
1794         { 0x33,  0x40,  FALSE, 0x000, 0x010, { {rsp,0x008}, {-1,-1}}},
1795     };
1796 
1797 
1798     static const BYTE function_1[] =
1799     {
1800         0x53,                     /* 00: push %rbx */
1801         0x55,                     /* 01: push %rbp */
1802         0x56,                     /* 02: push %rsi */
1803         0x57,                     /* 03: push %rdi */
1804         0x41, 0x54,               /* 04: push %r12 */
1805         0x48, 0x83, 0xec, 0x30,   /* 06: sub $0x30,%rsp */
1806         0x90, 0x90,               /* 0a: nop; nop */
1807         0x48, 0x83, 0xc4, 0x30,   /* 0c: add $0x30,%rsp */
1808         0x41, 0x5c,               /* 10: pop %r12 */
1809         0x5f,                     /* 12: pop %rdi */
1810         0x5e,                     /* 13: pop %rsi */
1811         0x5d,                     /* 14: pop %rbp */
1812         0x5b,                     /* 15: pop %rbx */
1813         0xc3                      /* 16: ret */
1814      };
1815 
1816     static const BYTE unwind_info_1[] =
1817     {
1818         1 | (UNW_FLAG_EHANDLER << 3),  /* version + flags */
1819         0x0a,                          /* prolog size */
1820         6,                             /* opcode count */
1821         0,                             /* frame reg */
1822 
1823         0x0a, UWOP(ALLOC_SMALL, 5),   /* 0a: sub $0x30,%rsp */
1824         0x06, UWOP(PUSH_NONVOL, r12), /* 06: push %r12 */
1825         0x04, UWOP(PUSH_NONVOL, rdi), /* 04: push %rdi */
1826         0x03, UWOP(PUSH_NONVOL, rsi), /* 03: push %rsi */
1827         0x02, UWOP(PUSH_NONVOL, rbp), /* 02: push %rbp */
1828         0x01, UWOP(PUSH_NONVOL, rbx), /* 01: push %rbx */
1829 
1830         0x00, 0x02, 0x00, 0x00,  /* handler */
1831         0x05, 0x06, 0x07, 0x08,  /* data */
1832     };
1833 
1834     static const struct results results_1[] =
1835     {
1836       /* offset  rbp   handler  rip   frame   registers */
1837         { 0x00,  0x50,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1838         { 0x01,  0x50,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbx,0x000}, {-1,-1} }},
1839         { 0x02,  0x50,  FALSE, 0x010, 0x000, { {rsp,0x018}, {rbx,0x008}, {rbp,0x000}, {-1,-1} }},
1840         { 0x03,  0x50,  FALSE, 0x018, 0x000, { {rsp,0x020}, {rbx,0x010}, {rbp,0x008}, {rsi,0x000}, {-1,-1} }},
1841         { 0x04,  0x50,  FALSE, 0x020, 0x000, { {rsp,0x028}, {rbx,0x018}, {rbp,0x010}, {rsi,0x008}, {rdi,0x000}, {-1,-1} }},
1842         { 0x06,  0x50,  FALSE, 0x028, 0x000, { {rsp,0x030}, {rbx,0x020}, {rbp,0x018}, {rsi,0x010}, {rdi,0x008}, {r12,0x000}, {-1,-1} }},
1843         { 0x0a,  0x50,  TRUE,  0x058, 0x000, { {rsp,0x060}, {rbx,0x050}, {rbp,0x048}, {rsi,0x040}, {rdi,0x038}, {r12,0x030}, {-1,-1} }},
1844         { 0x0c,  0x50,  FALSE, 0x058, 0x000, { {rsp,0x060}, {rbx,0x050}, {rbp,0x048}, {rsi,0x040}, {rdi,0x038}, {r12,0x030}, {-1,-1} }},
1845         { 0x10,  0x50,  FALSE, 0x028, 0x000, { {rsp,0x030}, {rbx,0x020}, {rbp,0x018}, {rsi,0x010}, {rdi,0x008}, {r12,0x000}, {-1,-1} }},
1846         { 0x12,  0x50,  FALSE, 0x020, 0x000, { {rsp,0x028}, {rbx,0x018}, {rbp,0x010}, {rsi,0x008}, {rdi,0x000}, {-1,-1} }},
1847         { 0x13,  0x50,  FALSE, 0x018, 0x000, { {rsp,0x020}, {rbx,0x010}, {rbp,0x008}, {rsi,0x000}, {-1,-1} }},
1848         { 0x14,  0x50,  FALSE, 0x010, 0x000, { {rsp,0x018}, {rbx,0x008}, {rbp,0x000}, {-1,-1} }},
1849         { 0x15,  0x50,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbx,0x000}, {-1,-1} }},
1850         { 0x16,  0x50,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1851     };
1852 
1853     static const struct unwind_test tests[] =
1854     {
1855         { function_0, sizeof(function_0), unwind_info_0,
1856           results_0, sizeof(results_0)/sizeof(results_0[0]) },
1857         { function_1, sizeof(function_1), unwind_info_1,
1858           results_1, sizeof(results_1)/sizeof(results_1[0]) }
1859     };
1860     unsigned int i;
1861 
1862     for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
1863         call_virtual_unwind( i, &tests[i] );
1864 }
1865 
1866 static int consolidate_dummy_called;
1867 static PVOID CALLBACK test_consolidate_dummy(EXCEPTION_RECORD *rec)
1868 {
1869     CONTEXT *ctx = (CONTEXT *)rec->ExceptionInformation[1];
1870     consolidate_dummy_called = 1;
1871     ok(ctx->Rip == 0xdeadbeef, "test_consolidate_dummy failed for Rip, expected: 0xdeadbeef, got: %lx\n", ctx->Rip);
1872     return (PVOID)rec->ExceptionInformation[2];
1873 }
1874 
1875 static void test_restore_context(void)
1876 {
1877     SETJMP_FLOAT128 *fltsave;
1878     EXCEPTION_RECORD rec;
1879     _JUMP_BUFFER buf;
1880     CONTEXT ctx;
1881     int i, pass;
1882 
1883     if (!pRtlUnwindEx || !pRtlRestoreContext || !pRtlCaptureContext || !p_setjmp)
1884     {
1885         skip("RtlUnwindEx/RtlCaptureContext/RtlRestoreContext/_setjmp not found\n");
1886         return;
1887     }
1888 
1889     /* RtlRestoreContext(NULL, NULL); crashes on Windows */
1890 
1891     /* test simple case of capture and restore context */
1892     pass = 0;
1893     InterlockedIncrement(&pass); /* interlocked to prevent compiler from moving after capture */
1894     pRtlCaptureContext(&ctx);
1895     if (InterlockedIncrement(&pass) == 2) /* interlocked to prevent compiler from moving before capture */
1896     {
1897         pRtlRestoreContext(&ctx, NULL);
1898         ok(0, "shouldn't be reached\n");
1899     }
1900     else
1901         ok(pass < 4, "unexpected pass %d\n", pass);
1902 
1903     /* test with jmp using RltRestoreContext */
1904     pass = 0;
1905     InterlockedIncrement(&pass);
1906     RtlCaptureContext(&ctx);
1907     InterlockedIncrement(&pass); /* only called once */
1908     p_setjmp(&buf);
1909     InterlockedIncrement(&pass);
1910     if (pass == 3)
1911     {
1912         rec.ExceptionCode = STATUS_LONGJUMP;
1913         rec.NumberParameters = 1;
1914         rec.ExceptionInformation[0] = (DWORD64)&buf;
1915 
1916         /* uses buf.Rip instead of ctx.Rip */
1917         pRtlRestoreContext(&ctx, &rec);
1918         ok(0, "shouldn't be reached\n");
1919     }
1920     else if (pass == 4)
1921     {
1922         ok(buf.Rbx == ctx.Rbx, "longjmp failed for Rbx, expected: %lx, got: %lx\n", buf.Rbx, ctx.Rbx);
1923         ok(buf.Rsp == ctx.Rsp, "longjmp failed for Rsp, expected: %lx, got: %lx\n", buf.Rsp, ctx.Rsp);
1924         ok(buf.Rbp == ctx.Rbp, "longjmp failed for Rbp, expected: %lx, got: %lx\n", buf.Rbp, ctx.Rbp);
1925         ok(buf.Rsi == ctx.Rsi, "longjmp failed for Rsi, expected: %lx, got: %lx\n", buf.Rsi, ctx.Rsi);
1926         ok(buf.Rdi == ctx.Rdi, "longjmp failed for Rdi, expected: %lx, got: %lx\n", buf.Rdi, ctx.Rdi);
1927         ok(buf.R12 == ctx.R12, "longjmp failed for R12, expected: %lx, got: %lx\n", buf.R12, ctx.R12);
1928         ok(buf.R13 == ctx.R13, "longjmp failed for R13, expected: %lx, got: %lx\n", buf.R13, ctx.R13);
1929         ok(buf.R14 == ctx.R14, "longjmp failed for R14, expected: %lx, got: %lx\n", buf.R14, ctx.R14);
1930         ok(buf.R15 == ctx.R15, "longjmp failed for R15, expected: %lx, got: %lx\n", buf.R15, ctx.R15);
1931 
1932         fltsave = &buf.Xmm6;
1933         for (i = 0; i < 10; i++)
1934         {
1935             ok(fltsave[i].Part[0] == ctx.u.FltSave.XmmRegisters[i + 6].Low,
1936                 "longjmp failed for Xmm%d, expected %lx, got %lx\n", i + 6,
1937                 fltsave[i].Part[0], ctx.u.FltSave.XmmRegisters[i + 6].Low);
1938 
1939             ok(fltsave[i].Part[1] == ctx.u.FltSave.XmmRegisters[i + 6].High,
1940                 "longjmp failed for Xmm%d, expected %lx, got %lx\n", i + 6,
1941                 fltsave[i].Part[1], ctx.u.FltSave.XmmRegisters[i + 6].High);
1942         }
1943     }
1944     else
1945         ok(0, "unexpected pass %d\n", pass);
1946 
1947     /* test with jmp through RtlUnwindEx */
1948     pass = 0;
1949     InterlockedIncrement(&pass);
1950     pRtlCaptureContext(&ctx);
1951     InterlockedIncrement(&pass); /* only called once */
1952     p_setjmp(&buf);
1953     InterlockedIncrement(&pass);
1954     if (pass == 3)
1955     {
1956         rec.ExceptionCode = STATUS_LONGJUMP;
1957         rec.NumberParameters = 1;
1958         rec.ExceptionInformation[0] = (DWORD64)&buf;
1959 
1960         /* uses buf.Rip instead of bogus 0xdeadbeef */
1961         pRtlUnwindEx((void*)buf.Rsp, (void*)0xdeadbeef, &rec, NULL, &ctx, NULL);
1962         ok(0, "shouldn't be reached\n");
1963     }
1964     else
1965         ok(pass == 4, "unexpected pass %d\n", pass);
1966 
1967 
1968     /* test with consolidate */
1969     pass = 0;
1970     InterlockedIncrement(&pass);
1971     RtlCaptureContext(&ctx);
1972     InterlockedIncrement(&pass);
1973     if (pass == 2)
1974     {
1975         rec.ExceptionCode = STATUS_UNWIND_CONSOLIDATE;
1976         rec.NumberParameters = 3;
1977         rec.ExceptionInformation[0] = (DWORD64)test_consolidate_dummy;
1978         rec.ExceptionInformation[1] = (DWORD64)&ctx;
1979         rec.ExceptionInformation[2] = ctx.Rip;
1980         ctx.Rip = 0xdeadbeef;
1981 
1982         pRtlRestoreContext(&ctx, &rec);
1983         ok(0, "shouldn't be reached\n");
1984     }
1985     else if (pass == 3)
1986         ok(consolidate_dummy_called, "test_consolidate_dummy not called\n");
1987     else
1988         ok(0, "unexpected pass %d\n", pass);
1989 }
1990 
1991 static RUNTIME_FUNCTION* CALLBACK dynamic_unwind_callback( DWORD64 pc, PVOID context )
1992 {
1993     static const int code_offset = 1024;
1994     static RUNTIME_FUNCTION runtime_func;
1995     (*(DWORD *)context)++;
1996 
1997     runtime_func.BeginAddress = code_offset + 16;
1998     runtime_func.EndAddress   = code_offset + 32;
1999     runtime_func.UnwindData   = 0;
2000     return &runtime_func;
2001 }
2002 
2003 static void test_dynamic_unwind(void)
2004 {
2005     static const int code_offset = 1024;
2006     char buf[sizeof(RUNTIME_FUNCTION) + 4];
2007     RUNTIME_FUNCTION *runtime_func, *func;
2008     ULONG_PTR table, base;
2009     DWORD count;
2010 
2011     /* Test RtlAddFunctionTable with aligned RUNTIME_FUNCTION pointer */
2012     runtime_func = (RUNTIME_FUNCTION *)buf;
2013     runtime_func->BeginAddress = code_offset;
2014     runtime_func->EndAddress   = code_offset + 16;
2015     runtime_func->UnwindData   = 0;
2016     ok( pRtlAddFunctionTable( runtime_func, 1, (ULONG_PTR)code_mem ),
2017         "RtlAddFunctionTable failed for runtime_func = %p (aligned)\n", runtime_func );
2018 
2019     /* Lookup function outside of any function table */
2020     base = 0xdeadbeef;
2021     func = pRtlLookupFunctionEntry( (ULONG_PTR)code_mem + code_offset + 16, &base, NULL );
2022     ok( func == NULL,
2023         "RtlLookupFunctionEntry returned unexpected function, expected: NULL, got: %p\n", func );
2024     ok( !base || broken(base == 0xdeadbeef),
2025         "RtlLookupFunctionEntry modified base address, expected: 0, got: %lx\n", base );
2026 
2027     /* Test with pointer inside of our function */
2028     base = 0xdeadbeef;
2029     func = pRtlLookupFunctionEntry( (ULONG_PTR)code_mem + code_offset + 8, &base, NULL );
2030     ok( func == runtime_func,
2031         "RtlLookupFunctionEntry didn't return expected function, expected: %p, got: %p\n", runtime_func, func );
2032     ok( base == (ULONG_PTR)code_mem,
2033         "RtlLookupFunctionEntry returned invalid base, expected: %lx, got: %lx\n", (ULONG_PTR)code_mem, base );
2034 
2035     /* Test RtlDeleteFunctionTable */
2036     ok( pRtlDeleteFunctionTable( runtime_func ),
2037         "RtlDeleteFunctionTable failed for runtime_func = %p (aligned)\n", runtime_func );
2038     ok( !pRtlDeleteFunctionTable( runtime_func ),
2039         "RtlDeleteFunctionTable returned success for nonexistent table runtime_func = %p\n", runtime_func );
2040 
2041     /* Unaligned RUNTIME_FUNCTION pointer */
2042     runtime_func = (RUNTIME_FUNCTION *)((ULONG_PTR)buf | 0x3);
2043     runtime_func->BeginAddress = code_offset;
2044     runtime_func->EndAddress   = code_offset + 16;
2045     runtime_func->UnwindData   = 0;
2046     ok( pRtlAddFunctionTable( runtime_func, 1, (ULONG_PTR)code_mem ),
2047         "RtlAddFunctionTable failed for runtime_func = %p (unaligned)\n", runtime_func );
2048     ok( pRtlDeleteFunctionTable( runtime_func ),
2049         "RtlDeleteFunctionTable failed for runtime_func = %p (unaligned)\n", runtime_func );
2050 
2051     /* Attempt to insert the same entry twice */
2052     runtime_func = (RUNTIME_FUNCTION *)buf;
2053     runtime_func->BeginAddress = code_offset;
2054     runtime_func->EndAddress   = code_offset + 16;
2055     runtime_func->UnwindData   = 0;
2056     ok( pRtlAddFunctionTable( runtime_func, 1, (ULONG_PTR)code_mem ),
2057         "RtlAddFunctionTable failed for runtime_func = %p (first attempt)\n", runtime_func );
2058     ok( pRtlAddFunctionTable( runtime_func, 1, (ULONG_PTR)code_mem ),
2059         "RtlAddFunctionTable failed for runtime_func = %p (second attempt)\n", runtime_func );
2060     ok( pRtlDeleteFunctionTable( runtime_func ),
2061         "RtlDeleteFunctionTable failed for runtime_func = %p (first attempt)\n", runtime_func );
2062     ok( pRtlDeleteFunctionTable( runtime_func ),
2063         "RtlDeleteFunctionTable failed for runtime_func = %p (second attempt)\n", runtime_func );
2064     ok( !pRtlDeleteFunctionTable( runtime_func ),
2065         "RtlDeleteFunctionTable returned success for nonexistent table runtime_func = %p\n", runtime_func );
2066 
2067     /* Test RtlInstallFunctionTableCallback with both low bits unset */
2068     table = (ULONG_PTR)code_mem;
2069     ok( !pRtlInstallFunctionTableCallback( table, (ULONG_PTR)code_mem, code_offset + 32, &dynamic_unwind_callback, (PVOID*)&count, NULL ),
2070         "RtlInstallFunctionTableCallback returned success for table = %lx\n", table );
2071 
2072     /* Test RtlInstallFunctionTableCallback with both low bits set */
2073     table = (ULONG_PTR)code_mem | 0x3;
2074     ok( pRtlInstallFunctionTableCallback( table, (ULONG_PTR)code_mem, code_offset + 32, &dynamic_unwind_callback, (PVOID*)&count, NULL ),
2075         "RtlInstallFunctionTableCallback failed for table = %lx\n", table );
2076 
2077     /* Lookup function outside of any function table */
2078     count = 0;
2079     base = 0xdeadbeef;
2080     func = pRtlLookupFunctionEntry( (ULONG_PTR)code_mem + code_offset + 32, &base, NULL );
2081     ok( func == NULL,
2082         "RtlLookupFunctionEntry returned unexpected function, expected: NULL, got: %p\n", func );
2083     ok( !base || broken(base == 0xdeadbeef),
2084         "RtlLookupFunctionEntry modified base address, expected: 0, got: %lx\n", base );
2085     ok( !count,
2086         "RtlLookupFunctionEntry issued %d unexpected calls to dynamic_unwind_callback\n", count );
2087 
2088     /* Test with pointer inside of our function */
2089     count = 0;
2090     base = 0xdeadbeef;
2091     func = pRtlLookupFunctionEntry( (ULONG_PTR)code_mem + code_offset + 24, &base, NULL );
2092     ok( func != NULL && func->BeginAddress == code_offset + 16 && func->EndAddress == code_offset + 32,
2093         "RtlLookupFunctionEntry didn't return expected function, got: %p\n", func );
2094     ok( base == (ULONG_PTR)code_mem,
2095         "RtlLookupFunctionEntry returned invalid base, expected: %lx, got: %lx\n", (ULONG_PTR)code_mem, base );
2096     ok( count == 1,
2097         "RtlLookupFunctionEntry issued %d calls to dynamic_unwind_callback, expected: 1\n", count );
2098 
2099     /* Clean up again */
2100     ok( pRtlDeleteFunctionTable( (PRUNTIME_FUNCTION)table ),
2101         "RtlDeleteFunctionTable failed for table = %p\n", (PVOID)table );
2102     ok( !pRtlDeleteFunctionTable( (PRUNTIME_FUNCTION)table ),
2103         "RtlDeleteFunctionTable returned success for nonexistent table = %p\n", (PVOID)table );
2104 
2105 }
2106 
2107 static int termination_handler_called;
2108 static void WINAPI termination_handler(ULONG flags, ULONG64 frame)
2109 {
2110     termination_handler_called++;
2111 
2112     ok(flags == 1 || broken(flags == 0x401), "flags = %x\n", flags);
2113     ok(frame == 0x1234, "frame = %p\n", (void*)frame);
2114 }
2115 
2116 static void test___C_specific_handler(void)
2117 {
2118     DISPATCHER_CONTEXT dispatch;
2119     EXCEPTION_RECORD rec;
2120     CONTEXT context;
2121     ULONG64 frame;
2122     EXCEPTION_DISPOSITION ret;
2123     SCOPE_TABLE scope_table;
2124 
2125     if (!p__C_specific_handler)
2126     {
2127         win_skip("__C_specific_handler not available\n");
2128         return;
2129     }
2130 
2131     memset(&rec, 0, sizeof(rec));
2132     rec.ExceptionFlags = 2; /* EH_UNWINDING */
2133     frame = 0x1234;
2134     memset(&dispatch, 0, sizeof(dispatch));
2135     dispatch.ImageBase = (ULONG_PTR)GetModuleHandleA(NULL);
2136     dispatch.ControlPc = dispatch.ImageBase + 0x200;
2137     dispatch.HandlerData = &scope_table;
2138     dispatch.ContextRecord = &context;
2139     scope_table.Count = 1;
2140     scope_table.ScopeRecord[0].BeginAddress = 0x200;
2141     scope_table.ScopeRecord[0].EndAddress = 0x400;
2142     scope_table.ScopeRecord[0].HandlerAddress = (ULONG_PTR)termination_handler-dispatch.ImageBase;
2143     scope_table.ScopeRecord[0].JumpTarget = 0;
2144     memset(&context, 0, sizeof(context));
2145 
2146     termination_handler_called = 0;
2147     ret = p__C_specific_handler(&rec, frame, &context, &dispatch);
2148     ok(ret == ExceptionContinueSearch, "__C_specific_handler returned %x\n", ret);
2149     ok(termination_handler_called == 1, "termination_handler_called = %d\n",
2150             termination_handler_called);
2151     ok(dispatch.ScopeIndex == 1, "dispatch.ScopeIndex = %d\n", dispatch.ScopeIndex);
2152 
2153     ret = p__C_specific_handler(&rec, frame, &context, &dispatch);
2154     ok(ret == ExceptionContinueSearch, "__C_specific_handler returned %x\n", ret);
2155     ok(termination_handler_called == 1, "termination_handler_called = %d\n",
2156             termination_handler_called);
2157     ok(dispatch.ScopeIndex == 1, "dispatch.ScopeIndex = %d\n", dispatch.ScopeIndex);
2158 }
2159 
2160 #endif  /* __x86_64__ */
2161 
2162 #if defined(__i386__) || defined(__x86_64__)
2163 
2164 static DWORD WINAPI register_check_thread(void *arg)
2165 {
2166     NTSTATUS status;
2167     CONTEXT ctx;
2168 
2169     memset(&ctx, 0, sizeof(ctx));
2170     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2171 
2172     status = pNtGetContextThread(GetCurrentThread(), &ctx);
2173     ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %x\n", status);
2174     ok(!ctx.Dr0, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr0);
2175     ok(!ctx.Dr1, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr1);
2176     ok(!ctx.Dr2, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr2);
2177     ok(!ctx.Dr3, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr3);
2178     ok(!ctx.Dr6, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr6);
2179     ok(!ctx.Dr7, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr7);
2180 
2181     return 0;
2182 }
2183 
2184 static void test_debug_registers(void)
2185 {
2186     static const struct
2187     {
2188         ULONG_PTR dr0, dr1, dr2, dr3, dr6, dr7;
2189     }
2190     tests[] =
2191     {
2192         { 0x42424240, 0, 0x126bb070, 0x0badbad0, 0, 0xffff0115 },
2193         { 0x42424242, 0, 0x100f0fe7, 0x0abebabe, 0, 0x115 },
2194     };
2195     NTSTATUS status;
2196     CONTEXT ctx;
2197     HANDLE thread;
2198     int i;
2199 
2200     for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
2201     {
2202         memset(&ctx, 0, sizeof(ctx));
2203         ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2204         ctx.Dr0 = tests[i].dr0;
2205         ctx.Dr1 = tests[i].dr1;
2206         ctx.Dr2 = tests[i].dr2;
2207         ctx.Dr3 = tests[i].dr3;
2208         ctx.Dr6 = tests[i].dr6;
2209         ctx.Dr7 = tests[i].dr7;
2210 
2211         status = pNtSetContextThread(GetCurrentThread(), &ctx);
2212         ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %08x\n", status);
2213 
2214         memset(&ctx, 0, sizeof(ctx));
2215         ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2216 
2217         status = pNtGetContextThread(GetCurrentThread(), &ctx);
2218         ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %08x\n", status);
2219         ok(ctx.Dr0 == tests[i].dr0, "test %d: expected %lx, got %lx\n", i, tests[i].dr0, (DWORD_PTR)ctx.Dr0);
2220         ok(ctx.Dr1 == tests[i].dr1, "test %d: expected %lx, got %lx\n", i, tests[i].dr1, (DWORD_PTR)ctx.Dr1);
2221         ok(ctx.Dr2 == tests[i].dr2, "test %d: expected %lx, got %lx\n", i, tests[i].dr2, (DWORD_PTR)ctx.Dr2);
2222         ok(ctx.Dr3 == tests[i].dr3, "test %d: expected %lx, got %lx\n", i, tests[i].dr3, (DWORD_PTR)ctx.Dr3);
2223         ok((ctx.Dr6 &  0xf00f) == tests[i].dr6, "test %d: expected %lx, got %lx\n", i, tests[i].dr6, (DWORD_PTR)ctx.Dr6);
2224         ok((ctx.Dr7 & ~0xdc00) == tests[i].dr7, "test %d: expected %lx, got %lx\n", i, tests[i].dr7, (DWORD_PTR)ctx.Dr7);
2225     }
2226 
2227     memset(&ctx, 0, sizeof(ctx));
2228     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2229     ctx.Dr0 = 0xffffffff;
2230     ctx.Dr1 = 0xffffffff;
2231     ctx.Dr2 = 0xffffffff;
2232     ctx.Dr3 = 0xffffffff;
2233     ctx.Dr6 = 0xffffffff;
2234     ctx.Dr7 = 0x00000400;
2235     status = pNtSetContextThread(GetCurrentThread(), &ctx);
2236     ok(status == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", status);
2237 
2238     thread = CreateThread(NULL, 0, register_check_thread, NULL, CREATE_SUSPENDED, NULL);
2239     ok(thread != INVALID_HANDLE_VALUE, "CreateThread failed with %d\n", GetLastError());
2240 
2241     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
2242     status = pNtGetContextThread(thread, &ctx);
2243     ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %x\n", status);
2244     ok(!ctx.Dr0, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr0);
2245     ok(!ctx.Dr1, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr1);
2246     ok(!ctx.Dr2, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr2);
2247     ok(!ctx.Dr3, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr3);
2248     ok(!ctx.Dr6, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr6);
2249     ok(!ctx.Dr7, "expected 0, got %lx\n", (DWORD_PTR)ctx.Dr7);
2250 
2251     ResumeThread(thread);
2252     WaitForSingleObject(thread, 10000);
2253     CloseHandle(thread);
2254 }
2255 
2256 static DWORD outputdebugstring_exceptions;
2257 
2258 static LONG CALLBACK outputdebugstring_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
2259 {
2260     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
2261     trace("vect. handler %08x addr:%p\n", rec->ExceptionCode, rec->ExceptionAddress);
2262 
2263     ok(rec->ExceptionCode == DBG_PRINTEXCEPTION_C, "ExceptionCode is %08x instead of %08x\n",
2264         rec->ExceptionCode, DBG_PRINTEXCEPTION_C);
2265     ok(rec->NumberParameters == 2, "ExceptionParameters is %d instead of 2\n", rec->NumberParameters);
2266     ok(rec->ExceptionInformation[0] == 12, "ExceptionInformation[0] = %d instead of 12\n", (DWORD)rec->ExceptionInformation[0]);
2267     ok(!strcmp((char *)rec->ExceptionInformation[1], "Hello World"),
2268         "ExceptionInformation[1] = '%s' instead of 'Hello World'\n", (char *)rec->ExceptionInformation[1]);
2269 
2270     outputdebugstring_exceptions++;
2271     return EXCEPTION_CONTINUE_SEARCH;
2272 }
2273 
2274 static void test_outputdebugstring(DWORD numexc)
2275 {
2276     PVOID vectored_handler;
2277 
2278     if (!pRtlAddVectoredExceptionHandler || !pRtlRemoveVectoredExceptionHandler)
2279     {
2280         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler not found\n");
2281         return;
2282     }
2283 
2284     vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &outputdebugstring_vectored_handler);
2285     ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
2286 
2287     outputdebugstring_exceptions = 0;
2288     OutputDebugStringA("Hello World");
2289 
2290     ok(outputdebugstring_exceptions == numexc, "OutputDebugStringA generated %d exceptions, expected %d\n",
2291        outputdebugstring_exceptions, numexc);
2292 
2293     pRtlRemoveVectoredExceptionHandler(vectored_handler);
2294 }
2295 
2296 static DWORD ripevent_exceptions;
2297 
2298 static LONG CALLBACK ripevent_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
2299 {
2300     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
2301     trace("vect. handler %08x addr:%p\n", rec->ExceptionCode, rec->ExceptionAddress);
2302 
2303     ok(rec->ExceptionCode == DBG_RIPEXCEPTION, "ExceptionCode is %08x instead of %08x\n",
2304        rec->ExceptionCode, DBG_RIPEXCEPTION);
2305     ok(rec->NumberParameters == 2, "ExceptionParameters is %d instead of 2\n", rec->NumberParameters);
2306     ok(rec->ExceptionInformation[0] == 0x11223344, "ExceptionInformation[0] = %08x instead of %08x\n",
2307        (NTSTATUS)rec->ExceptionInformation[0], 0x11223344);
2308     ok(rec->ExceptionInformation[1] == 0x55667788, "ExceptionInformation[1] = %08x instead of %08x\n",
2309        (NTSTATUS)rec->ExceptionInformation[1], 0x55667788);
2310 
2311     ripevent_exceptions++;
2312     return (rec->ExceptionCode == DBG_RIPEXCEPTION) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
2313 }
2314 
2315 static void test_ripevent(DWORD numexc)
2316 {
2317     EXCEPTION_RECORD record;
2318     PVOID vectored_handler;
2319 
2320     if (!pRtlAddVectoredExceptionHandler || !pRtlRemoveVectoredExceptionHandler || !pRtlRaiseException)
2321     {
2322         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler or RtlRaiseException not found\n");
2323         return;
2324     }
2325 
2326     vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &ripevent_vectored_handler);
2327     ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
2328 
2329     record.ExceptionCode = DBG_RIPEXCEPTION;
2330     record.ExceptionFlags = 0;
2331     record.ExceptionRecord = NULL;
2332     record.ExceptionAddress = NULL;
2333     record.NumberParameters = 2;
2334     record.ExceptionInformation[0] = 0x11223344;
2335     record.ExceptionInformation[1] = 0x55667788;
2336 
2337     ripevent_exceptions = 0;
2338     pRtlRaiseException(&record);
2339     ok(ripevent_exceptions == numexc, "RtlRaiseException generated %d exceptions, expected %d\n",
2340        ripevent_exceptions, numexc);
2341 
2342     pRtlRemoveVectoredExceptionHandler(vectored_handler);
2343 }
2344 
2345 static DWORD debug_service_exceptions;
2346 
2347 static LONG CALLBACK debug_service_handler(EXCEPTION_POINTERS *ExceptionInfo)
2348 {
2349     EXCEPTION_RECORD *rec = ExceptionInfo->ExceptionRecord;
2350     trace("vect. handler %08x addr:%p\n", rec->ExceptionCode, rec->ExceptionAddress);
2351 
2352     ok(rec->ExceptionCode == EXCEPTION_BREAKPOINT, "ExceptionCode is %08x instead of %08x\n",
2353        rec->ExceptionCode, EXCEPTION_BREAKPOINT);
2354 
2355 #ifdef __i386__
2356     ok(ExceptionInfo->ContextRecord->Eip == (DWORD)code_mem + 0x1c,
2357        "expected Eip = %x, got %x\n", (DWORD)code_mem + 0x1c, ExceptionInfo->ContextRecord->Eip);
2358     ok(rec->NumberParameters == (is_wow64 ? 1 : 3),
2359        "ExceptionParameters is %d instead of %d\n", rec->NumberParameters, is_wow64 ? 1 : 3);
2360     ok(rec->ExceptionInformation[0] == ExceptionInfo->ContextRecord->Eax,
2361        "expected ExceptionInformation[0] = %x, got %lx\n",
2362        ExceptionInfo->ContextRecord->Eax, rec->ExceptionInformation[0]);
2363     if (!is_wow64)
2364     {
2365         ok(rec->ExceptionInformation[1] == 0x11111111,
2366            "got ExceptionInformation[1] = %lx\n", rec->ExceptionInformation[1]);
2367         ok(rec->ExceptionInformation[2] == 0x22222222,
2368            "got ExceptionInformation[2] = %lx\n", rec->ExceptionInformation[2]);
2369     }
2370 #else
2371     ok(ExceptionInfo->ContextRecord->Rip == (DWORD_PTR)code_mem + 0x2f,
2372        "expected Rip = %lx, got %lx\n", (DWORD_PTR)code_mem + 0x2f, ExceptionInfo->ContextRecord->Rip);
2373     ok(rec->NumberParameters == 1,
2374        "ExceptionParameters is %d instead of 1\n", rec->NumberParameters);
2375     ok(rec->ExceptionInformation[0] == ExceptionInfo->ContextRecord->Rax,
2376        "expected ExceptionInformation[0] = %lx, got %lx\n",
2377        ExceptionInfo->ContextRecord->Rax, rec->ExceptionInformation[0]);
2378 #endif
2379 
2380     debug_service_exceptions++;
2381     return (rec->ExceptionCode == EXCEPTION_BREAKPOINT) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
2382 }
2383 
2384 #ifdef __i386__
2385 
2386 static const BYTE call_debug_service_code[] = {
2387     0x53,                         /* pushl %ebx */
2388     0x57,                         /* pushl %edi */
2389     0x8b, 0x44, 0x24, 0x0c,       /* movl 12(%esp),%eax */
2390     0xb9, 0x11, 0x11, 0x11, 0x11, /* movl $0x11111111,%ecx */
2391     0xba, 0x22, 0x22, 0x22, 0x22, /* movl $0x22222222,%edx */
2392     0xbb, 0x33, 0x33, 0x33, 0x33, /* movl $0x33333333,%ebx */
2393     0xbf, 0x44, 0x44, 0x44, 0x44, /* movl $0x44444444,%edi */
2394     0xcd, 0x2d,                   /* int $0x2d */
2395     0xeb,                         /* jmp $+17 */
2396     0x0f, 0x1f, 0x00,             /* nop */
2397     0x31, 0xc0,                   /* xorl %eax,%eax */
2398     0xeb, 0x0c,                   /* jmp $+14 */
2399     0x90, 0x90, 0x90, 0x90,       /* nop */
2400     0x90, 0x90, 0x90, 0x90,
2401     0x90,
2402     0x31, 0xc0,                   /* xorl %eax,%eax */
2403     0x40,                         /* incl %eax */
2404     0x5f,                         /* popl %edi */
2405     0x5b,                         /* popl %ebx */
2406     0xc3,                         /* ret */
2407 };
2408 
2409 #else
2410 
2411 static const BYTE call_debug_service_code[] = {
2412     0x53,                         /* push %rbx */
2413     0x57,                         /* push %rdi */
2414     0x48, 0x89, 0xc8,             /* movl %rcx,%rax */
2415     0x48, 0xb9, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, /* movabs $0x1111111111111111,%rcx */
2416     0x48, 0xba, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* movabs $0x2222222222222222,%rdx */
2417     0x48, 0xbb, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, /* movabs $0x3333333333333333,%rbx */
2418     0x48, 0xbf, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, /* movabs $0x4444444444444444,%rdi */
2419     0xcd, 0x2d,                   /* int $0x2d */
2420     0xeb,                         /* jmp $+17 */
2421     0x0f, 0x1f, 0x00,             /* nop */
2422     0x48, 0x31, 0xc0,             /* xor %rax,%rax */
2423     0xeb, 0x0e,                   /* jmp $+16 */
2424     0x90, 0x90, 0x90, 0x90,       /* nop */
2425     0x90, 0x90, 0x90, 0x90,
2426     0x48, 0x31, 0xc0,             /* xor %rax,%rax */
2427     0x48, 0xff, 0xc0,             /* inc %rax */
2428     0x5f,                         /* pop %rdi */
2429     0x5b,                         /* pop %rbx */
2430     0xc3,                         /* ret */
2431 };
2432 
2433 #endif
2434 
2435 static void test_debug_service(DWORD numexc)
2436 {
2437     DWORD (CDECL *func)(DWORD_PTR) = code_mem;
2438     DWORD expected_exc, expected_ret;
2439     void *vectored_handler;
2440     DWORD ret;
2441 
2442     /* code will return 0 if execution resumes immediately after "int $0x2d", otherwise 1 */
2443     memcpy(code_mem, call_debug_service_code, sizeof(call_debug_service_code));
2444 
2445     vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &debug_service_handler);
2446     ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
2447 
2448     expected_exc = numexc;
2449     expected_ret = (numexc != 0);
2450 
2451     /* BREAKPOINT_BREAK */
2452     debug_service_exceptions = 0;
2453     ret = func(0);
2454     ok(debug_service_exceptions == expected_exc,
2455        "BREAKPOINT_BREAK generated %u exceptions, expected %u\n",
2456        debug_service_exceptions, expected_exc);
2457     ok(ret == expected_ret,
2458        "BREAKPOINT_BREAK returned %u, expected %u\n", ret, expected_ret);
2459 
2460     /* BREAKPOINT_PROMPT */
2461     debug_service_exceptions = 0;
2462     ret = func(2);
2463     ok(debug_service_exceptions == expected_exc,
2464        "BREAKPOINT_PROMPT generated %u exceptions, expected %u\n",
2465        debug_service_exceptions, expected_exc);
2466     ok(ret == expected_ret,
2467        "BREAKPOINT_PROMPT returned %u, expected %u\n", ret, expected_ret);
2468 
2469     /* invalid debug service */
2470     debug_service_exceptions = 0;
2471     ret = func(6);
2472     ok(debug_service_exceptions == expected_exc,
2473        "invalid debug service generated %u exceptions, expected %u\n",
2474        debug_service_exceptions, expected_exc);
2475     ok(ret == expected_ret,
2476       "invalid debug service returned %u, expected %u\n", ret, expected_ret);
2477 
2478     expected_exc = (is_wow64 ? numexc : 0);
2479     expected_ret = (is_wow64 && numexc);
2480 
2481     /* BREAKPOINT_PRINT */
2482     debug_service_exceptions = 0;
2483     ret = func(1);
2484     ok(debug_service_exceptions == expected_exc,
2485        "BREAKPOINT_PRINT generated %u exceptions, expected %u\n",
2486        debug_service_exceptions, expected_exc);
2487     ok(ret == expected_ret,
2488        "BREAKPOINT_PRINT returned %u, expected %u\n", ret, expected_ret);
2489 
2490     /* BREAKPOINT_LOAD_SYMBOLS */
2491     debug_service_exceptions = 0;
2492     ret = func(3);
2493     ok(debug_service_exceptions == expected_exc,
2494        "BREAKPOINT_LOAD_SYMBOLS generated %u exceptions, expected %u\n",
2495        debug_service_exceptions, expected_exc);
2496     ok(ret == expected_ret,
2497        "BREAKPOINT_LOAD_SYMBOLS returned %u, expected %u\n", ret, expected_ret);
2498 
2499     /* BREAKPOINT_UNLOAD_SYMBOLS */
2500     debug_service_exceptions = 0;
2501     ret = func(4);
2502     ok(debug_service_exceptions == expected_exc,
2503        "BREAKPOINT_UNLOAD_SYMBOLS generated %u exceptions, expected %u\n",
2504        debug_service_exceptions, expected_exc);
2505     ok(ret == expected_ret,
2506        "BREAKPOINT_UNLOAD_SYMBOLS returned %u, expected %u\n", ret, expected_ret);
2507 
2508     /* BREAKPOINT_COMMAND_STRING */
2509     debug_service_exceptions = 0;
2510     ret = func(5);
2511     ok(debug_service_exceptions == expected_exc || broken(debug_service_exceptions == numexc),
2512        "BREAKPOINT_COMMAND_STRING generated %u exceptions, expected %u\n",
2513        debug_service_exceptions, expected_exc);
2514     ok(ret == expected_ret || broken(ret == (numexc != 0)),
2515        "BREAKPOINT_COMMAND_STRING returned %u, expected %u\n", ret, expected_ret);
2516 
2517     pRtlRemoveVectoredExceptionHandler(vectored_handler);
2518 }
2519 
2520 static DWORD breakpoint_exceptions;
2521 
2522 static LONG CALLBACK breakpoint_handler(EXCEPTION_POINTERS *ExceptionInfo)
2523 {
2524     EXCEPTION_RECORD *rec = ExceptionInfo->ExceptionRecord;
2525     trace("vect. handler %08x addr:%p\n", rec->ExceptionCode, rec->ExceptionAddress);
2526 
2527     ok(rec->ExceptionCode == EXCEPTION_BREAKPOINT, "ExceptionCode is %08x instead of %08x\n",
2528        rec->ExceptionCode, EXCEPTION_BREAKPOINT);
2529 
2530 #ifdef __i386__
2531     ok(ExceptionInfo->ContextRecord->Eip == (DWORD)code_mem + 1,
2532        "expected Eip = %x, got %x\n", (DWORD)code_mem + 1, ExceptionInfo->ContextRecord->Eip);
2533     ok(rec->NumberParameters == (is_wow64 ? 1 : 3),
2534        "ExceptionParameters is %d instead of %d\n", rec->NumberParameters, is_wow64 ? 1 : 3);
2535     ok(rec->ExceptionInformation[0] == 0,
2536        "got ExceptionInformation[0] = %lx\n", rec->ExceptionInformation[0]);
2537     ExceptionInfo->ContextRecord->Eip = (DWORD)code_mem + 2;
2538 #else
2539     ok(ExceptionInfo->ContextRecord->Rip == (DWORD_PTR)code_mem + 1,
2540        "expected Rip = %lx, got %lx\n", (DWORD_PTR)code_mem + 1, ExceptionInfo->ContextRecord->Rip);
2541     ok(rec->NumberParameters == 1,
2542        "ExceptionParameters is %d instead of 1\n", rec->NumberParameters);
2543     ok(rec->ExceptionInformation[0] == 0,
2544        "got ExceptionInformation[0] = %lx\n", rec->ExceptionInformation[0]);
2545     ExceptionInfo->ContextRecord->Rip = (DWORD_PTR)code_mem + 2;
2546 #endif
2547 
2548     breakpoint_exceptions++;
2549     return (rec->ExceptionCode == EXCEPTION_BREAKPOINT) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
2550 }
2551 
2552 static const BYTE breakpoint_code[] = {
2553     0xcd, 0x03,                   /* int $0x3 */
2554     0xc3,                         /* ret */
2555 };
2556 
2557 static void test_breakpoint(DWORD numexc)
2558 {
2559     DWORD (CDECL *func)(void) = code_mem;
2560     void *vectored_handler;
2561 
2562     memcpy(code_mem, breakpoint_code, sizeof(breakpoint_code));
2563 
2564     vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &breakpoint_handler);
2565     ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
2566 
2567     breakpoint_exceptions = 0;
2568     func();
2569     ok(breakpoint_exceptions == numexc, "int $0x3 generated %u exceptions, expected %u\n",
2570        breakpoint_exceptions, numexc);
2571 
2572     pRtlRemoveVectoredExceptionHandler(vectored_handler);
2573 }
2574 
2575 static DWORD invalid_handle_exceptions;
2576 
2577 static LONG CALLBACK invalid_handle_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
2578 {
2579     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
2580     trace("vect. handler %08x addr:%p\n", rec->ExceptionCode, rec->ExceptionAddress);
2581 
2582     ok(rec->ExceptionCode == EXCEPTION_INVALID_HANDLE, "ExceptionCode is %08x instead of %08x\n",
2583        rec->ExceptionCode, EXCEPTION_INVALID_HANDLE);
2584     ok(rec->NumberParameters == 0, "ExceptionParameters is %d instead of 0\n", rec->NumberParameters);
2585 
2586     invalid_handle_exceptions++;
2587     return (rec->ExceptionCode == EXCEPTION_INVALID_HANDLE) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
2588 }
2589 
2590 static void test_closehandle(DWORD numexc)
2591 {
2592     PVOID vectored_handler;
2593     NTSTATUS status;
2594     DWORD res;
2595 
2596     if (!pRtlAddVectoredExceptionHandler || !pRtlRemoveVectoredExceptionHandler || !pRtlRaiseException)
2597     {
2598         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler or RtlRaiseException not found\n");
2599         return;
2600     }
2601 
2602     vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &invalid_handle_vectored_handler);
2603     ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
2604 
2605     invalid_handle_exceptions = 0;
2606     res = CloseHandle((HANDLE)0xdeadbeef);
2607     ok(!res, "CloseHandle(0xdeadbeef) unexpectedly succeeded\n");
2608     ok(GetLastError() == ERROR_INVALID_HANDLE, "wrong error code %d instead of %d\n",
2609        GetLastError(), ERROR_INVALID_HANDLE);
2610     ok(invalid_handle_exceptions == numexc, "CloseHandle generated %d exceptions, expected %d\n",
2611        invalid_handle_exceptions, numexc);
2612 
2613     invalid_handle_exceptions = 0;
2614     status = pNtClose((HANDLE)0xdeadbeef);
2615     ok(status == STATUS_INVALID_HANDLE, "NtClose(0xdeadbeef) returned status %08x\n", status);
2616     ok(invalid_handle_exceptions == numexc, "NtClose generated %d exceptions, expected %d\n",
2617        invalid_handle_exceptions, numexc);
2618 
2619     pRtlRemoveVectoredExceptionHandler(vectored_handler);
2620 }
2621 
2622 static void test_vectored_continue_handler(void)
2623 {
2624     PVOID handler1, handler2;
2625     ULONG ret;
2626 
2627     if (!pRtlAddVectoredContinueHandler || !pRtlRemoveVectoredContinueHandler)
2628     {
2629         skip("RtlAddVectoredContinueHandler or RtlRemoveVectoredContinueHandler not found\n");
2630         return;
2631     }
2632 
2633     handler1 = pRtlAddVectoredContinueHandler(TRUE, (void *)0xdeadbeef);
2634     ok(handler1 != 0, "RtlAddVectoredContinueHandler failed\n");
2635 
2636     handler2 = pRtlAddVectoredContinueHandler(TRUE, (void *)0xdeadbeef);
2637     ok(handler2 != 0, "RtlAddVectoredContinueHandler failed\n");
2638     ok(handler1 != handler2, "RtlAddVectoredContinueHandler returned same handler\n");
2639 
2640     if (pRtlRemoveVectoredExceptionHandler)
2641     {
2642         ret = pRtlRemoveVectoredExceptionHandler(handler1);
2643         ok(!ret, "RtlRemoveVectoredExceptionHandler succeeded\n");
2644     }
2645 
2646     ret = pRtlRemoveVectoredContinueHandler(handler1);
2647     ok(ret, "RtlRemoveVectoredContinueHandler failed\n");
2648 
2649     ret = pRtlRemoveVectoredContinueHandler(handler2);
2650     ok(ret, "RtlRemoveVectoredContinueHandler failed\n");
2651 
2652     ret = pRtlRemoveVectoredContinueHandler(handler1);
2653     ok(!ret, "RtlRemoveVectoredContinueHandler succeeded\n");
2654 
2655     ret = pRtlRemoveVectoredContinueHandler((void *)0x11223344);
2656     ok(!ret, "RtlRemoveVectoredContinueHandler succeeded\n");
2657 }
2658 #endif /* defined(__i386__) || defined(__x86_64__) */
2659 
2660 START_TEST(exception)
2661 {
2662     HMODULE hntdll = GetModuleHandleA("ntdll.dll");
2663 #if defined(__x86_64__)
2664     HMODULE hmsvcrt = LoadLibraryA("msvcrt.dll");
2665 #endif
2666 
2667 #ifdef __REACTOS__
2668     if (!winetest_interactive &&
2669         !strcmp(winetest_platform, "windows"))
2670     {
2671         skip("ROSTESTS-240: Skipping ntdll_winetest:exception because it hangs on WHS-Testbot. Set winetest_interactive to run it anyway.\n");
2672         return;
2673     }
2674 #endif
2675     code_mem = VirtualAlloc(NULL, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
2676     if(!code_mem) {
2677         trace("VirtualAlloc failed\n");
2678         return;
2679     }
2680 
2681     pNtGetContextThread  = (void *)GetProcAddress( hntdll, "NtGetContextThread" );
2682     pNtSetContextThread  = (void *)GetProcAddress( hntdll, "NtSetContextThread" );
2683     pNtReadVirtualMemory = (void *)GetProcAddress( hntdll, "NtReadVirtualMemory" );
2684     pNtClose             = (void *)GetProcAddress( hntdll, "NtClose" );
2685     pRtlUnwind           = (void *)GetProcAddress( hntdll, "RtlUnwind" );
2686     pRtlRaiseException   = (void *)GetProcAddress( hntdll, "RtlRaiseException" );
2687     pRtlCaptureContext   = (void *)GetProcAddress( hntdll, "RtlCaptureContext" );
2688     pNtTerminateProcess  = (void *)GetProcAddress( hntdll, "NtTerminateProcess" );
2689     pRtlAddVectoredExceptionHandler    = (void *)GetProcAddress( hntdll,
2690                                                                  "RtlAddVectoredExceptionHandler" );
2691     pRtlRemoveVectoredExceptionHandler = (void *)GetProcAddress( hntdll,
2692                                                                  "RtlRemoveVectoredExceptionHandler" );
2693     pRtlAddVectoredContinueHandler     = (void *)GetProcAddress( hntdll,
2694                                                                  "RtlAddVectoredContinueHandler" );
2695     pRtlRemoveVectoredContinueHandler  = (void *)GetProcAddress( hntdll,
2696                                                                  "RtlRemoveVectoredContinueHandler" );
2697     pNtQueryInformationProcess         = (void*)GetProcAddress( hntdll,
2698                                                                  "NtQueryInformationProcess" );
2699     pNtSetInformationProcess           = (void*)GetProcAddress( hntdll,
2700                                                                  "NtSetInformationProcess" );
2701     pIsWow64Process = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "IsWow64Process");
2702 
2703 #ifdef __i386__
2704     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &is_wow64 )) is_wow64 = FALSE;
2705 
2706     if (pRtlAddVectoredExceptionHandler && pRtlRemoveVectoredExceptionHandler)
2707         have_vectored_api = TRUE;
2708     else
2709         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler not found\n");
2710 
2711     my_argc = winetest_get_mainargs( &my_argv );
2712     if (my_argc >= 4)
2713     {
2714         void *addr;
2715         sscanf( my_argv[3], "%p", &addr );
2716 
2717         if (addr != &test_stage)
2718         {
2719             skip( "child process not mapped at same address (%p/%p)\n", &test_stage, addr);
2720             return;
2721         }
2722 
2723         /* child must be run under a debugger */
2724         if (!NtCurrentTeb()->Peb->BeingDebugged)
2725         {
2726             ok(FALSE, "child process not being debugged?\n");
2727             return;
2728         }
2729 
2730         if (pRtlRaiseException)
2731         {
2732             test_stage = 1;
2733             run_rtlraiseexception_test(0x12345);
2734             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
2735             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
2736             test_stage = 2;
2737             run_rtlraiseexception_test(0x12345);
2738             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
2739             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
2740             test_stage = 3;
2741             test_outputdebugstring(0);
2742             test_stage = 4;
2743             test_outputdebugstring(2);
2744             test_stage = 5;
2745             test_ripevent(0);
2746             test_stage = 6;
2747             test_ripevent(1);
2748             test_stage = 7;
2749             test_debug_service(0);
2750             test_stage = 8;
2751             test_debug_service(1);
2752             test_stage = 9;
2753             test_breakpoint(0);
2754             test_stage = 10;
2755             test_breakpoint(1);
2756             test_stage = 11;
2757             test_closehandle(0);
2758             test_stage = 12;
2759             test_closehandle(1);
2760         }
2761         else
2762             skip( "RtlRaiseException not found\n" );
2763 
2764         /* rest of tests only run in parent */
2765         return;
2766     }
2767 
2768     test_unwind();
2769     test_exceptions();
2770     test_rtlraiseexception();
2771     test_debug_registers();
2772     test_outputdebugstring(1);
2773     test_ripevent(1);
2774     test_debug_service(1);
2775     test_breakpoint(1);
2776     test_closehandle(0);
2777     test_vectored_continue_handler();
2778     test_debugger();
2779     test_simd_exceptions();
2780     test_fpu_exceptions();
2781     test_dpe_exceptions();
2782     test_prot_fault();
2783     test_thread_context();
2784 
2785 #elif defined(__x86_64__)
2786     pRtlAddFunctionTable               = (void *)GetProcAddress( hntdll,
2787                                                                  "RtlAddFunctionTable" );
2788     pRtlDeleteFunctionTable            = (void *)GetProcAddress( hntdll,
2789                                                                  "RtlDeleteFunctionTable" );
2790     pRtlInstallFunctionTableCallback   = (void *)GetProcAddress( hntdll,
2791                                                                  "RtlInstallFunctionTableCallback" );
2792     pRtlLookupFunctionEntry            = (void *)GetProcAddress( hntdll,
2793                                                                  "RtlLookupFunctionEntry" );
2794     p__C_specific_handler              = (void *)GetProcAddress( hntdll,
2795                                                                  "__C_specific_handler" );
2796     pRtlCaptureContext                 = (void *)GetProcAddress( hntdll,
2797                                                                  "RtlCaptureContext" );
2798     pRtlRestoreContext                 = (void *)GetProcAddress( hntdll,
2799                                                                  "RtlRestoreContext" );
2800     pRtlUnwindEx                       = (void *)GetProcAddress( hntdll,
2801                                                                  "RtlUnwindEx" );
2802     p_setjmp                           = (void *)GetProcAddress( hmsvcrt,
2803                                                                  "_setjmp" );
2804 
2805     test_debug_registers();
2806     test_outputdebugstring(1);
2807     test_ripevent(1);
2808     test_debug_service(1);
2809     test_breakpoint(1);
2810     test_closehandle(0);
2811     test_vectored_continue_handler();
2812     test_virtual_unwind();
2813     test___C_specific_handler();
2814     test_restore_context();
2815 
2816     if (pRtlAddFunctionTable && pRtlDeleteFunctionTable && pRtlInstallFunctionTableCallback && pRtlLookupFunctionEntry)
2817       test_dynamic_unwind();
2818     else
2819       skip( "Dynamic unwind functions not found\n" );
2820 
2821 #endif
2822 
2823     VirtualFree(code_mem, 0, MEM_RELEASE);
2824 }
2825