iphlpapi: Don't allocate gobs of memory when the route table is empty.
[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/wdm.h"
35 #include "wine/unicode.h"
36 #include "wine/server.h"
37 #include "wine/debug.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(ntoskrnl);
40 WINE_DECLARE_DEBUG_CHANNEL(relay);
41
42
43 KSYSTEM_TIME KeTickCount;
44
45 typedef struct _KSERVICE_TABLE_DESCRIPTOR
46 {
47     PULONG_PTR Base;
48     PULONG Count;
49     ULONG Limit;
50     PUCHAR Number;
51 } KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR;
52
53 KSERVICE_TABLE_DESCRIPTOR KeServiceDescriptorTable[4];
54
55 typedef void (WINAPI *PCREATE_PROCESS_NOTIFY_ROUTINE)(HANDLE,HANDLE,BOOLEAN);
56
57 #ifdef __i386__
58 #define DEFINE_FASTCALL1_ENTRYPOINT( name ) \
59     __ASM_GLOBAL_FUNC( name, \
60                        "popl %eax\n\t" \
61                        "pushl %ecx\n\t" \
62                        "pushl %eax\n\t" \
63                        "jmp " __ASM_NAME("__regs_") #name )
64 #define DEFINE_FASTCALL2_ENTRYPOINT( name ) \
65     __ASM_GLOBAL_FUNC( name, \
66                        "popl %eax\n\t" \
67                        "pushl %edx\n\t" \
68                        "pushl %ecx\n\t" \
69                        "pushl %eax\n\t" \
70                        "jmp " __ASM_NAME("__regs_") #name )
71 #endif
72
73 static inline LPCSTR debugstr_us( const UNICODE_STRING *us )
74 {
75     if (!us) return "<null>";
76     return debugstr_wn( us->Buffer, us->Length / sizeof(WCHAR) );
77 }
78
79 static HANDLE get_device_manager(void)
80 {
81     static HANDLE device_manager;
82     HANDLE handle = 0, ret = device_manager;
83
84     if (!ret)
85     {
86         SERVER_START_REQ( create_device_manager )
87         {
88             req->access     = SYNCHRONIZE;
89             req->attributes = 0;
90             if (!wine_server_call( req )) handle = reply->handle;
91         }
92         SERVER_END_REQ;
93
94         if (!handle)
95         {
96             ERR( "failed to create the device manager\n" );
97             return 0;
98         }
99         if (!(ret = InterlockedCompareExchangePointer( &device_manager, handle, 0 )))
100             ret = handle;
101         else
102             NtClose( handle );  /* somebody beat us to it */
103     }
104     return ret;
105 }
106
107 /* exception handler for emulation of privileged instructions */
108 static LONG CALLBACK vectored_handler( EXCEPTION_POINTERS *ptrs )
109 {
110     extern DWORD __wine_emulate_instruction( EXCEPTION_RECORD *rec, CONTEXT86 *context );
111
112     EXCEPTION_RECORD *record = ptrs->ExceptionRecord;
113     CONTEXT86 *context = ptrs->ContextRecord;
114
115     if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
116         record->ExceptionCode == EXCEPTION_PRIV_INSTRUCTION)
117     {
118         if (__wine_emulate_instruction( record, context ) == ExceptionContinueExecution)
119             return EXCEPTION_CONTINUE_EXECUTION;
120     }
121     return EXCEPTION_CONTINUE_SEARCH;
122 }
123
124 /* process an ioctl request for a given device */
125 static NTSTATUS process_ioctl( DEVICE_OBJECT *device, ULONG code, void *in_buff, ULONG in_size,
126                                void *out_buff, ULONG *out_size )
127 {
128     IRP irp;
129     MDL mdl;
130     IO_STACK_LOCATION irpsp;
131     PDRIVER_DISPATCH dispatch = device->DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL];
132     NTSTATUS status;
133     LARGE_INTEGER count;
134
135     TRACE( "ioctl %x device %p in_size %u out_size %u\n", code, device, in_size, *out_size );
136
137     /* so we can spot things that we should initialize */
138     memset( &irp, 0x55, sizeof(irp) );
139     memset( &irpsp, 0x66, sizeof(irpsp) );
140     memset( &mdl, 0x77, sizeof(mdl) );
141
142     irp.RequestorMode = UserMode;
143     irp.AssociatedIrp.SystemBuffer = in_buff;
144     irp.UserBuffer = out_buff;
145     irp.MdlAddress = &mdl;
146     irp.Tail.Overlay.s.u.CurrentStackLocation = &irpsp;
147
148     irpsp.MajorFunction = IRP_MJ_DEVICE_CONTROL;
149     irpsp.Parameters.DeviceIoControl.OutputBufferLength = *out_size;
150     irpsp.Parameters.DeviceIoControl.InputBufferLength = in_size;
151     irpsp.Parameters.DeviceIoControl.IoControlCode = code;
152     irpsp.Parameters.DeviceIoControl.Type3InputBuffer = in_buff;
153     irpsp.DeviceObject = device;
154
155     mdl.Next = NULL;
156     mdl.Size = 0;
157     mdl.StartVa = out_buff;
158     mdl.ByteCount = *out_size;
159     mdl.ByteOffset = 0;
160
161     device->CurrentIrp = &irp;
162
163     KeQueryTickCount( &count );  /* update the global KeTickCount */
164
165     if (TRACE_ON(relay))
166         DPRINTF( "%04x:Call driver dispatch %p (device=%p,irp=%p)\n",
167                  GetCurrentThreadId(), dispatch, device, &irp );
168
169     status = dispatch( device, &irp );
170
171     if (TRACE_ON(relay))
172         DPRINTF( "%04x:Ret  driver dispatch %p (device=%p,irp=%p) retval=%08x\n",
173                  GetCurrentThreadId(), dispatch, device, &irp, status );
174
175     *out_size = irp.IoStatus.u.Status ? 0 : irp.IoStatus.Information;
176     return irp.IoStatus.u.Status;
177 }
178
179
180 /***********************************************************************
181  *           wine_ntoskrnl_main_loop   (Not a Windows API)
182  */
183 NTSTATUS wine_ntoskrnl_main_loop( HANDLE stop_event )
184 {
185     HANDLE manager = get_device_manager();
186     HANDLE ioctl = 0;
187     NTSTATUS status = STATUS_SUCCESS;
188     ULONG code = 0;
189     void *in_buff, *out_buff = NULL;
190     DEVICE_OBJECT *device = NULL;
191     ULONG in_size = 4096, out_size = 0;
192     HANDLE handles[2];
193
194     if (!(in_buff = HeapAlloc( GetProcessHeap(), 0, in_size )))
195     {
196         ERR( "failed to allocate buffer\n" );
197         return STATUS_NO_MEMORY;
198     }
199
200     handles[0] = stop_event;
201     handles[1] = manager;
202
203     for (;;)
204     {
205         SERVER_START_REQ( get_next_device_request )
206         {
207             req->manager = manager;
208             req->prev = ioctl;
209             req->status = status;
210             wine_server_add_data( req, out_buff, out_size );
211             wine_server_set_reply( req, in_buff, in_size );
212             if (!(status = wine_server_call( req )))
213             {
214                 code     = reply->code;
215                 ioctl    = reply->next;
216                 device   = reply->user_ptr;
217                 in_size  = reply->in_size;
218                 out_size = reply->out_size;
219             }
220             else
221             {
222                 ioctl = 0; /* no previous ioctl */
223                 out_size = 0;
224                 in_size = reply->in_size;
225             }
226         }
227         SERVER_END_REQ;
228
229         switch(status)
230         {
231         case STATUS_SUCCESS:
232             HeapFree( GetProcessHeap(), 0, out_buff );
233             if (out_size) out_buff = HeapAlloc( GetProcessHeap(), 0, out_size );
234             else out_buff = NULL;
235             status = process_ioctl( device, code, in_buff, in_size, out_buff, &out_size );
236             break;
237         case STATUS_BUFFER_OVERFLOW:
238             HeapFree( GetProcessHeap(), 0, in_buff );
239             in_buff = HeapAlloc( GetProcessHeap(), 0, in_size );
240             /* restart with larger buffer */
241             break;
242         case STATUS_PENDING:
243             if (WaitForMultipleObjects( 2, handles, FALSE, INFINITE ) == WAIT_OBJECT_0)
244                 return STATUS_SUCCESS;
245             break;
246         }
247     }
248 }
249
250 /***********************************************************************
251  *           IoAllocateMdl  (NTOSKRNL.EXE.@)
252  */
253 PMDL WINAPI IoAllocateMdl( PVOID VirtualAddress, ULONG Length, BOOLEAN SecondaryBuffer, BOOLEAN ChargeQuota, PIRP Irp )
254 {
255     FIXME( "stub: %p, %u, %i, %i, %p\n", VirtualAddress, Length, SecondaryBuffer, ChargeQuota, Irp );
256     return NULL;
257 }
258
259
260 /***********************************************************************
261  *           IoAllocateWorkItem  (NTOSKRNL.EXE.@)
262  */
263 PIO_WORKITEM WINAPI IoAllocateWorkItem( PDEVICE_OBJECT DeviceObject )
264 {
265     FIXME( "stub: %p\n", DeviceObject );
266     return NULL;
267 }
268
269
270 /***********************************************************************
271  *           IoCreateDevice   (NTOSKRNL.EXE.@)
272  */
273 NTSTATUS WINAPI IoCreateDevice( DRIVER_OBJECT *driver, ULONG ext_size,
274                                 UNICODE_STRING *name, DEVICE_TYPE type,
275                                 ULONG characteristics, BOOLEAN exclusive,
276                                 DEVICE_OBJECT **ret_device )
277 {
278     NTSTATUS status;
279     DEVICE_OBJECT *device;
280     HANDLE handle = 0;
281     HANDLE manager = get_device_manager();
282
283     TRACE( "(%p, %u, %s, %u, %x, %u, %p)\n",
284            driver, ext_size, debugstr_us(name), type, characteristics, exclusive, ret_device );
285
286     if (!(device = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*device) + ext_size )))
287         return STATUS_NO_MEMORY;
288
289     SERVER_START_REQ( create_device )
290     {
291         req->access     = 0;
292         req->attributes = 0;
293         req->rootdir    = 0;
294         req->manager    = manager;
295         req->user_ptr   = device;
296         if (name) wine_server_add_data( req, name->Buffer, name->Length );
297         if (!(status = wine_server_call( req ))) handle = reply->handle;
298     }
299     SERVER_END_REQ;
300
301     if (status == STATUS_SUCCESS)
302     {
303         device->DriverObject    = driver;
304         device->DeviceExtension = device + 1;
305         device->DeviceType      = type;
306         device->Reserved        = handle;
307
308         device->NextDevice   = driver->DeviceObject;
309         driver->DeviceObject = device;
310
311         *ret_device = device;
312     }
313     else HeapFree( GetProcessHeap(), 0, device );
314
315     return status;
316 }
317
318
319 /***********************************************************************
320  *           IoDeleteDevice   (NTOSKRNL.EXE.@)
321  */
322 void WINAPI IoDeleteDevice( DEVICE_OBJECT *device )
323 {
324     NTSTATUS status;
325
326     TRACE( "%p\n", device );
327
328     SERVER_START_REQ( delete_device )
329     {
330         req->handle = device->Reserved;
331         status = wine_server_call( req );
332     }
333     SERVER_END_REQ;
334
335     if (status == STATUS_SUCCESS)
336     {
337         DEVICE_OBJECT **prev = &device->DriverObject->DeviceObject;
338         while (*prev && *prev != device) prev = &(*prev)->NextDevice;
339         if (*prev) *prev = (*prev)->NextDevice;
340         NtClose( device->Reserved );
341         HeapFree( GetProcessHeap(), 0, device );
342     }
343 }
344
345
346 /***********************************************************************
347  *           IoCreateSymbolicLink   (NTOSKRNL.EXE.@)
348  */
349 NTSTATUS WINAPI IoCreateSymbolicLink( UNICODE_STRING *name, UNICODE_STRING *target )
350 {
351     HANDLE handle;
352     OBJECT_ATTRIBUTES attr;
353
354     attr.Length                   = sizeof(attr);
355     attr.RootDirectory            = 0;
356     attr.ObjectName               = name;
357     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
358     attr.SecurityDescriptor       = NULL;
359     attr.SecurityQualityOfService = NULL;
360
361     TRACE( "%s -> %s\n", debugstr_us(name), debugstr_us(target) );
362     /* FIXME: store handle somewhere */
363     return NtCreateSymbolicLinkObject( &handle, SYMBOLIC_LINK_ALL_ACCESS, &attr, target );
364 }
365
366
367 /***********************************************************************
368  *           IofCompleteRequest   (NTOSKRNL.EXE.@)
369  */
370 #ifdef DEFINE_FASTCALL2_ENTRYPOINT
371 DEFINE_FASTCALL2_ENTRYPOINT( IofCompleteRequest )
372 void WINAPI __regs_IofCompleteRequest( IRP *irp, UCHAR priority_boost )
373 #else
374 void WINAPI IofCompleteRequest( IRP *irp, UCHAR priority_boost )
375 #endif
376 {
377     TRACE( "%p %u\n", irp, priority_boost );
378     /* nothing to do for now */
379 }
380
381
382 /***********************************************************************
383  *           ExAllocatePool   (NTOSKRNL.EXE.@)
384  */
385 PVOID WINAPI ExAllocatePool( POOL_TYPE type, SIZE_T size )
386 {
387     return ExAllocatePoolWithTag( type, size, 0 );
388 }
389
390
391 /***********************************************************************
392  *           ExAllocatePoolWithQuota   (NTOSKRNL.EXE.@)
393  */
394 PVOID WINAPI ExAllocatePoolWithQuota( POOL_TYPE type, SIZE_T size )
395 {
396     return ExAllocatePoolWithTag( type, size, 0 );
397 }
398
399
400 /***********************************************************************
401  *           ExAllocatePoolWithTag   (NTOSKRNL.EXE.@)
402  */
403 PVOID WINAPI ExAllocatePoolWithTag( POOL_TYPE type, SIZE_T size, ULONG tag )
404 {
405     /* FIXME: handle page alignment constraints */
406     void *ret = HeapAlloc( GetProcessHeap(), 0, size );
407     TRACE( "%lu pool %u -> %p\n", size, type, ret );
408     return ret;
409 }
410
411
412 /***********************************************************************
413  *           ExAllocatePoolWithQuotaTag   (NTOSKRNL.EXE.@)
414  */
415 PVOID WINAPI ExAllocatePoolWithQuotaTag( POOL_TYPE type, SIZE_T size, ULONG tag )
416 {
417     return ExAllocatePoolWithTag( type, size, tag );
418 }
419
420
421 /***********************************************************************
422  *           ExFreePool   (NTOSKRNL.EXE.@)
423  */
424 void WINAPI ExFreePool( void *ptr )
425 {
426     ExFreePoolWithTag( ptr, 0 );
427 }
428
429
430 /***********************************************************************
431  *           ExFreePoolWithTag   (NTOSKRNL.EXE.@)
432  */
433 void WINAPI ExFreePoolWithTag( void *ptr, ULONG tag )
434 {
435     TRACE( "%p\n", ptr );
436     HeapFree( GetProcessHeap(), 0, ptr );
437 }
438
439
440 /***********************************************************************
441  *           KeInitializeTimer   (NTOSKRNL.EXE.@)
442  */
443 void WINAPI KeInitializeTimer( PKTIMER Timer )
444 {
445     FIXME("%p\n", Timer);
446 }
447
448
449 /***********************************************************************
450  *           KeQuerySystemTime   (NTOSKRNL.EXE.@)
451  */
452 void WINAPI KeQuerySystemTime( LARGE_INTEGER *time )
453 {
454     NtQuerySystemTime( time );
455 }
456
457
458 /***********************************************************************
459  *           KeQueryTickCount   (NTOSKRNL.EXE.@)
460  */
461 void WINAPI KeQueryTickCount( LARGE_INTEGER *count )
462 {
463     count->QuadPart = NtGetTickCount();
464     /* update the global variable too */
465     KeTickCount.LowPart   = count->u.LowPart;
466     KeTickCount.High1Time = count->u.HighPart;
467     KeTickCount.High2Time = count->u.HighPart;
468 }
469
470
471 /***********************************************************************
472  *           KeQueryTimeIncrement   (NTOSKRNL.EXE.@)
473  */
474 ULONG WINAPI KeQueryTimeIncrement(void)
475 {
476     return 10000;
477 }
478
479
480 /***********************************************************************
481  *           MmAllocateNonCachedMemory   (NTOSKRNL.EXE.@)
482  */
483 PVOID WINAPI MmAllocateNonCachedMemory( SIZE_T size )
484 {
485     TRACE( "%lu\n", size );
486     return VirtualAlloc( NULL, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE|PAGE_NOCACHE );
487 }
488
489
490 /***********************************************************************
491  *           MmFreeNonCachedMemory   (NTOSKRNL.EXE.@)
492  */
493 void WINAPI MmFreeNonCachedMemory( void *addr, SIZE_T size )
494 {
495     TRACE( "%p %lu\n", addr, size );
496     VirtualFree( addr, 0, MEM_RELEASE );
497 }
498
499 /***********************************************************************
500  *           PsCreateSystemThread   (NTOSKRNL.EXE.@)
501  */
502 NTSTATUS WINAPI PsCreateSystemThread(PHANDLE ThreadHandle, ULONG DesiredAccess,
503                                      POBJECT_ATTRIBUTES ObjectAttributes,
504                                      HANDLE ProcessHandle, PCLIENT_ID ClientId,
505                                      PKSTART_ROUTINE StartRoutine, PVOID StartContext)
506 {
507     if (!ProcessHandle) ProcessHandle = GetCurrentProcess();
508     return RtlCreateUserThread(ProcessHandle, 0, FALSE, 0, 0,
509                                0, StartRoutine, StartContext,
510                                ThreadHandle, ClientId);
511 }
512
513 /***********************************************************************
514  *           PsGetCurrentProcessId   (NTOSKRNL.EXE.@)
515  */
516 HANDLE WINAPI PsGetCurrentProcessId(void)
517 {
518     return (HANDLE)GetCurrentProcessId();  /* FIXME: not quite right... */
519 }
520
521
522 /***********************************************************************
523  *           PsGetCurrentThreadId   (NTOSKRNL.EXE.@)
524  */
525 HANDLE WINAPI PsGetCurrentThreadId(void)
526 {
527     return (HANDLE)GetCurrentThreadId();  /* FIXME: not quite right... */
528 }
529
530
531 /***********************************************************************
532  *           PsGetVersion   (NTOSKRNL.EXE.@)
533  */
534 BOOLEAN WINAPI PsGetVersion(ULONG *major, ULONG *minor, ULONG *build, UNICODE_STRING *version )
535 {
536     RTL_OSVERSIONINFOEXW info;
537
538     RtlGetVersion( &info );
539     if (major) *major = info.dwMajorVersion;
540     if (minor) *minor = info.dwMinorVersion;
541     if (build) *build = info.dwBuildNumber;
542
543     if (version)
544     {
545 #if 0  /* FIXME: GameGuard passes an uninitialized pointer in version->Buffer */
546         size_t len = min( strlenW(info.szCSDVersion)*sizeof(WCHAR), version->MaximumLength );
547         memcpy( version->Buffer, info.szCSDVersion, len );
548         if (len < version->MaximumLength) version->Buffer[len / sizeof(WCHAR)] = 0;
549         version->Length = len;
550 #endif
551     }
552     return TRUE;
553 }
554
555
556 /***********************************************************************
557  *           PsSetCreateProcessNotifyRoutine   (NTOSKRNL.EXE.@)
558  */
559 NTSTATUS WINAPI PsSetCreateProcessNotifyRoutine( PCREATE_PROCESS_NOTIFY_ROUTINE callback, BOOLEAN remove )
560 {
561     FIXME( "stub: %p %d\n", callback, remove );
562     return STATUS_SUCCESS;
563 }
564
565
566 /*****************************************************
567  *           DllMain
568  */
569 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
570 {
571     LARGE_INTEGER count;
572
573     switch(reason)
574     {
575     case DLL_PROCESS_ATTACH:
576         DisableThreadLibraryCalls( inst );
577         RtlAddVectoredExceptionHandler( TRUE, vectored_handler );
578         KeQueryTickCount( &count );  /* initialize the global KeTickCount */
579         break;
580     }
581     return TRUE;
582 }