kernel32: Add GetConsoleFontInfo stub.
[wine.git] / programs / winedevice / device.c
blob94132ed07875d8f56fa1e0d89703e676f1d874ac
1 /*
2 * Service process to load a kernel driver
4 * Copyright 2007 Alexandre Julliard
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.
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.
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <stdarg.h>
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winternl.h"
31 #include "winreg.h"
32 #include "winnls.h"
33 #include "winsvc.h"
34 #include "ddk/wdm.h"
35 #include "wine/unicode.h"
36 #include "wine/debug.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(winedevice);
39 WINE_DECLARE_DEBUG_CHANNEL(relay);
41 extern NTSTATUS CDECL wine_ntoskrnl_main_loop( HANDLE stop_event );
43 static WCHAR *driver_name;
44 static SERVICE_STATUS_HANDLE service_handle;
45 static HANDLE stop_event;
46 static DRIVER_OBJECT driver_obj;
47 static DRIVER_EXTENSION driver_extension;
49 /* find the LDR_MODULE corresponding to the driver module */
50 static LDR_MODULE *find_ldr_module( HMODULE module )
52 LDR_MODULE *ldr;
53 ULONG_PTR magic;
55 LdrLockLoaderLock( 0, NULL, &magic );
56 if (LdrFindEntryForAddress( module, &ldr ))
58 WARN( "module not found for %p\n", module );
59 ldr = NULL;
61 LdrUnlockLoaderLock( 0, magic );
63 return ldr;
66 /* load the driver module file */
67 static HMODULE load_driver_module( const WCHAR *name )
69 IMAGE_NT_HEADERS *nt;
70 const IMAGE_IMPORT_DESCRIPTOR *imports;
71 SYSTEM_BASIC_INFORMATION info;
72 int i;
73 INT_PTR delta;
74 ULONG size;
75 HMODULE module = LoadLibraryW( name );
77 if (!module) return NULL;
78 nt = RtlImageNtHeader( module );
80 if (!(delta = (char *)module - (char *)nt->OptionalHeader.ImageBase)) return module;
82 /* the loader does not apply relocations to non page-aligned binaries or executables,
83 * we have to do it ourselves */
85 NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL );
86 if (nt->OptionalHeader.SectionAlignment < info.PageSize ||
87 !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
89 DWORD old;
90 IMAGE_BASE_RELOCATION *rel, *end;
92 if ((rel = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_BASERELOC, &size )))
94 WINE_TRACE( "%s: relocating from %p to %p\n",
95 wine_dbgstr_w(name), (char *)module - delta, module );
96 end = (IMAGE_BASE_RELOCATION *)((char *)rel + size);
97 while (rel < end && rel->SizeOfBlock)
99 void *page = (char *)module + rel->VirtualAddress;
100 VirtualProtect( page, info.PageSize, PAGE_EXECUTE_READWRITE, &old );
101 rel = LdrProcessRelocationBlock( page, (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
102 (USHORT *)(rel + 1), delta );
103 if (old != PAGE_EXECUTE_READWRITE) VirtualProtect( page, info.PageSize, old, &old );
104 if (!rel) goto error;
106 /* make sure we don't try again */
107 size = FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + nt->FileHeader.SizeOfOptionalHeader;
108 VirtualProtect( nt, size, PAGE_READWRITE, &old );
109 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
110 VirtualProtect( nt, size, old, &old );
114 /* make sure imports are relocated too */
116 if ((imports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
118 for (i = 0; imports[i].Name && imports[i].FirstThunk; i++)
120 char *name = (char *)module + imports[i].Name;
121 WCHAR buffer[32], *p = buffer;
123 while (p < buffer + 32) if (!(*p++ = *name++)) break;
124 if (p <= buffer + 32) FreeLibrary( load_driver_module( buffer ) );
128 return module;
130 error:
131 FreeLibrary( module );
132 return NULL;
135 /* call the driver init entry point */
136 static NTSTATUS init_driver( HMODULE module, UNICODE_STRING *keyname )
138 unsigned int i;
139 NTSTATUS status;
140 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
142 if (!nt->OptionalHeader.AddressOfEntryPoint) return STATUS_SUCCESS;
144 driver_obj.Size = sizeof(driver_obj);
145 driver_obj.DriverSection = find_ldr_module( module );
146 driver_obj.DriverInit = (PDRIVER_INITIALIZE)((char *)module + nt->OptionalHeader.AddressOfEntryPoint);
147 driver_obj.DriverExtension = &driver_extension;
149 driver_extension.DriverObject = &driver_obj;
150 driver_extension.ServiceKeyName = *keyname;
152 if (WINE_TRACE_ON(relay))
153 WINE_DPRINTF( "%04x:Call driver init %p (obj=%p,str=%s)\n", GetCurrentThreadId(),
154 driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer) );
156 status = driver_obj.DriverInit( &driver_obj, keyname );
158 if (WINE_TRACE_ON(relay))
159 WINE_DPRINTF( "%04x:Ret driver init %p (obj=%p,str=%s) retval=%08x\n", GetCurrentThreadId(),
160 driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer), status );
162 WINE_TRACE( "init done for %s obj %p\n", wine_dbgstr_w(driver_name), &driver_obj );
163 WINE_TRACE( "- DriverInit = %p\n", driver_obj.DriverInit );
164 WINE_TRACE( "- DriverStartIo = %p\n", driver_obj.DriverStartIo );
165 WINE_TRACE( "- DriverUnload = %p\n", driver_obj.DriverUnload );
166 for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
167 WINE_TRACE( "- MajorFunction[%d] = %p\n", i, driver_obj.MajorFunction[i] );
169 return status;
172 /* call the driver unload function */
173 static void unload_driver( HMODULE module, DRIVER_OBJECT *driver_obj )
175 if (driver_obj->DriverUnload)
177 if (WINE_TRACE_ON(relay))
178 WINE_DPRINTF( "%04x:Call driver unload %p (obj=%p)\n", GetCurrentThreadId(),
179 driver_obj->DriverUnload, driver_obj );
181 driver_obj->DriverUnload( driver_obj );
183 if (WINE_TRACE_ON(relay))
184 WINE_DPRINTF( "%04x:Ret driver unload %p (obj=%p)\n", GetCurrentThreadId(),
185 driver_obj->DriverUnload, driver_obj );
187 FreeLibrary( module );
190 /* load the .sys module for a device driver */
191 static HMODULE load_driver(void)
193 static const WCHAR driversW[] = {'\\','d','r','i','v','e','r','s','\\',0};
194 static const WCHAR systemrootW[] = {'\\','S','y','s','t','e','m','R','o','o','t','\\',0};
195 static const WCHAR postfixW[] = {'.','s','y','s',0};
196 static const WCHAR ntprefixW[] = {'\\','?','?','\\',0};
197 static const WCHAR ImagePathW[] = {'I','m','a','g','e','P','a','t','h',0};
198 static const WCHAR servicesW[] = {'\\','R','e','g','i','s','t','r','y',
199 '\\','M','a','c','h','i','n','e',
200 '\\','S','y','s','t','e','m',
201 '\\','C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t',
202 '\\','S','e','r','v','i','c','e','s','\\',0};
204 UNICODE_STRING keypath;
205 HKEY driver_hkey;
206 HMODULE module;
207 LPWSTR path = NULL, str;
208 DWORD type, size;
210 str = HeapAlloc( GetProcessHeap(), 0, sizeof(servicesW) + strlenW(driver_name)*sizeof(WCHAR) );
211 lstrcpyW( str, servicesW );
212 lstrcatW( str, driver_name );
214 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, str + 18 /* skip \registry\machine */, &driver_hkey ))
216 WINE_ERR( "cannot open key %s, err=%u\n", wine_dbgstr_w(str), GetLastError() );
217 HeapFree( GetProcessHeap(), 0, str);
218 return NULL;
220 RtlInitUnicodeString( &keypath, str );
222 /* read the executable path from memory */
223 size = 0;
224 if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, NULL, &size ))
226 str = HeapAlloc( GetProcessHeap(), 0, size );
227 if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, (LPBYTE)str, &size ))
229 size = ExpandEnvironmentStringsW(str,NULL,0);
230 path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
231 ExpandEnvironmentStringsW(str,path,size);
233 HeapFree( GetProcessHeap(), 0, str );
234 if (!path)
236 RtlFreeUnicodeString( &keypath );
237 RegCloseKey( driver_hkey );
238 return NULL;
241 if (!strncmpiW( path, systemrootW, 12 ))
243 WCHAR buffer[MAX_PATH];
245 GetWindowsDirectoryW(buffer, MAX_PATH);
247 str = HeapAlloc(GetProcessHeap(), 0, (size -11 + strlenW(buffer))
248 * sizeof(WCHAR));
249 lstrcpyW(str, buffer);
250 lstrcatW(str, path + 11);
251 HeapFree( GetProcessHeap(), 0, path );
252 path = str;
254 else if (!strncmpW( path, ntprefixW, 4 ))
255 str = path + 4;
256 else
257 str = path;
259 else
261 /* default is to use the driver name + ".sys" */
262 WCHAR buffer[MAX_PATH];
263 GetSystemDirectoryW(buffer, MAX_PATH);
264 path = HeapAlloc(GetProcessHeap(),0,
265 (strlenW(buffer) + strlenW(driversW) + strlenW(driver_name) + strlenW(postfixW) + 1)
266 *sizeof(WCHAR));
267 lstrcpyW(path, buffer);
268 lstrcatW(path, driversW);
269 lstrcatW(path, driver_name);
270 lstrcatW(path, postfixW);
271 str = path;
273 RegCloseKey( driver_hkey );
275 WINE_TRACE( "loading driver %s\n", wine_dbgstr_w(str) );
277 module = load_driver_module( str );
278 HeapFree( GetProcessHeap(), 0, path );
279 if (!module)
281 RtlFreeUnicodeString( &keypath );
282 return NULL;
285 init_driver( module, &keypath );
286 return module;
289 static DWORD WINAPI service_handler( DWORD ctrl, DWORD event_type, LPVOID event_data, LPVOID context )
291 SERVICE_STATUS status;
293 status.dwServiceType = SERVICE_WIN32;
294 status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
295 status.dwWin32ExitCode = 0;
296 status.dwServiceSpecificExitCode = 0;
297 status.dwCheckPoint = 0;
298 status.dwWaitHint = 0;
300 switch(ctrl)
302 case SERVICE_CONTROL_STOP:
303 case SERVICE_CONTROL_SHUTDOWN:
304 WINE_TRACE( "shutting down %s\n", wine_dbgstr_w(driver_name) );
305 status.dwCurrentState = SERVICE_STOP_PENDING;
306 status.dwControlsAccepted = 0;
307 SetServiceStatus( service_handle, &status );
308 SetEvent( stop_event );
309 return NO_ERROR;
310 default:
311 WINE_FIXME( "got service ctrl %x for %s\n", ctrl, wine_dbgstr_w(driver_name) );
312 status.dwCurrentState = SERVICE_RUNNING;
313 SetServiceStatus( service_handle, &status );
314 return NO_ERROR;
318 static void WINAPI ServiceMain( DWORD argc, LPWSTR *argv )
320 SERVICE_STATUS status;
321 HMODULE driver_module;
323 WINE_TRACE( "starting service %s\n", wine_dbgstr_w(driver_name) );
325 stop_event = CreateEventW( NULL, TRUE, FALSE, NULL );
327 service_handle = RegisterServiceCtrlHandlerExW( driver_name, service_handler, NULL );
328 if (!service_handle)
329 return;
331 status.dwServiceType = SERVICE_WIN32;
332 status.dwCurrentState = SERVICE_START_PENDING;
333 status.dwControlsAccepted = 0;
334 status.dwWin32ExitCode = 0;
335 status.dwServiceSpecificExitCode = 0;
336 status.dwCheckPoint = 0;
337 status.dwWaitHint = 10000;
338 SetServiceStatus( service_handle, &status );
340 driver_module = load_driver();
341 if (driver_module)
343 status.dwCurrentState = SERVICE_RUNNING;
344 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
345 SetServiceStatus( service_handle, &status );
347 wine_ntoskrnl_main_loop( stop_event );
348 unload_driver( driver_module, &driver_obj );
350 else WINE_ERR( "driver %s failed to load\n", wine_dbgstr_w(driver_name) );
352 status.dwCurrentState = SERVICE_STOPPED;
353 status.dwControlsAccepted = 0;
354 SetServiceStatus( service_handle, &status );
355 WINE_TRACE( "service %s stopped\n", wine_dbgstr_w(driver_name) );
358 int wmain( int argc, WCHAR *argv[] )
360 SERVICE_TABLE_ENTRYW service_table[2];
362 if (!(driver_name = argv[1]))
364 WINE_ERR( "missing device name, winedevice isn't supposed to be run manually\n" );
365 return 1;
368 service_table[0].lpServiceName = argv[1];
369 service_table[0].lpServiceProc = ServiceMain;
370 service_table[1].lpServiceName = NULL;
371 service_table[1].lpServiceProc = NULL;
373 StartServiceCtrlDispatcherW( service_table );
374 return 0;