ntdll/tests: Clear the direction flag in the handler since Windows may not do it.
[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 #include "ntstatus.h"
29 #define WIN32_NO_STATUS
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winnt.h"
33 #include "winreg.h"
34 #include "winternl.h"
35 #include "excpt.h"
36 #include "wine/test.h"
37
38 #ifdef __i386__
39 static int      my_argc;
40 static char**   my_argv;
41 static int      test_stage;
42
43 static struct _TEB * (WINAPI *pNtCurrentTeb)(void);
44 static NTSTATUS  (WINAPI *pNtGetContextThread)(HANDLE,CONTEXT*);
45 static NTSTATUS  (WINAPI *pNtSetContextThread)(HANDLE,CONTEXT*);
46 static NTSTATUS  (WINAPI *pRtlRaiseException)(EXCEPTION_RECORD *rec);
47 static PVOID     (WINAPI *pRtlAddVectoredExceptionHandler)(ULONG first, PVECTORED_EXCEPTION_HANDLER func);
48 static ULONG     (WINAPI *pRtlRemoveVectoredExceptionHandler)(PVOID handler);
49 static NTSTATUS  (WINAPI *pNtReadVirtualMemory)(HANDLE, const void*, void*, SIZE_T, SIZE_T*);
50 static NTSTATUS  (WINAPI *pNtTerminateProcess)(HANDLE handle, LONG exit_code);
51 static void *code_mem;
52
53 /* Test various instruction combinations that cause a protection fault on the i386,
54  * and check what the resulting exception looks like.
55  */
56
57 static const struct exception
58 {
59     BYTE     code[18];   /* asm code */
60     BYTE     offset;     /* offset of faulting instruction */
61     BYTE     length;     /* length of faulting instruction */
62     NTSTATUS status;     /* expected status code */
63     DWORD    nb_params;  /* expected number of parameters */
64     DWORD    params[4];  /* expected parameters */
65 } exceptions[] =
66 {
67     /* test some privileged instructions */
68     { { 0xfb, 0xc3 },  /* 0: sti; ret */
69       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
70     { { 0x6c, 0xc3 },  /* 1: insb (%dx); ret */
71       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
72     { { 0x6d, 0xc3 },  /* 2: insl (%dx); ret */
73       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
74     { { 0x6e, 0xc3 },  /* 3: outsb (%dx); ret */
75       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
76     { { 0x6f, 0xc3 },  /* 4: outsl (%dx); ret */
77       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
78     { { 0xe4, 0x11, 0xc3 },  /* 5: inb $0x11,%al; ret */
79       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
80     { { 0xe5, 0x11, 0xc3 },  /* 6: inl $0x11,%eax; ret */
81       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
82     { { 0xe6, 0x11, 0xc3 },  /* 7: outb %al,$0x11; ret */
83       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
84     { { 0xe7, 0x11, 0xc3 },  /* 8: outl %eax,$0x11; ret */
85       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
86     { { 0xed, 0xc3 },  /* 9: inl (%dx),%eax; ret */
87       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
88     { { 0xee, 0xc3 },  /* 10: outb %al,(%dx); ret */
89       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
90     { { 0xef, 0xc3 },  /* 11: outl %eax,(%dx); ret */
91       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
92     { { 0xf4, 0xc3 },  /* 12: hlt; ret */
93       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
94     { { 0xfa, 0xc3 },  /* 13: cli; ret */
95       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
96
97     /* test long jump to invalid selector */
98     { { 0xea, 0, 0, 0, 0, 0, 0, 0xc3 },  /* 14: ljmp $0,$0; ret */
99       0, 7, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
100
101     /* test iret to invalid selector */
102     { { 0x6a, 0x00, 0x6a, 0x00, 0x6a, 0x00, 0xcf, 0x83, 0xc4, 0x0c, 0xc3 },
103       /* 15: pushl $0; pushl $0; pushl $0; iret; addl $12,%esp; ret */
104       6, 1, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
105
106     /* test loading an invalid selector */
107     { { 0xb8, 0xef, 0xbe, 0x00, 0x00, 0x8e, 0xe8, 0xc3 },  /* 16: mov $beef,%ax; mov %ax,%gs; ret */
108       5, 2, STATUS_ACCESS_VIOLATION, 2, { 0, 0xbee8 } }, /* 0xbee8 or 0xffffffff */
109
110     /* test accessing a zero selector */
111     { { 0x06, 0x31, 0xc0, 0x8e, 0xc0, 0x26, 0xa1, 0, 0, 0, 0, 0x07, 0xc3 },
112       /* 17: push %es; xor %eax,%eax; mov %ax,%es; mov %es:(0),%ax; pop %es; ret */
113       5, 6, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
114
115     /* test moving %cs -> %ss */
116     { { 0x0e, 0x17, 0x58, 0xc3 },  /* 18: pushl %cs; popl %ss; popl %eax; ret */
117       1, 1, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
118
119     /* 19: test overlong instruction (limit is 16 bytes) */
120     { { 0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0xfa,0xc3 },
121       0, 16, STATUS_ILLEGAL_INSTRUCTION, 0 },
122     { { 0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0x64,0xfa,0xc3 },
123       0, 15, STATUS_PRIVILEGED_INSTRUCTION, 0 },
124
125     /* test invalid interrupt */
126     { { 0xcd, 0xff, 0xc3 },   /* 21: int $0xff; ret */
127       0, 2, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
128
129     /* test moves to/from Crx */
130     { { 0x0f, 0x20, 0xc0, 0xc3 },  /* 22: movl %cr0,%eax; ret */
131       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
132     { { 0x0f, 0x20, 0xe0, 0xc3 },  /* 23: movl %cr4,%eax; ret */
133       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
134     { { 0x0f, 0x22, 0xc0, 0xc3 },  /* 24: movl %eax,%cr0; ret */
135       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
136     { { 0x0f, 0x22, 0xe0, 0xc3 },  /* 25: movl %eax,%cr4; ret */
137       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
138
139     /* test moves to/from Drx */
140     { { 0x0f, 0x21, 0xc0, 0xc3 },  /* 26: movl %dr0,%eax; ret */
141       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
142     { { 0x0f, 0x21, 0xc8, 0xc3 },  /* 27: movl %dr1,%eax; ret */
143       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
144     { { 0x0f, 0x21, 0xf8, 0xc3 },  /* 28: movl %dr7,%eax; ret */
145       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
146     { { 0x0f, 0x23, 0xc0, 0xc3 },  /* 29: movl %eax,%dr0; ret */
147       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
148     { { 0x0f, 0x23, 0xc8, 0xc3 },  /* 30: movl %eax,%dr1; ret */
149       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
150     { { 0x0f, 0x23, 0xf8, 0xc3 },  /* 31: movl %eax,%dr7; ret */
151       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
152
153     /* test memory reads */
154     { { 0xa1, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* 32: movl 0xfffffffc,%eax; ret */
155       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffc } },
156     { { 0xa1, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* 33: movl 0xfffffffd,%eax; ret */
157       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffd } },
158     { { 0xa1, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* 34: movl 0xfffffffe,%eax; ret */
159       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffe } },
160     { { 0xa1, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* 35: movl 0xffffffff,%eax; ret */
161       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
162
163     /* test memory writes */
164     { { 0xa3, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* 36: movl %eax,0xfffffffc; ret */
165       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffc } },
166     { { 0xa3, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* 37: movl %eax,0xfffffffd; ret */
167       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffd } },
168     { { 0xa3, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* 38: movl %eax,0xfffffffe; ret */
169       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffe } },
170     { { 0xa3, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* 39: movl %eax,0xffffffff; ret */
171       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xffffffff } },
172
173     /* 40: test exception with cleared %ds and %es */
174     { { 0x1e, 0x06, 0x31, 0xc0, 0x8e, 0xd8, 0x8e, 0xc0, 0xfa, 0x07, 0x1f, 0xc3 },
175           /* push %ds; push %es; xorl %eax,%eax; mov %ax,%ds; mov %ax,%es; cli; pop %es; pop %ds; ret */
176       8, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
177 };
178
179 static int got_exception;
180 static BOOL have_vectored_api;
181
182 static void run_exception_test(void *handler, const void* context,
183                                const void *code, unsigned int code_size)
184 {
185     struct {
186         EXCEPTION_REGISTRATION_RECORD frame;
187         const void *context;
188     } exc_frame;
189     void (*func)(void) = code_mem;
190
191     exc_frame.frame.Handler = handler;
192     exc_frame.frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
193     exc_frame.context = context;
194
195     memcpy(code_mem, code, code_size);
196
197     pNtCurrentTeb()->Tib.ExceptionList = &exc_frame.frame;
198     func();
199     pNtCurrentTeb()->Tib.ExceptionList = exc_frame.frame.Prev;
200 }
201
202 LONG CALLBACK rtlraiseexception_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
203 {
204     PCONTEXT context = ExceptionInfo->ContextRecord;
205     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
206     trace("vect. handler %08x addr:%p context.Eip:%x\n", rec->ExceptionCode,
207           rec->ExceptionAddress, context->Eip);
208
209     todo_wine {
210     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
211        rec->ExceptionAddress, (char *)code_mem + 0xb);
212
213     if (pNtCurrentTeb()->Peb->BeingDebugged)
214         ok((void *)context->Eax == pRtlRaiseException, "debugger managed to modify Eax to %x should be %p\n",
215            context->Eax, pRtlRaiseException);
216     }
217
218     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
219      * even if raised by RtlRaiseException
220      */
221     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
222     {
223         ok(context->Eip == (DWORD)code_mem + 0xa ||
224            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
225            "Eip at %x instead of %x or %x\n", context->Eip,
226            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
227     }
228     else
229     {
230         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
231            context->Eip, (DWORD)code_mem + 0xb);
232     }
233
234     /* test if context change is preserved from vectored handler to stack handlers */
235     context->Eax = 0xf00f00f0;
236     return EXCEPTION_CONTINUE_SEARCH;
237 }
238
239 static DWORD rtlraiseexception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
240                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
241 {
242     trace( "exception: %08x flags:%x addr:%p context: Eip:%x\n",
243            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Eip );
244
245     todo_wine {
246     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
247        rec->ExceptionAddress, (char *)code_mem + 0xb);
248     }
249
250     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
251      * even if raised by RtlRaiseException
252      */
253     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
254     {
255         ok(context->Eip == (DWORD)code_mem + 0xa ||
256            broken(context->Eip == (DWORD)code_mem + 0xb), /* win2k3 */
257            "Eip at %x instead of %x or %x\n", context->Eip,
258            (DWORD)code_mem + 0xa, (DWORD)code_mem + 0xb);
259     }
260     else
261     {
262         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
263            context->Eip, (DWORD)code_mem + 0xb);
264     }
265
266     if(have_vectored_api)
267         ok(context->Eax == 0xf00f00f0, "Eax is %x, should have been set to 0xf00f00f0 in vectored handler\n",
268            context->Eax);
269
270     /* give the debugger a chance to examine the state a second time */
271     /* without the exception handler changing Eip */
272     if (test_stage == 2)
273         return ExceptionContinueSearch;
274
275     /* Eip in context is decreased by 1
276      * Increase it again, else execution will continue in the middle of a instruction */
277     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT && (context->Eip == (DWORD)code_mem + 0xa))
278         context->Eip += 1;
279     return ExceptionContinueExecution;
280 }
281
282
283 static const BYTE call_one_arg_code[] = {
284         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
285         0x50,                   /* push %eax */
286         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
287         0xff, 0xd0,             /* call *%eax */
288         0x90,                   /* nop */
289         0x90,                   /* nop */
290         0x90,                   /* nop */
291         0x90,                   /* nop */
292         0xc3,                   /* ret */
293 };
294
295
296 static void run_rtlraiseexception_test(DWORD exceptioncode)
297 {
298     EXCEPTION_REGISTRATION_RECORD frame;
299     EXCEPTION_RECORD record;
300     PVOID vectored_handler = NULL;
301
302     void (*func)(void* function, EXCEPTION_RECORD* record) = code_mem;
303
304     record.ExceptionCode = exceptioncode;
305     record.ExceptionFlags = 0;
306     record.ExceptionRecord = NULL;
307     record.ExceptionAddress = NULL; /* does not matter, copied return address */
308     record.NumberParameters = 0;
309
310     frame.Handler = rtlraiseexception_handler;
311     frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
312
313     memcpy(code_mem, call_one_arg_code, sizeof(call_one_arg_code));
314
315     pNtCurrentTeb()->Tib.ExceptionList = &frame;
316     if (have_vectored_api)
317     {
318         vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &rtlraiseexception_vectored_handler);
319         ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
320     }
321
322     func(pRtlRaiseException, &record);
323
324     if (have_vectored_api)
325         pRtlRemoveVectoredExceptionHandler(vectored_handler);
326     pNtCurrentTeb()->Tib.ExceptionList = frame.Prev;
327 }
328
329 static void test_rtlraiseexception(void)
330 {
331     if (!pRtlRaiseException)
332     {
333         skip("RtlRaiseException not found\n");
334         return;
335     }
336
337     /* test without debugger */
338     run_rtlraiseexception_test(0x12345);
339     run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
340     run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
341 }
342
343 static DWORD handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
344                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
345 {
346     const struct exception *except = *(const struct exception **)(frame + 1);
347     unsigned int i, entry = except - exceptions;
348
349     got_exception++;
350     trace( "exception: %x flags:%x addr:%p\n",
351            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
352
353     ok( rec->ExceptionCode == except->status,
354         "%u: Wrong exception code %x/%x\n", entry, rec->ExceptionCode, except->status );
355     ok( rec->ExceptionAddress == (char*)code_mem + except->offset,
356         "%u: Wrong exception address %p/%p\n", entry,
357         rec->ExceptionAddress, (char*)code_mem + except->offset );
358
359     ok( rec->NumberParameters == except->nb_params,
360         "%u: Wrong number of parameters %u/%u\n", entry, rec->NumberParameters, except->nb_params );
361
362     /* Most CPUs (except Intel Core apparently) report a segment limit violation */
363     /* instead of page faults for accesses beyond 0xffffffff */
364     if (except->nb_params == 2 && except->params[1] >= 0xfffffffd)
365     {
366         if (rec->ExceptionInformation[0] == 0 && rec->ExceptionInformation[1] == 0xffffffff)
367             goto skip_params;
368     }
369
370     /* Seems that both 0xbee8 and 0xfffffffff can be returned in windows */
371     if (except->nb_params == 2 && rec->NumberParameters == 2
372         && except->params[1] == 0xbee8 && rec->ExceptionInformation[1] == 0xffffffff
373         && except->params[0] == rec->ExceptionInformation[0])
374     {
375         goto skip_params;
376     }
377
378     for (i = 0; i < rec->NumberParameters; i++)
379         ok( rec->ExceptionInformation[i] == except->params[i],
380             "%u: Wrong parameter %d: %lx/%x\n",
381             entry, i, rec->ExceptionInformation[i], except->params[i] );
382
383 skip_params:
384     /* don't handle exception if it's not the address we expected */
385     if (rec->ExceptionAddress != (char*)code_mem + except->offset) return ExceptionContinueSearch;
386
387     context->Eip += except->length;
388     return ExceptionContinueExecution;
389 }
390
391 static void test_prot_fault(void)
392 {
393     unsigned int i;
394
395     for (i = 0; i < sizeof(exceptions)/sizeof(exceptions[0]); i++)
396     {
397         got_exception = 0;
398         run_exception_test(handler, &exceptions[i], &exceptions[i].code,
399                            sizeof(exceptions[i].code));
400         if (!i && !got_exception)
401         {
402             trace( "No exception, assuming win9x, no point in testing further\n" );
403             break;
404         }
405         ok( got_exception == (exceptions[i].status != 0),
406             "%u: bad exception count %d\n", i, got_exception );
407     }
408 }
409
410 /* test handling of debug registers */
411 static DWORD dreg_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
412                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
413 {
414     context->Eip += 2;  /* Skips the popl (%eax) */
415     context->Dr0 = 0x42424242;
416     context->Dr1 = 0;
417     context->Dr2 = 0;
418     context->Dr3 = 0;
419     context->Dr6 = 0;
420     context->Dr7 = 0x155;
421     return ExceptionContinueExecution;
422 }
423
424 static const BYTE segfault_code[5] = {
425         0x31, 0xc0, /* xor    %eax,%eax */
426         0x8f, 0x00, /* popl   (%eax) - cause exception */
427         0xc3        /* ret */
428 };
429
430 /* test the single step exception behaviour */
431 static DWORD single_step_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
432                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
433 {
434     got_exception++;
435     ok (!(context->EFlags & 0x100), "eflags has single stepping bit set\n");
436
437     if( got_exception < 3)
438         context->EFlags |= 0x100;  /* single step until popf instruction */
439     else {
440         /* show that the last single step exception on the popf instruction
441          * (which removed the TF bit), still is a EXCEPTION_SINGLE_STEP exception */
442         ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
443             "exception is not EXCEPTION_SINGLE_STEP: %x\n", rec->ExceptionCode);
444     }
445
446     return ExceptionContinueExecution;
447 }
448
449 static const BYTE single_stepcode[] = {
450     0x9c,               /* pushf */
451     0x58,               /* pop   %eax */
452     0x0d,0,1,0,0,       /* or    $0x100,%eax */
453     0x50,               /* push   %eax */
454     0x9d,               /* popf    */
455     0x35,0,1,0,0,       /* xor    $0x100,%eax */
456     0x50,               /* push   %eax */
457     0x9d,               /* popf    */
458     0xc3
459 };
460
461 /* Test the alignment check (AC) flag handling. */
462 static const BYTE align_check_code[] = {
463     0x55,                       /* push   %ebp */
464     0x89,0xe5,                  /* mov    %esp,%ebp */
465     0x9c,                       /* pushf   */
466     0x58,                       /* pop    %eax */
467     0x0d,0,0,4,0,               /* or     $0x40000,%eax */
468     0x50,                       /* push   %eax */
469     0x9d,                       /* popf    */
470     0x89,0xe0,                  /* mov %esp, %eax */
471     0x8b,0x40,0x1,              /* mov 0x1(%eax), %eax - cause exception */
472     0x9c,                       /* pushf   */
473     0x58,                       /* pop    %eax */
474     0x35,0,0,4,0,               /* xor    $0x40000,%eax */
475     0x50,                       /* push   %eax */
476     0x9d,                       /* popf    */
477     0x5d,                       /* pop    %ebp */
478     0xc3,                       /* ret     */
479 };
480
481 static DWORD align_check_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
482                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
483 {
484     ok (!(context->EFlags & 0x40000), "eflags has AC bit set\n");
485     got_exception++;
486     return ExceptionContinueExecution;
487 }
488
489 /* Test the direction flag handling. */
490 static const BYTE direction_flag_code[] = {
491     0x55,                       /* push   %ebp */
492     0x89,0xe5,                  /* mov    %esp,%ebp */
493     0xfd,                       /* std */
494     0xfa,                       /* cli - cause exception */
495     0x5d,                       /* pop    %ebp */
496     0xc3,                       /* ret     */
497 };
498
499 static DWORD direction_flag_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
500                                      CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
501 {
502 #ifdef __GNUC__
503     unsigned int flags;
504     __asm__("pushfl; popl %0; cld" : "=r" (flags) );
505     /* older windows versions don't clear DF properly so don't test */
506     if (flags & 0x400) trace( "eflags has DF bit set\n" );
507 #endif
508     ok( context->EFlags & 0x400, "context eflags has DF bit cleared\n" );
509     got_exception++;
510     context->Eip++;  /* skip cli */
511     context->EFlags &= ~0x400;  /* make sure it is cleared on return */
512     return ExceptionContinueExecution;
513 }
514
515 /* test single stepping over hardware breakpoint */
516 static DWORD bpx_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
517                           CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
518 {
519     got_exception++;
520     ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
521         "wrong exception code: %x\n", rec->ExceptionCode);
522
523     if(got_exception == 1) {
524         /* hw bp exception on first nop */
525         ok( context->Eip == (DWORD)code_mem, "eip is wrong:  %x instead of %x\n",
526                                              context->Eip, (DWORD)code_mem);
527         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
528         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
529         context->Dr0 = context->Dr0 + 1;  /* set hw bp again on next instruction */
530         context->EFlags |= 0x100;       /* enable single stepping */
531     } else if(  got_exception == 2) {
532         /* single step exception on second nop */
533         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
534                                                  context->Eip, (DWORD)code_mem + 1);
535         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
536        /* depending on the win version the B0 bit is already set here as well
537         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n"); */
538         context->EFlags |= 0x100;
539     } else if( got_exception == 3) {
540         /* hw bp exception on second nop */
541         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
542                                                  context->Eip, (DWORD)code_mem + 1);
543         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
544         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
545         context->Dr0 = 0;       /* clear breakpoint */
546         context->EFlags |= 0x100;
547     } else {
548         /* single step exception on ret */
549         ok( context->Eip == (DWORD)code_mem + 2, "eip is wrong: %x instead of %x\n",
550                                                  context->Eip, (DWORD)code_mem + 2);
551         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n");
552         ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n");
553     }
554
555     context->Dr6 = 0;  /* clear status register */
556     return ExceptionContinueExecution;
557 }
558
559 static const BYTE dummy_code[] = { 0x90, 0x90, 0xc3 };  /* nop, nop, ret */
560
561 /* test int3 handling */
562 static DWORD int3_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
563                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
564 {
565     ok( rec->ExceptionAddress == code_mem, "exception address not at: %p, but at %p\n",
566                                            code_mem,  rec->ExceptionAddress);
567     ok( context->Eip == (DWORD)code_mem, "eip not at: %p, but at %#x\n", code_mem, context->Eip);
568     if(context->Eip == (DWORD)code_mem) context->Eip++; /* skip breakpoint */
569
570     return ExceptionContinueExecution;
571 }
572
573 static const BYTE int3_code[] = { 0xCC, 0xc3 };  /* int 3, ret */
574
575
576 static void test_exceptions(void)
577 {
578     CONTEXT ctx;
579     NTSTATUS res;
580
581     if (!pNtGetContextThread || !pNtSetContextThread)
582     {
583         skip( "NtGetContextThread/NtSetContextThread not found\n" );
584         return;
585     }
586
587     /* test handling of debug registers */
588     run_exception_test(dreg_handler, NULL, &segfault_code, sizeof(segfault_code));
589
590     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
591     res = pNtGetContextThread(GetCurrentThread(), &ctx);
592     ok (res == STATUS_SUCCESS,"NtGetContextThread failed with %x\n", res);
593     ok(ctx.Dr0 == 0x42424242,"failed to set debugregister 0 to 0x42424242, got %x\n", ctx.Dr0);
594     ok((ctx.Dr7 & ~0xdc00) == 0x155,"failed to set debugregister 7 to 0x155, got %x\n", ctx.Dr7);
595
596     /* test single stepping behavior */
597     got_exception = 0;
598     run_exception_test(single_step_handler, NULL, &single_stepcode, sizeof(single_stepcode));
599     ok(got_exception == 3, "expected 3 single step exceptions, got %d\n", got_exception);
600
601     /* test alignment exceptions */
602     got_exception = 0;
603     run_exception_test(align_check_handler, NULL, align_check_code, sizeof(align_check_code));
604     ok(got_exception == 0, "got %d alignment faults, expected 0\n", got_exception);
605
606     /* test direction flag */
607     got_exception = 0;
608     run_exception_test(direction_flag_handler, NULL, direction_flag_code, sizeof(direction_flag_code));
609     ok(got_exception == 1, "got %d exceptions, expected 1\n", got_exception);
610
611     /* test single stepping over hardware breakpoint */
612     memset(&ctx, 0, sizeof(ctx));
613     ctx.Dr0 = (DWORD) code_mem;  /* set hw bp on first nop */
614     ctx.Dr7 = 3;
615     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
616     res = pNtSetContextThread( GetCurrentThread(), &ctx);
617     ok( res == STATUS_SUCCESS, "NtSetContextThread faild with %x\n", res);
618
619     got_exception = 0;
620     run_exception_test(bpx_handler, NULL, dummy_code, sizeof(dummy_code));
621     ok( got_exception == 4,"expected 4 exceptions, got %d\n", got_exception);
622
623     /* test int3 handling */
624     run_exception_test(int3_handler, NULL, int3_code, sizeof(int3_code));
625 }
626
627 static void test_debugger(void)
628 {
629     char cmdline[MAX_PATH];
630     PROCESS_INFORMATION pi;
631     STARTUPINFO si = { 0 };
632     DEBUG_EVENT de;
633     DWORD continuestatus;
634     PVOID code_mem_address = NULL;
635     NTSTATUS status;
636     SIZE_T size_read;
637     BOOL ret;
638     int counter = 0;
639     si.cb = sizeof(si);
640
641     if(!pNtGetContextThread || !pNtSetContextThread || !pNtReadVirtualMemory || !pNtTerminateProcess)
642     {
643         skip("NtGetContextThread, NtSetContextThread, NtReadVirtualMemory or NtTerminateProcess not found\n)");
644         return;
645     }
646
647     sprintf(cmdline, "%s %s %s %p", my_argv[0], my_argv[1], "debuggee", &test_stage);
648     ret = CreateProcess(NULL, cmdline, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi);
649     ok(ret, "could not create child process error: %u\n", GetLastError());
650     if (!ret)
651         return;
652
653     do
654     {
655         continuestatus = DBG_CONTINUE;
656         ok(WaitForDebugEvent(&de, INFINITE), "reading debug event\n");
657
658         if (de.dwThreadId != pi.dwThreadId)
659         {
660             trace("event %d not coming from main thread, ignoring\n", de.dwDebugEventCode);
661             ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
662             continue;
663         }
664
665         if (de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
666         {
667             if(de.u.CreateProcessInfo.lpBaseOfImage != pNtCurrentTeb()->Peb->ImageBaseAddress)
668             {
669                 skip("child process loaded at different address, terminating it\n");
670                 pNtTerminateProcess(pi.hProcess, 0);
671             }
672         }
673         else if (de.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
674         {
675             CONTEXT ctx;
676             int stage;
677
678             counter++;
679             status = pNtReadVirtualMemory(pi.hProcess, &code_mem, &code_mem_address,
680                                           sizeof(code_mem_address), &size_read);
681             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
682             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
683                                           sizeof(stage), &size_read);
684             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
685
686             ctx.ContextFlags = CONTEXT_FULL;
687             status = pNtGetContextThread(pi.hThread, &ctx);
688             ok(!status, "NtGetContextThread failed with 0x%x\n", status);
689
690             trace("exception 0x%x at %p firstchance=%d Eip=0x%x, Eax=0x%x\n",
691                   de.u.Exception.ExceptionRecord.ExceptionCode,
692                   de.u.Exception.ExceptionRecord.ExceptionAddress, de.u.Exception.dwFirstChance, ctx.Eip, ctx.Eax);
693
694             if (counter > 100)
695             {
696                 ok(FALSE, "got way too many exceptions, probaby caught in a infinite loop, terminating child\n");
697                 pNtTerminateProcess(pi.hProcess, 1);
698             }
699             else if (counter >= 2) /* skip startup breakpoint */
700             {
701                 if (stage == 1)
702                 {
703                     ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at %x instead of %p\n",
704                        ctx.Eip, (char *)code_mem_address + 0xb);
705                     /* setting the context from debugger does not affect the context, the exception handlers gets */
706                     /* uncomment once wine is fixed */
707                     /* ctx.Eip = 0x12345; */
708                     ctx.Eax = 0xf00f00f1;
709
710                     /* let the debuggee handle the exception */
711                     continuestatus = DBG_EXCEPTION_NOT_HANDLED;
712                 }
713                 else if (stage == 2)
714                 {
715                     if (de.u.Exception.dwFirstChance)
716                     {
717                         /* debugger gets first chance exception with unmodified ctx.Eip */
718                         ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
719                             ctx.Eip, (char *)code_mem_address + 0xb);
720
721                         /* setting the context from debugger does not affect the context, the exception handlers gets */
722                         /* uncomment once wine is fixed */
723                         /* ctx.Eip = 0x12345; */
724                         ctx.Eax = 0xf00f00f1;
725
726                         /* pass exception to debuggee
727                          * exception will not be handled and
728                          * a second chance exception will be raised */
729                         continuestatus = DBG_EXCEPTION_NOT_HANDLED;
730                     }
731                     else
732                     {
733                         /* debugger gets context after exception handler has played with it */
734                         /* ctx.Eip is the same value the exception handler got */
735                         if (de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
736                         {
737                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xa, "Eip at 0x%x instead of %p\n",
738                                 ctx.Eip, (char *)code_mem_address + 0xa);
739                             /* need to fixup Eip for debuggee */
740                             if ((char *)ctx.Eip == (char *)code_mem_address + 0xa)
741                                 ctx.Eip += 1;
742                         }
743                         else
744                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
745                                 ctx.Eip, (char *)code_mem_address + 0xb);
746                         /* here we handle exception */
747                     }
748                 }
749                 else
750                     ok(FALSE, "unexpected stage %x\n", stage);
751
752                 status = pNtSetContextThread(pi.hThread, &ctx);
753                 ok(!status, "NtSetContextThread failed with 0x%x\n", status);
754             }
755         }
756
757         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, continuestatus);
758
759     } while (de.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
760
761     winetest_wait_child_process( pi.hProcess );
762     ok(CloseHandle(pi.hThread) != 0, "error %u\n", GetLastError());
763     ok(CloseHandle(pi.hProcess) != 0, "error %u\n", GetLastError());
764
765     return;
766 }
767
768 static DWORD simd_fault_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
769                                  CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
770 {
771     int *stage = *(int **)(frame + 1);
772
773     got_exception++;
774
775     if( *stage == 1) {
776         /* fault while executing sse instruction */
777         context->Eip += 3; /* skip addps */
778         return ExceptionContinueExecution;
779     }
780
781     /* stage 2 - divide by zero fault */
782     if( rec->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION)
783         skip("system doesn't support SIMD exceptions\n");
784     else {
785         ok( rec->ExceptionCode ==  STATUS_FLOAT_MULTIPLE_TRAPS,
786             "exception code: %#x, should be %#x\n",
787             rec->ExceptionCode,  STATUS_FLOAT_MULTIPLE_TRAPS);
788         ok( rec->NumberParameters == 1, "# of params: %i, should be 1\n",
789             rec->NumberParameters);
790         if( rec->NumberParameters == 1 )
791             ok( rec->ExceptionInformation[0] == 0, "param #1: %lx, should be 0\n", rec->ExceptionInformation[0]);
792     }
793
794     context->Eip += 3; /* skip divps */
795
796     return ExceptionContinueExecution;
797 }
798
799 static const BYTE simd_exception_test[] = {
800     0x83, 0xec, 0x4,                     /* sub $0x4, %esp       */
801     0x0f, 0xae, 0x1c, 0x24,              /* stmxcsr (%esp)       */
802     0x66, 0x81, 0x24, 0x24, 0xff, 0xfd,  /* andw $0xfdff,(%esp)  * enable divide by */
803     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       * zero exceptions  */
804     0x6a, 0x01,                          /* push   $0x1          */
805     0x6a, 0x01,                          /* push   $0x1          */
806     0x6a, 0x01,                          /* push   $0x1          */
807     0x6a, 0x01,                          /* push   $0x1          */
808     0x0f, 0x10, 0x0c, 0x24,              /* movups (%esp),%xmm1  * fill dividend  */
809     0x0f, 0x57, 0xc0,                    /* xorps  %xmm0,%xmm0   * clear divisor  */
810     0x0f, 0x5e, 0xc8,                    /* divps  %xmm0,%xmm1   * generate fault */
811     0x83, 0xc4, 0x10,                    /* add    $0x10,%esp    */
812     0x66, 0x81, 0x0c, 0x24, 0x00, 0x02,  /* orw    $0x200,(%esp) * disable exceptions */
813     0x0f, 0xae, 0x14, 0x24,              /* ldmxcsr (%esp)       */
814     0x83, 0xc4, 0x04,                    /* add    $0x4,%esp     */
815     0xc3,                                /* ret */
816 };
817
818 static const BYTE sse_check[] = {
819     0x0f, 0x58, 0xc8,                    /* addps  %xmm0,%xmm1 */
820     0xc3,                                /* ret */
821 };
822
823 static void test_simd_exceptions(void)
824 {
825     int stage;
826
827     /* test if CPU & OS can do sse */
828     stage = 1;
829     got_exception = 0;
830     run_exception_test(simd_fault_handler, &stage, sse_check, sizeof(sse_check));
831     if(got_exception) {
832         skip("system doesn't support SSE\n");
833         return;
834     }
835
836     /* generate a SIMD exception */
837     stage = 2;
838     got_exception = 0;
839     run_exception_test(simd_fault_handler, &stage, simd_exception_test,
840                        sizeof(simd_exception_test));
841     ok( got_exception == 1, "got exception: %i, should be 1\n", got_exception);
842 }
843
844 #endif  /* __i386__ */
845
846 START_TEST(exception)
847 {
848 #ifdef __i386__
849     HMODULE hntdll = GetModuleHandleA("ntdll.dll");
850
851     pNtCurrentTeb        = (void *)GetProcAddress( hntdll, "NtCurrentTeb" );
852     pNtGetContextThread  = (void *)GetProcAddress( hntdll, "NtGetContextThread" );
853     pNtSetContextThread  = (void *)GetProcAddress( hntdll, "NtSetContextThread" );
854     pNtReadVirtualMemory = (void *)GetProcAddress( hntdll, "NtReadVirtualMemory" );
855     pRtlRaiseException   = (void *)GetProcAddress( hntdll, "RtlRaiseException" );
856     pNtTerminateProcess  = (void *)GetProcAddress( hntdll, "NtTerminateProcess" );
857     pRtlAddVectoredExceptionHandler    = (void *)GetProcAddress( hntdll,
858                                                                  "RtlAddVectoredExceptionHandler" );
859     pRtlRemoveVectoredExceptionHandler = (void *)GetProcAddress( hntdll,
860                                                                  "RtlRemoveVectoredExceptionHandler" );
861     if (!pNtCurrentTeb)
862     {
863         skip( "NtCurrentTeb not found\n" );
864         return;
865     }
866
867     if (pRtlAddVectoredExceptionHandler && pRtlRemoveVectoredExceptionHandler)
868         have_vectored_api = TRUE;
869     else
870         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler not found\n");
871
872     /* 1024 byte should be sufficient */
873     code_mem = VirtualAlloc(NULL, 1024, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
874     if(!code_mem) {
875         trace("VirtualAlloc failed\n");
876         return;
877     }
878
879     my_argc = winetest_get_mainargs( &my_argv );
880     if (my_argc >= 4)
881     {
882         void *addr;
883         sscanf( my_argv[3], "%p", &addr );
884
885         if (addr != &test_stage)
886         {
887             skip( "child process not mapped at same address (%p/%p)\n", &test_stage, addr);
888             return;
889         }
890
891         /* child must be run under a debugger */
892         if (!pNtCurrentTeb()->Peb->BeingDebugged)
893         {
894             ok(FALSE, "child process not being debugged?\n");
895             return;
896         }
897
898         if (pRtlRaiseException)
899         {
900             test_stage = 1;
901             run_rtlraiseexception_test(0x12345);
902             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
903             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
904             test_stage = 2;
905             run_rtlraiseexception_test(0x12345);
906             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
907             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
908         }
909         else
910             skip( "RtlRaiseException not found\n" );
911
912         /* rest of tests only run in parent */
913         return;
914     }
915
916     test_prot_fault();
917     test_exceptions();
918     test_rtlraiseexception();
919     test_debugger();
920     test_simd_exceptions();
921
922     VirtualFree(code_mem, 1024, MEM_RELEASE);
923 #endif
924 }