winedevice: Fix up protections before writing to the NT header.
[wine/multimedia.git] / programs / winedevice / device.c
blobe0cd07bf39075792aa4eb5454b594a1676b67a3b
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 HKEY driver_hkey;
46 static HANDLE stop_event;
47 static DRIVER_OBJECT driver_obj;
48 static DRIVER_EXTENSION driver_extension;
50 /* find the LDR_MODULE corresponding to the driver module */
51 static LDR_MODULE *find_ldr_module( HMODULE module )
53 LIST_ENTRY *entry, *list = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
55 for (entry = list->Flink; entry != list; entry = entry->Flink)
57 LDR_MODULE *ldr = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
58 if (ldr->BaseAddress == module) return ldr;
59 if (ldr->BaseAddress > (void *)module) break;
61 return NULL;
64 /* load the driver module file */
65 static HMODULE load_driver_module( const WCHAR *name )
67 IMAGE_NT_HEADERS *nt;
68 const IMAGE_IMPORT_DESCRIPTOR *imports;
69 size_t page_size = getpagesize();
70 int i, delta;
71 ULONG size;
72 HMODULE module = LoadLibraryW( name );
74 if (!module) return NULL;
75 nt = RtlImageNtHeader( module );
77 if (!(delta = (char *)module - (char *)nt->OptionalHeader.ImageBase)) return module;
79 /* the loader does not apply relocations to non page-aligned binaries or executables,
80 * we have to do it ourselves */
82 if (nt->OptionalHeader.SectionAlignment < page_size ||
83 !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
85 DWORD old;
86 IMAGE_BASE_RELOCATION *rel, *end;
88 if ((rel = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_BASERELOC, &size )))
90 WINE_TRACE( "%s: relocating from %p to %p\n",
91 wine_dbgstr_w(name), (char *)module - delta, module );
92 end = (IMAGE_BASE_RELOCATION *)((char *)rel + size);
93 while (rel < end && rel->SizeOfBlock)
95 void *page = (char *)module + rel->VirtualAddress;
96 VirtualProtect( page, page_size, PAGE_EXECUTE_READWRITE, &old );
97 rel = LdrProcessRelocationBlock( page, (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
98 (USHORT *)(rel + 1), delta );
99 if (old != PAGE_EXECUTE_READWRITE) VirtualProtect( page, page_size, old, NULL );
100 if (!rel) goto error;
102 /* make sure we don't try again */
103 size = FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + nt->FileHeader.SizeOfOptionalHeader;
104 VirtualProtect( nt, size, PAGE_READWRITE, &old );
105 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
106 VirtualProtect( nt, size, old, NULL );
110 /* make sure imports are relocated too */
112 if ((imports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
114 for (i = 0; imports[i].Name && imports[i].FirstThunk; i++)
116 char *name = (char *)module + imports[i].Name;
117 WCHAR buffer[32], *p = buffer;
119 while (p < buffer + 32) if (!(*p++ = *name++)) break;
120 if (p <= buffer + 32) FreeLibrary( load_driver_module( buffer ) );
124 return module;
126 error:
127 FreeLibrary( module );
128 return NULL;
131 /* call the driver init entry point */
132 static NTSTATUS init_driver( HMODULE module, UNICODE_STRING *keyname )
134 unsigned int i;
135 NTSTATUS status;
136 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
138 if (!nt->OptionalHeader.AddressOfEntryPoint) return STATUS_SUCCESS;
140 driver_obj.Size = sizeof(driver_obj);
141 driver_obj.DriverSection = find_ldr_module( module );
142 driver_obj.DriverInit = (PDRIVER_INITIALIZE)((char *)module + nt->OptionalHeader.AddressOfEntryPoint);
143 driver_obj.DriverExtension = &driver_extension;
145 driver_extension.DriverObject = &driver_obj;
146 driver_extension.ServiceKeyName = *keyname;
148 if (WINE_TRACE_ON(relay))
149 WINE_DPRINTF( "%04x:Call driver init %p (obj=%p,str=%s)\n", GetCurrentThreadId(),
150 driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer) );
152 status = driver_obj.DriverInit( &driver_obj, keyname );
154 if (WINE_TRACE_ON(relay))
155 WINE_DPRINTF( "%04x:Ret driver init %p (obj=%p,str=%s) retval=%08x\n", GetCurrentThreadId(),
156 driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer), status );
158 WINE_TRACE( "init done for %s obj %p\n", wine_dbgstr_w(driver_name), &driver_obj );
159 WINE_TRACE( "- DriverInit = %p\n", driver_obj.DriverInit );
160 WINE_TRACE( "- DriverStartIo = %p\n", driver_obj.DriverStartIo );
161 WINE_TRACE( "- DriverUnload = %p\n", driver_obj.DriverUnload );
162 for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
163 WINE_TRACE( "- MajorFunction[%d] = %p\n", i, driver_obj.MajorFunction[i] );
165 return status;
168 /* load the .sys module for a device driver */
169 static BOOL load_driver(void)
171 static const WCHAR driversW[] = {'\\','d','r','i','v','e','r','s','\\',0};
172 static const WCHAR postfixW[] = {'.','s','y','s',0};
173 static const WCHAR ntprefixW[] = {'\\','?','?','\\',0};
174 static const WCHAR ImagePathW[] = {'I','m','a','g','e','P','a','t','h',0};
175 static const WCHAR servicesW[] = {'\\','R','e','g','i','s','t','r','y',
176 '\\','M','a','c','h','i','n','e',
177 '\\','S','y','s','t','e','m',
178 '\\','C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t',
179 '\\','S','e','r','v','i','c','e','s','\\',0};
181 UNICODE_STRING keypath;
182 HMODULE module;
183 LPWSTR path = NULL, str;
184 DWORD type, size;
186 str = HeapAlloc( GetProcessHeap(), 0, sizeof(servicesW) + strlenW(driver_name)*sizeof(WCHAR) );
187 lstrcpyW( str, servicesW );
188 lstrcatW( str, driver_name );
190 if (RegOpenKeyW( HKEY_LOCAL_MACHINE, str + 18 /* skip \registry\machine */, &driver_hkey ))
192 WINE_ERR( "cannot open key %s, err=%u\n", wine_dbgstr_w(str), GetLastError() );
193 HeapFree( GetProcessHeap(), 0, str);
194 return FALSE;
196 RtlInitUnicodeString( &keypath, str );
198 /* read the executable path from memory */
199 size = 0;
200 if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, NULL, &size ))
202 str = HeapAlloc( GetProcessHeap(), 0, size );
203 if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, (LPBYTE)str, &size ))
205 size = ExpandEnvironmentStringsW(str,NULL,0);
206 path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
207 ExpandEnvironmentStringsW(str,path,size);
209 HeapFree( GetProcessHeap(), 0, str );
210 if (!path) return FALSE;
212 else
214 /* default is to use the driver name + ".sys" */
215 WCHAR buffer[MAX_PATH];
216 GetSystemDirectoryW(buffer, MAX_PATH);
217 path = HeapAlloc(GetProcessHeap(),0,
218 (strlenW(buffer) + strlenW(driversW) + strlenW(driver_name) + strlenW(postfixW) + 1)
219 *sizeof(WCHAR));
220 lstrcpyW(path, buffer);
221 lstrcatW(path, driversW);
222 lstrcatW(path, driver_name);
223 lstrcatW(path, postfixW);
226 /* GameGuard uses an NT-style path name */
227 str = path;
228 if (!strncmpW( path, ntprefixW, 4 )) str += 4;
230 WINE_TRACE( "loading driver %s\n", wine_dbgstr_w(str) );
232 module = load_driver_module( str );
233 HeapFree( GetProcessHeap(), 0, path );
234 if (!module) return FALSE;
236 init_driver( module, &keypath );
237 return TRUE;
240 static DWORD WINAPI service_handler( DWORD ctrl, DWORD event_type, LPVOID event_data, LPVOID context )
242 SERVICE_STATUS status;
244 status.dwServiceType = SERVICE_WIN32;
245 status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
246 status.dwWin32ExitCode = 0;
247 status.dwServiceSpecificExitCode = 0;
248 status.dwCheckPoint = 0;
249 status.dwWaitHint = 0;
251 switch(ctrl)
253 case SERVICE_CONTROL_STOP:
254 case SERVICE_CONTROL_SHUTDOWN:
255 WINE_TRACE( "shutting down %s\n", wine_dbgstr_w(driver_name) );
256 status.dwCurrentState = SERVICE_STOP_PENDING;
257 status.dwControlsAccepted = 0;
258 SetServiceStatus( service_handle, &status );
259 SetEvent( stop_event );
260 return NO_ERROR;
261 default:
262 WINE_FIXME( "got service ctrl %x for %s\n", ctrl, wine_dbgstr_w(driver_name) );
263 status.dwCurrentState = SERVICE_RUNNING;
264 SetServiceStatus( service_handle, &status );
265 return NO_ERROR;
269 static void WINAPI ServiceMain( DWORD argc, LPWSTR *argv )
271 SERVICE_STATUS status;
273 WINE_TRACE( "starting service %s\n", wine_dbgstr_w(driver_name) );
275 stop_event = CreateEventW( NULL, TRUE, FALSE, NULL );
277 service_handle = RegisterServiceCtrlHandlerExW( driver_name, service_handler, NULL );
278 if (!service_handle)
279 return;
281 status.dwServiceType = SERVICE_WIN32;
282 status.dwCurrentState = SERVICE_START_PENDING;
283 status.dwControlsAccepted = 0;
284 status.dwWin32ExitCode = 0;
285 status.dwServiceSpecificExitCode = 0;
286 status.dwCheckPoint = 0;
287 status.dwWaitHint = 10000;
288 SetServiceStatus( service_handle, &status );
290 if (load_driver())
292 status.dwCurrentState = SERVICE_RUNNING;
293 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
294 SetServiceStatus( service_handle, &status );
296 wine_ntoskrnl_main_loop( stop_event );
298 else WINE_ERR( "driver %s failed to load\n", wine_dbgstr_w(driver_name) );
300 status.dwCurrentState = SERVICE_STOPPED;
301 status.dwControlsAccepted = 0;
302 SetServiceStatus( service_handle, &status );
303 WINE_TRACE( "service %s stopped\n", wine_dbgstr_w(driver_name) );
306 int wmain( int argc, WCHAR *argv[] )
308 SERVICE_TABLE_ENTRYW service_table[2];
310 if (!(driver_name = argv[1]))
312 WINE_ERR( "missing device name, winedevice isn't supposed to be run manually\n" );
313 return 1;
316 service_table[0].lpServiceName = argv[1];
317 service_table[0].lpServiceProc = ServiceMain;
318 service_table[1].lpServiceName = NULL;
319 service_table[1].lpServiceProc = NULL;
321 StartServiceCtrlDispatcherW( service_table );
322 return 0;