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