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