view: Add message contexts for accelerators that can be translated.
[wine] / programs / winedevice / device.c
1 /*
2  * Service process to load a kernel driver
3  *
4  * Copyright 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 #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"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(winedevice);
39 WINE_DECLARE_DEBUG_CHANNEL(relay);
40
41 extern NTSTATUS CDECL wine_ntoskrnl_main_loop( HANDLE stop_event );
42
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;
49
50 /* find the LDR_MODULE corresponding to the driver module */
51 static LDR_MODULE *find_ldr_module( HMODULE module )
52 {
53     LIST_ENTRY *entry, *list = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
54
55     for (entry = list->Flink; entry != list; entry = entry->Flink)
56     {
57         LDR_MODULE *ldr = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
58         if (ldr->BaseAddress == module) return ldr;
59         if (ldr->BaseAddress > (void *)module) break;
60     }
61     return NULL;
62 }
63
64 /* load the driver module file */
65 static HMODULE load_driver_module( const WCHAR *name )
66 {
67     IMAGE_NT_HEADERS *nt;
68     const IMAGE_IMPORT_DESCRIPTOR *imports;
69     size_t page_size = getpagesize();
70     int i;
71     INT_PTR delta;
72     ULONG size;
73     HMODULE module = LoadLibraryW( name );
74
75     if (!module) return NULL;
76     nt = RtlImageNtHeader( module );
77
78     if (!(delta = (char *)module - (char *)nt->OptionalHeader.ImageBase)) return module;
79
80     /* the loader does not apply relocations to non page-aligned binaries or executables,
81      * we have to do it ourselves */
82
83     if (nt->OptionalHeader.SectionAlignment < page_size ||
84         !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
85     {
86         DWORD old;
87         IMAGE_BASE_RELOCATION *rel, *end;
88
89         if ((rel = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_BASERELOC, &size )))
90         {
91             WINE_TRACE( "%s: relocating from %p to %p\n",
92                         wine_dbgstr_w(name), (char *)module - delta, module );
93             end = (IMAGE_BASE_RELOCATION *)((char *)rel + size);
94             while (rel < end && rel->SizeOfBlock)
95             {
96                 void *page = (char *)module + rel->VirtualAddress;
97                 VirtualProtect( page, page_size, PAGE_EXECUTE_READWRITE, &old );
98                 rel = LdrProcessRelocationBlock( page, (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
99                                                  (USHORT *)(rel + 1), delta );
100                 if (old != PAGE_EXECUTE_READWRITE) VirtualProtect( page, page_size, old, NULL );
101                 if (!rel) goto error;
102             }
103             /* make sure we don't try again */
104             size = FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + nt->FileHeader.SizeOfOptionalHeader;
105             VirtualProtect( nt, size, PAGE_READWRITE, &old );
106             nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = 0;
107             VirtualProtect( nt, size, old, NULL );
108         }
109     }
110
111     /* make sure imports are relocated too */
112
113     if ((imports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
114     {
115         for (i = 0; imports[i].Name && imports[i].FirstThunk; i++)
116         {
117             char *name = (char *)module + imports[i].Name;
118             WCHAR buffer[32], *p = buffer;
119
120             while (p < buffer + 32) if (!(*p++ = *name++)) break;
121             if (p <= buffer + 32) FreeLibrary( load_driver_module( buffer ) );
122         }
123     }
124
125     return module;
126
127 error:
128     FreeLibrary( module );
129     return NULL;
130 }
131
132 /* call the driver init entry point */
133 static NTSTATUS init_driver( HMODULE module, UNICODE_STRING *keyname )
134 {
135     unsigned int i;
136     NTSTATUS status;
137     const IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
138
139     if (!nt->OptionalHeader.AddressOfEntryPoint) return STATUS_SUCCESS;
140
141     driver_obj.Size            = sizeof(driver_obj);
142     driver_obj.DriverSection   = find_ldr_module( module );
143     driver_obj.DriverInit      = (PDRIVER_INITIALIZE)((char *)module + nt->OptionalHeader.AddressOfEntryPoint);
144     driver_obj.DriverExtension = &driver_extension;
145
146     driver_extension.DriverObject   = &driver_obj;
147     driver_extension.ServiceKeyName = *keyname;
148
149     if (WINE_TRACE_ON(relay))
150         WINE_DPRINTF( "%04x:Call driver init %p (obj=%p,str=%s)\n", GetCurrentThreadId(),
151                       driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer) );
152
153     status = driver_obj.DriverInit( &driver_obj, keyname );
154
155     if (WINE_TRACE_ON(relay))
156         WINE_DPRINTF( "%04x:Ret  driver init %p (obj=%p,str=%s) retval=%08x\n", GetCurrentThreadId(),
157                       driver_obj.DriverInit, &driver_obj, wine_dbgstr_w(keyname->Buffer), status );
158
159     WINE_TRACE( "init done for %s obj %p\n", wine_dbgstr_w(driver_name), &driver_obj );
160     WINE_TRACE( "- DriverInit = %p\n", driver_obj.DriverInit );
161     WINE_TRACE( "- DriverStartIo = %p\n", driver_obj.DriverStartIo );
162     WINE_TRACE( "- DriverUnload = %p\n", driver_obj.DriverUnload );
163     for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++)
164         WINE_TRACE( "- MajorFunction[%d] = %p\n", i, driver_obj.MajorFunction[i] );
165
166     return status;
167 }
168
169 /* load the .sys module for a device driver */
170 static BOOL load_driver(void)
171 {
172     static const WCHAR driversW[] = {'\\','d','r','i','v','e','r','s','\\',0};
173     static const WCHAR systemrootW[] = {'\\','S','y','s','t','e','m','R','o','o','t','\\',0};
174     static const WCHAR postfixW[] = {'.','s','y','s',0};
175     static const WCHAR ntprefixW[] = {'\\','?','?','\\',0};
176     static const WCHAR ImagePathW[] = {'I','m','a','g','e','P','a','t','h',0};
177     static const WCHAR servicesW[] = {'\\','R','e','g','i','s','t','r','y',
178                                       '\\','M','a','c','h','i','n','e',
179                                       '\\','S','y','s','t','e','m',
180                                       '\\','C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t',
181                                       '\\','S','e','r','v','i','c','e','s','\\',0};
182
183     UNICODE_STRING keypath;
184     HMODULE module;
185     LPWSTR path = NULL, str;
186     DWORD type, size;
187
188     str = HeapAlloc( GetProcessHeap(), 0, sizeof(servicesW) + strlenW(driver_name)*sizeof(WCHAR) );
189     lstrcpyW( str, servicesW );
190     lstrcatW( str, driver_name );
191
192     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, str + 18 /* skip \registry\machine */, &driver_hkey ))
193     {
194         WINE_ERR( "cannot open key %s, err=%u\n", wine_dbgstr_w(str), GetLastError() );
195         HeapFree( GetProcessHeap(), 0, str);
196         return FALSE;
197     }
198     RtlInitUnicodeString( &keypath, str );
199
200     /* read the executable path from memory */
201     size = 0;
202     if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, NULL, &size ))
203     {
204         str = HeapAlloc( GetProcessHeap(), 0, size );
205         if (!RegQueryValueExW( driver_hkey, ImagePathW, NULL, &type, (LPBYTE)str, &size ))
206         {
207             size = ExpandEnvironmentStringsW(str,NULL,0);
208             path = HeapAlloc(GetProcessHeap(),0,size*sizeof(WCHAR));
209             ExpandEnvironmentStringsW(str,path,size);
210         }
211         HeapFree( GetProcessHeap(), 0, str );
212         if (!path) return FALSE;
213
214         if (!strncmpiW( path, systemrootW, 12 ))
215         {
216             WCHAR buffer[MAX_PATH];
217
218             GetWindowsDirectoryW(buffer, MAX_PATH);
219
220             str = HeapAlloc(GetProcessHeap(), 0, (size -11 + strlenW(buffer))
221                                                         * sizeof(WCHAR));
222             lstrcpyW(str, buffer);
223             lstrcatW(str, path + 11);
224             HeapFree( GetProcessHeap(), 0, path );
225             path = str;
226         }
227         else if (!strncmpW( path, ntprefixW, 4 ))
228             str = path + 4;
229         else
230             str = path;
231     }
232     else
233     {
234         /* default is to use the driver name + ".sys" */
235         WCHAR buffer[MAX_PATH];
236         GetSystemDirectoryW(buffer, MAX_PATH);
237         path = HeapAlloc(GetProcessHeap(),0,
238           (strlenW(buffer) + strlenW(driversW) + strlenW(driver_name) + strlenW(postfixW) + 1)
239           *sizeof(WCHAR));
240         lstrcpyW(path, buffer);
241         lstrcatW(path, driversW);
242         lstrcatW(path, driver_name);
243         lstrcatW(path, postfixW);
244         str = path;
245     }
246
247     WINE_TRACE( "loading driver %s\n", wine_dbgstr_w(str) );
248
249     module = load_driver_module( str );
250     HeapFree( GetProcessHeap(), 0, path );
251     if (!module) return FALSE;
252
253     init_driver( module, &keypath );
254     return TRUE;
255 }
256
257 static DWORD WINAPI service_handler( DWORD ctrl, DWORD event_type, LPVOID event_data, LPVOID context )
258 {
259     SERVICE_STATUS status;
260
261     status.dwServiceType             = SERVICE_WIN32;
262     status.dwControlsAccepted        = SERVICE_ACCEPT_STOP;
263     status.dwWin32ExitCode           = 0;
264     status.dwServiceSpecificExitCode = 0;
265     status.dwCheckPoint              = 0;
266     status.dwWaitHint                = 0;
267
268     switch(ctrl)
269     {
270     case SERVICE_CONTROL_STOP:
271     case SERVICE_CONTROL_SHUTDOWN:
272         WINE_TRACE( "shutting down %s\n", wine_dbgstr_w(driver_name) );
273         status.dwCurrentState     = SERVICE_STOP_PENDING;
274         status.dwControlsAccepted = 0;
275         SetServiceStatus( service_handle, &status );
276         SetEvent( stop_event );
277         return NO_ERROR;
278     default:
279         WINE_FIXME( "got service ctrl %x for %s\n", ctrl, wine_dbgstr_w(driver_name) );
280         status.dwCurrentState = SERVICE_RUNNING;
281         SetServiceStatus( service_handle, &status );
282         return NO_ERROR;
283     }
284 }
285
286 static void WINAPI ServiceMain( DWORD argc, LPWSTR *argv )
287 {
288     SERVICE_STATUS status;
289
290     WINE_TRACE( "starting service %s\n", wine_dbgstr_w(driver_name) );
291
292     stop_event = CreateEventW( NULL, TRUE, FALSE, NULL );
293
294     service_handle = RegisterServiceCtrlHandlerExW( driver_name, service_handler, NULL );
295     if (!service_handle)
296         return;
297
298     status.dwServiceType             = SERVICE_WIN32;
299     status.dwCurrentState            = SERVICE_START_PENDING;
300     status.dwControlsAccepted        = 0;
301     status.dwWin32ExitCode           = 0;
302     status.dwServiceSpecificExitCode = 0;
303     status.dwCheckPoint              = 0;
304     status.dwWaitHint                = 10000;
305     SetServiceStatus( service_handle, &status );
306
307     if (load_driver())
308     {
309         status.dwCurrentState     = SERVICE_RUNNING;
310         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
311         SetServiceStatus( service_handle, &status );
312
313         wine_ntoskrnl_main_loop( stop_event );
314     }
315     else WINE_ERR( "driver %s failed to load\n", wine_dbgstr_w(driver_name) );
316
317     status.dwCurrentState     = SERVICE_STOPPED;
318     status.dwControlsAccepted = 0;
319     SetServiceStatus( service_handle, &status );
320     WINE_TRACE( "service %s stopped\n", wine_dbgstr_w(driver_name) );
321 }
322
323 int wmain( int argc, WCHAR *argv[] )
324 {
325     SERVICE_TABLE_ENTRYW service_table[2];
326
327     if (!(driver_name = argv[1]))
328     {
329         WINE_ERR( "missing device name, winedevice isn't supposed to be run manually\n" );
330         return 1;
331     }
332
333     service_table[0].lpServiceName = argv[1];
334     service_table[0].lpServiceProc = ServiceMain;
335     service_table[1].lpServiceName = NULL;
336     service_table[1].lpServiceProc = NULL;
337
338     StartServiceCtrlDispatcherW( service_table );
339     return 0;
340 }