quartz: Use proper alloc/free functions for COM objects.
[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 },  /* sti; ret */
69       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
70     { { 0x6c, 0xc3 },  /* insb (%dx); ret */
71       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
72     { { 0x6d, 0xc3 },  /* insl (%dx); ret */
73       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
74     { { 0x6e, 0xc3 },  /* outsb (%dx); ret */
75       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
76     { { 0x6f, 0xc3 },  /* outsl (%dx); ret */
77       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
78     { { 0xe4, 0x11, 0xc3 },  /* inb $0x11,%al; ret */
79       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
80     { { 0xe5, 0x11, 0xc3 },  /* inl $0x11,%eax; ret */
81       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
82     { { 0xe6, 0x11, 0xc3 },  /* outb %al,$0x11; ret */
83       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
84     { { 0xe7, 0x11, 0xc3 },  /* outl %eax,$0x11; ret */
85       0, 2, STATUS_PRIVILEGED_INSTRUCTION, 0 },
86     { { 0xed, 0xc3 },  /* inl (%dx),%eax; ret */
87       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
88     { { 0xee, 0xc3 },  /* outb %al,(%dx); ret */
89       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
90     { { 0xef, 0xc3 },  /* outl %eax,(%dx); ret */
91       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
92     { { 0xf4, 0xc3 },  /* hlt; ret */
93       0, 1, STATUS_PRIVILEGED_INSTRUCTION, 0 },
94     { { 0xfa, 0xc3 },  /* 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 },  /* 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       /* 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 },  /* mov $beef,%ax; mov %ax,%gs; ret */
108       5, 2, STATUS_ACCESS_VIOLATION, 2, { 0, 0xbee8 } },
109
110     /* test accessing a zero selector */
111     { { 0x06, 0x31, 0xc0, 0x8e, 0xc0, 0x26, 0xa1, 0, 0, 0, 0, 0x07, 0xc3 },
112           /* push %es; xor %eax,%eax; mov %ax,%es; mov %es:(0),%ax; pop %es */
113       5, 6, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
114
115     /* test moving %cs -> %ss */
116     { { 0x0e, 0x17, 0x58, 0xc3 },  /* pushl %cs; popl %ss; popl %eax; ret */
117       1, 1, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
118
119     /* 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_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
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 },   /* int $0xff; ret */
127       0, 2, STATUS_ACCESS_VIOLATION, 2, { 0, 0xffffffff } },
128
129     /* test moves to/from Crx */
130     { { 0x0f, 0x20, 0xc0, 0xc3 },  /* movl %cr0,%eax; ret */
131       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
132     { { 0x0f, 0x20, 0xe0, 0xc3 },  /* movl %cr4,%eax; ret */
133       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
134     { { 0x0f, 0x22, 0xc0, 0xc3 },  /* movl %eax,%cr0; ret */
135       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
136     { { 0x0f, 0x22, 0xe0, 0xc3 },  /* movl %eax,%cr4; ret */
137       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
138
139     /* test moves to/from Drx */
140     { { 0x0f, 0x21, 0xc0, 0xc3 },  /* movl %dr0,%eax; ret */
141       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
142     { { 0x0f, 0x21, 0xc8, 0xc3 },  /* movl %dr1,%eax; ret */
143       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
144     { { 0x0f, 0x21, 0xf8, 0xc3 },  /* movl %dr7,%eax; ret */
145       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
146     { { 0x0f, 0x23, 0xc0, 0xc3 },  /* movl %eax,%dr0; ret */
147       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
148     { { 0x0f, 0x23, 0xc8, 0xc3 },  /* movl %eax,%dr1; ret */
149       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
150     { { 0x0f, 0x23, 0xf8, 0xc3 },  /* movl %eax,%dr7; ret */
151       0, 3, STATUS_PRIVILEGED_INSTRUCTION, 0 },
152
153     /* test memory reads */
154     { { 0xa1, 0xfc, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffc,%eax; ret */
155       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffc } },
156     { { 0xa1, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffd,%eax; ret */
157       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffd } },
158     { { 0xa1, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl 0xfffffffe,%eax; ret */
159       0, 5, STATUS_ACCESS_VIOLATION, 2, { 0, 0xfffffffe } },
160     { { 0xa1, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* 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 },  /* movl %eax,0xfffffffc; ret */
165       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffc } },
166     { { 0xa3, 0xfd, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffd; ret */
167       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffd } },
168     { { 0xa3, 0xfe, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xfffffffe; ret */
169       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xfffffffe } },
170     { { 0xa3, 0xff, 0xff, 0xff, 0xff, 0xc3 },  /* movl %eax,0xffffffff; ret */
171       0, 5, STATUS_ACCESS_VIOLATION, 2, { 1, 0xffffffff } },
172 };
173
174 static int got_exception;
175 static BOOL have_vectored_api;
176
177 static void run_exception_test(const void *handler, const void* context,
178                                const void *code, unsigned int code_size)
179 {
180     struct {
181         EXCEPTION_REGISTRATION_RECORD frame;
182         const void *context;
183     } exc_frame;
184     void (*func)(void) = code_mem;
185
186     exc_frame.frame.Handler = handler;
187     exc_frame.frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
188     exc_frame.context = context;
189
190     memcpy(code_mem, code, code_size);
191
192     pNtCurrentTeb()->Tib.ExceptionList = &exc_frame.frame;
193     func();
194     pNtCurrentTeb()->Tib.ExceptionList = exc_frame.frame.Prev;
195 }
196
197 LONG CALLBACK rtlraiseexception_vectored_handler(EXCEPTION_POINTERS *ExceptionInfo)
198 {
199     PCONTEXT context = ExceptionInfo->ContextRecord;
200     PEXCEPTION_RECORD rec = ExceptionInfo->ExceptionRecord;
201     trace("vect. handler %08x addr:%p context.Eip:%x\n", rec->ExceptionCode,
202           rec->ExceptionAddress, context->Eip);
203
204     todo_wine {
205     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
206        rec->ExceptionAddress, (char *)code_mem + 0xb);
207
208     if (pNtCurrentTeb()->Peb->BeingDebugged)
209         ok((void *)context->Eax == pRtlRaiseException, "debugger managed to modify Eax to %x should be %p\n",
210            context->Eax, pRtlRaiseException);
211     }
212
213     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
214      * even if raised by RtlRaiseException
215      */
216     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
217     {
218         todo_wine {
219         ok(context->Eip == (DWORD)code_mem + 0xa, "Eip at %x instead of %x\n",
220            context->Eip, (DWORD)code_mem + 0xa);
221         }
222     }
223     else
224     {
225         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
226            context->Eip, (DWORD)code_mem + 0xb);
227     }
228
229     /* test if context change is preserved from vectored handler to stack handlers */
230     context->Eax = 0xf00f00f0;
231     return EXCEPTION_CONTINUE_SEARCH;
232 }
233
234 static DWORD rtlraiseexception_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
235                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
236 {
237     trace( "exception: %08x flags:%x addr:%p context: Eip:%x\n",
238            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Eip );
239
240     todo_wine {
241     ok(rec->ExceptionAddress == (char *)code_mem + 0xb, "ExceptionAddress at %p instead of %p\n",
242        rec->ExceptionAddress, (char *)code_mem + 0xb);
243     }
244
245     /* check that context.Eip is fixed up only for EXCEPTION_BREAKPOINT
246      * even if raised by RtlRaiseException
247      */
248     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT)
249     {
250         todo_wine {
251         ok(context->Eip == (DWORD)code_mem + 0xa, "Eip at %x instead of %x\n",
252            context->Eip, (DWORD)code_mem + 0xa);
253         }
254     }
255     else
256     {
257         ok(context->Eip == (DWORD)code_mem + 0xb, "Eip at %x instead of %x\n",
258            context->Eip, (DWORD)code_mem + 0xb);
259     }
260
261     if(have_vectored_api)
262         ok(context->Eax == 0xf00f00f0, "Eax is %x, should have been set to 0xf00f00f0 in vectored handler\n",
263            context->Eax);
264
265     /* give the debugger a chance to examine the state a second time */
266     /* without the exception handler changing Eip */
267     if (test_stage == 2)
268         return ExceptionContinueSearch;
269
270     /* Eip in context is decreased by 1
271      * Increase it again, else execution will continue in the middle of a instruction */
272     if(rec->ExceptionCode == EXCEPTION_BREAKPOINT && (context->Eip == (DWORD)code_mem + 0xa))
273         context->Eip += 1;
274     return ExceptionContinueExecution;
275 }
276
277
278 static const BYTE call_one_arg_code[] = {
279         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
280         0x50,                   /* push %eax */
281         0x8b, 0x44, 0x24, 0x08, /* mov 0x8(%esp),%eax */
282         0xff, 0xd0,             /* call *%eax */
283         0x90,                   /* nop */
284         0x90,                   /* nop */
285         0x90,                   /* nop */
286         0x90,                   /* nop */
287         0xc3,                   /* ret */
288 };
289
290
291 static void run_rtlraiseexception_test(DWORD exceptioncode)
292 {
293     EXCEPTION_REGISTRATION_RECORD frame;
294     EXCEPTION_RECORD record;
295     PVOID vectored_handler = NULL;
296
297     void (*func)(void* function, EXCEPTION_RECORD* record) = code_mem;
298
299     record.ExceptionCode = exceptioncode;
300     record.ExceptionFlags = 0;
301     record.ExceptionRecord = NULL;
302     record.ExceptionAddress = NULL; /* does not matter, copied return address */
303     record.NumberParameters = 0;
304
305     frame.Handler = rtlraiseexception_handler;
306     frame.Prev = pNtCurrentTeb()->Tib.ExceptionList;
307
308     memcpy(code_mem, call_one_arg_code, sizeof(call_one_arg_code));
309
310     pNtCurrentTeb()->Tib.ExceptionList = &frame;
311     if (have_vectored_api)
312     {
313         vectored_handler = pRtlAddVectoredExceptionHandler(TRUE, &rtlraiseexception_vectored_handler);
314         ok(vectored_handler != 0, "RtlAddVectoredExceptionHandler failed\n");
315     }
316
317     func(pRtlRaiseException, &record);
318
319     if (have_vectored_api)
320         pRtlRemoveVectoredExceptionHandler(vectored_handler);
321     pNtCurrentTeb()->Tib.ExceptionList = frame.Prev;
322 }
323
324 static void test_rtlraiseexcpetion(void)
325 {
326     if (!pRtlRaiseException)
327     {
328         skip("RtlRaiseException not found\n");
329         return;
330     }
331
332     /* test without debugger */
333     run_rtlraiseexception_test(0x12345);
334     run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
335     run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
336 }
337
338 static DWORD handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
339                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
340 {
341     const struct exception *except = *(const struct exception **)(frame + 1);
342     unsigned int i, entry = except - exceptions;
343
344     got_exception++;
345     trace( "exception: %x flags:%x addr:%p\n",
346            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
347
348     ok( rec->ExceptionCode == except->status,
349         "%u: Wrong exception code %x/%x\n", entry, rec->ExceptionCode, except->status );
350     ok( rec->ExceptionAddress == (char*)code_mem + except->offset,
351         "%u: Wrong exception address %p/%p\n", entry,
352         rec->ExceptionAddress, (char*)code_mem + except->offset );
353
354     ok( rec->NumberParameters == except->nb_params,
355         "%u: Wrong number of parameters %u/%u\n", entry, rec->NumberParameters, except->nb_params );
356
357     /* Most CPUs (except Intel Core apparently) report a segment limit violation */
358     /* instead of page faults for accesses beyond 0xffffffff */
359     if (except->nb_params == 2 && except->params[1] >= 0xfffffffd)
360     {
361         if (rec->ExceptionInformation[0] == 0 && rec->ExceptionInformation[1] == 0xffffffff)
362             goto skip_params;
363     }
364
365     for (i = 0; i < rec->NumberParameters; i++)
366         ok( rec->ExceptionInformation[i] == except->params[i],
367             "%u: Wrong parameter %d: %lx/%x\n",
368             entry, i, rec->ExceptionInformation[i], except->params[i] );
369
370 skip_params:
371     /* don't handle exception if it's not the address we expected */
372     if (rec->ExceptionAddress != (char*)code_mem + except->offset) return ExceptionContinueSearch;
373
374     context->Eip += except->length;
375     return ExceptionContinueExecution;
376 }
377
378 static void test_prot_fault(void)
379 {
380     unsigned int i;
381
382     for (i = 0; i < sizeof(exceptions)/sizeof(exceptions[0]); i++)
383     {
384         got_exception = 0;
385         run_exception_test(handler, &exceptions[i], &exceptions[i].code,
386                            sizeof(exceptions[i].code));
387         if (!i && !got_exception)
388         {
389             trace( "No exception, assuming win9x, no point in testing further\n" );
390             break;
391         }
392         ok( got_exception == (exceptions[i].status != 0),
393             "%u: bad exception count %d\n", i, got_exception );
394     }
395 }
396
397 /* test handling of debug registers */
398 static DWORD dreg_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
399                       CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
400 {
401     context->Eip += 2;  /* Skips the popl (%eax) */
402     context->Dr0 = 0x42424242;
403     context->Dr1 = 0;
404     context->Dr2 = 0;
405     context->Dr3 = 0;
406     context->Dr6 = 0;
407     context->Dr7 = 0x155;
408     return ExceptionContinueExecution;
409 }
410
411 static const BYTE segfault_code[5] = {
412         0x31, 0xc0, /* xor    %eax,%eax */
413         0x8f, 0x00, /* popl   (%eax) - cause exception */
414         0xc3        /* ret */
415 };
416
417 /* test the single step exception behaviour */
418 static DWORD single_step_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
419                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
420 {
421     got_exception++;
422     ok (!(context->EFlags & 0x100), "eflags has single stepping bit set\n");
423
424     if( got_exception < 3)
425         context->EFlags |= 0x100;  /* single step until popf instruction */
426     else {
427         /* show that the last single step exception on the popf instruction
428          * (which removed the TF bit), still is a EXCEPTION_SINGLE_STEP exception */
429         ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
430             "exception is not EXCEPTION_SINGLE_STEP: %x\n", rec->ExceptionCode);
431     }
432
433     return ExceptionContinueExecution;
434 }
435
436 static const BYTE single_stepcode[] = {
437     0x9c,               /* pushf */
438     0x58,               /* pop   %eax */
439     0x0d,0,1,0,0,       /* or    $0x100,%eax */
440     0x50,               /* push   %eax */
441     0x9d,               /* popf    */
442     0x35,0,1,0,0,       /* xor    $0x100,%eax */
443     0x50,               /* push   %eax */
444     0x9d,               /* popf    */
445     0xc3
446 };
447
448 /* Test the alignment check (AC) flag handling. */
449 static const BYTE align_check_code[] = {
450     0x55,                       /* push   %ebp */
451     0x89,0xe5,                  /* mov    %esp,%ebp */
452     0x9c,                       /* pushf   */
453     0x58,                       /* pop    %eax */
454     0x0d,0,0,4,0,               /* or     $0x40000,%eax */
455     0x50,                       /* push   %eax */
456     0x9d,                       /* popf    */
457     0x89,0xe0,                  /* mov %esp, %eax */
458     0x8b,0x40,0x1,              /* mov 0x1(%eax), %eax - cause exception */
459     0x9c,                       /* pushf   */
460     0x58,                       /* pop    %eax */
461     0x35,0,0,4,0,               /* xor    $0x40000,%eax */
462     0x50,                       /* push   %eax */
463     0x9d,                       /* popf    */
464     0x5d,                       /* pop    %ebp */
465     0xc3,                       /* ret     */
466 };
467
468 static DWORD align_check_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
469                                   CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
470 {
471     ok (!(context->EFlags & 0x40000), "eflags has AC bit set\n");
472     got_exception++;
473     return ExceptionContinueExecution;
474 }
475
476 /* test single stepping over hardware breakpoint */
477 static DWORD bpx_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
478                           CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
479 {
480     got_exception++;
481     ok( rec->ExceptionCode == EXCEPTION_SINGLE_STEP,
482         "wrong exception code: %x\n", rec->ExceptionCode);
483
484     if(got_exception == 1) {
485         /* hw bp exception on first nop */
486         ok( context->Eip == (DWORD)code_mem, "eip is wrong:  %x instead of %x\n",
487                                              context->Eip, (DWORD)code_mem);
488         ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n");
489         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
490         context->Dr0 = context->Dr0 + 1;  /* set hw bp again on next instruction */
491         context->EFlags |= 0x100;       /* enable single stepping */
492     } else if(  got_exception == 2) {
493         /* single step exception on second nop */
494         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
495                                                  context->Eip, (DWORD)code_mem + 1);
496         todo_wine{ ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n"); };
497         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n");
498         context->EFlags |= 0x100;
499     } else if( got_exception == 3) {
500         /* hw bp exception on second nop */
501         ok( context->Eip == (DWORD)code_mem + 1, "eip is wrong: %x instead of %x\n",
502                                                  context->Eip, (DWORD)code_mem + 1);
503         todo_wine{ ok( (context->Dr6 & 0xf) == 1, "B0 flag is not set in Dr6\n"); };
504         ok( !(context->Dr6 & 0x4000), "BS flag is set in Dr6\n");
505         context->Dr0 = 0;       /* clear breakpoint */
506         context->EFlags |= 0x100;
507     } else {
508         /* single step exception on ret */
509         ok( context->Eip == (DWORD)code_mem + 2, "eip is wrong: %x instead of %x\n",
510                                                  context->Eip, (DWORD)code_mem + 2);
511         ok( (context->Dr6 & 0xf) == 0, "B0...3 flags in Dr6 shouldn't be set\n");
512         todo_wine{ ok( (context->Dr6 & 0x4000), "BS flag is not set in Dr6\n"); };
513     }
514
515     context->Dr6 = 0;  /* clear status register */
516     return ExceptionContinueExecution;
517 }
518
519 static const BYTE dummy_code[] = { 0x90, 0x90, 0xc3 };  /* nop, nop, ret */
520
521 /* test int3 handling */
522 static DWORD int3_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
523                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
524 {
525     ok( rec->ExceptionAddress == code_mem, "exception address not at: %p, but at %p\n",
526                                            code_mem,  rec->ExceptionAddress);
527     todo_wine {
528         ok( context->Eip == (DWORD)code_mem, "eip not at: %p, but at %#x\n", code_mem, context->Eip);
529     }
530     if(context->Eip == (DWORD)code_mem) context->Eip++; /* skip breakpoint */
531
532     return ExceptionContinueExecution;
533 }
534
535 static const BYTE int3_code[] = { 0xCC, 0xc3 };  /* int 3, ret */
536
537
538 static void test_exceptions(void)
539 {
540     CONTEXT ctx;
541     NTSTATUS res;
542
543     if (!pNtGetContextThread || !pNtSetContextThread)
544     {
545         trace( "NtGetContextThread/NtSetContextThread not found, skipping tests\n" );
546         return;
547     }
548
549     /* test handling of debug registers */
550     run_exception_test(dreg_handler, NULL, &segfault_code, sizeof(segfault_code));
551
552     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
553     res = pNtGetContextThread(GetCurrentThread(), &ctx);
554     ok (res == STATUS_SUCCESS,"NtGetContextThread failed with %x\n", res);
555     ok(ctx.Dr0 == 0x42424242,"failed to set debugregister 0 to 0x42424242, got %x\n", ctx.Dr0);
556     ok(ctx.Dr7 == 0x155,"failed to set debugregister 7 to 0x155, got %x\n", ctx.Dr7);
557
558     /* test single stepping behavior */
559     got_exception = 0;
560     run_exception_test(single_step_handler, NULL, &single_stepcode, sizeof(single_stepcode));
561     ok(got_exception == 3, "expected 3 single step exceptions, got %d\n", got_exception);
562
563     /* test alignment exceptions */
564     got_exception = 0;
565     run_exception_test(align_check_handler, NULL, align_check_code, sizeof(align_check_code));
566     ok(got_exception == 0, "got %d alignment faults, expected 0\n", got_exception);
567
568     /* test single stepping over hardware breakpoint */
569     memset(&ctx, 0, sizeof(ctx));
570     ctx.Dr0 = (DWORD) code_mem;  /* set hw bp on first nop */
571     ctx.Dr7 = 3;
572     ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
573     res = pNtSetContextThread( GetCurrentThread(), &ctx);
574     ok( res == STATUS_SUCCESS, "NtSetContextThread faild with %x\n", res);
575
576     got_exception = 0;
577     run_exception_test(bpx_handler, NULL, dummy_code, sizeof(dummy_code));
578     ok( got_exception == 4,"expected 4 exceptions, got %d\n", got_exception);
579
580     /* test int3 handling */
581     run_exception_test(int3_handler, NULL, int3_code, sizeof(int3_code));
582 }
583
584 static void test_debugger(void)
585 {
586     char cmdline[MAX_PATH];
587     PROCESS_INFORMATION pi;
588     STARTUPINFO si = { 0 };
589     DEBUG_EVENT de;
590     DWORD continuestatus;
591     PVOID code_mem_address = NULL;
592     NTSTATUS status;
593     SIZE_T size_read;
594     BOOL ret;
595     int counter = 0;
596     si.cb = sizeof(si);
597
598     if(!pNtGetContextThread || !pNtSetContextThread || !pNtReadVirtualMemory || !pNtTerminateProcess)
599     {
600         skip("NtGetContextThread, NtSetContextThread, NtReadVirtualMemory or NtTerminateProcess not found\n)");
601         return;
602     }
603
604     sprintf(cmdline, "%s %s %s", my_argv[0], my_argv[1], "debuggee");
605     ret = CreateProcess(NULL, cmdline, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi);
606     ok(ret, "could not create child process error: %u\n", GetLastError());
607     if (!ret)
608         return;
609
610     do
611     {
612         continuestatus = DBG_CONTINUE;
613         ok(WaitForDebugEvent(&de, INFINITE), "reading debug event\n");
614
615         if (de.dwThreadId != pi.dwThreadId)
616         {
617             trace("event %d not coming from main thread, ignoring\n", de.dwDebugEventCode);
618             ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
619             continue;
620         }
621
622         if (de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
623         {
624             if(de.u.CreateProcessInfo.lpBaseOfImage != pNtCurrentTeb()->Peb->ImageBaseAddress)
625             {
626                 skip("child process loaded at different address, terminating it\n");
627                 pNtTerminateProcess(pi.hProcess, 1);
628             }
629         }
630         else if (de.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
631         {
632             CONTEXT ctx;
633             int stage;
634
635             counter++;
636             status = pNtReadVirtualMemory(pi.hProcess, &code_mem, &code_mem_address,
637                                           sizeof(code_mem_address), &size_read);
638             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
639             status = pNtReadVirtualMemory(pi.hProcess, &test_stage, &stage,
640                                           sizeof(stage), &size_read);
641             ok(!status,"NtReadVirtualMemory failed with 0x%x\n", status);
642
643             ctx.ContextFlags = CONTEXT_FULL;
644             status = pNtGetContextThread(pi.hThread, &ctx);
645             ok(!status, "NtGetContextThread failed with 0x%x\n", status);
646
647             trace("excpetion 0x%x at %p firstchance=%d Eip=0x%x, Eax=0x%x\n",
648                   de.u.Exception.ExceptionRecord.ExceptionCode,
649                   de.u.Exception.ExceptionRecord.ExceptionAddress, de.u.Exception.dwFirstChance, ctx.Eip, ctx.Eax);
650
651             if (counter > 100)
652             {
653                 ok(FALSE, "got way too many exceptions, probaby caught in a infinite loop, terminating child\n");
654                 pNtTerminateProcess(pi.hProcess, 1);
655             }
656             else if (counter >= 2) /* skip startup breakpoint */
657             {
658                 if (stage == 1)
659                 {
660                     ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at %x instead of %p\n",
661                        ctx.Eip, (char *)code_mem_address + 0xb);
662                     /* setting the context from debugger does not affect the context, the exception handlers gets */
663                     /* uncomment once wine is fixed */
664                     /* ctx.Eip = 0x12345; */
665                     ctx.Eax = 0xf00f00f1;
666
667                     /* let the debuggee handle the exception */
668                     continuestatus = DBG_EXCEPTION_NOT_HANDLED;
669                 }
670                 else if (stage == 2)
671                 {
672                     if (de.u.Exception.dwFirstChance)
673                     {
674                         /* debugger gets first chance exception with unmodified ctx.Eip */
675                         ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
676                             ctx.Eip, (char *)code_mem_address + 0xb);
677
678                         /* setting the context from debugger does not affect the context, the exception handlers gets */
679                         /* uncomment once wine is fixed */
680                         /* ctx.Eip = 0x12345; */
681                         ctx.Eax = 0xf00f00f1;
682
683                         /* pass exception to debuggee
684                          * exception will not be handled and
685                          * a second chance exception will be raised */
686                         continuestatus = DBG_EXCEPTION_NOT_HANDLED;
687                     }
688                     else
689                     {
690                         /* debugger gets context after exception handler has played with it */
691                         /* ctx.Eip is the same value the exception handler got */
692                         if (de.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
693                         {
694                             todo_wine{
695                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xa, "Eip at 0x%x instead of %p\n",
696                                 ctx.Eip, (char *)code_mem_address + 0xa);
697                             }
698                             /* need to fixup Eip for debuggee */
699                             if ((char *)ctx.Eip == (char *)code_mem_address + 0xa)
700                                 ctx.Eip += 1;
701                         }
702                         else
703                             ok((char *)ctx.Eip == (char *)code_mem_address + 0xb, "Eip at 0x%x instead of %p\n",
704                                 ctx.Eip, (char *)code_mem_address + 0xb);
705                         /* here we handle exception */
706                     }
707                 }
708                 else
709                     ok(FALSE, "unexpected stage %d\n", stage);
710
711                 status = pNtSetContextThread(pi.hThread, &ctx);
712                 ok(!status, "NtSetContextThread failed with 0x%x\n", status);
713             }
714         }
715
716         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, continuestatus);
717
718     } while (de.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
719
720     ok(CloseHandle(pi.hThread) != 0, "error %u\n", GetLastError());
721     ok(CloseHandle(pi.hProcess) != 0, "error %u\n", GetLastError());
722
723     return;
724 }
725
726 #endif  /* __i386__ */
727
728 START_TEST(exception)
729 {
730 #ifdef __i386__
731     pNtCurrentTeb = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "NtCurrentTeb" );
732     pNtGetContextThread  = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "NtGetContextThread" );
733     pNtSetContextThread  = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "NtSetContextThread" );
734     pNtReadVirtualMemory = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "NtReadVirtualMemory" );
735     pRtlRaiseException   = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "RtlRaiseException" );
736     pNtTerminateProcess  = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"), "NtTerminateProcess" );
737     pRtlAddVectoredExceptionHandler    = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"),
738                                                                  "RtlAddVectoredExceptionHandler" );
739     pRtlRemoveVectoredExceptionHandler = (void *)GetProcAddress( GetModuleHandleA("ntdll.dll"),
740                                                                  "RtlRemoveVectoredExceptionHandler" );
741     if (!pNtCurrentTeb)
742     {
743         trace( "NtCurrentTeb not found, skipping tests\n" );
744         return;
745     }
746
747     if (pRtlAddVectoredExceptionHandler && pRtlRemoveVectoredExceptionHandler)
748         have_vectored_api = TRUE;
749     else
750         skip("RtlAddVectoredExceptionHandler or RtlRemoveVectoredExceptionHandler not found\n");
751
752     /* 1024 byte should be sufficient */
753     code_mem = VirtualAlloc(NULL, 1024, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
754     if(!code_mem) {
755         trace("VirtualAlloc failed\n");
756         return;
757     }
758
759     my_argc = winetest_get_mainargs( &my_argv );
760     if (my_argc >= 3)
761     {
762         /* child must be run under a debugger */
763         if (!pNtCurrentTeb()->Peb->BeingDebugged)
764         {
765             ok(FALSE, "child process not being debugged?\n");
766             return;
767         }
768
769         if (pRtlRaiseException)
770         {
771             test_stage = 1;
772             run_rtlraiseexception_test(0x12345);
773             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
774             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
775             test_stage = 2;
776             run_rtlraiseexception_test(0x12345);
777             run_rtlraiseexception_test(EXCEPTION_BREAKPOINT);
778             run_rtlraiseexception_test(EXCEPTION_INVALID_HANDLE);
779         }
780         else
781             skip( "RtlRaiseException not found\n" );
782
783         /* rest of tests only run in parent */
784         return;
785     }
786
787     test_prot_fault();
788     test_exceptions();
789     test_rtlraiseexcpetion();
790
791     test_debugger();
792
793     VirtualFree(code_mem, 1024, MEM_RELEASE);
794 #endif
795 }