+captive_Module_GetExportAddress() to access W32 modules symbols
[captive.git] / src / libcaptive / ldr / loader.c
1 /* $Id$
2  * reactos ldr/ (loader) emulation of libcaptive
3  * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include "captive/ldr.h"        /* self */
23 #include "captive/ldr_exports.h"        /* self */
24 #include "reactos/internal/ldr.h"       /* self */
25 #include "captive/unicode.h"
26 #include "captive/rtl-file.h"
27 #include <glib/gtypes.h>
28 #include <glib/gmessages.h>
29 #include <glib/gmem.h>
30 #include "reactos/napi/types.h"
31 #include "reactos/internal/kd.h"        /* for KDB_LOADDRIVER_HOOK */
32 #include <fcntl.h>
33 #include <sys/mman.h>   /* for PROT_READ, MAP_SHARED */
34 #include "captive/macros.h"
35 #include <stdarg.h>
36 #include "reactos/ntos/rtl.h"   /* for InsertTailList() */
37 #include "reactos/internal/debug.h"     /* for assert() */
38 #include <glib/gutils.h>        /* for g_path_get_basename() */
39 #include <gmodule.h>
40
41
42 /* map: ExportAddress -> (struct captive_ModuleList_patchpoint *) */
43 static GHashTable *captive_ModuleList_patchpoint_hash;
44
45 /* initialize 'captive_ModuleList_patchpoint_hash' */
46 static void captive_ModuleList_patchpoint_hash_init(void)
47 {
48         if (captive_ModuleList_patchpoint_hash)
49                 return;
50         captive_ModuleList_patchpoint_hash=g_hash_table_new(g_direct_hash,g_direct_equal);
51 }
52
53
54 /* map: ExportAddress -> (CHAR *)funcname */
55 static GHashTable *captive_ModuleList_function_disable_hash;
56
57 /* initialize 'captive_ModuleList_function_disable_hash' */
58 static void captive_ModuleList_function_disable_hash_init(void)
59 {
60         if (captive_ModuleList_function_disable_hash)
61                 return;
62         captive_ModuleList_function_disable_hash=g_hash_table_new(g_direct_hash,g_direct_equal);
63 }
64
65
66 /* reactos/ntoskrnl/ldr/loader.c file-scope global declaration: */
67 NTSTATUS LdrProcessModule(PVOID ModuleLoadBase,PUNICODE_STRING ModuleName,PMODULE_OBJECT *ModuleObject);
68 PVOID LdrGetExportAddress(PMODULE_OBJECT ModuleObject,char *Name,unsigned short Hint);
69
70
71 /* 'ntoskrnl/ldr/loader.c' file-scoped declaration: */
72 VOID LdrpBuildModuleBaseName(PUNICODE_STRING BaseName,PUNICODE_STRING FullName);
73
74
75 static MODULE_OBJECT *captive_LdrLoadModule_gmodule(const gchar *Filename_utf8,const gchar *Filename_bslash_utf8)
76 {
77 MODULE_OBJECT *r;
78 GModule *gmodule;
79 MODULE_TEXT_SECTION *ModuleTextSection;
80 gboolean errbool;
81
82         g_return_val_if_fail(Filename_utf8!=NULL,NULL);
83         g_return_val_if_fail(Filename_bslash_utf8!=NULL,NULL);
84         g_return_val_if_fail(TRUE==g_module_supported(),NULL);
85
86         gmodule=g_module_open(Filename_utf8,
87                         0);     /* Flags; !LAZY */
88         if (!gmodule)
89                 g_message(g_module_error());
90         g_assert(gmodule!=NULL);
91
92         captive_new0(r);
93
94         errbool=g_module_symbol(gmodule,"DriverEntry",&r->EntryPoint);
95         g_assert(errbool==TRUE);
96
97         r->Base=(PVOID)gmodule;
98         r->Flags=MODULE_FLAG_COFF;      /* some weird value - reactos uses MODULE_FLAG_PE */
99   
100         RtlCreateUnicodeString(&r->FullName,captive_utf8_to_UnicodeString_alloca(Filename_bslash_utf8)->Buffer);
101   LdrpBuildModuleBaseName(&r->BaseName,&r->FullName);
102
103         /* r->Length=0; */
104   
105   /* Insert module */
106         InsertTailList(&ModuleListHead,&r->ListEntry);
107
108         captive_new0(ModuleTextSection);
109         /* ModuleTextSection->Base=0; */
110         /* ModuleTextSection->Length=0; */
111         ModuleTextSection->Name=g_memdup(r->BaseName.Buffer,
112                         (captive_ucs2_strlen(r->BaseName.Buffer)+1)*sizeof(captive_ucs2));
113         /* ModuleTextSection->OptionalHeader=NULL; */
114         InsertTailList(&ModuleTextListHead,&ModuleTextSection->ListEntry);
115         r->TextSection=ModuleTextSection;
116
117         return r;
118 }
119
120
121 /**
122  * LdrLoadModule:
123  * @Filename: Filename of module to load based on host OS disk.
124  * Loading of already loaded module is forbidden.
125  * @ModuleObject: Returns initialized module object.
126  *
127  * Load and initialize module to reactos using host OS functions.
128  *
129  * Returns: STATUS_SUCCESS if the module was loaded successfuly during the call.
130  */
131 NTSTATUS LdrLoadModule(PUNICODE_STRING Filename,PMODULE_OBJECT *ModuleObjectp)
132 {
133 PVOID ModuleLoadBase;
134 PMODULE_OBJECT Module;
135 NTSTATUS err;
136 gchar *Filename_utf8=(/* de-const */ gchar *)captive_UnicodeString_to_utf8_alloca(Filename);
137 gchar *Filename_bslash_utf8,*s;
138 UNICODE_STRING *Filename_bslash;
139
140         *ModuleObjectp=NULL;
141
142         /* Open the Module */
143         ModuleLoadBase=captive_rtl_file_mmap(
144                         NULL,   /* lenp */
145                         Filename_utf8,  /* path */
146                         O_RDONLY,       /* open_flags */
147                         PROT_READ,      /* mmap_prot */
148                         MAP_SHARED);    /* mmap_flags */
149         /* FIXME: convert errno instead of STATUS_INSUFFICIENT_RESOURCES */
150         g_return_val_if_fail(ModuleLoadBase!=NULL,STATUS_INSUFFICIENT_RESOURCES);
151
152         /* Filename=~s#/#\\#g -> Filename_bslash to satisfy basename-derivations by reactos. */
153         Filename_bslash_utf8=g_strdup(Filename_utf8);
154         for (s=Filename_bslash_utf8;(s=strchr(s,'/'));s++)
155                 *s='\\';
156         Filename_bslash=captive_utf8_to_UnicodeString_alloca(Filename_bslash_utf8);
157
158         if ((('M'<<8U)|('Z'<<0U))==GUINT16_FROM_BE(*(const guint16 *)ModuleLoadBase)) {
159                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: Loading module format: %s",G_STRLOC,"MZ/PE-32");
160                 /* examine/relocate the module */
161                 err=LdrProcessModule(ModuleLoadBase,Filename_bslash,&Module);
162                 if (!NT_SUCCESS(err)) {
163                         g_error("LdrLoadModule(): LdrProcessModule()=0x%08lX",(gulong)err);
164                         goto err_captive_rtl_file_munmap;
165                         }
166                 }
167         else {
168                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: Loading module format: %s",G_STRLOC,"native .so");
169                 Module=captive_LdrLoadModule_gmodule(Filename_utf8,Filename_bslash_utf8);
170                 g_assert(Module!=NULL);
171                 }
172
173         /* we were successful */
174         captive_rtl_file_munmap(ModuleLoadBase);
175         *ModuleObjectp=Module;
176
177         /* Hook for KDB on loading a driver. */
178         KDB_LOADDRIVER_HOOK(Filename_bslash,Module);
179
180         return STATUS_SUCCESS;
181
182         /* Error recoveries */
183 err_captive_rtl_file_munmap:
184         captive_rtl_file_munmap(ModuleLoadBase);
185
186         g_return_val_if_reached(err);
187 }
188
189
190 /**
191  * captive_LdrpLoadAndCallImage:
192  * @ModuleObjectp: Returns PMODULE_OBJECT successfuly loaded.
193  * @ModuleName: Filename of module to load based on host OS disk.
194  * Loading of already loaded module is forbidden despite original
195  * LdrpLoadAndCallImage().
196  * @DriverEntry_DriverObject: argument #DriverObject of #PDRIVER_INITIALIZE call.
197  * @DriverEntry_RegistryPath: argument #RegistryPath of #PDRIVER_INITIALIZE call.
198  *
199  * Corresponds to reactos LdrpLoadAndCallImage() but it also provides arguments
200  * to pass to #PDRIVER_INITIALIZE call of module driver initialization.
201  *
202  * Returns: STATUS_SUCCESS if the driver module was loaded and initialized
203  * successfuly during this call. Ignore returned @ModuleObjectp if function failed.
204  */
205 NTSTATUS captive_LdrpLoadAndCallImage(PMODULE_OBJECT *ModuleObjectp,PUNICODE_STRING ModuleName,
206                 PDRIVER_OBJECT DriverEntry_DriverObject,PUNICODE_STRING DriverEntry_RegistryPath)
207 {
208 PDRIVER_INITIALIZE DriverEntry;
209 PMODULE_OBJECT ModuleObject_tmp;
210 NTSTATUS err;
211
212         /* check for duplicity */
213         g_return_val_if_fail(LdrGetModuleObject(ModuleName)==NULL,STATUS_IMAGE_ALREADY_LOADED);
214
215         /* provide our temporary storage if the caller doesn't want to know ModuleObject address */
216         if (!ModuleObjectp)
217                 ModuleObjectp=&ModuleObject_tmp;
218
219         /* load the module */
220         err=LdrLoadModule(ModuleName,ModuleObjectp);
221         g_return_val_if_fail(NT_SUCCESS(err),err);
222
223         /* initialize the module */
224         DriverEntry=(PDRIVER_INITIALIZE)(*ModuleObjectp)->EntryPoint;
225         err=(*DriverEntry)(DriverEntry_DriverObject,DriverEntry_RegistryPath);
226         if (!NT_SUCCESS(err))
227                 goto err_LdrUnloadModule;
228
229         /* assumed STATUS_SUCCESS */
230         return err;
231
232 err_LdrUnloadModule:
233         /* errors ignored */
234         LdrUnloadModule(*ModuleObjectp);
235         *ModuleObjectp=NULL;
236 /* err: */
237         g_return_val_if_reached(err);
238 }
239
240
241 /**
242  * captive_ModuleList_add_builtin:
243  * @FullName_utf8: String to fill in #PMODULE_OBJECT->FullName.
244  * @...: (const gchar *sym_name,void *sym_val) symbol list terminated by %NULL.
245  *
246  * Adds simulated built-in module to #ModuleListHead module list.
247  * It can be used for the functionality of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement().
248  * libcaptive does not support Ordinals - we just pretend liner (%0-based)
249  * Ordinal numbers of the functions in given @... stdargs order.
250  *
251  * Returns: %TRUE if the module was successfuly added.
252  */
253 gboolean captive_ModuleList_add_builtin(const gchar *FullName_utf8,...)
254 {
255 MODULE_OBJECT *ModuleObject;
256 BOOLEAN errbool;
257 va_list ap;
258 const gchar *sym_name;
259 const void *sym_val;
260 gchar *basename_utf8;
261 IMAGE_DOS_HEADER *DosHeader;
262 IMAGE_NT_HEADERS *NTHeaders;
263 IMAGE_EXPORT_DIRECTORY *ExportDir;
264 guint symi,symN;        /* index,number of passed stdarg sym_name/sym_val pairs */
265 ptrdiff_t *NameList;    /* filled by sym_name; MODULEOBJECT_BASE_OFFSET_MINUS()ed */
266 WORD *OrdinalList;      /* linear list - libcaptive doesn't support Ordinals */
267 ptrdiff_t *FunctionList;        /* filled by sym_val; MODULEOBJECT_BASE_OFFSET_MINUS()ed */
268
269         g_return_val_if_fail(FullName_utf8!=NULL,FALSE);
270
271         captive_new0(ModuleObject);
272         /* A lot of offsets in the structures are relative to ModuleObject->Base */
273 #define MODULEOBJECT_BASE_OFFSET_MINUS(addr) ((ptrdiff_t)((char *)addr-(char *)ModuleObject->Base))
274
275         ModuleObject->Flags = MODULE_FLAG_PE;
276
277         /* fill ModuleObject->FullName
278          * ModuleObject->FullName should be probably "\\SYSTEM32\\..." style but
279          * we put there '/'-based UNIX filenames in libcaptive.
280          */
281         errbool=RtlCreateUnicodeString(&ModuleObject->FullName,captive_utf8_to_UnicodeString_alloca(FullName_utf8)->Buffer);
282         if (!errbool) {
283                 g_error("captive_ModuleList_add_builtin: RtlCreateUnicodeString()==FALSE");
284                 goto err_g_free_ModuleObject;
285                 }
286
287         /* fill ModuleObject->BaseName
288          * reactos/ntoskrnl/ldr/loader.c/LdrpBuildModuleBaseName() does this one
289          * but it is 'static' for that file and also it is stricly backslash based.
290          * ModuleObject->FullName should be probably "\\SYSTEM32\\..." style but
291          * we put there '/'-based UNIX filenames in libcaptive.
292          */
293         basename_utf8=g_path_get_basename(FullName_utf8);
294         errbool=RtlCreateUnicodeString(&ModuleObject->BaseName,captive_utf8_to_UnicodeString_alloca(basename_utf8)->Buffer);
295         g_free(basename_utf8);
296         if (!errbool) {
297                 g_error("captive_ModuleList_add_builtin: RtlCreateUnicodeString()==FALSE");
298                 goto err_g_free_ModuleObject;
299                 }
300
301         /* We must satisfy reactos/ntoskrnl/ldr/rtl.c/RtlImageDirectoryEntryToData(,,IMAGE_DIRECTORY_ENTRY_EXPORT)
302          * prepare module headers
303          */
304         captive_new0(DosHeader);
305         ModuleObject->Base=DosHeader;   /* link DosHeader to ModuleObject */
306         DosHeader->e_magic=IMAGE_DOS_MAGIC;
307         captive_new0(NTHeaders);
308         DosHeader->e_lfanew=MODULEOBJECT_BASE_OFFSET_MINUS(NTHeaders);  /* link NTHeaders to DosHeader */
309         NTHeaders->Signature=IMAGE_PE_MAGIC;
310         NTHeaders->OptionalHeader.NumberOfRvaAndSizes=IMAGE_DIRECTORY_ENTRY_EXPORT+1;
311         NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
312                         =sizeof(*ExportDir);    /* in bytes; just prevent LdrPEFixupForward() invocation */
313         captive_new0(ExportDir);
314         NTHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
315                         =MODULEOBJECT_BASE_OFFSET_MINUS(ExportDir);     /* link ExportDir to NTHeaders */
316         ExportDir->Base=0;      /* base Ordinal number; Ordinals are not supported by libcaptive */
317
318         /* count the number of symbols */
319         va_start(ap,FullName_utf8);
320         for (symN=0;captive_va_arg(sym_name,ap);symN++)
321                 captive_va_arg(sym_val,ap);
322         va_end(ap);
323         ExportDir->NumberOfNames=symN;
324         ExportDir->NumberOfFunctions=symN;
325
326         /* allocate and link the symbol tables */
327         captive_newn(NameList,symN);
328         ExportDir->AddressOfNames=(PDWORD *)MODULEOBJECT_BASE_OFFSET_MINUS(NameList);   /* link NameList to ExportDir */
329         captive_newn(OrdinalList,symN);
330         ExportDir->AddressOfNameOrdinals=(PWORD *)MODULEOBJECT_BASE_OFFSET_MINUS(OrdinalList);  /* link OrdinalList to ExportDir */
331         captive_newn(FunctionList,symN);
332         ExportDir->AddressOfFunctions=(PDWORD *)MODULEOBJECT_BASE_OFFSET_MINUS(FunctionList);   /* link FunctionList to ExportDir */
333
334         /* fill in symbol tables */
335         va_start(ap,FullName_utf8);
336         for (symi=0;symi<symN;symi++) {
337                 captive_va_arg(sym_name,ap);
338                 captive_va_arg(sym_val ,ap);
339                 NameList[symi]=MODULEOBJECT_BASE_OFFSET_MINUS(sym_name);
340                 OrdinalList[symi]=symi; /* Ordinals are not supported by libcaptive */
341                 FunctionList[symi]=MODULEOBJECT_BASE_OFFSET_MINUS(sym_val);
342                 }
343         va_end(ap);
344
345         /* successful module info build */
346         InsertTailList(&ModuleListHead,&ModuleObject->ListEntry);
347         return TRUE;
348
349 err_g_free_ModuleObject:
350         g_free(ModuleObject);
351 /* err */
352         g_return_val_if_reached(FALSE);
353 }
354
355
356 static gsize instruction_length(const guint8 *instr)
357 {
358         if ((instr[0] & 0xF8)==0x50)    /* push %regular-register */
359                 return 1;
360         if ((instr[0] & 0xF8)==0x58)    /* pop  %regular-register */
361                 return 1;
362         if ((instr[0] & 0xE7)==0x06)    /* push %segment-register */
363                 return 1;
364         if ((instr[0] & 0xE7)==0x07 && instr[0]!=0x0F)  /* pop  %segment-register */
365                 return 1;
366         switch (instr[0]) {
367                 case 0x33:      /* xor GB,Ev */
368                         return 1+1;
369                 case 0x64:      /* prefix %fs */
370                         return instruction_length(instr+1);
371                 case 0x68:      /* push $quad-byte */
372                         return 1+4;
373                 case 0x6A:      /* push $single-byte */
374                         return 1+1;
375                 case 0x80:
376                         switch (instr[1]) {
377                                 case 0x3D:      /* cmpb $byte,immediate-quad-indirect */
378                                         return 1+1+4+1; /* 80 3D immediate-quad-indirect byte */
379                                 default: g_assert_not_reached();
380                                 }
381                 case 0x83:
382                         switch (instr[1]) {
383                                 case 0x01:      /* addl $byte,(%ecx) */
384                                         return 1+1+1;
385                                 case 0x3D:      /* cmpl $byte,immediate-quad-indirect */
386                                         return 1+1+4+1; /* 83 3D immediate-quad-indirect byte */
387                                 default: g_assert_not_reached();
388                                 }
389                 case 0x8A:      /* mov ??,?? */
390                 case 0x8B:      /* mov Gb,Eb */
391                         switch (instr[1]) {
392                                 case 0x0D:      /* mov immediate-quad-indirect,%ecx */
393                                         return 1+1+4;
394                                 case 0x15:      /* mov immediate-quad-indirect,%edx */
395                                         return 1+1+4;
396                                 case 0x44:      /* mov #offset(%reg,%reg,#mult),%reg */
397                                 case 0x4C:      /* mov #offset(%reg,#mult),%reg */
398                                 case 0x54:      /* mov #offset(%reg,#mult),%reg */
399                                         return 1+1+1+1; /* 8B 44 address-mode offset */
400                                 default: g_assert_not_reached();
401                                 }
402                 case 0x8D:      /* lea Gb,M */
403                         switch (instr[1]) {
404                                 case 0x44:      /* mov #offset(%reg,%reg,#mult),%reg */
405                                         return 4;       /* 8B 44 address-mode offset */
406                                 default: g_assert_not_reached();
407                                 }
408                 case 0x8F:      /* lea Gb,M */
409                         switch (instr[1]) {
410                                 case 0x04:
411                                         switch (instr[2]) {
412                                                 case 0x24:      /* popl (%esp,1) */
413                                                         return 3;
414                                                 default: g_assert_not_reached();
415                                                 }
416                                 default: g_assert_not_reached();
417                                 }
418                 case 0x9C:      /* pushf */
419                         return 1;
420                 case 0x9D:      /* popf */
421                         return 1;
422                 case 0xA1:      /* mov immediate-quad-indirect,%eax */
423                         return 1+4;
424                 case 0xB8:      /* mov $immediate-quad,%eax */
425                         return 1+4;
426                 case 0xC2:      /* ret $immediate-double */
427                         return 1+2;
428                 case 0xCC:      /* int $0x3 */
429                         return 1;
430                 case 0xFA:      /* cli */
431                         return 1;
432                 case 0xFB:      /* sti */
433                         return 1;
434                 case 0xFF:      /* inc/dec Ev */
435                         return 2;
436                 default: g_assert_not_reached();
437                 }
438         g_assert_not_reached(); /* TODO:fill the table */
439         /* NOTREACHED */
440         return 0;
441 }
442
443
444         /* A lot of offsets in the structures are relative to ModuleObject->Base */
445 #define MODULEOBJECT_BASE_OFFSET_PLUS(addr) ((gpointer)((char *)addr+(ptrdiff_t)ModuleObject->Base))
446
447 static void captive_ModuleList_patch_function_disable
448                 (CHAR *funcname,PVOID *ExportAddressp,MODULE_OBJECT *ModuleObject /* user_data */)
449 {
450 PVOID ExportAddress;
451
452         g_return_if_fail(funcname!=NULL);
453         g_return_if_fail(ExportAddressp!=NULL);
454         g_return_if_fail(ModuleObject!=NULL);
455
456         ExportAddress=(PVOID)MODULEOBJECT_BASE_OFFSET_PLUS(*ExportAddressp);
457         g_return_if_fail(ExportAddress!=NULL);
458
459         /* Some alised name; safe to ignore as we checked for possible W32 binary 0xF4
460          * hits during our initialization in captive_ModuleList_patch().
461          */
462         if (0xF4 /* hlt */ ==*(guint8 *)ExportAddress)
463                 return;
464
465         captive_ModuleList_function_disable_hash_init();
466
467         *(guint8 *)ExportAddress=0xF4; /* hlt */
468         /* We may get aliased here; already existing entry is therefore allowed. */
469         g_hash_table_insert(captive_ModuleList_function_disable_hash,
470                         ExportAddress,  /* key */
471                         funcname);      /* value */
472 }
473
474
475 /**
476  * captive_ModuleList_patch:
477  * @FullName_utf8: String to find #PMODULE_OBJECT by #FullName.
478  * @...: (const gchar *sym_name,void (*sym_val)(void),struct captive_ModuleList_patchpoint *patchpoint) symbol list terminated by %NULL.
479  *
480  * Patches existing @FullName_utf8 module to use for function named #sym_name
481  * pointer to the handler #sym_val. If #patchpoint is not %NULL it gets assigned the original
482  * pointer value (used for %pass keyword in #exports.captivesym).
483  * 
484  * Put here 0xF4 'hlt' instead of 0xCC 'int $0x3; breakpoint'
485  * as 'hlt' will generate handled SIGSEGV instead of SIGTRAP which
486  * is used by gdb(1) during debugging.
487  * See also libcaptive/ps/signal.c/ sigaction_SIGSEGV().
488  *
489  * Returns: %TRUE if the module was successfuly added.
490  */
491 gboolean captive_ModuleList_patch(const gchar *FullName_utf8,...)
492 {
493 MODULE_OBJECT *ModuleObject;
494 va_list ap;
495 IMAGE_EXPORT_DIRECTORY *ExportDir;
496 ptrdiff_t *NameList;    /* filled by sym_name; MODULEOBJECT_BASE_OFFSET_PLUS()ed */
497 WORD *OrdinalList;      /* linear list - libcaptive doesn't support Ordinals */
498 ptrdiff_t *FunctionList;        /* filled by sym_val; MODULEOBJECT_BASE_OFFSET_PLUS()ed */
499 ULONG ExportDirSize;
500 USHORT Idx;
501 PVOID ExportAddress,*ExportAddressp;
502 const gchar *sym_name;
503 void (*sym_val)(void);
504 struct captive_ModuleList_patchpoint *patchpoint;
505 GHashTable *exportdir_hash;
506 gboolean errbool;
507
508         g_return_val_if_fail(FullName_utf8!=NULL,FALSE);
509
510         captive_ModuleList_patchpoint_hash_init();
511
512         ModuleObject=LdrGetModuleObject(captive_utf8_to_UnicodeString_alloca(g_path_get_basename(FullName_utf8)));
513         g_return_val_if_fail(ModuleObject!=NULL,FALSE);
514
515         ExportDir=(PIMAGE_EXPORT_DIRECTORY)RtlImageDirectoryEntryToData(ModuleObject->Base,
516                         TRUE,IMAGE_DIRECTORY_ENTRY_EXPORT,&ExportDirSize);
517         g_return_val_if_fail(ExportDir!=NULL,FALSE);
518
519         NameList    =MODULEOBJECT_BASE_OFFSET_PLUS(ExportDir->AddressOfNames);
520         OrdinalList =MODULEOBJECT_BASE_OFFSET_PLUS(ExportDir->AddressOfNameOrdinals);
521         FunctionList=MODULEOBJECT_BASE_OFFSET_PLUS(ExportDir->AddressOfFunctions);
522
523         /* map (CHAR *)funcname->(PVOID *)ExportAddressp */
524         exportdir_hash=g_hash_table_new(g_str_hash,g_str_equal);
525
526         /* Initialize 'exportdir_hash' by all W32 exported functions. */
527         for (Idx=0;Idx<ExportDir->NumberOfNames;Idx++) {
528 CHAR *funcname=MODULEOBJECT_BASE_OFFSET_PLUS(NameList[Idx]);
529
530                 ExportAddressp=(PVOID *)(FunctionList+OrdinalList[Idx]);
531                 ExportAddress=(PVOID)MODULEOBJECT_BASE_OFFSET_PLUS(*ExportAddressp);
532                 if (0xF4 /* hlt */ ==*(guint8 *)ExportAddress) {
533                         /* FIXME: 'data' type symbols should be permitted to have 0xF4 byte */
534                         g_error("%s: Function already patched although we did not touch it yet: %s",G_STRLOC,funcname);
535                         g_assert_not_reached();
536                         }
537                 g_assert(NULL==g_hash_table_lookup(exportdir_hash,funcname));
538                 g_hash_table_insert(exportdir_hash,
539                                 funcname,       /* key */
540                                 ExportAddressp);        /* value */
541                 }
542
543         /* Patch wished functions and remove them from 'exportdir_hash'. */
544         va_start(ap,FullName_utf8);
545         while (captive_va_arg(sym_name,ap)) {
546                 captive_va_arg(sym_val ,ap);
547                 /* 'sym_val' may be NULL if 'data' type && "pass"ed */
548                 captive_va_arg(patchpoint,ap);  /* 'data' type if ==NULL */
549                 ExportAddressp=g_hash_table_lookup(exportdir_hash,sym_name);
550                 if (ExportAddressp==NULL) {
551                         g_error("%s: Function not found for patchpoint: %s",G_STRLOC,sym_name);
552                         g_assert_not_reached();
553                         }
554                 errbool=g_hash_table_remove(exportdir_hash,sym_name);
555                 g_assert(errbool==TRUE);
556                 if (!sym_val) { /* 'data' type && "pass"ed => do not corrupt it by 0xF4 */
557                         g_assert(!patchpoint);
558                         continue;
559                         }
560                 ExportAddress=(PVOID)MODULEOBJECT_BASE_OFFSET_PLUS(*ExportAddressp);
561                 *ExportAddressp=(PVOID)MODULEOBJECT_BASE_OFFSET_MINUS(sym_val);
562                 if (((ULONG)ExportAddress >= (ULONG)ExportDir) &&
563                                 ((ULONG)ExportAddress <  (ULONG)ExportDir + ExportDirSize))
564                         g_assert_not_reached(); /* LdrPEFixupForward() needed */
565                 if (!patchpoint) /* 'data' type && !"pass"ed => do not corrupt it by 0xF4 */
566                         continue;
567                 patchpoint->orig_w32_func=ExportAddress;
568                 if (0xF4 /* hlt */ ==*patchpoint->orig_w32_func)        /* Already patched by name-aliased function? */
569                         continue;
570                 g_assert(0xF4 /* hlt */ !=*patchpoint->orig_w32_func);
571                 patchpoint->orig_w32_2ndinstr=patchpoint->orig_w32_func
572                                 +instruction_length((guint8 *)patchpoint->orig_w32_func);
573                 g_assert(0xF4 /* hlt */ !=*patchpoint->orig_w32_2ndinstr);
574                 patchpoint->wrap_wrap_func=sym_val;
575                 patchpoint->orig_w32_func_byte=*patchpoint->orig_w32_func;
576                 patchpoint->orig_w32_2ndinstr_byte=*patchpoint->orig_w32_2ndinstr;
577                 patchpoint->through_w32_func=FALSE;
578                 g_assert(NULL==g_hash_table_lookup(captive_ModuleList_patchpoint_hash,patchpoint->orig_w32_func));
579                 g_hash_table_insert(captive_ModuleList_patchpoint_hash,
580                                 patchpoint->orig_w32_func,      /* key */
581                                 patchpoint);    /* value */
582                 g_assert(NULL==g_hash_table_lookup(captive_ModuleList_patchpoint_hash,patchpoint->orig_w32_2ndinstr));
583                 g_hash_table_insert(captive_ModuleList_patchpoint_hash,
584                                 patchpoint->orig_w32_2ndinstr,  /* key */
585                                 patchpoint);    /* value */
586                 *(guint8 *)ExportAddress=0xF4;  /* hlt */
587                 }
588         va_end(ap);
589
590         /* The remaining entries of 'exportdir_hash' are W32 native functions
591          * unspecified by .captivesym file; we patch them as not-implemented ones.
592          */
593         g_hash_table_foreach(exportdir_hash,
594                         (GHFunc)captive_ModuleList_patch_function_disable,      /* func */
595                         ModuleObject);  /* used_data; unused */
596
597         g_hash_table_destroy(exportdir_hash);
598
599 #undef MODULEOBJECT_BASE_OFFSET_PLUS    /* no longer valid */
600 #undef MODULEOBJECT_BASE_OFFSET_MINUS   /* no longer valid */
601         return TRUE;
602 }
603
604
605 struct captive_ModuleList_patchpoint *captive_ModuleList_patchpoint_find(gconstpointer ExportAddress)
606 {
607 struct captive_ModuleList_patchpoint *r;
608
609         g_return_val_if_fail(ExportAddress!=NULL,NULL);
610
611         captive_ModuleList_patchpoint_hash_init();
612
613         r=g_hash_table_lookup(captive_ModuleList_patchpoint_hash,ExportAddress);
614         g_return_val_if_fail(r!=NULL,NULL);
615         g_assert(r->orig_w32_func==ExportAddress || r->orig_w32_2ndinstr==ExportAddress);
616
617         return r;
618 }
619
620
621 G_CONST_RETURN gchar *captive_ModuleList_function_disable_find(gconstpointer ExportAddress)
622 {
623         g_return_val_if_fail(ExportAddress!=NULL,NULL);
624
625         return g_hash_table_lookup(captive_ModuleList_function_disable_hash,ExportAddress);     /* funcname */
626 }
627
628
629 void *captive_Module_GetExportAddress(const gchar *ModuleName_utf8,const gchar *FunctionName)
630 {
631 MODULE_OBJECT *ModuleObject;
632 void *r;
633
634         g_return_val_if_fail(ModuleName_utf8!=NULL,NULL);
635         g_return_val_if_fail(FunctionName!=NULL,NULL);
636
637         ModuleObject=LdrGetModuleObject(captive_utf8_to_UnicodeString_alloca(g_path_get_basename(ModuleName_utf8)));
638         g_return_val_if_fail(ModuleObject!=NULL,NULL);
639
640         r=LdrGetExportAddress(
641                         ModuleObject,   /* ModuleObject */
642                         (/* de-const */char *)FunctionName,     /* Name */
643                         -1);    /*Hint*/
644         g_return_val_if_fail(r!=NULL,NULL);
645
646         return r;
647 }