Release 970914
[wine.git] / loader / pe_image.c
blob415094f8950fdced674713140798ca79941fa214
1 #ifndef WINELIB
2 /*
3 * Copyright 1994 Eric Youndale & Erik Bos
4 * Copyright 1995 Martin von Löwis
5 * Copyright 1996 Marcus Meissner
7 * based on Eric Youndale's pe-test and:
9 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
10 * make that:
11 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
14 #include <ctype.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/mman.h>
22 #include "windows.h"
23 #include "winbase.h"
24 #include "callback.h"
25 #include "neexe.h"
26 #include "peexe.h"
27 #include "process.h"
28 #include "pe_image.h"
29 #include "module.h"
30 #include "global.h"
31 #include "task.h"
32 #include "ldt.h"
33 #include "options.h"
34 #include "stddebug.h"
35 #include "debug.h"
36 #include "debugger.h"
37 #include "xmalloc.h"
39 static void PE_InitDLL(PE_MODREF* modref, DWORD type, LPVOID lpReserved);
41 /* convert PE image VirtualAddress to Real Address */
42 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
44 void dump_exports(IMAGE_EXPORT_DIRECTORY * pe_exports, unsigned int load_addr)
46 char *Module;
47 int i;
48 u_short *ordinal;
49 u_long *function,*functions;
50 u_char **name,*ename;
51 char buffer[1000];
52 DBG_ADDR daddr;
54 daddr.seg = 0;
55 daddr.type = NULL;
56 Module = (char*)RVA(pe_exports->Name);
57 dprintf_win32(stddeb,"\n*******EXPORT DATA*******\nModule name is %s, %ld functions, %ld names\n",
58 Module,
59 pe_exports->NumberOfFunctions,
60 pe_exports->NumberOfNames);
62 ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
63 functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
64 name=(u_char**) RVA(pe_exports->AddressOfNames);
66 dprintf_win32(stddeb,"%-32s Ordinal Virt Addr\n", "Function Name");
67 for (i=0;i<pe_exports->NumberOfFunctions;i++) {
68 if (i<pe_exports->NumberOfNames) {
69 ename=(char*)RVA(*name++);
70 dprintf_win32(stddeb,"%-32s %4d %8.8lx (%8.8lx)\n",ename,*ordinal,functions[*ordinal],*function);
71 sprintf(buffer,"%s_%s",Module,ename);
72 daddr.off=RVA(functions[*ordinal]);
73 ordinal++;
74 function++;
75 } else {
76 /* ordinals/names no longer valid, but we still got functions */
77 dprintf_win32(stddeb,"%-32s %4s %8s %8.8lx\n","","","",*function);
78 sprintf(buffer,"%s_%d",Module,i);
79 daddr.off=RVA(*functions);
80 function++;
82 DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
86 /* Look up the specified function or ordinal in the exportlist:
87 * If it is a string:
88 * - look up the name in the Name list.
89 * - look up the ordinal with that index.
90 * - use the ordinal as offset into the functionlist
91 * If it is a ordinal:
92 * - use ordinal-pe_export->Base as offset into the functionlist
94 FARPROC32 PE_FindExportedFunction(struct pe_data *pe, LPCSTR funcName)
96 IMAGE_EXPORT_DIRECTORY *exports;
97 unsigned load_addr;
98 u_short * ordinal;
99 u_long * function;
100 u_char ** name, *ename;
101 int i;
102 PDB32 *process=(PDB32*)GetCurrentProcessId();
103 PE_MODREF *pem;
105 pem = process->modref_list;
106 while (pem && (pem->pe_module != pe))
107 pem=pem->next;
108 if (!pem) {
109 fprintf(stderr,"No MODREF found for PE_MODULE %p in process %p\n",pe,process);
110 return NULL;
112 load_addr = pem->load_addr;
113 exports = pem->pe_export;
115 if (HIWORD(funcName))
116 dprintf_win32(stddeb,"PE_FindExportedFunction(%s)\n",funcName);
117 else
118 dprintf_win32(stddeb,"PE_FindExportedFunction(%d)\n",(int)funcName);
119 if (!exports) {
120 fprintf(stderr,"Module %p/MODREF %p doesn't have a exports table.\n",pe,pem);
121 return NULL;
123 ordinal = (u_short*) RVA(exports->AddressOfNameOrdinals);
124 function= (u_long*) RVA(exports->AddressOfFunctions);
125 name = (u_char **) RVA(exports->AddressOfNames);
127 if (HIWORD(funcName)) {
128 for(i=0; i<exports->NumberOfNames; i++) {
129 ename=(char*)RVA(*name);
130 if(!strcmp(ename,funcName))
131 return (FARPROC32) RVA(function[*ordinal]);
132 ordinal++;
133 name++;
135 } else {
136 if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
137 dprintf_win32(stddeb," ordinal %d out of range!\n",
138 LOWORD(funcName));
139 return NULL;
141 return (FARPROC32) RVA(function[(int)funcName-exports->Base]);
143 return NULL;
146 void
147 fixup_imports (PDB32 *process,PE_MODREF *pem)
149 PE_MODULE *pe = pem->pe_module;
150 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
151 int fixup_failed = 0;
152 unsigned int load_addr = pem->load_addr;
153 int i;
154 char *modname;
156 if (pem->pe_export)
157 modname = (char*) RVA(pem->pe_export->Name);
158 else
159 modname = "<unknown>";
161 /* OK, now dump the import list */
162 dprintf_win32 (stddeb, "\nDumping imports list\n");
164 /* first, count the number of imported non-internal modules */
165 pe_imp = pem->pe_import;
166 if (!pe_imp)
167 fprintf(stderr,"no import directory????\n");
169 /* FIXME: should terminate on 0 Characteristics */
170 for (i = 0; pe_imp->Name; pe_imp++)
171 i++;
173 /* load the imported modules. They are automatically
174 * added to the modref list of the process.
177 /* FIXME: should terminate on 0 Characteristics */
178 for (i = 0, pe_imp = pem->pe_import; pe_imp->Name; pe_imp++) {
179 HMODULE32 res;
180 PE_MODREF *xpem,**ypem;
183 char *name = (char *) RVA(pe_imp->Name);
185 /* don't use MODULE_Load, Win32 creates new task differently */
186 res = PE_LoadLibraryEx32A( name, 0, 0 );
187 if (res <= (HMODULE32) 32) {
188 char *p, buffer[256];
190 /* Try with prepending the path of the current module */
191 GetModuleFileName32A (pe->mappeddll, buffer, sizeof (buffer));
192 if (!(p = strrchr (buffer, '\\')))
193 p = buffer;
194 strcpy (p + 1, name);
195 res = PE_LoadLibraryEx32A( buffer, 0, 0 );
197 if (res <= (HMODULE32) 32) {
198 fprintf (stderr, "Module %s not found\n", name);
199 exit (0);
201 res = MODULE_HANDLEtoHMODULE32(res);
202 xpem = pem->next;
203 while (xpem) {
204 if (xpem->pe_module->mappeddll == res)
205 break;
206 xpem = xpem->next;
208 if (xpem) {
209 /* it has been loaded *BEFORE* us, so we have to init
210 * it before us. we just swap the two modules which should
211 * work.
213 /* unlink xpem from chain */
214 ypem = &(process->modref_list);
215 while (*ypem) {
216 if ((*ypem)==xpem)
217 break;
218 ypem = &((*ypem)->next);
220 *ypem = xpem->next;
222 /* link it directly before pem */
223 ypem = &(process->modref_list);
224 while (*ypem) {
225 if ((*ypem)==pem)
226 break;
227 ypem = &((*ypem)->next);
229 *ypem = xpem;
230 xpem->next = pem;
233 i++;
235 pe_imp = pem->pe_import;
236 while (pe_imp->Name) {
237 char *Module;
238 IMAGE_IMPORT_BY_NAME *pe_name;
239 LPIMAGE_THUNK_DATA import_list,thunk_list;
240 int ordimportwarned;
242 ordimportwarned = 0;
243 Module = (char *) RVA(pe_imp->Name);
244 dprintf_win32 (stddeb, "%s\n", Module);
246 /* FIXME: forwarder entries ... */
248 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
249 dprintf_win32 (stddeb, "Microsoft style imports used\n");
250 import_list =(LPIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
251 thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
253 while (import_list->u1.Ordinal) {
254 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
255 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
257 if(!lstrncmpi32A(Module,"kernel32",8) && !ordimportwarned){
258 fprintf(stderr,"%s imports kernel32.dll by ordinal. May crash.\n",modname);
259 ordimportwarned = 1;
261 dprintf_win32 (stddeb, "--- Ordinal %s,%d\n", Module, ordinal);
262 thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),(LPCSTR)ordinal);
263 if (!thunk_list->u1.Function) {
264 fprintf(stderr,"No implementation for %s.%d, setting to NULL\n",
265 Module, ordinal);
266 /* fixup_failed=1; */
268 } else { /* import by name */
269 pe_name = (LPIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
270 dprintf_win32 (stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
271 thunk_list->u1.Function=(LPDWORD)GetProcAddress32(
272 MODULE_FindModule (Module),
273 pe_name->Name);
274 if (!thunk_list->u1.Function) {
275 fprintf(stderr,"No implementation for %s.%d(%s), setting to NULL\n",
276 Module,pe_name->Hint,pe_name->Name);
277 /* fixup_failed=1; */
280 import_list++;
281 thunk_list++;
283 } else { /* Borland style */
284 dprintf_win32 (stddeb, "Borland style imports used\n");
285 thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
286 while (thunk_list->u1.Ordinal) {
287 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
288 /* not sure about this branch, but it seems to work */
289 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
292 if (!lstrncmpi32A(Module,"kernel32",8) &&
293 !ordimportwarned
295 fprintf(stderr,"%s imports kernel32.dll by ordinal. May crash.\n",modname);
296 ordimportwarned = 1;
298 dprintf_win32(stddeb,"--- Ordinal %s.%d\n",Module,ordinal);
299 thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),
300 (LPCSTR) ordinal);
301 if (!thunk_list->u1.Function) {
302 fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
303 Module,ordinal);
304 /* fixup_failed=1; */
306 } else {
307 pe_name=(LPIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
308 dprintf_win32(stddeb,"--- %s %s.%d\n",
309 pe_name->Name,Module,pe_name->Hint);
310 thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),pe_name->Name);
311 if (!thunk_list->u1.Function) {
312 fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
313 Module, pe_name->Hint);
314 /* fixup_failed=1; */
317 thunk_list++;
320 pe_imp++;
322 if (fixup_failed) exit(1);
325 static int calc_vma_size(struct pe_data *pe)
327 int i,vma_size = 0;
329 dprintf_win32(stddeb, "Dump of segment table\n");
330 dprintf_win32(stddeb, " Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
331 for(i=0; i< pe->pe_header->FileHeader.NumberOfSections; i++)
333 dprintf_win32(stddeb, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
334 pe->pe_seg[i].Name,
335 pe->pe_seg[i].Misc.VirtualSize,
336 pe->pe_seg[i].VirtualAddress,
337 pe->pe_seg[i].SizeOfRawData,
338 pe->pe_seg[i].PointerToRawData,
339 pe->pe_seg[i].PointerToRelocations,
340 pe->pe_seg[i].PointerToLinenumbers,
341 pe->pe_seg[i].NumberOfRelocations,
342 pe->pe_seg[i].NumberOfLinenumbers,
343 pe->pe_seg[i].Characteristics);
344 vma_size = MAX(vma_size,
345 pe->pe_seg[i].VirtualAddress +
346 pe->pe_seg[i].SizeOfRawData);
348 return vma_size;
351 static void do_relocations(PE_MODREF *pem)
353 int delta = pem->load_addr - pem->pe_module->pe_header->OptionalHeader.ImageBase;
355 unsigned int load_addr= pem->load_addr;
356 IMAGE_BASE_RELOCATION *r = pem->pe_reloc;
357 int hdelta = (delta >> 16) & 0xFFFF;
358 int ldelta = delta & 0xFFFF;
360 /* int reloc_size = */
362 if(delta == 0)
363 /* Nothing to do */
364 return;
365 while(r->VirtualAddress)
367 char *page = (char*) RVA(r->VirtualAddress);
368 int count = (r->SizeOfBlock - 8)/2;
369 int i;
370 dprintf_fixup(stddeb, "%x relocations for page %lx\n",
371 count, r->VirtualAddress);
372 /* patching in reverse order */
373 for(i=0;i<count;i++)
375 int offset = r->TypeOffset[i] & 0xFFF;
376 int type = r->TypeOffset[i] >> 12;
377 dprintf_fixup(stddeb,"patching %x type %x\n", offset, type);
378 switch(type)
380 case IMAGE_REL_BASED_ABSOLUTE: break;
381 case IMAGE_REL_BASED_HIGH:
382 *(short*)(page+offset) += hdelta;
383 break;
384 case IMAGE_REL_BASED_LOW:
385 *(short*)(page+offset) += ldelta;
386 break;
387 case IMAGE_REL_BASED_HIGHLOW:
388 #if 1
389 *(int*)(page+offset) += delta;
390 #else
391 { int h=*(unsigned short*)(page+offset);
392 int l=r->TypeOffset[++i];
393 *(unsigned int*)(page + offset) = (h<<16) + l + delta;
395 #endif
396 break;
397 case IMAGE_REL_BASED_HIGHADJ:
398 fprintf(stderr, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
399 break;
400 case IMAGE_REL_BASED_MIPS_JMPADDR:
401 fprintf(stderr, "Is this a MIPS machine ???\n");
402 break;
403 default:
404 fprintf(stderr, "Unknown fixup type\n");
405 break;
408 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
416 /**********************************************************************
417 * PE_LoadImage
418 * Load one PE format DLL/EXE into memory
420 * Unluckily we can't just mmap the sections where we want them, for
421 * (at least) Linux does only support offset with are multiples of the
422 * underlying filesystemblocksize, but PE DLLs usually have alignments of 512
423 * byte. This fails for instance when you try to map from CDROM (bsize 2048).
425 * BUT we have to map the whole image anyway, for Win32 programs sometimes
426 * want to access them. (HMODULE32 point to the start of it)
428 static PE_MODULE *PE_LoadImage( int fd )
430 struct pe_data *pe;
431 DBG_ADDR daddr;
432 struct stat stbuf;
434 daddr.seg=0;
435 daddr.type = NULL;
436 if (-1==fstat(fd,&stbuf)) {
437 perror("PE_LoadImage:fstat");
438 return NULL;
440 pe = xmalloc(sizeof(struct pe_data));
441 memset(pe,0,sizeof(struct pe_data));
443 /* map the PE image somewhere */
444 pe->mappeddll = (HMODULE32)mmap(NULL,stbuf.st_size,PROT_READ,MAP_SHARED,fd,0);
445 if (!pe->mappeddll || pe->mappeddll==-1) {
446 perror("PE_LoadImage:mmap");
447 free(pe);
448 return NULL;
450 /* link PE header */
451 pe->pe_header = (IMAGE_NT_HEADERS*)(pe->mappeddll+(((IMAGE_DOS_HEADER*)pe->mappeddll)->e_lfanew));
452 if (pe->pe_header->Signature!=IMAGE_NT_SIGNATURE) {
453 fprintf(stderr,"image doesn't have PE signature, but 0x%08lx\n",
454 pe->pe_header->Signature
456 free(pe);
457 return NULL;
460 if (pe->pe_header->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
461 fprintf(stderr,"trying to load PE image for unsupported architecture (");
462 switch (pe->pe_header->FileHeader.Machine) {
463 case IMAGE_FILE_MACHINE_UNKNOWN:
464 fprintf(stderr,"Unknown");break;
465 case IMAGE_FILE_MACHINE_I860:
466 fprintf(stderr,"I860");break;
467 case IMAGE_FILE_MACHINE_R3000:
468 fprintf(stderr,"R3000");break;
469 case IMAGE_FILE_MACHINE_R4000:
470 fprintf(stderr,"R4000");break;
471 case IMAGE_FILE_MACHINE_R10000:
472 fprintf(stderr,"R10000");break;
473 case IMAGE_FILE_MACHINE_ALPHA:
474 fprintf(stderr,"Alpha");break;
475 case IMAGE_FILE_MACHINE_POWERPC:
476 fprintf(stderr,"PowerPC");break;
477 default:
478 fprintf(stderr,"Unknown-%04x",pe->pe_header->FileHeader.Machine);break;
480 fprintf(stderr,")\n");
481 return NULL;
483 pe->pe_seg = (IMAGE_SECTION_HEADER*)(((LPBYTE)(pe->pe_header+1))-
484 (16 - pe->pe_header->OptionalHeader.NumberOfRvaAndSizes) * sizeof(IMAGE_DATA_DIRECTORY));
486 /* FIXME: the (16-...) is a *horrible* hack to make COMDLG32.DLL load OK. The
487 * problem needs to be fixed properly at some stage.
489 return pe;
492 /**********************************************************************
493 * This maps a loaded PE dll into the address space of the specified process.
495 void
496 PE_MapImage(PE_MODULE *pe,PDB32 *process, OFSTRUCT *ofs, DWORD flags) {
497 PE_MODREF *pem;
498 int i, result;
499 int load_addr;
500 IMAGE_DATA_DIRECTORY dir;
501 char buffer[200];
502 DBG_ADDR daddr;
503 char *modname;
504 int vma_size;
506 pem = (PE_MODREF*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*pem));
507 /* NOTE: fixup_imports takes care of the correct order */
508 pem->next = process->modref_list;
509 process->modref_list = pem;
511 pem->pe_module = pe;
512 if (!(pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL)) {
513 if (process->exe_modref)
514 fprintf(stderr,"overwriting old exe_modref... arrgh\n");
515 process->exe_modref = pem;
518 load_addr = pe->pe_header->OptionalHeader.ImageBase;
519 dprintf_win32(stddeb, "Load addr is %x\n",load_addr);
520 vma_size = calc_vma_size(pe);
521 load_addr = (int) VirtualAlloc( (void*)load_addr, vma_size, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
522 pem->load_addr = load_addr;
524 dprintf_win32(stddeb, "Load addr is really %lx, range %x\n",
525 pem->load_addr, vma_size);
528 for(i=0; i < pe->pe_header->FileHeader.NumberOfSections; i++)
530 /* memcpy only non-BSS segments */
531 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
532 * but it is not possible for (at least) Linux needs an offset
533 * aligned to a block on the filesystem.
535 if(!(pe->pe_seg[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
536 memcpy((char*)RVA(pe->pe_seg[i].VirtualAddress),
537 (char*)(pe->mappeddll+pe->pe_seg[i].PointerToRawData),
538 pe->pe_seg[i].SizeOfRawData
541 result = RVA (pe->pe_seg[i].VirtualAddress);
542 #if 1
543 /* not needed, memory is zero */
544 if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
545 memset((void *)result, 0,
546 pe->pe_seg[i].Misc.VirtualSize ?
547 pe->pe_seg[i].Misc.VirtualSize :
548 pe->pe_seg[i].SizeOfRawData);
549 #endif
551 if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
552 pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) result;
554 if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
555 pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) result;
557 if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0)
558 pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) result;
560 if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
561 pem->pe_reloc = (LPIMAGE_BASE_RELOCATION) result;
564 /* There is word that the actual loader does not care about the
565 section names, and only goes for the DataDirectory */
566 dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
567 if(dir.Size)
569 if(pem->pe_export && (int)pem->pe_export!=RVA(dir.VirtualAddress))
570 fprintf(stderr,"wrong export directory??\n");
571 /* always trust the directory */
572 pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) RVA(dir.VirtualAddress);
575 dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
576 if(dir.Size)
578 if(pem->pe_import && (int)pem->pe_import!=RVA(dir.VirtualAddress))
579 fprintf(stderr,"wrong import directory??\n");
580 pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) RVA(dir.VirtualAddress);
583 dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
584 if(dir.Size)
586 if(pem->pe_resource && (int)pem->pe_resource!=RVA(dir.VirtualAddress))
587 fprintf(stderr,"wrong resource directory??\n");
588 pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) RVA(dir.VirtualAddress);
591 if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size)
592 dprintf_win32(stdnimp,"Exception directory ignored\n");
594 if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size)
595 dprintf_win32(stdnimp,"Security directory ignored\n");
599 dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
600 if(dir.Size)
602 if(pem->pe_reloc && (int)pem->pe_reloc!= RVA(dir.VirtualAddress))
603 fprintf(stderr,"wrong relocation list??\n");
604 pem->pe_reloc = (void *) RVA(dir.VirtualAddress);
607 if(pe->pe_header->OptionalHeader.DataDirectory
608 [IMAGE_DIRECTORY_ENTRY_DEBUG].Size)
610 DEBUG_RegisterDebugInfo(pe, load_addr,
611 pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress,
612 pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size);
615 if(pe->pe_header->OptionalHeader.DataDirectory
616 [IMAGE_DIRECTORY_ENTRY_COPYRIGHT].Size)
617 dprintf_win32(stdnimp,"Copyright string ignored\n");
619 if(pe->pe_header->OptionalHeader.DataDirectory
620 [IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size)
621 dprintf_win32(stdnimp,"Global Pointer (MIPS) ignored\n");
623 if(pe->pe_header->OptionalHeader.DataDirectory
624 [IMAGE_DIRECTORY_ENTRY_TLS].Size)
625 fprintf(stdnimp,"Thread local storage ignored\n");
627 if(pe->pe_header->OptionalHeader.DataDirectory
628 [IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size)
629 dprintf_win32(stdnimp,"Load Configuration directory ignored\n");
631 if(pe->pe_header->OptionalHeader.DataDirectory
632 [IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size)
633 dprintf_win32(stdnimp,"Bound Import directory ignored\n");
635 if(pe->pe_header->OptionalHeader.DataDirectory
636 [IMAGE_DIRECTORY_ENTRY_IAT].Size)
637 dprintf_win32(stdnimp,"Import Address Table directory ignored\n");
638 if(pe->pe_header->OptionalHeader.DataDirectory[13].Size)
639 dprintf_win32(stdnimp,"Unknown directory 13 ignored\n");
640 if(pe->pe_header->OptionalHeader.DataDirectory[14].Size)
641 dprintf_win32(stdnimp,"Unknown directory 14 ignored\n");
642 if(pe->pe_header->OptionalHeader.DataDirectory[15].Size)
643 dprintf_win32(stdnimp,"Unknown directory 15 ignored\n");
645 if(pem->pe_reloc) do_relocations(pem);
646 if(pem->pe_export) dump_exports(pem->pe_export,load_addr);
647 if(pem->pe_import) fixup_imports(process,pem);
649 if (pem->pe_export)
650 modname = (char*)RVA(pem->pe_export->Name);
651 else {
652 char *s;
653 modname = s = ofs->szPathName;
654 while ((s=strchr(modname,'\\')))
655 modname = s+1;
656 if ((s=strchr(modname,'.')))
657 *s='\0';
660 /* add start of sections as debugsymbols */
661 for(i=0;i<pe->pe_header->FileHeader.NumberOfSections;i++) {
662 sprintf(buffer,"%s_%s",modname,pe->pe_seg[i].Name);
663 daddr.off= RVA(pe->pe_seg[i].VirtualAddress);
664 DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
666 /* add entry point */
667 sprintf(buffer,"%s_EntryPoint",modname);
668 daddr.off=RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint);
669 DEBUG_AddSymbol(buffer,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
670 /* add start of DLL */
671 daddr.off=load_addr;
672 DEBUG_AddSymbol(modname,&daddr, NULL, SYM_WIN32 | SYM_FUNC);
675 HINSTANCE16 MODULE_CreateInstance(HMODULE16 hModule,LOADPARAMS *params);
677 /******************************************************************************
678 * The PE Library Loader frontend.
679 * FIXME: handle the flags.
681 HMODULE32 PE_LoadLibraryEx32A (LPCSTR name, HFILE32 hFile, DWORD flags) {
682 OFSTRUCT ofs;
683 HMODULE32 hModule;
684 NE_MODULE *pModule;
686 if ((hModule = MODULE_FindModule( name )))
687 return hModule;
689 /* try to load builtin, enabled modules first */
690 if ((hModule = BUILTIN_LoadModule( name, FALSE )))
691 return hModule;
693 /* try to open the specified file */
694 if (HFILE_ERROR32==(hFile=OpenFile32(name,&ofs,OF_READ))) {
695 /* Now try the built-in even if disabled */
696 if ((hModule = BUILTIN_LoadModule( name, TRUE ))) {
697 fprintf( stderr, "Warning: could not load Windows DLL '%s', using built-in module.\n", name );
698 return hModule;
700 return 1;
702 if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) {
703 _lclose32(hFile);
704 return hModule;
707 pModule = (NE_MODULE *)GlobalLock16( hModule );
708 pModule->flags = NE_FFLAGS_WIN32;
710 /* FIXME: check if pe image loaded already ... */
711 pModule->pe_module = PE_LoadImage( FILE_GetUnixHandle(hFile) );
712 _lclose32(hFile);
713 if (!pModule->pe_module)
714 return 21;
715 /* recurse */
716 PE_MapImage(pModule->pe_module,(PDB32*)GetCurrentProcessId(),&ofs,flags);
717 return pModule->pe_module->mappeddll;
720 /*****************************************************************************
721 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryEx32A
722 * FIXME: this function should use PE_LoadLibraryEx32A, but currently can't
723 * due to the TASK_CreateTask stuff.
725 HINSTANCE16 PE_LoadModule( HFILE32 hFile, OFSTRUCT *ofs, LOADPARAMS* params )
727 HMODULE16 hModule;
728 HINSTANCE16 hInstance;
729 NE_MODULE *pModule;
731 if ((hModule = MODULE_CreateDummyModule( ofs )) < 32) return hModule;
732 pModule = (NE_MODULE *)GlobalLock16( hModule );
733 pModule->flags = NE_FFLAGS_WIN32;
735 pModule->pe_module = PE_LoadImage( FILE_GetUnixHandle(hFile) );
736 _lclose32(hFile);
737 if (!pModule->pe_module)
738 return 21;
740 hInstance = MODULE_CreateInstance( hModule, params );
741 if (!(pModule->pe_module->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL))
743 TASK_CreateTask( hModule, hInstance, 0,
744 params->hEnvironment,
745 (LPSTR)PTR_SEG_TO_LIN( params->cmdLine ),
746 *((WORD*)PTR_SEG_TO_LIN(params->showCmd) + 1) );
748 PE_MapImage(pModule->pe_module,(PDB32*)GetCurrentProcessId(),ofs,0);
749 return hInstance;
752 int PE_UnloadImage( HMODULE32 hModule )
754 printf("PEunloadImage() called!\n");
755 /* free resources, image, unmap */
756 return 1;
759 /* Called if the library is loaded or freed.
760 * NOTE: if a thread attaches a DLL, the current thread will only do
761 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
762 * (SDK)
764 static void PE_InitDLL(PE_MODREF *pem, DWORD type,LPVOID lpReserved)
766 PE_MODULE *pe = pem->pe_module;
767 unsigned int load_addr = pem->load_addr;
769 if (type==DLL_PROCESS_ATTACH)
770 pem->flags |= PE_MODREF_PROCESS_ATTACHED;
771 #ifndef WINELIB
772 if (Options.debug) {
773 DBG_ADDR addr = { NULL, 0, RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint) };
774 DEBUG_AddBreakpoint( &addr );
775 DEBUG_SetBreakpoints(TRUE);
777 #endif
779 /* DLL_ATTACH_PROCESS:
780 * lpreserved is NULL for dynamic loads, not-NULL for static loads
781 * DLL_DETACH_PROCESS:
782 * lpreserved is NULL if called by FreeLibrary, not-NULL otherwise
783 * the SDK doesn't mention anything for DLL_THREAD_*
786 /* Is this a library? And has it got an entrypoint? */
787 if ( (pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
788 (pe->pe_header->OptionalHeader.AddressOfEntryPoint)
790 FARPROC32 entry = (FARPROC32)RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint);
791 dprintf_relay( stddeb, "CallTo32(entryproc=%p,module=%d,type=%ld,res=%p)\n",
792 entry, pe->mappeddll, type, lpReserved );
793 entry( pe->mappeddll, type, lpReserved );
797 /* Call the DLLentry function of all dlls used by that process.
798 * (NOTE: this may recursively call this function (if a library calls
799 * LoadLibrary) ... but it won't matter)
801 void PE_InitializeDLLs(PDB32 *process,DWORD type,LPVOID lpReserved) {
802 PE_MODREF *pem;
804 pem = process->modref_list;
805 while (pem) {
806 if (pem->flags & PE_MODREF_NO_DLL_CALLS) {
807 pem = pem->next;
808 continue;
810 if (type==DLL_PROCESS_ATTACH) {
811 if (pem->flags & PE_MODREF_PROCESS_ATTACHED) {
812 pem = pem->next;
813 continue;
816 PE_InitDLL( pem, type, lpReserved );
817 pem = pem->next;
821 void PE_InitTls(PDB32 *pdb)
823 /* FIXME: tls callbacks ??? */
824 PE_MODREF *pem;
825 IMAGE_NT_HEADERS *peh;
826 DWORD size,datasize,index;
827 LPVOID mem;
828 LPIMAGE_TLS_DIRECTORY pdir;
830 pem = pdb->modref_list;
831 while (pem) {
832 peh = pem->pe_module->pe_header;
833 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress) {
834 pem = pem->next;
835 continue;
837 pdir = (LPVOID)(pem->load_addr + peh->OptionalHeader.
838 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
839 index = TlsAlloc();
840 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
841 size = datasize + pdir->SizeOfZeroFill;
842 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
843 memcpy(mem,(LPVOID) pdir->StartAddressOfRawData, datasize);
844 TlsSetValue(index,mem);
845 *(pdir->AddressOfIndex)=index;
846 pem=pem->next;
850 /****************************************************************************
851 * DisableThreadLibraryCalls (KERNEL32.74)
852 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
854 BOOL32 WINAPI DisableThreadLibraryCalls(HMODULE32 hModule)
856 PDB32 *process = (PDB32*)GetCurrentProcessId();
857 PE_MODREF *pem = process->modref_list;
859 while (pem) {
860 if (pem->pe_module->mappeddll == hModule)
861 pem->flags|=PE_MODREF_NO_DLL_CALLS;
862 pem = pem->next;
864 return TRUE;
867 #endif /* WINELIB */