ntoskrnl.exe: Correctly remove the vectored exception handler.
[wine] / dlls / ntoskrnl.exe / ntoskrnl.c
1 /*
2  * ntoskrnl.exe implementation
3  *
4  * Copyright (C) 2007 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 "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25
26 #define NONAMELESSUNION
27 #define NONAMELESSSTRUCT
28
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winternl.h"
33 #include "excpt.h"
34 #include "ddk/ntddk.h"
35 #include "wine/unicode.h"
36 #include "wine/server.h"
37 #include "wine/list.h"
38 #include "wine/debug.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(ntoskrnl);
41 WINE_DECLARE_DEBUG_CHANNEL(relay);
42
43
44 KSYSTEM_TIME KeTickCount = { 0, 0, 0 };
45
46 typedef struct _KSERVICE_TABLE_DESCRIPTOR
47 {
48     PULONG_PTR Base;
49     PULONG Count;
50     ULONG Limit;
51     PUCHAR Number;
52 } KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR;
53
54 KSERVICE_TABLE_DESCRIPTOR KeServiceDescriptorTable[4] = { { 0 } };
55
56 typedef void (WINAPI *PCREATE_PROCESS_NOTIFY_ROUTINE)(HANDLE,HANDLE,BOOLEAN);
57 typedef void (WINAPI *PCREATE_THREAD_NOTIFY_ROUTINE)(HANDLE,HANDLE,BOOLEAN);
58
59 static struct list Irps = LIST_INIT(Irps);
60
61 struct IrpInstance
62 {
63     struct list entry;
64     IRP *irp;
65 };
66
67 #ifdef __i386__
68 #define DEFINE_FASTCALL1_ENTRYPOINT( name ) \
69     __ASM_GLOBAL_FUNC( name, \
70                        "popl %eax\n\t" \
71                        "pushl %ecx\n\t" \
72                        "pushl %eax\n\t" \
73                        "jmp " __ASM_NAME("__regs_") #name )
74 #define DEFINE_FASTCALL2_ENTRYPOINT( name ) \
75     __ASM_GLOBAL_FUNC( name, \
76                        "popl %eax\n\t" \
77                        "pushl %edx\n\t" \
78                        "pushl %ecx\n\t" \
79                        "pushl %eax\n\t" \
80                        "jmp " __ASM_NAME("__regs_") #name )
81 #endif
82
83 static inline LPCSTR debugstr_us( const UNICODE_STRING *us )
84 {
85     if (!us) return "<null>";
86     return debugstr_wn( us->Buffer, us->Length / sizeof(WCHAR) );
87 }
88
89 static HANDLE get_device_manager(void)
90 {
91     static HANDLE device_manager;
92     HANDLE handle = 0, ret = device_manager;
93
94     if (!ret)
95     {
96         SERVER_START_REQ( create_device_manager )
97         {
98             req->access     = SYNCHRONIZE;
99             req->attributes = 0;
100             if (!wine_server_call( req )) handle = wine_server_ptr_handle( reply->handle );
101         }
102         SERVER_END_REQ;
103
104         if (!handle)
105         {
106             ERR( "failed to create the device manager\n" );
107             return 0;
108         }
109         if (!(ret = InterlockedCompareExchangePointer( &device_manager, handle, 0 )))
110             ret = handle;
111         else
112             NtClose( handle );  /* somebody beat us to it */
113     }
114     return ret;
115 }
116
117 /* exception handler for emulation of privileged instructions */
118 static LONG CALLBACK vectored_handler( EXCEPTION_POINTERS *ptrs )
119 {
120     EXCEPTION_RECORD *record = ptrs->ExceptionRecord;
121
122     if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
123         record->ExceptionCode == EXCEPTION_PRIV_INSTRUCTION)
124     {
125 #ifdef __i386__
126         CONTEXT *context = ptrs->ContextRecord;
127         extern DWORD __wine_emulate_instruction( EXCEPTION_RECORD *rec, CONTEXT *context );
128
129         if (__wine_emulate_instruction( record, context ) == ExceptionContinueExecution)
130             return EXCEPTION_CONTINUE_EXECUTION;
131 #else
132         FIXME( "Privileged instruction emulation not implemented on this CPU\n" );
133 #endif
134     }
135     return EXCEPTION_CONTINUE_SEARCH;
136 }
137
138 /* process an ioctl request for a given device */
139 static NTSTATUS process_ioctl( DEVICE_OBJECT *device, ULONG code, void *in_buff, ULONG in_size,
140                                void *out_buff, ULONG *out_size )
141 {
142     IRP irp;
143     MDL mdl;
144     IO_STACK_LOCATION irpsp;
145     PDRIVER_DISPATCH dispatch = device->DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL];
146     NTSTATUS status;
147     LARGE_INTEGER count;
148
149     TRACE( "ioctl %x device %p in_size %u out_size %u\n", code, device, in_size, *out_size );
150
151     /* so we can spot things that we should initialize */
152     memset( &irp, 0x55, sizeof(irp) );
153     memset( &irpsp, 0x66, sizeof(irpsp) );
154     memset( &mdl, 0x77, sizeof(mdl) );
155
156     irp.RequestorMode = UserMode;
157     irp.AssociatedIrp.SystemBuffer = in_buff;
158     irp.UserBuffer = out_buff;
159     irp.MdlAddress = &mdl;
160     irp.Tail.Overlay.s.u.CurrentStackLocation = &irpsp;
161     irp.UserIosb = NULL;
162
163     irpsp.MajorFunction = IRP_MJ_DEVICE_CONTROL;
164     irpsp.Parameters.DeviceIoControl.OutputBufferLength = *out_size;
165     irpsp.Parameters.DeviceIoControl.InputBufferLength = in_size;
166     irpsp.Parameters.DeviceIoControl.IoControlCode = code;
167     irpsp.Parameters.DeviceIoControl.Type3InputBuffer = in_buff;
168     irpsp.DeviceObject = device;
169     irpsp.CompletionRoutine = NULL;
170
171     mdl.Next = NULL;
172     mdl.Size = 0;
173     mdl.StartVa = out_buff;
174     mdl.ByteCount = *out_size;
175     mdl.ByteOffset = 0;
176
177     device->CurrentIrp = &irp;
178
179     KeQueryTickCount( &count );  /* update the global KeTickCount */
180
181     if (TRACE_ON(relay))
182         DPRINTF( "%04x:Call driver dispatch %p (device=%p,irp=%p)\n",
183                  GetCurrentThreadId(), dispatch, device, &irp );
184
185     status = dispatch( device, &irp );
186
187     if (TRACE_ON(relay))
188         DPRINTF( "%04x:Ret  driver dispatch %p (device=%p,irp=%p) retval=%08x\n",
189                  GetCurrentThreadId(), dispatch, device, &irp, status );
190
191     *out_size = (irp.IoStatus.u.Status >= 0) ? irp.IoStatus.Information : 0;
192     return irp.IoStatus.u.Status;
193 }
194
195
196 /***********************************************************************
197  *           wine_ntoskrnl_main_loop   (Not a Windows API)
198  */
199 NTSTATUS CDECL wine_ntoskrnl_main_loop( HANDLE stop_event )
200 {
201     HANDLE manager = get_device_manager();
202     obj_handle_t ioctl = 0;
203     NTSTATUS status = STATUS_SUCCESS;
204     ULONG code = 0;
205     void *in_buff, *out_buff = NULL;
206     DEVICE_OBJECT *device = NULL;
207     ULONG in_size = 4096, out_size = 0;
208     HANDLE handles[2];
209
210     if (!(in_buff = HeapAlloc( GetProcessHeap(), 0, in_size )))
211     {
212         ERR( "failed to allocate buffer\n" );
213         return STATUS_NO_MEMORY;
214     }
215
216     handles[0] = stop_event;
217     handles[1] = manager;
218
219     for (;;)
220     {
221         SERVER_START_REQ( get_next_device_request )
222         {
223             req->manager = wine_server_obj_handle( manager );
224             req->prev = ioctl;
225             req->status = status;
226             wine_server_add_data( req, out_buff, out_size );
227             wine_server_set_reply( req, in_buff, in_size );
228             if (!(status = wine_server_call( req )))
229             {
230                 code     = reply->code;
231                 ioctl    = reply->next;
232                 device   = wine_server_get_ptr( reply->user_ptr );
233                 in_size  = reply->in_size;
234                 out_size = reply->out_size;
235             }
236             else
237             {
238                 ioctl = 0; /* no previous ioctl */
239                 out_size = 0;
240                 in_size = reply->in_size;
241             }
242         }
243         SERVER_END_REQ;
244
245         switch(status)
246         {
247         case STATUS_SUCCESS:
248             HeapFree( GetProcessHeap(), 0, out_buff );
249             if (out_size) out_buff = HeapAlloc( GetProcessHeap(), 0, out_size );
250             else out_buff = NULL;
251             status = process_ioctl( device, code, in_buff, in_size, out_buff, &out_size );
252             break;
253         case STATUS_BUFFER_OVERFLOW:
254             HeapFree( GetProcessHeap(), 0, in_buff );
255             in_buff = HeapAlloc( GetProcessHeap(), 0, in_size );
256             /* restart with larger buffer */
257             break;
258         case STATUS_PENDING:
259             if (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ) == WAIT_OBJECT_0)
260             {
261                 HeapFree( GetProcessHeap(), 0, in_buff );
262                 HeapFree( GetProcessHeap(), 0, out_buff );
263                 return STATUS_SUCCESS;
264             }
265             break;
266         }
267     }
268 }
269
270
271 /***********************************************************************
272  *           IoAllocateDriverObjectExtension  (NTOSKRNL.EXE.@)
273  */
274 NTSTATUS WINAPI IoAllocateDriverObjectExtension( PDRIVER_OBJECT DriverObject,
275                                                  PVOID ClientIdentificationAddress,
276                                                  ULONG DriverObjectExtensionSize,
277                                                  PVOID *DriverObjectExtension )
278 {
279     FIXME( "stub: %p, %p, %u, %p\n", DriverObject, ClientIdentificationAddress,
280             DriverObjectExtensionSize, DriverObjectExtension );
281     return STATUS_NOT_IMPLEMENTED;
282 }
283
284
285 /***********************************************************************
286  *           IoGetDriverObjectExtension  (NTOSKRNL.EXE.@)
287  */
288 PVOID WINAPI IoGetDriverObjectExtension( PDRIVER_OBJECT DriverObject,
289                                          PVOID ClientIdentificationAddress )
290 {
291     FIXME( "stub: %p, %p\n", DriverObject, ClientIdentificationAddress );
292     return NULL;
293 }
294
295
296 /***********************************************************************
297  *           IoInitializeIrp  (NTOSKRNL.EXE.@)
298  */
299 void WINAPI IoInitializeIrp( IRP *irp, USHORT size, CCHAR stack_size )
300 {
301     TRACE( "%p, %u, %d\n", irp, size, stack_size );
302
303     RtlZeroMemory( irp, size );
304
305     irp->Type = IO_TYPE_IRP;
306     irp->Size = size;
307     InitializeListHead( &irp->ThreadListEntry );
308     irp->StackCount = stack_size;
309     irp->CurrentLocation = stack_size + 1;
310     irp->Tail.Overlay.s.u.CurrentStackLocation =
311             (PIO_STACK_LOCATION)(irp + 1) + stack_size;
312 }
313
314
315 /***********************************************************************
316  *           IoAllocateIrp  (NTOSKRNL.EXE.@)
317  */
318 PIRP WINAPI IoAllocateIrp( CCHAR stack_size, BOOLEAN charge_quota )
319 {
320     SIZE_T size;
321     PIRP irp;
322
323     TRACE( "%d, %d\n", stack_size, charge_quota );
324
325     size = sizeof(IRP) + stack_size * sizeof(IO_STACK_LOCATION);
326     irp = ExAllocatePool( NonPagedPool, size );
327     if (irp == NULL)
328         return NULL;
329     IoInitializeIrp( irp, size, stack_size );
330     irp->AllocationFlags = IRP_ALLOCATED_FIXED_SIZE;
331     if (charge_quota)
332         irp->AllocationFlags |= IRP_LOOKASIDE_ALLOCATION;
333     return irp;
334 }
335
336
337 /***********************************************************************
338  *           IoFreeIrp  (NTOSKRNL.EXE.@)
339  */
340 void WINAPI IoFreeIrp( IRP *irp )
341 {
342     TRACE( "%p\n", irp );
343
344     ExFreePool( irp );
345 }
346
347
348 /***********************************************************************
349  *           IoAllocateMdl  (NTOSKRNL.EXE.@)
350  */
351 PMDL WINAPI IoAllocateMdl( PVOID VirtualAddress, ULONG Length, BOOLEAN SecondaryBuffer, BOOLEAN ChargeQuota, PIRP Irp )
352 {
353     FIXME( "stub: %p, %u, %i, %i, %p\n", VirtualAddress, Length, SecondaryBuffer, ChargeQuota, Irp );
354     return NULL;
355 }
356
357
358 /***********************************************************************
359  *           IoAllocateWorkItem  (NTOSKRNL.EXE.@)
360  */
361 PIO_WORKITEM WINAPI IoAllocateWorkItem( PDEVICE_OBJECT DeviceObject )
362 {
363     FIXME( "stub: %p\n", DeviceObject );
364     return NULL;
365 }
366
367
368 /***********************************************************************
369  *           IoAttachDeviceToDeviceStack  (NTOSKRNL.EXE.@)
370  */
371 PDEVICE_OBJECT WINAPI IoAttachDeviceToDeviceStack( DEVICE_OBJECT *source,
372                                                    DEVICE_OBJECT *target )
373 {
374     TRACE( "%p, %p\n", source, target );
375     target->AttachedDevice = source;
376     source->StackSize = target->StackSize + 1;
377     return target;
378 }
379
380
381 /***********************************************************************
382  *           IoBuildDeviceIoControlRequest  (NTOSKRNL.EXE.@)
383  */
384 PIRP WINAPI IoBuildDeviceIoControlRequest( ULONG IoControlCode,
385                                            PDEVICE_OBJECT DeviceObject,
386                                            PVOID InputBuffer,
387                                            ULONG InputBufferLength,
388                                            PVOID OutputBuffer,
389                                            ULONG OutputBufferLength,
390                                            BOOLEAN InternalDeviceIoControl,
391                                            PKEVENT Event,
392                                            PIO_STATUS_BLOCK IoStatusBlock )
393 {
394     PIRP irp;
395     PIO_STACK_LOCATION irpsp;
396     struct IrpInstance *instance;
397
398     TRACE( "%x, %p, %p, %u, %p, %u, %u, %p, %p\n",
399            IoControlCode, DeviceObject, InputBuffer, InputBufferLength,
400            OutputBuffer, OutputBufferLength, InternalDeviceIoControl,
401            Event, IoStatusBlock );
402
403     if (DeviceObject == NULL)
404         return NULL;
405
406     irp = IoAllocateIrp( DeviceObject->StackSize, FALSE );
407     if (irp == NULL)
408         return NULL;
409
410     instance = HeapAlloc( GetProcessHeap(), 0, sizeof(struct IrpInstance) );
411     if (instance == NULL)
412     {
413         IoFreeIrp( irp );
414         return NULL;
415     }
416     instance->irp = irp;
417     list_add_tail( &Irps, &instance->entry );
418
419     irpsp = irp->Tail.Overlay.s.u.CurrentStackLocation - 1;
420     irpsp->MajorFunction = InternalDeviceIoControl ?
421             IRP_MJ_INTERNAL_DEVICE_CONTROL : IRP_MJ_DEVICE_CONTROL;
422     irpsp->Parameters.DeviceIoControl.IoControlCode = IoControlCode;
423     irp->UserIosb = IoStatusBlock;
424     irp->UserEvent = Event;
425
426     return irp;
427 }
428
429
430 /***********************************************************************
431  *           IoCreateDriver   (NTOSKRNL.EXE.@)
432  */
433 NTSTATUS WINAPI IoCreateDriver( UNICODE_STRING *name, PDRIVER_INITIALIZE init )
434 {
435     DRIVER_OBJECT *driver;
436     DRIVER_EXTENSION *extension;
437     NTSTATUS status;
438
439     if (!(driver = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
440                                     sizeof(*driver) + sizeof(*extension) )))
441         return STATUS_NO_MEMORY;
442
443     if ((status = RtlDuplicateUnicodeString( 1, name, &driver->DriverName )))
444     {
445         RtlFreeHeap( GetProcessHeap(), 0, driver );
446         return status;
447     }
448
449     extension = (DRIVER_EXTENSION *)(driver + 1);
450     driver->Size            = sizeof(*driver);
451     driver->DriverInit      = init;
452     driver->DriverExtension = extension;
453     extension->DriverObject   = driver;
454     extension->ServiceKeyName = driver->DriverName;
455
456     status = driver->DriverInit( driver, name );
457
458     if (status)
459     {
460         RtlFreeUnicodeString( &driver->DriverName );
461         RtlFreeHeap( GetProcessHeap(), 0, driver );
462     }
463     return status;
464 }
465
466
467 /***********************************************************************
468  *           IoDeleteDriver   (NTOSKRNL.EXE.@)
469  */
470 void WINAPI IoDeleteDriver( DRIVER_OBJECT *driver )
471 {
472     RtlFreeUnicodeString( &driver->DriverName );
473     RtlFreeHeap( GetProcessHeap(), 0, driver );
474 }
475
476
477 /***********************************************************************
478  *           IoCreateDevice   (NTOSKRNL.EXE.@)
479  */
480 NTSTATUS WINAPI IoCreateDevice( DRIVER_OBJECT *driver, ULONG ext_size,
481                                 UNICODE_STRING *name, DEVICE_TYPE type,
482                                 ULONG characteristics, BOOLEAN exclusive,
483                                 DEVICE_OBJECT **ret_device )
484 {
485     NTSTATUS status;
486     DEVICE_OBJECT *device;
487     HANDLE handle = 0;
488     HANDLE manager = get_device_manager();
489
490     TRACE( "(%p, %u, %s, %u, %x, %u, %p)\n",
491            driver, ext_size, debugstr_us(name), type, characteristics, exclusive, ret_device );
492
493     if (!(device = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*device) + ext_size )))
494         return STATUS_NO_MEMORY;
495
496     SERVER_START_REQ( create_device )
497     {
498         req->access     = 0;
499         req->attributes = 0;
500         req->rootdir    = 0;
501         req->manager    = wine_server_obj_handle( manager );
502         req->user_ptr   = wine_server_client_ptr( device );
503         if (name) wine_server_add_data( req, name->Buffer, name->Length );
504         if (!(status = wine_server_call( req ))) handle = wine_server_ptr_handle( reply->handle );
505     }
506     SERVER_END_REQ;
507
508     if (status == STATUS_SUCCESS)
509     {
510         device->DriverObject    = driver;
511         device->DeviceExtension = device + 1;
512         device->DeviceType      = type;
513         device->StackSize       = 1;
514         device->Reserved        = handle;
515
516         device->NextDevice   = driver->DeviceObject;
517         driver->DeviceObject = device;
518
519         *ret_device = device;
520     }
521     else HeapFree( GetProcessHeap(), 0, device );
522
523     return status;
524 }
525
526
527 /***********************************************************************
528  *           IoDeleteDevice   (NTOSKRNL.EXE.@)
529  */
530 void WINAPI IoDeleteDevice( DEVICE_OBJECT *device )
531 {
532     NTSTATUS status;
533
534     TRACE( "%p\n", device );
535
536     SERVER_START_REQ( delete_device )
537     {
538         req->handle = wine_server_obj_handle( device->Reserved );
539         status = wine_server_call( req );
540     }
541     SERVER_END_REQ;
542
543     if (status == STATUS_SUCCESS)
544     {
545         DEVICE_OBJECT **prev = &device->DriverObject->DeviceObject;
546         while (*prev && *prev != device) prev = &(*prev)->NextDevice;
547         if (*prev) *prev = (*prev)->NextDevice;
548         NtClose( device->Reserved );
549         HeapFree( GetProcessHeap(), 0, device );
550     }
551 }
552
553
554 /***********************************************************************
555  *           IoCreateSymbolicLink   (NTOSKRNL.EXE.@)
556  */
557 NTSTATUS WINAPI IoCreateSymbolicLink( UNICODE_STRING *name, UNICODE_STRING *target )
558 {
559     HANDLE handle;
560     OBJECT_ATTRIBUTES attr;
561
562     attr.Length                   = sizeof(attr);
563     attr.RootDirectory            = 0;
564     attr.ObjectName               = name;
565     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
566     attr.SecurityDescriptor       = NULL;
567     attr.SecurityQualityOfService = NULL;
568
569     TRACE( "%s -> %s\n", debugstr_us(name), debugstr_us(target) );
570     /* FIXME: store handle somewhere */
571     return NtCreateSymbolicLinkObject( &handle, SYMBOLIC_LINK_ALL_ACCESS, &attr, target );
572 }
573
574
575 /***********************************************************************
576  *           IoDeleteSymbolicLink   (NTOSKRNL.EXE.@)
577  */
578 NTSTATUS WINAPI IoDeleteSymbolicLink( UNICODE_STRING *name )
579 {
580     HANDLE handle;
581     OBJECT_ATTRIBUTES attr;
582     NTSTATUS status;
583
584     attr.Length                   = sizeof(attr);
585     attr.RootDirectory            = 0;
586     attr.ObjectName               = name;
587     attr.Attributes               = OBJ_CASE_INSENSITIVE;
588     attr.SecurityDescriptor       = NULL;
589     attr.SecurityQualityOfService = NULL;
590
591     if (!(status = NtOpenSymbolicLinkObject( &handle, 0, &attr )))
592     {
593         SERVER_START_REQ( unlink_object )
594         {
595             req->handle = wine_server_obj_handle( handle );
596             status = wine_server_call( req );
597         }
598         SERVER_END_REQ;
599         NtClose( handle );
600     }
601     return status;
602 }
603
604
605 /***********************************************************************
606  *           IoGetDeviceObjectPointer   (NTOSKRNL.EXE.@)
607  */
608 NTSTATUS  WINAPI IoGetDeviceObjectPointer( UNICODE_STRING *name, ACCESS_MASK access, PFILE_OBJECT *file, PDEVICE_OBJECT *device )
609 {
610     FIXME( "stub: %s %x %p %p\n", debugstr_us(name), access, file, device );
611     return STATUS_NOT_IMPLEMENTED;
612 }
613
614
615 /***********************************************************************
616  *           IofCallDriver   (NTOSKRNL.EXE.@)
617  */
618 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
619 DEFINE_FASTCALL2_ENTRYPOINT( IofCallDriver )
620 NTSTATUS WINAPI __regs_IofCallDriver( DEVICE_OBJECT *device, IRP *irp )
621 #else
622 NTSTATUS WINAPI IofCallDriver( DEVICE_OBJECT *device, IRP *irp )
623 #endif
624 {
625     PDRIVER_DISPATCH dispatch;
626     IO_STACK_LOCATION *irpsp;
627     NTSTATUS status;
628
629     TRACE( "%p %p\n", device, irp );
630
631     --irp->CurrentLocation;
632     irpsp = --irp->Tail.Overlay.s.u.CurrentStackLocation;
633     dispatch = device->DriverObject->MajorFunction[irpsp->MajorFunction];
634     status = dispatch( device, irp );
635
636     return status;
637 }
638
639
640 /***********************************************************************
641  *           IoGetRelatedDeviceObject    (NTOSKRNL.EXE.@)
642  */
643 PDEVICE_OBJECT WINAPI IoGetRelatedDeviceObject( PFILE_OBJECT obj )
644 {
645     FIXME( "stub: %p\n", obj );
646     return NULL;
647 }
648
649 static CONFIGURATION_INFORMATION configuration_information;
650
651 /***********************************************************************
652  *           IoGetConfigurationInformation    (NTOSKRNL.EXE.@)
653  */
654 PCONFIGURATION_INFORMATION WINAPI IoGetConfigurationInformation(void)
655 {
656     FIXME( "partial stub\n" );
657     /* FIXME: return actual devices on system */
658     return &configuration_information;
659 }
660
661
662 /***********************************************************************
663  *           IoRegisterDriverReinitialization    (NTOSKRNL.EXE.@)
664  */
665 void WINAPI IoRegisterDriverReinitialization( PDRIVER_OBJECT obj, PDRIVER_REINITIALIZE reinit, PVOID context )
666 {
667     FIXME( "stub: %p %p %p\n", obj, reinit, context );
668 }
669
670
671 /***********************************************************************
672  *           IoRegisterShutdownNotification    (NTOSKRNL.EXE.@)
673  */
674 NTSTATUS WINAPI IoRegisterShutdownNotification( PDEVICE_OBJECT obj )
675 {
676     FIXME( "stub: %p\n", obj );
677     return STATUS_SUCCESS;
678 }
679
680
681 /***********************************************************************
682  *           IofCompleteRequest   (NTOSKRNL.EXE.@)
683  */
684 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
685 DEFINE_FASTCALL2_ENTRYPOINT( IofCompleteRequest )
686 void WINAPI __regs_IofCompleteRequest( IRP *irp, UCHAR priority_boost )
687 #else
688 void WINAPI IofCompleteRequest( IRP *irp, UCHAR priority_boost )
689 #endif
690 {
691     IO_STACK_LOCATION *irpsp;
692     PIO_COMPLETION_ROUTINE routine;
693     IO_STATUS_BLOCK *iosb;
694     struct IrpInstance *instance;
695     NTSTATUS status, stat;
696     int call_flag = 0;
697
698     TRACE( "%p %u\n", irp, priority_boost );
699
700     iosb = irp->UserIosb;
701     status = irp->IoStatus.u.Status;
702     while (irp->CurrentLocation <= irp->StackCount)
703     {
704         irpsp = irp->Tail.Overlay.s.u.CurrentStackLocation;
705         routine = irpsp->CompletionRoutine;
706         call_flag = 0;
707         /* FIXME: add SL_INVOKE_ON_CANCEL support */
708         if (routine)
709         {
710             if ((irpsp->Control & SL_INVOKE_ON_SUCCESS) && STATUS_SUCCESS == status)
711                 call_flag = 1;
712             if ((irpsp->Control & SL_INVOKE_ON_ERROR) && STATUS_SUCCESS != status)
713                 call_flag = 1;
714         }
715         ++irp->CurrentLocation;
716         ++irp->Tail.Overlay.s.u.CurrentStackLocation;
717         if (call_flag)
718         {
719             TRACE( "calling %p( %p, %p, %p )\n", routine,
720                     irpsp->DeviceObject, irp, irpsp->Context );
721             stat = routine( irpsp->DeviceObject, irp, irpsp->Context );
722             TRACE( "CompletionRoutine returned %x\n", stat );
723             if (STATUS_MORE_PROCESSING_REQUIRED == stat)
724                 return;
725         }
726     }
727     if (iosb && STATUS_SUCCESS == status)
728     {
729         iosb->u.Status = irp->IoStatus.u.Status;
730         iosb->Information = irp->IoStatus.Information;
731     }
732     LIST_FOR_EACH_ENTRY( instance, &Irps, struct IrpInstance, entry )
733     {
734         if (instance->irp == irp)
735         {
736             list_remove( &instance->entry );
737             HeapFree( GetProcessHeap(), 0, instance );
738             IoFreeIrp( irp );
739             break;
740         }
741     }
742 }
743
744
745 /***********************************************************************
746  *           InterlockedCompareExchange   (NTOSKRNL.EXE.@)
747  */
748 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
749 DEFINE_FASTCALL2_ENTRYPOINT( NTOSKRNL_InterlockedCompareExchange )
750 LONG WINAPI __regs_NTOSKRNL_InterlockedCompareExchange( LONG volatile *dest, LONG xchg, LONG compare )
751 #else
752 LONG WINAPI NTOSKRNL_InterlockedCompareExchange( LONG volatile *dest, LONG xchg, LONG compare )
753 #endif
754 {
755     return InterlockedCompareExchange( dest, xchg, compare );
756 }
757
758
759 /***********************************************************************
760  *           InterlockedDecrement   (NTOSKRNL.EXE.@)
761  */
762 #ifdef DEFINE_FASTCALL1_ENTRYPOINT
763 DEFINE_FASTCALL1_ENTRYPOINT( NTOSKRNL_InterlockedDecrement )
764 LONG WINAPI __regs_NTOSKRNL_InterlockedDecrement( LONG volatile *dest )
765 #else
766 LONG WINAPI NTOSKRNL_InterlockedDecrement( LONG volatile *dest )
767 #endif
768 {
769     return InterlockedDecrement( dest );
770 }
771
772
773 /***********************************************************************
774  *           InterlockedExchange   (NTOSKRNL.EXE.@)
775  */
776 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
777 DEFINE_FASTCALL2_ENTRYPOINT( NTOSKRNL_InterlockedExchange )
778 LONG WINAPI __regs_NTOSKRNL_InterlockedExchange( LONG volatile *dest, LONG val )
779 #else
780 LONG WINAPI NTOSKRNL_InterlockedExchange( LONG volatile *dest, LONG val )
781 #endif
782 {
783     return InterlockedExchange( dest, val );
784 }
785
786
787 /***********************************************************************
788  *           InterlockedExchangeAdd   (NTOSKRNL.EXE.@)
789  */
790 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
791 DEFINE_FASTCALL2_ENTRYPOINT( NTOSKRNL_InterlockedExchangeAdd )
792 LONG WINAPI __regs_NTOSKRNL_InterlockedExchangeAdd( LONG volatile *dest, LONG incr )
793 #else
794 LONG WINAPI NTOSKRNL_InterlockedExchangeAdd( LONG volatile *dest, LONG incr )
795 #endif
796 {
797     return InterlockedExchangeAdd( dest, incr );
798 }
799
800
801 /***********************************************************************
802  *           InterlockedIncrement   (NTOSKRNL.EXE.@)
803  */
804 #ifdef DEFINE_FASTCALL1_ENTRYPOINT
805 DEFINE_FASTCALL1_ENTRYPOINT( NTOSKRNL_InterlockedIncrement )
806 LONG WINAPI __regs_NTOSKRNL_InterlockedIncrement( LONG volatile *dest )
807 #else
808 LONG WINAPI NTOSKRNL_InterlockedIncrement( LONG volatile *dest )
809 #endif
810 {
811     return InterlockedIncrement( dest );
812 }
813
814
815 /***********************************************************************
816  *           ExAllocatePool   (NTOSKRNL.EXE.@)
817  */
818 PVOID WINAPI ExAllocatePool( POOL_TYPE type, SIZE_T size )
819 {
820     return ExAllocatePoolWithTag( type, size, 0 );
821 }
822
823
824 /***********************************************************************
825  *           ExAllocatePoolWithQuota   (NTOSKRNL.EXE.@)
826  */
827 PVOID WINAPI ExAllocatePoolWithQuota( POOL_TYPE type, SIZE_T size )
828 {
829     return ExAllocatePoolWithTag( type, size, 0 );
830 }
831
832
833 /***********************************************************************
834  *           ExAllocatePoolWithTag   (NTOSKRNL.EXE.@)
835  */
836 PVOID WINAPI ExAllocatePoolWithTag( POOL_TYPE type, SIZE_T size, ULONG tag )
837 {
838     /* FIXME: handle page alignment constraints */
839     void *ret = HeapAlloc( GetProcessHeap(), 0, size );
840     TRACE( "%lu pool %u -> %p\n", size, type, ret );
841     return ret;
842 }
843
844
845 /***********************************************************************
846  *           ExAllocatePoolWithQuotaTag   (NTOSKRNL.EXE.@)
847  */
848 PVOID WINAPI ExAllocatePoolWithQuotaTag( POOL_TYPE type, SIZE_T size, ULONG tag )
849 {
850     return ExAllocatePoolWithTag( type, size, tag );
851 }
852
853
854 /***********************************************************************
855  *           ExFreePool   (NTOSKRNL.EXE.@)
856  */
857 void WINAPI ExFreePool( void *ptr )
858 {
859     ExFreePoolWithTag( ptr, 0 );
860 }
861
862
863 /***********************************************************************
864  *           ExFreePoolWithTag   (NTOSKRNL.EXE.@)
865  */
866 void WINAPI ExFreePoolWithTag( void *ptr, ULONG tag )
867 {
868     TRACE( "%p\n", ptr );
869     HeapFree( GetProcessHeap(), 0, ptr );
870 }
871
872
873 /***********************************************************************
874  *           KeInitializeEvent   (NTOSKRNL.EXE.@)
875  */
876 void WINAPI KeInitializeEvent( PRKEVENT Event, EVENT_TYPE Type, BOOLEAN State )
877 {
878     FIXME( "stub: %p %d %d\n", Event, Type, State );
879 }
880
881
882 /***********************************************************************
883  *           KeInitializeSpinLock   (NTOSKRNL.EXE.@)
884  */
885 void WINAPI KeInitializeSpinLock( PKSPIN_LOCK SpinLock )
886 {
887     FIXME( "stub: %p\n", SpinLock );
888 }
889
890
891 /***********************************************************************
892  *           KeInitializeTimerEx   (NTOSKRNL.EXE.@)
893  */
894 void WINAPI KeInitializeTimerEx( PKTIMER Timer, TIMER_TYPE Type )
895 {
896     FIXME( "stub: %p %d\n", Timer, Type );
897 }
898
899
900 /***********************************************************************
901  *           KeInitializeTimer   (NTOSKRNL.EXE.@)
902  */
903 void WINAPI KeInitializeTimer( PKTIMER Timer )
904 {
905     KeInitializeTimerEx(Timer, NotificationTimer);
906 }
907
908
909 /**********************************************************************
910  *           KeQueryActiveProcessors   (NTOSKRNL.EXE.@)
911  *
912  * Return the active Processors as bitmask
913  *
914  * RETURNS
915  *   active Processors as bitmask
916  *
917  */
918 KAFFINITY WINAPI KeQueryActiveProcessors( void )
919 {
920     DWORD_PTR AffinityMask;
921
922     GetProcessAffinityMask( GetCurrentProcess(), &AffinityMask, NULL);
923     return AffinityMask;
924 }
925
926
927 /**********************************************************************
928  *           KeQueryInterruptTime   (NTOSKRNL.EXE.@)
929  *
930  * Return the interrupt time count
931  *
932  */
933 ULONGLONG WINAPI KeQueryInterruptTime( void )
934 {
935     LARGE_INTEGER totaltime;
936
937     KeQueryTickCount(&totaltime);
938     return totaltime.QuadPart;
939 }
940
941
942 /***********************************************************************
943  *           KeQuerySystemTime   (NTOSKRNL.EXE.@)
944  */
945 void WINAPI KeQuerySystemTime( LARGE_INTEGER *time )
946 {
947     NtQuerySystemTime( time );
948 }
949
950
951 /***********************************************************************
952  *           KeQueryTickCount   (NTOSKRNL.EXE.@)
953  */
954 void WINAPI KeQueryTickCount( LARGE_INTEGER *count )
955 {
956     count->QuadPart = NtGetTickCount();
957     /* update the global variable too */
958     KeTickCount.LowPart   = count->u.LowPart;
959     KeTickCount.High1Time = count->u.HighPart;
960     KeTickCount.High2Time = count->u.HighPart;
961 }
962
963
964 /***********************************************************************
965  *           KeQueryTimeIncrement   (NTOSKRNL.EXE.@)
966  */
967 ULONG WINAPI KeQueryTimeIncrement(void)
968 {
969     return 10000;
970 }
971
972
973 /***********************************************************************
974  *           MmAllocateNonCachedMemory   (NTOSKRNL.EXE.@)
975  */
976 PVOID WINAPI MmAllocateNonCachedMemory( SIZE_T size )
977 {
978     TRACE( "%lu\n", size );
979     return VirtualAlloc( NULL, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE|PAGE_NOCACHE );
980 }
981
982
983 /***********************************************************************
984  *           MmFreeNonCachedMemory   (NTOSKRNL.EXE.@)
985  */
986 void WINAPI MmFreeNonCachedMemory( void *addr, SIZE_T size )
987 {
988     TRACE( "%p %lu\n", addr, size );
989     VirtualFree( addr, 0, MEM_RELEASE );
990 }
991
992 /***********************************************************************
993  *           MmIsAddressValid   (NTOSKRNL.EXE.@)
994  *
995  * Check if the process can access the virtual address without a pagefault
996  *
997  * PARAMS
998  *  VirtualAddress [I] Address to check
999  *
1000  * RETURNS
1001  *  Failure: FALSE
1002  *  Success: TRUE  (Accessing the Address works without a Pagefault)
1003  *
1004  */
1005 BOOLEAN WINAPI MmIsAddressValid(PVOID VirtualAddress)
1006 {
1007     TRACE("(%p)\n", VirtualAddress);
1008     return !IsBadWritePtr(VirtualAddress, 1);
1009 }
1010
1011 /***********************************************************************
1012  *           MmPageEntireDriver   (NTOSKRNL.EXE.@)
1013  */
1014 PVOID WINAPI MmPageEntireDriver(PVOID AddrInSection)
1015 {
1016     TRACE("%p\n", AddrInSection);
1017     return AddrInSection;
1018 }
1019
1020 /***********************************************************************
1021  *           MmResetDriverPaging   (NTOSKRNL.EXE.@)
1022  */
1023 void WINAPI MmResetDriverPaging(PVOID AddrInSection)
1024 {
1025     TRACE("%p\n", AddrInSection);
1026 }
1027
1028
1029  /***********************************************************************
1030  *           ObReferenceObjectByHandle    (NTOSKRNL.EXE.@)
1031  */
1032 NTSTATUS WINAPI ObReferenceObjectByHandle( HANDLE obj, ACCESS_MASK access,
1033                                            POBJECT_TYPE type,
1034                                            KPROCESSOR_MODE mode, PVOID* ptr,
1035                                            POBJECT_HANDLE_INFORMATION info)
1036 {
1037     FIXME( "stub: %p %x %p %d %p %p\n", obj, access, type, mode, ptr, info);
1038     return STATUS_NOT_IMPLEMENTED;
1039 }
1040
1041
1042 /***********************************************************************
1043  *           ObfDereferenceObject   (NTOSKRNL.EXE.@)
1044  */
1045 #ifdef DEFINE_FASTCALL1_ENTRYPOINT
1046 DEFINE_FASTCALL1_ENTRYPOINT( ObfDereferenceObject )
1047 void WINAPI __regs_ObfDereferenceObject( VOID *obj )
1048 #else
1049 void WINAPI ObfDereferenceObject( VOID *obj )
1050 #endif
1051 {
1052     FIXME( "stub: %p\n", obj );
1053 }
1054
1055
1056 /***********************************************************************
1057  *           PsCreateSystemThread   (NTOSKRNL.EXE.@)
1058  */
1059 NTSTATUS WINAPI PsCreateSystemThread(PHANDLE ThreadHandle, ULONG DesiredAccess,
1060                                      POBJECT_ATTRIBUTES ObjectAttributes,
1061                                      HANDLE ProcessHandle, PCLIENT_ID ClientId,
1062                                      PKSTART_ROUTINE StartRoutine, PVOID StartContext)
1063 {
1064     if (!ProcessHandle) ProcessHandle = GetCurrentProcess();
1065     return RtlCreateUserThread(ProcessHandle, 0, FALSE, 0, 0,
1066                                0, StartRoutine, StartContext,
1067                                ThreadHandle, ClientId);
1068 }
1069
1070 /***********************************************************************
1071  *           PsGetCurrentProcessId   (NTOSKRNL.EXE.@)
1072  */
1073 HANDLE WINAPI PsGetCurrentProcessId(void)
1074 {
1075     return UlongToHandle(GetCurrentProcessId());  /* FIXME: not quite right... */
1076 }
1077
1078
1079 /***********************************************************************
1080  *           PsGetCurrentThreadId   (NTOSKRNL.EXE.@)
1081  */
1082 HANDLE WINAPI PsGetCurrentThreadId(void)
1083 {
1084     return UlongToHandle(GetCurrentThreadId());  /* FIXME: not quite right... */
1085 }
1086
1087
1088 /***********************************************************************
1089  *           PsGetVersion   (NTOSKRNL.EXE.@)
1090  */
1091 BOOLEAN WINAPI PsGetVersion(ULONG *major, ULONG *minor, ULONG *build, UNICODE_STRING *version )
1092 {
1093     RTL_OSVERSIONINFOEXW info;
1094
1095     RtlGetVersion( &info );
1096     if (major) *major = info.dwMajorVersion;
1097     if (minor) *minor = info.dwMinorVersion;
1098     if (build) *build = info.dwBuildNumber;
1099
1100     if (version)
1101     {
1102 #if 0  /* FIXME: GameGuard passes an uninitialized pointer in version->Buffer */
1103         size_t len = min( strlenW(info.szCSDVersion)*sizeof(WCHAR), version->MaximumLength );
1104         memcpy( version->Buffer, info.szCSDVersion, len );
1105         if (len < version->MaximumLength) version->Buffer[len / sizeof(WCHAR)] = 0;
1106         version->Length = len;
1107 #endif
1108     }
1109     return TRUE;
1110 }
1111
1112
1113 /***********************************************************************
1114  *           PsSetCreateProcessNotifyRoutine   (NTOSKRNL.EXE.@)
1115  */
1116 NTSTATUS WINAPI PsSetCreateProcessNotifyRoutine( PCREATE_PROCESS_NOTIFY_ROUTINE callback, BOOLEAN remove )
1117 {
1118     FIXME( "stub: %p %d\n", callback, remove );
1119     return STATUS_SUCCESS;
1120 }
1121
1122
1123 /***********************************************************************
1124  *           PsSetCreateThreadNotifyRoutine   (NTOSKRNL.EXE.@)
1125  */
1126 NTSTATUS WINAPI PsSetCreateThreadNotifyRoutine( PCREATE_THREAD_NOTIFY_ROUTINE NotifyRoutine )
1127 {
1128     FIXME( "stub: %p\n", NotifyRoutine );
1129     return STATUS_SUCCESS;
1130 }
1131
1132
1133 /***********************************************************************
1134  *           MmGetSystemRoutineAddress   (NTOSKRNL.EXE.@)
1135  */
1136 PVOID WINAPI MmGetSystemRoutineAddress(PUNICODE_STRING SystemRoutineName)
1137 {
1138     HMODULE hMod;
1139     STRING routineNameA;
1140     PVOID pFunc = NULL;
1141
1142     static const WCHAR ntoskrnlW[] = {'n','t','o','s','k','r','n','l','.','e','x','e',0};
1143     static const WCHAR halW[] = {'h','a','l','.','d','l','l',0};
1144
1145     if (!SystemRoutineName) return NULL;
1146
1147     if (RtlUnicodeStringToAnsiString( &routineNameA, SystemRoutineName, TRUE ) == STATUS_SUCCESS)
1148     {
1149         /* We only support functions exported from ntoskrnl.exe or hal.dll */
1150         hMod = GetModuleHandleW( ntoskrnlW );
1151         pFunc = GetProcAddress( hMod, routineNameA.Buffer );
1152         if (!pFunc)
1153         {
1154            hMod = GetModuleHandleW( halW );
1155            if (hMod) pFunc = GetProcAddress( hMod, routineNameA.Buffer );
1156         }
1157         RtlFreeAnsiString( &routineNameA );
1158     }
1159
1160     TRACE( "%s -> %p\n", debugstr_us(SystemRoutineName), pFunc );
1161     return pFunc;
1162 }
1163
1164 /*****************************************************
1165  *           DllMain
1166  */
1167 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
1168 {
1169     static void *handler;
1170     LARGE_INTEGER count;
1171
1172     switch(reason)
1173     {
1174     case DLL_PROCESS_ATTACH:
1175         DisableThreadLibraryCalls( inst );
1176         handler = RtlAddVectoredExceptionHandler( TRUE, vectored_handler );
1177         KeQueryTickCount( &count );  /* initialize the global KeTickCount */
1178         break;
1179     case DLL_PROCESS_DETACH:
1180         RtlRemoveVectoredExceptionHandler( handler );
1181         break;
1182     }
1183     return TRUE;
1184 }