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