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