ntdll/tests: Wait for async I/O to complete when the result is STATUS_PENDING.
[wine] / dlls / ntdll / tests / exception.c
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 <stdarg.h>
22 #include <stdio.h>
23
24 #ifndef _WIN32_WINNT
25 #define _WIN32_WINNT 0x500 /* For NTSTATUS */
26 #endif
27
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30 #include "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winnt.h"
35 #include "winreg.h"
36 #include "winternl.h"
37 #include "excpt.h"
38 #include "wine/test.h"
39
40 static void *code_mem;
41
42 static struct _TEB * (WINAPI *pNtCurrentTeb)(void);
43 static NTSTATUS  (WINAPI *pNtGetContextThread)(HANDLE,CONTEXT*);
44 static NTSTATUS  (WINAPI *pNtSetContextThread)(HANDLE,CONTEXT*);
45 static NTSTATUS  (WINAPI *pRtlRaiseException)(EXCEPTION_RECORD *rec);
46 static PVOID     (WINAPI *pRtlAddVectoredExceptionHandler)(ULONG first, PVECTORED_EXCEPTION_HANDLER func);
47 static ULONG     (WINAPI *pRtlRemoveVectoredExceptionHandler)(PVOID handler);
48 static NTSTATUS  (WINAPI *pNtReadVirtualMemory)(HANDLE, const void*, void*, SIZE_T, SIZE_T*);
49 static NTSTATUS  (WINAPI *pNtTerminateProcess)(HANDLE handle, LONG exit_code);
50 static NTSTATUS  (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
51 static NTSTATUS  (WINAPI *pNtSetInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG);
52 static BOOL      (WINAPI *pIsWow64Process)(HANDLE, PBOOL);
53
54 #ifdef __i386__
55
56 #ifndef __WINE_WINTRNL_H
57 #define ProcessExecuteFlags 0x22
58 #define MEM_EXECUTE_OPTION_DISABLE   0x01
59 #define MEM_EXECUTE_OPTION_ENABLE    0x02
60 #define MEM_EXECUTE_OPTION_PERMANENT 0x08
61 #endif
62
63 static int      my_argc;
64 static char**   my_argv;
65 static int      test_stage;
66
67 static BOOL is_wow64;
68
69 /* Test various instruction combinations that cause a protection fault on the i386,
70  * and check what the resulting exception looks like.
71  */
72
73 static const struct exception
74 {
75     BYTE     code[18];      /* asm code */
76     BYTE     offset;        /* offset of faulting instruction */
77     BYTE     length;        /* length of faulting instruction */
78     BOOL     wow64_broken;  /* broken on Wow64, should be skipped */
79     NTSTATUS status;        /* expected status code */
80     DWORD    nb_params;     /* expected number of parameters */
81     DWORD    params[4];     /* expected parameters */
82     NTSTATUS alt_status;    /* alternative status code */
83     DWORD    alt_nb_params; /* alternative number of parameters */
84     DWORD    alt_params[4]; /* alternative parameters */
85 } exceptions[] =
86 {
87 /* 0 */
88     /* test some privileged instructions */
89     { { 0xfb, 0xc3 },  /* 0: sti; ret */
90       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
91     { { 0x6c, 0xc3 },  /* 1: insb (%dx); ret */
92       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
93     { { 0x6d, 0xc3 },  /* 2: insl (%dx); ret */
94       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
95     { { 0x6e, 0xc3 },  /* 3: outsb (%dx); ret */
96       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
97     { { 0x6f, 0xc3 },  /* 4: outsl (%dx); ret */
98       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
99 /* 5 */
100     { { 0xe4, 0x11, 0xc3 },  /* 5: inb $0x11,%al; ret */
101       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
102     { { 0xe5, 0x11, 0xc3 },  /* 6: inl $0x11,%eax; ret */
103       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
104     { { 0xe6, 0x11, 0xc3 },  /* 7: outb %al,$0x11; ret */
105       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
106     { { 0xe7, 0x11, 0xc3 },  /* 8: outl %eax,$0x11; ret */
107       0, 2, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
108     { { 0xed, 0xc3 },  /* 9: inl (%dx),%eax; ret */
109       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
110 /* 10 */
111     { { 0xee, 0xc3 },  /* 10: outb %al,(%dx); ret */
112       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
113     { { 0xef, 0xc3 },  /* 11: outl %eax,(%dx); ret */
114       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
115     { { 0xf4, 0xc3 },  /* 12: hlt; ret */
116       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
117     { { 0xfa, 0xc3 },  /* 13: cli; ret */
118       0, 1, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
119
120     /* test long jump to invalid selector */
121     { { 0xea, 0, 0, 0, 0, 0, 0, 0xc3 },  /* 14: ljmp $0,$0; ret */
122       0, 7, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
123
124 /* 15 */
125     /* test iret to invalid selector */
126     { { 0x6a, 0x00, 0x6a, 0x00, 0x6a, 0x00, 0xcf, 0x83, 0xc4, 0x0c, 0xc3 },
127       /* 15: pushl $0; pushl $0; pushl $0; iret; addl $12,%esp; ret */
128       6, 1, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
129
130     /* test loading an invalid selector */
131     { { 0xb8, 0xef, 0xbe, 0x00, 0x00, 0x8e, 0xe8, 0xc3 },  /* 16: mov $beef,%ax; mov %ax,%gs; ret */
132       5, 2, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xbee8 } }, /* 0xbee8 or 0xffffffff */
133
134     /* test accessing a zero selector (%es broken on Wow64) */
135     { { 0x06, 0x31, 0xc0, 0x8e, 0xc0, 0x26, 0xa1, 0, 0, 0, 0, 0x07, 0xc3 },
136        /* push %es; xor %eax,%eax; mov %ax,%es; mov %es:(0),%ax; pop %es; ret */
137       5, 6, TRUE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
138     { { 0x0f, 0xa8, 0x31, 0xc0, 0x8e, 0xe8, 0x65, 0xa1, 0, 0, 0, 0, 0x0f, 0xa9, 0xc3 },
139       /* push %gs; xor %eax,%eax; mov %ax,%gs; mov %gs:(0),%ax; pop %gs; ret */
140       6, 6, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
141
142     /* test moving %cs -> %ss */
143     { { 0x0e, 0x17, 0x58, 0xc3 },  /* pushl %cs; popl %ss; popl %eax; ret */
144       1, 1, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
145
146 /* 20 */
147     /* test overlong instruction (limit is 15 bytes, 5 on Win7) */
148     { { 0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0xfa,0xc3 },
149       0, 16, TRUE, STATUS_ILLEGAL_INSTRUCTION, 0, { 0 },
150       STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
151     { { 0x64,0x64,0x64,0x64,0xfa,0xc3 },
152       0, 5, TRUE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
153
154     /* test invalid interrupt */
155     { { 0xcd, 0xff, 0xc3 },   /* int $0xff; ret */
156       0, 2, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
157
158     /* test moves to/from Crx */
159     { { 0x0f, 0x20, 0xc0, 0xc3 },  /* movl %cr0,%eax; ret */
160       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
161     { { 0x0f, 0x20, 0xe0, 0xc3 },  /* movl %cr4,%eax; ret */
162       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
163 /* 25 */
164     { { 0x0f, 0x22, 0xc0, 0xc3 },  /* movl %eax,%cr0; ret */
165       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
166     { { 0x0f, 0x22, 0xe0, 0xc3 },  /* movl %eax,%cr4; ret */
167       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
168
169     /* test moves to/from Drx */
170     { { 0x0f, 0x21, 0xc0, 0xc3 },  /* movl %dr0,%eax; ret */
171       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
172     { { 0x0f, 0x21, 0xc8, 0xc3 },  /* movl %dr1,%eax; ret */
173       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
174     { { 0x0f, 0x21, 0xf8, 0xc3 },  /* movl %dr7,%eax; ret */
175       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
176 /* 30 */
177     { { 0x0f, 0x23, 0xc0, 0xc3 },  /* movl %eax,%dr0; ret */
178       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
179     { { 0x0f, 0x23, 0xc8, 0xc3 },  /* movl %eax,%dr1; ret */
180       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
181     { { 0x0f, 0x23, 0xf8, 0xc3 },  /* movl %eax,%dr7; ret */
182       0, 3, FALSE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
183
184     /* test memory reads */
185     { { 0xa1, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffc,%eax; ret */
186       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffc } },
187     { { 0xa1, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffd,%eax; ret */
188       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffd } },
189 /* 35 */
190     { { 0xa1, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffe,%eax; ret */
191       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffe } },
192     { { 0xa1, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xffffffff,%eax; ret */
193       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
194
195     /* test memory writes */
196     { { 0xa3, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffc; ret */
197       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffc } },
198     { { 0xa3, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffd; ret */
199       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffd } },
200     { { 0xa3, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffe; ret */
201       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffe } },
202 /* 40 */
203     { { 0xa3, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xffffffff; ret */
204       0, 5, FALSE, STATUS_ACCESS_VIOLATION, 2, { 1, 0xffffffff } },
205
206     /* test exception with cleared %ds and %es (broken on Wow64) */
207     { { 0x1e, 0x06, 0x31, 0xc0, 0x8e, 0xd8, 0x8e, 0xc0, 0xfa, 0x07, 0x1f, 0xc3 },
208           /* push %ds; push %es; xorl %eax,%eax; mov %ax,%ds; mov %ax,%es; cli; pop %es; pop %ds; ret */
209       8, 1, TRUE, STATUS_PRIVILEGED_INSTRUCTION, 0 },
210
211     { { 0xf1, 0x90, 0xc3 },  /* icebp; nop; ret */
212       1, 1, FALSE, STATUS_SINGLE_STEP, 0 },
213 };
214
215 static int got_exception;
216 static BOOL have_vectored_api;
217
218 static void run_exception_test(void *handler, const void* context,
219                                const void *code, unsigned int code_size,
220                                DWORD access)
221 {
222     struct {
223         EXCEPTION_REGISTRATION_RECORD frame;
224         const void *context;
225     } exc_frame;
226     void (*func)(void) = code_mem;
227     DWORD oldaccess, oldaccess2;
228
229     exc_frame.frame.Handler = handler;
230     exc_frame.frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
231     exc_frame.context = context;
232
233     memcpy(code_mem, code, code_size);
234     if(access)
235         VirtualProtect(code_mem, code_size, access, &oldaccess);
236
237     pNtCurrentTeb()->Tib.ExceptionList = &exc_frame.frame;
238     func();
239     pNtCurrentTeb()->Tib.ExceptionList = exc_frame.frame.Prev;
240
241     if(access)
242         VirtualProtect(code_mem, code_size, oldaccess, &oldaccess2);
243 }
244
245 static LONG CALLBACK rtlraiseexception_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
246 {
247     PCONTEXT context = ExceptionInfo->ContextRecord;
248     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
249     trace("vect. handler %08x addr:%p context.Eip:%x\n", rec->ExceptionCode,
250           rec->ExceptionAddress, context->Eip);
251
252     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
253        rec->ExceptionAddress, (char *)code_mem + 0xb);
254
255     if (pNtCurrentTeb()->Peb->BeingDebugged)
256         ok((void *)context->Eax == pRtlRaiseException ||
257            broken( is_wow64 && context->Eax == 0xf00f00f1 ), /* broken on vista */
258            "debugger managed to modify Eax to %x should be %p\n",
259            context->Eax, pRtlRaiseException);
260
261     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
262      * even if raised by RtlRaiseException
263      */
264     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
265     {
266         ok(context->Eip == (DWORD)code_mem + 0xa ||
267            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
268            "Eip at %x instead of %x or %x\n", context->Eip,
269            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
270     }
271     else
272     {
273         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
274            context->Eip, (DWORD)code_mem + 0xb);
275     }
276
277     /* test if context change is preserved from vectored handler to stack handlers */
278     context->Eax = 0xf00f00f0;
279     return EXCEPTION_CONTINUE_SEARCH;
280 }
281
282 static DWORD rtlraiseexception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
283                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
284 {
285     trace( "exception: %08x flags:%x addr:%p context: Eip:%x\n",
286            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Eip );
287
288     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
289        rec->ExceptionAddress, (char *)code_mem + 0xb);
290
291     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
292      * even if raised by RtlRaiseException
293      */
294     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
295     {
296         ok(context->Eip == (DWORD)code_mem + 0xa ||
297            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
298            "Eip at %x instead of %x or %x\n", context->Eip,
299            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
300     }
301     else
302     {
303         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
304            context->Eip, (DWORD)code_mem + 0xb);
305     }
306
307     if(have_vectored_api)
308         ok(context->Eax == 0xf00f00f0, "Eax is %x, should have been set to 0xf00f00f0 in vectored handler\n",
309            context->Eax);
310
311     /* give the debugger a chance to examine the state a second time */
312     /* without the exception handler changing Eip */
313     if (test_stage == 2)
314         return ExceptionContinueSearch;
315
316     /* Eip in context is decreased by 1
317      * Increase it again, else execution will continue in the middle of a instruction */
318     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT && (context->Eip == (DWORD)code_mem + 0xa))
319         context->Eip += 1;
320     return ExceptionContinueExecution;
321 }
322
323
324 static const BYTE call_one_arg_code[] = {
325         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
326         0x50,                   /* push %eax */
327         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
328         0xff, 0xd0,             /* call *%eax */
329         0x90,                   /* nop */
330         0x90,                   /* nop */
331         0x90,                   /* nop */
332         0x90,                   /* nop */
333         0xc3,                   /* ret */
334 };
335
336
337 static void run_rtlraiseexception_test(DWORD exceptioncode)
338 {
339     EXCEPTION_REGISTRATION_RECORD frame;
340     EXCEPTION_RECORD record;
341     PVOID vectored_handler = NULL;
342
343     void (*func)(void* function, EXCEPTION_RECORD* record) = code_mem;
344
345     record.ExceptionCode = exceptioncode;
346     record.ExceptionFlags = 0;
347     record.ExceptionRecord = NULL;
348     record.ExceptionAddress = NULL; /* does not matter, copied return address */
349     record.NumberParameters = 0;
350
351     frame.Handler = rtlraiseexception_handler;
352     frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
353
354     memcpy(code_mem, call_one_arg_code, sizeof(call_one_arg_code));
355
356     pNtCurrentTeb()->Tib.ExceptionList = &frame;
357     if (have_vectored_api)
358     {
359         vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &rtlraiseexception_vectored_handler);
360         ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
361     }
362
363     func(pRtlRaiseException, &record);
364     ok( record.ExceptionAddress == (char *)code_mem + 0x0b,
365         "address set to %p instead of %p\n", record.ExceptionAddress, (char *)code_mem + 0x0b );
366
367     if (have_vectored_api)
368         pRtlRemoveVectoredExceptionHandler(vectored_handler);
369     pNtCurrentTeb()->Tib.ExceptionList = frame.Prev;
370 }
371
372 static void test_rtlraiseexception(void)
373 {
374     if (!pRtlRaiseException)
375     {
376         skip("RtlRaiseException not found\n");
377         return;
378     }
379
380     /* test without debugger */
381     run_rtlraiseexception_test(0x12345);
382     run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
383     run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
384 }
385
386 static DWORD handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
387                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
388 {
389     const struct exception *except = *(const struct exception **)(frame + 1);
390     unsigned int i, entry = except - exceptions;
391
392     got_exception++;
393     trace( "exception %u: %x flags:%x addr:%p\n",
394            entry, rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
395
396     ok( rec->ExceptionCode == except->status ||
397         (except->alt_status != 0 && rec->ExceptionCode == except->alt_status),
398         "%u: Wrong exception code %x/%x\n", entry, rec->ExceptionCode, except->status );
399     ok( rec->ExceptionAddress == (char*)code_mem + except->offset,
400         "%u: Wrong exception address %p/%p\n", entry,
401         rec->ExceptionAddress, (char*)code_mem + except->offset );
402
403     if (except->alt_status == 0 || rec->ExceptionCode != except->alt_status)
404     {
405         ok( rec->NumberParameters == except->nb_params,
406             "%u: Wrong number of parameters %u/%u\n", entry, rec->NumberParameters, except->nb_params );
407     }
408     else
409     {
410         ok( rec->NumberParameters == except->alt_nb_params,
411             "%u: Wrong number of parameters %u/%u\n", entry, rec->NumberParameters, except->nb_params );
412     }
413
414     /* Most CPUs (except Intel Core apparently) report a segment limit violation */
415     /* instead of page faults for accesses beyond 0xffffffff */
416     if (except->nb_params == 2 && except->params[1] >= 0xfffffffd)
417     {
418         if (rec->ExceptionInformation[0] == 0 && rec->ExceptionInformation[1] == 0xffffffff)
419             goto skip_params;
420     }
421
422     /* Seems that both 0xbee8 and 0xfffffffff can be returned in windows */
423     if (except->nb_params == 2 && rec->NumberParameters == 2
424         && except->params[1] == 0xbee8 && rec->ExceptionInformation[1] == 0xffffffff
425         && except->params[0] == rec->ExceptionInformation[0])
426     {
427         goto skip_params;
428     }
429
430     if (except->alt_status == 0 || rec->ExceptionCode != except->alt_status)
431     {
432         for (i = 0; i < rec->NumberParameters; i++)
433             ok( rec->ExceptionInformation[i] == except->params[i],
434                 "%u: Wrong parameter %d: %lx/%x\n",
435                 entry, i, rec->ExceptionInformation[i], except->params[i] );
436     }
437     else
438     {
439         for (i = 0; i < rec->NumberParameters; i++)
440             ok( rec->ExceptionInformation[i] == except->alt_params[i],
441                 "%u: Wrong parameter %d: %lx/%x\n",
442                 entry, i, rec->ExceptionInformation[i], except->alt_params[i] );
443     }
444
445 skip_params:
446     /* don't handle exception if it's not the address we expected */
447     if (rec->ExceptionAddress != (char*)code_mem + except->offset) return ExceptionContinueSearch;
448
449     context->Eip += except->length;
450     return ExceptionContinueExecution;
451 }
452
453 static void test_prot_fault(void)
454 {
455     unsigned int i;
456
457     for (i = 0; i < sizeof(exceptions)/sizeof(exceptions[0]); i++)
458     {
459         if (is_wow64 && exceptions[i].wow64_broken && !strcmp( winetest_platform, "windows" ))
460         {
461             skip( "Exception %u broken on Wow64\n", i );
462             continue;
463         }
464         got_exception = 0;
465         run_exception_test(handler, &exceptions[i], &exceptions[i].code,
466                            sizeof(exceptions[i].code), 0);
467         if (!i && !got_exception)
468         {
469             trace( "No exception, assuming win9x, no point in testing further\n" );
470             break;
471         }
472         ok( got_exception == (exceptions[i].status != 0),
473             "%u: bad exception count %d\n", i, got_exception );
474     }
475 }
476
477 struct dbgreg_test {
478     DWORD dr0, dr1, dr2, dr3, dr6, dr7;
479 };
480
481 /* test handling of debug registers */
482 static DWORD dreg_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
483                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
484 {
485     const struct dbgreg_test *test = *(const struct dbgreg_test **)(frame + 1);
486
487     context->Eip += 2;  /* Skips the popl (%eax) */
488     context->Dr0 = test->dr0;
489     context->Dr1 = test->dr1;
490     context->Dr2 = test->dr2;
491     context->Dr3 = test->dr3;
492     context->Dr6 = test->dr6;
493     context->Dr7 = test->dr7;
494     return ExceptionContinueExecution;
495 }
496
497 #define CHECK_DEBUG_REG(n, m) \
498     ok((ctx.Dr##n & m) == test->dr##n, "(%d) failed to set debug register " #n " to %x, got %x\n", \
499        test_num, test->dr##n, ctx.Dr##n)
500
501 static void check_debug_registers(int test_num, const struct dbgreg_test *test)
502 {
503     CONTEXT ctx;
504     NTSTATUS status;
505
506     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
507     status = pNtGetContextThread(GetCurrentThread(), &ctx);
508     ok(status == STATUS_SUCCESS, "NtGetContextThread failed with %x\n", status);
509
510     CHECK_DEBUG_REG(0, ~0);
511     CHECK_DEBUG_REG(1, ~0);
512     CHECK_DEBUG_REG(2, ~0);
513     CHECK_DEBUG_REG(3, ~0);
514     CHECK_DEBUG_REG(6, 0x0f);
515     CHECK_DEBUG_REG(7, ~0xdc00);
516 }
517
518 static const BYTE segfault_code[5] = {
519         0x31, 0xc0, /* xor    %eax,%eax */
520         0x8f, 0x00, /* popl   (%eax) - cause exception */
521         0xc3        /* ret */
522 };
523
524 /* test the single step exception behaviour */
525 static DWORD single_step_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
526                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
527 {
528     got_exception++;
529     ok (!(context->EFlags & 0x100), "eflags has single stepping bit set\n");
530
531     if( got_exception < 3)
532         context->EFlags |= 0x100;  /* single step until popf instruction */
533     else {
534         /* show that the last single step exception on the popf instruction
535          * (which removed the TF bit), still is a EXCEPTION_SINGLE_STEP exception */
536         ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
537             "exception is not EXCEPTION_SINGLE_STEP: %x\n", rec->ExceptionCode);
538     }
539
540     return ExceptionContinueExecution;
541 }
542
543 static const BYTE single_stepcode[] = {
544     0x9c,               /* pushf */
545     0x58,               /* pop   %eax */
546     0x0d,0,1,0,0,       /* or    $0x100,%eax */
547     0x50,               /* push   %eax */
548     0x9d,               /* popf    */
549     0x35,0,1,0,0,       /* xor    $0x100,%eax */
550     0x50,               /* push   %eax */
551     0x9d,               /* popf    */
552     0xc3
553 };
554
555 /* Test the alignment check (AC) flag handling. */
556 static const BYTE align_check_code[] = {
557     0x55,                       /* push   %ebp */
558     0x89,0xe5,                  /* mov    %esp,%ebp */
559     0x9c,                       /* pushf   */
560     0x58,                       /* pop    %eax */
561     0x0d,0,0,4,0,               /* or     $0x40000,%eax */
562     0x50,                       /* push   %eax */
563     0x9d,                       /* popf    */
564     0x89,0xe0,                  /* mov %esp, %eax */
565     0x8b,0x40,0x1,              /* mov 0x1(%eax), %eax - cause exception */
566     0x9c,                       /* pushf   */
567     0x58,                       /* pop    %eax */
568     0x35,0,0,4,0,               /* xor    $0x40000,%eax */
569     0x50,                       /* push   %eax */
570     0x9d,                       /* popf    */
571     0x5d,                       /* pop    %ebp */
572     0xc3,                       /* ret     */
573 };
574
575 static DWORD align_check_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
576                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
577 {
578     ok (!(context->EFlags & 0x40000), "eflags has AC bit set\n");
579     got_exception++;
580     return ExceptionContinueExecution;
581 }
582
583 /* Test the direction flag handling. */
584 static const BYTE direction_flag_code[] = {
585     0x55,                       /* push   %ebp */
586     0x89,0xe5,                  /* mov    %esp,%ebp */
587     0xfd,                       /* std */
588     0xfa,                       /* cli - cause exception */
589     0x5d,                       /* pop    %ebp */
590     0xc3,                       /* ret     */
591 };
592
593 static DWORD direction_flag_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
594                                      CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
595 {
596 #ifdef __GNUC__
597     unsigned int flags;
598     __asm__("pushfl; popl %0; cld" : "=r" (flags) );
599     /* older windows versions don't clear DF properly so don't test */
600     if (flags & 0x400) trace( "eflags has DF bit set\n" );
601 #endif
602     ok( context->EFlags & 0x400, "context eflags has DF bit cleared\n" );
603     got_exception++;
604     context->Eip++;  /* skip cli */
605     context->EFlags &= ~0x400;  /* make sure it is cleared on return */
606     return ExceptionContinueExecution;
607 }
608
609 /* test single stepping over hardware breakpoint */
610 static DWORD bpx_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
611                           CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
612 {
613     got_exception++;
614     ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
615         "wrong exception code: %x\n", rec->ExceptionCode);
616
617     if(got_exception == 1) {
618         /* hw bp exception on first nop */
619         ok( context->Eip == (DWORD)code_mem, "eip is wrong:  %x instead of %x\n",
620                                              context->Eip, (DWORD)code_mem);
621         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
622         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
623         context->Dr0 = context->Dr0 + 1;  /* set hw bp again on next instruction */
624         context->EFlags |= 0x100;       /* enable single stepping */
625     } else if(  got_exception == 2) {
626         /* single step exception on second nop */
627         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
628                                                  context->Eip, (DWORD)code_mem + 1);
629         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
630        /* depending on the win version the B0 bit is already set here as well
631         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n"); */
632         context->EFlags |= 0x100;
633     } else if( got_exception == 3) {
634         /* hw bp exception on second nop */
635         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
636                                                  context->Eip, (DWORD)code_mem + 1);
637         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
638         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
639         context->Dr0 = 0;       /* clear breakpoint */
640         context->EFlags |= 0x100;
641     } else {
642         /* single step exception on ret */
643         ok( context->Eip == (DWORD)code_mem + 2, "eip is wrong: %x instead of %x\n",
644                                                  context->Eip, (DWORD)code_mem + 2);
645         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n");
646         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
647     }
648
649     context->Dr6 = 0;  /* clear status register */
650     return ExceptionContinueExecution;
651 }
652
653 static const BYTE dummy_code[] = { 0x90, 0x90, 0xc3 };  /* nop, nop, ret */
654
655 /* test int3 handling */
656 static DWORD int3_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
657                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
658 {
659     ok( rec->ExceptionAddress == code_mem, "exception address not at: %p, but at %p\n",
660                                            code_mem,  rec->ExceptionAddress);
661     ok( context->Eip == (DWORD)code_mem, "eip not at: %p, but at %#x\n", code_mem, context->Eip);
662     if(context->Eip == (DWORD)code_mem) context->Eip++; /* skip breakpoint */
663
664     return ExceptionContinueExecution;
665 }
666
667 static const BYTE int3_code[] = { 0xCC, 0xc3 };  /* int 3, ret */
668
669
670 static void test_exceptions(void)
671 {
672     CONTEXT ctx;
673     NTSTATUS res;
674     struct dbgreg_test dreg_test;
675
676     if (!pNtGetContextThread || !pNtSetContextThread)
677     {
678         skip( "NtGetContextThread/NtSetContextThread not found\n" );
679         return;
680     }
681
682     /* test handling of debug registers */
683     memset(&dreg_test, 0, sizeof(dreg_test));
684
685     dreg_test.dr0 = 0x42424240;
686     dreg_test.dr2 = 0x126bb070;
687     dreg_test.dr3 = 0x0badbad0;
688     dreg_test.dr7 = 0xffff0115;
689     run_exception_test(dreg_handler, &dreg_test, &segfault_code, sizeof(segfault_code), 0);
690     check_debug_registers(1, &dreg_test);
691
692     dreg_test.dr0 = 0x42424242;
693     dreg_test.dr2 = 0x100f0fe7;
694     dreg_test.dr3 = 0x0abebabe;
695     dreg_test.dr7 = 0x115;
696     run_exception_test(dreg_handler, &dreg_test, &segfault_code, sizeof(segfault_code), 0);
697     check_debug_registers(2, &dreg_test);
698
699     /* test single stepping behavior */
700     got_exception = 0;
701     run_exception_test(single_step_handler, NULL, &single_stepcode, sizeof(single_stepcode), 0);
702     ok(got_exception == 3, "expected 3 single step exceptions, got %d\n", got_exception);
703
704     /* test alignment exceptions */
705     got_exception = 0;
706     run_exception_test(align_check_handler, NULL, align_check_code, sizeof(align_check_code), 0);
707     ok(got_exception == 0, "got %d alignment faults, expected 0\n", got_exception);
708
709     /* test direction flag */
710     got_exception = 0;
711     run_exception_test(direction_flag_handler, NULL, direction_flag_code, sizeof(direction_flag_code), 0);
712     ok(got_exception == 1, "got %d exceptions, expected 1\n", got_exception);
713
714     /* test single stepping over hardware breakpoint */
715     memset(&ctx, 0, sizeof(ctx));
716     ctx.Dr0 = (DWORD) code_mem;  /* set hw bp on first nop */
717     ctx.Dr7 = 3;
718     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
719     res = pNtSetContextThread( GetCurrentThread(), &ctx);
720     ok( res == STATUS_SUCCESS, "NtSetContextThread failed with %x\n", res);
721
722     got_exception = 0;
723     run_exception_test(bpx_handler, NULL, dummy_code, sizeof(dummy_code), 0);
724     ok( got_exception == 4,"expected 4 exceptions, got %d\n", got_exception);
725
726     /* test int3 handling */
727     run_exception_test(int3_handler, NULL, int3_code, sizeof(int3_code), 0);
728 }
729
730 static void test_debugger(void)
731 {
732     char cmdline[MAX_PATH];
733     PROCESS_INFORMATION pi;
734     STARTUPINFO si = { 0 };
735     DEBUG_EVENT de;
736     DWORD continuestatus;
737     PVOID code_mem_address = NULL;
738     NTSTATUS status;
739     SIZE_T size_read;
740     BOOL ret;
741     int counter = 0;
742     si.cb = sizeof(si);
743
744     if(!pNtGetContextThread || !pNtSetContextThread || !pNtReadVirtualMemory || !pNtTerminateProcess)
745     {
746         skip("NtGetContextThread, NtSetContextThread, NtReadVirtualMemory or NtTerminateProcess not found\n");
747         return;
748     }
749
750     sprintf(cmdline, "%s %s %s %p", my_argv[0], my_argv[1], "debuggee", &test_stage);
751     ret = CreateProcess(NULL, cmdline, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi);
752     ok(ret, "could not create child process error: %u\n", GetLastError());
753     if (!ret)
754         return;
755
756     do
757     {
758         continuestatus = DBG_CONTINUE;
759         ok(WaitForDebugEvent(&de, INFINITE), "reading debug event\n");
760
761         if (de.dwThreadId != pi.dwThreadId)
762         {
763             trace("event %d not coming from main thread, ignoring\n", de.dwDebugEventCode);
764             ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
765             continue;
766         }
767
768         if (de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
769         {
770             if(de.u.CreateProcessInfo.lpBaseOfImage != pNtCurrentTeb()->Peb->ImageBaseAddress)
771             {
772                 skip("child process loaded at different address, terminating it\n");
773                 pNtTerminateProcess(pi.hProcess, 0);
774             }
775         }
776         else if (de.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
777         {
778             CONTEXT ctx;
779             int stage;
780
781             counter++;
782             status = pNtReadVirtualMemory(pi.hProcess, &code_mem, &code_mem_address,
783                                           sizeof(code_mem_address), &size_read);
784             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
785             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
786                                           sizeof(stage), &size_read);
787             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
788
789             ctx.ContextFlags = CONTEXT_FULL;
790             status = pNtGetContextThread(pi.hThread, &ctx);
791             ok(!status, "NtGetContextThread failed with 0x%x\n", status);
792
793             trace("exception 0x%x at %p firstchance=%d Eip=0x%x, Eax=0x%x\n",
794                   de.u.Exception.ExceptionRecord.ExceptionCode,
795                   de.u.Exception.ExceptionRecord.ExceptionAddress, de.u.Exception.dwFirstChance, ctx.Eip, ctx.Eax);
796
797             if (counter > 100)
798             {
799                 ok(FALSE, "got way too many exceptions, probably caught in a infinite loop, terminating child\n");
800                 pNtTerminateProcess(pi.hProcess, 1);
801             }
802             else if (counter >= 2) /* skip startup breakpoint */
803             {
804                 if (stage == 1)
805                 {
806                     ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at %x instead of %p\n",
807                        ctx.Eip, (char *)code_mem_address + 0xb);
808                     /* setting the context from debugger does not affect the context, the exception handlers gets */
809                     /* uncomment once wine is fixed */
810                     /* ctx.Eip = 0x12345; */
811                     ctx.Eax = 0xf00f00f1;
812
813                     /* let the debuggee handle the exception */
814                     continuestatus = DBG_EXCEPTION_NOT_HANDLED;
815                 }
816                 else if (stage == 2)
817                 {
818                     if (de.u.Exception.dwFirstChance)
819                     {
820                         /* debugger gets first chance exception with unmodified ctx.Eip */
821                         ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
822                             ctx.Eip, (char *)code_mem_address + 0xb);
823
824                         /* setting the context from debugger does not affect the context, the exception handlers gets */
825                         /* uncomment once wine is fixed */
826                         /* ctx.Eip = 0x12345; */
827                         ctx.Eax = 0xf00f00f1;
828
829                         /* pass exception to debuggee
830                          * exception will not be handled and
831                          * a second chance exception will be raised */
832                         continuestatus = DBG_EXCEPTION_NOT_HANDLED;
833                     }
834                     else
835                     {
836                         /* debugger gets context after exception handler has played with it */
837                         /* ctx.Eip is the same value the exception handler got */
838                         if (de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
839                         {
840                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xa ||
841                                broken(is_wow64 && (char *)ctx.Eip == (char *)code_mem_address + 0xb),
842                                "Eip at 0x%x instead of %p\n",
843                                 ctx.Eip, (char *)code_mem_address + 0xa);
844                             /* need to fixup Eip for debuggee */
845                             if ((char *)ctx.Eip == (char *)code_mem_address + 0xa)
846                                 ctx.Eip += 1;
847                         }
848                         else
849                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
850                                 ctx.Eip, (char *)code_mem_address + 0xb);
851                         /* here we handle exception */
852                     }
853                 }
854                 else
855                     ok(FALSE, "unexpected stage %x\n", stage);
856
857                 status = pNtSetContextThread(pi.hThread, &ctx);
858                 ok(!status, "NtSetContextThread failed with 0x%x\n", status);
859             }
860         }
861
862         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, continuestatus);
863
864     } while (de.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
865
866     winetest_wait_child_process( pi.hProcess );
867     ret = CloseHandle(pi.hThread);
868     ok(ret, "error %u\n", GetLastError());
869     ret = CloseHandle(pi.hProcess);
870     ok(ret, "error %u\n", GetLastError());
871
872     return;
873 }
874
875 static DWORD simd_fault_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
876                                  CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
877 {
878     int *stage = *(int **)(frame + 1);
879
880     got_exception++;
881
882     if( *stage == 1) {
883         /* fault while executing sse instruction */
884         context->Eip += 3; /* skip addps */
885         return ExceptionContinueExecution;
886     }
887
888     /* stage 2 - divide by zero fault */
889     if( rec->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION)
890         skip("system doesn't support SIMD exceptions\n");
891     else {
892         ok( rec->ExceptionCode ==  STATUS_FLOAT_MULTIPLE_TRAPS,
893             "exception code: %#x, should be %#x\n",
894             rec->ExceptionCode,  STATUS_FLOAT_MULTIPLE_TRAPS);
895         ok( rec->NumberParameters == 1 || broken(is_wow64 && rec->NumberParameters == 2),
896             "# of params: %i, should be 1\n",
897             rec->NumberParameters);
898         if( rec->NumberParameters == 1 )
899             ok( rec->ExceptionInformation[0] == 0, "param #1: %lx, should be 0\n", rec->ExceptionInformation[0]);
900     }
901
902     context->Eip += 3; /* skip divps */
903
904     return ExceptionContinueExecution;
905 }
906
907 static const BYTE simd_exception_test[] = {
908     0x83, 0xec, 0x4,                     /* sub $0x4, %esp       */
909     0x0f, 0xae, 0x1c, 0x24,              /* stmxcsr (%esp)       */
910     0x66, 0x81, 0x24, 0x24, 0xff, 0xfd,  /* andw $0xfdff,(%esp)  * enable divide by */
911     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       * zero exceptions  */
912     0x6a, 0x01,                          /* push   $0x1          */
913     0x6a, 0x01,                          /* push   $0x1          */
914     0x6a, 0x01,                          /* push   $0x1          */
915     0x6a, 0x01,                          /* push   $0x1          */
916     0x0f, 0x10, 0x0c, 0x24,              /* movups (%esp),%xmm1  * fill dividend  */
917     0x0f, 0x57, 0xc0,                    /* xorps  %xmm0,%xmm0   * clear divisor  */
918     0x0f, 0x5e, 0xc8,                    /* divps  %xmm0,%xmm1   * generate fault */
919     0x83, 0xc4, 0x10,                    /* add    $0x10,%esp    */
920     0x66, 0x81, 0x0c, 0x24, 0x00, 0x02,  /* orw    $0x200,(%esp) * disable exceptions */
921     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       */
922     0x83, 0xc4, 0x04,                    /* add    $0x4,%esp     */
923     0xc3,                                /* ret */
924 };
925
926 static const BYTE sse_check[] = {
927     0x0f, 0x58, 0xc8,                    /* addps  %xmm0,%xmm1 */
928     0xc3,                                /* ret */
929 };
930
931 static void test_simd_exceptions(void)
932 {
933     int stage;
934
935     /* test if CPU & OS can do sse */
936     stage = 1;
937     got_exception = 0;
938     run_exception_test(simd_fault_handler, &stage, sse_check, sizeof(sse_check), 0);
939     if(got_exception) {
940         skip("system doesn't support SSE\n");
941         return;
942     }
943
944     /* generate a SIMD exception */
945     stage = 2;
946     got_exception = 0;
947     run_exception_test(simd_fault_handler, &stage, simd_exception_test,
948                        sizeof(simd_exception_test), 0);
949     ok( got_exception == 1, "got exception: %i, should be 1\n", got_exception);
950 }
951
952 struct fpu_exception_info
953 {
954     DWORD exception_code;
955     DWORD exception_offset;
956     DWORD eip_offset;
957 };
958
959 static DWORD fpu_exception_handler(EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
960         CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher)
961 {
962     struct fpu_exception_info *info = *(struct fpu_exception_info **)(frame + 1);
963
964     info->exception_code = rec->ExceptionCode;
965     info->exception_offset = (BYTE *)rec->ExceptionAddress - (BYTE *)code_mem;
966     info->eip_offset = context->Eip - (DWORD)code_mem;
967
968     ++context->Eip;
969     return ExceptionContinueExecution;
970 }
971
972 static void test_fpu_exceptions(void)
973 {
974     static const BYTE fpu_exception_test_ie[] =
975     {
976         0x83, 0xec, 0x04,                   /* sub $0x4,%esp        */
977         0x66, 0xc7, 0x04, 0x24, 0xfe, 0x03, /* movw $0x3fe,(%esp)   */
978         0x9b, 0xd9, 0x7c, 0x24, 0x02,       /* fstcw 0x2(%esp)      */
979         0xd9, 0x2c, 0x24,                   /* fldcw (%esp)         */
980         0xd9, 0xee,                         /* fldz                 */
981         0xd9, 0xe8,                         /* fld1                 */
982         0xde, 0xf1,                         /* fdivp                */
983         0xdd, 0xd8,                         /* fstp %st(0)          */
984         0xdd, 0xd8,                         /* fstp %st(0)          */
985         0x9b,                               /* fwait                */
986         0xdb, 0xe2,                         /* fnclex               */
987         0xd9, 0x6c, 0x24, 0x02,             /* fldcw 0x2(%esp)      */
988         0x83, 0xc4, 0x04,                   /* add $0x4,%esp        */
989         0xc3,                               /* ret                  */
990     };
991
992     static const BYTE fpu_exception_test_de[] =
993     {
994         0x83, 0xec, 0x04,                   /* sub $0x4,%esp        */
995         0x66, 0xc7, 0x04, 0x24, 0xfb, 0x03, /* movw $0x3fb,(%esp)   */
996         0x9b, 0xd9, 0x7c, 0x24, 0x02,       /* fstcw 0x2(%esp)      */
997         0xd9, 0x2c, 0x24,                   /* fldcw (%esp)         */
998         0xdd, 0xd8,                         /* fstp %st(0)          */
999         0xd9, 0xee,                         /* fldz                 */
1000         0xd9, 0xe8,                         /* fld1                 */
1001         0xde, 0xf1,                         /* fdivp                */
1002         0x9b,                               /* fwait                */
1003         0xdb, 0xe2,                         /* fnclex               */
1004         0xdd, 0xd8,                         /* fstp %st(0)          */
1005         0xdd, 0xd8,                         /* fstp %st(0)          */
1006         0xd9, 0x6c, 0x24, 0x02,             /* fldcw 0x2(%esp)      */
1007         0x83, 0xc4, 0x04,                   /* add $0x4,%esp        */
1008         0xc3,                               /* ret                  */
1009     };
1010
1011     struct fpu_exception_info info;
1012
1013     memset(&info, 0, sizeof(info));
1014     run_exception_test(fpu_exception_handler, &info, fpu_exception_test_ie, sizeof(fpu_exception_test_ie), 0);
1015     ok(info.exception_code == EXCEPTION_FLT_STACK_CHECK,
1016             "Got exception code %#x, expected EXCEPTION_FLT_STACK_CHECK\n", info.exception_code);
1017     ok(info.exception_offset == 0x19 ||
1018        broken( is_wow64 && info.exception_offset == info.eip_offset ),
1019        "Got exception offset %#x, expected 0x19\n", info.exception_offset);
1020     ok(info.eip_offset == 0x1b, "Got EIP offset %#x, expected 0x1b\n", info.eip_offset);
1021
1022     memset(&info, 0, sizeof(info));
1023     run_exception_test(fpu_exception_handler, &info, fpu_exception_test_de, sizeof(fpu_exception_test_de), 0);
1024     ok(info.exception_code == EXCEPTION_FLT_DIVIDE_BY_ZERO,
1025             "Got exception code %#x, expected EXCEPTION_FLT_DIVIDE_BY_ZERO\n", info.exception_code);
1026     ok(info.exception_offset == 0x17 ||
1027        broken( is_wow64 && info.exception_offset == info.eip_offset ),
1028        "Got exception offset %#x, expected 0x17\n", info.exception_offset);
1029     ok(info.eip_offset == 0x19, "Got EIP offset %#x, expected 0x19\n", info.eip_offset);
1030 }
1031
1032 struct dpe_exception_info {
1033     BOOL exception_caught;
1034     DWORD exception_info;
1035 };
1036
1037 static DWORD dpe_exception_handler(EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
1038         CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher)
1039 {
1040     DWORD old_prot;
1041     struct dpe_exception_info *info = *(struct dpe_exception_info **)(frame + 1);
1042
1043     ok(rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION,
1044        "Exception code %08x\n", rec->ExceptionCode);
1045     ok(rec->NumberParameters == 2,
1046        "Parameter count: %d\n", rec->NumberParameters);
1047     ok((LPVOID)rec->ExceptionInformation[1] == code_mem,
1048        "Exception address: %p, expected %p\n",
1049        (LPVOID)rec->ExceptionInformation[1], code_mem);
1050
1051     info->exception_info = rec->ExceptionInformation[0];
1052     info->exception_caught = TRUE;
1053
1054     VirtualProtect(code_mem, 1, PAGE_EXECUTE_READWRITE, &old_prot);
1055     return ExceptionContinueExecution;
1056 }
1057
1058 static void test_dpe_exceptions(void)
1059 {
1060     static char single_ret[] = {0xC3};
1061     struct dpe_exception_info info;
1062     NTSTATUS stat;
1063     BOOL has_hw_support;
1064     BOOL is_permanent = FALSE, can_test_without = TRUE, can_test_with = TRUE;
1065     DWORD val;
1066     ULONG len;
1067
1068     /* Query DEP with len to small */
1069     stat = pNtQueryInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val - 1, &len);
1070     if(stat == STATUS_INVALID_INFO_CLASS)
1071     {
1072         skip("This software platform does not support DEP\n");
1073         return;
1074     }
1075     ok(stat == STATUS_INFO_LENGTH_MISMATCH, "buffer too small: %08x\n", stat);
1076
1077     /* Query DEP */
1078     stat = pNtQueryInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val, &len);
1079     ok(stat == STATUS_SUCCESS, "querying DEP: status %08x\n", stat);
1080     if(stat == STATUS_SUCCESS)
1081     {
1082         ok(len == sizeof val, "returned length: %d\n", len);
1083         if(val & MEM_EXECUTE_OPTION_PERMANENT)
1084         {
1085             skip("toggling DEP impossible - status locked\n");
1086             is_permanent = TRUE;
1087             if(val & MEM_EXECUTE_OPTION_DISABLE)
1088                 can_test_without = FALSE;
1089             else
1090                 can_test_with = FALSE;
1091         }
1092     }
1093
1094     if(!is_permanent)
1095     {
1096         /* Enable DEP */
1097         val = MEM_EXECUTE_OPTION_DISABLE;
1098         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1099         ok(stat == STATUS_SUCCESS, "enabling DEP: status %08x\n", stat);
1100     }
1101
1102     if(can_test_with)
1103     {
1104         /* Try access to locked page with DEP on*/
1105         info.exception_caught = FALSE;
1106         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_NOACCESS);
1107         ok(info.exception_caught == TRUE, "Execution of disabled memory succeeded\n");
1108         ok(info.exception_info == EXCEPTION_READ_FAULT ||
1109            info.exception_info == EXCEPTION_EXECUTE_FAULT,
1110               "Access violation type: %08x\n", (unsigned)info.exception_info);
1111         has_hw_support = info.exception_info == EXCEPTION_EXECUTE_FAULT;
1112         trace("DEP hardware support: %s\n", has_hw_support?"Yes":"No");
1113
1114         /* Try execution of data with DEP on*/
1115         info.exception_caught = FALSE;
1116         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_READWRITE);
1117         if(has_hw_support)
1118         {
1119             ok(info.exception_caught == TRUE, "Execution of data memory succeeded\n");
1120             ok(info.exception_info == EXCEPTION_EXECUTE_FAULT,
1121                   "Access violation type: %08x\n", (unsigned)info.exception_info);
1122         }
1123         else
1124             ok(info.exception_caught == FALSE, "Execution trapped without hardware support\n");
1125     }
1126     else
1127         skip("DEP is in AlwaysOff state\n");
1128
1129     if(!is_permanent)
1130     {
1131         /* Disable DEP */
1132         val = MEM_EXECUTE_OPTION_ENABLE;
1133         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1134         ok(stat == STATUS_SUCCESS, "disabling DEP: status %08x\n", stat);
1135     }
1136
1137     /* page is read without exec here */
1138     if(can_test_without)
1139     {
1140         /* Try execution of data with DEP off */
1141         info.exception_caught = FALSE;
1142         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_READWRITE);
1143         ok(info.exception_caught == FALSE, "Execution trapped with DEP turned off\n");
1144
1145         /* Try access to locked page with DEP off - error code is different than
1146            with hardware DEP on */
1147         info.exception_caught = FALSE;
1148         run_exception_test(dpe_exception_handler, &info, single_ret, sizeof(single_ret), PAGE_NOACCESS);
1149         ok(info.exception_caught == TRUE, "Execution of disabled memory succeeded\n");
1150         ok(info.exception_info == EXCEPTION_READ_FAULT,
1151               "Access violation type: %08x\n", (unsigned)info.exception_info);
1152     }
1153     else
1154         skip("DEP is in AlwaysOn state\n");
1155
1156     if(!is_permanent)
1157     {
1158         /* Turn off DEP permanently */
1159         val = MEM_EXECUTE_OPTION_ENABLE | MEM_EXECUTE_OPTION_PERMANENT;
1160         stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1161         ok(stat == STATUS_SUCCESS, "disabling DEP permanently: status %08x\n", stat);
1162     }
1163
1164     /* Try to turn off DEP */
1165     val = MEM_EXECUTE_OPTION_ENABLE;
1166     stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1167     ok(stat == STATUS_ACCESS_DENIED, "disabling DEP while permanent: status %08x\n", stat);
1168
1169     /* Try to turn on DEP */
1170     val = MEM_EXECUTE_OPTION_DISABLE;
1171     stat = pNtSetInformationProcess(GetCurrentProcess(), ProcessExecuteFlags, &val, sizeof val);
1172     ok(stat == STATUS_ACCESS_DENIED, "enabling DEP while permanent: status %08x\n", stat);
1173 }
1174
1175 #elif defined(__x86_64__)
1176
1177 #define UNW_FLAG_NHANDLER  0
1178 #define UNW_FLAG_EHANDLER  1
1179 #define UNW_FLAG_UHANDLER  2
1180 #define UNW_FLAG_CHAININFO 4
1181
1182 #define UWOP_PUSH_NONVOL     0
1183 #define UWOP_ALLOC_LARGE     1
1184 #define UWOP_ALLOC_SMALL     2
1185 #define UWOP_SET_FPREG       3
1186 #define UWOP_SAVE_NONVOL     4
1187 #define UWOP_SAVE_NONVOL_FAR 5
1188 #define UWOP_SAVE_XMM128     8
1189 #define UWOP_SAVE_XMM128_FAR 9
1190 #define UWOP_PUSH_MACHFRAME  10
1191
1192 struct results
1193 {
1194     int rip_offset;   /* rip offset from code start */
1195     int rbp_offset;   /* rbp offset from stack pointer */
1196     int handler;      /* expect handler to be set? */
1197     int rip;          /* expected final rip value */
1198     int frame;        /* expected frame return value */
1199     int regs[8][2];   /* expected values for registers */
1200 };
1201
1202 struct unwind_test
1203 {
1204     const BYTE *function;
1205     size_t function_size;
1206     const BYTE *unwind_info;
1207     const struct results *results;
1208     unsigned int nb_results;
1209 };
1210
1211 enum regs
1212 {
1213     rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
1214     r8,  r9,  r10, r11, r12, r13, r14, r15
1215 };
1216
1217 static const char * const reg_names[16] =
1218 {
1219     "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
1220     "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15"
1221 };
1222
1223 #define UWOP(code,info) (UWOP_##code | ((info) << 4))
1224
1225 static void call_virtual_unwind( int testnum, const struct unwind_test *test )
1226 {
1227     static const int code_offset = 1024;
1228     static const int unwind_offset = 2048;
1229     void *handler, *data;
1230     CONTEXT context;
1231     RUNTIME_FUNCTION runtime_func;
1232     KNONVOLATILE_CONTEXT_POINTERS ctx_ptr;
1233     UINT i, j, k;
1234     ULONG64 fake_stack[256];
1235     ULONG64 frame, orig_rip, orig_rbp, unset_reg;
1236     UINT unwind_size = 4 + 2 * test->unwind_info[2] + 8;
1237
1238     memcpy( (char *)code_mem + code_offset, test->function, test->function_size );
1239     memcpy( (char *)code_mem + unwind_offset, test->unwind_info, unwind_size );
1240
1241     runtime_func.BeginAddress = code_offset;
1242     runtime_func.EndAddress = code_offset + test->function_size;
1243     runtime_func.UnwindData = unwind_offset;
1244
1245     trace( "code: %p stack: %p\n", code_mem, fake_stack );
1246
1247     for (i = 0; i < test->nb_results; i++)
1248     {
1249         memset( &ctx_ptr, 0, sizeof(ctx_ptr) );
1250         memset( &context, 0x55, sizeof(context) );
1251         memset( &unset_reg, 0x55, sizeof(unset_reg) );
1252         for (j = 0; j < 256; j++) fake_stack[j] = j * 8;
1253
1254         context.Rsp = (ULONG_PTR)fake_stack;
1255         context.Rbp = (ULONG_PTR)fake_stack + test->results[i].rbp_offset;
1256         orig_rbp = context.Rbp;
1257         orig_rip = (ULONG64)code_mem + code_offset + test->results[i].rip_offset;
1258
1259         trace( "%u/%u: rip=%p (%02x) rbp=%p rsp=%p\n", testnum, i,
1260                (void *)orig_rip, *(BYTE *)orig_rip, (void *)orig_rbp, (void *)context.Rsp );
1261
1262         data = (void *)0xdeadbeef;
1263         handler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, (ULONG64)code_mem, orig_rip,
1264                                     &runtime_func, &context, &data, &frame, &ctx_ptr );
1265         if (test->results[i].handler)
1266         {
1267             ok( (char *)handler == (char *)code_mem + 0x200,
1268                 "%u/%u: wrong handler %p/%p\n", testnum, i, handler, (char *)code_mem + 0x200 );
1269             if (handler) ok( *(DWORD *)data == 0x08070605,
1270                              "%u/%u: wrong handler data %p\n", testnum, i, data );
1271         }
1272         else
1273         {
1274             ok( handler == NULL, "%u/%u: handler %p instead of NULL\n", testnum, i, handler );
1275             ok( data == (void *)0xdeadbeef, "%u/%u: handler data set to %p\n", testnum, i, data );
1276         }
1277
1278         ok( context.Rip == test->results[i].rip, "%u/%u: wrong rip %p/%x\n",
1279             testnum, i, (void *)context.Rip, test->results[i].rip );
1280         ok( frame == (ULONG64)fake_stack + test->results[i].frame, "%u/%u: wrong frame %p/%p\n",
1281             testnum, i, (void *)frame, (char *)fake_stack + test->results[i].frame );
1282
1283         for (j = 0; j < 16; j++)
1284         {
1285             static const UINT nb_regs = sizeof(test->results[i].regs) / sizeof(test->results[i].regs[0]);
1286
1287             for (k = 0; k < nb_regs; k++)
1288             {
1289                 if (test->results[i].regs[k][0] == -1)
1290                 {
1291                     k = nb_regs;
1292                     break;
1293                 }
1294                 if (test->results[i].regs[k][0] == j) break;
1295             }
1296
1297             if (j == rsp)  /* rsp is special */
1298             {
1299                 ok( !ctx_ptr.u2.IntegerContext[j],
1300                     "%u/%u: rsp should not be set in ctx_ptr\n", testnum, i );
1301                 ok( context.Rsp == (ULONG64)fake_stack + test->results[i].regs[k][1],
1302                     "%u/%u: register rsp wrong %p/%p\n",
1303                     testnum, i, (void *)context.Rsp, (char *)fake_stack + test->results[i].regs[k][1] );
1304                 continue;
1305             }
1306
1307             if (ctx_ptr.u2.IntegerContext[j])
1308             {
1309                 ok( k < nb_regs, "%u/%u: register %s should not be set to %lx\n",
1310                     testnum, i, reg_names[j], *(&context.Rax + j) );
1311                 if (k < nb_regs)
1312                     ok( *(&context.Rax + j) == test->results[i].regs[k][1],
1313                         "%u/%u: register %s wrong %p/%x\n",
1314                         testnum, i, reg_names[j], (void *)*(&context.Rax + j), test->results[i].regs[k][1] );
1315             }
1316             else
1317             {
1318                 ok( k == nb_regs, "%u/%u: register %s should be set\n", testnum, i, reg_names[j] );
1319                 if (j == rbp)
1320                     ok( context.Rbp == orig_rbp, "%u/%u: register rbp wrong %p/unset\n",
1321                         testnum, i, (void *)context.Rbp );
1322                 else
1323                     ok( *(&context.Rax + j) == unset_reg,
1324                         "%u/%u: register %s wrong %p/unset\n",
1325                         testnum, i, reg_names[j], (void *)*(&context.Rax + j));
1326             }
1327         }
1328     }
1329 }
1330
1331 static void test_virtual_unwind(void)
1332 {
1333     static const BYTE function_0[] =
1334     {
1335         0xff, 0xf5,                                  /* 00: push %rbp */
1336         0x48, 0x81, 0xec, 0x10, 0x01, 0x00, 0x00,    /* 02: sub $0x110,%rsp */
1337         0x48, 0x8d, 0x6c, 0x24, 0x30,                /* 09: lea 0x30(%rsp),%rbp */
1338         0x48, 0x89, 0x9d, 0xf0, 0x00, 0x00, 0x00,    /* 0e: mov %rbx,0xf0(%rbp) */
1339         0x48, 0x89, 0xb5, 0xf8, 0x00, 0x00, 0x00,    /* 15: mov %rsi,0xf8(%rbp) */
1340         0x90,                                        /* 1c: nop */
1341         0x48, 0x8b, 0x9d, 0xf0, 0x00, 0x00, 0x00,    /* 1d: mov 0xf0(%rbp),%rbx */
1342         0x48, 0x8b, 0xb5, 0xf8, 0x00, 0x00, 0x00,    /* 24: mov 0xf8(%rbp),%rsi */
1343         0x48, 0x8d, 0xa5, 0xe0, 0x00, 0x00, 0x00,    /* 2b: lea 0xe0(%rbp),%rsp */
1344         0x5d,                                        /* 32: pop %rbp */
1345         0xc3                                         /* 33: ret */
1346     };
1347
1348     static const BYTE unwind_info_0[] =
1349     {
1350         1 | (UNW_FLAG_EHANDLER << 3),  /* version + flags */
1351         0x1c,                          /* prolog size */
1352         8,                             /* opcode count */
1353         (0x03 << 4) | rbp,             /* frame reg rbp offset 0x30 */
1354
1355         0x1c, UWOP(SAVE_NONVOL, rsi), 0x25, 0, /* 1c: mov %rsi,0x128(%rsp) */
1356         0x15, UWOP(SAVE_NONVOL, rbx), 0x24, 0, /* 15: mov %rbx,0x120(%rsp) */
1357         0x0e, UWOP(SET_FPREG, rbp),            /* 0e: lea 0x30(%rsp),rbp */
1358         0x09, UWOP(ALLOC_LARGE, 0), 0x22, 0,   /* 09: sub $0x110,%rsp */
1359         0x02, UWOP(PUSH_NONVOL, rbp),          /* 02: push %rbp */
1360
1361         0x00, 0x02, 0x00, 0x00,  /* handler */
1362         0x05, 0x06, 0x07, 0x08,  /* data */
1363     };
1364
1365     static const struct results results_0[] =
1366     {
1367       /* offset  rbp   handler  rip   frame   registers */
1368         { 0x00,  0x40,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1369         { 0x02,  0x40,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbp,0x000}, {-1,-1} }},
1370         { 0x09,  0x40,  FALSE, 0x118, 0x000, { {rsp,0x120}, {rbp,0x110}, {-1,-1} }},
1371         { 0x0e,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {-1,-1} }},
1372         { 0x15,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {-1,-1} }},
1373         { 0x1c,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1374         { 0x1d,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1375         { 0x24,  0x40,  TRUE,  0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {rbx,0x130}, {rsi,0x138}, {-1,-1}}},
1376         { 0x2b,  0x40,  FALSE, 0x128, 0x010, { {rsp,0x130}, {rbp,0x120}, {-1,-1}}},
1377         { 0x32,  0x40,  FALSE, 0x008, 0x010, { {rsp,0x010}, {rbp,0x000}, {-1,-1}}},
1378         { 0x33,  0x40,  FALSE, 0x000, 0x010, { {rsp,0x008}, {-1,-1}}},
1379     };
1380
1381
1382     static const BYTE function_1[] =
1383     {
1384         0x53,                     /* 00: push %rbx */
1385         0x55,                     /* 01: push %rbp */
1386         0x56,                     /* 02: push %rsi */
1387         0x57,                     /* 03: push %rdi */
1388         0x41, 0x54,               /* 04: push %r12 */
1389         0x48, 0x83, 0xec, 0x30,   /* 06: sub $0x30,%rsp */
1390         0x90, 0x90,               /* 0a: nop; nop */
1391         0x48, 0x83, 0xc4, 0x30,   /* 0c: add $0x30,%rsp */
1392         0x41, 0x5c,               /* 10: pop %r12 */
1393         0x5f,                     /* 12: pop %rdi */
1394         0x5e,                     /* 13: pop %rsi */
1395         0x5d,                     /* 14: pop %rbp */
1396         0x5b,                     /* 15: pop %rbx */
1397         0xc3                      /* 16: ret */
1398      };
1399
1400     static const BYTE unwind_info_1[] =
1401     {
1402         1 | (UNW_FLAG_EHANDLER << 3),  /* version + flags */
1403         0x0a,                          /* prolog size */
1404         6,                             /* opcode count */
1405         0,                             /* frame reg */
1406
1407         0x0a, UWOP(ALLOC_SMALL, 5),   /* 0a: sub $0x30,%rsp */
1408         0x06, UWOP(PUSH_NONVOL, r12), /* 06: push %r12 */
1409         0x04, UWOP(PUSH_NONVOL, rdi), /* 04: push %rdi */
1410         0x03, UWOP(PUSH_NONVOL, rsi), /* 03: push %rsi */
1411         0x02, UWOP(PUSH_NONVOL, rbp), /* 02: push %rbp */
1412         0x01, UWOP(PUSH_NONVOL, rbx), /* 01: push %rbx */
1413
1414         0x00, 0x02, 0x00, 0x00,  /* handler */
1415         0x05, 0x06, 0x07, 0x08,  /* data */
1416     };
1417
1418     static const struct results results_1[] =
1419     {
1420       /* offset  rbp   handler  rip   frame   registers */
1421         { 0x00,  0x50,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1422         { 0x01,  0x50,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbx,0x000}, {-1,-1} }},
1423         { 0x02,  0x50,  FALSE, 0x010, 0x000, { {rsp,0x018}, {rbx,0x008}, {rbp,0x000}, {-1,-1} }},
1424         { 0x03,  0x50,  FALSE, 0x018, 0x000, { {rsp,0x020}, {rbx,0x010}, {rbp,0x008}, {rsi,0x000}, {-1,-1} }},
1425         { 0x04,  0x50,  FALSE, 0x020, 0x000, { {rsp,0x028}, {rbx,0x018}, {rbp,0x010}, {rsi,0x008}, {rdi,0x000}, {-1,-1} }},
1426         { 0x06,  0x50,  FALSE, 0x028, 0x000, { {rsp,0x030}, {rbx,0x020}, {rbp,0x018}, {rsi,0x010}, {rdi,0x008}, {r12,0x000}, {-1,-1} }},
1427         { 0x0a,  0x50,  TRUE,  0x058, 0x000, { {rsp,0x060}, {rbx,0x050}, {rbp,0x048}, {rsi,0x040}, {rdi,0x038}, {r12,0x030}, {-1,-1} }},
1428         { 0x0c,  0x50,  FALSE, 0x058, 0x000, { {rsp,0x060}, {rbx,0x050}, {rbp,0x048}, {rsi,0x040}, {rdi,0x038}, {r12,0x030}, {-1,-1} }},
1429         { 0x10,  0x50,  FALSE, 0x028, 0x000, { {rsp,0x030}, {rbx,0x020}, {rbp,0x018}, {rsi,0x010}, {rdi,0x008}, {r12,0x000}, {-1,-1} }},
1430         { 0x12,  0x50,  FALSE, 0x020, 0x000, { {rsp,0x028}, {rbx,0x018}, {rbp,0x010}, {rsi,0x008}, {rdi,0x000}, {-1,-1} }},
1431         { 0x13,  0x50,  FALSE, 0x018, 0x000, { {rsp,0x020}, {rbx,0x010}, {rbp,0x008}, {rsi,0x000}, {-1,-1} }},
1432         { 0x14,  0x50,  FALSE, 0x010, 0x000, { {rsp,0x018}, {rbx,0x008}, {rbp,0x000}, {-1,-1} }},
1433         { 0x15,  0x50,  FALSE, 0x008, 0x000, { {rsp,0x010}, {rbx,0x000}, {-1,-1} }},
1434         { 0x16,  0x50,  FALSE, 0x000, 0x000, { {rsp,0x008}, {-1,-1} }},
1435     };
1436
1437     static const struct unwind_test tests[] =
1438     {
1439         { function_0, sizeof(function_0), unwind_info_0,
1440           results_0, sizeof(results_0)/sizeof(results_0[0]) },
1441         { function_1, sizeof(function_1), unwind_info_1,
1442           results_1, sizeof(results_1)/sizeof(results_1[0]) }
1443     };
1444     unsigned int i;
1445
1446     for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
1447         call_virtual_unwind( i, &tests[i] );
1448 }
1449
1450 #endif  /* __x86_64__ */
1451
1452 START_TEST(exception)
1453 {
1454     HMODULE hntdll = GetModuleHandleA("ntdll.dll");
1455
1456     code_mem = VirtualAlloc(NULL, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
1457     if(!code_mem) {
1458         trace("VirtualAlloc failed\n");
1459         return;
1460     }
1461
1462     pNtCurrentTeb        = (void *)GetProcAddress( hntdll, "NtCurrentTeb" );
1463     pNtGetContextThread  = (void *)GetProcAddress( hntdll, "NtGetContextThread" );
1464     pNtSetContextThread  = (void *)GetProcAddress( hntdll, "NtSetContextThread" );
1465     pNtReadVirtualMemory = (void *)GetProcAddress( hntdll, "NtReadVirtualMemory" );
1466     pRtlRaiseException   = (void *)GetProcAddress( hntdll, "RtlRaiseException" );
1467     pNtTerminateProcess  = (void *)GetProcAddress( hntdll, "NtTerminateProcess" );
1468     pRtlAddVectoredExceptionHandler    = (void *)GetProcAddress( hntdll,
1469                                                                  "RtlAddVectoredExceptionHandler" );
1470     pRtlRemoveVectoredExceptionHandler = (void *)GetProcAddress( hntdll,
1471                                                                  "RtlRemoveVectoredExceptionHandler" );
1472     pNtQueryInformationProcess         = (void*)GetProcAddress( hntdll,
1473                                                                  "NtQueryInformationProcess" );
1474     pNtSetInformationProcess           = (void*)GetProcAddress( hntdll,
1475                                                                  "NtSetInformationProcess" );
1476     pIsWow64Process = (void *)GetProcAddress(GetModuleHandle("kernel32.dll"), "IsWow64Process");
1477
1478 #ifdef __i386__
1479     if (!pNtCurrentTeb)
1480     {
1481         skip( "NtCurrentTeb not found\n" );
1482         return;
1483     }
1484     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &is_wow64 )) is_wow64 = FALSE;
1485
1486     if (pRtlAddVectoredExceptionHandler && pRtlRemoveVectoredExceptionHandler)
1487         have_vectored_api = TRUE;
1488     else
1489         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler not found\n");
1490
1491     my_argc = winetest_get_mainargs( &my_argv );
1492     if (my_argc >= 4)
1493     {
1494         void *addr;
1495         sscanf( my_argv[3], "%p", &addr );
1496
1497         if (addr != &test_stage)
1498         {
1499             skip( "child process not mapped at same address (%p/%p)\n", &test_stage, addr);
1500             return;
1501         }
1502
1503         /* child must be run under a debugger */
1504         if (!pNtCurrentTeb()->Peb->BeingDebugged)
1505         {
1506             ok(FALSE, "child process not being debugged?\n");
1507             return;
1508         }
1509
1510         if (pRtlRaiseException)
1511         {
1512             test_stage = 1;
1513             run_rtlraiseexception_test(0x12345);
1514             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
1515             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
1516             test_stage = 2;
1517             run_rtlraiseexception_test(0x12345);
1518             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
1519             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
1520         }
1521         else
1522             skip( "RtlRaiseException not found\n" );
1523
1524         /* rest of tests only run in parent */
1525         return;
1526     }
1527
1528     test_prot_fault();
1529     test_exceptions();
1530     test_rtlraiseexception();
1531     test_debugger();
1532     test_simd_exceptions();
1533     test_fpu_exceptions();
1534     test_dpe_exceptions();
1535
1536 #elif defined(__x86_64__)
1537
1538     test_virtual_unwind();
1539
1540 #endif
1541
1542     VirtualFree(code_mem, 0, MEM_FREE);
1543 }